text:
Produce the number 2014 from an image
In the 2014 challenge, Michael Stern suggests using OCR to parse  to 2014. I'd like to take this challenge in a different direction. Using built-in OCR from the language/standard library of your choice, design the smallest image (in bytes) which is parsed into the ASCII string "2014".
Stern's original image is 7357 bytes, but with a bit of effort it can be losslessly compressed to 980 bytes. No doubt the black-and-white version (181 bytes) works as well with the same code.
Rules: Each answer should give the image, its size in bytes, and the code needed to process it. No custom OCR allowed, for obvious reasons...! Any reasonable languages and image formats are allowed.
Edit: In response to comments, I'll broaden this to include any preexisting library, or even http://www.free-ocr.com/ for those languages where no OCR is available.

How many languages or standard libraries have built-in OCR? Or do you intend "standard library" here to mean "any library which hasn't been created specifically for this challenge"?

Does any development platform other than Mathematica have OCR built in?

You should standardize, say something like "use http://www.free-ocr.com/" or some other easily accessible ocr.

Shell (ImageMagick, Tesseract), 18 bytes
file=golf_2014
echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > $file.pbm
convert -border 2x2 -bordercolor white -resize 300% -sharpen 0 -monochrome $file.pbm $file.png
tesseract $file.png $file digits
cat $file.txt
rm $file.pbm $file.png $file.txt

The image is 18 bytes and can be reproduced like this:
echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > 2014.pbm

It looks like this (this is a PNG copy, not the original):

After processing with ImageMagick, it looks like this:

Using ImageMagick version 6.6.9-7, Tesseract version 3.02. The PBM image was created in Gimp and edited with a hex editor.

This version requires jp2a.
file=golf_2014
echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > $file.pbm
convert -border 2x2 -bordercolor white -resize 300% -sharpen 0 -monochrome $file.pbm $file.png
tesseract $file.png $file digits
cat $file.txt
convert -background black -fill white -border 2x2 -bordercolor black -pointsize 100 label:$(cat $file.txt) $file.jpg
jp2a --chars=" $(cat $file.txt) " $file.jpg
rm $file.pbm $file.png $file.txt $file.jpg

It outputs something like this:
    2014444444102         01144444102              214441                 214441
   1             1      24           1            04    4                0     4
  1    410201     0    0    410004    1       2014      4              21      4
 24   42     0    4    4    0     1    0    24          4             04       4
  22222      1    1   0    42     0    4    2   4100    4            1   41    4
            1    42   0    4      2     2   2412   0    4          24   420    4
          04    42    0    1      2     2          0    4         0   40  0    4
       204    42      0    1      2     2          0    4       24   42   0    4
     21     12        0    4      0    42          0    4      2     411114     1112
    04   412          24    0     1    0           0    4      0                   0
  24     1111111110    1    42  21    4            0    4      200011111001    40002
  4               4     04    44     42            0    4                 0    4
 0                4      214       10              0    4                 0    4
  22222222222222222         222222                  22222                  22222

Very, very impressive. 3 bytes for the header, 5 bytes for the dimensions of the image, 10 bytes for the bitmap. The format is described here: http://netpbm.sourceforge.net/doc/pbm.html

Java + Tesseract, 53 bytes
Since I don't have Mathematica, I decided to bend the rules a bit and use Tesseract to do the OCR. I wrote a program that renders "2014" into an image, using various fonts, sizes and styles, and finds the smallest image that gets recognized as "2014". Results depend on the available fonts.
Here is the winner on my computer - 53 bytes, using the "URW Gothic L" font:
Code:
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Ocr {
    public static boolean blankLine(final BufferedImage img, final int x1, final int y1, final int x2, final int y2) {
        final int d = x2 - x1 + y2 - y1 + 1;
        final int dx = (x2 - x1 + 1) / d;
        final int dy = (y2 - y1 + 1) / d;
        for (int i = 0, x = x1, y = y1; i < d; ++i, x += dx, y += dy) {
            if (img.getRGB(x, y) != -1) {
                return false;
            }
        }
        return true;
    }

    public static BufferedImage trim(final BufferedImage img) {
        int x1 = 0;
        int y1 = 0;
        int x2 = img.getWidth() - 1;
        int y2 = img.getHeight() - 1;
        while (x1 < x2 && blankLine(img, x1, y1, x1, y2)) x1++;
        while (x1 < x2 && blankLine(img, x2, y1, x2, y2)) x2--;
        while (y1 < y2 && blankLine(img, x1, y1, x2, y1)) y1++;
        while (y1 < y2 && blankLine(img, x1, y2, x2, y2)) y2--;
        return img.getSubimage(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
    }

    public static int render(final Font font, final int w, final String name) throws IOException {
        BufferedImage img = new BufferedImage(w, w, BufferedImage.TYPE_BYTE_BINARY);
        Graphics2D g = img.createGraphics();
        float size = font.getSize2D();
        Font f = font;
        while (true) {
            final FontMetrics fm = g.getFontMetrics(f);
            if (fm.stringWidth("2014") <= w) {
                break;
            }
            size -= 0.5f;
            f = f.deriveFont(size);
        }
        g = img.createGraphics();
        g.setFont(f);
        g.fillRect(0, 0, w, w);
        g.setColor(Color.BLACK);
        g.drawString("2014", 0, w - 1);
        g.dispose();
        img = trim(img);
        final File file = new File(name);
        ImageIO.write(img, "gif", file);
        return (int) file.length();
    }

    public static boolean ocr() throws Exception {
        Runtime.getRuntime().exec("/usr/bin/tesseract 2014.gif out -psm 8").waitFor();
        String t = "";
        final BufferedReader br = new BufferedReader(new FileReader("out.txt"));
        while (true) {
            final String s = br.readLine();
            if (s == null) break;
            t += s;
        }
        br.close();
        return t.trim().equals("2014");
    }

    public static void main(final String... args) throws Exception {
        int min = 10000;
        for (String s : GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()) {
            for (int t = 0; t < 4; ++t) {
                final Font font = new Font(s, t, 50);
                for (int w = 10; w < 25; ++w) {
                    final int size = render(font, w, "2014.gif");
                    if (size < min && ocr()) {
                        render(font, w, "2014win.gif");
                        min = size;
                        System.out.println(s + ", " + size);
                    }
                }
            }
        }
    }
}

I changed the rules to allow this and similar entries. Impressive file size.

Mathematica 753 100
f[n_,format_]:=
Module[{filename},
Print["raster: ",n," by ", n];
filename="2014At"<>ToString[n]<>"."<>format;
Print["filename:  ",filename];
Print["format: ",format];
Print["raster image: ",rasterImg=Rasterize[Style[2014,"OCR A Std"],
RasterSize->n,ImageSize->1n,ImageResolution->6n]];
Export[filename,rasterImg];
Print["Actual imported image: ",img=Switch[format,"PDF"|"HDF",Import[filename][[1]],
_,Import[filename]]];
Print["Identified text: ",TextRecognize[ImageResize[img,Scaled[3]]]];
Print["filesize (bytes): ",FileByteCount[filename]]]

My best case so far:
f[24, "PBM"]

Mathematica, 78 bytes
The trick to winning this in Mathematica will probably be use of the ImageResize[] function as below.
First, I created the text "2014" and saved it to a GIF file, for fair comparison with David Carraher's solution. The text looks like . This is not optimized in any way; it's just Geneva in a small font size; other fonts and smaller sizes may be possible. Straight TextRecognize[] would fail, but TextRecognize[ImageResize[]]] has no problem
filename = "~/Desktop/2014.gif";
Print["Actual imported image: ", img = Import[filename]]
Print["Identified text: ",
 TextRecognize[ImageResize[img, Scaled[2]]]]
Print["filesize (bytes): ", FileByteCount[filename]]

Fussing with the typeface, font size, degree of scaling, etc., will probably result in even smaller files that work.

Very impressive file size.

You can crop the image off the white borders to make it  smaller and shorter the spaces between digits, maybe redraw to make them more compact.

@swish indeed, trimming the white border takes it to 78 byes.


text:
Calculate 6*9 in different bases
Output the following result (which is a result of calculating 6 * 9 in bases from 2 to 36). Make sure letters are uppercase, and the multiplication itself is outputed on every line.
6 * 9 = 110110
6 * 9 = 2000
6 * 9 = 312
6 * 9 = 204
6 * 9 = 130
6 * 9 = 105
6 * 9 = 66
6 * 9 = 60
6 * 9 = 54
6 * 9 = 4A
6 * 9 = 46
6 * 9 = 42
6 * 9 = 3C
6 * 9 = 39
6 * 9 = 36
6 * 9 = 33
6 * 9 = 30
6 * 9 = 2G
6 * 9 = 2E
6 * 9 = 2C
6 * 9 = 2A
6 * 9 = 28
6 * 9 = 26
6 * 9 = 24
6 * 9 = 22
6 * 9 = 20
6 * 9 = 1Q
6 * 9 = 1P
6 * 9 = 1O
6 * 9 = 1N
6 * 9 = 1M
6 * 9 = 1L
6 * 9 = 1K
6 * 9 = 1J
6 * 9 = 1I

Shortest code wins.

It's the result from bases 2 to 36, not 10 to 36.

@Howard: Fixed. I was considering changing 2 to 10, but forgot about this edit while fixing something else in the result, so I accidentally left it the wrong way.

The challenge would be more interesting if you weren't allowed to use to use library functions for base conversion.

Calculate 6*9 in different bases I wonder why the statement is worded thus, why 6*9 and not simply 54? Perhaps the originally intended meaning was that 6 and 9 should be interpreted not always as decimal but in different bases? That would make the statement more logical, and the problem more interesting (but then we should start from base 10 to 36)

@leonbloy: 6 and 9 are single-digit numbers. They mean the same in every base in which those digits are valid.

@IlmariKaronen: Correct, but 6 * 9 = 110110 doesn't make a lot of sense...

This is a reference to the Hitchhiker's Guide to the Galaxy series by Douglas Adams.  In the series, the Answer to the Ultimate Question of Life, The Universe, and Everything is "42".  Later, its revealed that the Ultimate Question of Life, the Universe, and Everything is "What do you get when you multiply six by nine?", which works out in base-13. Note: Douglas Adams said this was unintentional; "I don't write jokes in base-13".

@leonbloy - "I wonder why the statement is worded thus," it's worded that way because of Hitchhiker's Guide to the Galaxy series.  See http://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life.2C_the_Universe.2C_and_Everything_.2842.29

05AB1E, 21 20 bytes
36G54N>B"6 * 9 = ÿ",

Try it online!

I assume it's non-competing just because the language is newer than a challenge? Marking as accepted, as rules as of now allow this.

@xfix pretty much haha

GolfScript, 39 characters
35,{2+'6 * 9 = '54@base{.9>7*+48+}%n+}/

Result can be seen here.

Octave, 49
for i=2:36printf("6 * 9 = %s\n",dec2base(54,i))end

Javascript, 57 55 bytes
for(i=2;++i<37;)console.log('6 * 9 = '+54..toString(i))

Could be shortened to 49 with alert, but I don't want to submit anyone to that...

Output should be uppercase, and (54) can be replaced with 54. (to write 54..toString).

for(i=1;++i<37;) also saves a character.

Can you ignore the 37? It will result in an error and stop

Ruby (47)
2.upto(36){|t|puts"9 * 6 = "+54.to_s(t).upcase}

Well, I know that GolfScript solution is better, but hey, at least this is not esoteric...

2.step{|t|puts"9 * 6 = "+54.to_s(t).upcase} saves a few bytes. It exits with an error, but that's ok :D.

Python, 89
B=lambda x:x*'.'and B(x/b)+chr(x%b+7*(x%b>9)+48)
b=2
while b<37:print'6 * 9 =',B(54);b+=1

Brilliant. Quite noticeable that I'm a total Python noob in comparison :)

@JoachimIsaksson Thanks... I've got loads more to learn.

You can shave off one character by using a while loop instead: b=2  while b<37:print'6 * 9 =',B(54);b+=1 (assuming single character for a *nix linebreak)

@Bob Whenever I try a while loop, it's too expensive.  Then, I forget to try the next time.  ;)  Thanks!

Python 2.7 (124 114)
EDIT: Cut some fluff thanks to @boothby's comment below
I think Python is doing ok considering it has no built-in (that I know of) to do the base conversion so it has to be done in code;
for b in range(2,37):print'6 * 9 = '+''.join(chr((54/b**y%b>9)*7+48+54/b**y%b)for y in range(4,-1,-1)).lstrip('0')

I have to remind myself of this continually: print'\n'.join(...for x in y) is rather longer than for x in y:print....

@boothby Thanks, updated with your suggestion :)

Perl 6, 36 bytes
say '6 * 9 = ',54.base($_) for 2..36

Mathematica 40
Not in contention (lower case letters used):
Print["6*9 = ",54~BaseForm~#]&/@2~Range~36

J - 78 70
'6 * 9 = ',"1>;/(a.#~48 10 7 26 165#0 1 0 1 0){~<&.>(2+i.35)#.inv&.>54

Haskell - 137
let s=['0'..'9']++['A'..'Z'];t _(0,r)=[s!!r];t b(q,r)=(t b$b q)++[s!!r]in mapM_(putStrLn.("6 * 9 = "++).(\b->t b$b 54).flip divMod)[2..36]

Perl
Had to use the Math::BaseCnv module
35 chars without the use statement:
map{say"6 * 9 = ",cnv(54,$_)}2..36

54 chars with the use statement:
use Math::BaseCnv;
map{say"6 * 9 = ",cnv(54,$_)}2..36

Not sure how you'd score this, so both are included.
The map BLOCK LIST structure was used.  List is the range 2 to 36, that was requested.  The meat is in the cnv($NUMBER, $BASE) function, and the map is an implied loop.

Count the use statement.  The first one doesn't work in my perl.

Julia 0.6, 60 bytes
for b=2:36;@printf("6 * 9 = %s\n",uppercase(base(b,54)));end

Try it online!
Pretty painless, apart from remembering to use the macro @printf versus printf.
Import Base; not needed ...

for b=2:36;println("6 * 9 = $(uppercase(base(b,54)))");end is also good...

C (166 151)
Got rid of some unnecessary characters and changed some declarations. Assumes that you are running the program with no arguments.
p[7],i,l,v,r;main(b){for(r=2;r<37;r++){b++;printf("6 * 9 = ");v=54;while(v>0)l=v%b,p[i++]=l>9?l+55:l+48,v/=b;while(i^0)printf("%c",p[--i]);puts("");}}

CoffeeScript 71
alert ("6 * 9 = "+59.toString(x).toUpperCase()for x in[2..36]).join "\n"

Link

Clojure, 75
(for[i(range 2 37)](println"6 * 9 ="(.toUpperCase(Integer/toString 54 i))))

Python 3, 83 bytes
import numpy;print('\n'.join('6 * 9 = '+numpy.base_repr(54,i)for i in range(2,37)))

You can use '\n'.join('6 * 9 = '+numpy.base_repr(54,i)for i in range(2,37)) instead of *['6 * 9 = '+numpy.base_repr(54,i)for i in range(2,37)],sep='\n' to save a byte.

You should probably specify "Python 3 with Numpy" as it's not a standard library

@FlipTack Without numpy I can get it down to 143 if I have to hardcode '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', or down to 130 if I'm allowed to import string.printable (but that results in lowercase instead of uppercase): Try it online!. Do you think that's worth making an answer?

Dart, 75 bytes
for(int x=2;x<37;x++)print("6 * 9 = ${54.toRadixString(x).toUpperCase()}");

Dart is a bit verbose when it comes to the stdlib, but hey... at least you can read it :P

Scala, 71
2 to 36 map(i=>println("6 * 9 = "+Integer.toString(54,i).toUpperCase))

Common Lisp: 56 characters
(do((b 2(1+ b)))((> b 36))(format t"6 * 9 = ~vr~%"b 54))

Sage, 48:
Shame Sage prints in lowercase... I'd only be one over Howard.  Or, I guess, wrong and tied with David Carraher.
for i in[2..36]:print'6 * 9 =',54.str(i).upper()

Forth, 54
: f 54 37 2 do ." 6 * 9 = " dup i base ! . cr loop ; f

///, 133 bytes
/R/6 * 9 = //S/
R/R110110S2000S312S204S130S105S66S60S54S4AS46S42S3CS39S36S33S30S2GS2ES2CS2AS28S26S24S22S20S1QS1PS1OS1NS1MS1LS1KS1JS1I

Try it online!

SpecBAS - 48 bytes
1 FOR i=2 TO 36: ?"6 * 9 = ";BASE$(54,i): NEXT i

SpecBAS is actually quite competitive for a change :-)

8th, 65 62 bytes
This is a complete program. Exit after execution
( "6 * 9 = " . #54 swap base drop >s s:uc . cr ) 2 36 loop bye

Explanation
(
   "6 * 9 = " .   \ Print the first part of the formula
    #54 swap base \ Enter into the base provided by loop index and
                  \ convert 54 (which is always expressed in base 10)
    drop          \ Get rid of previous base
    >s s:uc       \ Convert number into an upper case string
    . cr          \ Print result and newline
) 2 36 loop       \ Provide base from 2 to 36
bye               \ Quit

Vyxal rRMj, 119 bitsv2, 14.875 bytes
34ƛ⇧54R`6*9=`ṄðpJ

Try it Online!
Bitstring:
01001000111011011000001000111100010001001111010001100010011111010011011001011001000000010100011011001000011111011100011

so many flags
34ƛ⇧54R`6*9=`ṄðpJ
# R flag casts numbers to ranges
# M flag starts implicit ranges at 0
# The r flag reverses the arguments which makes the base conversion easier
34ƛ                # map over the range 0-34
   ⇧               # add 2, giving a range 2-36
    54R            # Convert 54 to base B
       `6*9=`Ṅ     # separate the multiplication by spaces
              ðpJ  # add a space, and append the converted base

# -j flag joins output on newlines

Created with the help of Luminespire.

Julia 1.0, 59 bytes
2:36 .|>b->println("6 * 9 = ",uppercase(string(54,base=b)))

Try it online!
Julia 0.6, 46 bytes
@.println("6 * 9 = ",uppercase(base(2:36,54)))

Try it online!

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:
Backtickify code snippets on Stack Exchange
Your goal is to input any arbitrary text, such as:
This is some text

And output that text formatted as code for posts (SE-flavored Markdown) and comments (mini-Markdown) on Stack Exchange, such as:
`This is some text`
`This is some text`

However, it gets trickier. Consider the input:
Perl has a variable called $`

The output must be
`` Perl has a variable called $` ``
`Perl has a varaible called $\``

The full rules for the formatting are:

Full posts (full SE Markdown)

Step 1: count the least number for which there are not exactly that many consecutive backticks in the string. Let's call this n. (For example, for the string potato, n is 1, for this is a backtick: `, n is 2, and for ` `` ``` ````` ``````, n is 4.)
Step 2: wrap the string in n backticks. If the string starts or ends with a backtick, you must wrap with spaces as well. (For example, potato becomes `potato`, this is a backtick: ` becomes `` this is a backtick: ` ``, and ` `` ``` ````` `````` becomes ```` ` `` ``` ````` `````` ````.

Comments (mini-Markdown)

Wrap in ` and escape all `'s with \`. (For example, potato becomes `potato`, this is a backtick: ` becomes this is a backtick: \`, and ` `` ``` ````` `````` becomes \` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\`.

This is code-golf; the shortest answer in byte count wins.

What about space?   does not get code-formatting...

@Quincunx Hmm... how are you supposed to format spaces in code anyway?

I have no idea. This post is where I learned how to format backticks and such.

The comment form also doesn't work for \; to format a \, you need to do \`\\``. Also, anything ending with a ``\`` runs into the same problem: ``asdf\`` produces asdf`

APL (90)
(Yes, the APL charset does fit in a byte, here's IBM's codepage 907.)
{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'}

This is a function that takes a string, and returns an array of two strings, where the first string is the comment representation and the second string is the full post representation.
Tests:
      backtickify←{⎕ML←3⋄(,/m,m,⍨{⍵=m:'\`'⋄⍵}¨⍵),⊂(⌽g),⍵,g←(''↑⍨∨/t[1,⍴t]),m/⍨0⍳⍨z∊⍨⍳⌈/0,z←,⊃⍴¨⍵⊂⍨t←⍵=m←'`'}
      ↑backtickify 'potato'
`potato`
`potato`

      ↑backtickify 'this is a backtick: `'
`this is a backtick: \``
`` this is a backtick: ` ``

      ↑backtickify '` `` ``` ````` ``````'
`\` \`\` \`\`\` \`\`\`\`\` \`\`\`\`\`\``
```` ` `` ``` ````` `````` ````

      ⍝ testcase for not wrapping with spaces
      ↑backtickify 'no`spaces``at````the`edges'
`no\`spaces\`\`at\`\`\`\`the\`edges`
```no`spaces``at````the`edges```

Note: I gave the function a name for readability's sake, this is not strictly necessary to use it (you can just put the argument next to the anonymous function) so I didn't count it.

Ruby, 119
s=gets.chop
c=1
c+=1while s=~/([^`]|\A)#{?`*c}([^`]|\z)/
puts ?`+s.gsub('`','\\\\`')+'`
'+?`*c+(s=~/$`|`^/?" #{s} ":s)+?`*c

Ungolfed:
def backtickify str, comment = false
  return "`#{str.gsub '`', '\\\\`'}`" if comment
  c = 1
  c += 1 while str =~ /([^`]|\A)#{?` * c}([^`]|\z)/
  str = ' ' + str + ' ' if str[0] == ?` || str[-1] == ?`
  return ?` * c + str + ?` * c
end

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


text:
Random Password Generator
The domain server requires that all employees have a strong, random password conforming to the following rules:

Exactly 15 characters long.
Keyboard-typeable characters only (as shown in code-type below).  Teaching the sales to use ALT+NUMPAD codes is not permitted.
At least 1 lower case letter: abcdefghijklmnopqrstuvwxyz
At least 1 upper case letter: ABCDEFGHIJKLMNOPQRSTUVWXYZ
At least 1 numeric digit: 0123456789
At least 1 symbol: `~!@#$%^&*()_+-={}|[]\:";'<>?,./

For this purpose IT have commissioned and will be distributing a Random Password Generator to all employees.  All employees will be required to use the Random Password Generator.  The requirements for the Random Password Generator are, in addition to the password restrictions above:

It must be able to generate all permutations of all allowable characters.
It must display the generated password on the screen.
The code is required to be as small as possible (in bytes).

Please submit your proposed solution within the next week.

You should also demand that all passwords which are allowed appear with the same probability (otherwise I can simply make a 30 characters long list with allowed characters, shuffle it, and give the first 15 ones)

@moose, agreed.  I've added a new rule.

The IT guys should be fired, or at least better educated: If you do generate passwords randomly, then restricting the set of permissible passwords to those which include at least one character of each category in fact weakens the passwords, since it reduces the size of the permissible set. And our programs would be that much easier if we didn't have to check for that… OK, don't modify the contest after so many submissions have arrived; it's fine as a challenge.

Password Generator (mkpasswd) (Python recipe)

@MvG Indeed: correcthorsebatterystaple

Well, technically those passwords are safe, but you can be 150% sure that they will be written down by everyone. This reminds me of https://codegolf.stackexchange.com/questions/6203/security-by-post-it, but it isn't a duplicate (because that one was about verifying).

"It must be able to generate all permutations of all allowable characters." If you enforce that rule strictly, most answers will be invalid since the underlying PRNG is too bad. In many languages it's seeded by a 32 bit value which is obviously not enough to generate all possible values of such a complex password.

Just give everyone "Passw@rd1234" . They'll never suspect anyone else has the same password!

@CodesInChaos for simplification we can probably assume true rng?

You haven't really answered @moose by requiring that all passwords be generatable. They should appear with equal probability.

@EthanBolker: Well, I guess that is now ok. It would be quite difficult to check if it really is with equal probability. And probably the only solutions that would come out of this would be "generate and test" ones.

@xfix I wouldn't even dare put the word "safe" near to such a broken password system. Firing the security guys should not be enough for such a mistake, you should also fire the guy who hired them.

@CodesInChaos I don't see why a true RNG is required to create all possible passwords. To generate all possible passwords with equal probability, yes. But (unless I'm misunderstanding something) the PRNG limitation you describe does not preclude one from meeting the requirements specified above. Certainly, you could not generate all possible passwords from a single output of the PRNG. But if every character was individually generated according to separate PRNG outputs, as is done in my answer (and I'm sure some others), you need a very small fraction of that 32-bit PRNG space.

Mathematica (18)
Let me a little cheat
= 15char ASCII pwd

&(^F7yP8k:*1P<t

P.S. not safety :)

Where's the code?

Is that guaranteed to satisfy the at least one of each character class requirement?

@DavidCarraher when you print "=" then the following will be converted to WolframAlpha expression. It is roughly the same as WolframAlpha["ASCII password 15 char"].

@Hand-E-Food Yes, it is! If you look at the interpretation you will see: password length 15, lower-case letters required,
upper-case letters required, numbers required,
special characters required.

+1 Clever, but sneaky.

That's great!  :-D

I knew that Mathematica has a function for everything, but this?

Wolfram Alpha states that there are about 10³⁴ passwords with the given properties, corresponding to 113 bit of entropy. The question statement allows only for 315853215942003667374440448000<10³⁰ passwords or 98 bit, so it seems Wolfram Alpha should generate huge amounts of passwords that don't satisfy the criteria. It is therefore very surprising that we haven't noticed a single one non-conforming password. The most plausible reason is that they give a wrong number. They also don't specify a list of the special characters they use, so I doubt whether that agrees with the question.

@MvG From 200-char password with special symbols only I've got !@#%^&*()_-+=~`{[}]|\<>.,;"?'/:$ after deleting duplicates. It looks like the list in the question.

Ruby, 74 69 bytes
Just randomly sample from the ascii range 33 - 126 until all classes of characters are present:
$_=[*?!..?~].sample(15)*''until~/\d/&&~/[a-z]/&&~/[A-Z]/&&~/\W|_/
p$_

Ruby, 39 bytes
Using moose's clever discovery:
p"0123abcdABCD-+/<".chars.sample(15)*''

Edit to satisfy the mob:

Note that the rules changed after I first posted this. At the time both the previous entries applied to the rules. I would also like to point out that the rules are still not too well defined:

(..) all permutations of all allowable characters

"Permutations". There are no permutations of the allowable characters that complies with the rest of the rules, because any permutation of the set of allowable characters is as long as the set of allowable characters itself (while the password is supposed to be 15 characters long). And there are no repetitions in a permutation. However my first entry is still more "random" than many of the other well upvoted answers here.
Nevertheless, here you have it. Allows repetitions of characters and underscore:
Ruby, 77 bytes
$_=([*?!..?~]*15).sample(15)*''until~/\d/&&~/[a-z]/&&~/[A-Z]/&&~/\W|_/
puts$_

I also used puts instead of p in this one because p prints out the string enclosed in "quotation marks" and some characters escaped with a backslash.
Ruby, 70 bytes
As Ventero points out, ~ can be skipped in front of the regexes, and print can replace puts$_. But with the ugly output this causes you might as well print all the rejected passwords too, squeezing it into a one-liner:
puts$_=([*?!..?~]*15).sample(15)*''until/\d/&&/[a-z]/&&/[A-Z]/&&/\W|_/

Explanation
As requested. $_ is a semi-magical variable that contains the last line read from input - so you don't always need to store it, like this. Here however we use it because of another property, namely that the ~ operator applies a regex directly to it, a trick I first learned by chron. I replaced the usage of all, but it should be quite easy to understand if you get the rest (see the docs).

+1 This is the way I would have done it, but not in Ruby.

Could you please explain your code a bit? What does .all?{|r|~r} do? What does $_= do?

You can make it a little shorter without the call to #all?, something like: until~/\d/&&~/[a-z]/&&~/[A-Z]/&&~/\W/

The sample line is clever and all, but I think it violates "It must be able to generate all permutations of all allowable characters." Nowhere does it says that the password may only contain a-d as far as letters are concerned. If z is an allowed character, there should be a chance >0 that z is in the password.

Does \W in Ruby include the underscore _? In most regex dialects I know it does not. And if your code could not generate passwords where a single _ was the only non-alphanumeric symbol, then it would violate one requirement. The second approach very obviously violates that requirement, but I guess it wasn't phrased correctly at that time.

@MvG: You're correct. \W does not contain an underscore in Perl-compatible RegEx (source).

Furthermore, your solution is affected by the same problem @moose and I had with Python: sample does not repeat elements, so passwords with repeated elements cannot be generated by your code.Can you fix these two issues to make your answer conform to the question? Seeing how yours is the leading solution, excepting Wolfram Alpha, it would be nice to see whether you can conform and still keep the lead. I guess it shouldn't be too hard.

@moose @Mvg @nitro2k01 see edit. @chron thanks! the usage of all? saved some spaced at first because I assigned the string to another variable and had to use s=~r. Then I remembered your (!) assign-to-$_ trick but forgot to replace all?.

print (with an implicit $_) is shorter than puts$_ (and I don't see a requirement for a trailing newline in the output). If you don't mind generating some warnings you can drop all the unary ~ operators.

Java 8 - 354 329 319 275 267 characters
Just for fun, using lambdas with Java 8 - each possible output has the same probability of being found.
It uses the fact that the allowed characters have consecutive ascii codes, from 33 to 126.
class A {
    //flags for, respectively, small caps, large caps, digits, punctuation
    static int a, A, d, p;

    public static void main(String[] x) {
        String s;
        do {
            //Using special String constructor that takes an int[]
            s = new String(new java.util.Random().ints(15, 33, 127)
                                .toArray(),
                           0, 15);
            a = A = d = p = 0;
            s.chars()
                .map(c ->
                      c > 96 & c < 123 ? a = 1
                    : c > 64 & c < 90  ? A = 1
                    : c > 47 & c < 58  ? d = 1
                    : (p = 1))
                .min();
        } while (a + A + d + p < 4);
        System.out.println(s);
    }
}

Sample output:
.*;Tm?svthiEK`3
o.dzMgtW5|Q?ATo
FUmVsu<4JF4eB]1

Compressed program:
class A{static int a,A,d,p;public static void main(String[]x){String s;do{s=new String(new java.util.Random().ints(15,33,127).toArray(),0,15);a=A=d=p=0;s.chars().map(c->c>96&c<123?a=1:c>64&c<90?A=1:c>47&c<58?d=1:(p=1)).min();}while(a+A+d+p<4);System.out.println(s);}}

How about while(a+A+d+p<4) together with a|=1 instead of a++? Or use bitmasks, i.e. stuff like a|=1 through a|=8, with a<15 as loop condition. This saves another 13 chars if I counted correctly.

@MvG good point - did something similar, saving a couple extra chars I believe.

@MvG And using new String(int[],int,int) saves another 40-odd chars!

Python 2.X + 3.X (229 characters): Generate and replace
Idea

First make a list with 15 allowed symbols
Replace a random position r by a random digit
Replace a random position s, with s != r, by an upper case letter
The same for lower case letter and symbol as in 2 and 3.

Code
from random import randint as r, shuffle as s
a=list(range(15))
p=a[:]
for i in range(15):
    a[i]=chr(r(32,126))
s(p)
a[p.pop()]=chr(r(48,57))
a[p.pop()]=chr(r(65,90))
a[p.pop()]=chr(r(97,122))
a[p.pop()]=chr(r(33,47))
print(a)

Python 2.X + 3.X (194 characters): Generate and check
import random
from re import search as s
p=''
while not all([s("\d",p),s("[a-z]",p),s("[A-Z]",p),s("[\W_]",p)]):
 p=str(map(chr,[random.choice(list(range(33,127))) for i in range(15)]))
print(p)

Thanks to MvG who told me that \u and \l does not exist in Python regex.
Thanks to grc who told me that random.sample is without replacement, be to get every possible allowed password we need sampling with replacement.

Using flaw in the problem description
Currently, the problem description does not demand that every symbol / digit appears with the same probability. With the following solution, you cannot make any assumption about a single symbol and/or position. But you can do it with multiple ones.
Python 2.X+ 3.X (62 characters)
from random import sample
print(sample("0123abcdABCD-+/<",15))

Thanks to daniero for the idea to use sample.

Very smooth finding the flaw!  I've plugged that one, but bonus points for identifying it.  :-)

Your gen&check is similar to my approach. Out of curiosity:where is this \l and so on for python regexes documented? Don't see it in the reference. My Python 3.3.3 won't even accept "\u". The str(…) does not join the letters in either 3.3.3 or 2.7.6. One suggestion for optmization: all(s("\\"+i,p)for i in "dluW").

random.sample chooses elements without replacement, so not all passwords are possible.

@MvG: Thank you. I've just seen that \u and \l is vim-only.

Bash on *nix (109)
while ! grep -Pq [A-Z].*[a-z].*[0-9].*[\\W_]<<<$a$a$a$a
do a=`tr -dc !-~</dev/urandom|head -c15`
done
echo $a

To work correctly, $a must not be set to a valid but non-random password up front. If you want to include a= and a line break up front, that's three more characters but it allows you to run the thing repeatedly. You can obviously also replace all newlines with ; so you have a one-liner which you can execute as often as you whish.
Furthermore, you should have set LC_ALL=C or not set any locale-specific environment variables (LANG and LC_CTYPE in particular), since the character ranges depend on collation order being equal to ascii order.
/dev/urandom is the a source of random bytes. !-~ is the range of all permissible characters, as specified in the question. tr -dc removes all characters not listed in its next argument. head takes 15 of the remaining characters. grep checks whether each of the required kinds does occur at least once. Its input consists of four copies of the candidate, so order of the symbols does not matter, hence all possible passwords stand a chance of getting selected. The -q to grep suppresses output.
For reasons unknown, /dev/random instead of /dev/urandom takes ages. It seems like entropy got exhausted pretty quickly. If you cd into /dev, you can avoid some more bytes, but that feels a bit like cheating.
Python 2 (138)
import re,random
a=''
while not re.search('[A-Z].*[a-z].*[0-9].*[\W_]',a*4):
 a=''.join(random.sample(map(chr,range(33,127))*15,15))
print a

To make the code readable I added a newline and indentation after the loop which is not neccessary and which I did not count.
This is essentially the same idea as in the bash version. The random source here is random.sample, which will not repeat elements. To counter this fact, we use 15 copies of the list of permissible letters. That way, every combination can still occur, although those with repeated letters will occur less often. But I decide to consider this a feature, not a bug, since the question did not require equal probability for all permutations, only the possibility.
Python 3 (145)
import re,random
a=''
while not re.search('[A-Z].*[a-z].*[0-9].*[\W_]',a*4):
 a=''.join(random.sample(list(map(chr,range(33,127)))*15,15))
print(a)

One newline and one indent again not counted. Apart from some Python-3-specific syntax overhead this is the same solution as for Python 2.
JavaScript (161)
a=[];for(i=33;i<127;)a.push(s=String.fromCharCode(i++));
while(!/[A-Z].*[a-z].*[0-9].*[\W_]/.test(s+s+s+s))
for(i=0,s="";i<15;++i)s+=a[Math.random()*94|0];alert(s)

I added the newlines for readability, but did not count them.
R (114)
s<-""
while(!grepl("[A-Z].*[a-z].*[0-9].*(\\W|_)",paste(rep(s,4),collapse="")))
 s<-intToUtf8(sample(33:126,15,T))
s

Linebreak and indentation inside loop added but not counted. If you feel like it, you can again move this to a single ;-separated line.

Ha!  I was just about to point out that you could have used grepl in your R code.  If only I'd thought of repeating the test password four times so you could do all the checks in one.  And you know, if only I'd thought about sample and intToUtf8.  However, you need to add replace=TRUE (or more concisely, you just need to add ,T) to your sample method to make sure you're getting all possible passwords.

@AmeliaBR: You are right, fixed that replace=T mistake, thanks for pointing this out. Finding intToUtf8 by guessing likely names with tab completion took me quite a while; I knew such a function has to exist, but the more common names like chr and so on were not used.

@MvG: I don't understand why your Python code terminates at all. Why do you need that *4? I thought your regex would match any string, that ad first one uppercase letter, then anything, then one lowercase letter, than anything ... what did I get wrong?

@moose: As you already noticed, my regex checks for the required categories in a specific order. But by taking the concatenation of four copies of the current candidate, I can ensure that the order no longer matters: Even if my password is symbols followed by digits followed by lowercase followed by uppercase, then there would still be a match. The only way a match can fail is if a category is missing altogether. Also note that I do re.search not re.match, so the regex might match anywhere in the candidate password. Does this explain why it will terminate eventually?

Ah, I did not notice that you use re.search instead of re.match. That explains it. But I still think you don't need the *4. Thank you for the explanation (+1)

@MvG: I think you can remove the inner join. This way, you have 9 characters less.

That is some clever regex! I was going to point out that it matches false positives, but after some thinking, I see it really will succeed.

@moose: Here is how 'aaa0aaaaAaa.aaa'*4 matches against my regex: aaa0aaaa[A][a]a.aaa|aaa[0]aaaaAaa[.]aaa|aaa0aaaaAaa.aaa|aaa0aaaaAaa.aaa. | denote the concatenation seams, [.] the characters matched by each of the character classes. Thanks for the hint about the inner join!

@moose: Now I know what sample problem you are talking about. Hadn't read the comment by grc, and hadn't thought that the R issue AmeliaBR mentioned might affect other languages as well. Will need to fix that.

@moose: Fixed now. I decided to stay with random.sample since the overhead of random.choice is considerable. It's a bit sad, though, because I had such a sneaky idea there: I saved the first 15 bytes of my regexp into a string variable, and used that also in place of your range(15). The result was indeed shorter – by one byte, but no matter this small difference, I'm still immensely proud of this idea. So sad that sample is so much shorter…

Nice fix :-) (Although the solution is terrible in terms of runtime ... but that's not a matter for this codegolf :-))

JavaScript version could be shorten using for(i=15,s="";i--;)

C# (123 - 139  103 - 127 characters compacted):
Using a perfectly adequate framework method in System.Web.dll:
class P
{
    static void Main()
    {
        Console.WriteLine(System.Web.Security.Membership.GeneratePassword(15, 1));
    }
}

Compacted:
class P{static void Main()
{Console.WriteLine(System.Web.Security.Membership.GeneratePassword(15,1));}}

Example:
b+m2ae0K:{dz7:A

Alternatively, take the value of the second parameter (int numberOfNonAlphanumericCharacters) from the command line:
class P
{
    static void Main(string[] a)
    {
        Console.WriteLine(System.Web.Security.Membership.GeneratePassword(15, int.Parse(a[0])));
    }
}

GeneratePassword does not support the full set of symbols specified in the question. Neither did I find any guarantees about the minimum number of occurrences of each character category.

You could compact further by using class P and string[] a.

@MvG, that's interesting.  It looks like it excludes any symbol that's commonly used to write accented characters in languages such as French.  Probably a smart move.  Changing the keyboard language would be enough to stuff up your password.

R (301 322 characters)
Correction forgot to check for digits.
a='abcdefghijklmnopqrstuvwxyz';
f=as.factor(strsplit(paste(a,toupper(a),
    sep="0123456789`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./"),"")[[1]]);
g=gsub("(.):","\\1",levels(q:q:q:q:q:q:q:q:q:q:q:q:q:q:q));
repeat{p=g[runif(1)*length(g)];
    if(grepl("[A-Z]",p)&&grepl("[a-z]",p)&&grepl("[0-9]",p)&&grepl("[^A-Za-z0-9]",p))break;};
print(p);

(whitespace added for clarity only).
Generates all possible 15-character permutations of the 94 characters.  Then randomly selects one until it matches the criteria.
The magic is in the  q:q operation, which generates a new factor data type that is the interaction of all the factors in the first q list with all the factors in the second list, with every possible combination of those two lists being included in the list of "levels" of that factor.  Interact 15 copies of the list of allowed characters, and you get (94^15) possible levels.
Please do not try this at home.  The code takes a couple seconds to figure out all the three-character permutations, I really can't imagine how long it would take to figure out all the 15-character permutations, if your computer didn't just run out of memory in the meantime.  When I ran the finished (three-character password) script to check it, the first password it spit out was "oO=", which I think about sums up the reaction you should have to this code.

@MvG has an R script that is both much more practical and much shorter, if much less awesome: http://codegolf.stackexchange.com/a/17700/12413

Nevertheless, I like your idea. Many code-golf snippets I saw let specific features of the language do the hard work. And your code certainly does that for R, with those interactions.

Python 2.7 (182)
import random as r,string as s
z=r.sample
j=list(z(s.ascii_lowercase,12)+z(s.ascii_uppercase,1)+z(s.digits,1)+z('`~!@#$%^&*()_+-={}|[]\\:";\'<>?,./',1))
r.shuffle(j)
print ''.join(j)

You can get 9 digits less by removing the join as it is not required by the problem descript. Another 2 less by removing spaces.

@moose I took out the spaces right before you commented :-) I feel like the join kinda has to be there: Would users be expected to understand python list syntax from the output: ['q', 'u', ...]?

I thought about removing print at all. When size in bytes is important, they might live in the punch card time. That way, they might be able to read the memory ... just by looking at it. Or they are "real programmers": http://xkcd.com/378/

This is my first swing(?) at code golf... I guess we have to be pedantic, huh :-)

If I'm reading the code correctly, this does not fulfill the all permutations requirement, it will always have 12 lowercase characters, making passwords with more than one of the other groups (like aA$bc1111111111) impossible.

In Johnathon's defence, I think the permutations rule was added 5 minutes after his post.

@Hand-E-Food There was still some sort of "cannot be predictable" requirement. (Though, I am still impressed by how "slim" this answer is)

One tiny problem, you need to escape the backslash (right now, it's just escaping the :)

@IQAndreas Thanks for pointing that out. But it was still working, as '\:' == '\\:'.

Mathematica 170
r=RandomSample;f[i_]:=(FromCharacterCode/@Range@@i);
{t,A,a,n}=f/@{{33,126},{65,90},{97,122},{48,57}};
s=Complement[t,A,a,n];
""<>r[Join[RandomChoice/@{A,a,n,s},r[t,11]],15]

Examples
"<]}Pg3/e?3+Z~Oz"
"X/8jWe@f(_x5P:="
"2wz2VQhtJC?*R7^"

Golfscript (60)
Since the obl. golfscript is missing and as a noob I need the practice anyway :)
[48 10{rand}:r~+65 26r+97 26r+33 15r+11,{;32 96r+}%~]{r}$''+

It just builds an array with the 4 required + 11 random characters and sorts in random order.

+1 for {r}$. That's a pretty dirty way to shuffle a list — I like it! ;-)

...however, I don't think this can ever output e.g. 0Aa~~~~~~~~~~~~. :-(

JavaScript 258 240 233 225
R=Math.random;a=b=>b[b.length*R()|0];for(x=[a(l="abcdefghijklmnopqrstuvwxyz"),a(u=l.toUpperCase()),a(n="0123456789"),a(s="`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./")];15>x.length;x.push(a(l+u+n+s)));alert(x.sort(y=>.5-R()).join(""))

Using a rule where:
function(x){return x*x} can be re-written as function(x)x*x. Only seems to work for functions returning a value.
Next iteration, reduced x.sort(function().5-R()) to x.sort(y=>.5-R())
Next iteration, reduced further with fat arrow notation, which sadly only works for Firefox 22 and above.

Nice compacting! :D

JavaScript (269 characters compacted)
For clarity, this is the code before I compacted it down JS-Fiddle of it:
var lowerLetters = "abcdefghijklmnopqrstuvwxyz";
var upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "0123456789";
var symbols = "`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./";
var allCharacters = lowerLetters + upperLetters + numbers + symbols;

String.prototype.randomChar = function() {
    return this[Math.floor(this.length * Math.random())];
}

var minLength = 15;
var result = [];

// Start off by picking one random character from each group
result.push(lowerLetters.randomChar());
result.push(upperLetters.randomChar());
result.push(numbers.randomChar());
result.push(symbols.randomChar());
// Next, pick a random character from all groups until the desired length is met
while(result.length < minLength) {
    result.push(allCharacters.randomChar());
}
result.shuffle(); // Finally, shuffle the items (custom function; doesn't actually exist in JavaScript, but is very easy to add) -> http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
result.join("");

Here it is compacted down to 269 characters (JS-Fiddle of it):
l="abcdefghijklmnopqrstuvwxyz";
u=l.toUpperCase();
n="0123456789";
s="`~!@#$%^&*()_+-={}|[]\\:\";'<>?,./";
R=Math.random;

function r(t){
    return t[~~(t.length*R())]
}

for(x=[r(l),r(u),r(n),r(s)];x.length<15;x.push(r(l+u+n+s)));
x.sort(function(){return .5-R()});
alert(x.join(""));

Since I'm ending lines with semi-colons, all removable whitespace was ignored for character counting, but left in for clarity.

What do you mean by shuffle() being a "custom function".  Is it part of JavaScript or code you would have to write it yourself?

@Hand-E-Food I meant it is not built into JavaScript, and since any developers here should know how to shuffle an array, I felt including the function in the code was unnecessary. It is available in the JS-Fiddle though (line 16).

My point is, it counts towards your byte-count.  But I see now you have implemented it in the compacted version, so please ignore me.  :-)

Clojure (63):
(->> (map char (range 33 127)) (shuffle) (take 15) (apply str))

But need to be improved to ensure that containing at least 1 character of each category (Upper, Lower, Digit, Symbol).

In sql-server
declare @a nvarchar(28)
set @a='abcdefghijklmnopqrstuvwxyz'
declare @b nvarchar(max)
set @b='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
declare @c nvarchar(max)
set @c='0123456789'
declare @d nvarchar(max)
set @d='~!@#$%^&*()_+-={}|[]\:";<>?,./'

select left(substring(@a,cast(rand()*10 as int),3)+substring(@b,cast(rand()*10 as int),6)+substring(@c,cast(rand()*10 as int),3)+substring(@d,cast(rand()*10 as int),5),15)

See it in action--1
see it in Action--2

I'm having trouble following the last line, but the code does not seem to fulfill the all permutations requirement.

Your code will never generate any password starting with ~0Aa, nor any password where b is followed by a.

@Heinzi:yes i agree all permutations required r not taken into account it just displays a 15 length..characters randomly choosen from a...z,A..Z,0..9,!...+ :(...

SAS (191)
%macro c(p);compress(p,,"&p")ne''%mend;data x;length p$15;do x=1by 1;do t=1to 15;substr(p,t,1)=byte(ranuni(7)*94+33);end;if %c(kd)and %c(kl)and %c(ku)and %c(ad)then do;put p;stop;end;end;run;

*TQP,(f=h10*)S=
Commented/indented:
%macro c(p); /*compress removes or keeps certain classes of characters*/
  compress(p,,"&p")ne''
%mend;
data x;
length p$15;
do x=1by 1;
    do t=1to 15;
        substr(p,t,1)=byte(ranuni(7)*94+33); /*give it a 33-126, byte discards the noninteger portion rounding down*/
    end;
    if %c(kd)and %c(kl)and %c(ku)and %c(ad)then do; /*k=keep d=digit l/u=lower/upper ad=remove digits and alphas*/
        put p;
        stop;  /*met our requirement, head home*/
    end;
end;
run;

PowerShell: 119
Gofled Code
for(;!($x-cmatch'.*(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!-/:-@[-`{-~]).*')){$x='';1..15|%{$x+=[char](33..126|random)}}$x

Un-golfed and Commented
# Start for loop definition.
for(
    # Skip variable initialization, start definition of run condition.
    ;
    # Loop runs if $x does not meet complexity requirements.
    # Length requirement is not tested here because it is enforced by the generator later.
    # Much thanks to @VasiliSyrakis for the RegEx help.
    !($x-cmatch'.*(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!-/:-@[-`{-~]).*')
)
{
    # Reset $x in case the script block has already run.
    $x='';
    # Use ForEach-Object, via the % alias, to run a loop 15 times.
    1..15|%{
        # Append a random ASCII character from 33-126 to $x.
        # Note: Use get-random instead of random for faster performance.
        $x+=[char](33..126|random)
    }
}
# Display $x.
$x
# Variable cleanup - not included in golfed code.
rv x

I think this regex may make it ever so slightly shorter: ^.*(?=.{15,})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!#$%&? "]).*$, you can do one match with this, which will only match when there is one Upper,Lower,Digit,Symbol.

@VasiliSyrakis Ok, You might have to walk me through that a bit. Feel free to start up a chat room if you think it will take awhile. A couple things I'm confused on: 1.) I see the number 15 included there. Is that to make sure the string is exactly 15 characters? If so, this can be omitted, since the script naturally only generates 15-character strings. 2.) What do you mean "will only match when there is one Upper, Lower, Digit, Symbol"? Does that mean it will only match when there is exactly one of each, or at least one of each? The former will break things.

Also, does your RegEx ignore ordering of characters? For example, if tuned down to match 4-character strings, would both 1aZ% and (p3R match? I had some difficulty finding ways to do that online.

Tested the new RegEx against output from my current script. It doesn't seem quite reliable. Code: $x-cmatch'^.*(?=.{15,})(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!#$%&? "]).*$' Good matches: C>suD1?hTwbDx(z j%4O]HyeG|u[U$5 O/rGeD0$hJk=GO/ Failed matches: 3evthX3_X^nBrR\ .nA~uYzrR4YV-r. u-IjZE48ntQ;HxV

How do I open a chat room?

@VasiliSyrakis Let's just repurpose this one. I think we're done discussing the original topic there.

PHP, 235 225
This script shuffles characters around and then is checked via RegEx to make sure the password is strong (or it is regenerated).
<?php
while(!preg_match('/^(?=.*[A-Z])(?=.*[^A-Za-z])(?=.*[0-9])(?=.*[a-z]).{15}$/',$p)){ $p = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()_+-={}|[]\:";\'<>?,./'),0,15); }
echo $p;

Clever, but doesn't allow duplicate characters.

Instead of while(true) ... if (condition) break you can use while (!condition)

Powershell

One Liner version (143 bytes)
sal g random;1..11|%{$P+=[char](33..126|g)};(65..90|g),(97..122|g),(48..57|g),(33..47+58..64+123..126|g)|%{$P=$P.insert((1..11|g),[char]$_)};$P

Mini version (146 bytes)
sal g random
1..11|%{$P+=[char](33..126|g)}
(65..90|g),(97..122|g),(48..57|g),(33..47+58..64+123..126|g)|%{$P=$P.insert((1..11|g),[char]$_)}
$P

Readable version (860 bytes)
function pwgen {

    # Fulfill Upper,Lower,Digit,Symbol requirement by predefining ASCII ranges for each
    # These will be added into the string beginning at line 24

    [array[]]$symbolrange = (33..47),(58..64),(123..126)

    [char]$upper = (get-random (65..90))
    [char]$lower = (get-random (97..122))
    [char]$digit = (get-random (48..57))
    [char]$symbol = $symbolrange | get-random

    [char[]]$requirement = $upper + $lower + $digit + $symbol

    # Create the first 11 characters using any ASCII character between 32 - 126

    foreach ($number in (1..11)) {
        [string]$pass += [char](get-random (33..126))
    }

    # Insert each requirement character at a random position in the string

    foreach ($char in $requirement) {
        [string]$pass = $pass.insert((Get-Random (1..11)),$char)
    }

    return $pass
}

Credit to Iszi for various tips to shorten the code.

This doesn't cover all permutations.  As an example, abcd1234ABCD{|}~ will never come up because $symbol forces at least one of the symbols to be between ASCII 33 and 47.

Dangit! Must you point out my laziness!? Just kidding... I've edited it now. I also made each "requirement" character go to a separate index within the string, instead of clumping the four in together at the same index. Now if only I could shorten this...

Is there any reason you can't shave a couple more characters by shortening $SR to, perhaps $Q?

You should also be able to cut stuff like (g(65..90)) down to 65..90|g'. And change the foreachstatements toforeach-objectloops using the%alias. Example:foreach($N in (1..11)){...}should be doable as1..11|%{...}`. I'm pretty sure there's other optimizations which are possible, but I've actually got a completely different implementation in mind that I'm planning to try later.

Nice tips :) I shortened it to 213 bytes if I take out the carriage returns and replace with semicolons.

More tips: Get-Random can be truncated to just Random. This may bloat the running time a bit, but it still works. Replace (33..47),(58..64),(123..126) with 33..47+58..64+123..126. You also don't need to force the type of $symbolrange to an array - it will auto-type based on the data you've given it. In the shorter version you don't need += to define $Q either - just =.

For that matter, you probably don't even need $Q,$U,$L,$D, or $S at all. If you have a variable that effectively only ever gets used once, then it's probably a variable you don't need.

Damn, awesome tips man, I have to add a credit into the post for all your help :) We're down to 143 bytes now. I never imagined that Powershell could get so short!

@VasiliSyrakis Just wait until you see what I'm working on. Pretty sure it's going to still beat 143. Also, check out a thread somewhere around here called something like "Golfing tips for PowerShell".

Okay, so apparently this can be done as per the F# example... like this: [Web.Security.Membership]::GeneratePassword(15,1)... Kinda ruins it :P

@VasiliSyrakis Unable to find type [Web.Security.Membership].

You know what's weird? I get the same error, unless I type [web.security.membership]:: and then do a tab completion on gen or similar. Not sure how to manually load the assembly.

Well, ignoring the fact that the OP omitted a requirement to avoid built-in password generation functions, I went ahead and banged it out in 135 characters here.

One little bug in the code (which I've now got to fix in mine, too) that doesn't affect length: Spaces (ASCII character 32) are not valid characters per the spec of "Keyboard-typeable characters only (as shown in code-type ...)."

Python 2.7 (149)
from random import*
''.join(map(lambda x:chr(randint(*(x[1]or(32,126)))),sorted(map(None,sample(range(15),15),((48,57),(65,90),(97,122),(33,47))))))

Written out in a more readable (and not executable) way;
from random import *
''.join(                                          # Concatenate characters to string
  map(                                            # Map all characters using below lambda
    lambda x:chr(randint(*(x[1] or (32, 126)))),  # Map a single range to a random character
                                                  # within a specific range if supplied,
                                                  # otherwise the default "all" range.
    sorted(                                       # After distributing ranges, sort
      map(None,                                   # zip_longest alternative, distributes the
                                                  # required ranges over 4 random positions
        sample(range(15), 15),                    # 0-14 in random order
        ((48, 57), (65, 90), (97, 122), (33, 47)) # The 4 required ranges
      )
    )
  )
)

Fairly straight forward and surprisingly not much longer than a "generate, retry on match fail" version.

Are you sure this can really generate all eligible passwords, including e.g. 0Aa~~~~~~~~~~~~? (Note that '~' == chr(126).)

PSQL (189)
Feels like PSQL is a bit verbose... :)
SELECT ARRAY_TO_STRING(ARRAY_AGG(CHR((TRUNC((b-a)*RANDOM()+a))::int)ORDER BY RANDOM()),'')FROM(SELECT 32 a,127 b FROM generate_series(1,11)UNION ALL VALUES(48,58),(65,91),(97,123),(33,48))a

SQLfiddle demo.

Perl, 92
Not as concise as the Ruby answer, but I'm sure a Perl wizard could make this even shorter... I'm not too happy with all the m//s at the end, but seems to work and should satisfy the conditions to eventually generate all permutations.
do{$_=join"",map{(map{chr}33..127)[rand 94]}0..14}while!(/[A-Z]/&/[a-z]/&/\d/&/[\W_]/);print

Sample usage:
perl -e 'do{$_=join"",map{(map{chr}33..127)[rand 94]}0..14}while!(/[A-Z]/&/[a-z]/&/\d/&/[\W_]/);print'

Edited to fix validation and change [[:punct:]] to [\W_] after MvGs comments.

Your generation part is nice, but your selection criterion in the loop condition is plain wrong: e.g. a password of aaaaaaaaaaaaaa would cause the loop to terminate. You should test criteria with non-random passwords to make sure they do what you want them to.

Indeed, you are correct, I've fixed this and saved some bytes! Thanks!

Are you sure about this [[:punct:]]? I guess I'd prefer '[\W_], which is shorter and of which I'm even more sure that it is correct, at least combined with your 33..127` range.

A good point, I think I was concerned that \W didn't include _, however you're absolutely right, it's not needed:
https://gist.github.com/anonymous/8301237. Thank you!

Javascript (209)
r=Math.random;function t(x,y){return String.fromCharCode(Math.floor(y*r()+x))};x=[t(33,14),t(48,10),t(65,26),t(97,26)];for(i=0;i<11;i++)x.push(t(32,95));console.log(x.sort(function(){return r()-0.5}).join(''))

Semi-ungolfed;
// Return a character in the range [x,x+y)
function t(x,y) { return String.fromCharCode(Math.floor(y*Math.random()+x)) }
// Prefill required ranges
x=[ t(33,14), t(48,10), t(65,26), t(97,26)]
// Push 11 totally random (valid) characters
for(i=0; i<11; i++)
  x.push(t(32,95))
// Shuffle and output as string
console.log(x.sort(function(){return Math.random()-0.5})
             .join(''))

Java 7 (270 234 characters)
The premise is the same used by @assylias with java 8 (generate random passwords until valid password). However, instead of using lambdas, the password is generated by iterating a char array and validated by matching a regex.
class A {
  public static void main(String [] a) {
    byte[] b = new byte[15];
    String s;
    do {
      new java.util.Random().nextBytes(b);
      s = new String(b);
    } while(!s.matches("(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)(?=.*?[!-/:-@\\[-`]).*"));
    System.out.println(s);
  }
}

Minified Code:
class A {public static void main(String[] a){byte[] b=new byte[15];String s;do{new java.util.Random().nextBytes(b);s=new String(b);}while(!s.matches("(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\\d)(?=.*?[!-/:-@\\[-`]).*"));System.out.println(s);}}

Factor, 196 characters
Same algorithm as MvG and moose's. It is not the shortest but should satisfy all the (current) criteria in the question:
USING: io kernel math pcre random sequences sequences.repeating ;
[ 15 94 random-integers [ 33 + ] "" map-as dup 60 cycle
"[A-Z].*[a-z].*[0-9].*[\\W_]" findall { } = not ] [ drop ] until print

I might be misinterpreting the regex, but I think something like ~{}|1234abcdABCD will fail the regex.

No it will work: "~{}|1234abcdABCD" 60 cycle "[A-Z].*[a-z].*[0-9].*[\\W_]" findall empty? not => t

I'll take your word for it.  :-)

C - 154 characters
char p[16],c,f,w;main(){srand(time());while(f^15){c=p[15]=f=0;while(c^15){w=33+rand()%94;f|=w
>96&&w<123?1:w>47&&w<59?2:w>64&&w<91?4:8;p[c++]=w;}}puts(p);}

How do I hate srand()? Let me count the ways.

Haskell, 192
import System.Random
main=getStdGen>>= \g->(print.(take 15))$until((\x->all(any(`elem`x))[['a'..'z'],['A'..'Z'],['0'..'9'],['!'..'/']++":;<=>?@[\\]^_`{|}~"]).(take 15))tail$randomRs('"','~')g

The printed string has quotes around it and escapes the backslash and quote characters; if that's unacceptable, print can be replaced with putStrLn for 3 more bytes. Here's a more readable version:
import System.Random

main = do
    g <- getStdGen
    let chars = randomRs ('"', '~') g
    let password = take 15 $ until (hasChars.(take 15)) tail chars
    print password

hasChars :: String -> Bool
hasChars x = all (any (`elem` x)) $
    [ ['a'..'z']
    , ['A'..'Z']
    , ['0'..'9']
    , "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
    ]

It's quite straightforward, it just creates an infinite/lazy list of random ASCII characters in the range '!' to '~', then tosses out the first element until the first 15 characters have at least one character from each string of required characters.

Excel VBA, 209 bytes
For i = 1 To 15
x = x + Chr(Int(90 * Rnd + 33))
Next
p = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$"
With New RegExp
.Pattern = p
Set m = .Execute(x)
If m.Count = 0 Then
MsgBox "redo"
Else
MsgBox x
End If
End With

Randomly generates 15 ASCII characters so all possible combinations are possible.
Then uses a regular expression pattern to check if it contains at least one of each criteria.
If it does then the password is displayed, if not "redo" is displayed.
Credit to Bart Kiers for the Regular Expression pattern: https://stackoverflow.com/questions/1559751/regex-to-make-sure-that-the-string-contains-at-least-one-lower-case-char-upper

Python 3 + passgen, 64 bytes
import passgen as p
print(p.passgen(length=15,punctuation=True))

If you have any suggestions for improvement, let me now in the comments!
Try it online! (or rather don't, as the passgen module isn't on TIO)
Github:
https://github.com/EacyCoding/Password_Generator
or in one line:
import passgen as p;print(p.passgen(length=15,punctuation=True))

Sample Outputs:
;dLjI3pr7541(CW
3ptRCt%OK^8+iW;
dDZk7^1!53rG$3M

Welcome to the site! Both of these solutions are 117 bytes. You can remove the spaces before the * and after the ) ()for x) and be sure to check out our Tips for golfing in Python page for more ways you could golf your answer. Also, the challenge requires that you include "at least 1" for 4 different categories. It's unlikely, but this program does have a chance to return e.g. abcdefghijklmno, which doesn't meet the challenge specs.

@cairdcoinheringaahing thank you very much for your feedback, I see the problem with the chance to return abcdefghijklmno, so I have a new solution (:

Feel free to edit the post and link to the try it yourself page. I don't know how to automatically insert my code in the link, would love if you coul explain me.

I've edited the title slightly to indicate the use of a non-standard library (perfectly fine, so long as it's made clear). To get the answer format from Try It Online (TIO), click the link button at the top of the page and copy paste the contents of the "Code Golf submission" text area

@cairdcoinheringaahing thank you

AutoHotkey 352
global o:={}
loop 4
o[c()]:=o(A_index-1)
loop 11
o[c()]:=o(m(r(),4))
loop 15
s.=o[A_index-1]
msgbox % s
r(){
Random,z
return z
}
m(z,r){
return mod(z,r)
}
c(){
while o[t:=m(r(),15)]!=""
j++
return t
}
o(f){
r0:=48,l0:=10,r1:=97,l1:=l2:=26,r2:=65
r := chr(r%f%+m(r(),l%f%))
if f=3
r:=Substr("``~!@#$%^&*()_+-={}|[]\:"";'<>?,./",m(r(),32)+1,1)
return r
}

Using - Just run the script

Python (121 characters)
Makes use of the fact that you can multiply lists in Python [1,2,3] * 2 gives [1,2,3,1,2,3]. Imports random. Numbers in a list multiplied by three are borders between ranges in ascii table for needed characters, e.g. [65, 90] maps to uppercase letters.
print "".join([random.choice([chr(i) for i in range(z[0],z[1])]) for z in [[33,48],[48,58],[58,65],[65,90],[90,123]]* 3])

"It must be able to generate all permutations of all allowable characters.". I don't think it does that since the ranges are always applied in the same order...?

You are right, thank you. Indeed I didn't notice that ranges should be applied in random order, they should be shuffled, I'll edit that in a moment.

This needs to actually include import random in the code.

Perl (134 characters)
Perl one-liner::
perl -e 'push @a,map{(33..47,58..64,91..96,123..126)[rand (32)]}1;push @a,map{(65..90)[rand(26)]}1;push @a,map{(97..122)[rand(26)]}1;push @a,map{(48..57)[rand(10)]}1;push @a,map{(33..126)[rand(10)]} 1..11;foreach (@a){print chr($_);}'

The Output:
_Gj2()%%&)$#"%&
$Vn7"#"'#%*&$%(
]Tj2*'%)&"#"#(%

Update:
perl -MList::Util=shuffle -e 'push @a,map{(33..47,58..64,91..96,123..126)[rand (32)]}1;push @a,map{(65..90)[rand(26)]}1;push @a,map{(97..122)[rand(26)]}1;push @a,map{(48..57)[rand(10)]}1;push @a,map{(33..126)[rand(10)]} 1..11; @a=shuffle @a;foreach (@a){print chr($_);}'

It is a small sample but the punctuation signs seem to appear a lot more than numbers or letters...

This approach uses the categories in a fixed order, so it doesn't allow all possible passwords.

@assylias : It is randomized selection so no-one can predict it, n' in some runs you can get more of alphabets and numbers than the punctuation mark. And for what it matters, it satisfies all the above mentioned criteria for a strong password. Please, do correct me if I am missing something.

@MvG: Thanks for pointing it out, I fixed it. Please see for the Update.

Now you are using the characters from the different categories in random order, but still in fixed proportion. Which is why you have so many more symbols in your examples than one would expect, as assylias pointed out.

Python 3.3 (360 characters)
First generate a random character from each list, to ensure the first rule.
Them add a random sample from the whole group of allowed characters to complete the rest of the password.
Now we have a random sequence of 15 chars (a seed), with at least one of each, but the first 4 are always, in order, a lower, an upper, a numeric and a symbol. So we shuffle the seed, thus allowing all possible and valid passwords to be generated.
from random import sample

lower = 'abcdefghijklmnopqrstuvwxyz'
upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
numeric = '0123456789'
symbol = '''`~!@#$%^&*()_+-={}|[]\:";'<>?,./'''

seed = sample(lower, 1) + sample(upper, 1) + sample(numeric, 1) + sample(symbol, 1) +\
   sample(lower + upper + numeric + symbol, 11)
pwd = ''.join(sample(seed, 15))
print(pwd)

Since this is code-golf, you should add character (or byte, in this case) count to your post.

PHP 5.5 (230 bytes)
echo preg_replace_callback('/./', function ($a)
{
  return chr([rand(33, 126), rand(48, 57), rand(65, 90), rand(97, 122), ord(str_shuffle('`~!@#$%^&*()_+-={}|[]\:";\'<>?,./')[0])][$a[0]]);
}
, str_shuffle(str_pad('1234', 15, 0)));

Or on one line (211 bytes)
echo preg_replace_callback('/./',function($a){return chr([rand(33,126),rand(48,57),rand(65,90),rand(97,122),ord(str_shuffle('`~!@#$%^&*()_+-={}|[]\:";\'<>?,./')[0])][$a[0]]);},str_shuffle(str_pad('1234',15,0)));

F#, 67 66 59 characters
Using the same framework method as the C# solution, but obviously F# is shorter:
Web.Security.Membership.GeneratePassword(15,1)|>printf "%s"

I don't need to specify System, apparently.

C++11 (489 characters)
#include <algorithm>
#include <iostream>
#include <string>
#include <random>
using namespace std;random_device r;uniform_int_distribution<> d4(0,3),d10(0,9),d26(0,25);
char rc(int t){int i=0;switch(t){case 0:i=48+d10(r);break;case 1:i=32;case 2:i+=65+d26(r);break;case 3:i=33+[](unsigned j){return j<15?j:j<22?j+10:j+68;}(d26(r));}return char(i);}
int main(){string s(15,0);int i=0;for(;i<4;i++){s[i]=rc(i);}for(;i<15;i++){s[i]=rc(d4(r));}random_shuffle(s.begin(),s.end());cout<<s<<endl;}

Update: stripped down from 673 to 489 characters

That's kind of the point; to reduce the code size to as small as possible.

Bash (111 bytes)
a=`strings /dev/urandom | head -c 512 | iconv -f utf-8 -t us-ascii//TRANSLIT | tr -d '\n' | head -c 15`
echo $a

Example outputs:
bw?<{qqH$lh}VC2
M)2@(nH9IdkOwYh
x;&_IR)NM7bCNd~

Perl (73 characters)
sub x{@x=map{chr rand6+6*$_+27%122}1..15;print splice@x,rand@x,1 while@x}

Maybe someone can minify it more..

The requirement “It must be able to generate all permutations of all allowable characters.” is not satisfied. For example, the first generated symbol will be between 33 and 37. Even if you reoder afterwards, the fact that your password must contain one of these six letters remains. Other passwords cannot be the result of your code.


text:
Tips for golfing in APL
I started one code golf challenge recently and it seems like the winner is GolfScript (surprise, surprise!). What's interesting is that there was another very strong competitor that had all chances to win over GolfScript. Its name is APL. I see a lot of answers written in APL here. It seems like this language is fairly efficient for code golfing, so I decide to ask for any code golfing tips you know for APL programs. Feel free to post some code examples. It is usually very interesting to see language in action.

Edit: for people reading this who don't  know APL at all but want  to take it up, Mastering Dyalog APL is a very good resource.

Evaluation is strictly right-to-left. This includes setting variables, so take advantage of it.
2+a, 1+a←1  -> 3 4
a is set to 1, 1+a evaluates to 2, a,2 evaluates to 1 2 and 2+1 2 evaluates to 3 4.

Like C, ← can be combined with a function, i.e. a +← 3. Unlike C, this is generic: foo F← bar sets foo to F bar. Somewhat unintuitively, as an expression this returns bar, not F bar.
It works with anonymous functions too:
       a←0
       a+←3 ⋄ a
 3
       a+←3 ⋄ a
 6
       a { ⍵/'!' } ←4 ⋄ a
 !!!!

You can assign to an array: A[3]←8, like you'd expect. But you can also assign multiple items at the same time: A[3 5 6]←9 1 4, or even A[3 5 6]←9, setting them all to the same item. You can, of course, add a function to the ← here too. The  function will then be applied to each element separately, as if you did F¨.

⍨ is your friend, even if he doesn't look too happy about it.

If F is dyadic, dyadic ⍨ switches the arguments: a F b <-> b F⍨ a. This comes in handy when golfing because it can save you from using braces:
(F G H x) K y      <->     y K⍨ F G H x

This does change the evaluation order, as the right hand is always evaluated before the left hand.

If F is dyadic, monadic ⍨ applies the same argument to both sides of the function:
      5⍴5
5 5 5 5 5
      ⍴⍨5
5 5 5 5 5

The argument is only evaluated once. This particularly comes in handy with outer products, i.e. to compare each value in an array with the other values in the same array, you can use ∘.=⍨ instead of having to do x∘.=x←(whatever).

If F is monadic, ⍨ does nothing, but it does separate the function from the argument. So it can still save you braces if the function is complex:
      {⍵+3}⍣5 6
      ∇{⍵+3}
     ∇ ⍣ 5 6
      ({⍵+3}⍣5)6
21
      {⍵+3}⍣5⍨6
21

Learn the idioms! Then golf the idioms. For example:
 ((((1↑⍴X),⍴Y)↑X)^.=Y)⌿X

can be mechanically transformed into:
 X⌿⍨Y^.=⍨X↑⍨(1↑⍴X),⍴Y

and then further into:
 X⌿⍨Y^.=⍨X↑⍨(⊃⍴X),⍴Y

⊃ (first) being equivalent to 1↑ (take one) in this case. And possibly:
 X⌿⍨Y^.=⍨X↑⍨(≢X),⍴Y

≢ (tally) being equivalent to ⊃⍴ (the first element of the shape) for all but scalars.

Is there a way to get a free license beside having the raspberry pi version?

A legal way to get it, obviously.

@Fabinout: At dyalog.com you can download a free Windows version. Click "Download Zone" and then "Unregistered Download". It will nag you to register but otherwise it's fully functional and free and legal. If you're a student, you can get the normal version for free by filling out a form. If you don't live in a country where they ruin your life for pirating, well, you know what to do.

There is also Nars2000, an open source implementation that has many more features than Dyalog (and some bugs.) Some of its features come in handy for golfing, such as the prime number functions or multisets.

There is GNU APL.

@M.Alaggan: GNU APL is not very good though, especially for golfing. (It lacks proper d-fns, for one, and it certainly doesn't do trains or other fancy stuff.) If you want an open-source APL for golfing, ngn/apl is probably better. (Though that one's arguably a worse APL, as that one lacks the ∇-functions completely, but you don't use those for golfing anyway.)

@marinus Should it not be possible to contribute improvements to GNU APL so it kicks the same amount of arse? I have the program installed on Mac OS, how much is it lacking in terms of the language's coverage...?

+1 Excellent post. Regarding 4.3. ⊢ is better than ⍨ for separating arguments, as it works on dyadic functions too, and doesn't cause syntax errors if the function is strictly monadic.

Trains
A(f g h)B      ←→  (A f B)g A h B  ⍝ fork
 (f g h)B      ←→  (  f B)g   h B  ⍝ fork
A(  g h)B      ←→         g A h B  ⍝ atop
 (  g h)B      ←→         g   h B  ⍝ atop
 (A g h)       ←→  ({A} g h)       ⍝ "Agh" fork
 (f g h k)     ←→  (f (g h k))     ⍝ 4-train
 (f g h k l)   ←→  (f g (h k l))   ⍝ 5-train, etc
 (f g h k l m) ←→  (f(g h(k l m))) ⍝ groups of 3 from the right, last could be 2
  f∘g B        ←→    f g B         ⍝ "compose" operator, useful in trains
A f∘g B        ←→  A f g B

Does that mean that for the sake of future readers, we shouldn't tell Oberon how to shorten it?

No, do as you normally would on PPCG. I'll remove that line after the expression reaches (what I believe to be) its shortest. It's an easy exercise - I don't think you personally would benefit from it.

I can get it down to 16, but I'm not using any of your tips, so maybe I'm way off.

@Adám well, you are using a train :) mine was similar but longer because I didn't think of ⎕ML

Isn't it "groups of 3 from the right"?

@Adám right, I don't know what I was thinking...

Use ⊥ to combine multiplication with addition
(a×b)+C  ->  a⊥b,C
(C)+a×b  ->  a⊥b,C
(a×b)-C  ->  a⊥b,-C

Assumptions:

a and b are terms that don't require further parentheses when used as a left argument
C is an expression that may need parentheses when used as a left argument
a b C evaluate to numeric scalars

Tricks for dealing with / and ⌿ in trains
When using trains you may want to use reductions f/ like sum +/ or even replicate reduction // . However, if your train has more parts to the left of the reduction you need parentheses to create an atop. Here are some tricks to save bytes.
Use 1∊ instead of monadic ∨/ or ∨⌿ on Boolean arrays
Task: Given two equal-length strings A and B, return 2 if any corresponding characters of A and B are equal, 0 otherwise. E.g. A←'abc' and B←'def' gives 0 and A←'abc' and B←'dec' gives 2.
A dfn solution may be A{2×∨/⍺=⍵}B but you want to shorten it by going tacit. A(2×∨/=)B is not going to work because the rules of train formation parse this as 2 (× ∨/ =) but you want 2 × (∨/=) .
Observe that ∨/ or ∨⌿ on a Boolean vector (∨/, or ∨⌿, for higher rank arrays) asks whether there is any 1 present, i.e. 1∊ , so we can write our train as 2×1∊= .
Note that ∊ ravels its right argument, so you cannot use it to reduce each row or column separately.
Use 1⊥ instead of monadic +/ or +⌿
Task: Given a list of lists L and an index N, return thrice the sum of the Nth list. E.g. L←(3 1 4)(2 7) and N←1 gives 24.
A dfn solution may be N{3×+/⍺⊃⍵}L but you want to shorten it by going tacit. N(3×+/⊃)L is not going to work because the rules of train formation parse this as 3(× +/ ⊃) but you want 3 × (+/⊃) .
Observe that evaluating a list of numbers in unary (base-1) is equivalent to summing the list because ∑{a, b, c, d} = a + b + c + d = (a × 1³) + (b × 1²) + (c × 1¹) + (d × 1⁰). Therefore +/a b c d is the same as 1⊥a b c d , and we can write our train as 3×1⊥⊃ .
Note that on higher-rank arguments, 1⊥ is equivalent to +⌿.
Use f.g instead of f/g with scalar and/or vector arguments
Task: Given a list L and a number N, return the range 1 thorough the number of minimum division remainder when the elements of L are divided by N. E.g. L←31 41 59 and N←7 gives 1 2 3.
A dfn solution may be N{⍳⌊/⍺|⍵}L but you want to shorten it by going tacit. N(⍳⌊/|)L is not going to work because the rules of train formation parse this as ⍳ (⌊/) | but you want ⍳ (⌊/|) .
The inner product A f.g B of scalar two functions when the arguments are scalars and/or vectors is the same as f/ A g B because both are (A[1] g B[1]) f (A[2] g B[2]) f (A[3] g B[3]) etc., so we can write our train as ⍳⌊.| .
Note that this does not work for higher-rank arrays.
Use ∊⊆ instead of / with Boolean left and simple vector right arguments
Task: Given a list L and a number N, filter the list so that only numbers greater than N remain. E.g. L←3 1 4 and N←1 gives 3 4.
A dfn solution may be N{(⍺<⍵)/⍵}L but you want to shorten it by going tacit. N(</⊢)L is not going to work because the binding rules will parse this as (</) ⊢ but you want / to be the function replicate rather than the operator reduce.
Dyadic ⊆ with a Boolean left argument partitions the right argument according to runs of 1s in the left argument, dropping elements indicated by 0s. This is almost what we want, save for the unwanted partitioning. However, we can get rid of the partitioning by applying monadic ∊. Thus {(⍺<⍵)/⍵} can become {∊(⍺<⍵)⊆⍵} and thus we can write our train as ∊<⊆⊢ .
Note that this does not work for higher-rank arrays.
Use ∊⍴¨ instead of / with non-Boolean left and simple vector right arguments
Task: Given a list L, replicate Nth item N times. E.g. L←3 1 4 gives 3 1 1 4 4 4.
A dfn solution may be {(⍳⍵)/⍵}L but you want to shorten it by going tacit. (⍳/⊢)L is not going to work because the binding rules will parse this as (⍳/) ⊢ but you want / to be the function replicate rather than the operator reduce.
Dyadic ⍴ combined with ¨ copies each element of the right argument according to the matching element in the left argument. This is almost what we want (e.g. 1 2 3⍴¨3 1 4 → (3)(1 1)(4 4 4)). Then, we can get rid of the nesting by applying monadic ∊. Thus {(⍳⍵)/⍵} can become {∊(⍳⍵)⍴¨⍵} and thus we can write our train as ∊⍳⍴¨⊢.
Note that this does not work for higher-rank arrays.
Use 0⊥ instead of ⊢/ or ⊢⌿ with numeric arguments
Task: Given a list L and a number N, multiply the N with the rightmost element of L. E.g. L←3 1 4 and N←2 gives 8.
A dfn solution may be N{⍺×⊢/⍵}L but you want to shorten it by going tacit. N(⊣×⊢/⊢)L is not going to work because the rules of train formation parse this as ⊣ (× ⊢/ ⊢) but you want ⊣ × (⊢/⊢) .
Observe that 0⊥ on a numeric array is the same as ⊢⌿ , so we can write our train as ⊣×0⊥⊢ .
Note that this selects the last major cell of higher-rank arrays.

Complex numbers
Often overlooked, they present wonderful opportunities to shorten expressions dealing with grids, mazes, fractals, or geometry.
0j1⊥¨    0j1⊥   ⍝ pair(s) of reals -> complex
11 9∘○¨  11 9○  ⍝ complex -> pair(s) of reals
|z0-z1          ⍝ distance between two points
0j1×z   0j¯1×z  ⍝ rotate by ±90° around (0,0)
0j1*⍳4          ⍝ the four cardinal directions
+z       -+z    ⍝ reflect across x or y axis
+\0,z           ⍝ sequence of steps -> path
¯2-/z           ⍝ path -> sequence of steps
0j1⊥¨n-⍳2⍴1+2×n ⍝ lattice centred on (0,0)

Indexing modulo vector length
⊃i⌽a is often shorter than the naive ⊃a[(≢a)|i] or a⊃⍨i|⍨≢a (where a is a vector and i is an integer, and ⎕io is 0)
a useful variation on this (thanks EriktheOutgolfer for pointing out) is: I↑Y⌽⍨I×X where Y is the concatenation of some length-I vectors and X is the index of the one we want to pick, for instance: 3↑'JanFeb...Dec'⌽⍨3×month

Generate A001057, A130472, and many variations
A001057 is a simple sequence of alternating integers, starting with 0, 1, -1, 2, -2, 3, -3, .... A130472 is its negation, 0, -1, 1, -2, 2, -3, 3, ....
APL has a surprisingly short way to generate nth term or first n terms:
nth term of A001057 (0-indexed)
⎕IO←1
-/⍳

Try it online!
nth term of A130472 (1-indexed)
⎕IO←0
-/⍳

Try it online!
first n terms of A001057, leading 0 removed (1, -1, 2, -2, ...)
⎕IO←1
-\⍳

Try it online!
first n terms of A130472 (0, -1, 1, -2, 2, ...)
⎕IO←0
-\⍳

Try it online!
Applying various primitive functions to these sequences can give many interesting results which are shorter than other alternatives:

1, 1, 2, 2, 3, 3, ...: With ⎕IO←1, |-\⍳n is shorter than n↑2/⍳n in explicit form
0, 1, 1, 2, 2, 3, ...: With ⎕IO←0, |-\⍳n is shorter than ⌈2÷⍨⍳n in explicit form
0, 1, 0, 2, 0, 3, ...: With any ⎕IO, |0⌊-\⍳n or -0⌊-\⍳n is shorter than any known alternatives, both tacit and explicit
0, -1, 0, -2, 0, -3, ...: With any ⎕IO, 0⌊-\⍳n
1, 0, 2, 0, 3, 0, 4, ...: With ⎕IO←1, 0⌈-\⍳n
0, 1, 1, 0 repeated: With ⎕IO←0, 2|-\⍳n
1, 1, 0, 0 repeated: With ⎕IO←1, 2|-\⍳n
Reverse odd then forward even, e.g. 7 → 5 3 1 0 2 4 6: ⍋-\⍳n with ⎕IO←0. ⎕IO←1 gives 7 → 6 4 2 1 3 5 7.
Permutation of 0 to n-1, alternating front and end, e.g. 7 → 0 6 1 5 2 4 3: n|-\⍳n with ⎕IO←0.
First n terms of A002620, 0, 1, 2, 4, 6, 9, 12, 16, 20, ...: -\-\⍳n with ⎕IO←0 (⎕IO←1 gives same sequence with leading zero removed), which is shorter than ⌊×⍨2÷⍨⍳n with ⎕IO←1.

Use ⍨
Avoid parentheses
⍨ (Commute) can save you bytes by avoiding parentheses. Whenever you have a function where the left argument needs to be parenthesised and the right argument does not, you can save a byte, e.g. (A<B)÷C → C÷⍨A<B.
Double arrays
To append a copy of an array to its end, use ,⍨A or ⍪⍨A.
Double numbers
Instead of using 2∘× to double, you can use +⍨ since it adds the argument to itself: 1+2∘× → 1++⍨.
Square numbers
Instead of using 2*⍨Y to square, you can use ×⍨Y since it multiplies the argument with itself: 2*⍨A+B → ×⍨A+B.
Random permutation
?⍨N will give you a random permutation of length N.
Self-classify
Find the indices of the first occurrence of each major cell with ⍳⍨A
Count trailing 1s in a Boolean vector
Instead of +/∧\⌽B to count how many trailing 1s there are in N you can use ⊥⍨.
Reverse composition
A f∘g B is A f g B, but if you want (g A) f B, use f⍨∘g⍨.
Reverse reduce
f/ a1 a2 a3 is a1 f (a2 f a3). If you want (a1 f a2) f a3, use f⍨/⌽.
Reverse scan
f\ A B C is
 A  (A f B)  (A f (B f C)).
f⍨/∘⌽¨,\ A B C is
 A  (A f B)  ((A f B) f C).
f⍨\⌽ A B C is
 ((A f B) f C)  (B f C)  C.
⌽f/∘⌽¨,\⌽ A B C. is
 (A f (B f C))  (B f C)  C.

Generate all nonempty subsequences
I recently discovered the expression (⊢,,¨)\ in this answer. If applied to a simple numeric or char vector, it does the following:

(⊢,,¨)/ v gives all subsequences of v which include the last item.

  (⊢,,¨)/ '1234'
→ '1' (⊢,,¨) '2' (⊢,,¨) '3' (⊢,,¨) '4'
→ '1' (⊢,,¨) '2' (⊢,,¨) '4' '34'
→ '1' (⊢,,¨) '4' '34' '24' '234'
→ '4' '34' '24' '234' '14' '134' '124' '1234'

(⊢,,¨)\ v applies (⊢,,¨)/ to each prefix of v, giving all non-empty subsequences as a list of lists of vectors.

  (⊢,,¨)\ '1234'
→ '1' ('2' '12') ('3' '23' '13' '123') ('4' '34' '24' '234' '14' '134' '124' '1234')

The result can be flattened once using ⊃,/, which gives the list of nonempty subsequences.
The order is the one imposed by the binary digits of 0..2^n-1, grouped by the last item. You can use it whenever it suffices to generate all subsequences in any order. An interesting feature is that the original vector comes last, so you can also test e.g. "the original satisfies something but any smaller subsequence doesn't" using </.
Note that the order is different from plain binary/lexicographic/shortlex order, so it is hard to use when the challenge requires specific ordering of subsequences.
A nice application of this trick is "extract all subsequences of digits of a number": ⍎⍕(⊢,,¨)\⍕n. Figuring out how it works is left as an exercise to the reader. :)

(⊢,,¨)/ can be used to generate all subsequences (including empty), with the same order as binary order:
 ¯1↓¨¨(⊢,,¨)/'1234',0
→ '' '4' '3' '34' '2' '24' '23' '234' '1' '14' '13' '134' '12' '124' '123' '1234'

It's longer than the scan version, but it fits in a train better and might be useful when the order is important.

Very nice, is there a J equivalent of that subsequence trick?

@Jonah Inception? :P

Damn, hate being outgolfed by my former self.

@Jonah Actually, if you want to reduce over the subsequences instead of collecting them, J works equally well without explicit boxing.

Enumerate the characters in a string without ⍳≢
Task: Given two strings, S and T, list the indices of their concatenation. E.g. S←'abcd' and T←'xyz' gives 1 2 3 4 5 6 7.
A dfn solution may be S{⍳≢⍺,⍵}T but you want to shorten it by going tacit. ⍳≢, is not going to work because the train parsing rules will parse this as (⍳)≢(,) but you want (⍳≢),.
Dyadic ⍋ with an empty left argument grades simple character arrays according to their current order, which is the same as ⍳≢. Thus {⍳≢⍺,⍵}  can become {⍬⍋⍺,⍵} , so we can write our train as ⍬⍋, .
Note that this does not work for numeric or mixed arrays.

Wow, didn't know that was a thing.

Constant functions
=⍨ and ≠⍨ thanks to ngn.
Sometimes you just need a single value for each element of a list. While you might be tempted to use {value}¨ (it is shorter to use value⊣¨ or value⍨¨), you can get even shorter (using ⎕IO←0) for some common values:
¯1s with ⍬⍸list
0s with ⍬⍳list
1s with ⍬⍷list
Note that these only work on lists (though they may be nested). For higher-rank simple arrays, you can use the following to get all 0s and all 1s:
1s with =⍨
0s with ≠⍨
If you set ⎕ML←0, all numbers can be made into zeros (as if 0×) with:
∊
If you only need a single number, you may be able to use monadic ≡ to get 1 or 0 instead of using 1⊣ or 0⊣.
Note that Dyalog APL 18.0 added a constant operator which derives an ambivalent function that always returns the constant.

"Sometimes you just need a single value for each element of a list." - It may be noteworthy: when that value is the first element of the list, you can use ⊣\

@ngn I'd say that ⊣ and ⊢ with / and ⌿ merit a post of their own.

Constructing a long complex string (char vector)
Original idea from @ngn.
We can (ab)use rotation n⌽ and enlist ∊ to shorten multiple concatenations:
'(',(⍺∇r),'|',(⍺∇s),')'
  → Rotate the last ')' to front and apply 1⌽
1⌽')(',(⍺∇r),'|',(⍺∇s)  (-1 byte)
  → We don't need parens at the end
1⌽')(',(⍺∇r),'|',⍺∇s    (-3 bytes in total)
  → Remove some concats(,) to use stranding instead and enlist(∊) later
1⌽∊')('(⍺∇r)'|',⍺∇s     (-4 bytes in total)

Note that we can't remove the last concat (,) in this case; otherwise the recursive call would be screwed up.
The ∊ trick can also be used to shorten construction of numeric arrays:
0,(⍳5),0
  →
∊0(⍳5)0   (-1 byte)

⎕FMT, the formatting function
Dyalog documentation page
In user's answer to ascii art reflection,, they used an interesting builtin called ⎕FMT to split text on a carriage return \r. I feel it has potential to save a lot of bytes in ascii-art and string challenges. It works very well with specific output/input specifications.
Converting carriage return separated input directly to a matrix
A string with carriage returns can be converted directly to the matrix using monadic ⎕FMT:
      ⎕FMT'Hello'(⎕UCS 13)'There'
 Hello
 There
      ⍴⎕FMT'Hello'(⎕UCS 13)'There'
2 7

It automatically pads the matrix with spaces, just like ↑(mix).

⎕FMT can take arrays as arguments, and can apply a format specification to each of it's elements. However, the rank of the array must not exceed 2, and the format specifier must be a proper match for the elements.
There are multiple format specifiers allowed, which give different results:
rAw     Alphanumeric format
rEw.s   Scaled format
rqFw.d  Decimal format
rqG⍞pattern⍞    Pattern
rqIw    Integer format
Tn  Absolute tabulation
Xn  Relative tabulation
⍞t⍞     Text insertion

Where:
r   is an optional repetition factor indicating that the format phrase is to be applied to r columns of Y
q   is an optional usage of qualifiers or affixtures from those described below.
w   is an integer value specifying the total field width per column of Y, including any affixtures.
s   is an integer value specifying the number of significant digits in Scaled format; s must be less than w-1
d   is an integer value specifying the number of places of decimal in Decimal format; d must be less than w.
n   is an integer value specifying a tab position relative to the notional left margin (for T-format) or relative to the last formatted position (for X-format) at which to begin the next format.
t   is any arbitrary text excluding the surrounding character pair.  Double quotes imply a single quote in the result.

This allows a lot of useful tricks like format strings, ASCII tabulation, representation of arbitrary precision floating point values, and allow you to apply them cyclically to the contents of any matrix you choose. ⎕R might be simpler to use in the case of a single line character vector, however.
These letters and their modifiers are discussed in more depth in the Documentation.

Base Conversions
The function b⊥v, where b is a numeric base and v is a vector of digit values in that base, converts the vector v into its decimal (base-10) equivalent. If you want to convert a base-10 number into base b, a naïve approach would be to try to use ⊤, but this requires figuring out (or calculating) how many digits the number would require in base b. Instead, use the Power operator ⍣ with a right operand of ¯1: (b∘⊥⍣¯1). This will invert the convert-to-decimal function to convert back to base b with exactly the minimum necessary number of digits in the base-b representation.
      2⊥1 1 0 1            ⍝ Convert the base-2 digit vector 1 1 0 1 to base-10
13
      (2∘⊥⍣¯1)13           ⍝ Convert 13 to its base-2 digit vector
1 1 0 1

Often, you don't need the ∘:  2(⊥⍣¯1)13

Miscellaneous ideas
Cross-post of my own J tip, because APL and J are so closely related that the two can share many ideas.
If you're facing -⍨/, try ¯1⊥ instead
A common reason to use -⍨/ is to reverse-subtract over a length-2 axis, e.g. given a 2-element array x y, compute y-x.
If this is the case, ¯1⊥ is an equivalent expression; just like 2⊥x y computes 2x+y, ¯1⊥x y computes -x+y. While the two expressions have same length, ¯1⊥ is more likely to fit well in trains (due to being a dyadic primitive function with a left arg, vs -⍨/ being a monadic derived function).
Note that, if you apply it to longer axis, ¯1⊥ gives you more similar result to -/ (alternating sum), with negated result when the length is even.
Construct a boolean square matrix where the border is ones/zeros and the interior is the opposite
This is mainly for large fixed-size matrices, say 6 by 6.
The matrix
1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

can be generated by ∘.∨⍨ -ing the boolean vector 1 0 0 0 0 1. The shortest known way to generate that vector is 6⍴5↑1, so we can get the matrix above in just 9 bytes:
∘.∨⍨6⍴5↑1

We can also get negation of it at no extra cost, by swapping ∨ with ⍱! (Remember that APL has NOR ⍱ and NAND ⍲; they are rarely needed, but definitely are a byte saver when we do need them.)

Repeat with intermediate results
This is originally @ngn's suggestion on an APL answer of mine.
While APL has the power operator ⍣ which can repeat a function certain number of times, it cannot collect intermediate results on its own (unlike J's ^: allowing <n or i.n right operand to do the job). Usually one would collect the intermediate results by using an auxiliary variable with modified assignment, or "hack" the left operand of ⍣ to something like (⊣/,f¨)⍣n⊂x, or naively write down the iterations like {⍵(f⍵)(f f⍵)}x.
But there is a clever way using scan ⊢∘f\. Since x ⊢∘f y ignores x and applies f to y monadically, such a scan over n copies of x (enclosed if x is non-scalar) gives the results of f applied to x 0..n-1 times:
  ⊢∘f\n⍴⊂x
→ ⊢∘f\x x x ... x
→ (x)(x ⊢∘f x)(x ⊢∘f x ⊢∘f x) ...
→ x(f x)(f f x)(f⍣3⊢x) ... (f⍣(n-1)⊢x)

This is shorter than several alternatives (assume x is a complex expression):
{⍵(f⍵)(f f⍵)}x  ⍝ way too long for 2nd or higher iterations
(⊣/,f¨)⍣n⊂x     ⍝ shorter, but still long
⊢∘f\n⍴⊂x        ⍝ shortest

Interestingly, the scan expression ties when compared to various expressions that collect only zeroth and first iterations:
{⍵(f⍵)}x  ⍝ dfn
(⊂,⊂∘f)x  ⍝ tacit
y(f y←x)  ⍝ intermediate assignment; this wins if f is a single primitive
⊢∘f\2⍴⊂x  ⍝ scan

Also note that ⊢∘f\n⍴⊂ without the right arg is also a valid train.

As of Dyalog 18.0, you can write f⍤⊢\ in place of ⊢∘f\, which may or may not save bytes depending on the structure of f. (The conversion never adds bytes, so f⍤⊢\ can be universally used.)

some times is better not be clever

When you need to encode some arbitrary data (as is common in the Kolmogorov complexity questions), it can be achieved with a string of characters from the atomic vector ⎕AV.
For example, to encode the array 256 13 16 127 128 168 192 in Dyalog APL:
⎕AV[256 13 16 127 128 168 192]      ⍝ the result is: ⍣%⍵⊣⌷∧⊤

Then to decode it:
⎕AV⍳'⍣%⍵⊣⌷∧⊤'

Adám's SBCS (single byte character set) also allows to encode some other characters (⊆⍠⍤⌸⌺⍸) as a single byte.

This, of course, only works if all your integers are 1≤n≤256 (or 0≤n≤255 with ⎕IO←0). If all your integers are 1≤n≤26 (or 0≤n≤25 with ⎕IO←0), you can use ⎕A instead of ⎕AV.

Another thing to note is that, if you're unlucky, you will get some chars like linefeed which can't be embedded in the string literal.

Well, I used it like this ∊(5 5 5⊤⊢)¯6+⎕AV⍳'ÏSSS9i⌶⌶⌶⌶RSÐSS'. In this case each byte is decoded into three numbers in range 0≤k<5. So you get 45 numbers from 15 characters. But I had to use an offset -6 because I was "unlucky". (And, of course, added logic worsens the "compression rate".)

…Another trick here is to pick the string so that to avoid using ¨, of course.

Encode into base b without digit limit
b⊥⍣¯1
Explanation:
  ⍣¯1 Do the inverse of...
b⊥    Decoding from base b (which is encoding to base b with no digit limit!!!)

what is digit limit?

@thejonymyster none, it's how many digits it can get

i had no idea apl normally had a digit limit for base conversion. that's insane

Because you need to specify a mixed radix there's a limit, for example 2⊤11 is 1

Also high minus is the negative number identifier, which is different from monadic - (negation)