text:
Output a playable crossword grid
Write a program to produce a file containing a crossword grid
that the user can print out and work the puzzle on.
Input
A filename representing a crossword grid file and
optionally a second filename representing a crossword numbering
file. The input should be accepted by a conventional means for
your programming environment: command line arguments, the standard
input, web forms, etc..
You may assume that the crossword has been validated, and if
using a numbering file that is corresponds to the grid provided.
Grid file format: The first line consists of two white-space
separated integer constants M and N. Following that line are M
lines each consisting of N characters (plus a new line) selected
from [#A-Z ]. These characters are interpreted such that '#'
indicates a blocked square, ' ' a open square in the puzzle
with no known contents and any letter an open square whose
containing that letter.
Numbering file format Lines starting with '#' are ignored and
may be used for comments. All other lines contain a tab separated
triplet i, m, n where i represents a number to be printed
on the grid, and m and n represent the row and column of the
square where it should be printed. The number of both rows and
columns starts at 1.
Output
The output will be a file that the user can print out and work a
crossword on. ASCII, postscript, pdf, png, and any other
reasonable format will be accepted, but all must abide by these
rules:

There must be a rule around the entire puzzle and between
every pair of squares.
Blocked squares must be filled in darkly.
In play square that represent the start of a numbered (across
or down) clue must be provided with a number in the upper,
left corner of the square, while leaving most of the square
blank for the play to write in. Note that typical grid published
in the papers will have many tens of clues and may have more than
100.

The output will be of the grid alone, without the list of clues.
Output should be sent to a conventional destination (a file whose name
is derived from the input filename, produced as a web page, etc..)
Test case
Given a input of
5   5
#  ##
#
  #
    #
##  #

the starting corner of an acceptable ASCII output might look like this
+-----+-----+-----+---
|#####|1    |2    |###
|#####|     |     |###
|#####|     |     |###
+-----+-----+-----+---
|#####|3    |     |4
|#####|     |     |
|#####|     |     |
+-----+-----+-----+---
|6    |     |#####|
|     |     |#####|

Those using graphical formats should take their inspiration from
the usual printed sources.
Numbering scheme
A correctly numbered grid has the following properties:

Numbering begins at 1.
No column or span of open squares is unnumbered.
Numbers will be encountered in counting order by scanning from
top row to the bottom taking each row from left to right.

Aside
This is the third of several crossword related challenges. I
plan to use a consistent set of file-formats throughout and to
build up a respectable suite of crossword related utilities in
the process.
Previous challenges in this series:

Crossword numbering
Crossword grid validation

I can't comment, but the example output violates your own numbering scheme.

@Samuel: So it does. That's what I get for writing it by hand rather than looking back at my own work. Thanks. Corrected.

Python, 379 characters
import sys
A=sys.argv
f=open(A[1])
V,H=map(int,f.readline().split())
M={}
if A[2:]:
 for r in open(A[2]).readlines():n,y,x=map(int,r.split());M[y*H+y+x]=n
R='+-----'*H+'+'
n,v,s='\n| '
x=y=z=''
p=V+1
for c in n+''.join(f):
 if c==n:print x+n+y+n+z+n+R;x=y=z=''
 elif'@'>c:x+=5*c;y+=5*c;z+=5*c
 else:x+=5*s;y+=s+s+c+s+s;z+=5*s
 if p in M:x=x[:-5]+"%-5d"%M[p]
 x+=v;y+=v;z+=v;p+=1

Works nicely as long as there are no comments in the numbering file.

You can use next(f) instead of f.readline(). You don't need the .readlines() there at all.

Postscript 905 797 677 675 629 608 330 320 308
{G N}/Times-Roman .3 2 22 1 30/.{<920>dup 1 4 3 roll put cvx
exec}def/${//. 73 .}def[/R{99<a51f3e7d75>$}/G{<1fab75>$
R(uN)${0 R{1(X)$ 0 1 -1 5 4 roll 35 eq{4<1980>$}if<81>$
1 add}(I)$(u)$ 0 -1<ad>$}<834d>$}/X{{exit}if}/N{-.9
.7<ad>${<1fab70>$ X}loop{{(>nk)$(  )<31a0>$}<a3>$
X}loop}>><0d38388b369bad8e3f>$

This program is written as a "protocol prolog" so you just cat it together with the grid and number files (in that order, separated by blank lines) and pipe the whole mess to ghostscript or Distiller or a PS printer. Appended to the reference version below is a NYT puzzle (From Nov. 5, 2011) with numbers and one answer I'm pretty sure of (Saturdays is hard!).
The new revision uses these two procedures to execute binary-encoded
system names from strings.
/.{
    <920>  % two-byte binary-encoded name template with 0x92 prefix
    dup 1 4 3 roll put  % insert number into string
    cvx exec  % and execute it
}def
/${
    //.   %the /. procedure body defined above
    73 .  %"forall" (by code number)
}def

Indented and (somewhat) commented.
/Times-Roman .3 2 22 1 30
/.{<920>dup 1 4 3 roll put cvx exec}def/${//. 73 .}def
[
/R{99<a51f3e7d75>$}    %currentfile 99 string readline pop
/G{<1fab75>$ %currentfile token pop
    R (uN)$ %<754e>$ %pop gsave
    {
        0 R {
            1 (X)$ %index
            0 1 -1 5 4 roll
            35 eq{
                4<1980>$ %copy rectfill
            }if
            <81>$ %rectstroke
            1 add
        }(I)$
        (u)$ % 73 . %forall pop
        0 -1<ad>$ %translate
    }<834d>$ %repeat grestore
}
/X{{exit}if}
/N{
    -.9 .7<ad>$ %translate
    %{ currentfile token not {exit} if } loop
    {<1fab70>$
        X %{exit}if
    }loop
    {
        %dup type/integertype ne{exit}if
        {
            (>nk)$ %<3e6e6b>$ %exch neg moveto
            (  )<31a0>$ %cvs show
        }<a3>$ %stopped
        X %{exit}if
    }loop
}
>>
<0d38388b369bad8e>$
%begin dup dup scale div setlinewidth translate selectfont
{G N}exec

Data files.
15 15
     #   #

       #     ##
##   #   #
    #     #
   #    #
       #
      #    #
    #     #
    K#   #   ##
##  I  #
    L
    N
    S#   #

#i m n   figure(number), row, col
1 1 1
2 1 2
3 1 3
4 1 4
5 1 5
6 1 7
7 1 8
8 1 9
9 1 11
10 1 12
11 1 13
12 1 14
13 1 15
14 2 1
15 2 6
16 2 10
17 3 1
18 4 1
19 4 9
20 5 3
21 5 7
22 5 8
23 5 11
24 5 14
25 5 15
26 6 1
27 6 2
28 6 6
29 6 10
30 6 12
31 7 1
32 7 5
33 7 10
34 7 11
35 8 1
36 8 4
37 8 9
38 9 1
39 9 8
40 9 13
41 10 1
42 10 6
43 10 7
44 10 12
45 11 1
46 11 5
47 11 7
48 11 11
49 12 3
50 12 6
51 12 9
52 12 10
53 12 14
54 12 15
55 13 1
56 13 2
57 13 8
58 14 1
59 15 1
60 15 7
60 15 11

It should look okay from a printer, but on-screen it needs a little help.
This 19-char procedure and 9 chars to invoke it on all user-space points, helps make evenly-spaced lines look more even. So 308 + 19 + 9 = 337, used to generate this image.
/F{<ac893e893e5f>$} % transform round exch round exch itransform

Postscript 608
This earlier version (from revision 8) uses a completely different approach, reusing the main-line code as a "lexicon" from which longer tokens can be indexed using strings.
<<-1{{30 700 translate 0 0 moveto
currentfile 2{(@A1*)*}repeat exch string
3 2 roll{('BO1)*{( )(@#)*
4(,.N:;<%)*<<( ){p}/#{(1:;>%)*}0{(;,'.)*
6 -26(CE%)*}>>(IJ'B)* known not{p
0}if(LG #C)*}forall(#;*1 D%)*}repeat
p/Times-Roman 8 selectfont 99
string{('BO)*{(@)* length(#=)*{p}{(@#L)*
35(=)*{p}{cvx(GID ?'H*ID ?KHF%)*(   )cvs(E)*}e}e}{showpage
exit}e}loop exit{( @#M# FMF#M)*
closepath}currentpoint stroke eq fill
mul dup token copy rmoveto sub show
neg exec add 1 index 9 get rlineto
put readline}loop}0 1 index 0 get{1
index 1 add}forall pop/*{{32 sub load
exec}forall}/e{ifelse}/p{pop}>>begin(23,?4)*<1f>*

It was written using this commented version which illustrates the encoding of the lexicon. The first token 30 is commented space therefore ( )* is a synonym for 30. Not very beneficial for 30, but for longer tokens this is(was) a big win (until deeper encoding possibilities are(were) discovered).
<<-1{{
%space  !    "         # $ %      &           '(        )     %*    +      , - .   %/
 30     700  translate 0 0 moveto currentfile 2{(@A1*)*}repeat exch string 3 2 roll
{('BO1)*{( )(@#)* 4(,.N:;<%)*<<( ){p}/#{(1:;>%)*}0{(;,'.)* 6 -26(CE%)*}>>(IJ'B)*
known not{p 0}if(LG #C)*}forall(#;*1 D%)*}
%0      1   2          3 4          5  6     7
 repeat p /Times-Roman 8 selectfont 99 string{('BO)*{(@)* length(#=)*{p}{
(@#L)* 35(=)*{p}{cvx(GID ?'H*ID ?KHF%)*(   )cvs(E)*}e}e}{showpage clear exit}e}
%8    9   :                         %;            <      =    >    ?
 loop exit{( @#M# FMF#M)* closepath} currentpoint stroke eq fill mul
%@   A     B    C       D   E    F   G    H   I J     K L   M       N   O
 dup token copy rmoveto sub show neg exec add 1 index 9 get rlineto put readline
}loop}0 1 index 0 get{1 index 1 add}forall
pop/*{{32 sub load exec}forall}/e{ifelse}/p{pop}>>begin(23,?4)*<1f>*

You don't need to keep all the old versions, because people can access the history of the post if they're really interested.

Understood. I'll trim some fat when I update.

I've posted  some alternate versions in this thread.

Invocation works how?

@userunknown Sorry, I trimmed the explanation during one of my edits. I'll restore it.

@luserdroog: Ah - I'm a bit surprised - it is just one file, I'm not used to ps-format. It looked like 3 files to me. :) Looks good in gv.

Seems that the overhead for the golf-style PostScript is still larger than my "traditional" solution ;-).

BTW, do you think using binary token encoding with Base85 strings would be useful for golfing?

Probably. I've never figured out how to use binary tokens. I start reading about it and my eyes just glaze over. I think part of my problem was trying to understand it from the implementation side, not the user side.

Try something like this: "<9100>cvx exec =". The first byte says "This is a literal system name", the second one points to the index of the name, i.e. /abs in this case.

As one token consumes 2 bytes in memory and 4 bytes in the source code (at least for hex strings), maybe one could save characters by creating a procedure that takes a string where each byte signifies one token, maps those bytes to some range in the system name encoding vector, creates a binary token string of it and executes it? Any unused system names could be associated with numbers, procedures etc., like "/abs 0 def <9200>cvx exec =".

[flipping through PLRM]... We could take the first 360 (or 430 names) and encode a base-360 number. ...If we chat too much here, we'll get in trouble. We should probably move to the chatroom or CLP. :P

@ThomasW. Good call on the binary tokens idea.

Wow, insane stuff! I'll have to read the code carefully in a quiet minute.

C (output to SVG), 553 chars
I know, the code is huge, but this problem is just crying out for an SVG answer.
char*f,b[99];h,w;main(i){fscanf(f=fopen(gets(b),"r"),"%d%d%*[\n]",&h,&w);for(
printf("<svg xmlns='http://www.w3.org/2000/svg' viewBox='.9 .9 %d.2 %d.2'><path d='M1 1",
i=w,h);i--;)printf("v%dv-%dh1",h,h);for(;h--;)printf("v1h-%dh%d",w,w);for(
puts("' style='fill:none;stroke:#000;stroke-width:.04'/><path d='");
fgets(b,99,f);++h)for(i=0;i<w;)b[i++]-35||printf("M%d %dh1v1h-1Z",i,h+2);puts("'/>");
for(f=fopen(gets(b),"r");fgets(b,99,f);)sscanf(b,"%d%d%d",&i,&h,&w)>2&&
printf("<text x='%d.1' y='%d.3' style='font-size:.3px'>%d</text>",w,h,i);puts("</svg>");}

When run it gets the two filenames on two separate lines of standard input; first the grid file, then the numbers file.
The logic in this one is actually quite simple. The format of the SVG allows it to create all the elements in any order (instead of going from top to bottom as with the ASCII output solution). The size is due almost entirely to SVG boilerplate.
But the resulting image looks great!
Edited to add: Here's a shorter version (517 chars) that output to a specific resolution. This allows the code to use more default settings, but at the (to my mind) prohibitive cost that the SVG no longer auto-resizes in your web browser.
char*f,b[99];h,w;main(i){fscanf(f=fopen(gets(b),"r"),"%d%d%*[\n]",&h,&w);for(
printf("<svg xmlns='http://www.w3.org/2000/svg'><path d='M1 1",i=w,h);i--;)
printf("v%d0v-%d0h50",h*5,h*5);for(;h--;)printf("v50h-%d0h%d0",w*5,w*5);for(
puts("' style='fill:none;stroke:#000'/><path d='");fgets(b,99,f);++h)
for(i=-1;++i<w;)b[i]-35||printf("M%d1 %d1h50v50h-50Z",i*5,h*5+5);puts("'/>");
for(f=fopen(gets(b),"r");fgets(b,99,f);)sscanf(b,"%d%d%d",&i,&h,&w)>2&&
printf("<text x='%d3' y='%d5'>%d</text>",w*5-5,h*5-4,i);puts("</svg>");}

The SVG looks great!

Haskell, 328 characters
import System
main=do(g:d)<-mapM(fmap lines.readFile)=<<getArgs;mapM_ putStrLn$g% \i k->[t|x<-d,y@(c:_)<-x,c/='#',(t,q)<-lex y,w q==i,k<1]
(s:g)%n=[q|(i,x)<-e g,q<-b s:[c['|':f#n[i,j]k|(j,f)<-e x]++"|"|k<-[0..2]]]++[b s]
'#'#_="#####";_#n=take 5$c n++"     ";b n='+':([1..w n!!1]>>"-----+")
e=zip[1..];c=concat;w=map read.words

C, 375 chars
char b[99];g[999],*r=g,*f,i,j,w;main(n){
for(fscanf(f=fopen(gets(b),"r"),"%*d%d%*[\n]",&w);fgets(b,99,f);)
for(i=0;i<w;)*r++=-(b[i++]==35);
for(f=fopen(gets(b),"r");fgets(b,99,f);)
sscanf(b,"%d%d%d",&n,&j,&i)?g[j*w-w+i-1]=n:0;
for(f=g;f<=r;f+=w){for(i=w;i--;)printf(" ----");puts("");
if(f<r)for(j=3;j--;puts("|"))
for(i=0;i<w;printf(~n?n&&j>1?"|%-4d":"|    ":"|////",n))n=f[i++];}}

The two input filenames are entered on standard input, each on a separate line. The grid is rendered in ASCII on standard output. Yes, it's a lousy UI, but anything better cost characters. I took to invoking it like so:
printf "%s\n%s" grid.txt numbering.txt | ./crosswd-render > render.txt

The program should correctly handle things like commented lines in the numbering file.

*r++-=b[i++]==35 (g is initialized to zeros).

for(j=3*(f<r);j--;puts("|")) saves if.

n&&j>1 ->j/2*n

Scala 463, output-format: html
object H extends App{val z=readLine.split("[ ]+")map(_.toInt-1)
val d="\t\t<td width='50' height='50'"
println("

")
val b=(0 to z(0)).map{r=>readLine}
var c=0
(0 to z(0)).map{
y=>(0 to z(1)).map{
x=>if(b(y)(x)==' '&&((x==0||b(y)(x-1)==35)||(y==0||b(y-1)(x)==35))){
c+=1
println(d+"valign='top'>"+c+"	")}
else println(d+{if(b(y)(x)!=' ')"bgcolor='#0'>"else"> "}+"	")}
println("\t
\n\t
")}
println("
")
}

Sample output

Very pretty. The output just looks good.

PostScript (435) (434)
[/r{currentfile 999 string readline pop}/p{pop}/x{exch}/T{translate}/S{scale}/G{gsave}/R{grestore}/_( )>>begin/Courier 1 selectfont
20 20 S
.05 setlinewidth{r token
p x p
dup 3 x 3 add
T
G G{R
0 -1 T
G
_ 0
r{0 0 1 1
4 index 35 eq{rectfill p}{rectstroke
put
.3 .1 moveto
_ show}ifelse
1 0 T _ 0}forall}repeat
R R
1 -1 S -.9 -.7 T{{r
dup 0 get 35 ne{( )search
p 3 2 roll
cvx exec
G
x
T
.4 -.4 S
0 0 moveto show
p
R}if}loop}stopped}exec

Un-golfed with data:
%!
<<
  /r{currentfile 999 string readline pop}
  /p{pop}
  /x{exch}
  /T{translate}
  /S{scale}
  /G{gsave}
  /R{grestore}
  /_( )
>>begin
/Courier 1 selectfont
% In theory, 20 20 scale isn't needed,
% but it would make the whole thing very tiny when printed
% (on screen it doesn't matter too much, it can be zoomed)
20 20 S
.05 setlinewidth
{ % exec
% Read number of lines
r token                          % restString numberOfLines true
% Discard rest of line (Contains number of columns.
% It becomes clear implicitly from number of letters in a line of grid definition)
p x p                            % numberOfLines
% Move to where the top line starts
dup 3 x 3 add                    % numberOfLines x y
T                                % numberOfLines
G G
{ %repeat
  R
  % Move to next line
  0 -1 T
  G
  _ 0
  r                              % ( ) 0 line
  { %forall                      % ( ) 0 char
    0 0 1 1                      % ( ) 0 char 0 0 x y
    % Check whether char is a hash
    4 index 35 eq{ %ifelse
      4 copy rectfill
    }if
    rectstroke                   % ( ) 0 char
    put                          % -/-
    .3 .1 moveto
    _ show
    1 0 T
    _ 0                          % ( ) 0
  }forall                        %
}repeat
R R
% Now, render the numbers according to the numbering definitions
1 -1 S -.9 -.7 T
{{
  r
  %Check whether this is a comment
  dup 0 get 35 ne{               % line
    % Split at the first tab
    %TODO: Ust tab instead of space
    ( )search                    % (y x) tab number true
    p 3 2 roll                   % tab number (y x)
    cvx exec                     % tab number y x
    G
    x                            % tab number x y
    T                            % tab number
    .4 -.4 S
    0 0 moveto show              % tab
    % This pop can be eliminated in theory to save two characters,
    % but the operand stack will continue to grow
    p
    R
  }if
}loop}stopped
}exec
15 15
     #   #

       #     ##
##   #   #
    #     #
   #    #
       #
      #    #
    #     #
    K#   #   ##
##  I  #
    L
    N
    S#   #
#i m n   figure(number), row, col
1 1 1
2 1 2
3 1 3
4 1 4
5 1 5
6 1 7
7 1 8
8 1 9
9 1 11
10 1 12
11 1 13
12 1 14
13 1 15
14 2 1
15 2 6
16 2 10
17 3 1
18 4 1
19 4 9
20 5 3
21 5 7
22 5 8
23 5 11
24 5 14
25 5 15
26 6 1
27 6 2
28 6 6
29 6 10
30 6 12
31 7 1
32 7 5
33 7 10
34 7 11
35 8 1
36 8 4
37 8 9
38 9 1
39 9 8
40 9 13
41 10 1
42 10 6
43 10 7
44 10 12
45 11 1
46 11 5
47 11 7
48 11 11
49 12 3
50 12 6
51 12 9
52 12 10
53 12 14
54 12 15
55 13 1
56 13 2
57 13 8
58 14 1
59 15 1
60 15 7
60 15 11

Awesome. I really need to make better use of stopped. ... I'm gonna leave the bounty open for a day or so to attract attention.

Postscript, non-combatant.
Inspired (yet again) by your related question on SO, I've made a reference version in Postscript using file-IO. It also creates a derived fixed-width font so the grid data is simply
passed to show.  is an empty box and # is a filled box. Any other ascii character is drawn as a small Times-Roman glyph surrounded by a box.
This program makes use of a ghostscript feature which may not be present in all Postscript interpreters. If ghostscript is invoked with the -- option, it passes command-line arguments to the postscript program in an array of strings named /ARGUMENTS. So you need to invoke the program like this gs -- xw-io.ps grid-file number-file.
%!

ARGUMENTS{}forall
/numfile exch (r) file def
/gridfile exch (r) file def

/q{0 0 moveto 1 0 lineto 1 1 lineto 0 1 lineto closepath}def
/X<</FontType 3/FontBBox[0 0 1 1]/FontMatrix[1 0 0 1 0 0]
    /Encoding StandardEncoding
    /BuildChar{
        1 0 0 0 1 1 setcachedevice
        .001 setlinewidth
        q stroke
        dup 35 eq { pop
            q fill
        }{
            .3 .1 moveto
            .1 .1 scale
            /Times-Roman 8 selectfont
            (?)dup 0 4 3 roll put show
        }ifelse pop}
>>definefont pop /X 30 selectfont
40 700 moveto {
    gridfile 2{dup token pop exch}repeat pop pop
    {
        gridfile =string readline{
            dup length 0 ne{
                show currentpoint exch pop 30 sub 40 exch moveto
            }{clear exit}ifelse
        }{clear exit}ifelse
    }loop
    /Times-Roman 8 selectfont
    {
        40 700 moveto
        numfile =string readline{
            dup length 0 ne{
                dup 0 get 35 ne{
                    cvx exec
                    1 sub 30 mul 2 add exch
                    1 sub -30 mul 22 add rmoveto
                    (   )cvs show
                }{clear}ifelse
            }{clear}ifelse
        }{clear exit}ifelse
    }loop showpage
}exec

Looks great. How big is it? I count 1247 chars. But it can be golfed - can't it? A simple translation 4 blanks=> 1 tab leads to 980 chars, eliminating all tabs to 891.

Due to all the special words needed to create a font, this one cannot be made smaller than my other postscript answer.


text:
Draw a BCD Binary clock
Create a BCD binary clock
in ASCII. As implied, it shall display time in six columns of dots:

(source: Wikimedia Commons)
Each column is a binary-coded digit, reading hours, minutes and seconds
from left to right. Hours are given in 24-hour format.
The time to display is read from the command-line or from stdin (whichever
fits better). If empty, the current time should be used instead.
Output size is a little constrained here and we can only fit two lines of
text. So you are required to put the dots into only two lines. The
characters ., : and ' come in handy here.
Input
The time to display in ISO-8601 format, i.e. HH:MM:SS without fractional
seconds. Mandatory 24-hour format. Input can be empty in which case the
current time will be used.
Output
Two lines with represent the BCD binary clock as in the image above. Each
line is exactly six characters long and the only allowed characters are
space, period, colon and apostrophe.
Winner
Shortest code by byte count wins. In a tie, the solution posted first wins.
Sample input 1

(empty)
Sample output 1
     .
''. ::

Sample input 2
17:59:20

Sample output 2
 ..'
.:..'

Sample input 3
01:08:01

Sample output 3
   '
 .   .

Golfscript (+ruby/date) - 46 chars
"#{`date`}"10>+9<" .':":S-.{4/12-S=}%n@{4%S=}%

You can replace `date` with Time.now if necessary (+2 chars).

I knew it was hopeless to even try Golfscripting ;-)

Ruby, 107 103 99 94 90 characters
$><<[$/,(gets||Time.now.to_s[11,8]).tr(z=" .':","").bytes.map{|a|$><<z[a/4-12];z[a%4]}]*""

Note that the input shouldn't contain a linebreak, so to test the solution use something like echo -n "01:08:01" | ruby1.9 bcd.rb.
To test the default behavior, run it with ruby1.9 bcd.rb and enter ^D (i.e. a literal EOF).

There's no such thing as a literal EOF! :-)

You can shave off 4 characters with Time.now.to_s[11,8].

Windows PowerShell, 81
Since I did not create an implementation when writing the task I feel myself eligible to golf it from the start, too :-)
-join" .':
"[(($d="$(date)$args"[-8..-1]-ne58)|%{($_-band12)/4})+,4+($d|%{$_%4})]

History:

2011-02-26 23:50 (119) First attempt.
2011-02-26 23:55 (108) Inlining fun.
2011-02-27 00:03 (102) Optimized selecting the first line. [Math]::Floor is waaaayy too long. I hate that.
2011-02-27 02:22 (101) I don't need : for the first line.
2011-02-27 02:53   (95) Optimized getting input or current time.
2011-03-04 20:36   (88) Only a single join remains. Indexing every character needed (including the line break) from a single string.
2011-03-04 20:39   (83) Using 58 instead of : which auto-casts to integer as well – no more need to enclose $_ in quotes :-)
2011-03-04 20:42   (81) The parentheses after the -join are no longer necessary.

Jelly, 21 bytes
o7ŒT¤fØDV€d4Zị“.': ”Y

Try it online!
For the empty input, you can use either an empty string or no argument at all.
Explanation
o7ŒT¤fØDV€d4Zị“.': ”Y   Main monadic or niladic link
o                       Logical or (Python-like)
 7ŒT¤                     Current time in hh:mm:ss format
     f                  Filter
      ØD                  Digits
         €              Each
        V                 Evaluate
          d             Divmod
           4              4
            Z           Zip
             ị          Index into [1-indexed, auto-maps]
              “.': ”      ".': "
                    Y   Join with newlines

Didn't know jelly had a time function. Too bad there's none in Husk.

C#
236 characters
using System;using System.Linq;class X{static void Main(){var d=Console.In.ReadToEnd().Replace(":","");for(int i=0;i<2;i++)Console.WriteLine(string.Join("",(d==""?DateTime.Now.ToString("HHmmss"):d).Select(c=>" .':"[i<1?c/4-12:c%4])));}}

Readable:
using System;
using System.Linq;
class X
{
    static void Main()
    {
        var d = Console.In.ReadToEnd().Replace(":", "");
        for (int i = 0; i < 2; i++)
            Console.WriteLine(string.Join("",
                (d == "" ? DateTime.Now.ToString("HHmmss") : d)
                .Select(c => " .':"[i < 1 ? c / 4 - 12 : c % 4])));
    }
}

There's no need to do - 48 when you are doing % 4, as 48 % 4 == 0

@Dogbert: Brilliant, thank you! That also gave me the idea that c/4-12 is shorter than (c-48)/4... :)

You can delete a lot of spaces and tabs too which would get rid of a lot of characters, also think about using the new top level code feature of c#

Ruby - 124 chars
t=*((i=gets)=="
"? Time.now.strftime('%H%M%S'):i).tr(':
','').bytes
puts (0..1).map{|i|t.map{|_|" .':"[i<1? _/4-12:_%4]}*''}

Golfscript (+ Ruby), 63
."#{Time.now.strftime'%T'}"if':'-:|{4/12-" .':":@\=}%n|{4%@\=}%

Still a beginner with Golfscript. Don't hit me.

There's a few things to shorten (see my answer). Specific to what you have at the moment that isn't in my answer -- brackets can be omitted from ruby function calls, "" coerces to false so you can remove ,\.

@Nabb: Thanks. Well, Ventero already told me he had it down to 63, though I couldn't bring him to tell me how ;-). Still, dragging Ruby into this through the string interpolation feels like cheating, somehow. I think I'll stay with my preferred language below and just try to beat Ruby :-)

well since the question required access to the current time, it's not really possible without resorting to ruby anyway

@gnibbler: I know. Still, it's the only really unportable feature of Golfscript and I don't particularly like using it due to that ;-)

Perl (84)

#!perl -pl
$_||=localtime;y/://d;/\d{6}/;$_=$&;y/0-9/    ....''/;$_.="\n$&";y/0-9/ .': .': ./

You can save one character by changing "\n$&" to $/.$& — common Perl-golf trick :)

@Timwi I could use a real newline there :)

Python 3, 136 chars
import time
d=input()
for i in(0,1):print(''.join([" .':"[[c>>2,c&3][i]]for c in map(int,d.replace(':','')or time.strftime('%H%M%S'))]))

I get 137 when I do a wc -c. Good work tho. +1

VimScript, 143 characters
if getline(1)==''
norm"=strftime("%T")^Mp
en
nm- "ax"=@a/4^MgP
nm, "ax"=@a%4^MgP
norm0YP--x--x--xP^M,,x,,x,,xP
%s/0/ /g
%s/1/./g
%s/2/'/g
%s/3/:/g

APL (Dyalog Extended), 45 42 bytes
' .'':'[4 4⊤{×≢⍵:⍎¨⍵~':'⋄,⍉0 10⊤3↑3↓⎕TS}⍞]

Try it online!
A full program submission.
-3 bytes from Bubbler.
Very barely edges out Golfscript (Thanks, Bubbler!).
Explanation
' .'':'[4 4⊤⍎¨{×≢⍵:⍵~':'⋄,⍉ 0 10⊤3↑3↓⎕TS}⍞]
                                        ⍞    string input
              {×≢⍵:                          if length is nonzero:
                   ⍵~':'                     remove ':'s from it
                        ⋄            ⎕TS     otherwise get current time array
                                 3↑3↓        remove yymmdd and take hhmmss
                         ,⍉ 0 10⊤            convert to base 10 digits and transpose, then flatten
                                             (pads with a zero)
            ⍎¨                               convert each character to digit
        4 4⊤                                 encode into base 4 matrix
' .'':'[                                   ] index into string " .':"

Javascript, 232 165 characters
t=>(a=t.match(/\d/g).map(x=>(+x).toString(2)).flatMap(x=>x.padStart(4).match(/..?/g)).map(x=>" .':"[x%4])).filter((_,i)=>~i&1).join``+`
`+a.filter((_,i)=>i%2).join``

Snippet
(modified because i dont count console.log() and the function assignment/call in the byte count)

f=

// 215
t=>(a=t.match(/\d/g).map(x=>(+x).toString(2)).flatMap(x=>x.padStart(4).match(/..?/g)).map(x=>" .':"[x%4])).filter((_,i)=>~i&1).join``+`
`+a.filter((_,i)=>i%2).join``

console.log(f('17:59:20'))

Haskell, 192 180 174 166 bytes
-21 characters thanks to @Laikoni
import Data.Time
main=getCurrentTime>>=interact.(\x y->unlines[map(!!i)[mapM(pure" .':")"__"!!(fromEnum e-48)|e<-take 8$y++formatTime undefined"%T"x,e<':']|i<-[0,1]])

Try it online!

@Laikoni thank you! i noticed the transpose+unlines can be made shorter too

Even shorter transpose: (\x y->(++).(++"\n").map(!!0)<*>map(!!1)$[ ... ]) can be (\x y->unlines[map(!!i)[ ... ]|i<-[0,1]]): Try it online!

Python - 201 172 characters
from time import*
t=raw_input()
if not t:t=strftime('%H:%M:%S')
t=t.replace(':','')
for i in(0,2):print''.join(" .':"[int(bin(int(d))[2:].rjust(4,'0')[i:i+2],2)]for d in t)

How about: t=raw_input().replace(':','') / if not t:t=strftime('%H%M%S') — saves you 5 characters :)

Lua - 163 160 Chars
s=io.read():match"(%S+)"or os.date("%X",os.time())t=" .':"w=io.write for l=1,2 do for k in s:gmatch"(%d)"do y=1+select(l,(k-k%4)/4,k%4)w(t:sub(y,y))end w"\n"end

VBA (Excel), 150 148 132 bytes
Using Immediate Window and Cell [A1] as input.
a=Format(IIf([a1]="",Now,[a1]),"hhmmss"):b=Split(" ,.,',:",","):For c=1To Len(a):d=Mid(a,c,1):e=e &b(d\4):f=f &b(d Mod 4):Next:?e:?f

The time is given either from the command-line or from stdin. Neither seems to work here.

I'm sorry, what do you mean?

It's an older task with a fairly stringent input restriction and VBA probably cannot handle input like specified. In terms of the task given, this answer does not solve it as it chooses to ignore part of the requirements.

@Joey, VBA, excel and several other spreadsheeting applications do not have an official STDIN or STDOUT, and as such the community has decided to allow it some leeway in how to take input. I took quite a bit of input in actually writing these down in March of 2017. Under the rules we set down then, I see no reason why this answer would be invalid, as it takes input in ISO-8601 formart

@remoel, You can improve this answer by bringing the If statement into the [..] notation, and using a non-breaking space instead of a regular space in the split statement (Alt+255), and then by using string addition instead of the string concatenation. Should look like a=Format([IF(A1,A1,NOW())],"hhmmss"):b=Split("  . ' :"):For c=1To Len(a):d=Mid(a,c,1):e=e+b(d\4):f=f+b(d Mod 4):Next:?e:?f, where the first character in the split statement is the nonbreaking space

cool tricks of non-breaking space for split function. Learned new things again XD Nice! And Thanks! :D

@TaylorScott: Okay, it's been too long that I've been active here. Usually on my tasks (back when I was active) I rigidly defined input and output to be able to provide a script that checks a solution for correctness (which can't be done if everyone can just use whatever they want). This was not one of those tasks, though. However, thinking back, I think I'd rather have fewer languages that can compete, but an objective way of checking correctness automatically. I think the thing about test scripts never really caught on, sadly.

K (ngn/k), 35 bytes
{-1_'" .':"@2/+0 2_2\.'(x^":"),"9"}

Try it online!

Scala, 222:
object C{def main(a:Array[String]){
val t=if(a.length==0)new java.text.SimpleDateFormat("HHmmss").format(new java.util.Date)else a(0).replaceAll(":","")
t.map(c=>print(" ,'"(c/4%4)));println;t.map(c=>print(" ,':"(c%4)))}}

Dash (SUSv2-compatible?), 202 200 193 169 138 137 bytes
Usage.

Requires input from positional argument.
Outputs to stdout, without trailing line.

I think I should change the language for golfing off.
Notes about 138 and 137 bytes:

May not SUSv2-compatible because it gives floating value to second argument for substr() in AWK.
It ran successfully on GAWK.

s='for(;++i<7;){D=substr($0,i,1);printf substr(" .'\'':",(h?D%4:D/4)+1,1)}i=h++'
echo ${1-`date +%H%M%S`}|tr -d :|awk "{$s;$s}"|fold -w 6

Try it online!

05AB1E, 28 bytes
õQižažbžc)T‰}Sþ4‰ø" .':"sèJ»

Try it online or verify all test cases.
Explanation:
õQi                # If the (implicit) input is empty/absent:
   ža              #  Push the current hours
     žb            #  Push the current minutes
       žc          #  Push the current seconds
         )         #  Wrap all three into a list
          T‰       #  Divmod each by 10 to add leading 0s
  }S               # After the if-statement: convert it to a flattened list of characters
                   # (which will use the implicit input-string if necessary)
    þ              # Only keep all digits to remove potential ":"
     4‰            # Divmod each digit by 4
       ø           # Zip/transpose; swapping rows/columns
        " .':"sè   # Index each into string " .':'
                J  # Join each row of characters together
                 » # Join the lines by newlines
                   # (after which the result is output implicitly)

source: Stack Exchange

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

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

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

sort: votes


text:
Calculate probability of getting half as many heads as coin tosses.
Write a program that, given a small positive even integer from standard input, calculates the probability that flipping that many coins will result in half as many heads.
For example, given 2 coins the possible outcomes are:
HH HT TH TT

where H and T are heads and tails. There are 2 outcomes (HT and TH) that are half as many heads as the number of coins. There are a total of 4 outcomes, so the probability is 2/4 = 0.5.
This is simpler than it looks.
Test cases:
2 -> 0.5
4 -> 0.375
6 -> 0.3125
8 -> 0.2734375

We can assume the coins are perfect and there's an even chance of getting heads or tails?

Do we need to print the output to stdout?

@Juan yes. @Dogbert yes.

Could we get some more test cases to verify our solutions?

@Dogbert  - done

Does the output have to be actually printed out or is computing enough?  I've got a couple of answers I could shave characters from if I migrated from complete program to interactive session.

J, 22 19 (killer approach)
I got down to this while golfing my Haskell answer.
%/@:>:@i.&.(".@stdin)_

(same I/O as my other J answer)

This gives an error for me: 0 1|domain error: script |   %/    >:i.&.(".@stdin)_

@david4dev Ouch.  My leftover script file didn't work either.  I don't remember where I messed up, but the version you tested is faulty indeed.  It's now fixed.

Pari/GP - 32 30 34 chars
print(binomial(n=input(),n\2)/2^n)

Wow, I didn't consider a programming language having a built in binomial function.

32 characters: print(binomial(n=input,n\2)/2^n).

Python 53 Characters
i=r=1.;exec"r*=(2*i-1)/i/2;i+=1;"*(input()/2);print r

Haskell, 39 43 46
main=do x<-readLn;print$foldr1(/)[1..x]

Demonstration:
$ runhaskell coins.hs <<<2
0.5
$ runhaskell coins.hs <<<4
0.375
$ runhaskell coins.hs <<<6
0.3125
$ runhaskell coins.hs <<<8
0.2734375

I get an error: Undefined variable "readln"

@david4dev the 'L' in readLn is a capital one.

I think main=do x<-readLn;print$foldr1(/)[1..x] does the same thing and saves 3 bytes?

Indeed. Merging, thanks!

Excel, 25
Not quite according to spec, though :)
Name a cell n and then type the following into another cell:
=COMBIN(n,n/2)/POWER(2,n)

Excel actually implements the ^ properly, so you can cut out a few characters that way.

Golfscript - 30 chars
Limitation - only works for inputs less than 63
'0.'\~..),1>\2//{{*}*}%~\/5@?*

test cases
$ echo 2 | ruby golfscript.rb binom.gs
0.50
$ echo 4 | ruby golfscript.rb binom.gs
0.3750
$ echo 6 | ruby golfscript.rb binom.gs
0.312500
$ echo 8 | ruby golfscript.rb binom.gs
0.27343750

Analysis
'0.' GS doesn't do floating point, so we'll fake it by writing an integer after this
\~ Pull the input to the top of the stack and convert to an integer
.. Make 2 copies of the input
),1>Create a list from 1..n
\2//Split the list into 1..n/2 and n/2+1..n
{{*}*}%Multiply the elements of the two sublists giving (n/2)! and n!/(n/2)!
~Extract those two numbers onto the stack
\Swap the two numbers around
/Divide
5@?*Multiply by 5**n. This is the cause of the limitation given above

I'm curious as to why the limitation. Are you using Gosper's hack to generate all the combinations? The idea occurred to me (and the spec doesn't say anything about execution time).

Golfscript doesn't have a float point variable class, so what he does is calculate an integer that written after the string 0. is the decimal part of the answer, but that method leaves out the required 0 when the chance grows less than 10%.

@Peter, what eBusiness said :)

J, 25 (natural approach)
((!~-:)%2&^)&.(".@stdin)_

Sample use:
$ echo -n 2 | jconsole coins.ijs
0.5
$ echo -n 4 | jconsole coins.ijs
0.375
$ echo -n 6 | jconsole coins.ijs
0.3125
$ echo -n 8 | jconsole coins.ijs
0.273438

It's all self-explanatory, but for a rough split of responsibilities:

!~ -: could be thought of as binomial(x,x/2)
% 2&^ is "divided by 2^x"
&. (". @ stdin) _ for I/O

GNU Octave - 36 Characters
disp(binopdf((n=input(""))/2,n,.5));

Ruby, 39 characters
p 1/(1..gets.to_i).inject{|a,b|1.0*b/a}

TI-BASIC, 10
This will take more than ten bytes of calculator memory because there is a program header, but there are only ten bytes of code.
binompdf(Ans,.5,.5Ans

//Equivalently:

2^~AnsAns nCr (.5Ans

This takes input in the form [number]:[program name]; adding an Input command uses three more bytes. ~ is the unary minus token.

Ruby - 50 57 54 chars
p (1..(n=gets.to_i)/2).reduce(1.0){|r,i|r*(n+1-i)/i/4}

This calculates nCr not the probability.

@david4dev, fixed.

J, 20
f=:(]!~[:<.2%~])%2^]

examples:
f 2
0.5
f 4
0.375
f 6
0.3125
f 8
0.273438

The question asks for input from STDIN, not a function.

@Dogbert: I know; I forgot to mention this. I intended to update it...

APL 21 15 chars
((N÷2)!N)÷2*N←⎕

For where it doesn't render right
((N{ColonBar}2)!N){ColonBar}2*N{LeftArrow}{Quad}

Where everything in {} are APL specific symbols like here.

Is the last character supposed to be a square?

Yes it should be the quad symbol.

I get �[token]: � undefined

I guess this is a coding issue. In NARS2000 you can copy paste it as is.

Windows PowerShell, 45
($p=1)..($n="$input"/2)|%{$p*=(1+$n/$_)/4}
$p

Meh.

MATLAB, 29
n=input('');binopdf(n/2,n,.5)

PostScript, 77
([)(%stdin)(r)file token{2 idiv}if def
1
1 1[{[exch div 1 add 4 div mul}for
=

Mathematica, 19
f=2^-# #!/(#/2)!^2&

Javascript, 86 bytes
a=prompt(f=function(n){return n?n*f(n-1):1});alert(f(a)/(f(a/2)*f(a/2)*Math.pow(2,a)))

Python 3, 99
This is a naive approach, I suppose, and fR0DDY's solution is much cooler, but at least I am able to solve it.
Try it here
from itertools import*
n=int(input())
print(sum(n/2==i.count("H")for i in product(*["HT"]*n))/2**n)

Python 2, 103
from itertools import*
n=int(raw_input())
print sum(n/2==i.count("H")for i in product(*["HT"]*n))/2.**n

Objective-C:
152 148 bytes for just the function.
Class methods, headers, and UI are not included within the code.
Input: an int value determinining the number of coins.
Output: a float value determining the probability.
-(float)calcPWithCoins:(int)x {int i=0;int j=0;for (int c=x;c<1;c+-){i=i*c;} for(int d=x/2;d<1;d+-){j=j*d;} return (((float)i/(float)j)/powf(2,x));}

Ungolfed:
-(float)calcPWithCoints:(int)x
{
    int i = 0;
    int j = 0;
    for (int c = x; c < 1; c+-) {
         i = i * c;
    }
    // Calculate the value of x! (Factorial of x)

    for (int d = x / 2; d < 1; d+-)
         j = j * d;
    }
    // Calculate (x/2)! (Factorial of x divided by 2)

    return (((float)i / (float)j) / powf(2, x));
    /* Divides i! by (i/2)!, then divides that result (known as the nCr) by 2^x.
    This is all floating-point and precise. If I didn't have casts in there,
    It would be Integer division and, therefore, wouldn't have any decimal
    precision. */
}

This is based off of the Microsoft Excel answer. In C and Objective-C, the challenge is in hard-coding the algorithms.

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


text:
Break the broken cipher
I have designed a simple random generator that cycles two numbers in a chaotic way using a multiply and modulus method. It works great for that.
If I were to use it as a cipher generator it would however be vulnerable to a known plaintext attack, given that an attacker can reverse engineer the seed from a series of random numbers in a computationally efficient manner.
To prove the cipher broken find a legal pair of seed values that generate 7 zeros in a row in the range [0;255], using as little power, CPU-time etc. as possible.
Here is the random generator written in JavaScript:
function seed(state1,state2){
    //Constants
    var mod1=4294967087
    var mul1=65539
    var mod2=4294965887
    var mul2=65537
    function random(limit){
        //Cycle each state variable 1 step
        state1=(state1*mul1)%mod1
        state2=(state2*mul2)%mod2
        //Return a random variable
        return (state1+state2)%limit
    }
    //Return the random function
    return random
}

//Initiate the random generator using 2 integer values,
//they must be in the ranges [1;4294967086] and [1;4294965886]
random=seed(31337,42)
//Write 7 random values in the range [0;255] to screen
for(a=0;a<7;a++){
    document.write(random(256)+"<br>")
}

I have made a tool for testing candidate number pairs, it can be found here.
For the next 3 days, no spoilers allowed, an answer must contain only a set of numbers, and it should of course be a different set from those posted by previous solvers. Thereafter you are encouraged to post code and explain your approach.
Edit, quarantine is over:
Answers should contain both a unique set of numbers and explanation and code to document the solving method.
Most elegant solution wins.
For the record:
Writing a program that can find a solution quickly is elegant.
Making a program that utilize the features of a GPU efficiently to do it even faster is elegant.
Doing the job on a piece of "museumware" is elegant.
Finding a solution method that can feasibly be utilized using only pen and paper is very elegant.
Explaining your solution in an instructive and easily understandable manner is elegant.
Using multiple or very expensive computers is inelegant.

Are you sure an answer exists for this?

Yes, there are ~256 of them. And I'm also sure that it's possible to find an answer in a few minutes, given a modern PC and the right programming.

Just wondering, why are GPUs elegant but not multiple CPUs?

Because they are harder to program efficiently than CPUs. You got to make sure that you are actually utilizing the GPU, no points for having most of the shaders idling because some other subsystem is bottlenecking. And of course you still got to implement an efficient algorithm to score the big points.

If I submit my working code, it's almost as if I submitted a large bunch of seed pairs.  Game end already?

I'll end it officially 1 week after start and declare a winner. It's the code that is the interesting part of any solution, you really have to post it to make a full answer. And there is definitely still room for some optimizations relative to Keith Randall's answer. Doing some code optimization surely wouldn't hurt you chances of winning. And anyone else may still participate, it takes something better to beat the first submissions, but that is not impossible.

this is an awesome question, even though the quarantine is over. thanks for creating this. i look forward to more.

I'm afraid that I don't have any equally good ideas, I'll post them if I figure something, but no guarantees.

C++, 44014022 / 164607120
It is in C++, uses 1 GB of memory, and took about 45 seconds to find this first pair.  I'll update the time once it finds them all.
Code below.  It first finds all pairs that generate 4 zeros, then whittles those down by simple trial (see the check method).  It finds pairs that generate 4 zeros by generating two large arrays, one which contains the first 4 low-order bytes of the state1 generator, and the second which contains the negative of the first 4 low-order bytes of the state2 generator.  These arrays are then sorted and searched for a match, which corresponds to the overall generator outputting 4 zeros to start.
The arrays are too big to store in memory, so it does the work in batches sized to just fit in memory.
Looks like the complete run will take ~12 hours.
Edit: Improved the code so it only takes ~1 hour to get all possible seeds.  Now it generates the tables into 256 different files, one for each first byte of output.  We can then process each file independently so we don't have to regenerate data.
Edit: Turns out you can generate the 256 subtables individually instead of all at once, so no disk needed.  Running time down to ~15 minutes using 256MB.
#include <stdio.h>
#include <stdint.h>
#include <algorithm>
using namespace std;

#define M1 65539
#define N1 4294967087
#define M2 65537
#define N2 4294965887
#define MATCHES 7

// M^-1 mod N
#define M1_INV 3027952124
#define M2_INV 1949206866

int npairs = 0;

void check(uint32_t seed1, uint32_t seed2) {
  uint32_t s1 = seed1;
  uint32_t s2 = seed2;
  for (int i = 0; i < MATCHES; i++) {
    s1 = (uint64_t)s1 * M1 % N1;
    s2 = (uint64_t)s2 * M2 % N2;
    if (((s1 + s2) & 0xff) != 0) return;
  }
  printf("%d %u %u\n", npairs++, seed1, seed2);
}

struct Record {
  uint32_t signature; // 2nd through 5th generated bytes
  uint32_t seed;      // seed that generated them
};
// for sorting Records
bool operator<(const Record &a, const Record &b) {
  return a.signature < b.signature;
}

int main(int argc, char *argv[]) {
  Record *table1 = (Record*)malloc((N1/256+1)*sizeof(*table1));
  Record *table2 = (Record*)malloc((N2/256+1)*sizeof(*table2));

  for (int i = 0; i < 256; i++) {  // iterate over first byte
    printf("first byte %x\n", i);

    // generate signatures (bytes 2 through 5) for all states of generator 1
    // that generate i as the first byte.
    Record *r = table1;
    for (uint64_t k = i; k < N1; k += 256) {
      uint32_t sig = 0;
      uint32_t v = k;
      for (int j = 0; j < 4; j++) {
        v = (uint64_t)v * M1 % N1;
        sig = (sig << 8) + (v & 0xff);
      }
      r->signature = sig;
      r->seed = k;
      r++;
    }
    Record *endtable1 = r;

    // generate signatures (bytes 2 through 5) for all states of generator 2
    // that generate -i as the first byte.
    r = table2;
    for (uint64_t k = (-i & 0xff); k < N2; k += 256) {
      uint32_t sig = 0;
      uint32_t v = k;
      for (int j = 0; j < 4; j++) {
        v = (uint64_t)v * M2 % N2;
        sig = (sig << 8) + (-v & 0xff);
      }
      r->signature = sig;
      r->seed = k;
      r++;
    }
    Record *endtable2 = r;

    sort(table1, endtable1);
    sort(table2, endtable2);

    // iterate through looking for matches
    const Record *p1 = table1;
    const Record *p2 = table2;
    while (p1 < endtable1  && p2 < endtable2) {
      if (p1->signature < p2->signature) p1++;
      else if (p1->signature > p2->signature) p2++;
      else {
        check((uint64_t)p1->seed * M1_INV % N1, (uint64_t)p2->seed * M2_INV % N2);
        // NOTE: may skip some potential matches, if p1->signature==(p1+1)->signature or p2->signature==(p2+1)->signature
        p1++;
      }
    }
  }
}

I didn't think a harddisk would be fast enough to be efficient for the task. Interesting.


text:
Implement Shamir's Secret Sharing reconstruction
Shamir's secret sharing scheme is a simple way of protecting a secret by splitting it into several parts needed to reconstruct it.
Your task is to implement Shamir's Secret Sharing reconstruction over the Finite Field defined by the prime 1928049029. If you have any doubts about what this means, just ask or see Finite Field & Finite Field Arithmetic in wikipedia (more resources below).
Input
Input is done using stdin. First comes an integer k, then k lines follow. Each of these lines contains a pair of integers x y that represent a secret. In other words f(x) = y in the original polynomial that was used to construct the secrets.
The number of secrets given is always enough to construct the corresponding secret.
Output
Output to stdout the reconstructed secret.
Examples
Input:
5
1 564797566
2 804114535
4 1354242660
6 1818201132
7 503769263

Output:
1234

Input:
7
1 819016192
2 1888749673
3 1737609270
4 365594983
5 1628804870
6 1671140873
7 492602992

Output:
456457856

Resources
Wikipedia article
Paper
Finite field Source: Wikipedia
Finite field arithmetic Source: Wikipedia
Lagrange polynomial Source: Wikipedia
Chapter on Finite field arithmetic

bash, 271 chars
r(){
[ ${1/0/} ]&&{ r $(($2%$1)) $1;((t=u,u=v-$2/$1*u,v=t));}
}
read
((N=1928049029,n=0))
while read x[$n] y[$n]
do((n++))
done
for((i=n;z=(z+l)%N,i--;))do
for((j=n,l=y[i];j--;))do
((u=0,v=1,d=x[j]-x[i],M=N+d))
r M N
[ ${d/0/} ]&&((l=l*x[j]%N*(u+N)%N))
done
done
echo $z
The newlines could be replaced in most cases with semicolons, but I don't think there's any unnecessary whitespace.
(I hadn't realised before today that bash's integers are 64-bit - very helpful).
For bash the recursive GCD (exploiting global state) seems to be more compactible than the iterative one. This is mostly straightforward; the interesting trick is [ ${d/0/} ]&&foo which is effectively if [ $d -ne 0 ];then foo;fi

Nice! I never expected to see a bash answer to this problem. +1

@Juan, I started doing it in Perl, and got fed up with having to force it to do integer division rather than float. And I know bash better anyway, so it involves less beating of head against wall.

199 characters in Octave:
m=@(x)mod(x,1928049029);[d,l]=scanf('%d');c=d(1);e=repmat(int64(d(2:2:l)),1,c);[_,b]=gcd(e-e',1928049029*ones(c));b=eye(c)+m(e.*b);x=b(1,:);for i=2:c;x=m(x.*b(i,:));end;disp(m(sum(m(x'.*d(3:2:l)))))

Golfscript, 114 112 111 110 109 65 (86) chars
If you don't care about getting results this week, 65 chars suffice:
~](;2/0\:X{~\.X{0=}%^\{\.@- 1928049029:P.,\@{@*\%(!}++?**}+/+P%}/

But if you're looking for efficiency, it's slightly longer at 86 chars:
~](;2/0\:X{~\.X{0=}%^\{\[.0](@-[1928049029:P%P]{.~/{\.(;@@~@*-+\}+2*.1=}do;0=*}+/+P%}/

This is dissected in far more detail than I want to repeat here on my blog.

Mainly not my work, but cribbing heavily from Nabb gives 47 chars:
n%(!\:A{~A{~;.3$- 1928049029:N((?1or**}/\/+N%}/

Note: I've only reasoned about this code: trying to run it would be pointless given the length of time and amount of memory it would use.

Golfscript - 52 46 (67)
A brute force approach for modular inverses in 46 characters. Repeatedly computes a^(N-2) with arbitrary precision integers.
n%(!\:A{~A{~;.3$-.!+1928049029:N((?**}/\/+N%}/

Implementing the extended Euclidean algorithm only costs us an additional 15 characters.
n%(!\:A{~A{~;.3$-:|!1\1928049029:N{@2$|3$/*-\|\:|%.}do;;**}/\/+N%}/

This code is fully detailed on my blog post, including some alternatives for computing the modular multiplicative inverse.

Nice, but I think there are still at least two chars to be saved. Replace {*N%2<} with {*N%1=} as in the blog and you can ditch the (; after N,. But then for the performance-is-irrelevant entry you can use Fermat's little theorem without bothering about the modular side of the exponentiation - just leave that for the final tidy - so recip becomes N((?.

@Peter: {*N%1=}+ will miss the case with the denominator zero, which would take at least 3 characters to handle. Good catch on simply doing x^(N-2) though, we can actually get 46 characters using this.

Lua 444 Chars
Works for the example on the wiki page
3
2 1942
4 3402
5 4414

But somehow does not work for the examples here on this page. If anyone can find the error?
Non-golfed version:
-- Reconstruct shamir secret
-- convention, poly = {[0]=a0,a1,...,an}
i=io.read
f=math.fmod
w=1928049029
k=i():match"%d+"
x={} -- Will contain X values
y={} -- Will contain Y values
p={} -- will contain lagrange polynomials

-- Read data
for j=0,k-1 do
    x[j],y[j]=i():match("(%d+) (%d+)")
    print(j,x[j],y[j])
end
-- Multiplication and scaling function
function mul(p,q,s)
    -- multiply polies
    r={} -- poly to be returned
    for k=0,#p do
        for l=0,#q do
            r[l+k]=r[l+k] or 0 -- if the coeff for degree l+k of x doesn't exist, put 0
            p[k]=p[k] or 0 -- if p hasn't got a coeff for x^k
            q[l]=q[l] or 0 -- idem for q
            r[l+k]=(r[l+k]+s*p[k]*q[l]%w -- calculate increment for coeff for x^(l+k)
        end
    end
    -- Debugging
    io.write"Multiplied "
    printPoly(p)
    io.write"With       "
    printPoly(q)
    io.write("And scaling factor ",tostring(s),"\n")
    io.write"Yielding   "
    printPoly(r)
    return r
end

function printPoly(p) -- "Pretty" printing of the polynomial
    for k=#p,1,-1 do
        io.write(tostring(p[k] or 0),"x^",tostring(k),"+")
    end
    io.write(p[0])
    io.write"\n"
end
function egcd(a,b)
    if a == 0 then
        return b, 0, 1
    else
        local g, y, x = egcd(b % a, a)
        return g, x - math.floor(b / a) * y, y
    end
end

function inv(a,m)
    a=a>=0 and a or a+m
    local g,x,y = egcd(a,m)
    if g== 1 then
        return x%m
    else
        print(a,"has no inverse mod",m)
    end
end

-- generate lagrange polynomials
for j=0,#x do
    print("j=",j,"*********")
    for m=0,k-1 do
        if m~=j then -- if m==j, continue
            p[j]=p[j]or{[0]=1} -- if this poly doesn't exist, take 1
            p[j]=mul( p[j], {[0]=-x[m],1},inv(x[j]-x[m],w))-- multiply with (x-x_m)/(x_j-x_m)
            io.write"---------------------------------\n"
        end
    end
end
r=0 -- Result for x^0
for k=0,#p do
    print("l_"..k)
    printPoly(p[k]) -- print l_k
    r=r+f(y[k]*p[k][0],w) -- add coeff for x^0 to result
end
print("Secret was",f(r,w)) -- display result

Golfed (not using finite field), 444 chars:
i=io.read f=math.fmod w=1928049029 k=i():match"%d+"x={}y={}p={}for j=0,k-1 do x[j],y[j]=i():match("(%d+) (%d+)")end
function mul(p,q,s)r={}for k=0,#p do for l=0,#q do r[l+k]=r[l+k]or 0 p[k]=p[k]or 0 q[l]=q[l]or 0 r[l+k]=f(r[l+k]+s*p[k]*q[l],w)end end return r end
for j=0,#x do for m=0,k-1 do if m~=j then p[j]=p[j]or{[0]=1}p[j]=mul(p[j],{[0]=-x[m],1},1/(x[j]-x[m]))end end end r=0 for k=0,#p do r=r+f(y[k]*p[k][0],w)end
print(f(r,w))

The Wikipedia example doesn't use a finite field, which is really a shame, that would have been a lot more instructive. That is most likely the source of your error.

Java, 435 407 chars
import java.util.*;public class G{public static void main(String[]args){Scanner s=new Scanner(System.in);int i,k,n=s.nextInt();long N=1928049029L,x[]=new long[n],y[]=new long[n],z=0,l,c;for(i=n;i-->0;){x[i]=s.nextInt();y[i]=s.nextInt();}for(i=n;i-->0;){l=y[i];for(long j:x)if(x[i]!=j){c=1;for(long a=N+j-x[i],b=N,d=0,t;b>0;){t=d;d=c-a/b*d;c=t;t=b;b=a%b;a=t;}l=l*j%N*(c+N)%N;}z+=l;}System.out.println(z%N);}}

Ungolfed:
import java.util.*;
public class G {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int i,k,n=s.nextInt();
        long N=1928049029L,x[]=new long[n],y[]=new long[n],z=0,l,c;
        for (i=n; i-->0;) {
            x[i]=s.nextInt();
            y[i]=s.nextInt();
        }
        for (i=n; i-->0;) {
            l=y[i];
            for (long j:x)
                if (x[i]!=j) {
                    // Extended Euclid algorithm - iterative version -
                    // to find the reciprocal of j-x[i] (mod N)
                    c=1;
                    for (long a=N+j-x[i], b=N, d=0, t; b>0;) {
                        t=d; d=c-a/b*d; c=t;
                        t=b; b=a%b; a=t;
                    }
                    l = l*j%N;
                    l = l*(c+N)%N;
                }
                z+=l;
        }
        System.out.println(z%N);
    }
}

Haskell, 183
p=1928049029
a#0=(1,0)
a#b=let(s,t)=b#mod a b in(t,s-div a b*t)
s d=sum[y*product[z*fst((z-x)#p)|[z,_]<-d,z/=x]|[x,y]<-d]
main=interact$show.(`mod`p).s.map(map read.words).tail.lines


text:
Shorten this code while fixing a major bug
I found the code below today after much hair pulling. Shorten it down (code golf) and fix the bug that I found (bonus).
#define LN_SOME_TEXT_FIELD 256

void GetSomeText(LPTSTR text)
{
    TCHAR       buf[LN_SOME_TEXT_FIELD + 1];
    short       i;
    LPTSTR      curChar;

    curChar = text;
    i = 0;
    while (*curChar != NULL) {
        if (*curChar != '&') {
            buf[i] = *curChar;
            i++;
        }
        curChar++;
    }
    buf[i] = NULL;
    SomeOtherUIFunction(buf);
}

EDIT
Added a tail call, this is what the real function does, sorry for not including it earlier.

Hard to tell bugs from features without a spec

I'm guessing there is even a deeper bug here: Is this code meant to "unescape" a string, for some escaping mechanism?

@MtnViewMark, my guess is that it's removing the & which is used in Windows to indicate the shortcut key of a widget

@Peter, ah yes, the type names should have clued me in!

Is this code golf or darn it I'll post this as code golf and claim the credit at work. ¬¬ (shifty eyes)

@mbomb why bump this, lmao

@Flp.Tkc Because it's unclear what they're asking.

@mbomb007 but it was posted in 2011, buried under all challenges, why bring it to the top?

@Flp.Tkc To close it. We do that all the time. If we find an old question that'd not on topic, you close it.

Old questions can still be answered, so if one should be closed, it shouldn't be overlooked simply because it's old.

Similarly, if we find old answers that were not deleted, but are invalid or joke answers or don't meet the specs, then we delete them.

Are you sure you didn't fix the bug already?  I don't see a flaw in the logic, but I do see a few obvious problems:

The output buffer is never returned, so this function is a no-op. The post was changed so the buf is used now.
The output buffer has a fixed-width.  This is fine, as long as the input's length does not exceed LN_SOME_TEXT_FIELD.
Using NULL instead of '\0'.  NULL expands to ((void*) 0), meaning it's a pointer.  It should not be used to refer to the null character.

Anyway, here is a nicer (in my opinion) version of the code above:
void GetSomeText(const char *in, char *out)
{
    for (; *in != '\0'; in++) {
        if (*in != '&')
            *out++ = *in;
    }
    *out = '\0';
}

this one also fixes the possible i overflowing error. (well, actually, it'll go out of bounds before that...but still...)

Haskell, 13 characters
filter(/='&')

or, not golf'd:
getSomeText :: String -> String
getSomeText = filter (/='&')

But, I'm guessing that this isn't the desired function, but probably something that unescapes. If so, then the function is g, 36 characters:
g('&':a:z)=a:g z;g(a:z)=a:g z;g _=[]

or, not golf'd:
getSomeText :: String -> String
getSomeText ('&':a:as) = a : getSomeString as
getSomeText (    a:as) = a : getSomeString as
getSomeText []         = []

Seriously, this is exactly why functional programming matters. "Turn on, tune in, learn Haskell!"

Perl, 5 chars
s/&//
Or sub GetSomeText{$@[0]~=s/&//} if you insist on wrapping something so trivial in a subroutine.

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


text:
Rotate Cartesian coordinates.
Write a program rotates some Cartesian coordinates through an angle about the origin (0.0,0.0). The angle and coordinates will be read from a single line of stdin in the following format:
angle x1,y1 x2,y2 x3,y3 ...

eg.
3.14159265358979 1.0,0.0 0.0,1.0 1.0,1.0 0.0,0.0

The results should be printed to stdout in the following format:
x1',y1' x2',y2' x3',y3' ...

eg.
-1.0,-3.23108510433268e-15 -3.23108510433268e-15,-1.0 -1.0,-1.0 -0.0,-0.0

Am I allowed a leading space in the output?

@JB yes that is fine

Can J unary minus signs (_) be used for output? For input?

Perl, 112 80 78
s/\S*//;$c=cos$&;$s=sin$&;s/([^ ,]*),(\S*)/($1*$c-$2*$s).",".($1*$s+$2*$c)/ge

Run on command-line as perl -pe 'code here', p option counted in code size.
For reference, here's my previous approach.  But regexes are too damn powerful.
split/[ ,]/,<>;$_='A;Y,print$x*cos($a)-$y*sin$a,",",$x*sin($a)+$y*cos$a,$"whileX';s/[AXY]/\$\l$&=shift\@_/g;eval

Python (157)
from math import*;f=float
i=raw_input().split();a=f(i[0])
c=cos(a);s=sin(a)
def p((x,y)):print"%f,%f"%(c*x-s*y,s*x+c*y),
for l in i[1:]:p(map(f,l.split(',')))

C (124 Characters)
main(){double t,x,y,c,s;scanf("%lf",&t);c=cos(t);s=sin(t);while(~scanf("%lf,%lf",&x,&y))printf("%lf,%lf ",c*x-s*y,s*x+c*y);}

this doesn't compile.

@david4dev wild guess: link with -lm

@david4dev http://www.ideone.com/nuhLz

It compiles and runs OK with -lm.

J, 58 (with one bug)
c=:charsub
(r.@{.*}.)&.(".@('-_,j'&c :.('j,_-'&c))@stdin)_

Sample run (note I've replaced the origin test case with some negative input, as that was actually a pain to get right with J's representation of negatives):
echo -n '3.14159265358979 1.0,0.0 0.0,1.0 1.0,1.0 -1.0,-1.0' | jconsole rotate.ijs
-1,3.23109e-15 -3.23109e-15,-1 -1,-1 1,1

There is one family of input that will not render exactly as asked (though calling it wrong would be debatable).  Which one exactly is left as an exercise to the reader :-)

APL (Dyalog Extended), 51 bytes
x←⎕⋄g←{(¯1 2⍴1↓x)×⍤1⊢⍵○⊃x}⋄∊⍉↑(⊂-/g⌽⍳2)⍪⊂',',¨+/g⍳2

Try it online!
Reduced by a lot with dzaima's help at The APL Orchard. Apparently there's still room to save a few bytes, which I'll be golfing later.
Explanation
x←⎕⋄g←{(¯1 2⍴1↓x)×⍤1⊢⍵○⊃x}⋄∊⍉↑(⊂-/g⌽⍳2)⍪⊂',',¨+/g⍳2
x←⎕                                                 store input as x
   ⋄g←{                  }                          define function g:
                       ⊃x                           first element of x
                     ⍵○                             take sine & cosine of it based on argument
                 ×⍤1⊢                               multiply with each row of
       (¯1 2⍴1↓x)                                   the points reshaped into pairs
                          ⋄                         finally,
                                              +/g⍳2 x sin theta + y cos theta
                                        ⊂',',¨      prepend comma to each
                                       ⍪            joined with
                              (⊂-/g⌽⍳2)             x cos theta - y sin theta
                            ⍉↑                      convert to matrix and transpose
                           ∊                        and enlist the elements

Wolfram Mathematica, 35 bytes
 RotationTransform@#[[1]]/@#~Drop~1&

OP's test case:
 RotationTransform@#[[1]]/@#~Drop~1&@{3.14159265358979,{1.0,0.0},{0.0,1.0},{1.0,1.0},{0.0,0.0}}

{{-1., 3.23109*10^-15}, {-3.23109*10^-15, -1.}, {-1., -1.}, {0., 0.}}

If we instead use exact values, we can get an exact output:
 RotationTransform@#[[1]]/@#~Drop~1&@{Pi,{1,0},{0,1},{1,1},{0,0}}

{{-1, 0}, {0, -1}, {-1, -1}, {0, 0}}

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


text:
Detect rotated strings
Read two strings from stdin.
Output Yes if one string is a rotated version of the other.
Otherwise output No
Testcases
Input
CodeGolf GolfCode

Output
Yes

Input
stackexchange changestackex

Output
Yes

Input
stackexchange changestack

Output
No

Input
Hello World

Output
No

So (abcdefAB, ABabcdef) is a "YES"?

Should it really be a rotation or is a combination fine too? eg. what will Stackexchange Stackchangeex return?

@Eelvex, yes. @jpjacobs, It would return No. The rotation is a shift, like those LED scrolling signs

Are the strings always whitespace-free and separated by whitespace?

More specifically, what characters are allowed in those strings?

Originally I was intending two strings of non-whitespace separated by whitespace, but I see people are doing hacks with regex. That's cool as long as the test cases pass.

APL (28)
Takes input on two lines.
'No' 'Yes'[1+(⊂⍞)∊⌽∘A¨⍳⍴A←⍞]

Explanation:

A←⍞: read a line of input and store it in A
⌽∘A¨⍳⍴A: Rotate A by x, for each x in [1..length A]. Gives a list, i.e. estT stTe tTes Test
(⊂⍞)∊: read another line of input, and see if it is in this list.
1+: add one to this, giving 1 if the strings were not rotated and 2 if they were
'No' 'Yes'[...]: Select either the first or second element from the list 'No' 'Yes' depending on whether the strings were rotated or not.
This value is output automatically.

Ruby 49 41
a,b=$*;puts (a*2).sub(b,'')==a ?:yes: :no

Edit: replaced gets.split by $*

That's an ingenious idea.

Very clever. :)

$* is argv when the question specified stdin though.

Python, 70 bytes
a,b=raw_input().split()
print ['No','Yes'][a in b*2and len(a)==len(b)]

Testing ...

+1 Nice, selecting the result from an array is clever! :-)

The question states you should read two strings from stdin, which this solution does not.

@Ventero:Fixed.

You can skip the space in print ['No

Python 70 Characters
a,b=raw_input().split()
print'YNeos'[len(a)<>len(b)or a not in 2*b::2]

Thanks to gnibbler for the slice trick.

Same problem as the GolfScript solution: If you input nn nfn, you get Yes, which is wrong.

@TomWij Thanks for finding the bug. Corrected. Should work now.

You can replace <> by - as that will also result in 0 if they are of equal length.

But what if they are not of equal length?
Then it doesn't work so well :-)

@hallvabo then the strings are not rotated version of each other.

Yes of course, but the output will be wrong too, since the slicing trick only works with 0 or 1, not an arbitrary integer...

@hallvabo I am sorry I did not understand your point at first. Thanks for finding that. I have updated the solution.

I think python3 would be slightly shorter

J, 47
y=:>2{ARGV
(>1{ARGV e.1|.^:(i.#y)y){'No',:'Yes'

Why the two J answers?

@JB: because this one uses the buildin rotate. Both answers su^H^H are not so good btw. There is a lot of room for golfing.

why the other one, then, I'm tempted to ask? :-)

@JB: because I thought this one is barely legal ( :p ) [ while the other one extends nicely to lisp. ]

errr... the other one seems to read input from the command-line as well

According to the spec (same string lengths):
Perl, 42 43 chars
$.=pop;$_=(pop)x2;print+(qw'yes no')[!/$./]

If different sized strings are allowed, the solution would be:
Perl, 47 chars
$.=(pop)x8;$_=(pop)x9;print+(qw'yes no')[!/$./]

rbo

Same problem as the GolfScript solution: If you input nn nfn, you get Yes, which is wrong.

seems to be ok (I missed the'!' in the first version)
"nn nfn" => no
"CodeGolf GolfCode"
=> yes

Golfscript, 31
' '/:)~,\,=)~.+\/,(&'Yes''No'if

This one check length first, so it should work as expected.

:) and =) +1 for very happy code

J, 57
{&('No';'Yes')@-:/@:((/:~@(|."0 _~i.&$))&.>)&.(;:&stdin)_

Sample use:
$ echo -n CodeGolf GolfCode | jconsole rotate.ijs
Yes
$ echo -n stackexchange changestackex | jconsole rotate.ijs
Yes
$ echo -n stackexchange changestack | jconsole rotate.ijs
No
$ echo -n Hello World | jconsole rotate.ijs
No

Windows PowerShell, 76
$a,$b=-split$input
('No','Yes')[+!($a.length-$b.length)*"$b$b".contains($a)]

JavaScript, 51
function f(a,b)a&&(a+a).replace(b,"")==a?"Yes":"No"

JavaScript doesn't have a canonical host, so this answer is written as a function of two arguments.  The score goes up to 60 if we disallow JS 1.7 features (expression closures).
In the SpiderMonkey shell this would be (for a score of 71):
[a,b]=readline().split(" ");print(a&&(a+a).replace(b,"")==a?"Yes":"No")

5 years later and now you can use the => function notation ;)

Python, 66 63

a,b=raw_input().split()
print'YNeos'[a!=(2*a).replace(b,"")::2]

Another solution in 69 char
a,b=raw_input().split()
print['No','Yes'][a in b*2and len(a)==len(b)]

print'YNeos'[a!=(2*a).replace(b,"")::2]

@gnibbler nice trick, thanks for suggestion. I updated the code

J, 84
y=:(>1{ARGV),:(>2{ARGV)
((0{y)e.(y&((]$0{[),(]-~[:}.[:$[)$1{[)/.i.}.$y)){'No',:'Yes'

Python, 71
a,b=raw_input().split()
print'Yes'if a in b*2and len(a)==len(b)else'No'

Same problem as the GolfScript solution: If you input nn nfn, you get Yes, which is wrong.

Problem has been solved, remains low... :-)

Doesn't read from stdin as specified.

Now it does... :-)

JavaScript (120 chars)
function f(a,b) {for (i=0,A=a.split("");A.join("")!=b&&i++<a.length;A.push(A.shift()));return A.join("")==b?'Yes':'No';}

Output:
f('CodeGolf','GolfCode'); //Yes
f('stackexchange','changestackex'); //Yes
f('stackexchange','changestack'); //No
f('Hello','World'); //No
f('nn','nBn'); //No

Ruby, 58 (62) characters
a,b=gets.split;$><<(a.size==b.size&&/#{a}/=~b*2?:Yes: :No)

This solution assumes the input contains only alphanumeric characters (actually everything that doesn't have a special meaning inside a regular expression is ok).
A solution that doesn't have this constraint is 4 characters longer
a,b=gets.split;$><<(a.size==b.size&&(b*2).index(a)?:Yes: :No)

Haskell (98 96 chars)
g x y@(t:r)(z:w)|x==y="Yes"|1>0=g x(r++[t])w
g _ _[]="No"
f(x:y:_)=g x y y
main=interact$f.words

PHP, 61
<?echo preg_match('/^(.+)(.*) \\2\\1$/',fgets(STDIN))?Yes:No;

Ruby, 41
puts gets =~ /^(.+)(.*) \2\1$/ ?:Yes: :No

Doesn't print anything, results in ':No' for input 'aaa aaa' (on my machine). The regexp approach could be a good idea though.

Fix to actually print and input from stdin instead of args: puts gets =~ /^(.+)(.*) \2\1$/ ?:Yes: :No - ups it to 41 chars.

Q (50 43 chars)
{`No`Yes x in((!)(#)y)rotate\:y}." "vs(0:)0

bash 56
read a b
[[ $a$a =~ $b&&$b$b =~ $a ]]&&echo Yes||echo No

Scala 78
val b=readLine split " "
print(b(0).size==b(1).size&&(b(0)+b(0)contains b(1)))

It's a shame about the size check, without it the count drops to 54
val a=readLine split " "
print(a(0)+a(0)contains a(1))

"""val b=readLine split " " print(b(0).sorted==b(1).sorted)""".length yields 56

GolfScript, 25 bytes
' '/~.2*@/''+='Yes''No'if

How it works
             # STACK: "CodeGolf GolfCode"
' '/         # Split input string by spaces.
             # STACK: [ "CodeGolf" "GolfCode" ]
~            # Dump the array.
             # STACK: "CodeGolf" "GolfCode"
.            # Duplicate the topmost string.
             # STACK: "CodeGolf" "GolfCode" "GolfCode"
2*           # Repeat the topmost string.
             # STACK: "CodeGolf" "GolfCode" "GolfCodeGolfCode"
@            # Rotate the three topmost strings.
             # STACK: "GolfCode" "GolfCodeGolfCode" "CodeGolf"
/            # Split the second topmost string around the topmost one.
             # STACK: "GolfCode" [ "Golf" "Code" ]
''+          # Flatten the array of strings.
             # STACK: "GolfCode" "GolfCode"
=            # Check for equality.
             # STACK: 1
'Yes''No'if  # Push 'Yes' for 1, 'No' for 0.
             # STACK: "Yes"

CJam, 21 bytes
r]r_,,\f{\{(+}*}_@+^!

Try it online!

This answer seems to return 0/1 instead of No/Yes.

Jelly, 17 13 bytes
ɠṙJɠeị“Yes“No

Try it online!
How it works
ɠṙJɠeị“Yes“No - Main link. Takes no arguments
ɠ             - Read a line from STDIN
  J           - Indices; [1, 2, ..., len(S)]
 ṙ            - All rotations of S
   ɠe         - Read a line from STDIN; is that in the rotations?
     ị“Yes“No - Index that into ["Yes", "No"]

Husk, 14 bytes
Not sure about the rules here, Husk doesn't do IO at all. The closest alternative is a function:
!w¨Ye∫No¨€U¡ṙ1

Try it online!
Explanation
!w¨Ye∫No¨€U¡ṙ1
           ¡    -- iterate the following for ever:
            ṙ1  --   rotate string by 1
          U     -- only keep the longest prefix with unique elements
         €      -- is the argument in that list?
  ¨Ye∫No¨       -- compressed string: "Yes No"
 w              -- split on space
!               -- modular index (1-based)

Lua 115 chars
a,b=io.read():match"(%w+) (%w+)"c=b repeat c=c:sub(2,-1)..c:sub(1,1) s=s or a==c until b==c print(s and"Yes"or"No")

C program - 146
char b[99],c[99],*p,*q;main(n){q=(p=b+(n=strlen(gets(c))))+n;sprintf(b,"%s%s"
,c,c);for(gets(c);p>b&&strcmp(p,c);--p,*--q=0);puts(p>b?"Yes":"No");}

PHP, 82 characters
<?$s=split(" ",fgets(STDIN));echo str_replace($s[1],"",$s[0].$s[0])==$s[0]?Yes:No;

Ruby, 30 37
gets
puts~/^(.+)(.*) \2\1$/?:Yes: :No

A version that prints "true" and "false" instead of "yes" and "no":
gets
p !! ~/^(.+)(.*) \2\1$/

Both of these work with different-length strings (unlike the old one)

Does work if the two strings have the same length, but fails on input like 'golfcode golf'.

perl, 123 chars
@s1=split(//,shift);
$s2=shift;
$i=0;
while($i<=@s1){
    if(join("",@s1) eq $s2){die "yes";}
    unshift @s1,pop @s1;
    $i++;
}
die "no";

Python 2, 86 Characters
a,b=raw_input().split()
print"Yes"if any(a==b[n:]+b[:n]for n in range(len(a)))else"No"

Fixed to say Yes/No and improved (91 chars)
import List;f[a,b]|a`elem`[x++y|x<-tails b|y<-inits b]="Yes";f _="No";main=interact$f.words

original Haskell (92 chars) that says True/False
import Data.List;f(a:b:_)=any(a==)$zipWith(++)(tails b)(inits b);main=interact(show.f.words)

You can save a few characters with import List and also by using $ instead of parens around the argument to interact.  But your program outputs True and False instead of the required Yes and No, so that might take a few extra chars to fix.

Perl (just a quick fix)
A fix to rubber boots' solution, being a new user that I am I can't comment yet so I'll just post a new answer.
As the mentioned method uses a regular expression constructed from user input, it is possible to perform a small regex injection, as follows:

> perl -le '$.=pop;$_=(pop)x2;print+(qw/yes no/)[!/$./]' anything '.*'
yes

The fix is to use \Q (known also as quotemeta):

> perl -le '$.=pop;$_=(pop)x2;print+(qw/yes no/)[!/\Q$./]' anything '.*'
no

The code itself could be further shortened using 'say' but this is left as an exercise to the reader :)

Furthermore, instead of print+(qw/yes no/)[ you can probably write print qw(yes no)[ which is two characters shorter.

Clojure, 95
The function rotated? simply tests one string against all possible rotations of the other. Brute force.
(defn rotated?
  [a b]
  (let[l (count a)
       b (seq b)]
    (->> a cycle (partition l 1) (take l) (some #{b}))))

I personally don't care where the input strings come from, but if it has to be stdin...
(apply rotated? (.split (read-line) " "))

This would add 38 to character count, if strings were whitespace separated.
(rotated? (read-line) (read-line))

This would add 32 to character count, if strings were newline separated. The function rotated? works with any characters in the strings.

Bash, 70 65 59 55 characters
new approach:
read a b;c=$a$a;[[ ${c/$b/} == $a ]]&&echo yes||echo no

solution 2 fails on echo ofofo fofof | bash rotated.sh - doesn't it? Else I would remove even more WS: read a b[[ $a$a =~ $b&&${#a}-eq${#b} ]]&& echo yes||echo no. I had a very similar idea, and think it works.

You're right, more ws can be removed, and the paratheses! Need a ; after the read tho.

@userunknown - hah, got'cha ;)

You can remove a blank before and one behind ==.

I tried, but then it always return 'yes'.

You're right. So my test was wrong. Have to verify my own solution isn't wrongly tested too... - ok: verified.

JavaScript - 66
p=prompt,a=p(),b=p();alert(!b.match(a)&&!!b+b.match(a)?'Yes':'No')

This says True for “foo” and “foot”. 2) The output has to be “Yes” or “No”. The other participants spent great amount of code to produce the required output. Please do so.

Is the problem true/false or that 'foo' is not a rotation of 'foot'?

Giving wrong result for “foo” and “foot”, is a bug. 2) Producing different output then required, is just deviation. Many answers fail to conform with the requirements in various degrees – some got downvoted, others not. Is up to you to decide whether you risk some downvotes or correct them.

Should be working now.

Much better. It gives “Yes” for “foo” and “.*”, but as the question owner still not replied to the comment about allowed characters, let us suppose that only the character classed used in the samples are allowed.

@manatwork, Oops, dunno how I missed that for so long. I've replied to it now :)

05AB1E, 20 bytes
Code:
DgFÀD²Qi"Yes",q}}"No

Uses CP-1252 encoding. Try it online!

The builtins and features of 05AB1E have improved quite a bit over the years. :) 13 bytes is now possible

Jelly, 16 bytes
ɠJṙ@€ɠe@ị“Yes“No

Try it online!
Many thanks to @cairdcoinheringaahing and @MrXcoder for helping me out in chat.
Explanation:
ɠ                   # The first string
  ṙ@€               # Rotated by...
 J                  #   The indexes of each element in the string
     ɠ              # The second string
      e@            # Exists in that list of strings.
                    # (either '0' or '1')
        ị           # Indexed into the list...
         “Yes“No    # ["yes", "no"]

C (gcc), 118 113 111 bytes
-5 bytes thanks to ceilingcat
i,l,r;f(s,t)char*s,*t;{for(l=r=0,i=strlen(s);i--;)r=strncmp(s+i,t,++l)|strncmp(s,t+l,i)?r:3;puts(r+"No\0Yes");}

Try it online!

jq -Rn, 62 + 4 = 65 bytes
len('if[inputs|explode|sort|implode]|.[0]==.[1]then"Yes"else"No"end')

As in the accepted answer, the two strings should be on separate lines. -R is used to avoid having to quote the input strings, and -n is used to disable the default input processing because inputs takes care of that.

Stax, 11 bytes
Ä:∩ö┌┘/YJTI

Run and debug it
This program takes input on two lines.
Unpacked, ungolfed, and commented, it looks like this.
:(      get all rotations
s|#     other input is a member of rotations?
`n!`    "Yes"
.No     "No"
?       (a ? b : c)

Run this one

05AB1E, 13 bytes
ā._Êßi„Noë”…Ü

Try it online or verify all test cases.
Explanation:
ā         # Push a list in the range [0, length] for the (implicit) input-string,
          # without popping this input-string itself
          #  i.e. "CodeGolf" → [1,2,3,4,5,6,7,8]
 ._       # Rotate the string that many times towards the left (vectorized)
          #  "CodeGolf" and [1,2,3,4,5,6,7,8] → ["olfCodeG","lfCodeGo","fCodeGol","CodeGolf",
          #                                      "odeGolfC","deGolfCo","eGolfCod","GolfCode"]
   Ê      # Check for each whether it's NOT equal to the second (implicit) input-string
          #  "GolfCode" → [1,1,1,0,1,1,1,1]
    ß     # Pop and push the minimum (to check if any are falsey)
          #  [1,1,1,0,1,1,1,1] → 0 (falsey)
     i    # If this minimum is truthy (so all rotations were unequal to the second input):
      „No #  Push string "No"
     ë    # Else:
      ”…Ü #  Push dictionary string "Yes"
          # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to use the dictionary?) to understand why ”…Ü is "Yes".

PHP, 57 bytes
Input via space-delimited string on STDIN, output to STDOUT is "Yes" or "No" string.
<?=strpos(($a=explode(' ',$argn))[1].$a[1],$a[0])?Yes:No;

Try it online!
Or with Default I/O input via command line args and output truthy/falsey.
PHP, 37 bytes
<?=strpos(($a=$argv)[2].$a[2],$a[1]);

Try it online!
Or as a function:
PHP, 41 bytes
function($a,$b){return strpos($b.$b,$a);}

Try it online!

36 bytes

27 bytes using PHP 7.4 arrow functions

K3 / Kona, 28
{:[y _in![;x]'!#x;`Yes;`No]}

Pyth, 18 bytes
?}zm.<QdlQ"YES""NO

Try it online
Explanation
?}zm.<QdlQ"YES""NO
   m   dlQ            For each number in [1, ..., len(first input)]...
    .<Q               ... rotate the first input that many characters.
 }z                   Check if the second input is in that list.
?         "YES""NO    Return "YES" or "NO" appropriately.

Brachylog, 17 bytes
~c₂ᵐ↔ᵈ∧"Yes"|∧"No

Try it online!
(If the input strictly has to be whitespace-separated, add two bytes to prepend ṇ₁, but note that the input still has to be quoted. Brachylog does not have any sort of direct access to stdin.)
Takes input as a list of two strings, and outputs through the output variable. The actual logic is all in the first six bytes, which succeed if the elements of the input are rotations of each other, and fail if they are not:
   ᵐ      Both strings in the input
~c₂       can be split into two pieces each
    ↔ᵈ    such that one string's two chunks are the other's swapped.

(↔ᵈ could just as well be pᵈ, pᵛ, or oᵛ which is what it was originally before I decided that ↔ᵈ is more to the point.)
Although it would be possible to brute force rotating one of them until it matches, the number of rotations would need to be explicitly bounded, and on top of that just the effort required to separate out the two elements of the input list would be fairly costly. Since it's very easy to brute force partitions in Brachylog, the fact that a rotation is just as much taking one chunk off one end and moving it to the other as it is doing that to single characters however many times saves a lot of bytes.
With very flexible I/O, this could be as short as 5 bytes, taking one string through the input variable and the other through the output variable: ~c₂↔c

Thunno 2, 14 bytes
ż€ẒQM"YesNo"½i

Try it online!
Explanation
ż€ẒQM"YesNo"½i  # Implicit input
ż€Ẓ             # All rotations of the first input
   QM           # Is the second input NOT in it?
     "YesNo"½   # Push the list ["Yes", "No"]
             i  # Index the result into it
                # Implicit output

Raku, 55 bytes
->\a,\b {my@a=a.comb;grep {b eq@a.rotate($_).join},^@a}

Returns a list of rotate positions that produce a match, which is truthy when non-empty.
If you have to output Yes or No, then the following takes 66 bytes:
->\a,\b {my@a=a.comb;<No Yes>[?grep {b eq@a.rotate($_).join},^@a]}

Try it online!

J, 28 bytes
(;:'No Yes'){::~[e.#\@]|."{]

Takes in input via function arguments.
Attempt This Online!
(;:'No Yes'){::~[e.#\@]|."{]
                           ]  NB. right arg
                   #\@]       NB. take the right arg then get the length of each prefix [1..len(y)]
                       |."{   NB. rotate the right by each element of the left, obtain all rotations
                [e.           NB. is the left arg a member of the resulting table?
(;:'No Yes')                  NB. split the string, returns an array of boxed strings
            {::~              NB. fetch using the boolen result of e., unlike {, this unboxes the result


text:
GolfScript - The missing function
The GolfScript language has one serious lack, no float or fixed point handling. Remedy this by creating a function F for converting an integer number, given as a string, to a string representing 1 / 10 000 000 000 of it's value. The function must handle both positive and negative values as well as leading 0s.
The following pretty-print rules apply:
No trailing 0s.
No . if the result is integer.
No leading 0s, except for numbers with no integer part, they should have 1 leading 0.
The result must be output as a single string.
Examples:
123 -> 0.0000000123
-00 -> 0
012345678901234567890 -> 1234567890.123456789
-123 -> -0.0000000123
10000000000001 -> 1000.0000000001
123000000000000 -> 12300
The competition is only between GolfScript submissions using no Ruby functionality. Solutions in other languages may be posted, but they are not eligible for winning, these may not use any fixed or float point functionality that the language offers, and must accept arbitrarily large inputs.

55 chars
{~.0<"-"*\abs 10.?..3$@%+`-1%~`)[3-]1$,!!*+-1%@@/\++}:F

Negative numbers are a bit of a pain - responsible for about 13 chars of the 55. Trailing 0s are handled by using a 1 to stand for the decimal point, reversing as a string, converting to an int, and back again, and re-reversing.

I wrote the requirements pretty strictly, you better give them an extra read and correct your code as needed, I'll postpone a full validation until you make an edit. But it's great to see the question finally being answered.

@eBusiness, sorry, got so focussed on the pretty print rules that I forgot the bit about a function.

Okay, that makes one correct entry of 66 characters, and one incorrect of 57 that prints dots for integers.

@eBusiness, I'll fix the second one when I got home. Wrote it on a scrap of paper on the bus. Edit: actually, I think I spotted the problem.

It pass all my test cases now, time to dig in and see what delicious details are in your code.

Your 55 solution is also good. And just for the rabbit effect, I have got a 50 solution :-P

V - Seems like you are going to be the only contestant.

50 characters
{..~0<<\~abs`.,11\-,,0`*\++-10/(~.!!\"."+*\+-1%}:F

The most noteworthy trick in this solution is probably -10/, detach the last 10 characters and inverse, so that the trailing 0s can be culled by conversion by conversion to integer.

I think the nicest trick is the << to get the "-". I spent ages looking for a better way to do that and didn't find yours.

-10/ was what gave me the big advantage, though I probably was a bit lucky to find that "Hmmm, it also reverses the string, ohhh, that might be an advantage.". << surely ain't bad either. A shame that we didn't get some more participants, I'm sure this puzzle is hiding more tricks waiting to be uncovered.

@Nabb Are we missing anything obvious? (And do the summon even work when you haven't participated in the thread?)


text:
Quine Challenge I
Challenge

In this task you have to write a program that will take input
  an integer N (-1e9 <= N < 0 && 0 < N
  <= +1e9), then compute T = (abs(N) %
  M+1),if N is positive then output
  the T-th character from the
  beginning else output the T-th
  character from the end of your source.
M is the size of your source in bytes.

Example: If your source is: abcd efg/hi
Input:
 2

Output:
 c

Input:
-3

Output:
g

Input:
-9249678

Output:
b

Input:
-11

Output:
i

Constraints

Don't use any FILE operation
You can use any language of your choice
Try to avoid or rather don't use 1 byte submissions, since it spoils all fun.
Shortest solution wins!

EDIT: Problem statement have been modified so that the solutions could be
  judged using a random test-data (and
  same data for all solutions) hence
  please update your solution
  accordingly,sorry for the inconvenience
  (if any).

In the give example test case if the input is 5 or -7 the output should be a single space : " " (without quotation).

What if N is 0?

@eBusiness:Thanks for pointing that out, I have changed the problem statement,I don't think $0$ can occur now :-)

@Debanjan: your edit makes the case where N=M+1 a little weird.

Opertor precedence %M will be executed first before addition ;-)

@Debanjan: oh I see.  The spacing got me.

Your examples don't match your challenge description, if I'm not completely mistaken. First example: N=2, so T=3. The 3rd character is c, not b.

@Ventero:Yes,thanks for pointing,I fixed it now.

It sorta keeps on being a strange mapping, now a character is skipped at the jump from 0 to 1: -2 -> / -1 -> h 0 -> i 1 -> b 2 -> c. But at least the mapping is now unanimous.

I guess the && in the first sentence is meant to be a ||?

x86 assembly (32-bit Linux, AT&T syntax): 548
No newline at end of file:
pushl 8(%esp)
call atoi
mov $274,%ebx
cmp $0,%eax
jg a
dec %eax
a:cdq
idiv %ebx
cmp $0,%edx
jge p
add %ebx,%edx
p:add $s,%edx
cmp $s+273,%edx
jl l
push $34
mov %esp,%edx
l:mov $4,%eax
mov $1,%ebx
mov %edx,%ecx
mov $1,%edx
int $128
mov $0,%ebx
mov $1,%eax
int $128
s:.ascii "pushl 8(%esp)
call atoi
mov $274,%ebx
cmp $0,%eax
jg a
dec %eax
a:cdq
idiv %ebx
cmp $0,%edx
jge p
add %ebx,%edx
p:add $s,%edx
cmp $s+273,%edx
jl l
push $34
mov %esp,%edx
l:mov $4,%eax
mov $1,%ebx
mov %edx,%ecx
mov $1,%edx
int $128
mov $0,%ebx
mov $1,%eax
int $128
s:.ascii "

I compiled it with gcc -nostartfiles -m32 qc1.S -o qc1
Verification, positive numbers:
$ for i in $(seq 548 1095); do ./qc1 $i; done | cmp - qc1.S && echo Good
Good

Verification, negative numbers:
$ for i in $(seq -1095 -548); do ./qc1 $i; done | cmp - qc1.S && echo Good
Good

Edit got it right about the weird numbering scheme.  I think.  It didn't change the length.

+1,That's brilliant work to do this in assembly,but one small thing I have modified the problem to make testing unanimous so please modify your solution like-wise, Thanks.

Heh, pretty cool. And a funny thing, despite being so different languages this does seem to resemble my 44 characters GolfScript solution.

@Debanjan: I really can't seem to be able to wrap my head around the numbering scheme.  Could you provide the proper verification lines? (the problem statement would be a fine place)

+1, that's your second "invalid" asnwer here (code-golf wise) that worths upvoting :)

@Eelvex: for the record, the other one was valid at the time it was posted.

@Eelvex: there you go, this one's now totally valid.  Perhaps a bit long, though O:-)

Whaddaya know, HQ9+ makes its great return!
Q

No need to bother indexing when there's only one character to choose from!

Does it take any input?

@Debanjan: sure: echo '-1' | hq9+ qc1

Sorry,this is not making much sense to me,I have one similar solution in PHP but ain't this types of solution spoils all the fun? Thanks,

You don't have to accept it if you don't think it fits in, you know!  You don't even have to upvote it.  You may even downvote it, though I'd personally not appreciate ;-)

No,It's not about acceptation or rejection,I was just stating a point also I would like up-vote it since I learn something new :-)

Ruby 1.9, 66 characters
z=gets.to_i;s="z=gets.to_i;s=%p;$><<(s%%s)[z%%66]";$><<(s%s)[z%66]

Not much difference to a normal quine, actually.

Edit: Follows the new specs now.

GolfScript 26 characters
{':f`f'+1/\~.1<- 26%=}:f`f

Quines were more fun before the invention of dynamic languages.
Edit: For the whiners, here is a "real" GolfScript quine, no ` and ~ only used for parsing the input.
Handicapped GolfScript 44 characters
'"\x27"\+1/\~.1<- 22%='"\x27"\+1/\~.1<- 22%=

Notice how nicely it is the same string repeated twice, so the string literal just need a ' hacked in front of it and it's ready for use.

I don't know GolfScript, but your comment pushes me to think your code leans towards the "FILE operation" category of constraints.  Care to expand its innards?

The magic happens by the use of the  operator, basically I define a function, store it in a variable, convert the function to it's own string representation ( does that), and then I run the function, which can trivially finish the task as it has it's own innards in the string.

+1: to Quines were more fun before the invention of dynamic languages. :-)

Well I sure as hell wouldn't be trying this one in assembly language...

@J B:This is great fun in C,I did something like this recently :-)

Ok, maybe I'll give it a shot.  Just not this week.

I think I'm 100 years behind you people :(

Scratch that. I did try this one in assembly language.

Lenguage, 4 bytes
Source code consists of 4 null bytes. Regardless of the input, the output should thus be a null byte, which is accomplished by one . instruction.

Smalltalk, 94 90 59 52
for example, in the Object class, compile:
q:n|s|s:=thisContext method source.^s at:n\\s size+1

then send q:<n> to any object; here an integer:
verification:
1 q:0 -> q
1 q:1 -> :
1 q:2 -> n
...
1 q:-1 -> )
1 q:-2 -> )
1 q:-3 -> 1
or better:
(0 to:100) collect:[:n|1 q:n]as:String
-> ')q:n|s m|s:=thisContext method source.m:=s size.^s at:(n>=0ifTrue:n-1\\m+1ifFalse:m-(0-n\\m))q:n|s m|'
(-1 downTo:-500)collect:[:n|1 q:n]as:String
-> ')m\\n-0(-m:eslaFfi1+m\\1-n:eurTfi0=>n(:ta s^.ezis s=:m.ecruos dohtem txetnoCsiht=:s|m s|n:q))m\\n-0('
explanation for non-Smalltalkers:
thisContext is the current stack frame, which can be asked for its method, which can be asked for its source.

Runic Enchantments, 17 bytes
"3X4+kSq:l͍iS%%@

Try it online!
Just uses standard quine to generate the program string, then uses string-based modulo operator1 to get the character at a given index (which natively support negative and positive indicies, behavior influenced by Python).

The , "divide" command cuts the string up into chunks (logical enough inverse of * duplicating the string x times), + concatenates, and - removes x characters from the end (a logical enough inverse of +). So the % command takes the role of charAt(x): the only basic string operation remaining (after stack-like operations being handled by the same commands that deal with the stack; eg. l is the size of the stack so l͍ is the length of a string).

JavaScript (ES6), 28 bytes
f=n=>("f="+f).substr(n%28,1)

A modified quine.
A value larger than 28 is handled by %28, a value less than 0 is handled by .substr().