text:
Code Golf: Leibniz Series
This is the same question as Solve the CodeSprint4 Leibniz code golf challenge in Python in 66 characters. The variation is that I'm a C programmer. My code for the above question is:
#include <math.h>
main(){
int i,t,p;
scanf("%d",&t);
while(t--)
{
double s=1;
scanf("%d",&p);
for(i=1;i<p;++i)
s+=pow(-1,i)/(2*i+1);
printf("%.12lf\n",s);
}
}

Now I just need to know the places where I could reduce my code length.

You missed #include<stdio.h>

Actually, you don't need neither of the two #include @CoolGuy. Most C compilers will complain but compile nevertheless.

Please include a specification of the requirements in the body of the question.  When the link's dead, it's impossible to know what inputs are expected and what output to produce, other than by grokking the code.

I'm guessing that the objective is to compute the Leibniz formula for π (1 - 1/3 + 1/5 - 1/7 +...) to p terms, t times - is that right?

Do everything in one line.
Don't read number of test cases, scanf will return -1 on EOF
Don't include anything, pow(-1,i) can be replaced by 1-i%2*2
Do the sum loop in reverse to save a variable.

Here is my 102 bytes code
main(n){gets(&n);for(double s;s=scanf("%d",&n)>0;printf("%.15f\n",s))while(--n)s+=(1-n%2*2)/(1.+2*n);}

(1-n%2*2) - It seems that signs depend on n's parity, but they shouldn't. Or not?

@Qwertiy n here is decreased every loop

Yes, you are right. By some reason I thought about sign using n and formula using i, but there is n in both parts.

Remove include and replace pow by check.
Use the fact that scanf returns number of read and saved fields.
Replace while via for.
Remove figure brackets.
Use %f in printf for double - only scanf needs %lf.
I didn't check if following code works fine, but even if smth is wrong, the correct result have to be somewhere near it:
main(){
int i,t,p;
double s;
for(scanf("%d",&t);t--;printf("%.12f\n",s))
for(s=i=scanf("%d",&p);i<p;++i)
s+=(i&1?-1:1)/(2.*i+1);
}

By the way, what about making all variables double instead of int?

Can't i write a code in the comments here?

Drop the i variable, you just need p and s in the inner loop: for(s=scanf("%d",&p);--p;s+=(p&1?-1:1)/(1+2.*p));

(i&1?-1:1) --> (1-i%2*2)

From memory, I think you can do: main(i,t,p){ to declare them as ints.


text:
Minecraft Chest Placement
The video game Minecraft is all about placing and removing different types of blocks in the 3D integer lattice that makes up the virtual world. Each lattice point can contain exactly one block or be empty (an "air" block officially). In this challenge, we will only be concerned with one horizontal 2D plane of the 3D world, and one type of block: chests.
Chests let players store items. When two chests are orthogonally adjacent in the same horizontal plane, their textures link up and a double chest with twice the capacity forms. Nothing bigger than a double chest can be made; there are no triple chests nor quadruple chests.
A chest block can only be placed in an empty lattice point if its four orthogonally adjacent points are all empty, or if exactly one contains a chest block that is not already part of a double chest. These placement rules ensure that there can never be any ambiguity about which chest blocks link to form double chests.
For example, suppose . is empty space and C is a chest: (The numbers are also empty space and just for identification purposes.)
.......C..
.1.C2.C3..
........5C
.CC4..CC..
..........

A chest can be placed in spot 1 because its 4 neighbors are empty.
A chest can be placed in spot 2 because the neighboring chest is not (yet) part of a double chest.
A chest can't be put in spot 3 because there would be ambiguity over how the double chest forms.
A chest can't be placed in spot 4 because the neighboring chest is already part of a double chest.
A chest can be placed in spot 5. The diagonally neighboring double chest doesn't affect anything.

Assuming the area beyond the grid is empty, changing every . in the grid to a * if a chest could be placed there results in this:
******.C**
***C**C.**
*..***..*C
.CC.*.CC.*
*..***..**

Not all of the * spaces can be occupied with chests at the same time of course, but if you only had one chest, it could be placed in any of them.
Challenge
Write a program or function that takes in a . and C grid, and changes every . to a * if a chest could be placed there, printing or returning the resulting grid.

Input can be from stdin or a file or as a string argument to a function.
You may assume the input is well formed - i.e. a perfectly rectangular grid of text, at least 1 character wide and tall, only containing . and C You may optionally assume there is a trailing newline after the last row (and there may be one in the output).
You may assume the arrangement of chests in the input is consistent with the rules above. There will never be ambiguities about which chests form double chests.
If desired, you may use any three distinct printable ASCII characters in place of ., C, and *. You may not use something else in place of newlines.
All the chests are normal chests. Not trapped chests or ender chests.

Scoring
The submission with the fewest bytes wins.
For a Minecraft related challenge that's a bit more challenging, try Nether Portal Detection.

From a Minecrafting point of view, I found this pretty annoying in-game. Good thing there are trapped chests :P

When taking grid input from stdin or a single string argument, is it acceptable to take the grid dimensions as an additional input? or does it have to be inferred from newlines and string length?

@steveverrill It has to be inferred.

Just out of curiosity, why does every answer including my own have one downvote? I can only assume it is the same person, would they care to explain?

For an extra challenge, one could write a program to find the optimal placement for the chests; that is, find a configuration that allows the maximum number of additional chests to be placed without breaking the rules even between the new chests.

"If desired, you may use any three distinct printable ASCII characters in place of ., C, and *." -- Is that for input, output or both?

You can now place chests everywhere from 1.13

CJam, 82 76 66 62 58 54 bytes
qN/::~4{[8_]f/[9_]f*z{[{1$8-g)+}*]W%}%}*{_8<\2<8?}f%N*

Input format expects 0 for air cell and 8 for a chest cell. Output contains 1 for all cells that can be placed with a Chest.
UPDATE : Fixed a bug. Increased by 3 bytes :( golfed further :) . 4 bytes saved thanks to @Sp3000
Example input:
0000000800
0008008000
0000000008
0880008808
0000000000

Output:
1111110811
1110018010
1008800108
0880088008
1008800110

I think I am done golfing for now...
Explanation
qN/::~                   "This part converts the input into array of integer array";
qN/                      "Split input on new line";
   ::~                   "Parse each character in each row as integer";

4{[8_]f/[9_]f*z{[{1$8-g)+}*]W%}%}*

4{   ...z{       W%}%}*  "Run the logic 4 times, first, columns in correct order, then,";
                         "columns in reverse order, then for rows";
  [8_]f/[9_]f*           "Convert adjacent chests represented by two 8 into two 9";
                         "This happens for all the rows in the columns iterations and";
                         "for all the columns in the rows iterations";
  {               }%     "For each row/column";
   [{        }*]         "Reduce and wrap it back in the array";
     :I8-                "Store the second number in I, remove 8 from it";
         g               "Do signum. Now we have -1 for < 8 number, 0 for 8 and 1 for > 8";
          )+I            "Increment to get 0, 1 & 2. Add it to first number and put I back";

{_8<\2<8?}f%N*           "This part converts the output from previous iterations";
                         "to 3 character based final output and prints it";
{        }f%             "Map each row using the code block";
 _8<   8?                "If the value is greater than 7, make it 8, else:";
    \2<                  "If the value is greater than 1, make it 0, else 1";
            N*           "Join the arrays using new line";

Try it online here

.NET Regex (Retina), 434 416 310 + 1 = 311 bytes
After the last challenge I answered in regex (the Nether Portal Challenge linked to in this challenge), I finally set out to write a command-line tool, which acts as an interpreter for .NET-style regular expressions, so I can answer questions with regex without being challenged that they're not a stand-alone language. I've named it Retina.
Now, this challenge doesn't lend itself very well to a regex submission, but I just had to use Retina now. ;) (Plus, Sp3000 challenged me to do so in chat.) So here it is:
Regex file
m`(?<=(?=.(.)*).*)(?<=((?<=(?<2>C|C(?(1)!)(\n|(?<-1>.))*)?)C(?=(?<2>C|(\n|(?<-1>.))*(?(1)!)C)?)(()(?(6)!)|(?<=^(?(7)!)(?<-7>.)*C).*\n(.)*()(?(8)!)))?){2}_(?=(?<2>((?(10)!)()|(?(11)!)()(.)*\n.*(?=C(?<-12>.)*(?(12)!)$))(?<=(?<2>C|C(?(1)!)(\n|(?<-1>.))*)?)C(?=(?<2>C|(\n|(?<-1>.))*(?(1)!)C)?))?){2}(?<-2>)?(?(2)!)

Replacement file
*

The regex file is mostly just the regex, except that ` lets you put a few options in the file, in this case simply multiline mode. When given two files, Retina automatically assumes replace-all mode. These two files define a program which reads the input from STDIN and prints the result to STDOUT.
You can also test it on RegexHero and RegexStorm. The regex works both with and without trailing newline, and uses _ in place of .. (Apparently, RegexStorm occasionally has problems if there is no trailing newline, but RegexHero seems to handle either case fine.)
There is a horrible amount of duplication in the regex, and I have a couple of ideas for shortening it significantly... I'll give that a try later and then add an explanation. In the meantime, let me know if you can find any inputs which yield a wrong result.

J, 75 73 68 bytes
(+.0j1^i.4)(+:@](LF,@:,.~'*.C'{~>.)(2=f)+.[f]*f=.[:+/|.!.0)'C'&=;._2

Uses the format in the question, using ./*/C for space/usable space/chest, respectively.
Edit: fixes a small bug (I accidentally used a torus instead of properly treating the surrounding as empty space).
Explanation
## Preparation
              'C'&=;._2  NB. Map ./C to 0/1, turn into matrix
(+.0j1^i.4)              NB. Compute offsets to shift into each direction
                         NB. (i.e. [[_1 0], [1 0], [0 _1], [0 1]] in any order)

## "Part B"
(2=f)+.[f]*f=.[:+/|.!.0  NB. This part computes a matrix that is 1 for cells that
                         NB. cannot contain a chest:
              [:+/|.!.0  NB. Sum of shifts: shift in each of the four cardinal
                         NB. directions (using the array above) and then sum up.
           f=.           NB. Define this function as `f`; we'll use it some more.
         ]*              NB. Multiply by the "is chest" matrix: this isolates
                         NB. double-chests.
       [f                NB. Sum of shifts--1 for double-chest neighbours.
(2=f)                    NB. Isolate cells with two neighbouring chest.
     +.                  NB. Boolean or--either two neighbouring chests or next
                         NB. to a double-chest.

## Wrap up the result
(+:@] (fmt >.) PartB)    NB. Maximum of the array from the above and twice the "is
 +:@]      >.  PartB     NB. chest" matrix--this is 0,1,2 for '*', '.' or chest,
                         NB. respectively.

## Output formatting
LF,@:,.~'*.C'{~          NB. Format output...
        '*.C'{~          NB. Map 0,1,2 to '*.C' by using the value as index
LF   ,.~                 NB. Append line feed at end of each line
  ,@:                    NB. Ravel into one line

C,193
2 unnecesary newlines for clarity. Changes with respect to ungolfed code include: characters as ascii codes instead of character literals; rearrangement of v=0,strlen, and  strchr to save characters (strchr is the ugliest, as it means that a calculation that would otherwise be performed once only, is performed 5 times per cell!)
C functions do not accept strings as arguments or return them as values, so the best I can do is the following: q is a pointer to the input string. The function modifies the string and when the function returns the output is found in the original string.
g(char*q){int v,j,w,l;
int f(p,d){int s=0,i=w=strchr(q,10)-q+1,r;for(;w/i;i-=i-1?w-1:2)r=p+i,r>-1&r<l&&q[r]==67&&++s&&d&&f(r,0);v|=s>d;}
for(j=l=strlen(q);j--;f(j,1),46-q[j]||v||(q[j]=42))v=0;}

To summarize the rules:
a blank square (that does not contain C or newline) can be converted if it has max 1 neighbour with a C
...AND that neighbour has no neighbours with a C.
The function g contains a function f that recurses down from depth 1 to depth 0. With only 2 levels of recursion, a simple f(r,0) recursive call will do, there is no need for f(r,d-1)!
Ungolfed code in test program
Input test string is hardcoded. gets and scanf will not accept an input string with newlines in it; they chop it into pieces at each newline.
char n[]=".......C..\n...C..C...\n.........C\n.CC...CC..\n..........";

g(char*q){

  int v,j,w,l;

  int f(p,d){                    //p=cell to be checked,d=recursion depth
    int s=0,i=w,r;               //sum of C's found so far=0, i=width
    for(;w/i;i-=i-1?w-1:2)       //For i in   w,1,-1,-w   = down,right,left,up
      r=p+i,                     //r=cell adjacent to p
      r>-1&r<l&&q[r]=='C'&&++s   //If r not out of bounds and equal to C, increment s...
        &&d&&f(r,0);             //...and if recursion depth not yet at zero, try again one level deeper.
    v|=s>d;                      //If the local s exceeds d, set global v to true to indicate invalid.
  }

  w=strchr(q,10)-q+1;            //width equals index of first newline + 1
  l=strlen(q);                   //length of whole string;
  for(j=l;j--;)                  //for l-1 .. 0
    v=0,                         //clear v
    f(j,1),                      //and scan to see if it should be set
    '.'-q[j]||v||(q[j]='*');     //if the character is a '.' and v is not invalid, change to '*'
}

main(){
  g(n);
  puts(n);
}

Output based on question example
******.C**
***C**C.**
*..***..*C
.CC.*.CC.*
*..***..**

JavaScript (ES6) 124 129
Using characters 0 (*), 6 (C), 7(.)

F=s=>[for(c of(d=[o=~s.search('\n'),-o,1,i=-1],s))
   d.map(j=>t-=s[i+j]==6&&~d.some(k=>s[i+j+k]==6),t=i++)|c<7|t>i&&c
].join('')

Ungolfed and explained

F=s=>
{
  o=~s.search('\n') // offset to prev row (~ is shorter than +1 and sign does not matter)
  d=[o,-o,1,-1] // array of offset to 4 neighbors
  i=-1
  result = '' // in golfed code, use array comprehension to build the result into an array, then join it
  for (c of s) // scan each char
  {
    t = i++ // set a starting value in t and increment current position in i
    d.forEach(j => // for each near cell, offset in j
    {
      if (s[i+j]==6) // if cell contains a Chest, must increment t
      {
        // In golfed code "~some(...)" will be -1(false) or -2(true), using decrement instead of increment
        if (d.some(k=>s[i+j+k]==6)) // look for another Cheast in the neighbor's neighbors
        {
          // more than one chest, position invalid
          t += 2
        }
        else
        {
          t += 1
        }
      }
    })
    if (c < 7 // current cell is not blank
        || t > i) // or t incremented more than once, position invalid
    {
       result += c // curent cell value, unchanged
    }
    else
    {
       result += 0 // mark a valid position
    }
  }
  return result
}

Test In Firefox/FireBug console

a='\
7777777677\n\
7776776777\n\
7777777776\n\
7667776677\n\
7777777777\n';

console.log(F(a))

Output
0000007600
0006006700
0770007706
7667076670
0770007700

Perl, 66
The regexp matching chest conflicts ended up on the long side, so no competing with CJam this time.
#!perl -p0
/.
/;$"=".{@-}";s%0%s/\G0/2/r!~/2((.$")?2(.$")?|2$"|$"2)2/s*1%eg

Uses 0 and 2 for empty and chest spaces on the input, 1 to mark the spots on the output.
Try it here.

Python 2 - 281 bytes
f=lambda x,y:sum(m[y][x-1:x+2])+m[y-1][x]+m[y+1][x]
m=[];o=''
try:
 while 1:m+=[map(int,'0%s0'%raw_input())]
except:a=len(m[0]);l=len(m);m+=[[0]*a]
for y in range(l*2):
 for x in range(1,a-1):
    if y<l:m[y][x]*=f(x,y)
    else:o+=`2if m[y-l][x]else +(f(x,y-l)<5)`
 if y>=l:print o;o=''

(Lines 8 and 9 are intended with a single tab character, which SE converts to 4 spaces. Every line in this program has either 0 or 1 bytes of leading whitespace.)
Input: 0 for no chest, 2 for chest
Ouput: 0 for no chest, 2 for existing chest, 1 for possible new chest

God, this is horrible. I must be seriously out of practice. I threw every trick I know at it and it came out... well, it came out as 281 bytes, losing to every answer except the one in regex, haha. I honestly feel like I golfed it kinda well, so I'm guessing that my algorithm was just less than ideal.
Ungolfed:
def f(x,y):
    """Given x,y coords of the board, return the sum of that point and all
    adjacent points.
    """
    return (sum(board[y][x-1:x+2]) # (x-1,y) + (x,y) + (x+1,y)
            + board[y-1][x]
            + board[y+1][x])
board=[]
output=''
try:
    while True:
        row = '0%s0' % raw_input() # line from stdin with a leading and trailing 0
        board.append(map(int, row)) # convert to list of ints
except:
    pass # exception is thrown when stdin is empty

board_width = len(board[0])
board_height = len(board)

board.append([0]*board_width) # new row of all 0s

for y in xrange(board_height*2):
    # board_height multiplied by 2 so we can use this loop to simulate two
    for x in xrange(1,board_width-1):
        if y < board_height: # "first loop"
            board[y][x] *= f(x,y) # multiply everything on the board by itself + sum
                                  # of neighbours
                                  # empty cells (0) stay 0 no matter what
                                  # lone chests (2 surrounded by 0) become 2*2==4
                                  # double chests (2 touching another 2) are weird:
                                  # - one chest becomes 2*(2+2)==8
                                  # - the other chest becomes 2*(2+8)==20
        else: # "second loop"
            if board[y - board_height][x] != 0:
                output += '2' # anything not equal to 0 is an existing chest
            else:
                valid = f(x, y - board_height) < 5 # if the sum of neighbours > 4, the
                                                   # current cell is either beside a
                                                   # double chest or more than one
                                                   # single chest
                output += '01'[valid]
    if y >= board_height: # only print during the "second loop"
        print output
        output=''

source: Stack Exchange

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

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

sort: votes


text:
Fifty Shades of Grey
Boys and girls are excited to see Fifty Shades of Grey on the silver screen, we just want to code without being bothered, so here's a challenge to pick our brain.
You have to:

Print on the screen fifty squares filled each with a different shade of grey
If your language of choice lacks image processing capabilities, you could output an image file
Squares must be visible, at least 20 x 20 pixels
You cannot use random numbers unless you make sure each shade is unique.
You cannot connect to any service over any network
You cannot read any files in your program.
You cannot use any libraries out of the standard libraries of your language of choice.

This is code golf so shortest code wins.

Were they bothering us?

Can't use C++... ;-(

Can we also generate an image file if our language lacks image processing capabilities?

@FUZxxl yes, that's ok

Objection: misleading title!

Will we see a Piet submission?

@MukulKumar why not?

@BWG: presumably Mukul means because C++ has no standard means to access a screen. Terminal, yes, and you could do it assuming certain terminal properties (background colour control codes) and the aspect ratio of the terminal characters (to get a square).

@SteveJessop I didn't read the request fully, but couldn't you just write a bitmap? The header is pretty trivial, and the rest is just plain bytes.

@randomra If I could understand what "The interpreter finds the edge of the current colour block which is furthest in the direction of the DP. (This edge may be disjoint if the block is of a complex shape.)
The interpreter finds the codel of the current colour block on that edge which is furthest to the CC's direction of the DP's direction of travel. (Visualise this as standing on the program and walking in the direction of the DP; see table at right.)" meant, I would be working on a Piet submission

@BWG: that's what the CJam answer below does, so of course you could do that. It's clearly not what the question says, but I think the questioner has been overruled by the voters.

Not the pictures I thought we'd be generating for a 50 shades of grey contest.

@randomra ask and you shall receive: http://codegolf.stackexchange.com/questions/45736/fifty-shades-of-grey/46877#46877

Is jquery allowed?

Do black and white count as shades of grey? Or should they be excluded?

http://codepen.io/anon/pen/gbeKjR html: 666bytes

*devil in the details

@BWG Oh...I was so much immersed in array handling that I forgot to use graphical header files....LOL I was still thinking of ASCII characters....:P

@SalmonKiller Sure, if you include jquery.js in the byte count.

Why has not the shortest code won?

@Steffen sorry I thought that was the shortest answer that  didn't break any of the rules, what is the answer that you mention?

What about sanchises "MATLAB, 24 bytes"?

@Steffen you're right, thanks!

Now that Fifty Shades Darker has come out, should we make all these answers darker by 50 shades?

MATLAB, 24 bytes
Second attempt, now actually conforming to the rules.
imshow(0:1/49:1,'I',2e3)

The 'I' stands for 'InitialMagnification', but apparently Matlab will autocomplete names in name/value pairs. Sure is a good golfing trick!

Mathematica, 30 bytes
Here is another Mathematica approach:
ArrayPlot[#+5#2&~Array~{5,10}]

or
ArrayPlot[5#+#2&~Array~{10,5}]

The first one simply creates an array
{{6, 11, 16, 21, 26, 31, 36, 41, 46, 51},
 {7, 12, 17, 22, 27, 32, 37, 42, 47, 52},
 {8, 13, 18, 23, 28, 33, 38, 43, 48, 53},
 {9, 14, 19, 24, 29, 34, 39, 44, 49, 54},
 {10, 15, 20, 25, 30, 35, 40, 45, 50, 55}}

and the second one
{{6, 7, 8, 9, 10},
 {11, 12, 13, 14, 15},
 {16, 17, 18, 19, 20},
 {21, 22, 23, 24, 25},
 {26, 27, 28, 29, 30},
 {31, 32, 33, 34, 35},
 {36, 37, 38, 39, 40},
 {41, 42, 43, 44, 45},
 {46, 47, 48, 49, 50},
 {51, 52, 53, 54, 55}}

Then, ArrayPlot plots them as a grid and, by default, uses greyscale to visualise the values.

Lovely use of ArrayPlot.

That's funny, MatrixPlot seems to use colors by default, it's lucky for this challenge that ArrayPlot uses grayscale and it is one letter shorter than MatrixPlot.

You could do ArrayPlot@{Range@50}, which is only 20 bytes.

@ChipHurst when I do that, the default size is too small to meet the 20x20 pixels requirement.

CJam - 23 (no actual graphical output)
Since CJam can't draw on the screen (yet?), I wrote a program that outputs an image in plain pgm format.
Save the output to a file called 50.pgm and open with an image viewer/editor.
"P2"1e3K51_,1>K*$K*~]N*

Try it online
The result looks like this:

Explanation:
"P2"     push "P2" (netpbm magic number)
1e3K     push 1000 and K=20 (image size)
51       push 51 (value of white)
_,       duplicate 51 and convert to an array [0 1 2 ... 50]
1>       remove 0 (slice from 1)
K*       repeat the array 20 times
$        sort, to get [(20 1's) (20 2's) ... (20 50's)]
K*       repeat the array 20 times
~        dump the elements on the stack
]        put everything from the stack in an array
N*       join with newlines

So being happy increments the elements!?

@Caridorc of arrays containing numbers, yes. And being sad decrements them :p

You don't follow the PGM's specification: No line should be longer than 70 characters.

@iKiWiXz updated

@iKiWiXz Should, not must. Lines may be longer than that but programs that generate PGM images should try to keep them under 70 characters.

@FUZxxl Feel free to check: http://netpbm.sourceforge.net/doc/pgm.html

Mathematica 72 61 59 43 35 34 bytes
Current version (34 bytes)
GrayLevel[#/50]~Style~50 &~Array~50

Earlier version (59 bytes), thanks to Martin Büttner.
Graphics[{GrayLevel[#/50],Cuboid@{#~Mod~9,#/9}}&/@Range@50]

Blue borders added to highlight position of squares.
Graphics[{EdgeForm[Blue], GrayLevel[#/50], Cuboid@{#~Mod~9, #/9}} & /@Range@50]

Number of squares:
    Length[%[[1]]]

50

First attempt (72 bytes)
If the squares can overlap.
As Zgarb notes, there is a remote possibility that one square would hide another.
  Graphics@Table[{GrayLevel@k,Cuboid[{0,15}~RandomReal~2]},{k,.4,.89,.01}]

I'm guessing that one square could in principle cover another completely, so that less than 50 would be visible?

Definitely the most esthetically pleasing answer.

Sage - 26 24 35 29 characters
matrix(5,10,range(50)).plot()

It looks like this:

Previous attempts: First I had Matrix([range(50)]).plot(), then matrix_plot([range(50)]). These looked like this:

User @flawr pointed out that the squares produced with default settings are too small. Adding a figsize options fixes it, but it is 6 characters longer than the 5x10 version at the top of this answer:
matrix_plot([range(50)],figsize=20)

Looks like 51 shades and the squares look smaller than 20x20px, is it bigger when produced by your program?

I don't think extra output is forbidden, @flawr, I didn't bother removing the frame, tickmarks and numbers either. You might be right about the squares being too small, I'll check.

Argh! @flawr is right the squares are smaller than 20px by 20px.

I would say extra output should be forbidden.  The question specifies '50', not '50 or more'.

Am I understanding correctly, @Joe, that you don't object to the frame and the numbers outside the frame, only to the number of squares? If that's the case, just replace 50 with 49.

R, 47 42 39 38 37 36 35 bytes
Assuming they're allowed to overlap, this works. Symbols requires a vector that holds the size for each square, and I'm saving space by reusing the same vector for all function parameters. The largest square is always 1 inch wide. With 50:99 as the range of integers, the smallest square will be around half an inch wide, so 36 pixels at 72 dpi.
symbols(x,,,x<-50:99,bg=gray(x/99))

Thanks to everyone for the comments and suggestions, I'm pretty new to R so this is all very educational.

Previous versions:
symbols(x,sq=x<-50:99,bg=gray(x/99))            #36
x=50:99;symbols(x,sq=x,bg=gray(x/99))           #37
x<-50:99;symbols(x,sq=x,bg=gray(x/99))          #38
x<-1:50;symbols(x,sq=x/x,bg=gray(x/50))         #39
x<-1:50/50;symbols(x,sq=x/x,bg=rgb(x,x,x))      #42
x<-1:50/50;symbols(x,squares=x/x,bg=rgb(x,x,x)) #47

Previous image:

Could save a few more with symbols(x<-50:99,sq=x,bg=gray(x/99))

Minus two! Thanks @MickyT, I thought it was done already.

Whoops, and undo. Doesn't work. You can create in-line variables but you can't reference them in the same line.

Sorry about that ... must of had a object floating around when I tested it.  You can get one more from changing <- to =

@freekvd It does in general, it depends on the order in which the arguments are accessed inside the function (since arguments are lazily evaluated). You can test this by having f = function (a, b) { a; b} and then calling f(x <- 5, x). This works as expected. Once you reverse the arguments in f’s definition (and rm(x)), it doesn’t work any more.

Looks like evaluation starts at sq=x, so I can trim off another char with this. Thanks @KonradRudolph

Cut down by 1 byte symbols(x,,,x<-50:99,bg=gray(x/99))

Java - 180
Pretty straightforward, just drawing boxes.
import java.awt.*;void f(){new Frame(){public void paint(Graphics g){for(int i=1;i<51;g.setColor(new Color(328965*i)),g.fillRect(i%8*20,i++/8*20,20,20))setSize(600,600);}}.show();}

With line breaks:
import java.awt.*;
    void f(){
        new Frame(){
            public void paint(Graphics g){
                for(int i=1;
                    i<51;
                    g.setColor(new Color(328965*i)),
                    g.fillRect(i%8*20,i++/8*20,20,20))
                    setSize(600,600);
            }
        }.show();
    }

If anyone objects to the last box being technically white, just change the color multiplier to 263172. Same byte count, I just think it looks better this way.

I think you could also use int i; instead of int i=1 but then use ++i on the first use of i instead of i++ in the last occurence, would save 2 bytes. BTW: I didn't even know you can make a java program without class MyClass ... public static void main(...!!!

@flawr Nah, Java won't initialize local variables to default values. It might work if I moved it outside the function. If I was giving a full program instead, I'd try it that way (this is just a function, plus the necessary import). Thanks, though :)

Ah I forgot, it was initializing arrays where the default values are set. Sorry=) But still, I always thought you need a class and I am not the only one. Or is this a feature of a newer version?

@flawr If it was a full program then yes, you'd need that. This is just a function, since the question doesn't specify.

You could get rid of most of the overhead by writing it as a Processing sketch. Your program would then just be size(600,600);for(int i=1;i<51;fill(++i/51.))rect(i%8*20,i++/8*20,20,20); (or something thereabouts, anyway)

@AJMansfield I know, but I consider Processing a different language, and I like to golf in Java Java.

You can save 1 character by making your squares 51*51 and making your for loop for(int i=1,t=51;i<t;... and changing all your 20's to t.

You can save 2 characters by changing void f(){ to static{.

I think you could save lots of bytes by just drawing them in a line.

@iKiWiXz I was being friendly to those with <1000px resolution ;)

ipython 2, 54 bytes
The best I could do was with an ipython program. Starting ipython with ipython -pylab and executing this program will show a graph with 50 shades of grey in 50 squares:
t=arange(50);c=t/50.;scatter(t%5,t,500,zip(c,c,c),'s')

Output:

Solution 2:
Here is another program (61 bytes):
imshow(arange(50).reshape(5,10)*.02,'Greys',None,1,'nearest')

that displays the following window:

However note that ipython is not a language and what you used is Python library matplotlib, which is an external lib.

BBC BASIC, 57
FORn=51TO2STEP-1VDU19;-1,n,n,n:RECTANGLEFILL0,0,n*20NEXT

The squares have to be at least 20 pixels but there's nothing to say they have to be the same size, so I guess this qualifies.
It may be possible to shorten this by using more low-level VDU codes. But changing from this pattern to a less interesting one is unlikely to make it shorter.

Remember your BBC Basic abbreviations?  F.,N.,S.,V. ->  F.n=51TO2S.-1V.19;-1,n,n,n:RECTANGLEFILL0,0,n*20N.

@SeanCheshire http://www.bbcbasic.co.uk/bbcwin/bbcwin.html does support those abbreviations, I never thought to check! Your way counts as 50. The tokenised filesize is 41 bytes (each keyword tokenisied to a single byte outside the ASCII range) though I don't often count that way. I will use your tip in future though!

JavaScript (72, 70, 67 bytes)
72: original (borrowing the clever ■ usage from Sphinxxx's answer):

for(i=90;i>40;)document.write('■')

70: stealing shamelessly from Ismael Miguel (who deserves the votes), a shorter for loop and allowing the browser to correct for a lack of # proceeding the colour code...

for(i=60;--i>9;)document.write('■')

67 bytes (65 chars): swapping the entity for the unicode character:

for(i=60;--i>9;)document.write('■')

I think you should start at i=51. If I counted correctly, there are only 49 squares?

Hi, this should be a comment and rather there already exists a similar comment. Thus, this answer is an exact copy of another already existing.

Fair enough. I've attempted to better differentiate - if still too close, I'll delete permanently. Don't have enough rep for commenting, sorry.

I really like your answer! Dear lord, why I didn't though about it? +1 on this one! I would reduce this one to for(i=0;i++<50;)document.write('■') or similar. Untested but it might work!

I like it - unfortunately I think that method generates duplicates when i <= 5, since #555 (etc) is equivalent to #555555. Looping additional times to generate more swatches to give us a unique 50 probably bends the wording of the rules too far, yeah?

On the other hand, your use of for(i=60;--i>9;) as the loop in your JavaScript answer certainly does the trick of producing double-digit values of i (avoiding the duplicates issue) while still only requiring one double-digit number within the for statement... nice. ;)

Since you are stealing from me, at least steal properly. Remove the # character to have a 70-byte long solution.

Great tip (on both the # and the stealing). Actually I'm a little unclear on the etiquette around "incorporating others' brilliance"; always happy to retract an edit, more interested in shorter code than points. At least I finally have enough rep for commenting.

What are the rules around inputting a unicode character directly? For instance, instead of using the entity ■, just directly using ■? A quick search on meta seemed to indicate the question should specify whether scoring characters or bytes (and I'm assuming bytes by default). In any case, the unicode is also shorter in bytes, yes?

I was just about to recommend that. The default is counting bytes, but you should use the Unicode character because it is still fewer bytes.

for(i=50;i--;) = 14 characters and iterates 50 times, like your loop which takes 16 characters. (0 evaluates to false in JS so the loop exits when i hits 0) That should knock off two more bytes for you.

I just realized that my comment won't work. Once i becomes 4 it will output '444' which in HTML is a duplicate color of '444444' which would have been output by the i=44 iteration. So close.

I managed to get caught out by that a few times!

Did the question say exactly 50 squares? :) (The other solutions also draw extra stuff.) With that and the unicode literal, down to 65 bytes (63 chars): for(i=90;i;)document.write('■') - BUT at least on my browser's default settings (OSX/Chrome) the box is a bit smaller than 20x20 pixels anyway, so these ■ based solutions are questionable.

Might have to confer with a code golf lawyer regarding rule 1. ;) Interesting regarding the pixel sizing; Win7/Chrome has it at 21x21 px... of course I'd only previously eyeballed it and am somewhat relieved to be able to confirm it now! I believe on my system it's being rendered as a Times New Roman glyph at font-size 48px.

C++, 98 83 characters
Okay so, you are going to need a terminal emulator that supports true colors. For mac os there are the nightly builds of iTerm2, for example. For unix I believe konsole supports it. Here's a list, just in case: https://gist.github.com/XVilka/8346728#now-supporting-truecolor
Compile with g++ (\e is compiler dependent).
For the squares to have enough area, you will have to change your terminal font size.
#include <cstdio>
int main(){for(int i=51;i--;)printf("\e[48;2;%i;%i;%im ",i,i,i);}

Using C libraries instead of C++ allows for shaving some characters.

C, 61 58 characters
This is the same program but in C, which assumes untyped function declarations to return int, and which doesn't need includes for some of the standard library functions, like in this case, printf. Suggested by @cartographer. Three characters less thanks to @user3601420
main(i){for(i=51;i--;)printf("\e[48;2;%i;%i;%im ",i,i,i);}

Compiles with a couple of warnings (for assuming main's return type to be int and for implicitly including the declaration of printf).

If you switch this to C you can drop the include and the int in front of main and have it compile with just a couple of warnings with gcc.

Yes, but that would be another language. Anyway, I'll append it, thank you!

You can remove a few characters from the C version if you make i the first argument to main, as in: main(i){for(i=51;i--;)printf(...

Only one additional character to make it standard: \e → \33

This is code-golf!

J (43 41 40 38 33 29 characters)
After suggestions from randomra.
1!:2&4'P2 ',":(,*:,],*:#?~)50

This solution does not display anything as the standard library of J does not contain GUI routines. Instead, I generate an image and write it to standard output. The output is randomized, it ensured that all shades are distinct. Here is a some sample output and the image converted to png and rotated by 90° for easier viewing:

Pushing the 50 from the header into the generated part using 50*50 squares saves 1 byte: 1!:2&4'P2 50 2500 ',":(,*:#i.)50.

That's a neat idea.

Even more: push all numbers in 1!:2&4'P2 ',":(,*:,],*:#i.)50 for 29 chars! Btw plot isn't part of the standard J library?

@randomra plot is one of the auxiliary packages you can download from the package manager. I would hardly see it as a part of the standard library.

Piet- 2*103 = 206
This is unique in that the source code and the output fulfill the challenge:

Most of it is decorative, so I only counted the top two rows, which stand alone just fine. Outputs a grayscale ppm like some others have done.

Python 2, 125 115 104 bytes
from turtle import*
shape("square")
bk(500)
ht()
pu()
exec'color((xcor()/2e3+.5,)*3);stamp();fd(21);'*50

Sample output:

Good old turtle. This was the only method I could think of in Python which prints images to a screen using only the standard libraries.
The square turtle shape just happens to be 21 by 21, which is very convenient. This can be seen by digging through turtle.py:
"square" : Shape("polygon", ((10,-10), (10,10), (-10,10), (-10,-10)))

If you have a high res monitor or don't mind a few squares being off-screen, then this is 93 bytes:
from turtle import*
shape("square")
ht()
pu()
exec'color((xcor()/2e3,)*3);stamp();fd(21);'*50

Demo
(This demo uses Skulpt by adapting the snippet found here. It is only included to give an idea as to what the code does — I had to modify a few bits to get it working.)

function out(a){var b=document.getElementById("output");b.innerHTML+=a}function builtinRead(a){if(void 0===Sk.builtinFiles||void 0===Sk.builtinFiles.files[a])throw"File not found: '"+a+"'";return Sk.builtinFiles.files[a]}
$(document).ready(function run(){Sk.canvas="canvas";Sk.configure({output:out,read:builtinRead});try{Sk.importMainWithBody("<stdin>",!1,'import turtle\nt=turtle.Turtle()\nt.speed(9)\nt.shape("square")\n\nt.bk(500)\nt.ht()\nt.pu()\nfor i in range(50):t.color(64+2*i,64+2*i,64+2*i);t.stamp();t.fd(21)')}catch(a){throw Error(a.toString());}})

<canvas height="100" width="1200" id="canvas" style="border:1px solid gray">Your browser does not support HTML5 Canvas!</canvas>

Ah I see how you realised skulpt has updated. Thanks for this, I will probably use it to update the snippet.

Excel vba, 81
In the immediate window:
for i=1 to 9:for j=1 to 9:k=i+j*10:cells(i,j).interior.color=rgb(k,k,k):next:next

on the active sheet:

{81 shades is just as much code as 50}

Well, some people are interpreting the "50" to mean exactly 50. In that case, it's probably one more character to get 50=105 than it is to get 81=99.

@Omar, 0 to 9 and 1 to 5 will produce exactly 50 in the same number of characters.... This also means I can write the sequel too, in the same number of bytes - 0 to 9 twice

Oh, 0 to 9! I thought that for the cells(i,j) you needed i>0 and j>0.

@Omar, damn, you're right. I couldn't use zero

Slightly shorter (61) For i=1 To 50:Cells(i,1).Interior.Color=RGB(i*5,i*5,i*5):Next

you can also condense Next:Next to next j,i

Matlab 35 thanks to sanchises
imshow(int8(ones(20,1)*(0:.05:51)))

Matlab 36
imshow(uint8(ones(20,1)*(0:.05:51)))

Displays 50 squares filled with gray values 1 to 50 and 2 additional rectangles filled with gray value 0 and 51:

Matlab, 45
imshow(uint8(ones(20,1)*floor(1:0.05:50.95)))

You can shave off a whopping 1 byte by using int8 instead of uint8.

sanchises's solution is better!

@Memming It does hinge on some obscure (undocumented?) feature that I only found out by trying it out for the heck of it. Give Steffen credit were it's due :)

@TheBestOne / JaBe: Your answer actually doesn't work since it does not display squares. Steffen uses int8 to round the 1000 or so values to 50 squares.

R, 37 32 characters1:
image(t(1:50),c=gray.colors(50))

However, the display for this looks … meh (image rotated 90° to fit better into text; compressed, original square side length > 20px):

Here’s a nicer version which plots the squares in random order inside a matrix (50 characters):
image(matrix(sample(1:50),10),c=gray.colors(50))

(And yes, the three adjacent squares of seemingly identical colours are actually three different shades of grey.)
1 Yes, another R answer, and not even the shortest (now the shortest for R) – apologies. I was missing a pretty rendering in R.

How did you fix the aspect ratio?

? Basically the same as second version @ 37 image(matrix(1:50,5),c=gray(1:50/51))

@koekenbakker It’s not fixed, I’m manually adjusting the output window. It’s not perfect but the code does produce squares for a given window, and other code here has comparable issues.

JavaScript, 87 90 bytes

for(i=90;i>40;)document.write('
')

This outputs squares to the HTML, because it is really JavaScript's only method of graphical output. Thanks to edc65 for shaving off 3 bytes.

Save 3 bytes: for(i=90;i>40;)document.write('
'). Can't use single digits because grays would not be unique (#111 same color as #111111)

You can use other units. 1cm or 19mm would be better and more widely supported. Without changing your byte count.

PHP, 96 88 74 bytes
Thanks to Ismael Miguel for saving 22 bytes!

for($i=60;--$i>9;)echo"
";

Writes 50
s with 9mm as height and width (which should be bigger than 20px on the majority of screens), stacked on each other, all with a minor difference in shade.
Generated result (the image is zoomed out and 90° rotated):

Javascript (77 71 bytes):
This answer is no longer IE11 based. It works because the browser converts the bad color codes into usable ones (by adding # to the number).
Here is the code:

for(i=59;i-->9;)document.write("
")

Firefox still has the quirk of making circles.
(Small edit: Changed for(i=61;i-->9;) to for(i=59;i-->9;) because it was producing 52 squares)

Old answer:
This is based on my PHP answer, and uses almost the same ways to make the squares:

for(i=51;i--;)document.write("
");

Not the shortest answer, but it's worth adding here.

This solution isn't compatible with Chrome (produces multiple green colors) and Firefox (same result, but produces circles? o.O WTH?)
Since this is code-golf, a solution working with a specific version or a specific software is acceptable.

It might just be me, but running this code snippet produces mostly green and blue circles. I see @MartinBüttner beat me to this comment so it's not just me...

@MrLemon I guess chrome doesn't like RGB -.- But it does work on IE11. Since I'm not trying to make a cross-browser solution, this is acceptable. I will add this to the answer.

@IsmaelMiguel That's alright I guess. But just for clarity, I'm on FF right now. Can confirm it working on IE11 though.

@MrLemon It works on IE11, since I tried at home. I can provide print-screen if required. Firefox makes circles with it. I have no f#$%ing idea how. There is no way to revert it. I was expecting IE to have the quirks, not Firefox.

Firefox seems to put half-circles on the ends of
, probably to make it look more smooth. No clue as to what happens with the colors. Anyway have my +1 for baffling me.

@MrLemon I'm speachless as well. I was quite happy with the final result. I came from home and found that Chrome doesn't like it :/ (and yes, I use IE at home. I must use IE :/ Sad sad life). But thank you for the +1. I will try to "baffle" (?) you again.

@MrLemon I've made a new answer which doesn't produce weird colors on Chrome.

@MartinBüttner I've updated the answer and no longer produces those weird colors.

@MartinBüttner Actually, it was a SyntaxError. I've fixed it. Now it is showing and the byte count is the same.

I am very tempted to downvote for passing on the opportunity to use the "goes to" operator: --i>9 should be i-->9 which is read "as i goes to 9".

@corsiKa What? o.O What are you talking about?

Lol it was a joke. http://stackoverflow.com/questions/1642028/what-is-the-name-of-the-operator

@corsiKa Oh, it makes sense.... I will try to get something to work.

@corsiKa Better on this way?

Hahaha awesome! It was a joke, but haha nice!

Matlab - 33 bytes
surf(meshgrid(1:7)),colormap gray

Despite the verbose commands, the result is still quite compact. It looks a bit better if you replace surf with surface but that costs 3 chars.
If you don't notice the 50th gray square that is because it is a bit bigger than the others!

Use ndgrid! (2 bytes less). And, is each square a different gray?

JavaScript - 70 bytes

for(i=51;i-=1;)document.write('■')

The box size is smaller than 20 pixel

Then you need to adjust your browser's font size ;)

You have to use font:3em a or font-size:3em. I'm downvoting this one due to the size of the boxes. Until you fix.

You can use i-- instead of i-=1.

You can use the  tag. It won't change the code in any way, except ensuring that the text will be black. This isn't a requirement, but it might be a good idea.

@IsmaelMiguel what specification says b must be black? To my knowledge it inherits the font color…

@idmean The  tag usually has a different color. It may be blue with underline in some browsers. The  tag has the default black color. That is the only reason.

PHP (62 60 63 72 71 62  59 bytes):
I've made the shortest I could find:
for($i=59;$i-->9;)echo"
";

This is exactly the same code as my Javascript answer (with 71 bytes).
But SO MUCH shorter!
This have a quirk in Firefox: instead of squares, Firefox makes circles! (Go insanity!)
Othen than that, all the browsers produce the right color (even with the missing # on the color attribute).

Invalid submits and changelog:
Old answer, with 62 bytes.
while($i++<51)echo"
";

All shades are perfectly aligned.
This solution won't work for Chrome (will produce squares with multiple colors) and Firefox (which makes circles o.O Yes, circles with
! Horizontal ruler is a circle on Firefox!).
You can test it on IE11 and it should be fine.

(simply removed from above)
I've noticed something awful: It was outputting #111 instead of #010101 for some colors.
This meant that some colors were repeating.
Therefore, I had to sacrifice a few bytes:
<?while(f>$c=dechex(65-$i++))echo"
";

Outputs the 50 shades in perfect order, from lighter to darker.
Due to a correct point made by @edc65, I had to add width=20, to produce perfect squares.
Reduced one more byte by replacing f!=$c with f>$c, which works perfectly.

Final version, without width=20:
<?while(f!=$c=dechex(65-$i++))echo"
";

This is invalid because it is required to output squares.
This outputs the shades from lighter to darker.

Reduced 1 byte by switching to a while loop, like this:
<?while($c=dechex(50-$i++))echo"
";

First solution:
<?for($i=50;$c=dechex($i--);)echo"
";

This doesn't have the shades neatly ordered, but there are 50 different ones.
There is nothing stating that they must be ordered, but there is a requirement on size.
I hope I can reduce it a lot more.
You can test it on http://writecodeonline.com/php/ (click on "Display as HTML").

Processing, 66 characters:
size(1000,20);for(int i=0;i<981;i+=20){fill(i/4);rect(i,0,20,20);}

PostScript, 34 bytes
In ISO-Latin-1 encoding:
20’›‡üˆì0{’81e3’6’–10’k0ˆ                   (note, this is a Line Feed)
’c’§}’H

This is the binary equivalent to:
20 setlinewidth 1020 -20 0 { dup 1e3 div setgray 10 moveto 0 10 lineto stroke } for

(This assumes that you are using it on a device that is at least 1000 points [= 10 inches = 25.4 cm] wide.)

Give us a series of hex encoded octets (ie: 0f 4e 75 a3 ...).

@haneefmubarak I will, I just need to get home so I can use my golfer program. (The online postscript compactor doesn't ever seem to work.)

@haneefmubarak OK, updated with a direct representation of the file, although its not the hex octets. (I'll add that later once I can use the real converter program.)

A bit shorter: 1020 -20 0{dup 1e3 div setgray 10 20 20 rectfill}for which compresses down to 27 bytes (87fc0388ec307b923831653392369296880a8814323092807d9248 according to xxd -ps).

CSS (87 chars)
Uses animation ;)
:after{content:'\25A0';font:9em z;animation:g 8s steps(50)}@keyframes g{to{color:#fff}}

The runnable version is longer since Webkit still needs the vendor prefix. :(

:after{content:'\25A0';font:9em z;-webkit-animation:g 8s steps(50);animation:g 8s steps(50)}@-webkit-keyframes g{to{color:#fff}}@keyframes g{to{color:#fff}}

If we're allowed a random, empty  element, we can get it down to just 72 characters:
a{padding:3em;animation:g 8s steps(50)}@keyframes g{to{background:#000}}

See? CSS is a legit programming language!

R, 36 bytes
I can make freekvd's answer shorter trivially.
x=9:59/59;symbols(x,sq=x,bg=gray(x))

(Sorry for not making a comment under his solution. Stackexchange does not allow me to make comments, vote etc yet).

Doesn't this produce 51 squares?

This makes the smallest square less than 20 pixels wide? It depends on your dpi, but the largest square is 1 inch so a 72 dpi image will have a smalllest square of 11 pixels.

Though if you make it 1:99 you could argue that the 50 largest squares meet the criteria.

C# - 173
Using LINQPAD
var b=new Bitmap(1000,20);var g=Graphics.FromImage(b);for(int i=0;i<50;i++)g.FillRectangle(new SolidBrush(Color.FromArgb(i*5,i*5,i*5)),new Rectangle(i*20,0,20,20));b.Dump();

Expanded:
var b = new Bitmap(1000, 20);
var g = Graphics.FromImage(b);
for (int i = 0; i < 50; i++)
    g.FillRectangle(new SolidBrush(Color.FromArgb(i * 5, i * 5, i * 5)), new Rectangle(i * 20, 0, 20, 20));
b.Dump();

Output:

Suggestion: for(int i=0;i<250;i+=5) and then FromArgb(i,i,i) and Rectangle(i*4,0,20,20) gives 168

Furthermore, FillRectangle() has an overload which takes the rectangle coordinates directly, so you can remove the new Rectangle() and get away with 153

DrRacket - 83
Just for the sake of firing up DrRacket 1 year after "Introduction to Systematic Program Design".
EDIT:
(require htdp/image)(map(λ(i)(rectangle 50 50'solid(make-color i i i)))(range 50))

Save a couple of characters: switch from 2htdp/image to htdp/image, change the string "solid" to the symbol 'solid. For bigger savings, change the (range 9 209 4) to (range 50): the shades of grey are just required to be distinct, not easy to tell apart for the human eye!

You can save a few characters using for/set: (require htdp/image)(for/set([i 50])(rectangle 50 50'solid(make-color i i i)))

   JavaScript, 152 bytes.
Okay, so maybe this isn't the best solution but here is mine.
function b(a){c=document
e=c.createElement('p')
with(e.style){background="rgb("+[a,a,a]+")"
width=height="20px"}c.body.appendChild(e)
a<245&&b(a+5)}b(0)

Here is the output with css float left (just so it is easier to count the squares) and without:

You can save some bytes by using one-letter variable names, dropping all var keywords and removing unnecessary whitespace. Also, please include the language name and the byte count in your answer.

Thanks for the input. I reduced white space and added byte count but I'm not sure what you mean by dropping the var keywords.

Never mind. I feel dumb.

Use c+=5 instead of c=c+5. Also, you can save 2 chars by putting n=c.toString() at the end of the previous line, and then that line at the end of the previous line again. So your 2nd line would be function w(){if(c<250){n=c.toString()

Also, I'm pretty sure you can omit px for the height and width.

I've cut it down to 173 for you :) http://jsfiddle.net/87ofo7zx/

@eric_lagergren I've reduced it by 1 byte: http://jsfiddle.net/87ofo7zx/1/. And again, reduced to 169: http://jsfiddle.net/87ofo7zx/2/. And now to 166 bytes: http://jsfiddle.net/87ofo7zx/3/

@eric_lagergren Reduced once more to 162: http://jsfiddle.net/87ofo7zx/4/. And now again to 155: http://jsfiddle.net/87ofo7zx/5/

@eric_lagergren Sorry the spam, here is another one with 153 bytes: http://jsfiddle.net/87ofo7zx/6/ And 151: http://jsfiddle.net/87ofo7zx/7/

@Ismael Miguel awesome! Updated the post.

You're wellcome. I can try to see where I can reduce it a tiny bit more.

R 45 42 characters
New version, after some comments (thanks!):
plot(1:50%%5,col=gray(1:50/60),ce=5,pc=15)

Old version
It generates an error, but works fine :)
plot(x<-1:50,x%%5,col=gray(x/60),lw=30,pc=22)

Those are not squares though, they’re circles.

Better now? :))

,ce=3,pc=15 gives real squares and saves a character

You can shorten it further by replacing x<-1:50,x%%5 with 1:50%%5 and gray(x/60) with gray(1:50/60).  Also, it seems to work with co instead of col.

C++ Win32: 141 chars and 171 chars
C++ 171 chars

#include"stdafx.h"#include<windows.h>int _tmain(){HDC h=GetDC(0);for(int i=0;i<50;i++){SelectObject(h,CreatePen(0,9,RGB(64+i,64+i,64)));Rectangle(h,i*9,i*9,i*9+9,i*9+9);}}

This draws 50 grey boxes to your desktop.
Which is super long, but pretty good for actually drawing squares in C++. I doesn't think I was ever going to win/not-come-last but I'm pretty satisfied with this. I can't guarantee the whole pixel thing as I use coordinates, but IWOMM :D.
I don't know if win32 counts as a standard library of c++, but I was more interested in the win32 than the c++ tbh. I had a crack at GDI, which look prettier but is super verbose. I was hoping I could get a win32 ColorChooser and turn them all grey for instant victory, but alas no.
Here's the idea (I've removed the resource leak from this extended version):
#include "stdafx.h"
#include <windows.h>
int _tmain(int a, _TCHAR* b[])
{
   HDC h=GetWindowDC(GetDesktopWindow()); //Zero works for GetDesktopWindow() as  Konrad Rudolph points out. GetDC is a good as GetWindowDC.
   for (int i = 0; i < 50; i++){
       HPEN p = CreatePen(PS_COSMETIC, 9, RGB(64 + i, 64 + i, 64)); //PS_COSMETIC is 0
       SelectObject(h, p); MoveToEx(h, 0, 0, NULL); //We can get away with removing MoveToEx and assuming it starts in the top left
       Rectangle(h, i * 9, i * 9, i * 9 + 9, i * 9 + 9); DeleteObject(p);
   }
   DeleteDC(h); //Or was it releaseDC? Who cares. The golf'd code leaks it anyway.
}

Also this can happen. When you want to get rid of it you just 'wipe' it away with another window. You would also not believe how slow this is to execute.

Konrad Rudolph's comment: C++ 141
// stdafx.h isn’t needed.
// However, we DO need the line break after the include,
// even in the golf version.
#include <windows.h>
// _tmain => main; VC++ accepts both.
int main()
{
   HDC h = GetDC(0);
  // Remove i++ here …
  for (int i = 0; i < 50;){
  // 65793 == 0x010101; multiplying with 1…50 generates
  // grey tones and is much shorter than RGB macro use
  SelectObject(h, CreatePen(0, 9, i*65793));
  // i * 9 + 9 == i * 10
  // … add i++ here.
  Rectangle(h, i * 9, i * 9, i * 10, i++ * 10);
  }
}

short.cpp
#include <windows.h>
int main(){HDC h=GetDC(0);for(int i=0;i<50;){SelectObject(h,CreatePen(0,9,i*65793));Rectangle(h,i*9,i*9,i*10,i++*10);}}
//141 with the line break

I vaguely remember that it sometimes worked to use 0 instead of the Desktop DC (or was it the hWND?). However, that’s definitely not kosher and it might not work any more (it never worked reliably, as far as I remember).

@KonradRudolph Good trick. Apparently in WinUser.h it defines: #define HWND_DESKTOP ((HWND)0) and MapWindowPoints doco seems to suggest HWND_DESKTOP and NULL are both kosher. However, obviously outside of golfing using 0 would be horrible. Also, I've just noticed GetDCis just as good as GetWindowDC

You can make this much shorter actually. Since it’s too much for a comment, I’ve created a gist with the changes: https://gist.github.com/klmr/864a87d25c048736a11f – Result: 140 characters. There’s probably more room for improvement if you accept different colours/positions, by choosing colours and positions so that fewer computations are necessary. But then, according to the rules the squares probably shouldn’t overlap and be larger.

Okay. Wow. (You could tweet that now). Good stuff, thanks for the link. Thinking back, I should have seen that having macros probably means that the code isn't effectively golfed. I hope you don't mind if I add an attributed section.

Pyth - 23 21 bytes
Is similar to CJam solution. Outputs is PGM format, save output as foo.pgm and view here. Edited it to make it conform to PGM specs so that lines are less than 70 chars long, in fact they are only one pixel long.
K50"P2"*KKKKVKjbS*UKK

Generates:
Is fifty fifty by fifty squares. Goes from black to 49/50 of the way to white.
K50             K=50
"P2"            Prints P2 or pgm header magic #
*KK             Prints the length: 50*50
K               Prints width: 50
K               Prints value of white: 50
V         K     Do 50 times to make height of square 50
 j              joins by
  b             linebreaks
   S            Sort to bring out make each shade consecutive
    *  K        Times 50 to make length 50
     UK         Unary range 50 (0-49)

So you include black as a shade of grey?

@aditsu is that not allowed? The only reason I didn't include white was because range(50) only goes up to 49.

I'm not sure, but I excluded it. Otherwise I can also get 21 bytes. I guess I should ask...

@aditsu yeah it takes me 22 to get not black, replace UK with R1K

R - 35 characters
Barplot uses gray.colors by default, helpful to save some bytes. To make sure the size is sufficient regardless of the screen size, the window size has to be defined beforehand, with x and y size picked as to generate a 1:1 aspect ratio.
x11(,1.7,23);barplot(matrix(1,50))

Output, rotated 90° and sized down:

As per comments below, the x11() results vary between machines. Hence, a safer option - also forcing aspect ratio of 1 - is dev.new. Run from terminal:
dev.new(height=20);barplot(matrix(1,50),as=1)

That's 46 characters. If manual resizing is allowed, barplot(matrix(1,50),as=1) is enough - only 27 characters.

The x11 doesn’t actually yield reliable results. On my OS X the code doesn’t produce squares anyway. Just remove it. As far as I’m concerned, barplot(matrix(1,50)) is the shortest valid R code so far. 21 characters. It’s just a shame that rep(1,50) doesn’t work in place of matrix; t(t(rep(1,50)) does, but it’s longer.

You're right. Worked fine on my Linux machine, but not so on Windows. Added an alternative avoiding this.

xcode-select: note: no developer tools were found at '/Applications/Xcode.app', requesting install. Choose an option in the dialog to download the command line developer tools. Error in x11(h = 20) : X11 module cannot be loaded. I can't use this on OSX :(

I have provided a longer alternative, hope that works across platform

HTML/CSS - 81 characters
This is a very borderline solution because the shades aren't displayed very accurately (Chrome and Firefox both just use dithering), but in theory it "should" display 50 distinct shades. Also, the code is probably not very W3C compliant, but it compiles on any browser that knows CSS3.

Note that 0x30 is 50 and 1000 is 50*20.

C (73 65 characters)
Outputs a binary PGM to stdout, 20x20 squares.
s;main(){puts("P5 1000 20 50");while(s<2e4)putchar(s++%1000/20);}

Moar tricks would have been possible with 2^n instead of 50 shades, but nevermind.

CoffeeScript, 86 bytes
As per edc56's comment on the JavaScript solution:
i=90;document.write '
'while i>40

Python 2, 78 characters
This prints an image in PGM format to standard output (I took the idea from aditsu's CJam answer):
print"P2 2500 50 51"
r=range(50)
for x in r:
 for y in r:
  for z in r:print y

I wish Python would let me put all 3 fors on the same line. At least it lets me use a single space (or single tab) for each indentation level. I tried using variants of for t in itertools.product(r,r,r) instead, but the import is long and kills the benefit.

Thanks, @KSFT! I forgot my editor adds (and counts) a final newline automatically.

you can save a byte trivially by indenting your last line with one tab instead of two spaces

Mathematica, 20 characters
ArrayPlot@{Range@50}

gives the following output:

I deliberately did not post this, because you need to scale up the result manually in order to make the squares 20 pixels on a side. The default size is much smaller than that.

This is a good point...

Isn't that the same as ArrayPlot[Range@50], which is one character shorter?

@Omar No, ArrayPlot needs a 2-dim array. In your case it is 1-dim.

Oh, sorry, I misread the first @ as @@. Ignore my comment.

Haskell 133
import Data.List
r=replicate 20
f 0=""
f i=(f(i-1))++(concat$r$'\n':(intercalate " "$r$show i))
main=putStr $"P2\n20 1000\n50"++f 50

outputs in Netpbm Format to stdout

FFmpeg, 61 bytes
ffplay -f lavfi color=s=1000x20,format=y8,geq=8+4*trunc(X/20)

Javascript (60 char)

for(i=51;i--;)document.write("
")

These don't look very square to me. (in Chrome)

@MartinBüttner There are definitely squares. There are just also round parts. There's no rule against extra output.

@KSFT I see rectangles.

Okay, there are rectangles, too. There are still squares, just with long rectangles and round things on the ends. Do you see something like this? http://imgur.com/faT4CD4 I see squares in these places: http://imgur.com/ZD7hxHe

@KSFT I think this falls under this standard loophole. The question asks for 50 squares, not for squares embedded in arbitrary shapes.

@MartinBüttner If extra output weren't allowed, then a lot of other answers would be disqualified.

@KSFT I didn't say they shouldn't be. But still, IMHO, just printing arbitrary shapes and saying there's a square in there is a lot more cheating than printing 50 squares, and also plotting axes or something like that.

@MartinBüttner I disagree. It's just extra output, and fifty different shades are still being drawn.

Python, 72 bytes
print'P2 1000 20 50 '+20*(''.join([20*(str(x)+' ')for x in range(50)]))

Another PPM answer, usage:
python golf_grey.py > grey.ppm

Excel VBA, 60 Bytes
Anonymous VBE immediate window function that takes no input and outputs to the range [A1:A50] on the ActiveSheet object
For i=1To 50:j=5*i:Cells(i,1).Interior.Color=RGB(j,j,j):Next

Perl 5 + -M5.10.0, 39 bytes
Outputs PGM format.
say"P5 20 1000 50 ",map chr()x400,0..49
Try it online!

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


text:
Extract URI parts without using libraries
Given a URI like:
postgres://username:password@hostname:PORT/dbname

Extract it all into an array data-structure, like so:
['postgres', 'username', 'password', 'hostname', 'PORT', 'dbname']

More info: http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
Rules

No use of external libraries or web-services

Scoring

Your score will be the number of bytes in your code (whitespace not included) multiplied by your bonus. Initial bonus is 1.0.
Concision is king (codegolf!)
Use of regular expressions will increase your bonus by 0.50
Use of internal libraries (that need explicit importing) will increase your bonus by 0.50
Extra -0.8 bonus for getting query string also

"No use of internal/external libraries which need importing" - why? This basically prevents Java from participating. Also, we need a better spec. Which parts need to be extracted? How about the query string of HTTP URIs?

What is defined by internal library here ?

Clarified my question

x2 penalty to Java is brutal. As if import java.util.* wasn't penalty enough.

Okay @Optimizer, updated

Please use the sandbox next time...

One example does not make a spec. You should at the very least specify how the output should vary with the following variations to the input: no scheme name; no username and password; no port; no path; multi-segment path; containing query string; containing fragment; containing both; pure relative URI (i.e. no scheme or authority). Test cases for protocols with different numbers of slashes (e.g. file:/// and urn:) should also be included.

Whitespace not included...are you banning Whitespace or giving Whitespace a 0 byte count?

CJam, 15 bytes * 0.8 = 12
l":@?#"'/er'/%p

Reads the uri via STDIN. Updated to parse query string and fragments too.
Code explanation:
l                    "Read a line from STDIN";
 ":@?#"              "Put this string on stack";
       '/er          "Replace all occurrences of characters in above string by /";
           '/%       "Split on runs of /";
              p      "Print the array";

Try it online here

Maybe you can go for the query string bonus

APL, 24
 {⍵⊂⍨⍵∊⎕AV[∊65 17+¨⊂⍳26]}

Example:
 ]display {⍵⊂⍨⍵∊⎕AV[∊65 17+¨⊂⍳26]}'postgres://username:password@hostname:PORT/dbname'
┌→────────────────────────────────────────────────────────────┐
│ ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→───┐ ┌→─────┐ │
│ │postgres│ │username│ │password│ │hostname│ │PORT│ │dbname│ │
│ └────────┘ └────────┘ └────────┘ └────────┘ └────┘ └──────┘ │
└∊────────────────────────────────────────────────────────────┘

Note: ⎕ML variable must be set to 3 in Dyalog APL

Ruby, 43
%w[:// : @ /].map{|t|u.gsub! t,' '}
u.split

Since the OP doesn't specify how to take input and produce output, I'm assuming the URI is located in u as a String. There is no output; u.split returns an Array in the correct format (["postgres", "username", "password", "hostname", "PORT", "dbname"]).
The code itself is simple. Replace "://", ":", "@" and "/" with a space, then split on whitespace.

Python (characters: 207, score: 240)
reduce(list.__add__,reduce(list.__add__,map(lambda e: map(lambda i: i.split('/'),e),map(lambda j: j.split(':'),(lambda e:e[e.find('/')+2:].split('@'))('postgres://username:password@hostname:PORT/dbname')))))

Expanded out
reduce(list.__add__,
       reduce(list.__add__,
              map(lambda e: map(lambda i: i.split('/'), e),
                  map(lambda elem: elem.split(':'),
                      (lambda e: e[e.find('//') + 2:].split('@'))(
                          'postgres://username:password@hostname:PORT/dbname'
                      )
                  )
              )
       )
)

Note: in real-cases use from operator import add

It looks like you've written some Haskell in Python!

By the way, Python has int.__add__. Also, it looks like your code is a snippet rather than a program or function, as it expect the variable url to be pre-initialized with the input. This is not allowed by default for code golf, so if you intend it to be allowed, you should say so in the spec.

"It looks like you've written some Haskell in Python!" :P - Yeah, good find; using list.__add__ now.

This doesn't take input or do output.

I never said it had to? - Replace my constant with a variable or stdin call if you like, and throw a print statement in. Not needed though.


text:
Generate Lucky Numbers
Story:
Lucy asked George what his Lucky Number was. After some contemplation, George replied that he had several Lucky Numbers. After some brief confusion, Lucy asked George what his first n Lucky Numbers are. George then asked you, his buddy, to write him a program to do the work for him.
The Challenge:
You will write a program/function that will receive from standard input/function argument a string or integer n. The program/function will then return/output the first n Lucky Numbers. Lucky numbers are defined via a sieve as follows.
Start with the positive integers:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, ...

Now remove every second number:
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, ...

The second remaining number is 3, so remove every third number:
1, 3, 7, 9, 13, 15, 19, 21, 25, ...

Now the next remaining number is 7, so remove every seventh number:
1, 3, 7, 9, 13, 15, 21, 25, ...

Next, remove every ninth number and so on. The resulting sequence are the lucky numbers.
Winning:
As usual for codegolf, fewest bytes wins.
As usual, submissions using standard loopholes are disqualified.

I'd suggest including the definition in the post as well as the first ten or so numbers.

A cool extension would be that for each item examined (3, 7, etc.) will do that operation that number of times. For example for 3, remove the third element in the list 3 times, the 7th element 7 times, etc. (note this is not the sequence but the idea is the same)

@Ryan I think that sequence would be remarkably similar to the natural numbers :)

@TheBestOne You think so? I posted earlier to math.stackexchange: https://math.stackexchange.com/questions/1153889/characterization-of-extended-lucky-numbers

@Ryan Actually, I misinterpreted your suggestion. As you stated it in your question on math.se, I think that would be interesting.

Python 2, 79
n=input()
L=range(1,2**n)
for r in L:r+=r<2;map(L.remove,L[r-1::r])
print L[:n]

The magic of iterating over a list as the loop modifies it!
The list L starts with all the integers 1 to a sufficiently high value. The code iterates over each element r of L, taking the sublist of every r'th element, and removing each of those values. As a result, the removed values aren't iterated over. At the end, print the first n elements.
The expression map(A.remove,B) is a trick I've been waiting a long time to use. It calls A.remove for each element of B, which causes all the elements of B to removed from A. Effectively, it takes the list difference, though it requires B to be a sublist of A. It requires Python 2, since Python 3 wouldn't actually evaluate the map.
The first loop needs to be special-cased to convert r from 1 to 2, as r+=r<2.
The sufficiently high upper bound of 2**n makes the program very slow for large values of n. Using n*n+1 suffices, but costs a character. Note that n*n doesn't work for n=1.

You just need n**2 numbers, not 2**n

That's one amazing use of map you have there. I was wondering whether there was a better way...

@Optimizer Unfortunately, n**2+1, unless the case n=1 can be forgiven.

That use of map is brilliant. Like using an ordered set. Perhaps also can be used like map(A.index,B) to find the indexes of the elements of B in A, map(A.count,B) to find the number of the elements of B in A, map(A.extend,B) to add a flattened B list to A. The mind boggles.

Haskell, 71 69 bytes
s(n:k)p=n:s[m|(i,m)<-zip[p..]k,i`mod`n>0](p+1)
f n=take n$1:s[3,5..]3

Defines a function f. The expression 1:s[3,5..]3 evaluates to the infinite list of lucky numbers, and f simply takes the first n of them by take n.
f 20
[1,3,7,9,13,15,21,25,31,33,37,43,49,51,63,67,69,73,75,79]

I could shave off 5 bytes from the sieve using a parallel list comprehension
s(n:k)p=n:s[m|m<-k|i<-[p..],i`mod`n>0](p+1)

but that would require passing the humongous compiler flag -XParallelListComp to GHC to enable the extension.
Explanation of the sieve
s(n:k)p=               -- Sieving a list with head n and tail k with accumulator p is
 n:                    -- the head n, followed by
  s[m|                 -- the result of sieving the list of numbers m
    (i,m)<-zip[p..]k,  -- where (i,m) is drawn from [(p,k_0),(p+1,k_1),(p+2,k_2),..] and
    i`mod`n>0]         -- i does not divide n,
   (p+1)               -- using p+1 as the accumulator

The basic idea is that s(n:k)p produces the (p-1)th lucky number n, drops every nth number from the infinite tail k (offset by p to account for the numbers produced earlier), and recurses to that list with accumulator (p+1). In f, we initialize the process with the odd numbers starting from 3, and tack 1 to the front, obtaining exactly the lucky numbers.

Sorry, but is the input n$1? Cuz running running say f n=take 10:s[3,5..]3 doesnt work :/

@DialFrost The code snippet defines a function f that you can call like f 10. Try it online!

Ya lol, but I wanted it to be shorter? So theres no  other way?

Python 2, 71 69 67
At first, I thought this would be a great challenge for Python's array slicing. However, I encountered a stumbling block when I discovered that slices with a step other than 1 can only have another slice of identical length assigned to them. But after googling "python remove slice", my faith was restored: I found a funky del statement that does the trick perfectly.
n=input()
l=range(n*n+9)
for v in l:del l[v&~1::v or 2]
print l[:n]

Old version
n=input()
l=range(1,n*n+9)
for v in l:del l[v-1%v::v+1/v]
print l[:n]

-2 bytes thanks to Sp3000.

CJam - 25
Lri{1$W%{1$\(1e>/+}/)+}/p

Try it online
Explanation:
This implementation doesn't remove numbers successively from an array, but calculates each number based on how many would have been removed before it.
For each index i (from 0 to n-1) and each previous lucky number l, in reverse order, we increment i by i/(l-1), except for l=1 we use 1 instead of 0, and also add 1 at the end.
E.g. for i=4 we have the first 4 numbers, [1 3 7 9], and calculate:
4 + 4/(9-1) = 4
4 + 4/(7-1) = 4
4 + 4/(3-1) = 6
6 + 6/1 = 12
12 + 1 = 13
L              empty array - the first 0 lucky numbers :)
ri             read and convert to integer (n)
{…}/           for each number (i) from 0 to n-1
    1$         copy the previous array
    W%         reverse the order
    {…}/       for each array element (l)
        1$     copy i
        \(     swap with l and decrement l
        1e>    use 1 if l=1
        /+     divide and add to i
    )+         increment and add the new lucky number to the array
p              pretty print

><>, 121 114 111 bytes
i2+:&:*1\
:})?v:2+>l{
nao2\r~1
)?vv>1+:&:&=?;:[{::nao}]$}l1-[01+}:l3-$%$l1-@@-{$[{~l1
3.\ ff+
!?:<]-1v
~]{43. >

I have only a few words to say...
... "Argh my brain hurts."

Explanation
><> is a 2D esoteric programming language and is definitely not suited for this task, due to its lack of arrays. In fact, the only data type in ><> is strange mix of int/float/char, and everything happens on a stack of stacks.
Here's the rundown:
Line 1:            i2+:&:*1\

i2+:&              Read a char as input (n) and add 2, copying n+2 into the register
:*                 Duplicate and multiply, giving (n+2)^2 on the stack
1\                 Push 1 and go to the next line

Line 2:            >l{:})?v:2+

l{:})?v            Go to the next line if the stack's length is greater than (n+2)^2
:2+                Otherwise duplicate the top of the stack and add 2 to it

Line 3:            \r~1nao2

r~                 Reverse the stack and pop; stack contains the first (n+2)^2 odd integers
1nao               Print 1 (special case)
2\                 Push 2 (let's call this "i" for "iterations") and go to the next line

Line 4:            >1+:&:&=?;:[{::nao}]$}l1-[01+}:l3-$%$l1-@@-{$[{~l1)?vv

1+                 Increment i
:&:&=?;            If i is equal to n+2 (+2 because we started at 2), halt
:[{::nao}]$}       Print the i-th element down (the next lucky number) and also
                   copy it to the top of the stack, while moving i to the bottom
l1-[               Move everything but i to a new stack
0                  Push 0 (let's call this "r" for recursion depth)

Sieve loop:

1+                 Increment r
}:l3-$%$l1-@@-{$[  Move everything up to the last element to be sieved out to a new stack
{~                 Remove said last element
1)?vv              If the length is 1, go to line 6 (sieving complete)
                   Otherwise go to line 5, which repeats this sieve loop by teleporting

Line 6:            :?!v1-]

:?!v1-]            Keep unrolling and decrementing r until r is 0

Line 7:            >~]{43.

~]                 Pop r and unroll once more (to the stack where i waits)
43.                Loop, performing everything from line 4 all over again

Here's a mock example which demonstrates roughly how the sieving works (here k is the lucky number which we sieve with):
[[15 13 11 9 7 5 3 1 k=3 r=0]]     -- move -->
[[15 13] [11 9 7 5 3 1 k=3 r=1]]   -- pop  -->
[[15 13] [9 7 5 3 1 k=3 r=1]]      -- move -->
[[15 13] [9 7] [5 3 1 k=3 r=2]]    -- pop  -->
[[15 13] [9 7] [3 1 k=3 r=2]]      -- move -->
[[15 13] [9 7] [3 1] [k=3 r=3]]    -- pop  -->
[[15 13] [9 7] [3 1] [r=3]]        (now we unroll)

Still better than Java ;)

I like the fact that nao can apparently be interpreted as "print this thing now".

Pyth: 23 22 bytes
<u-G%@GhH+0GQ%2r1^hQ2Q

Try it online: Pyth Compiler/Executor
Explanation:
<u-G%@GhH+0GQ%2r1^hQ2Q    Q = input()
             %2r1^hQ2     create the list [1, 2, ..., (Q+1)^2-1][::2]
 u          Q%2r1^hQ2     G = [1, 2, ..., (Q+1)^2-1][::2]
                           modify G for each H in [0, 1, 2, ..., Q]:
  -G%:GhH+0G                  G = G - ([0] + G)[::G[H+1]]
                               (minus is remove in Pyth)
<                    Q    print the first Q elements of the resulting list

The reduce actually calculates more than Q lucky numbers (the remove command is called Q+1 times, Q-1 should be enough).

R, 58 bytes
n=scan();s=r=1:n^2;for(j in 1:n)r=r[-max(2,r[j])*s];r[1:n]

With line breaks:
n=scan()              #user input
s=r=1:n^2             #declare r and s simultaneously, both large enough to sieve
for(j in 1:n)
  r=r[-max(2,r[j])*s] #iteratively remove elements by position in vector
r[1:n]                #print

Previous version, 62 bytes
function(n){
  s=r=1:n^2             #declare r and s simultaneously, both large enough to sieve
  for(j in 1:n)
    r=r[-max(2,r[j])*s] #iteratively remove elements by position in vector
  r[1:n]                #print
}

Previous version, 78 bytes
n=as.numeric(readline())   #ask for user input and convert it to numeric
r=1:n^2                    #create a large enough vector to sieve
for(j in 1:n){             #loop
  r=r[-max(2,r[j])*1:n^2]  #iteratively remove elements by position in vector
}
r[1:n]                     #print

64 bytes: Change n=as.numeric(readline()) to function(n){...}. This creates a function object that can be assigned and called. Drop the curly braces in the for loop.

Thanks @Alex! Though that's 66, since it needs a name?

It doesn't need a name for the submission. See the Matlab/Octave solutions. R function objects are akin to unnamed/lambda functions in other languages, which are valid submissions.

What about n=scan(n=1)?

That works! And it's 1 character less. It's even shorter if I'd drop the n=1, the function ignores all elements of n after the first.

Python 2, 105 101 bytes
n=input()
L=range(-1,n*n+9,2)
i=2
while L[i:]:L=sorted(set(L)-set(L[L[i]::L[i]]));i+=1
print L[1:n+1]

Just a straightforward implementation.
Pyth, 39 36 35 32 bytes
J%2r1h^Q2VJI>JhN=J-J%@JhN+2J;<JQ

Similar to the approach above, but things are 0-indexed rather than 1-indexed. Try it online.
Thanks to @Jakube for pointing out a byte saving.

CJam, 32 30 bytes
3ri:N#,N{0\__I1e>)=%-+}fI(;N<p

Takes input from STDIN.
Code explanation:
3ri:N#,                          "Read the input in N and get first 3^N whole numbers";
       N{0\__I1e>)=%-+}fI        "Run the code block N times, storing index in I";
         0\__                    "Put 0 before the array and take 2 copies";
             I1e>)=              "Take min(2, I + 1) th index from the copy";
                   %             "Take every array[ min (2, I + 1)] element from the array";
                    -+           "Remove it from the list and prepend 0 to the list";
                         (;N<p   "Print number index 1 to N";

Try it online here

Perl, 86 81 78
86:
@a=(1..($k=<>)**2);for$n(@a){$i=1;@a=map{$i++%($n+($n<2))?$_:()}@a;$k-=$k&&print"$n "}

UPDATE: obviously, grep{...} is better than map{...?$_:()}
81:
@a=(1..($k=<>)**2);for$n(@a){$i=1;@a=grep{$i++%($n+($n<2))}@a;$k-=$k&&print"$n "}

UPDATE: OK, actually a one-liner now. I can stop. (?)
78:
@a=(1..($k=<>)**2);for$n(@a){$k-=$i=$k&&print"$n ";@a=grep{$i++%($n+=$n<2)}@a}

Mathematica, 80 bytes
(For[l=Range[#^2];i=1,(m=l[[i++]]~Max~2)<=Length@l,l=l~Drop~{m,-1,m}];l[[;;#]])&

Straight-forward implementation of the definition. As some other answers, starts with a range from 1 to n2 and then keeps filtering.

JavaScript (ES6) 96 99
Edit Counting down in first loop - thanks @DocMax
F=n=>(i=>{
  for(o=[1];--i;)o[i]=i-~i;
  for(;++i<n;)o=o.filter((x,j)=>++j%o[i]);
})(n*n)||o.slice(0,n)

Ungolfed
F=n=>{
  for (i = n*n, o = [1]; --i;)
    o[i] = i+i+1;
  for (; ++i < n; )
    o = o.filter((x, j) => (j+1) % o[i])
  return o.slice(0,n)
}

Test In Firefox / FireBug console
F(57)

Output
[1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 49, 51, 63, 67, 69, 73, 75, 79, 87, 93, 99, 105, 111, 115, 127, 129, 133, 135, 141, 151, 159, 163, 169, 171, 189, 193, 195, 201, 205, 211, 219, 223, 231, 235, 237, 241, 259, 261, 267, 273, 283, 285, 289, 297, 303]

You can save 1 by counting down with the first loop and up with the second: F=n=>{for(o=[1],i=n*n;--i;)o[i]=2*i+1;for(;++i<n;o=o.filter((x,j)=>++j%o[i]));return o.slice(0,n)}

Your ungolfed doesn't really help here :P ;)

@Optimizer ungolfed updated - maybe still not of much help, but at least working now

I meant more on lines on "simply a formatting change won't help, please provide comments :)"

J, 60 52 bytes
   ({.}.@((>:@{.,]#~0<({~{.)|i.@#)@]^:[2,1+2*i.@*:@>:)) 8
1 3 7 9 13 15 21 25

Explanation (from right to left):
2,1+2*i.@*:@>:  generates the list 2 1 3 5 7 9... with (n+1)^2 odd numbers
^:[             repeats n times the following
@]                using the list
0<({~{.)|i.@#     is the remainder of the indexes of the lists elements with the first element positive (i.e. index divisible by first element)
]#~               keep those elements from the list
>:@{.,            concatenate a first element with the value of the current one +1
}.@             drop first element
{.              take the first n element

2,1+2*i.@*:@>: seems way too long but I can only shorten it by 1 byte swapping *: with ! making the list grow exponentially.

Octave, 139 83 72
function r=l(n)r=1:2:n^2;for(i=2:n)h=r(i);r(h:h:end)=[];end;r=r(1:n);end

Ungolfed:
function r=l(n)
  r=1:2:n^2;
  for(i=2:n)
    h=r(i);
    r(h:h:end)=[];
  end
r=r(1:n);  # reduce it to only N lucky numbers
end

Matlab, 104 bytes
function x=f(n)
k=1;N=n;x=0;while nnz(x)<n
x=1:N;m=1;while m-nnz(x)
m=x(x>m);x(m:m:end)=[];end
N=N+2;end

With thanks to @flawr for very appropriate comments and suggestions.
Example from Matlab command prompt:
>> f(40)
ans =
  Columns 1 through 22
     1     3     7     9    13    15    21    25    31    33    37    43    49    51    63    67    69    73    75    79    87    93
  Columns 23 through 40
    99   105   111   115   127   129   133   135   141   151   159   163   169   171   189   193   195   201

Thanks! I used that in the past, but tend to forget

@flawr Good point. This answer is becoming more yours than mine! :-)

Sure! I hang out more often in StackOverflow, but it's the same spirit there. I appreciate it!

Good point! I'm not sure all this I'm learning will be helpful or actually harmful for my standard Matlab usage, though :-P

Well codegolf is not about the use, but rather about the abuse of a language^^

Yes, now that the ,1 has been removed, find is unnecessary. As for <=, I'm not sure. I've replaced by - just in case

In my experience, using n=input('');...code...;x is shorter than function x=f(n);...code...;end in MATLAB

@sanchises, Yes, but the end can be ommited, and strictly you would need disp(x), not x

@LuisMendo That completely depends on the challenge; if no format is specified, x (without semicolon) will do just fine. Also, even without end, using input still shaves off 3 bytes.

Julia, 66 bytes
x->(l=[1:x^2;];[deleteat!(l,(i+=i<2):i:length(l)) for i=l];l[1:x])

Try it online!

Bash+coreutils, 136
I'd hoped to golf this down more, but oh well.  Not every day that you pipe into a recursive function in a shell script:
f(){
mapfile -tn$2 a
(($1>$2))&&{
tr \  \\n<<<${a[@]}
sed $[${a[-1]}-$2]~${a[-1]}d
}|f $1 $[$2+1]||echo ${a[@]}
}
yes|sed -n 1~2=|f $1 2

Output:
$ ./lucky.sh 23
1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79 87 93 99
$

Bash+coreutils, 104
Shorter using a more straightforward implementation:
a=(`seq 1 2 $[3+$1**2]`)
for((;i++<$1;));{
a=($(tr \  \\n<<<${a[@]}|sed 0~${a[i]}d))
}
echo ${a[@]:0:$1}

MATLAB, 62 characters
n=input('');o=1:2:n^2;for i=2:n;o(o(i):o(i):end)=[];end;o(1:n)

I misinterpreted the challenge at first - my revised version is now actually shorter.

05AB1E, 17 16 bytes
∞IFD®LKн©ô€¨˜}I£

Try it online.
Explanation:
∞             # Push an infinite positive list: [1,2,3,...]
 IF           # Loop the input amount of times:
   D          #  Duplicate the infinite list
    ®L        #  Push a list in the range [1,`®`]
              #  (`®` is -1 by default, so the list is [1,0,-1] the first iteration)
      K       #  Remove all those values from the duplicated list
       н      #  Pop the list and leave the first (smallest) value
              #  (this is basically the smallest value above `®`)
        ©     #  Store it as new `®` (without popping)
         ô    #  Split the infinite list into parts of size `®`
          €¨  #  Remove the last item of each inner list
            ˜ #  Flatten it back to a single list
  }I£         # After the loop: only leave the first input amount of values
              # (after which the list is output implicitly as result)

Go, 326
package main
import"fmt"
func s(k, p int,in chan int)chan int{
    o := make(chan int)
    go func(){
        for p>0{
            o<-<-in;p--
        }
        for{
            <-in
            for i:=1;i<k;i++{o<-<-in}
        }
    }()
    return o
}
func main(){
    n := 20
    fmt.Print(1)
    c := make(chan int)
    go func(c chan int){
        for i:=3;;i+=2{c<-i}
    }(c)
    for i:=1;i<n;i++{
        v := <-c
        fmt.Print(" ", v)
        c = s(v, v-i-2, c)
    }
}

Straight forward implementation using goroutine and pipes to make sieves.

This Code Golf, please add a byte count.

Racket 196 bytes
Produces lucky numbers upto n:
(λ(n)(let loop((l(filter odd?(range 1 n)))(i 1))(define x(list-ref l i))(set! l(for/list((j(length l))
#:unless(= 0(modulo(add1 j)x)))(list-ref l j)))(if(>= i(sub1(length l)))l(loop l(add1 i)))))

Ungolfed version:
(define f
 (λ(n)
    (let loop ((l (filter odd? (range 1 n))) (i 1))
      (define x (list-ref l i))
      (set! l (for/list ((j (length l)) #:unless (= 0 (modulo (add1 j) x)))
                (list-ref l j)))
      (if (>= i (sub1 (length l)))
          l
          (loop l (add1 i)))))
  )

Testing:
(f 100)

Output:
'(1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79 87 93 99)