text:
Calculate the Delacorte Number of a square

Challenge: implement calculation of a Delacorte Number in any language. Shortest code wins.
For a given square matrix of distinct integers 1..n² (possible side length n at least between 3 and 27), its Delacorte Number is the sum of the products gcd(a, b) × distance²(a, b) for each distinct pair of integers {a, b}.
The following example shows a 3×3 square with a Delacorte Number of 160.
3 2 9
4 1 8
5 6 7

In this square we have 36 distinct pairs to calculate, for example the pair 4 and 6: gcd(4, 6) × distance²(4, 6) = 4
Another example square for testing - this has a Delacorte Number of 5957:
10  8 11 14 12
21  4 19  7  9
 5 13 23  1 16
18  3 17  2 15
24 22 25  6 20

Delacorte Numbers are taken from this programming contest - see there for further details... The contest ended in January 2015. It was great fun!
Rules:
Necessary line breaks count as 1 char. You may post your golfed solution with line breaks, but they are only counted if necessary in that language.
You can choose how to handle input and output and you don't have to count the necessary framework of your language, like standard-includes or main function headers. Only the actual code counts (including shortcut/alias definitions), like in this C# example:
namespace System
{
    using Collections.Generic;
    using I=Int32; //this complete line counts
    class Delacorte
    {
        static I l(I[]a){return a.Length;} //of course this complete line counts

        static void CalculateSquare(int[] a, out int r)
        {
            r=0;for(I i=l(a);i-->0;)r+=a[i]; //here only this line counts
        }

        static void Main()
        {
            int result;
            CalculateSquare(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, out result);
            Console.Write(result); //should output 140 for the example
            Console.ReadKey();
        }
    }
}

You may also input the square as 2-dimensional array or from a prompt or as string or some standard collection type. A 2-dimensional array is the only way not having to calculate the side length of the square yourself.
A sub-function for the actual work is not required, you could also put the code directly within Main().
Even more preparation is allowed for free, like here:
using System;
unsafe class Delacorte
{
    static void CalculateSquare(int* a, out int r)
    {
        r=0;while(*a>0)r+=*a++; //only this line counts
    }

    static void Main()
    {
        var input = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; //adding a terminator
        int result;
        fixed (int* a = &input[0]) //necessary in C#
            CalculateSquare(a, out result);
        Console.Write(result);
        Console.ReadKey();
    }
}

If you are unsure whether your lengthy preparation is in the spirit of these rules or could be called cheating, just ask :)

Sounds like, in case of Python, all includes are for free? This can cause some weird optimizations...

@Falko, the question is, what are standard-includes? Please try to understand the spirit of the rules and adapt them to your language. So, no: see my using example - if it is used to include a library because otherwise you could not call some function, it is free. If you use it to define some short alias for anything, the whole instruction counts.

@Optimizer: The meaning of the distance function is somewhat hidden in the link: It's the square of the euclidean distance between the two fields.

@Optimizer, instead of exactly defining it, I gave an example, so you can be sure what is meant. I thought that is enough and added fun...

And I must say that although its a legit question, it seems like that you have posted it here to finally be able to enter that contest ;)

yes, of course, I'll take the shortest implementation (which will naturally also be the fastest), put a loop around it and run some brute-force ;-) ... I added a link to wikipedia for the distance... and btw., the mentioned contest is great fun and much harder than it seems.

Can I get the matrix as a single list as well as the size of the side of matrix from input too ?

Okay. Can I rather treat the length calculation as part of preparations ?

Let us continue this discussion in chat.

The contest website is up again, I updated the link in the text.

In case someone liked the AZsPCs contest: the next one starts in a few days!

In case someone liked the AZsPCs contest: the next one starts soon! ;-)

In case someone liked the AZsPCs contest: the next one starts on Saturday!

APL (38)
{.5×+/∊∘.{(∨/Z[⍺⍵])×+/⊃×⍨⍺-⍵}⍨⊂¨⍳⍴Z←⍵}

This is a function that takes a matrix as its right argument, like so:
      sq5←↑(10 8 11 14 12)(21 4 19 7 9)(5 13 23 1 16)(18 3 17 2 15)(24 22 25 6 20)
      sq5
10  8 11 14 12
21  4 19  7  9
 5 13 23  1 16
18  3 17  2 15
24 22 25  6 20
      {.5×+/∊∘.{(∨/Z[⍺⍵])×+/⊃×⍨⍺-⍵}⍨⊂¨⍳⍴Z←⍵}sq5
5957

Explanation:

⊂¨⍳⍴Z←⍵: store the matrix in Z. Make a list of each possible pair of coordinates in Z.
∘.{...}⍨: for each pair of coordinates, combined with each pair of coordinates:

+/⊃×⍨⍺-⍵: calculate distance^2: subtract the first pair of coordinates from the second, multiply both by themselves and sum the result
∨/Z[⍺⍵]: get the number in Z for both pairs of coordinates, and find the GCD
×: multiply them by each other

+/∊: sum the elements of the result of that
.5×: multiply by 0.5 (because we counted each nonzero pair twice earlier)

This would be 72 bytes if we count using UTF-8 bytes.

@KennyTM: the APL charset fits within a byte. Encodings exist that use this. APL predates Unicode by decades. It seems to be accepted on this site to count APL characters as bytes, as long as no Unicode characters are used. (i.e. using Unicode codepoints to encode strings, or something.)

@marinus, that sounds reasonable. What do you think about the unicode chars in Mathematica?

@maf-soft: well, if there is an existing encoding by which all of the characters used fit within a byte (so that includes both the 'special' and the 'normal' characters, so there can't be more than 256 unique characters), then it can be counted as one byte per character. If not, then it can't. However, if Mathematica uses less than 128 unique Unicode characters, they can be trivially mapped into the upper half of the byte, with ASCII in the lower half. [1/2].

@maf-soft: this would be a novel encoding (~ "language"), though, so you'd need to provide a translator program, and you could only use it on questions that are newer than your translator program, by the rule that states you can only answer questions in languages that predate the question (this to prevent someone defining a language with an 1-byte command to exactly solve the question). [2/2]

Python - 128 112 90 89 88
Preparation:
import pylab as pl
from fractions import gcd
from numpy.linalg import norm
from itertools import product

A = pl.array([
    [10,  8, 11, 14, 12],
    [21,  4, 19,  7,  9],
    [ 5, 13, 23,  1, 16],
    [18,  3, 17,  2, 15],
    [24, 22, 25,  6, 20]])

Computing the Delacorte Number (the line that counts):
D=sum(gcd(A[i,j],A[m,n])*norm([m-i,n-j])**2for j,n,i,m in product(*[range(len(A))]*4))/2

Output:
print D

Result:
5957

You can collapse both for loops into a single generator and sum it once. Also, you can save P(R,R) to a variable by *x,=product(R,R), using the starred assignment to make a copy. Even better, you can make it be the four-fold product product(R,R,R,R) and just do for j,n,i,m in product(*[R]*4).

@xnor: Great! *[R]*4 is what I was looking for by myself but couldn't get to work.

seeing as your preparation doesn't count towards the byte count, can't you do something like from fractions import gcd as g to save bytes in the important section?

Mathematica (83 82 79 69 67 66)
Preparation
a={{10,8,11,14,12},{21,4,19,7,9},{5,13,23,1,16},{18,3,17,2,15},{24,22,25,6,20}}

Code
#/2&@@Tr[ArrayRules@a~Tuples~2/.{t_->u_,v_->w_}->u~GCD~w#.#&[t-v]]

If we count using Unicode characters: 62:
Tr[ArrayRules@a~Tuples~2/.{t_u_,v_w_}u~GCD~w#.#&[t-v]]〚1〛/2

You can use UTF version of '->`: 

@swish -> takes 2 characters and  takes 1 character, however, -> takes 2 bytes and  takes 3 bytes in UTF-8. So it may be longer depending on the metrics.

Well look at APL solution, so I guess the metric is in characters on this one ;)

@swish That's something OP should clarify as UTF-8 bytes is the default if not stated :)

@KennyTM - I'm not sure what's best. I'd like to follow what's common on this site. Currently I have no time to find out. Could someone help out with some links? You can also use the chat mentioned in the OP comments.

@maf-soft: The only relevant post I could find is http://meta.codegolf.stackexchange.com/questions/942/scoring-code-golf-bytes-vs-characters, but it doesn't really suggest what to do with APL by default.

@maf-soft The default is to count bytes, but to use any byte encoding (This means that the APL answer is fine, but the alternate answer above would have a higher count). See Peter Taylor's answer to that meta post. I've seen some answers that are written purely in hexadecimal :)

Pyth 43
This answer could almost certainly be golfed further; I particularly don't like the distance calculation.
K^lJ.5VJFdUN~Z*i@JN@Jd+^-/dK/NK2^-%dK%NK2;Z

To set this up, store the linear-ized array in the variable J. You can do this by writing:
J[3 2 9 4 1 8 5 6 7)

Try it online.
Outputs a float. I think this is legitimate, please tell me if I've broken a rule :)
Explanation:
                                             : Z=0 (implicit)
K^lJ.5                                       : K=sqrt(len(J))
      VJ                                     : for N in range(len(J))
        FdUN                                 : for d in range(N)
            ~Z*                              : Z+= the product of
               i@JN@Jd                       : GCD(J[N],J[d])
                      +^-/dK/NK2^-%dK%NK2    : (d/K-N/K)^2 + (d%K-N%K)^2 (distance)
                                         ;Z  : end all loops, and print Z

Wow, I finally beat Pyth with APL.

@marinus Haha, I'm still trying, but I think you've got me beat, at least :)

Wow, this is crazy. I'm reading the doc.txt now but I find it really hard to read!

@rubik At least it isn't APL :D The doc isn't 100% accurate because this whole language is mantained by one guy: isaacg. If you have questions, feel free to ask me/him in chat :)

CJam, 55
q~:Q__,mqi:L;m*{_~{_@\%}h;\[Qf#_Lf/\Lf%]{~-_*}/+*}%:+2/

Takes the matrix as STDIN in the following format:
[10  8 11 14 12
 21  4 19  7  9
  5 13 23  1 16
 18  3 17  2 15
 24 22 25  6 20]

Try it online here

I think you could hard-code the matrix for free and use {} to make a block rather than use stdin. Also, are you dumping the matrix into a one-dimensional array? I think you can take the matrix already formatted, see the OP's examples. (I don't know CJam well, so take this with a grain of salt ;) )

Reading the matrix and converting it to single list is the q~] part. which is shorter as compared to when i hard code it and use a block (I guess)


text:
Generalized Quine Generator
The Challenge
In this challenge, you specify a source language S and a target language T. Your task is to write the following program P in the language S. If a valid program Q in the language T is given as input to P, it will output a valid program R in the language T which takes no input and outputs Q(R), that is, the program Q applied to the source code of R. In addition, you should present in your answer a nontrivial example program Q (the more interesting, the better, although you score no points for this), the resulting program R, and the output of R. This is code-golf, so the shortest code for P wins.
In other words, this is a challenge about writing a "universal quine constructor" that can create arbitrary types of generalized quines.
Clarifications

Your source and target languages may be identical.
The program P should take one string as input (from STDIN or equivalent), and output one string (to STDOUT or equivalent), as should every output program R.
The input programs Q should also transform a string to another string, but their form is more flexible: they can be string-to-string functions, code snippets that modify a variable with a certain name, snippets that modify the data stack if your target language has one, etc. You can also further restrict the form of the Q's by stating that, for example, they may not contain any comments. However, you must be able to implement any computable string-to-string function as an input program Q, and you must explicitly state how they function and what further constraints you place on them.
The output program R should really be a (generalized) quine, so it must not read any input (user input, files etc.) unless Q does so.
Standard loopholes are disallowed.

An Example
Suppose I choose Python as my source language, and Haskell as my target language, and I further require that the input program should be a one-line definition of a String -> String function named f. If I give the string-reversing program
f x = reverse x

as input to my Python program P, it will output the source code of another Haskell program R. This program prints to STDOUT the source code of R, but reversed. If P is given the identity function
f x = x

as input, the output program R is a quine.

Source = Target = CJam, 19 17 16 bytes
{`"_~"+}`)q\"_~"

This assumes that the input program Q (given on STDIN) is some CJam snippet which expects a string on the top of the stack and leaves another string on top of the stack.
Test it here.
Examples

The identity would just be an empty snippet, so leaving STDIN empty prints
{`"_~"+}_~

Which is the standard quine, with an additional +.
To reverse a string in CJam, you can use W%, so putting that on STDIN, this yields:
{`"_~"+W%}_~

which we can run to obtain
~_}%W+"~_"`{

As a third example, say we use a snippet which intersperses a string with spaces: ' *. Running P with that as input, we get
{`"_~"+' *}_~

which in turn prints
{ ` " _ ~ " + '   * } _ ~

It now also works if Q contains line breaks (although that's never necessary in CJam). Here is a program with a line break, which removes all line breaks from a string (in an unnecessarily convoluted way - split into lines, then join):
N/
""
*

This results in the following R:
{`"_~"+N/
""
*}_~

which in turn prints
{`"_~"+N/""*}_~

Explanation
Let's look at the produced output first:
The standard CJam quine is
{`"_~"}_~

It works as follows:

Push the block {`"_~"}.
Duplicate it with _.
Execute the copy with ~.
Now inside the block, ` turns the first block into its string representation.
"_~" pushes the two characters of the source that are not part of the block (and hence missing from the string representation).
The two strings are printed back to back at the end of the program.

In the basic quine the ` is unnecessary, because if you just leave the block as it is, it's printed all the same at the end of the program.
The output of my program P is a modified version of this snippet. First, I've added a + to the block, which concatenates the two strings into one string containing the entire source. Note that this will be true no matter what I do inside the block, because that will all get added to the string representation obtained with `. Now I can simply put the program/snippet Q inside the block after the +, so that it can modify the source string before it is printed. Again, since Q goes inside the block, it will be part of said source string.
In summary, P prints
{`"_~"+Q}_~

Now, for how I go about constructing this output in P:
{`"_~"+}         "Push the block without Q.";
        `        "Turn it into a string. This is shorter than writing a string right away,
                  because I'd have to escape the quotes, and I'd need two quotes instead of
                  one backtick.";
         )       "Pop off the last character (the brace) and push it on the stack.";
          q      "Read input Q.";
           \     "Swap Q with the brace.";
            "_~" "Push the final two characters.";

The four strings are printed automatically (back-to-back) at the end of the program.

Well, this was fast! And certainly hard to beat. The explanation is nice too.

Where did you learn that W% reverses? https://dl.dropboxusercontent.com/u/15495351/cjam.pdf doesn't have it

Is there a more complete list of methods?

@FarazMasroor https://sourceforge.net/p/cjam/wiki/Basic%20operators/#percent (no. 3) ... it's a feature borrowed from GolfScript and at some point someone told me that's how it works in GolfScript. It appears to be such a common idiom that it's some weird implicit knowledge every CJam/GS user has but which isn't actually explained in a lot places. (For more, not thoroughly documented operators, see https://sourceforge.net/p/cjam/wiki/Operators/)

Haskell expressions → Haskell expressions, 41 bytes
((++)<*>show).('(':).(++")$(++)<*>show$")

Try it online!
How it works
P $ "Q" = ((++)<*>show).('(':).(++")$(++)<*>show$") $ "Q" constructs "R" by

(++")$(++)<*>show$"): appending the string ")$(++)<*>show$",
('(':): prepending the character '(', and
(++)<*>show (= \x->x++show x): appending a quoted version of that,

resulting in "R" = "(Q)$(++)<*>show$\"(Q)$(++)<*>show$\"".
R = (Q)$(++)<*>show$"(Q)$(++)<*>show$" works by

taking the string "(Q)$(++)<*>show$",
(++)<*>show: appending a quoted version of that,
applying Q to that,

resulting in Q "(Q)$(++)<*>show$\"(Q)$(++)<*>show$\"" = Q "R".
(The parens around Q are necessary because Q might contain $ just as easily as R does, and $ is unfortunately right-associative.)
Demo
λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "id"
(id)$(++)<*>show$"(id)$(++)<*>show$"
λ> putStrLn $ (id)$(++)<*>show$"(id)$(++)<*>show$"
(id)$(++)<*>show$"(id)$(++)<*>show$"
λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "reverse"
(reverse)$(++)<*>show$"(reverse)$(++)<*>show$"
λ> putStrLn $ (reverse)$(++)<*>show$"(reverse)$(++)<*>show$"
"$wohs>*<)++($)esrever("$wohs>*<)++($)esrever(
λ> putStrLn $ ((++)<*>show).('(':).(++")$(++)<*>show$") $ "length"
(length)$(++)<*>show$"(length)$(++)<*>show$"
λ> print $ (length)$(++)<*>show$"(length)$(++)<*>show$"
44

Not just $ needs the parentheses, but also trailing let, do or lambda expressions.

@ØrjanJohansen Right, but I could have defined a language subset that disallows unparenthesized lambda/let/if/case/do if I don’t emit them myself. Perhaps it’s just as well that I didn’t have to.

Jelly → 7, 9 bytes
“ṚƓ^ṾṂ’³3

Try it online!
Q is a 7 function (i.e. that doesn't look beyond the top stack element, and does I/O via the stack), and is given as a command-line argument.
Explanation
The 7 program
The universal quine constructor in 7 that I use here is:
717162234430…3

The first thing to note is that the leading 7 is the equivalent of leading whitespace, and doesn't have any effect on the program. The only reason it's there is to obey PPCG's rules against literal-only quines (it's encoded by the second 1 in the program rather than itself).
The rest of the program is a single stack element (it has balanced 7s and 6s), which does the following when run:
717162234430…3
 1716           Push a stack element "7" onto the stack
     2          Copy it
      23        Pop and output one of the copies (selecting format 7)
        4430    Prepend it to the top of stack
             3  Output it

In other words, this stack element is a program that prints the top of the stack, with 7 prepended, in output format 7 (which means "print literally, using the same encoding as the source code", and thus is clearly the best encoding for quines). It's fairly fortunate here that we can reuse the literal 7 for two purposes (the output format, and the leading whitespace.) Clearly, by inserting something just before the final 3, we can output a function of 7 + the input, rather than just outputting 7 and the input directly.
How does this stack element get at its own source code? Well, when the end of the program is reached, 7 evals the top stack element by default. However, it's not actually popped from the stack in the process, so the stack element literal that was evalled is still there. (In other words, the program isn't reading its own source – as evidenced by the fact that it's unable to see the 7 at the start of the program, which is a stack element separator rather than part of a literal – but rather, it consists mostly of a literal that gets evalled by default.)
The Jelly program
This is perhaps one of the least Jelly-like Jelly programs I've written; it consists of three nilads (“ṚƓ^ṾṂ’, ³, 3), which are just output in sequence because no operations are performed on them. The 3 is obvious enough, just being an integer constant. The ³ is also simple if you know Jelly: it's Jelly's explicit notation for the first command-line argument (which is where Jelly typically takes its input). The rest of the Jelly program represents the bulk of my 7 universal quine constructor: by exploiting the fact that all the commands in 7 can be represented using ASCII digits, we can interpret 717162234430 not as a series of commands, or even as an octal number (like it conceptually is), but as a decimal number, meaning that we don't need any special formatting for the output. That decimal number becomes “ṚƓ^ṾṂ’ in Jelly's compressed integer notation.
Example
If we give 24053 as program Q, we'll get the following output:
717162234430240533

Try it online!
2405 concatenates the top stack element to itself:
2405   Stack   Explanation
       x
2      x|x     Duplicate top of stack
 4     x||x    Swap two stack elements, with an empty element between
  0    x|(X)   Escape the top stack element, then concatenate the top two
   5   xx      Execute the top stack element

(The last step might look a little confusing; what's happening is that escaping a stack element converts each command in it from "run this command" to "append this command to the top of the stack", so each command appends itself to the original top stack element as it runs.)
As such, running the resulting program R gives us two copies of R:
7171622344302405371716223443024053

Source = Target = JavaScript, 66
console.log("function a(){console.log("+prompt()+"(a+'a()'))}a()")

Assumptions for Q:

Q should be a string-to-string JavaScript anonymous function.

Examples:

Reverse. Q = function(s) { return s.split('').reverse().join(''); }

In this case, P(Q) (or R) will be: function a(){console.log(function(s) { return s.split('').reverse().join(''); }(a+'a()'))}a(), and by executing it, we will get: )(a}))')(a'+a(} ;)''(nioj.)(esrever.)''(tilps.s nruter { )s(noitcnuf(gol.elosnoc{)(a noitcnuf which is exactly the same as Q(R).

Identity. Q = function(s) { return s; }

in this case, P(Q) (or R) will be: function a(){console.log(function(s) { return s; }(a+'a()'))}a() which is a JavaScript Quine. Needless to say, Q(R) will be the same, since Q is the Identity function.

Some notes:
STDIN in JavaScript is traditionally prompt(), however, I allowed myself to refrain from the tradition of alert() as STDOUT, in order to make the process of run output as a progrem using copy-paste easier. (I do realize I can save up to 12 characters when changing to alert()).
I can also make things much shorter in ES6, but I want to stay with Native JavaScript for now. I'm considering submitting a S=Scala,T=ECMA6 answer in future, just for the experience.
I also realize JavaScript can almost never beat CJam in code-golf, but I had to take this challenge! It was surly a fun one.

Thanks! It would indeed be cool to have an entry with different source and target languages.

CJam → CJam, 13 bytes
{`"_~"+7}_~qt

Try it online!
The input Q should be a code snippet that modifies the only string in the stack. Q is read from stdin.
Example
Input:
S*W%

It adds a space between every two characters, and reverses the string.
Output:
{`"_~"+S*W%}_~

Output of the generalized quine:
~ _ } % W * S + " ~ _ " ` {

Explanation
{`"_~"+7}_~      e# Evaluate a generalized quine in CJam that only appends a 7.
q                e# Read the input.
t                e# Replace the 7th character (0-based) with the input.

It firstly evaluates the quine, so we can get its string representation without unnecessary double quotes. Then replace the payload with the input.
It could be {`"_~"+ }_~7qt where the space is the placeholder of the payload. But changing the payload to 7 saves a byte.

RProgN 2, 11 bytes
'{`{.%s}{'F

Program Explanation
'{`{.%s}{'F
'{`{.%s}{'  # Push the string "{`{.%s}{" to the stack.
          F # Format the input with the top of the stack as a template. Which produces {`{.<INPUT>}{

Quine Explanation
The quine that's produced is simple, yet uses the functionality of unmatched function handlers in RProgN2 to create a short and sweet quine, called a "Looping" quine. It's a surprisingly similar concept to a ><> quine.
{`{.}{
{`{.}   # Push the function {`{.} to the stack.
     {  # Try to define a new function, fail, loop back to index 1. (Which in turn, skips the function definition.)
 `{     # Push the string "{" to the stack.
   .    # Concatenate the top two values of the stack, which stringifies the function, then appends { to it.
    }   # Try to terminate a function, fail quietly, and terminate the program.

Of course, because of the structure of this quine, anything but true no-ops (Which don't get stringified) can be placed after the concatenate function, and
Some quines

{`{.i}{: Outputs {}i.{`{. i is just the "inverse" function, so this program outputs itself reversed.
{`{.S§.}{: Outputs ..S`{{{}§. S converts the string to a stack of characters, § sorts the stack lexographically, then . joins it back together, outputting itself sorted.

Try it online!

Jelly → Underload, 15 bytes
“(a(:^)*“S):^”j

Try it online!
Takes the input Underload function Q as a command-like argument. Q must take input from the stack and push output to the stack, without attempting to inspect deeper stack elements (as they won't exist).
Explanation
The Underload
The Underload universal quine constructor used here is:
(a(:^)*…S):^

Most of the program is a single literal. We follow that by :^, which copies it, then evaluates one copy (leaving the other copy on the stack).
When the literal starts evaluating, we run a (escape, which brings it back into the same form as the original programA), and (:^)* (which appends :^), thus reconstructing the entire program's source code. We can then run the function Q to transform this in an arbitrary way, and print the result with S.
The Jelly
I can't use Charcoal this time because a validating Underload interpreter crashes at the end of the program if the program ends with a newline. (Some Underload interpreters, such as the one on TIO, don't enforce this rule, but I wanted to be properly portable.) Unfortunately, Charcoal naturally adds trailing newlines to its output. Instead, I used Jelly, which is almost as terse in simple cases like this; the program consists of a list literal with two elements (““”), and joins them on the input (j), thus interpolating the user input into the program.
Example
Using the input :S^ (print a copy, then evaluate the original), we get the following Underload program:
(a(:^)*:S^S):^

Try it online!
This prints itself infinitely many times, in a fairly interesting way: after doing the normal quine behaviour, it then runs eval on a copy of what it output. That causes the entire reconstructed program to run again, indefinitely (Underload is tail-recursive). Quining yourself and doing an eval is actually the only way to do an infinite loop in Underload.

Charcoal doesn't add trailing newlines anymore (yay)

Charcoal → Perl (5), 29 33 bytes
Ａ$_=q(αＡ);evalβαＳ"\α$_β\n";printβ

Try it online!
The Perl program Q should return a snippet that takes input as a string to its right hand side and provides output in the variable $_. (Arbitrary Perl functions can be converted to this form via wrapping them as sub x {…}; $_=x . In most cases, though, Perl's syntax means that no wrapping is required.)
Explanation
The Perl
Here's what the universal Perl quine constructor looks like:
$_=q(…"\$_=q($_);eval";print);eval

(In most cases you'd want to golf this down to $_=q(say…"\$_=q($_);eval");eval, but I'm not sure you can fit arbitrary Perl code into the … there.)
In other words, we have an outside wrapper $_=q(…);eval which assigns a string to $_ and then evaluates it. Inside the wrapper is "\$_=q($_);eval", i.e. a reconstruction of the wrapper together with its contents via using the value we stored in $_, plus the code Q specified by the user, plus print to print the output. (Unfortunately we can't use say; it adds a newline, and that's relevant in quines.)
The Charcoal
The "point" of this answer was to produce generalized quines in Perl, so once I had a golfed strategy for doing that (one I've used in many other answers), it was time to write the program P, which basically just substitutes a string into a template. What I wanted here was a language which was good at printing constant strings (ideally compressing them a bit), and interpolating user input into them.
After trying a few, I settled on Charcoal, which I've never used before (and which could really do with some documentation); it's designed for ASCII art but capable of writing strings in one dimension too. ASCII characters are printed literally in Charcoal, meaning that printing constant strings takes no boilerplate, and we can use the Ｓ command to interpolate a string taken from user input into the program.
It's possible to go (slightly) shorter, though. The Perl universal quine constructor contains two fairly long repeated sections. We can thus use the Ａ command to assign them to variables (e.g. Ａ…α assigns to the variable α), and simply interpolate the variables into the string we're printing via using their names. That saves a few bytes over just writing the string literally.
Unfortunately, Charcoal also appends a newline to the program, but that's not a huge deal; it simply costs two bytes for an \n to add that newline to the input of Q too.
Example
If we give the input $_=reverse (which reverses a string), we get the following output:
$_=q($_=reverse"\$_=q($_);eval\n";print);eval

Try it online!
which is a quine-alike that prints its source backwards, as expected.

Vyxal D -> Vyxal D, 4 bytes
\IpI

Try it Online! The D flag is necessary due to vyxal decompressing non-ASCII strings by default.
  p  # Prepend
\I   # "I"
   I # Quote and prepend to itself

For example, with the input "`hello`+Ṙ" (append "hello" and reverse) this outputs `I\`hello\`+Ṙ`I`hello`+Ṙ, which:
`I\`hello\`+Ṙ`           # "I`hello`+Ṙ"
              I          # Quote and prepend to self, obtaining source code
               `hello`+  # Append "hello"
                       Ṙ # Reverse

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:
Let's Judge Some Books By Their Covers
Everyone knows that the content makes the question. But a good title helps too, and that's the first thing we see. It's time to turn that first impression into a program, and figure out what kinds of titles get more upvotes.
You are hereby challenged to write a program or function that takes the title of a PPCG question as input, and returns a prediction of its score.
For instance, you might receive Counting Grains of Rice as an input, and you would be trying to return something close to the score, 59 in this case. Non-integer guesses are fine, but guesses at or below -20 are not.
Here is the data, for testing and scoring:
http://data.stackexchange.com/codegolf/query/244871/names-and-upvotes
Scoring: Your program will be run on every question in this site's (PPCG) history, not counting closed questions. The function ln(score + 20) will then be applied to each score, and to each guess. The root-mean-squared-error between the two resultant sets of values is your score. Lower is better.
For instance, a program that guessed 0 every time would score 0.577, while one that guessed 11 every time would score 0.362.
Please calculate your score and include it in the title of your answer. Please also include your program's prediction for how many upvotes this question will get.
Restrictions:

To prevent excessive hard-coding, no more than 1000 characters.
Must run on the entire data set above in under a minute on a reasonable machine.
Standard Loopholes are closed.

Here is a tester written in Python, for your use and/or to clear up ambiguities:
import sys
import math
import csv

scores_dict = {}

with open(sys.argv[1], 'r') as csv_file:
    score_reader = csv.reader(csv_file)
    for score, title in score_reader:
        if score == 'Score':
            continue
        scores_dict[title] = int(score)

def rate_guesses(guesser):
    def transform(score):
        return math.log(score + 20) if score > -20 else 0
    off_by_total = 0
    lines_count = 0
    for title in scores_dict:
        guessed_score = guesser(title)
        real_score = scores_dict[title]
        off_by_total += (transform(real_score) - transform(guessed_score)) ** 2
    return (off_by_total/len(scores_dict)) ** .5

def constant11(title):
    return 11

print(rate_guesses(constant11))

Nice idea, but it's a shame the dataset isn't stable, so the scores will become invalid after a while. There's also a minor possibility of strategic voting: anyone who answers this question and earns a vox-populi badge in the same week should be viewed with suspicion! ;-)

Will the title include or exclude things like [closed] and [on hold], where applicable?

@es1024 No, it will not. Closed questions and on hold questions are not in the data set, I believe. See the link for details.

@steveverrill Well, the flipside of that is as time progresses, we'll be able to see whether the programs do well on future posts as well as past ones.

It's difficult to defeat hard-coding. Each hard-coded top-voted question can reduce as much as 0.4 score. And there seems to be not much common pattern also, haha. I'm predicting that the answers will just compete on how to fit as many hard-coded result in 1000 bytes.

Are we allowed to use the entire list of titles when processing a single title?

You should not use the complete body of questions as your test set.  You should pre-select a certain number (10%-20%) at random, and define them as your test set (but not tell anyone what that is).  It's much easier to make an algorithm that predicts past history, than one that has future predictive value (ie, one that works well on any given subset).  (It would be even better to remove those 10% from what we can see at all, but that wouldn't really work well.)

@NathanMerrill Only if you can fit the entire list of titles in 1000 bytes.

@isaacg:: I think Nathan is referring to accessing a list of file containing the list of titles, like I did.

@justhalf I guess I'll allow it for now, but I'm not sure how I feel about it.

Python 2, 991 chars, score 0.221854834221, predict 11
import base64
e={}
d=base64.decodestring('vgAcRAEVDAIsqgQYalYaggcjQKwVXAoZWAsYQg0Ckg4VlWEX9hEDRhMe0hckCBkeuhsW3CAWQiEm\nSiMZMiwgTDAZZjIcSLMZfDQDnjwCe2AVaEQCYWEBIEgnDEoXzk0e3lQb5FYVKlkVZlwB+F0XwmI/\nGmRcuGUXWmYdVGkbzmwafG8eaHMdInkggHonRn5sKoMXgIkpbowVOI4cNJAubpQdYpcydJgVypkA\nZpweMp8ZsqEcRKMghKQYkKVPPXEWMqkWHKwbjrEdzLIBNLMf1LQivrYC99UV9rxNRsABNMEiPzob\npc0ActAhn3gcrNUZYNcWYNov/t8VgOEXAuMYqOUWsqUiCPIefPWNbvtKevwWvP0Cl9UsjQMdWwQb\nfQdpJQgWYwkCZRLBjxMWWdkqHRkWNxwB6x8p2SEZyyICSyYcgysaOS0CUy8hezAaGeEVpTRQ3zUz\nZzkZRzohizwwST4c8UAdF0OqG9AXIuEYYRN6208nU1AktVEVJ1IVWeMkIVQXdY4D2VYYD/cYb1om\nG1xA0zoY3uUaRWAhWpBSHWUXQTxGe+cad20CO3AZX3EBw3IiMXcef3gecXsVGXwhw30VbX4W24BD\n6qyQ45YaYYgZ4YobbYwauY4bMY82HZEdO5YmQ5cV35sVxaMbY6gYNas576ws+bADO7QpN7hdLJ8B\n4Eoks8EYX8VU68cYWfcar82QOdAaxdEfQ9UiW/kXL9k2ddwCW90m694enqUCkeEBE+IYWvsfA1FC\nJ+spMVIjhe4WEP0fAfYax/c3MfgbgfkqP/0DLf4V\n')
for i in range(0,600,3):
 e[ord(d[i])*256+ord(d[i+1])]=ord(d[i+2])*2-8
def p(t):
 return e.get(hash(t)%256**2,11)

Explanation:
This is shameless hardcoding, but trying to do it efficiently.
Preprocessing:
In a separate code, I hashed each title to a value between 0 and 256^2-1. Let's call these values bins. For each bin, I calculated the average score. (Average is needed because for a tiny fraction of the bins, there are collisions - more than 1 title hashes to the same bin. But for the vast majority each title maps to a bin of its own).
The idea behind the 2-byte code for each title is that 1 byte is not enough - we get too many collisions, so we don't really know what score to assign to each 1-byte bin. But with 2-byte bins, there are almost no collisions, and we effectively get a 2 byte representation of each title.
Then rank the bins - compute the gain in score if we assign this bin its computed value, instead of just guessing 11. Take the top N bins, and code them into a string (which is d in the actual code).
The encoding: the key of the bin is coded as 2 bytes. the value is encoded using 1 byte. I found values between -8 and 300+something, so had to squeeze a bit to get it into 1 byte: x -> (x+8)/2.
Actual code:
read d as byte triplets, decoding the encoding explained above. When a title is given, compute its hash (modulo 256^2), and if that key is found in the dict, return the value it maps to. Otherwise, return 11.

A suggestion: Average score is not that good. Look at the challenges scoring function, it's non-linear.

@Deduplicator Thanks, I realised that after I was done. The thing is, for 99% of the bins, there is no collisions, so the average is actually just the score of the single title that maps to that bin.

Javascript ES6
Score: 0.245663Length: 1000 bytesPredicts: 5
(I guess the question is due for an unexpected avalanche of downvotes. :P)
Minified
E="ABCDEFGHIJKLMNOPQRSTUVWXYZ";E=E+E.toLowerCase()+"0123456789!@#$%;*()";P="RCRHIFMGPGIDQKHMJLLRMLFJGKHEqHPOgJNKGPCHPJNUPOSGJQKKKMELMIJHLKIKNcKDOfSJLFHDILGKIOUKLMLLKMKIHGHJGIIJDGJKIHIIFIGMTIHFJMIKDJGQJKGMKJHPRJPLMGIOPIIIIPBYFMGLEIKIMMRUKFLFGJFKFTHPFODEQTGTHKIJDHNJGDGiHKNYLHHDLJHGILOEViKNEKGQZfHJMIISIJFRHKLJMLPIFJILKKKJKKJESHNLLIKIGKGJJJHKJRGULLSLRONJNEeLKIQGGPQIHPLEIHHIDXjQHNBKOGWWIENRbYoHINHNMKTNKHTGMIPXFJLLMLIHPPLDJJKFUMIQMOKJLJJKIJKNLHRILJIAIbJEZOGIELGHGLOINDPJMJeJWRIIJHSOZDOsOFRRIOIOTIJSGGJKFUIDOINGOcLQEJFEITLMNIIGIGIMG7LPSNLKVOKIFGHJITGOFUJIIRN";K={};"99r1501vz076mip077myv0733it280exx081gt9118i1g279dyx102uho203ejd07433z087uje097kdg1567ft2088rk275dmu1203ez106lih1763ei126f6q101aax084owh088aid161i9y179gvn236ptn3338vf132i55080fke101l4z3789ai281ulm081blm124euz074o5m07513z14117l095qdn092gl30757n5153".replace(/(...)(...)/g,(_,a,b)=>K[a]=1*b);D=40655;N=479;H=(s,T)=>(h=7,[...s].map(c=>h=~~(h*T+c.charCodeAt(0))),h);S=s=>(y=H(s,31),K[((y%D+D)%D).toString(36)]||E.indexOf(P[(H(s,48)%N+N)%N]));

Expanded
E = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
E = E + E.toLowerCase() + "0123456789!@#$%;*()";
K = {};
P = "RCRHIFMGPGIDQKHMJLLRMLFJGKHEqHPOgJNKGPCHPJNUPOSGJQKKKMELMIJHLKIKNcKDOfSJL" +
    "FHDILGKIOUKLMLLKMKIHGHJGIIJDGJKIHIIFIGMTIHFJMIKDJGQJKGMKJHPRJPLMGIOPIIIIP" +
    "BYFMGLEIKIMMRUKFLFGJFKFTHPFODEQTGTHKIJDHNJGDGiHKNYLHHDLJHGILOEViKNEKGQZfH" +
    "JMIISIJFRHKLJMLPIFJILKKKJKKJESHNLLIKIGKGJJJHKJRGULLSLRONJNEeLKIQGGPQIHPLE" +
    "IHHIDXjQHNBKOGWWIENRbYoHINHNMKTNKHTGMIPXFJLLMLIHPPLDJJKFUMIQMOKJLJJKIJKNL" +
    "HRILJIAIbJEZOGIELGHGLOINDPJMJeJWRIIJHSOZDOsOFRRIOIOTIJSGGJKFUIDOINGOcLQEJ" +
    "FEITLMNIIGIGIMG7LPSNLKVOKIFGHJITGOFUJIIRN";

   ("99r1501vz076mip077myv0733it280exx081gt9118i1g279dyx102uho203ejd07433z087u" +
    "je097kdg1567ft2088rk275dmu1203ez106lih1763ei126f6q101aax084owh088aid161i9" +
    "y179gvn236ptn3338vf132i55080fke101l4z3789ai281ulm081blm124euz074o5m07513z" +
    "14117l095qdn092gl30757n5153").
        replace( /(...)(...)/g, (_,a,b) => K[a] = 1*b );

D = 40655;
N = 479;
H = (s,T) => (
    h = 7,
    [...s].map( c => h = ~~(h*T + c.charCodeAt(0)) ),
    h
);

S = s => (
    y = H( s, 31 ),
    K[((y%D + D)%D).toString( 36 )] || E.indexOf( P[(H( s, 48 )%N + N)%N] )
);

The function S accepts a string (title) and returns its score.
Notes on Behaviour:

≤ 70 vote titles are handled separately from > 70 vote titles
≤ 70 vote titles are sorted into bins using a highly sophisticated holonomic keyword tracking potential optimization algorithm that in no way resembles a string hash function
after a bit of happy calculus it turns out that the optimal guess for each bin is simply the geometric average of the (votes + 20)'s for all titles in the bin, minus 20
the optimal guesses for all 479 bins are then encoded as a 479-character base-70 string
for > 70 vote titles, the titles are assigned unique 3-digit base-36 codes generated using a state-of-the-art hashing technique that guarantees no collisions with other > 70 vote titles and no false detections of ≤ 70 vote titles. This state-of-the-art technique in no way resembles trying random bin counts until one produces no collisions.
the > 70 vote title codes and their vote counts are encoded in a string (6 bytes per title), which is converted to a simple lookup table. The routine therefore has zero error for all > 70 vote titles.

Python 2, Score = 0.335027, 999 chars, Predict 11.34828 for this question
Just to get the ball rolling. This is nowhere optimal.
The fancy SVM thing is just my random idea and I felt like implementing it, so here it is. It does improve the baseline by 0.02 points, so I'm happy enough with that. But to show that hard-coding the input is where the majority of the improvement comes from, I'm hard coding some answer also.
Without the hard-coding the score is 0.360 (and actually all the predictions are around 11, haha)
I'm using scikit-learn and nltk
import sys
import math
import csv
from sklearn.feature_extraction.text import TfidfVectorizer as TV
from sklearn.svm import SVR
from nltk.stem.porter import PorterStemmer as PS
sd = {}
lr = None
tv = None
with open(sys.argv[1], 'r') as cf:
    sr = csv.reader(cf)
    for sc, t in sr:
        if sc == 'Score':
            continue
        sd[t] = int(sc)
ts,scs = zip(*sd.items())
s = PS()
def analyzer(st):
    r = []
    for word in st.split():
        if word.isdigit():
            r.append('<NUM>')
        elif not word.isalnum():
            r.append('<PUNCT>')
        else:
            r.append(s.stem(word.lower()))
    return r
tv = TV(min_df=25, stop_words='english', analyzer=analyzer)
ti = tv.fit_transform(ts)
lr = SVR()
lr.fit(ti, scs)
d={'4 w':378,'y 42':333,'eeta':280,'an Got':279,'s 2 ':275,"e I'":208,'r CP':203,'? No':179,'B.O':156}
def c(t):
    for s in d.keys():
        if s in t:
            return d[s]
    t = tv.transform([t])
    r = lr.predict(t)[0]+1.5
    return r

I'm not sure I understand - you read the scores from an external file? So why not just predict sd[t]? This would give a score of 0...

Because that would not be fun =p

Python 2, 535 chars, score 0.330910, predicts 11.35
Average the score for titles containing each word, then use the top and bottom 50 words to possibly modify the BASE score in the guess(title) function.
Python code:
BASE = 11.35
word={}
for sc,ti in csv.reader(open(sys.argv[1])):
    if sc == 'Score': continue
    parts = re.findall(r"[-a-zA-Z']+", ti.lower())
    for p in parts:
        a, c = word.get(p, (0.0,0))
        word[p] = (a+int(sc), c+1)

rank = sorted([(sc/ct,wd) for wd,(sc,ct) in word.items() if ct > 2])
adjust = rank[:50] + rank[-50:]

def guess(title):
    score = BASE
    parts = re.findall(r"[-a-zA-Z']+", title.lower())
    for sc,wd in adjust:
        if wd in parts:
            score *= 0.7 + 0.3*sc/BASE
    return score

Python 2, 986 chars, score 0.3480188, predict 12
M,S=14.29,23.02
D=lambda x:[ord(y)-32 for y in x]
w='fiLoNoNuMiNoTiMoShOnLoGoLeThRantexgensuBaSqUnInPeReGaMuLinprOuThInThEvEnClOpExPyThADdiSoLiSiMaTrEqUsImAsCoManstARrePoWoReawhapoLandradeTyPaLOsoReCreprediVeReSpebeTiPrImPladaTrihelmakwhicolpaReValpaTrafoROsoumovfinfunpuzyoufaSeQuiwhecoDeChagivcouchehanpoStrdiGraconjavwricalfrowitbinbrafrabuipoi'
for i in range(26):w=w.replace(chr(65+i),chr(97+i)*2)
w=[w[i:i+3]for i in range(0,372,3)]
m=D("(+),+)+=*...+..++'(*)5)/2)*43++16+0,+33*4*/(0.'+>-)+13+(2?8+6;,3;43+4(+.('(,.*.*+56+6)0((++(B,))+E0,-7/)/*++),+***)2+(3(.*)'")
s=D("))'B)'*j+:51(*3+0')+)^'/<-+MG,-1=),-0:A+T&J&K1%,O*()4Y-%:_A.=A*C]MJ-N%)5(%%-0+).*3Q(M&0'%(+$p*)()a8:-T?%5(-*'/.'+)+@,'J&1'&&")
def G(x,m,s):s=s or 1e-9;return(.4/s)*(2.78**(-(x-m)**2./(2*s*s)))
d={w[i]:(m[i],s[i])for i in range(124)}
def Z(t,c):
 p=1
 for W in t.split():
  if len(W)>3:
   W=W[:3].lower()
   if W in d:p*=G(c,*d[W])
 return p*G(c,M,S)
def J(t):return max([(Z(t,r),r)for r in range(-9,99)])[1]

The relevant function is J.
The program is essentially Naive Bayes using title words as features, but it's extremely restricted thanks to the char limit. How restricted? Well...

For each title we convert to lower case and only look at words at least 4 letters long. Then we take the first three letters of each of those words as features. We skip stripping punctuation to save on chars.
We choose only letter triplets which are at the start of at least 19 words (these are stored in w above). Compression is done by rearranging the triplets so that as many doubled letters are present as possible, and these pairs are replaced with their corresponding ASCII uppercase (e.g. fiLoNoN... → fil, lon, non, ...)
For each triplet, we look at the scores of the titles in which it appears and calculate the mean and standard deviation of the scores. Then we convert those to integers and store them in m, s above, by using the fact that the mean/sd are at most 90 (allowing a direct ASCII encoding, since there are 95 printable ASCII)
G is the normal distribution function - we round e to 2dp and the inverse square root of 2 pi to 1 dp to save on chars.

Altogether the extreme char limit made this one of the worst ideas I've ever come up with, but I'm pretty happy with how much I managed to cram in (even though it doesn't work very well). If anyone has better ideas for compression, please let me know :)
(Thanks to KennyTM for pointing out my pointless compression)

Unless I've executed the code wrongly, your compression code is even longer than the decompressed result... w='grge…scse';w=[w[i:i+2]for i in range(0,len(w),2)] is 165 bytes while yours C=lambda:…;w=C('…') is 179 bytes.

@KennyTM Oh thanks - I've been messing around with the code so much, trying to fit the char limit that I'd lost track of all the compressing. :P

C
Score: UnknownLength: 5 bytesPredicts: 5
Golfed:
int s(char *p){return 5;}

Ungolfed:
int s(char *p)
{
   return 5;
}

A query of the scores gives an average score of 5.
I've not got the ability to test it at the moment, others are welcome to run/edit.

Further Gulfed: int s(){return 5;}

"You are hereby challenged to write a program or function that takes the title of a PPCG question as input, and returns a prediction of its score." - Sorry but nope :0

I've seen a platform by which if you forgot main(), your first function was main(). Maybe he's depending on that.

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


text:
Predict the Falling Rocks
In this challenge, you are given a map of a two-dimensional terrain, viewed from the side. Unfortunately, some parts of the terrain are floating in the air, which means they'll come crashing down. Your job is to predict where they land.
The Input
Your input is one or more newline-separated strings of equal lengths, containing only the characters # (a number sign, signifying a rock) or . (a period, signifying empty space).
The Output
Your output has the same format as the input, but with the following modification. Let us view the input string as a two-dimensional grid of rocks. Every rock in the input which is connected to the bottom of the grid by a path of adjacent rocks is firm; other rocks are loose. Diagonally adjacent rocks are not considered to be adjacent. All the loose rocks will fall straight down, and end up as a stack on top of either a firm rock or the bottom row. The loose rocks are not attached to each other, so they fall individually, not as big formations. The output is the resulting grid.
Examples

The input
..###.
.##.#.
.#....
.##.#.

contains no loose rocks, so the output is identical to it.
The input
...#..
.#..#.
.#..##
.#...#
.#####
.#...#

contains one loose rock at the top, which falls down on the firm rock under it. The output is
......
.#..#.
.#..##
.#.#.#
.#####
.#...#

The input
.#####....
.#....####
###.###..#
#.#...##..
.####..#.#
......###.
..#...#..#
..#...#..#

has a large group of loose rocks on the left. The group breaks down as the rocks fall, so the output is
..........
....######
..#.###..#
. #...##..
.##....#..
.##...####
####..#..#
#####.#..#

Clarifications

You can either take the input from STDIN and output to STDOUT, or write a function.
This is code-golf, so shortest program (in bytes) is the winner.
Standard loopholes are disallowed.

related: http://codegolf.stackexchange.com/questions/25834/gravity-controls

CJam, 180 ... 133 101 ... 94 90 87 bytes
qN/~'#/S*_,):L;]N*_,_,*{:A1$='#={[W1LL~)]Af+{W>},1$f=S&,{ASct}*}*}/N/z{S/{$W%}%'#*}%zN*

There is definitely lots of golfing possible, but I wanted to post it first after getting it to work completely.

Look ma! No scrollbars!

Takes the rocks grid (made up of . and # without a trailing newline) from STDIN and prints the output to STDOUT
UPDATE : Using an inefficient but shorter partial flood fill to figure out firm rocks.
UPDATE 2: Changed the algorithm for making the rocks fall down. Much shorter now!
UPDATE 3: Did several small optimizations and in the end I was able to bring down the byte count to half of the original code!
How it works:
qN/~'#/S*_,):L;]N*             "Preparations";
qN/~                           "Read the input, split by new line and expand the array";
    '#/S*                      "In the last row, replace # by space";
         _,):L                 "Copy the last row and store length + 1 in L";
              ;]N*             "Pop the length, wrap everything in array and join by \n";

_,_,*{ ... }/                  "Flood fill";
_,                             "Copy the array and calculate its length";
  _,                           "Copy the length and calculate [0 - length] array";
    *                          "Repeat the above array, length times";
     { ... }/                  "Run the code block on each element of the array";

:A1$='#={ ... }*               "Process only #";
:A1$                           "Store the number in A and copy the input array to stack";
    =                          "Get Ath index element from input array";
     '#={ ... }*               "Run the code block if Ath element equals #";

[W1LL~)]Af+{W>},1$f=S&,{ASct}* "Flood fill spaces";
[W1LL~)]Af+                    "Get the indexes of the 4 elements on the cross formed by"
                               "the Ath index";
           {W>},               "Filter out the negative values";
                1$f=           "For each of the index, get the char from input string";
                    S&,        "Check if space is one of the 4 chars from above step";
                       {    }* "Run the code block if space is present";
                        ASct   "Make the Ath character of input string as space";

N/z{S/{$W%}%'#*}%zN*           "Let the rocks fall";
N/z                            "Split the resultant string by newlines and"
                               "transpose the matrix";
   {           }%              "Run the code block for each row (column of original)";
    S/{   }%                   "Split by space and run the code block for each part";
       $W%                     "Sort and reverse. This makes # come down and . to go up";
            '#*                "Join by 3, effectively replacing back spaces with #";
                 zN*           "Transpose to get back final matrix and join by newline";

For the floodfill, we iterate through the whole grid length(grid) times. In each iteration, we are guaranteed to convert at least 1 # which is directly touching a space to   (space). Space here represents a firm rock group. Thus at the end of length(grid) iterations, we are guaranteed to have all firm rocks represented by spaces.
Try it online here

Perl 5: 98
98 including 2 command line flags.
#!perl -p0
1while/
/,($x="($`)")=~y!#!.!,s/#(.*
$)/%$1/+s/#$x?%|%$x?#/%$1$2%/s;1while s/#$x\./.$1#/s;y!%!#!

Explanation:
#!perl -p0 #read entire input to $_ and print at the end
/\n/;($x="($`)")=~y!#!.!; #calculate pattern matching space
                          #between two characters in the same column
                          #looks like "(......)"
1 while s/#(.*\n$)/%$1/+s/#$x?%|%$x?#/%$1$2%/s;
                          #flood fill solid rock with %
1 while s/#$x\./.$1#/s;   #drop loose rock
y!%!#!                    #change % back to #

@Optimizer I rely on the final line of input being properly finished see: http://ideone.com/7E3gQh
Without this reliance it would be one char loner (or one shorter relying on the opposite - lack of final EOL).

Beating CJam by almost 30%? Amazing. I congratulate you.

@DLosc Not anymore :P

Beating other imperative languages by 100-300%? Amazing. I congratulate you. ;)

@DLosc Looking at the above answer, I won't include Perl in the list of imperative languages anymore :P

I accepted @Optimizer's answer since it is the shortest, but this definitely deserves at least an honorable mention.

JavaScript (ES6) 232
s=>{for(s=[...s+'1'.repeat(r=1+s.search('\n'))];s=s.map((c,p)=>c=='#'&(s[p+1]|s[p-1]|s[p-r]|s[p+r])?f=1:c,f=0),f;);for(;s.map((c,p)=>c=='#'&s[p+r]=='.'&&(s[p]='.',f=s[p+r]=c),f=0),f;);return s.join('').replace(/1/g,rok).slice(0,-r)}

As a function with a string parameter and returning a string.
At first, add a bottom row of '1' to identify the ground line.
The first loop search for the fixed rocks (that are near a '1') and marks them as '1' as well.The search is repeated until no more firm rocks are found.
The second loop move the remaining '#' characters towards the bottom row. Again, this is repeated until no rock can be moved.
At last, replace the '1' with '#' again and cut the bottom row.
Less golfed
s=>{
  r = 1+s.search('\n');
  s = [...s+'1'.repeat(r)];
  for (; s = s.map((c,p) => c=='#' & (s[p+1]|s[p-1]|s[p-r]|s[p+r])?f=1:c,f=0),f; );
  for (; s.map((c,p) => c=='#' & s[p+r]=='.'&& (s[p] ='.', s[p+r]=c, f=1),f=0),f; );
  return s.join('')
    .replace(/1/g,'#')
    .slice(0,-r)
}

Test
(You can have evidence of what rocks are firm and what have fallen)

F=
s=>{for(s=[...s+'1'.repeat(r=1+s.search('\n'))];s=s.map((c,p)=>c=='#'&(s[p+1]|s[p-1]|s[p-r]|s[p+r])?f=1:c,f=0),f;);for(;s.map((c,p)=>c=='#'&s[p+r]=='.'&&(s[p]='.',f=s[p+r]=c),f=0),f;);return s.join('').replace(/1/g,rok).slice(0,-r)}

var rok // using rok that is 3 chars like '#'

function update() {
  rok = C.checked ? '@' : '#';
  O.textContent=F(I.textContent)
}

update()
td { padding: 5px }
pre { border: 1px solid #000; margin:0 }

Input	Output

.#####....
.#....####
###.###..#
#.#...##..
.####..#.#
......###.
..#...#..#
..#...#..#

<input type='checkbox' id=C oninput='update()'>Show firm rocks

APL, 130 119
'.##'[1+⊖1↓⍉↑↑{,/{⍵[⍒⍵]}¨x⊂⍨2=x←2,⍵}¨↓ ⍉⊃⌈/(1,¨⍳⍴⊃↓x){x←⍵⋄(⍺⌷x)∧←2⋄x≡⍵:x⋄⊃⌈/((⊂⍴⍵)⌊¨1⌈(,∘-⍨↓∘.=⍨⍳2)+⊂⍺)∇¨⊂x}¨⊂⊖'#'=x←⎕]

Since it is not possible (as far as I know) to enter newlines when input is prompted, this program takes a character matrix as input.
The algorithm used is first converting to a binary matrix (0 is air and 1 is rock) then flood filling from the bottom row to mark firm rocks as 2. Then partition each column into "spaces between firm rocks" and sort each partition to make the loose rock "fall through" the air.
Edit1: Golfed some using a different flood fill algorithm

Test runs
Run 1
Define a character matrix A and prints it:
      A←↑('.#####....') ('.#....####') ('###.###..#') ('#.#...##..') ('.####..#.#') ('......###.') ('..#...#..#') ('..#...#..#')
      A
.#####....
.#....####
###.###..#
#.#...##..
.####..#.#
......###.
..#...#..#
..#...#..#

Then feed A into the program:
      '.##'[1+⊖1↓⍉↑↑{,/{⍵[⍒⍵]}¨x⊂⍨2=x←2,⍵}¨↓⍉(1,¨⍳⊃⌽⍴x){⍵≡y←⊃⌈/x←⍺{x←⍵⋄(⍺⌷x)∧←2⋄x}¨⊂⍵:y⋄((⊂⍴⍵)⌊¨1⌈,(,∘-⍨↓∘.=⍨⍳2)∘.+⍺/⍨x≢¨⊂⍵)∇y}⊖'#'=x←⎕]
⎕:
      A
..........
....######
..#.###..#
..#...##..
.##....#..
.##...####
####..#..#
#####.#..#

Run 2
      A←↑('#######')('#.....#')('#.#.#.#')('#.....#')('#######')
      A
#######
#.....#
#.#.#.#
#.....#
#######
      '.##'[1+⊖1↓⍉↑↑{,/{⍵[⍒⍵]}¨x⊂⍨2=x←2,⍵}¨↓⍉(1,¨⍳⊃⌽⍴x){⍵≡y←⊃⌈/x←⍺{x←⍵⋄(⍺⌷x)∧←2⋄x}¨⊂⍵:y⋄((⊂⍴⍵)⌊¨1⌈,(,∘-⍨↓∘.=⍨⍳2)∘.+⍺/⍨x≢¨⊂⍵)∇y}⊖'#'=x←⎕]
⎕:
      A
#######
#.....#
#.....#
#.#.#.#
#######

JS - 443 bytes
function g(b){function f(b,c,e){return b.substr(0,c)+e+b.substr(c+1)}function e(d,c){"#"==b[c][d]&&(b[c]=f(b[c],d,"F"),1<d&&e(d-1,c),d<w-1&&e(d+1,c),1<c&&e(d,c-1),c<h-1&&e(d,c+1))}b=b.split("\n");w=b[0].length;h=b.length;for(i=0;i<w;i++)"#"==b[h-1][i]&&e(i,h-1);for(j=h-2;-1<j;j--)for(i=0;i<w;i++)if(k=j+1,"#"==b[j][i]){for(;k<h&&"F"!=b[k][i]&&"#"!=b[k][i];)k++;k--;b[j]=f(b[j],i,".");b[k]=f(b[k],i,"#")}return b.join("\n").replace(/F/g,"#")};

Flood fills rocks from the bottom, then brings un-flood-filled rocks down. Uses a lot of recursion with the flood fill so it may lag your browser for a bit.
It's a function - call it with g("input")
JSFiddle: http://jsfiddle.net/mh66xge6/1/
Ungolfed JSFiddle: http://jsfiddle.net/mh66xge6/

Python 3, 364 bytes
I'm sure more could be squeezed out of this... but it's never going to compete with CJam and Perl anyway.
z="%";R=range
def F(r,c,g):
 if z>g[r][c]:g[r][c]=z;[F(r+d%2*(d-2),c+(d%2-1)*(d-1),g)for d in R(4)]
def P(s):
 t=s.split()[::-1];w=len(t[0]);g=[list(r+".")for r in t+["."*w]];[F(0,c,g)for c in R(w)]
 for c in R(w):
  for r in R(len(g)):
   while g[r][c]<z<g[r-1][c]and r:g[r][c],g[r-1][c]=".#";r-=1
 return"\n".join(''.join(r[:w])for r in g[-2::-1]).replace(z,"#")

Similar to other answers. One quirk is that it turns the grid upside down first (to make the loop indices more convenient) and adds an extra row & column of . (to avoid problems with wrapping -1 indices). Run by calling P(string).

authors: Бодя Бондаренко


text:
Michael Crichton's Mousetrap
In 1984, Michael Crichton wrote a security program in BASIC that was published in Creative Computing magazine. The program would ask the user to type a phrase of their choice, record the intervals between the keystrokes, then ask them to retype the phrase. If the timings differed by too much, the program would identify the user as an imposter.
Your assignment: create a version of Crichton's program in the language of your choice.
Rules:

Phrases for communicating with the user ("Please type the key phrase," "Please type the key phrase again," etc.) count as one byte each regardless of actual length. This is for user communication only, do not try to hide program code in the strings.

The pass/fail test should be based on the average absolute value of the percentage variances from the original intervals. If the strings don't match, either return fail or allow the user to try again, at your discretion.

The key phrase should not allow a null string. In the event the key phrase is too long for your string datatype, either truncate or disallow and start over, at your discretion.

The sensitivity of the test (the threshold for the pass/fail test) should be adjustable in the source code.

I originally provided a bonus of 20% of total byte count if your source code can be formatted to recognizably resemble a dinosaur. It has been pointed out that this is highly subjective and perhaps more appropriate for a popularity contest, so I have removed this bonus. However I still heartily encourage dinosaur formatting, and if you format your code to look like a dinosaur, you can deduct any purely cosmetic comments, linebreak or whitespace characters from your byte total.

Shortest byte count wins, subject to string-length and dinosaur formatting adjustments.

Note that my specification above does not exactly match the operation of Crichton's code, copies of which may be found online. Follow the spec, don't try to clone the original.

I'd say with a single bonus, that's still code golf. Regarding that bonus though... you say "can be formatted"... i.e. we don't need to count the spaces used only for formatting?

I like how the question says "phrase of her choice" :)

What if I write my code so that the program will run normally, but if I shift the code along a line, it'll still run? ;)

How do we handle the cases where the re-entered keyphrase does not match ? Ask to enter again ?

"It's Michael Crichton, so subtract 20% from total byte count if your source code can be formatted to recognizably resemble a dinosaur." - umm... no. This rule is too subjective. Please remove. Other than that, please go ahead.

@JanDvorak I don't think its "too" subjective. Its a fairly easy call to call some ASCII art as dino or not

@Optimizer Not in all cases. Does the greek letter lambda look like a dinosaur? I'm pretty sure it does.

removes moderator hat ~<^^^O A stegosaurus? Technically, I can argue that it has a head, body, and tail. In my opinion, I do agree that the dinosaur rule seems too subjective.

A few other minor comments: Does "Please type the key phrase" count as 1 byte, or does only the phrase count and the quoted phrase counts as 3 bytes (", phrase, ")? Is it intentional that a much longer interval and a much shorter interval will "cancel out" and become even again? Does the program have to verify that the two key phrases match?

@Doorknob "Please type the key phrase" would be one byte.

I too would suggest either removing the dinosaur requirement or using some mixture of [tag:popularity-contest] and [tag:code-golf] so people try to be creative.

It was in June 1984. You can see the original program here.

@squeamishossifrage Thanks for the link. Btw, there is a bug in the original version, which divides by zero when first and second inputs are empty strings.

... also, all comparisons are stricts, which may have unintended effects when SF equals NG or OK. If you intend to copy the original work, take care of corner cases.

@MichaelStern You asked to "Follow the spec, don't try to clone the original". Can you clarify the spec and tell us if we are required to check that both string actually match? Btw, do you have any rule regarding error handling? (e.g. empty strings, really long strings (buffer overflow), etc.)

@coredump I have clarified the rules as you suggest.

Ruby, 171 167 157 bytes
require'io/console';t=Time;f=->a{loop{x=t.now;STDIN.getch==?\r?break: a<<t.now-x};a};p"Please type the key phrase";f[r=[]];p"Please type the key phrase again";p r.zip(f[[]]).map{|x,y|(1-x/y).abs}.reduce(:+)/r.size>0.2

Outputs true if average variance is above 20%, otherwise outputs false.
Dinosaur ASCII art attempt:
(_=/\
  \ \
   \ \
    \ \              _...---..__
     \ \          .∕` #{t=Time} `\._
      \ \      .∕ #{z='io/console'} `\.
       \ \.__.∕  #{require z;s=STDIN} `\.
        \ #{p'1:';f=->a{loop{x=t.now;#   \.
         s.getch==?\r?break: a<<t.now-x;# `\.
          };a};f[r=[]];p'2:';p r.zip(f[[]])#\
           .map{|x,y|(1-x/y).abs}.reduce(:+)#|
            .fdiv(r.size)>0.2}###########\   \
            `-._    ,___...----...__,   ,__\  \
                |   |_|           |_|   |    \ \
                |___|               |___|      \\/)

Ungolfed:
require 'io/console' # so we can read one char at a time

t = Time

f = ->(a) {
  loop {
    x = t.now # record start time
    break if STDIN.getch == ?\r
    a << t.now - x # push (start time - end time) into array
  }
  a
}

puts "Please type the key phrase"
f[r = []]

puts "Please type the key phrase again"

# interweave timing arrays, compute variances, sum elements
# then divide by array length. Check to see if average
# is greater than threshold (0.2)
p r.zip(f[[]]).map { |x,y| (1-x/y).abs }.reduce(:+) / r.size > 0.2

require 'io/console' could be removed when run in some Ruby REPLs, as the library is already loaded.

Java  768 bytes
what? Java? for code golf?
This is probably the worst thing to do, but I tried it anyway.
It displays any messages in the console window, but the actual typing occurs in the JTextField. Not exactly nice looking. Oh, and to save 5 bytes, you have to resize the JFrame yourself. Also, it doesn't check for string correctness the second time. Not sure if that is against the specs.
To Use:
Type your key in the textfield.
Don't press enter, go to the console and type something. It will display another message
Type the same thing in the textfield (which should now be cleared).
Go to the console and press something again. It will display whether you are an intruder or not.
ungolfed:
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

public class CrichtonsMousetrap {
    public static void main(String[]a){
        new CrichtonsMousetrap();
    }
    long start;
    List<Long>elapsed = new ArrayList<>();
    List<Long>e2;
    public CrichtonsMousetrap(){
        JFrame f = new JFrame();
        f.setSize(199,70);
        f.setVisible(true);
        JTextField t = new JTextField();
        System.out.println("please type in the key phrase.");
        f.add(t);
        t.getDocument().addDocumentListener(new DocumentListener(){
            @Override
            public void changedUpdate(DocumentEvent e) {}
            @Override
            public void insertUpdate(DocumentEvent e) {
                long r = System.nanoTime();
                if(start!=0){elapsed.add(r-start);}
                start=r;}
            @Override
            public void removeUpdate(DocumentEvent e) {}
        });
        Scanner s = new Scanner(System.in);
        s.next();
        System.out.println("please type that again!");
        e2=elapsed;
        elapsed=new ArrayList<>();
        start=0;
        t.setText("");
        s.next();
        double sum=0;
        for(int i=0;i<e2.size();i++){
            sum+=Math.abs(1-elapsed.get(i)/(double)e2.get(i));
        }
        System.out.println("your average percent error was " + sum/e2.size());
        double okLimit = .2;
        System.out.println(sum/e2.size() < okLimit ? "you're ok":"INTRUDER!");
    }
}

golfed:
import java.util.*;import javax.swing.*;import javax.swing.event.*;class q{static long p;static List<Long>y=new ArrayList<>(),o;public static void main(String[]a){JFrame f=new JFrame();f.setSize(0,0);f.setVisible(true);JTextField t=new JTextField();System.out.println("please type in the key phrase.");f.add(t);t.getDocument().addDocumentListener(new DocumentListener(){public void changedUpdate(DocumentEvent e){}public void insertUpdate(DocumentEvent e){long r=System.nanoTime();if(p!=0){y.add(r-p);}p=r;}public void removeUpdate(DocumentEvent e){}});Scanner s = new Scanner(System.in);s.next();System.out.println("please type that again!");o=y;y=new ArrayList<>();p=0;t.setText("");s.next();double b=0;for(int i=0;i<o.size();b+=Math.abs(1-y.get(i)/(double)o.get(i++)));System.out.print(b/o.size() < .25 ? "you're ok":"INTRUDER!");}}

There is no way to set TTY in raw mode from java (unless you are ready to use JNI). So I understand why you need a JFrame. But really, this is the least user-friendly program I've seen in ages :-) I am not sure if I want to upvote or downvote this answer.

I upvote for the sheer amount of user unfriendliness (ist that even a word?). It's basically art.

I believe this could be golfed more by making the class extend JFrame, so you wouldn't need f.

C, 154 (86+68 for flags)
d[99],i,a,b;main(x,y){P"Please type the key phrase"W(E-13)U,x=y;U;P"Please type
the key phrase again"W(a<i)E,b+=abs(Y-Z)*99/Z,++a,x=y;b<a*9||P"No cake for imposters");}

Compile with -DY=(y=clock())-x, -DZ=a[d], -DE=getch(), -DW=);while, -DU=i++[d]=Y and -DP=puts(. Newlines added for presentation purposes and may be removed (byte count given is without).
Ungolfed+comments:
d[99],i,a,b;
main(x,y,z){
    puts("Please type the key phrase");
    do
        z = getch(),
        i++[d] = (y = clock()) - x, // save amount of time from last key. first value is garbage.
        x = y;
    while((z = getch())-13); // read until carriage return.
    for(;a < i && getch(); ++a) // don't check for validity, just get a char
        b += abs((y = clock())- x - d[a])*99/d[a], // (y=clock())-x is time from last key.
                                                     // subtract from original time, *99, divide by new
                                                     // then get sum of these
        x = y;
    b < i*9  // check that the average difference is less than 9/99
    || puts("No cake for imposters"); // identify as imposter if greater/equal
    // don't output anything if not an imposter
}

This does not check that the retyped phrase is identical, nor does it output anything if the user is not identified as an imposter.
This also does not consider the time taken after prompting before the first keystroke.

Shouldn't getch bet getc or getchar? I have an undefined reference to `getch', which if I recall correctly is deprecated?

I also had "file.c:1:1: warning: data definition has no type or storage class" (gcc). I added char before global declarations, and now, this gives a segmentation fault at runtime. Can you give details about how to build it? What compiler are you using? Thanks.

@coredump The warnings are harmless; though if you wanted to remove the warnings, it should be type int, and initialized to 0. I've tested this using gcc on Windows (using Window's getch). getch is used instead of getc or getchar because getch doesn't require the return key to be pressed before processing any characters (getch is indeed deprecated on Windows, though there's nothing wrong with using deprecated functions here).

I'm testing on Linux and resorted to http://stackoverflow.com/questions/7469139/what-is-equivalent-to-getch-getche-in-linux in order to make it works. Thanks.

HTML, JavaScript (ES6), 328
Total bytes count of the code is 402 bytes and the messages to interact with the user:
"Valid User"
"Imposter alert!!"
"Please Enter the Key again"
Please Enter the Key

are total 78 bytes, so total score => 402 - 78 + 4 = 328
Run the snippet below in a latest Firefox and type the key in the input box followed by Enter key.
The code checks that both the entered and re-entered keys are same, (prompts for re-entering again if not), calculates the average absolute difference percentage and checks if it is less than the the value of the variable V

Please Enter the Key<input id=f />

Scala REPL 233
def l:Stream[(Int,Long)]=(Console.in.read,System.nanoTime)#::l
def m={
    println("Enter");
    l.takeWhile(_._1!=13).map(_._2).toList.sliding(2).map(a=>a(1)-a(0))
}
val k=m.zip(m)
k.map(a=>Math.abs(a._2-a._1)/(a._1.toDouble*k.length)).sum<0.2

With all the spacing removed, you have:
def l:Stream[(Int,Long)]=(Console.in.read,System.nanoTime)#::l;def m={println("Enter");l.takeWhile(_._1!=13).map(_._2).toList.sliding(2).map(a=>a(1)-a(0))};val k=m.zip(m);k.map(a=>Math.abs(a._2-a._1)/(a._1.toDouble*k.length)).sum<0.2

Which I'm sure somebody more talented than I am could make into a dinosaur!
Brief explanation:
The l method read characters and keeps tract of the nanoTime of when each character was typed.
The m method prints "Enter", breaks the l method upon hitting enter (character 13), then maps it to just the nanoTimes, and then gets the time intervals between each character.
The next 2 lines reads in 2 strings, zips them, then finds the average absolute value of the percentage difference between the second intervals and the first, and finally prints whether or not this average was less than 0.2.

Common Lisp : 660
(ql:quickload'(cl-charms alexandria))(defun m(&key(ok 0.2))(labels((^(s)(fresh-line)(princ s)(return-from m))(d(a b)(abs(/ (- b a) b)))($(x)(princ x)(force-output))(?(m)(charms:with-curses()($ m)(clear-input)(charms:enable-raw-input)(loop for c = (read-char)for n = (get-internal-real-time)for x = nil then (/(- n b)internal-time-units-per-second)for b = n when (eql c #\Esc)do (^"QUIT")when x collect x into % until (eql c #\Newline) collect c into ! finally(progn(terpri)(return(cons(coerce !'string)%)))))))(let*((ip(?"INIT PASSWORD: "))(ps(car ip))(sp(if(equal""ps)(^"NO EMPTY PASSWORD ALLOWED")(?"ENTER PASSWORD: ")))(r(if(equal ps(car sp))(alexandria:mean(mapcar #'d(cdr sp)(cdr ip)))(^"YOU DIDN'T SAY THE MAGIC WORD!"))))(if(> r ok)($"YOU ARE A FAKE!")($"IDENTITY CONFIRMED")))))(m)

Ungolfed
(ql:quickload'(cl-charms alexandria))
(defun m(&key(ok 0.2))
  (labels
      ((^(s)(fresh-line)(princ s)(return-from m))
       (d(a b)(abs(/ (- b a) b)))
       ($(x)(princ x)(force-output))
       (?(m)(charms:with-curses()
              (clear-input)
              ($ m)
              (charms:enable-raw-input)
              (loop for c = (read-char)
                    for n = (get-internal-real-time)
                    for x = nil then (/ (- n b)
                                        internal-time-units-per-second)
                    for b = n
                    when (eql c #\Esc)
                      do (^"QUIT")
                    when x
                      collect x into %
                    until (eql c #\Newline)
                    collect c into !
                    finally (progn
                              (terpri)
                              (return
                                (cons (coerce !'string) %)))))))
    (let* ((ip (?"INIT PASSWORD: "))
           (ps (car ip))
           (sp (if (equal "" ps)
                 (^"NO EMPTY PASSWORD ALLOWED")
                 (?"ENTER PASSWORD: ")))
           (r (if (equal ps (car sp))
                (alexandria:mean(mapcar #'d(cdr sp)(cdr ip)))
                (^"YOU DIDN'T SAY THE MAGIC WORD!"))))
      (if (> r ok)
        ($"YOU ARE A FAKE!")
        ($"IDENTITY CONFIRMED")))))

(m) ;; call function

Additional remarks

Complies with all rules
When user first gives an empty password, the program aborts cleanly
When typing Escape, the program aborts cleanly.
Tested on recent SBCL and CCL implementations
Requires cl-charms, which is a wrapper around Ncurses. This is the easiest way to capture raw input.
This is inspired by (but not copied from) the original version found by squeamish-ossifrage

Dinosaur bonus
I should have a bonus because everybody knows that "Common Lisp is a moribund dinosaur".

Can you switch to code block instead of quote block ? (for your code)

@Optimizer done

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


text:
Tiling, given vertex configuration
Task
The task is to tile polygons, given a vertex configuration.
Scoring
Your score is equal to the "complexity level" your submission reaches. Complexity levels are cumulative, meaning that to reach #3 you must also support #1 & #2.
Submissions at an equal complexity level are distinguished by byte count; lowest wins.
Input
Input is a string containing a vertex configuration, representing a vertex figure. That is, a dot separated list of integers, where each integer (n) represents a regular n-gon, connected by a common vertex.
The following vertex configurations must be supported:

3.3.3.3.3.3
3.3.3.3.6
3.3.3.4.4 (note that order is reflected in the vertex figure, therefore the below does differ)
3.3.4.3.4
3.12.12
3.4.6.4
3.6.3.6
4.4.4.4
4.6.12
4.8.8
6.6.6

Output -  Complexity Level #1: Vertex Figure
At this complexity level, output is an image showing the vertex figure corresponding to the given input.
Input is prepended with an F to signify that the vertex figure should be output, and not the full tiling.
For example F3.6.3.6 gives this vertex figure:

Output - Complexity Level #2: Tiling
At this complexity level output is an image showing a uniform tiling using the vertex figure corresponding to the given input.
For example 3.6.3.6 gives this tiling:

There are no restrictions on colour or format (barring loopholes).
Output - Complexity Level #3: Dual Tiling
At this complexity level a 'dual tiling' can be formed from each tiling. This is achieved by drawing lines from the centre of each polygon to the centre of each bordering polygon.
Dual tiling is specified by prepending input with a V.
For example V3.6.3.6 gives this dual tiling (in red):

Some of these tilings have synonyms. For example the following are all the same: 3.3.3.4.4 3.3.4.4.3 3.4.4.3.3 4.4.3.3.3 4.3.3.3.4. Do we have to support all synonyms, or just the lexically lowest one (as given in the question)? Also, 3.3.3.3.6 exists in two mirror image forms. I understand either is acceptable.

The page you linked does not match the list given. 3.3.3.4.4 is missing for example. http://en.wikipedia.org/wiki/Tiling_by_regular_polygons#Regular_tilings matches your list exactly. I understand outline or filled polygons are acceptable (or a combination of the two?) Some duals are already in the list. For example 4.4.4.4 is its own dual and 3.3.3.3.3.3 and 6.6.6 are mutally dual. As the duals are displayed independently of their parents, I understand there is no need for correct alignment with the parent.

you must support input as it appears in the list - you may support synonyms but you don't have to - you must support all duals, even self-duals.

outline/filled - fine either way. any styling is allowed besides loopholes (make everything white, make drawing area tiny etc.). alignment not required. I could tell you you're not allowed to use one reflection of 3.3.3.3.6 but how would you know which one it is? :)

Now you've changed the scoring, what is the tie-break? Is that still shortest code? If so, do the vertex configurations have to be delimited by dots or can we choose another symbol like comma or space?

you must support input exactly as it appears, including dots and prepended letters. tie-breaker is lowest byte count, as it says.

imho, This would be better tagged as a code challenge than code golf.

@DavidCarraher it's been a code challenge for about a week now, with lowest byte count being the tie-breaker. See last two comments above yours. We both need to read more carefully!

My goodness. I do need to pay more attention.

BBC BASIC
Rev 1 Golfed code, 655 ASCII characters, tokenised filesize 614
Some major improvements to the data table, by hashing the string A.B..N to a number (1*A+2*B+..n*N)+n before looking up, and by storing only one translation vector (the other one is generated by code.) More explanation when I have finished golfing.
t=PI*2DIMm(9)
c=0z=0INPUTz$
FORi=1TOLEN(z$)d%=VAL(MID$(z$,i))IFd%c+=1m(c)=d%i-=d%=12z+=c*d%
NEXTREPEATREADl,e,f
UNTILl=z+c
l=4-3*(m(3)MOD3=0)-8*(l=59)
DATA69,0,70,65,100,35,66,149,0,49,109,0,52,80,0,55,0,189,39,120,0,44,40,40,58,55,95,47,136,0,59,40,0
VDU23,23,3|
FORr=-9TO19FORs=-9TO9a=1+e*(r*2+s)-f*l*s/4b=1+f*(r*2+s)+e*l*s/4p=40q=0FORk=1TOm(c)/2FORj=1TOc
n=m(j)o=TAN(PI/3)IFe=109ANDn<>4o=1
w=-p*COS(t/n)-q*SIN(t/n)q=p*SIN(t/n)-q*COS(t/n)p=w
u=p:v=q
x=a:y=b
MOVEx,y
FORi=1TO14x+=u*2y+=v*2IFVAL(z$)DRAWx,y ELSEGCOL9LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)
w=v*COS(t/n)-u*SIN(t/n)u=v*SIN(t/n)+u*COS(t/n)v=w
NEXTNEXT
p=u:q=v
a=x:b=y
NEXTNEXTNEXT

Rev 0 Golfed code, 770 ASCII characters, tokenised filesize 728
All I've done here is remove comments, unnecessary whitespace and quote marks, and put all the DATA on one line. There's certainly room for more golfing.
t=PI*2DIMm(9)
c=0INPUTz$
FORi=1TOLEN(z$)d%=VAL(MID$(z$,i))IFd%c+=1:m(c)=d%:i-=d%=12
NEXTREPEATREADl$,e,f,g,h
UNTILMID$(z$,1-(VAL(z$)=0))=l$
DATA3.3.3.3.3.3,240,0,120,70,3.3.3.3.6,200,70,40,210,3.3.3.4.4,80,0,40,150,3.3.4.3.4,-40,150,150,40,3.12.12,300,0,150,260,3.4.6.4,220,0,110,188,3.6.3.6,160,0,80,140,4.4.4.4,80,0,0,80,4.6.12,0,380,330,-190,4.8.8,272,0,136,136,6.6.6,240,0,120,70
VDU23,23,3|
FORr=-9TO19 FORs=0TO9a=1+e*r+g*s
b=1+f*r+h*s
p=40q=0FORk=1TOm(c)/2FORj=1TOc
n=m(j)o=TAN(PI/3):IFe=220ANDn<>4o=1
w=-p*COS(t/n)-q*SIN(t/n)q=p*SIN(t/n)-q*COS(t/n)p=w
u=p:v=q
x=a:y=b
MOVEx,y
FORi=1TO14x+=u*2y+=v*2IFVAL(z$)DRAWx,y ELSEGCOL9LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)
w=v*COS(t/n)-u*SIN(t/n)u=v*SIN(t/n)+u*COS(t/n)v=w
NEXTNEXT
p=u:q=v
a=x:b=y
NEXTNEXTNEXT

Explanation
This is a continuation of my previous Level 1 answer, but I decided to post it separately because it's rather long.
Level 2
This is achieved by translation of my "level 1.5" templates from my previous answer. The two translation vectors for each tiling are hardcoded. I take advantage of the fact that an isosceles triangle of base 80 and height 70 is a very good approximation of an equilateral triangle, and a right triangle with hypotenuse vector (56,56) has a hypotenuse length very close to 80.
Level 3
To plot the duals, instead of plotting an edge of the polygon, we plot a spoke from the middle of that edge to the centre of the polygon. This is at right angles to the edge and has length of 1/TAN/(PI/n) times of the vector (u,v) which in turn is half as long as the edge.
Unfortunately, because certain polygons in tilings 3.3.3.3.6 and 3.4.6.4 are not plotted explicitly, they would not be plotted if we only did this. Therefore the spoke also extends outward from the polygon. The outward extension is controlled by the variable o.
By default the extension is sufficient to reach the centre of a triangle, but for 3.4.6.4 it needs to be extended more in order to draw the duals of the squares that are not plotted explicitly. So enough extension to fill in the missing squares is applied when hexagons and triangles are plotted explicitly, but the normal extension is applied when squares are plotted explicitly, to avoid spurious lines in the adjacent triangles.
Here's what they look like without the spoke extensions. The holes in the dual pattern can be clearly seen. The correct output can be seen in the main picture at the bottom of the answer

Commented Code
Differences from my previous answer are indicated inline
  t=PI*2                                          :REM constant Tau = PI*2

  DIMm(9)                                         :REM declare array for the numbers in the input
  c=0                                             :REM number of polygons in the list

  INPUTz$
  FORi=1TOLEN(z$)                                 :REM for each character in the input
    d%=VAL(MID$(z$,i))                            :REM use VAL to return the numeric value of the substring to the right and store to integer variable
    IF d% c+=1 :m(c)=d%: i-=d%=12                 :REM if the last character read was a number, d% contains it, otherwise 0. Advance c and store to m. If it is 12, increment i to skip a character.
  NEXT

  REM BLOCK OF NEW CODE to define vectors (e,f) and (g,h) for each possible tiling

  REPEAT
    READ l$,e,f,g,h                               :REM read an entire line of the data below
  UNTIL MID$(z$,1-(VAL(z$)=0))=l$                 :REM abort the loop when l$ coincides with the input. the MID$ strips off the 'V' from the input where necessary.

  DATA"3.3.3.3.3.3",240,0,120,70
  DATA"3.3.3.3.6",200,70,40,210
  DATA"3.3.3.4.4",80,0,40,150
  DATA"3.3.4.3.4",-40,150,150,40
  DATA"3.12.12",300,0,150,260
  DATA"3.4.6.4",220,0,110,188
  DATA"3.6.3.6",160,0,80,140
  DATA"4.4.4.4",80,0,0,80
  DATA"4.6.12",0,380,330,-190
  DATA"4.8.8",272,0,136,136
  DATA"6.6.6",240,0,120,70

  VDU23,23,3|                                           :REM change linewidth to 3 (default is 1)

  REM END BLOCK OF NEW CODE

  FORr=-9TO19 FORs=0TO9                                 :REM two new loops for translations

      a=1+e*r+g*s                                       :REM modified code for
      b=1+f*r+h*s                                       :REM coordinates to start drawing at

      p=40:q=0                                          :REM vector of first line

      FORk=1TOm(c)/2                                    :REM draw half as many vertex figures as there are sides on the last polygon in the list

        FORj=1TOc                                       :REM for each polygon on the list
          n=m(j)                                        :REM n=number of sides
          o=TAN(PI/3): IF e=220 AND n<>4 o=1            :REM new code for the spoke extension 1/o.

          w=-p*COS(t/n)-q*SIN(t/n)                      :REM rotate the starting vector anticlockwise by the internal angle of the current polygon
          q=p*SIN(t/n)-q*COS(t/n)                       :REM to avoid overlapping the previous one, if any.
          p=w

          u=p:v=q                                       :REM make a local copy of the vector and coordinates
          x=a:y=b                                       :REM to avoid corruption of p,q,a,b during the drawing of the polygon
          MOVE x,y                                      :REM move the graphics cursor to the start without drawing
          FORi=1TO14                                    :REM do 14 iterations regardless of the number of sides on the polygon
            x+=u*2                                      :REM increment x and y by the vector representing the side
            y+=v*2                                      :REM the value is double (u,v) to facilitate drawing duals later

            REM if z$ begins with a numeric character, draw an edge. If not, change to red and draw a spoke.
            IFVAL(z$) DRAW x,y ELSE GCOL9: LINEx-u-v/o,y-v+u/o,x-u+v/TAN(PI/n),y-v-u/TAN(PI/n)

            w=v*COS(t/n)-u*SIN(t/n)                     :REM rotate the vector clockwise
            u=v*SIN(t/n)+u*COS(t/n)                     :REM through the external angle of the polygon
            v=w
          NEXT                                          :REM draw next edge of the current polygon
        NEXT                                            :REM draw next polygon of the current vertex

        p=u:q=v                                         :REM once the vertex is finished, we will be two sides around the perimeter of the last polygon.
        a=x:b=y                                         :REM copy the position and direction data into p,q,a,b.
      NEXT                                              :REM draw next vertex figure

    NEXT                                                :REM close the two new translation loops
  NEXT

Output
The program performs only one tiling or dual for each run. However it plots the duals in red. To save space, I ran the program twice without clearing the screen in order to superimpose the dual on top of the regular tiling.

Mathematica
Level 1 contains the basic tile templates that are repeatedly stamped to tile a plane.
Level 2 does the tiling.
There are still 2 tilings I haven't been able to achieve. They appear to require rotation as well as translation.
Level 1: Vertex Figure (559 bytes)
nGon[n_]:=
{ColorData[46,"ColorList"][[n]],Polygon@Switch[n,
3,{{0,0},{-1/2,.866},{-1,0},{0,0}},
4,{{0,0},{0,1},{-1,1},{-1,0},{0,0}},
6,Table[{Cos[i 2Pi/n],Sin[i 2Pi/n]}+{-.5,.866},{i,0,n}],
8,Table[1.31{Cos[i Pi/4],Sin[i Pi/4]}+{-0.5`,1.207},{i,1/2,9}],
_,Table[2{Cos[i 2Pi/n],Sin[i 2Pi/n]}+{-0.5176,1.932},{i,1/2,13}]]}
innerAngle[n_]:=180-360/n
g[{}]=0;
g[a_]:=-(Plus@@innerAngle/@a)

h[{{},__,out_}]:=out
h[{list_,angles_,out_}]:=(
z=GeometricTransformation[nGon[l=list[[1]]],RotationTransform[g[angles] Degree]];
h[{Rest@list,Append[angles,l],Append[out,z]}])

Testing
Row[Graphics[{EdgeForm[{Blue}], #},
      ImageSize -> 70] & @@ {h[{#, {}, {}}]} & /@ {{3, 3, 3, 3, 3,
    3}, {3, 3, 3, 3, 6}, {3, 3, 3, 4, 4}, {3, 3, 4, 3, 4}, {3, 12,
    12}, {3, 4, 6, 4}, {3, 6, 3, 6}, {4, 4, 4, 4}, {4, 6, 12}, {4, 8,
    8}, {6, 6, 6}}]

Level 2: Tiling  (690 additional bytes)
The rules return tiling offsets and indents for each configuration.
r is the basic function that outputs the tilings.
p shows the template and the respective tiling.  White spaces correspond to those not covered by the template.
rules={
{3,6,3,6}-> {2,3.47,0,0},
{4,4,4,4}-> {1,1,0,0},
{6,6,6}-> {3,2.6,1.5,0},
{3,3,3,3,3,3}-> {1.5,1.74,0,.9},
{3,3,3,3,6}-> {2,2.6,-0.4,1.8},

{4,6,12}->{4.2,4.9,0,2.5},
{3,3,4,3,4}-> {1.87,1.86,-.5,-0.5},
{4,8,8}-> {3.4,3.4,0,0},
{3,3,3,4,4}-> {2,1.87,.52,0},
{3,12,12}-> {3.82,6.73,0,0},
{3,4,6,4}-> {1.4,4.3,0(*1.375*)-1,-2.4}};

r[nGons_]:=
Module[{horizHop,vertHop,indent,downIndent},
{horizHop,vertHop,indent,downIndent}=(nGons/.rules);
Graphics[{EdgeForm[{Blue}],Table[GeometricTransformation[h[{#,{},{}}]&/@{nGons},
TranslationTransform[{
If[MemberQ[{{3,3,4,3,4},{3,3,3,3,6},{3,4,6,4}},nGons],indent *row,indent Boole[OddQ[row]]]+col horizHop,
If[MemberQ[{{3,3,4,3,4},{3,3,3,3,6},{3,4,6,4}},nGons],downIndent *col,downIndent Boole[OddQ[col]]]-row vertHop}]],
{col,0,5},{row,0,4}]},ImageSize-> 250]]

p[nGon_]:=Row[{Graphics[{EdgeForm[{Blue}],h[{nGon,{},{}}]},ImageSize->70],r@nGon}];

Testing
Triangular tiling
p[{3, 3, 3, 3, 3, 3}]

hexagonal
p[{6, 6, 6}]

square
p[{4, 4, 4, 4}]

unknown
p[{3, 3, 4, 3, 4}]

truncated square
p[{4, 8, 8}]

trihexagonal
p[{3, 6, 3, 6}]

truncated hexagonal
p[{3, 12, 12}]

unnamed
p[{3, 3, 3, 3, 6}]

elongated triangular
p[{3, 3, 3, 4, 4}]

Tilings to figure out

I'm pretty much at the same stage as you.  I can create the tiles, but working out the tiling is going to take a bit.  The wiki steveverill posted in his comments sort of makes it looks like various schemes made need to be supported.  Need to do a bit of study:)

Micky, The vertical and horizontal displacement of a tile will depend on the row no., the col no. using offsets unique to the case at hand.  I'm working them out one by one and will later generalize.

@DavidCarraher great start. I have made a change to the scoring criteria that may affect you.

Good so far! If you reduce your horizontal translation on 3.3.3.3.3.3 by half, so that the units overlap, you can get rid of those diamonds and fix that tiling. You still have more to do on 3.3.3.3.6,3.4.6.4 and 4.6.12 though.

Re 4.6.12 anyone know what it should look like? -  All the required tilings are at http://en.wikipedia.org/wiki/Tiling_by_regular_polygons#Regular_tilings . See my comment on the question. This is a different page to the one mentioned in the question. But 4.6.12 is also shown on that page anyway.

@steveverrill, thanks for the pointers. Should have colored the polygons to be able to easily spot gaps. I was able to solve a couple of the cases you raised. Still having trouble with two. Perhaps tomorrow I'll get to them.

R
Step #1
Here's my effort at building the tiles.  Tiling to come next.
This does not validate the input, so invalids will draw some weird tiles.
Input is typed in after first line
i=as.numeric(unlist(strsplit(readline(),"[.]")))
e=c()
for(n in 1:length(i)){
    o=sum(c(0,180-360/i[1:n-1]))
    for(z in 1:i[n]){
        e=c(e,(360/i[n])*(z-1)+o)
    }
}
f=pi/180
plot(c(0,cumsum(sin(e*f))),c(0,cumsum(cos(e*f))),type="l")

Step #1,#2 & #3: 1898
Finally got back to it.  Most of this is taken up with setting offsets and handling special cases :). Edit: V flag for duals are now handled
The general process is:

Take the input and make a list
Create a list of angles to draw the initial tile
Calculate centres of each polygon it the tile and the vectors from them to bisect the edges
Determine the tile set being drawn and make a list of angle offsets.  Some tiles have additional polygons added to them to assist with filling holes.
Draw the tiles
Draw the duals

I can probably still golf this a bit more.
##Get input (Enter by itself then type in the tile scheme)
i=strsplit(readline(),"[.]")[[1]]
## Run once i is set
q=0
if(substr(i[1],1,1)=="V"){q=1;i[1]=substr(i[1],2,9)}
i=as.numeric(i)
f=pi/180
e=x=y=q=p=c()
l=length(i)
d=1/(2*tan(pi/3))
g=1/(2*sin(pi/3))
for(n in 1:l){o=sum(c(0,180-360/i[1:n-1]))
r=1/(2*sin(pi/i[n]))
a=o+(180-360/i[n])/2
b=1/(2*tan(pi/i[n]))+d
for(z in 1:i[n]){x=c(x,r*sin(a*f))
y=c(y,r*cos(a*f))
q=c(q,b)
p=c(p,(360/i[n])*(z-1)+o-90)
e=c(e,(360/i[n])*(z-1)+o)}}
if(sum(i)==18&l==6){h=c(60,0);w=c(60,120)}
if(sum(i)==18&l==5){h=c(0,0,60);w=c(60,120,60)
e=c(e,0,-60,60,180,60,180)
x=c(x,g*sin(-30*f),g*sin(-30*f),g*sin(90*f))
y=c(y,1+g*cos(-30*f),1+g*cos(-30*f),1)
q=c(q,d+d,d+d,d+d)
p=c(p,-30,90,-30)}
if(sum(i)==17&l==5&sum(abs(diff(c(i,i[1]),1)))==2){h=c(0,0);w=c(90,60)}
if(sum(i)==17&l==5&sum(abs(diff(c(i,i[1]),1)))==4){h=c(0,30);w=c(270,300)}
if(sum(i)==17&l==4){h=c(0,30,-30);w=c(60,30,90)
e=c(e,150,120,210,300)
x=c(x,sin(150*f)+g*sin(90*f),sin(150*f)+sin(210*f)/2)
y=c(y,cos(150*f)+(1/(2*cos(pi/3)))*cos(90*f),cos(150*f)+cos(210*f)/2)
q=c(q,1,1)
p=c(p,210,120)}
if(sum(i)==18&l==4){h=c(0,0);w=c(120,120)}
if(sum(i)==16&l==4){h=c(0,0);w=c(90,90)}
if(sum(i)==27&l==3){h=c(0,-30,0,30);w=c(60,90,120,150,180)}
if(sum(i)==22&l==3){h=c(0,-30,30,90,60,30)
w=c(90,150,120,90,60,30)
e=c(e,0,-30,-60,30,120,210,30,90,150)
q=q-d+1/(2*tan(pi/4));q[13]=q[17]=q[21]=q[21]+3}
if(sum(i)==20&l==3){h=c(0,-45,-90);w=c(90,0,45)}
if(sum(i)==18&l==3){h=c(0,60,0,-60);w=c(0,60,120,60)}
hx=sum(sin(h*f))
hy=sum(cos(h*f))
wx=sum(sin(w*f))
wy=sum(cos(w*f))
plot(0,0,type="n")
par(pin=c(5,5),usr=c(0,20,0,20))
for(c in -20:20){for(j in -20:20){lines(c((c*hx)+(j*wx)+0,(c*hx)+(j*wx)+cumsum(sin(e*f))),c((c*hy)+(j*wy)+0,(c*hy)+(j*wy)+cumsum(cos(e*f))),type="l")
if(q){for(n in 1:length(x)){lines(c((c*hx)+(j*wx)+x[n],(c*hx)+(j*wx)+x[n]+q[n]*sin(p[n]*f)),c((c*hy)+(j*wy)+y[n],(c*hy)+(j*wy)+y[n]+q[n]*cos(p[n]*f)),col="RED")}}}}

Wow, only 4 hours behind me. And they look nice too, +1! Have you got all cases working yet?

@steveverrill Thanks and it works for all the cases in the question.

BBC BASIC
Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
Level 1

Level 1.5
Level 1.5 is my own designation, but it is an important milestone in my method.
Translating the vertex figures does not always lead to the correct tiling. In some cases lines are missing.
My solution to this is to go around the largest polygon, drawing the vertex figure for every second vertex of that polygon. This is a general solution for all cases. Note that the largest polygon always has an even number of sides and the vertex figure often alternates clockwise/anticlockwise as you go around the polygon. This can be seen most clearly with 4.6.12, but it is also true of 4.8.8 and 3.12.12: when viewed from any particular 8-gon or 12-gon, alternating vertices are mirror images of each other. This is also what is happening, somewhat less obviously, with 3.3.3.4.4 and 3.3.4.3.4: when viewed from any particular square, alternating vertices are mirror images of each other.
The algorithm I use to move 2 sides around the polygon is to always do 14 iterations of the edge-drawing loop, regardless of how many edges the polygon has. 8 is a factor of 16, therefore when drawing octagons the graphics cursor ends up 16-14=2 vertices behind where it started. 3- 4- 6- and 12- gons all have sides that are factors of 12, so the graphics cursor ends up 14-12=2 vertices ahead of where it started.
The figures can be seen below. Tomorrow I hope to work out the correct translations to complete the tiling. In all cases sufficient lines are drawn to complete level 2 with translations only. In some cases a great deal more than the minimum required is drawn, but there's no problem with overlap: the rules say nothing about drawing lines only once :-)
In general, the largest polygon is the last one on the list. There is, unfortunately one case where this is not so: 3.4.6.4 Therefore the figure drawn in this case is centred on a square rather than a hexagon. There are enough lines to complete level 2 using only translations, although there will certain squares that are not drawn explicitly. This will present some problems in level 3 (fortunately I think I know how to solve this.) Similarly with 3.3.3.3.6 there are enough lines to complete level 2 using only translations, but there will be certain triangles that are not drawn explicitly.

Code
The code for level 1.5 is commented out, only the code for level 1 is activated. There are four lines beginning with a REM. Remove these REMs to activate level 1.5.
  t=PI*2                                          :REM constant Tau = PI*2
  DIMm(9)                                         :REM declare array for the numbers in the input
  c=0                                             :REM number of polygons in the list

  INPUTz$
  FORi=1TOLEN(z$)                                 :REM for each character in the input
    d%=VAL(MID$(z$,i))                            :REM use VAL to return the numeric value of the substring to the right and store to integer variable
    IF d% c+=1 :m(c)=d%: i-=d%=12                 :REM if the last character read was a number, d% contains it, otherwise 0. Advance c and store to m. If it is 12, increment i to skip a character.
  NEXT

  FORi=1TOc PRINTm(i),:NEXT                       :REM parsing check for debugging.

  a=601:b=601                                     :REM coordinates to start drawing at
  p=40:q=0                                        :REM vector of first line

  REM FORk=1TOm(c)/2                              :REM draw half as many vertex figures as there are sides on the last polygon in the list

  FORj=1TOc                                       :REM for each polygon on the list
    n=m(j)                                        :REM n=number of sides

    w=-p*COS(t/n)-q*SIN(t/n)                      :REM rotate the starting vector anticlockwise by the internal angle of the current polygon
    q=p*SIN(t/n)-q*COS(t/n)                       :REM to avoid overlapping the previous one, if any.
    p=w

    u=p:v=q                                       :REM make a local copy of the vector and coordinates
    x=a:y=b                                       :REM to avoid corruption of p,q,a,b during the drawing of the polygon
    MOVE x,y                                      :REM move the graphics cursor to the start without drawing
    FORi=1TO14                                    :REM do 14 iterations regardless of the number of sides on the polygon
      x+=u*2                                      :REM increment x and y by the vector representing the side
      y+=v*2                                      :REM the value is double (u,v) to facilitate drawing duals later
      IFVAL(z$) DRAW x,y ELSE LINEx-u,y-v,x-u,y-v :REM if the first character of the input is a number, draw the side of the polygon. The ELSE part is unfinished and will be for drawing duals.
      w=v*COS(t/n)-u*SIN(t/n)                     :REM rotate the vector clockwise
      u=v*SIN(t/n)+u*COS(t/n)                     :REM through the external angle of the polygon
      v=w
    NEXT                                          :REM draw next edge of the current polygon
  NEXT                                            :REM draw next polygon of the current vertex

  REM p=u:q=v                                     :REM once the vertex is finished, we will be two sides around the perimeter of the last polygon.
  REM a=x:b=y                                     :REM copy the position and direction data into p,q,a,b.
  REM NEXT                                        :REM draw next vertex figure

Levels 2 and 3
See my other answer.

authors: سعود العسيري