text:
Find the best immediate move in a "match-3" game
Your challenge today is to take input like this:
fbcfbee
ffcabbe
debceec
bccabbe
edcfbcd
daeaafc
eebcbeb

And output the best possible move in a Bejeweled-like game that will match three or more letters, like this (note the capital B and C):
fbcfbee
ffcabbe
deBCeec
bccabbe
edcfbcd
daeaafc
eebcbeb

Full specifications:

The input will be n lines of n lowercase letters each (where n could be any number).
The output will be the best move you could make in a match-3 game, with the two letters you want to swap capitalized.
Matches should have the following priority (in these examples, . indicates a square that doesn't matter):

Five-in-a-row
xxYxx
..X..

Broken five-in-a-row
X..
Yxx
x..
x..

or
.X.
xYx
.x.
.x.

Four-in-a-row
xYxx
.X..

Three-in-a-row
xYx
.X.

You must find the match of the highest priority and output it.
If there are multiple matches of the same priority, you can output any one of them.
There will always be at least one match (your program can break if there are no matches, or do anything you want).
I/O can be in any reasonable format (stdin/out, reading and writing files, function arguments/return values, dialog boxes, etc.) but NOT hardcoded (like x="[insert input here]").
This is code-golf so shortest code in bytes wins. If you use any network access for some reason, all bytes downloaded from the network count against your score.

+1, but I protest the title; there could be a better move. For instance, one that creates two fives, or one that causes a drop to create more stuff.

Does broken five-in-a-row also cover ..x.\nxxYX\n..x.?

@Peter Yes, it does.

There are 2 broken 5 in a row pattern: the L pattern and the T pattern. Do you require both to be matched?

@nhahtdh  Yes, I'll edit to clarify that.

@Quincunx Ok, edited title

Python3.4, 772
(Using tabs for indentation, instead of spaces.)
import sys,itertools as I
B=[]
for l in sys.stdin:
    l=l.rstrip()
    B.append(list(l))
Z=len(B[0])
F=T=None
R=range
N=min
X=max
P=I.product
S=0
def C(I,J,K,L):
    global F,T,S
    if K<0 or K>=Z or L<0 or L>=Z: return
    B[I][J],B[K][L]=B[K][L],B[I][J]
    h=v=1
    m=B[K][L]
    for i in R(K+1,N(Z,K+5)):
        if B[i][L]!=m:break
        v+=1
    for i in R(K-1,X(0,K-5),-1):
        if B[i][L]!=m:break
        v+=1
    for j in R(L+1,N(Z,L+5)):
        if B[K][j]!=m:break
        h+=1
    for j in R(L-1,X(0,L-5),-1):
        if B[K][j]!=m:break
        h+=1
    c=X(h,v)*2
    if N(h,v)>=3:c+=N(h,v)
    if c>S:S=c;F=I,J;T=K,L
    B[I][J],B[K][L]=B[K][L],B[I][J]
for i,j in P(reversed(R(Z)),R(Z)):
    for d,e in (1,0),(0,-1),(0,1),(-1,0):
        C(i,j,i+d,j+e)
for i,j in P(R(Z),R(Z)):
    c=B[i][j]
    if (i,j)in(F,T):c=c.upper()
    print(c,end=('',"\n")[j==Z-1])

Instead of [c for c in l], you could just do list(l).

Use (i,j)in(F,T) instead of two compares - 778

F=(i,j) -> F=i,j. Deglobalize 2 r/o syms - 770

Fixed bug: broken-5 should not beat true-5.

source: Stack Exchange

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

authors: n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

sort: votes


text:
Tips for golfing in Io
What general tips do you have for golfing in Io? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Io (e.g. "remove comments" is not an answer). Please post one tip per answer.

Could you add a link to Io?

Higher-level function shorthand
This seems like a pretty interesting golfing point. E.g.
list(1,2,3)map(i,i+1)print

However, Io is pretty permissive on not specifying the counter; the map body can be used as a point-free function, as Io tries to fill in the operand of this expression. This can be golfed into
list(1,2,3)map(+1)print

Due to the helpful work of the language creator, you can even do this to reduces!
list(1,2,3)reduce(a,b,a*b)

Can easily be reduced into:
list(1,2,3)reduce(*)

(Unfortunately, I still haven't managed to understand how exactly this works, so I never managed to make the expression more complex.)

You can stick methods onto the back of most literals
"text" print    # 12 bytes
"text"print     # 11 bytes

12 print        # 8 bytes
12print         # 7 bytes

(0<1,0,1) print # 15 bytes
(0<1,0,1)print  # 14 bytes

Not everything
0x12print # prints nothing

You can leave out the else part of the if function
This isn't in the documentation... I initially thought that you have to include the else part, like the elvis operator in other languages; turns out that I can leave out the else part. (Please add this to the tutorial/documentation!)

if("bug"size>2,"True",nil)

So, if you don't want the else part to return anything, you could just do

if("bug"size>2,"True")

Use ~, :, and \ for variable names
You can stick methods onto the back of ~. E.g. instead of this:
method(i,i pop)

You can do this:
method(~,~pop)

You can even put this between them. Instead of this:
and a sqrt

You can do this
and~sqrt

: also does this trick (I discovered it from the := bug), as well as \. (This can empirically save a lot of bytes in your source code, if you use variables a lot)
Some other valid symbolic names that you can't stick

_
.

Can you stick these to other symbols as well?
Unfortunately, things get a little complicated here. Here's a table of how powerful these variable names are:
Unfortunately, you can't stick any of them before := or on the rhs of /, so pick whatever name you like. :P

Now I'm seriously wondering, what have I been doing in Io all these years...

Literal newlines
Just like JavaScript's ``, you can insert literal newlines. i.e. you can do:
"
"

Parenthesis dropping in method applications
Say, I want to split a string by whitespace. I am pretty used to this method when I first got used to Io:
a_string split()

After I heard about how Io parses the arithmetic operations, I realized that this is perfectly valid:
a_string split

Sometimes, you can do that to some one-operand functions as well. If you want to join by spaces, you can do:
a string join" "

I guess this doesn't work sometimes, though I can't find any examples here.

Prefer push over append
There are 2 methods that append values towards the caller object: add, push, and append. I didn't count add because add doesn't work. Try it online!
push and append basically do the same thing:
list(1,2,3)push(4) println
list(1,2,3)append(4) println

Try it online!
Therefore, whenever you want to write append, remember that you can substitute it for push to do the exact same thing.

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

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


text:
Finding number of digits in an integer
Given an integer n as input write a program to output the numbers of digit in it.
Input
12346

456

Output
5

3

Constraint
n<=10^9

This seems overly trivial...

I agree with @DoorknobofSnow.  It should be trivial.  But many or most of the submitted answers are incorrect.  Any solution based on string.length alone (currently most, below) will output the wrong number of digits for any negative integer.  And most values of n will be negative, since "n<=10^9".  Just sayin'.  ;-)

Is the Input/Output example supposed to represent two separate inputs & outputs, or is the program supposed to be able to handle multiple integers at once? Also, are we required to support negative integers and if so what is the lower bound?

I have a feeling OP was looking for (floor(log10(input))+1) or something the likes (I think that's right anyway)

Should 00501 return 3 or 5?

@Cruncher log10(0) and log10(-1) will fail for two different reasons.

@Dangling_pointer did you mean that |n|<=10⁹?

I'm voting to close as underspecified unless the challenge is improved.

@qwr : don't think it can be improved, it's 4 years old and OP has been inactive for over 1 year

GolfScript, 1 character
,

, means length...
Edit: You seem to have changed your question... please don't do that, but I still have a solution:
GolfScript, 12 7 characters (for multiline)
n%{,n}/

Thanks @Howard for reminding me about n to push newline and using separate strings instead of one, to save 5 chars ;)
Solutions that work with negative numbers:
GolfScript, 5 (for negative)
'-'-,

GolfScript, 11 (for multiline and negative)
n%{'-'-,n}/

Only if input has no newline with it.

n%{,}%n* is much shorter ;-)

@Howard Thanks, forgot about n :)

Or even n%{,n}/.

@Howard Oh wow, thanks! Took a bit for me to figure out how that works.

I'm trying to stay away from the simple string length functions, but the BF solution basically does a count.
Pure math/Mathematica - 22 chars (for mathematica)
floor(log10(abs(n)))+1

Thanks to @plg for the correction when n is a power of 10.
This invokes undefined behavior when n=0, but that case can be returned by a simple check.
PHP implementation of the above math solution - 34 chars
($n==0)?1:floor(log(abs($n),10))+1;

BrainF*ck - 54 characters
>>+[<+>++++++++++,----------]<-<++++++++[>++++++<-]>.

How about using log10() : ceil(log10(abs(n)) EDIT: this won't work for powers of 10!

This took me longer than it should have, but here's a working pure math solution : floor(log10(abs(n))) + 1

@plg I'm just realizing that both of our solutions fail when x=0

Perl
s/\D//;$_=length

run as:
perl -ple 's/\D//;$_=length'

works correctly for negative, and "Perl style" numbers like 1_000_000

Nice use of s///, but I think you need a g at the end for numbers like 1_000_000_000? Also, how about $_=s/\d//g? :)

Unfortunately this returns the length of all input whether its an integer or not :( For eg. AAA returns 0 & a1a2 would return 2.

@draegtun This is codegolf; The question says nothing about invalid input, so you ignore it ("Given an integer n ...").

@daniero - Yes I maybe being pernickety however the example input/output provided does (currently!) show that an empty line returned as is.  Also note the constraint.

@draegtun There is no specification anywhere; The empty line could just as well be a way to separate two examples (in markdown two lines indented by four spaces, separated by an empty line, will show up as one code block). Other answers seem to behave similarly or disregard empty line as well. I read the constraint as "don't worry about numbers larger than 10^9".

@daniero - The question with the examples provided are a specification.  It's just that they're ambiguous hence open to varying interpretation!    re: constraint - very possible indeed, as is probably the intention to only use positive integers.

If you care about input validation, perl -ple"$_=y/0-9//" seems like the proper way to do it.

python 2, 25
print len(`abs(input())`)

works for both positive and negative integers

Dc: 3 characters
?Zp

Sample run:
bash-4.2$ dc -e '?Zp' <<< '12346'
5

bash-4.2$ dc -e '?Zp' <<< '345'
3

I like how this (unintentionally?) works for negative numbers if you use something like -123 as input.

PHP (30 chars)
echo $n<0?(strlen($n)-1):strlen($n)
(without php opening tags <?php & ?>)
Explanation
Pretty simple, ints can be interpreted as strings, therefore $n<0 has a minus-char that should be removed in the true-statement of the ternary operator. If its positive then we just count the length ;)

You need to count the tags, but you don't have to close them, and there is a shorter version (I think it was <?) so just prepend that to your code and you'll be good.

Java 8, 29 28 bytes
i->(""+(i<0?-i:i)).length();

Ungolfed test program
public static void main(String[] args) {
    IntFunction<Integer> func = i -> ("" + (i < 0 ? -i : i)).length();

    System.out.println(func.apply(12345)); //5
}

R, 25 bytes
cat(nchar(scan("stdin")))

Perl (with -lp) (11 bytes, counting lp)
$_=length

Ruby
$*.first.size

or
ARGV.first.size

Welcome, shemerey.  Remember... code-golf...  keep it short.  Why not simply $*[0].size? (Aside from the negative integers issue.)

Befunge-98, 8 or 12 chars
Single number (actually counts input bytes ≥15 and prints count at EOF)

#.~f`+#@

Multiline support (same as above, but print count at byte <15 and reset counter)

#@~f`:2*j\.+

I thought ~$1+2j@. makes more sense for single number.

I suppose so, but I wanted to support a trailing newline even for the single-number one, since it doesn't cost me anything.  As for the more straightforward 2j, I usually forget about that, but you're right that it's prettier that way.

C - 59 characters
main(k){scanf("%i",&k);printf("%i\n",(int)log10(abs(k))+1);}

You can save a character by changing your variable declaration to be inside the function declaration: main(k)

A DELPHI PROGRAM FOR CONSOLE
program P;
{$APPTYPE CONSOLE}
uses
  System.SysUtils;
var a: Integer;
begin
   readln(a);
   writeln(length(IntToStr(a)));
end.

Python 2, 22 bytes
lambda a:len(`abs(a)`)

I actually built this myself, before seeing Wasi's answer! This is how I thought of it:

I need: a lambda.
len? False! What about n<0? Should the - be counted? False!
How to eliminate the - in just a few bytes? abs!

[Thinking ends]

Seems this is one of only a few of the answers which actually account for negative integers. There go 5 bytes.

Go, 67 bytes
package main;import."fmt";func main(){s:="";Scan(&s);Print(len(s))}

len(strconv.Itoa(i))

JavaScript, 20
alert((""+n).length)

“SyntaxError: return not in function” – Why you changed the alert()?

@manatwork Ok I will change it. I thought it was shorter with return but forgot that return has one more character than alert.

k [7 chars]
f:{#$x}

Example:
f 12346
5

f 456
3

Though only 2 characters (#$) are required to find the length of the input number.
#$123444
6

Explanation
convert the input to string.
$123456
"123456"

count the number of characters:
#$123456
6

Q equivalent of this code:
f:{count string x}
f 123456
6

APL - 4 characters
ρ'n'

The first symbol, rho, checks the number of cells in an array, where one character of a string is equal to one cell.

R
The solution at 18 characters (identical in concept to the python solution of Wasi):
nchar(abs(scan()))

And the funnier one at 33 characters:
which(!abs(scan())%/%10^(1:9))[1]

GTB, 3
Assuming value is already stored:
l?_

To make user input:
`_l?_

Newline support with interactive input:
[`_~l?_]

Perl
15 chars - no input or constraint checks
$_=()=$_=~/\d/g

48 chars - checks input & constraint
$_=/^-?(\d+)$/?($1<=10**9?length($1)."\n":$_):$_

NB. If the input ($_) is an integer (positive or negative) and comes under the constraint then it amends $_ to the number of digits.  Otherwise it just leaves the input as is.
Usage example:
perl -ple '... insert above code...'

PowerShell (25)
($n-replace"-",'').length

where $n is a number

Incorrect for negative numbers

@AdamSpeight Arguably, the challenge is unclear (and the OP has yet to edit it in response to this and other points) with regards to negative numbers. However, adding negative number support would bring it to 39: $x="$n".length;if($n-ge0){$x}else{$x-1}

I have modified my answer, i think it should work for negative numbers.  The question is very unclear, it is unbounded on negative side.

@microbian Kill two more characters - the spaces are unnecessary.

Scratch another character - substitute '-' instead of "\D".

@Iszi, thanks.  Should have thought about the '-' already.

C, 63 59 57 characters
It's slightly longer than the other C solution, but it works on arbitrarily large numbers (numbers with 2^32 - 1 digits rather than numbers up to 2^32 - 1).
EDIT: It's now shorter than the other C solution!
c;main(n){n-10?main(getchar(),c+=n>47):printf("%d\n",c);}

Note: if you call the program with exactly 9 arguments, it will fail.  But why would you do that??

bash - 19 characters
Assuming input via standard input:
grep -o [0-9]|wc -l

Multi-line version - 48 characters:
while read L;do echo $L|grep -o [0-9]|wc -l;done

Tcl, 26 bytes
puts [string length $argv]

Try it online!

05AB1E, 2 bytes
þg

Try it online or verify all test cases.
Explanation:
þ     # Take the digits of the input
 g    # And output the length

Japt, 2 bytes
ìl

Try it
ì converts to a digit array and l gets the length.

RProgN 2, 2 bytes
âL

Gets the length of the Absolute Value of the input. Trivial.
Try it online!

Braingolf, 5 bytes
!s*dl

Try it online!
As with all the others, abs then len

Thing, 12 bytes
idh\-=[tLe]L

Try it online!
How?
Gets input from command line arguments. If the first character of input is "-", push the length of the all but first items of the string and immediately end the program. Else, push the length of the string. Then implicitly print.
Does not work with multiline.
i push input
d duplicate
h first character of
\- push the character "-"
= if top two values are equal, push 1, if not, 0
    [ if top value is truthy (not [] or 0), go into the block. if not,  go past the end of the block.
    t push the all but first items of the stack's top value (literally s[1:] in python)
    L length
    e end the program
    ] end loop
L length

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


text:
Enlarge ASCII art
In this challenge, you must take multiline ASCII art as input, such as:
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OO      OOOOOOO
OO      OO    OO OO   OO OO          OO       OO    OO OO      OO
OO      OO    OO OO   OO OOOOO       OO   OOO OO    OO OO      OOOOO
OO      OO    OO OO   OO OO          OO    OO OO    OO OO      OO
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OOOOOOO OO

And you will also take an integer as input. You must output the ASCII art enlarged by the amount specified with the integer. For example, if you used a second argument of 3, the output would be
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOO                  OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOO                  OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOO                  OOOOOOOOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO                     OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO                     OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO                     OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO                     OOOOOO         OOOOOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO                     OOOOOO         OOOOOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO                     OOOOOO         OOOOOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO            OOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO            OOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO                              OOOOOO            OOOOOO   OOOOOO            OOOOOO   OOOOOO                  OOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO   OOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO   OOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO                  OOOOOOOOOOOOOOOOOO         OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO   OOOOOO

Specifically, each character must turn into an n by n box of that character, where n is the integer argument. For example, an input of
ab
cd

and 3 will result in
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

This is code-golf, so the shortest code in bytes wins.

ascii art looks interesting on the questions list

I think you should make a secondary/bonus round for a method that introduces proper aliasing into the enlarged art.  Your giant code golf art is looking pretty blocky.

@AmeliaBR See here.

APL, 7 chars/bytes*
{⍺/⍺⌿⍵}

Function that takes the number and input string as parameters and returns the result:
      a
abcde
fghij
      2 {⍺/⍺⌿⍵} a
aabbccddee
aabbccddee
ffgghhiijj
ffgghhiijj
      3 {⍺/⍺⌿⍵} a
aaabbbcccdddeee
aaabbbcccdddeee
aaabbbcccdddeee
fffggghhhiiijjj
fffggghhhiiijjj
fffggghhhiiijjj

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars that only uses ASCII characters and APL symbols can be considered to be N bytes long.

... :O How does it work?

@DoorknobofSnow The standard representation for a multiline string is APL is a rectangular character matrix (with trailing blanks if the lines have uneven width… yes, APL is that old.) The / function (not to be confused with the / operator… yes, same symbol) duplicates and/or removes columns from a matrix according to the left-side argument. If that is a scalar (simple number) then it's replicated for all input columns. Therefore 2/m is a matrix with all columns doubled. The ⌿ variant does the same, but for rows (or first-axis planes in the general case.)

Beautiful language, isn't it? It's actually pretty readable, once you learn a few dozen symbols. Much more so than the ASCII line-noise languages you see around here…

Cool. Was ⌿ always in the language? It wasn't in the Gilman and Rose book, and an Iverson book on APL\360 mentions /[1] but not ⌿ .

@MarkPlotnick No, it wasn't always there. I just checked the IBM APL2 reference and it doesn't mention it. But the latest ISO standard does (search for "ISO 13751", there's a pdf floating around) and all interpreters I have at my disposal recognize it: Dyalog, MicroAPL, and the recent GNU APL and https://github.com/ngn/apl

@MarkPlotnick I recently went back to the Gilman and Rose book and my copy (third edition) does mention ⌿ at least on Chapter 14, under Replication and compression on two-dimensional arrays.

@Tobia Thanks. I went back to my first edition and read more closely, and it is mentioned there.

Wow. That. Is. Just. Awesome. I. Am. Severely. Awestruck. By. This. Code. I would like to offer more than a mere +1, but my rep is quite low for a bounty yet.

@EriktheGolfer I recommend learning APL, even if you'll never use it for anything serious. Dyalog APL is the best interpreter, if you look carefully you should find a free (as in beer) version. Their manuals and snippet repositories are free and are the best too. If you want a gentler approach, the Gilman and Rose book we were discussing is still the best book. You can find it used for a few bucks.

@Tobia Generally, I'm into [tag:kolmogorov-complexity] constant output challenges, so /// or Jelly would suffice there. Besides, I'm learning Jelly now, and APL has some strange symbols that I can't type, but I might learn it. It's not a golfing language though.

GolfScript, 20 characters
n%(~{.{*}+@1/%n+*}+/

Takes all input from STDIN, first line is the scaling factor, the rest the multiline-input. You can try the example online.
Input
3
ab
cd

Output
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

Code
n%            # Split the input into separate lines
(~            # Take the first line and evaluate (factor)
{             # {...}+/ adds the factor to the code block and loops over
              # the remaining lines (i.e. the factor will be the top of stack
              # for each line of input
   .{         # Same thing, duplicate factor and add it to code block and
              # loop over each character (1/ splits the string into chars)
     *        # multiply single-char string with factor
   }+@1/%
   n+         # Join string by adding a newline
   *          # Multiply the line by the factor (left from the . operation)
}+/

Hey! You've got a better input format, score and time than me :-/ +1

Also, I'm kinda lost reading it.

@JanDvorak Added some explanation.

Wow. Today I've learned 1/. I also need to use value function + more.

Trying to figure out how to use GolfScript. echo inputFile | ./golfscript.rb scriptFile gives me an error...

@CoryKlein: It would kind of help if you told us what error, but... gazes into crystal ball ...it may be that golfscript.rb is not marked executable, or that the first line has the wrong path to the Ruby interpreter for your system. Oh, and that echo should presumably be cat. Try cat inputFile | ruby golfscript.rb scriptFile (or just ruby golfscript.rb scriptFile < inputFile) and see if that works.

@IlmariKaronen You're right, the echo was the problem. facepalm, what a newb mistake.

J, 20 17 characters
f=.([#&.|:#)];._2

Defines a verb f that does what is required. Usage:
   3 f a
aaaccc
aaaccc
aaaccc
bbbddd
bbbddd
bbbddd

where a is the input string.
On Windows an extra character is required to remove the \r:
f=.([#&.|:#)}:;._2

Explanation:
];._2 chops the input string into chunks based on the last character of the string, which in this case will be a \n. Windows has \r\n so we need to use }: to chop an extra character off: }:;._2. Cut verb documentation
The rest of the code (with the exception of the assignment f=.) is a fork.
It breaks down like this: [  #&.|:  #
If a is our input string the calculation will be 3 # a (we'll call this result x), then 3 [ a (we'll call this result y) then y #&.|: x.
3 # a just makes three copies of every member of a. Copy verb documentation
This turns
ab
cd

into
aaabbb
cccddd

3 [ a just returns 3. Left verb documentation
Finally y #&.|: x is y copy under transpose x. The # works as before, but the &.|: tells J to transpose the input first and then transpose it back when it's finished. Under conjunction documentation, transpose verb documentation.
The transpose turns
aaabbb
cccddd

into
ac
ac
ac
bd
bd
bd

then the copy changes it to
aaaccc
aaaccc
aaaccc
bbbddd
bbbddd
bbbddd

and transposing it back gives you
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

Windows sucks, eh? :P

@Trimsty Indeed it does.

This is shorter: [##"1 Also, I'm not sure about the unwritten rules of golfing in J, but I'd say the string splitting and the assignment could be omitted, given the question's loose requirements. I certainly did so in my APL answer. Example: 2 ([##"1) 'abcde',:'fghij'

Haskell, 49 bytes
x=(=<<).replicate
e n=unlines.x n.map(x n).lines

The enlarge function is e, which takes a count and a string, and returns a string:
λ: putStrLn $ e 3 "ab\ncd\n"
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

APL, 11 chars
@Gareth did essentially the same thing first, in J, so this APL entry is just for exhibition, not competition - he's the winner.
      E←{⍉⍺/⍉⍺/⍵}

Usage: magnification in left arg (⍺), art in the form of a 2d character matrix in right arg (⍵).
⍺/⍵ will replicate elements across each row of a vector or matrix (2/'O O' becomes 'OO OO').
⍉⍺/⍉ will transpose that, replicate the elements, transpose that.
(If we were going for clarity instead of program length, the code could have been E←{⍺/[1]⍺/⍵}   )
      I←5 32⍴' OOOOOO  OOOOOO  OOOOOO  OOOOOOOOO      OO    OO OO   OO OO     OO      OO    OO OO   OO OOOOO  OO      OO    OO OO   OO OO      OOOOOO  OOOOOO  OOOOOO  OOOOOOO'
      I
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO
OO      OO    OO OO   OO OO
OO      OO    OO OO   OO OOOOO
OO      OO    OO OO   OO OO
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO

      3 E I
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOOOOOOOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
OOOOOO                  OOOOOO            OOOOOO   OOOOOO         OOOOOO   OOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO
   OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOO      OOOOOOOOOOOOOOOOOOOOO

I should point out though, that I use 5 chars turning the string input into a character array, so you only beat me by 1 character really. :-)

J is hobbled by that pesky design goal in which operators are restricted to the ASCII character set. :)

Though, if we measure in bytes like the OP said, this is 44 bytes (implying unicode of course, not utf-8) and @Gareth's is still 17. That's the downside to languages that aren't restricted to ASCII.

@Trimsty But APL has it's own character set which maps each character to a single byte, so arguably this is still 11 bytes.

@Volatility Hm. That's really weird, sorry, didn't know :P

Bash/sed script, 48 chars
printf -vr %$1s
sed -n s/./${r// /&}/g${r// /;p}

Save as a script, chmod +x and run:
$ ./asciiexpand 3 <<< $'ab\ncd'
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd
$

How does it work?
The meat of it is in the sed command.  For example, if n=3, then the sed command is expanded to something like:
sed -n 's/./&&&/g;p;p;p'

This compound sed command can be broken up into:

s/./&&&/g - this substitute command matches each character and replaces it with the character repeated 3 times
3x p commands - this just prints the whole pattern space (i.e. the current line) 3 times

We pass -n to sed to tell it not to print anything unless explicitly told to, so we have full control of what is printed and how many times.
I couldn't figure out a quick way to generate arbitrary-length repeating strings directly in sed, so I used some bash tricks instead:
printf -vr "%3s"

This prints a string (not specified, i.e. empty), with 3 leading spaces, and assigns the result to the bash variable r.
We then use bash parameter expansion to transform this string of spaces to what we need substituted into the sed expression:
$ echo ${r// /&}
&&&
$ echo ${r// /;p}
;p;p;p
$

I was able to get away with removing quotes around the printf format specifier and the sed expression, as none of the characters within need escaping in the bash shell.
Character count:
$ submission='r=`printf %$1s`
> sed -n s/./${r// /&}/g${r// /;p}'
$ echo ${#submission}
48
$

I don't have an idea how this works but it works!

Variable n violates rule 1: “may NOT be hardcoded”.

Just use $1 and remove n=3;, you will even save 4 characters and maybe the {} in the printf too.

And as we can assume $1 will be numeric, the quotes around printf's argument are not necessary, reducing it to 52 characters: r=\printf %$1s`;sed -n "s/./${r// /&}/g${r// /;//p}"`.

@manatwork - my assumption was that it was the input text that shouldn't be hardcoded.  But I think you're right, and using $1 allows extra golfing.  Thanks for the tips!

@Tomas - You've probably figured out how it works by now, but I added a description in case you're interested.

Awesome demonstration of power of shell!! ( Ungolfed version may prefer syntaxe printf -v r %$1s to prevent useless forks, but this implie 1 more char... :-)

@F.Hauri - interesting!  In fact we could do printf -vr %$1s for the same number of chars.  But would a fork occur in the former case, given printf is a bash-builtin?

@DigitalTrauma Yes, it's the only way to modify environment (a fork can't modify parent environment). And yes, -vr work without adding one char. It's definitively a better solution;-)

PERL,  41 39  25   22 chars
PERL, simple and effective - created right for the task. When invoked with -pi3, where 3 is the parameter n:
s/./$&x$^I/ge;$_ x=$^I

Classical solution (39 chars):
$n=<>;print map{s/./$&x$n/ge;"$_"x$n}<>

Classical solution needs the n is specified in the first line of input, e.g.
3
ab
cd

Thanks @manatwork for the $& trick.

Cool. But you not need to capture the matched characters: s/./$&x$n/ge.

Ruby:  64  49 characters
All data received on STDIN: first line the scaling factor, then the ASCII art.
BEGIN{n=gets.to_i}
$_=[$_.gsub(/./){$&*n}]*n*$/

Sample run:
bash-4.2$ ruby -lpe 'BEGIN{n=gets.to_i};$_=[$_.gsub(/./){$&*n}]*n*$/' <<< '3
> ab
> cd'
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

Ruby:  44  41 characters
Assuming that every input line is terminated with line separator. Thanks to @Ventero.
$.<2?n=$_.to_i: $><<$_.gsub(/./){$&*n}*n

Sample run:
bash-4.2$ ruby -ne '$.<2?n=$_.to_i: $><<$_.gsub(/./){$&*n}*n' <<< '3
> ab
> cd'
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

A shorter way to set n: $.<2?n=$_.to_i: $><<$_.gsub(/./){$&*n}*n (sadly, the space after the colon is necessary, otherwise the parser gets confused). Run with ruby -n.

Doh. I tried dozens of approaches to shorten the assignment to n, but I missed the ternary operator. Thank you, @Ventero.

Python 3 - 84
Not the shortest but a different answer nonetheless. An interesting one-liner.
n=int(input())
for i in eval(input()):print(((''.join(j*n for j in i)+'\n')*n)[:-1])

Put in a number first, then the ASCII art as a Python list, e.g.:
C:\Users\User4\Desktop>c:/python33/python.exe golf.py
3
["aabb","bbcc","ccdd"]
aaaaaabbbbbb
aaaaaabbbbbb
aaaaaabbbbbb
bbbbbbcccccc
bbbbbbcccccc
bbbbbbcccccc
ccccccdddddd
ccccccdddddd
ccccccdddddd

GolfScript, 29 characters
{:i;n/{1/:c;{c{i*}/n}i*}/}:f;

This defines a block f, that when called will produce the desired output. It assumes arguments are on the stack (because that's basically how arguments are passed in GolfScript).
Ungolfed (does that even make sense? :P):
{:i;n/{ # for each line...
  1/:c; # save characters of string in c
  {     # i times...
    c{  # for each character...
      i*
    }/
    n
  }i*
}/}:f;

# Test run
"ab
cd" 3 f

Python 3 - 109 107 93
i=input;n,s,a=int(i()),i(),[]
while s:a+=[''.join(c*n for c in s)]*n;s=i()
print('\n'.join(a))

First, input the number, then the string. Should be self-explanatory...
Thanks to Waleed Khan for suggesting removing the []
Thanks to Volatility for suggesting having a be a list.

Just noticed; the nsa is watching your every input

Shortest code in bytes. Wouldn't that then include newlines? Shouldn't your count be 112?

Sorry, I meant 111.

@Trimsty you are right; I thought wordcounter.net counted newlines.

You can remove the []s of your list comprehensions to get generator expressions, which will work just as well.

Make a into a list, do a+=[''.join(c*n for c in s)]*n, then do print('\n'.join(a)) at the end. That should work.

I don't think you need a at all:  i=input;n,s=int(i()),i() ... while s:print('\n'.join([''.join(c*n for c in s)]*n);s=i()

@StevenRumbalski small problem with your method (other than a missing )); it prints for each line, not at the very end.

Golfscript, 23 characters
~(:i;n/{{{.}i*}:c%c}%n*

I've decided to write an entire program because it has less overhead than even an anonymous function does:

~(:i; - eval the input, then  decrement the multiplier, store it as i and discard.
n/{...}%n* - split by newlines, map each line, join by newlines

{...}:c%c, - take a block, apply it on map-each element, then apply it to the whole line.

{.}i* - duplicate this element i times

Live demo: http://golfscript.apphb.com/?c=OyciYWJjCmRlZiIzJwp%2BKDppO24ve3t7Ln1pKn06YyVjfSVuKg%3D%3D
Example usage:
;'"abc
def"3'
~(:i;n/{{{.}i*}:c%c}%n*

Java - 217
First try at golfing. Seems like Java isn't the language to do it in.
enum M{;public static void main(String[]a){int f=new Integer(a[0]),i=0,j,k;a=a[1].split("\n");for(;++i<a.length*f;System.out.println())for(j=0;++j<a[i/f].length();)for(k=0;k++<f;)System.out.print(a[i/f].charAt(j));}}

On Windows you need to replace "\n" with "\r\n".
java M 3 "ab
cd"
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

Are you sure the input is correct?

Ah, your right it should be abcd typo :/

The input characters need to expand downwards as well as across (so there should be 3 lines of aaabbb and 3 lines of cccddd in your output example above).

@Gareth darn, missed that too. Should be fixed now.

You can spare: 1 character by initializing i in the declaration instead of the for; 8 characters by using a instead of x (a=a[1].split("\n"), and change all x with a).

Yeah, with any language where just the declaration of main takes more bytes than entire programs in other languages, contestants are going to be getting bogeys.

Spare another byte by replacing for(k=0;k<f;k++) with for(k=0;k++<f;)

Doesn't seem optimal to write out System.out.print twice; I'd suggest something like making an empty string, append to it instead of the first ...print and then println it at the end.

Reusing a[0] and appending to it to print, ended up with the same amount of chars for me.

Hm ok. Here is 3 chars saved by rearranging the outter for loop a little bit: enum M{;public static void main(String[]a){int f=Integer.valueOf(a[0]),i=-1,j,k;a=a[1].split("\n");for(;++i<a.length*f;System.out.println())for(j=0;j<a[i/f].length();j++)for(k=0;k++<f;)System.out.print(a[i/f].charAt(j));}}

Another 4 bytes: Integer.valueOf(a[0]) -> new Integer(a[0])

Thanks all. Seems I still need to learn a few trick on minifying my code.

(Edit: This solution is now invalid because the semantics of the 銻 instruction has changed. I didn’t realise that I’d already made use of the instruction when I changed it. You can, however, fix ths program by simply changing it to the newer instruction 壹.)
Sclipting, 19 characters
Expects the input to be separated by \n (no \r) and the first line to contain the multiplying factor.
겠坼銻標⑴가殲各標⓶各①復終겠併①復終

Explanation
겠坼 | split everything at \n
銻 | get first element (the factor)
標 | mark
⑴가殲 | bring list to front; remove first element (the factor)
各 | for each line...
    標⓶ | mark
    各①復終 | for each character, multiply it
    겠併 | add a newline and concatenate everything above the mark
    ①復 | multiply that
終 | end of loop

At the end, the stack will look like this:
[ factor, mark, line1, line2, line3, ... ]

Everything above the mark is automatically concatenated and output, the rest discarded.

这太有意思了！你是原创者对吧？

@theGreenCabbage 对了. 踢木外 是 这个 电脑语言 的 创始人

@Timwi sorry for calling you 踢木外 (kick wood outside, pronounced tea-moo-why)...

@Quincunx: Hehe, I found it funny :) But the final i is pronounced [iː], not [ɑi]; how would you write it in Chinese now?

@Timwi Thought that's how it is pronounced (but I couldn't think of a corresponding character). I wrote by searching and copy-pasting (on http://www.mdbg.net/chindict/chindict.php)

Due to the trainwreck that is Mandarin, nothing is pronounced /wi:/ despite Mandarin having /i:/. The closest are /wei/ /wai/ /i:/

Right. "Kicking wood outside" is the founder of this computer language.

J, 7 chars
([#"1#)

Exact same thing as in @Tobia's APL answer, but in ascii chars.
a =. ' 0 ',.'0 0',.' 0 '
a
 0
0 0
 0

2 ([#"1#) a
  00
  00
00  00
00  00
  00
  00

Powershell (96)
function m($n,$s){$s.split("`n")|%{$l="";$_.ToCharArray()|%{$c=$_;1..$n|%{$l+=$c}};1..$n|%{$l}}}

Thought I'd give this a shot in PS.
Using piping into foreach's (%) to keep it short here, but the function and ToCharArray are making it take a hit it brevity.
To use it, you call it from the command line like this:
PS C:\> m 3 "ab
>> cd"
>>
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

Here's the non-minimised version:
function f($n, $s)
{
    $s.split("`n") | % {            # split input into separate lines
        $l=""                       # initialize an output line
        $_.ToCharArray() | % {      # split line into chars
            $c=$_ ; 1..$n | % {     # add n chars to the line
                $l+=$c
            }
        }
        1..$n | % {$l}              # output the line n times
    }
}

Mazzy suggested function m($n,$s){-split$s|%{,(-join($_-split''|%{$_*$n}))*$n}} for 63 bytes

Julia, 74 chars/bytes
julia> f(i,n)=print(prod([(prod(["$c"^n for c in l])*"\n")^3 for l in split(i)]))
f (generic function with 1 method)

julia> f("ab\ncd",3)
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

7 less if I just return the string. julia> is the interactive prompt.

This is the first Julia golf I've seen.

@Trimsty http://codegolf.stackexchange.com/search?q=julia still very rare, but they have been a few (including by one of the designers of the language actually).

@plannapus Interesting! There's a new, rare esolang called ~-~! that I've used as well, though it's terrible for golfing.

Canvas, 2 bytes
：＊

Try it here!

R, 83/72 bytes
Alt approach using regexps
If we're allowed a trailing newline, 72 bytes:
function(s,n)cat(gsub("([^
]*
)",r,gsub("([^
])",r<-strrep("\\1",n),s)))

Try it online!
Otherwise, 83 bytes:
function(s,n)write(rep(el(strsplit(gsub("([^\n])",strrep("\\1",n),s),"\n")),e=n),1)

Try it online!

Powershell, 54 bytes
param($s,$n)$s-replace'.',('$0'*$n)-split'
'|%{,$_*$n}

Test script:
$f = {

param($s,$n)$s-replace'.',('$0'*$n)-split'
'|%{,$_*$n}

}

@(
@"
ab
cd
"@
,
@"
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OO      OOOOOOO
OO      OO    OO OO   OO OO          OO       OO    OO OO      OO
OO      OO    OO OO   OO OOOOO       OO   OOO OO    OO OO      OOOOO
OO      OO    OO OO   OO OO          OO    OO OO    OO OO      OO
 OOOOOO  OOOOOO  OOOOOO  OOOOOOO      OOOOOO   OOOOOO  OOOOOOO OO
"@
) | % {
    &$f $_ 3
}

Explanation:

$s-replace'.',('$0'*$n) repeats each symbol exept new line.
-split'``n' splits the wide string by new line
|%{,$_*$n} repeats each line as an array element and returns array

The result is an array of wide and repeated strings.

Vyxal j, 3 bytes
•εf

Try it Online!
I/O is as lists of lines. The j flag formats the output into ASCII art.
•   # Repeat each character of each line by the number
 ε  # Repeat each line by the number
  f # Flatten

Extended BrainFuck : 158
{a<]<[->+}3>,>3+[->4+[-<<4->>]&a>+<<]<+[-<,[>10+[-<->>+<]<[[->>+<<]3>[->[->+&a&a#3<+>>]>>]<[-]<<]>>[>[-4<[<]>[.>]>>.>]4<[-]<[-]4>[-]]>>[->+<]>[-<+<+>>]4<+<]>]

It turns into:
Brainfuck: 185
>>>,>+++[->++++[-<<---->>]<]<[->+>+<<]<+[-<,[>++++++++++[-<->>+<]<[[->>+<<]>>>[->[->+<]<[->+<]<[->+<<<+>>]>>]<[-]<<]>>[>[-<<<<[<]>[.>]>>.>]<<<<[-]<[-]>>>>[-]]>>[->+<]>[-<+<+>>]<<<<+<]>]

It requires an interpreter that either has 0 or no change as EOF marker. beef, available from Ubuntu repos, works swell:
$ ( echo -n 2
> cat <<eof
> BBBB  RRRR   AAA  IIII NN  NN FFFFF * * * KK  KK
> BB BB RR RR AA AA  II  NNN NN FF      *   KK  KK
> BBBB  RRRR  AAAAA  II  NNNNNN FFFF  ***** KKKKK
> BB BB RR RR AA AA  II  NN NNN FF      *   KK  KK
> BBBB  RR RR AA AA IIII NN  NN FF    * * * KK  KK
> eof
> ) | beef double.bf
BBBBBBBB    RRRRRRRR      AAAAAA    IIIIIIII  NNNN    NNNN  FFFFFFFFFF  **  **  **  KKKK    KKKK
BBBBBBBB    RRRRRRRR      AAAAAA    IIIIIIII  NNNN    NNNN  FFFFFFFFFF  **  **  **  KKKK    KKKK
BBBB  BBBB  RRRR  RRRR  AAAA  AAAA    IIII    NNNNNN  NNNN  FFFF            **      KKKK    KKKK
BBBB  BBBB  RRRR  RRRR  AAAA  AAAA    IIII    NNNNNN  NNNN  FFFF            **      KKKK    KKKK
BBBBBBBB    RRRRRRRR    AAAAAAAAAA    IIII    NNNNNNNNNNNN  FFFFFFFF    **********  KKKKKKKKKK
BBBBBBBB    RRRRRRRR    AAAAAAAAAA    IIII    NNNNNNNNNNNN  FFFFFFFF    **********  KKKKKKKKKK
BBBB  BBBB  RRRR  RRRR  AAAA  AAAA    IIII    NNNN  NNNNNN  FFFF            **      KKKK    KKKK
BBBB  BBBB  RRRR  RRRR  AAAA  AAAA    IIII    NNNN  NNNNNN  FFFF            **      KKKK    KKKK
BBBBBBBB    RRRR  RRRR  AAAA  AAAA  IIIIIIII  NNNN    NNNN  FFFF        **  **  **  KKKK    KKKK
BBBBBBBB    RRRR  RRRR  AAAA  AAAA  IIIIIIII  NNNN    NNNN  FFFF        **  **  **  KKKK    KKKK

Ungolfed EBF code:
;;;; Multiply
;;;; Takes a digit x and ASCII art on STDIN
;;;; Prints ASCI art scaled x times
;;;; Usage:
;;;; bf ebf.bf < multiply.ebf >multiply.bf
;;;; bf multiply.bf

;;; Memory map for this program
:zero
:str
:flag
:tmp
:dup
:num

;;; Macros

;; EOL support. Comment out the body of the two
;; macros below to only support 0 and no change
;; Some interpreters use -1
{eol_start
  +(-
}

{eol_end
   )
}

;; macro that reads a digit.
;; the actual number is one more than input
;; ^12 uses 3 cells from origin
{read_number
  ,                    ; read char
  ^1 3+(-^2 4+(-^ 4-)) ; reduce by 3*4*4=48
}

;; duplicate current element
;; to the left using the right as tmp
{copy_left
  (-^1+)^1(-^0+<+)
}

;; Duplicate char n times while
;; shifting to the right
{handle_char
  $str(-$tmp+)               ; copy the char to tmp
  $dup(-$num(->+)            ; for each dup move num
        $dup(-$num+)         ; and dup one step to the right
        $tmp(-$dup+$str+)    ; and copy the char back to str and to dup
        @flag)               ; which is the new tmp (it gets shifted to the right)
  $tmp(-)                    ; clear char when done
}

{handle_linefeed
  $dup(-                     ; for each dup
    $zero[<]>                ; go to beginnning of string
    [.>]@str                 ; print string
    $tmp.                    ; print newline
  )
  $zero[-]<[-]>@zero         ; clean last two chars
  $tmp(-)                    ; remove line feed
}

;;; Main program

;; read number
$tmp &read_number
$tmp (-$dup+$num+)
;$tmp,[-] ; uncomment to require a newline before asci art
$flag+(-
  $str = ,
  ( ;; NB! The line containing EOF will not be printed!
    &eol_start
    $flag 10+(-$str-$tmp+)
    if $str is not linefeed (
       &handle_char
    ) $tmp ( linefeed
       &handle_linefeed
    )
    $num &copy_left      ; we need two copies of the duplicate dupber
    $flag+               ; flag to
    &eol_end
  )
)

Rebol - 87 79
r: do input while[d: input][forskip d r[insert/dup d d/1 r - 1]loop r[print d]]

Nicely formatted version:
r: do input

while [d: input] [
    forskip d r [insert/dup d d/1 r - 1]
    loop r [print d]
]

Usage example:
rebol -qw --do 'Rebol[]r: do input while[d: input][forskip d r[insert/dup d d/1 r - 1]loop r[print d]]' <<< "3
ab
cd"
aaabbb
aaabbb
aaabbb
cccddd
cccddd
cccddd

NB. This code only works in Rebol 2 at this moment (The INPUT function used is not fully implemented in Rebol 3 yet).

K, 20
.....
{,/y#',:',/'y#'/:x}

R, 125 bytes
function(s,n,x=utf8ToInt(s),m=matrix(x[u<-x!=10],,sum(!u)+1))for(i in 1:ncol(m))cat(rep(intToUtf8(rep(m[,i],e=n)),n),sep="
")

Try it online!
Converts string to UTF8, puts into a matrix whose columns are lines of text (removing newlines), and then repeats each char and the generated lines before printing separeated by newlines.

congrats on 1K by the way! :-)

ty :-) ! It's great to see R answers to most questions and even multiple answers to some questions.

R - 89
M=function(I,N) cat(paste(lapply(lapply(strsplit(I,""),rep,e=N),paste,collapse=""),"\n"))

I <- c("aa  aa  aa", "bbb bbb bbb", "c c c c c c")
N <- 3

I
# aa  aa  aa
# bbb bbb bbb
# c c c c c c"

M(I,N)

# aaaaaa      aaaaaa      aaaaaa
# bbbbbbbbb   bbbbbbbbb   bbbbbbbbb
# ccc   ccc   ccc   ccc   ccc   ccc

Looks interesting. But I get an error: “Error: could not find function "str_split"”. Do I need to explicitly install the stringr package to be able to run your code? (Sorry, not familiar with R.)

isn't it missing a call to cat to print it as stdout? Additionally each element of the string should not just be repeated n times in length but be repeated also in breadth.

You can also golf your function a bit more: <- can be =, paste0 can here be replaced by paste since you're using the collapse argument anyway and the argument each can be shorten to e. See here for some basic ideas on golfing with R.

Otherwise, it's a nice attempt (my own shortest attempt is still in the 200 characters or so :) )

@manatwork ok, no error anymore wihtout loading stringr

@plannapus thanks for the comments, I added a cat ... as every character in every string (provided as character vector) is repeated it really should scale the any asci-art :-)

MATLAB: 20 characters
['' imresize(ans,n)]

This solution assumes that the image is stored in a file called startup.m and that it is allowed to give the amount of replications to matlab when calling it, this can be done by means of: !matlab -r "n=3"&
MATLAB, call without argument: 23 characters
load;['' imresize(s,n)]

Unlike the first solution, the latter two assume that the amount of replications may not be expected in the call. For these solutions the original string and number are expected in a file called matlab.mat in your current directory.
MATLAB, mathematical alternative: 27 characters
load;['' kron(s,ones(1,n))]

C# (177)
public string e(string i,int x){return string.Join("",i.Split('\n').Select(a=>string.Join("",Enumerable.Repeat(string.Join("",a.ToCharArray().Select(c=>new string(c,x))),x))));}

Expects input string "i" containing new lines "\n" as the delimiter.
Formatted
public string e(string i, int x)
{
    return string.Join("", i.Split('\n').Select(a => string.Join("", Enumerable.Repeat( string.Join("", a.ToCharArray().Select(c => new string(c, x))), x))));
 }

CJam, 14 bytes
CJam is newer than this challenge (and the main feature I'm using is actually very recent), so this answer wouldn't be eligible for being accepted - but it's not beating APL anyway, so...
l~qN/1$e*fe*N*

Test it here.
Explanation
With the new e* which repeats each character in a string, this is really straightforward:
l~             e# Read and eval the scale factor.
  qN/          e# Read the rest of the input as the ASCII art and split into lines
     1$e*      e# Copy the scale factor and repeat each line by it.
         fe*   e# Repeat the characters in each line by the scale factor.
            N* e# Join with newlines.

I realize this is an old answer, but you can save a byte by using a function instead: {N/1$fe*e*N*}

RProgN 100 Bytes (Windows) Non-Competing
'l' asoc
'i' asoc
i '[^
]' '%0' l rep replace '[^
]*' '%0
' l rep 'z' asoc z 1 z len 1 - sub replace

RProgN doesn't have character escapes as of writing, which makes any handling of new lines require a physical new line. As such, this answer (and any input) has to use CRLFs, instead of just LFs. :(
Also, the 'rep' function was only added after this challenge was issued, as such, this is non-competing.

Vim, 39 keystrokes (excluding input, not competing)
the gotcha and the reason this is not competing is because the input has to be entered twice. Replace both 2 with your own input.
qayl2phxl@aquu:%norm @a<cr>gg0qbyy2P2jkddj@bq@b

Explanation

qayl2phxl@aquu records a macro that yanks a character, paste it and move to the next one, then replays itself. Then it undoes the changes. Because we want the loop not to be infinite, we don't delete the character, which means we have to delete the extraneous one but still finish with a movement that fails on the last char.
:%norm @a<cr> runs the macro on every line
gg0 returns to the very beginning
qbyy2P2jkddj@bq@b uses the same technique as @a to copy every line, but with a recursive macro.

I know this can be golfed more, e.g. by traversing backwards for line duplication but because of the multiple input entry requirement, I will stop there and mark this answer as non competing.
Previous answer (32 keystrokes,  only doubles)
qaylpl@aqu:%norm @a<cr>:%s/.*/&\r&<cr>

Explanation

qaylpl@aqu records a macro that yanks a character, paste it and move to the next one, then replays itself. Undo the change.
:%norm @a<cr> runs the macro on every line
:%s/.*/&\r&<cr> doubles every line

I wanted to do a nested macro, but the inner one (characters) stops the outer one (lines)... So I have to run two commands, adding quite a few keystrokes to an otherwise simple solution.

C (gcc), 113 bytes
i,j;f(s,n)char*s;{char*p;for(;*s;s=*p?++p:p)for(i=n;i--;puts(""))for(p=s;*p&&*p^10;p++)for(j=n;j--;)putchar(*p);}

Try it online!

Suggest for(char*p;*s;s=p+!!*p instead of char*p;for(;*s;s=*p?++p:p

Japt, 11 bytes
yW=_mpVÃmWR

Try it online!
Unpacked & How it works
UyW=Z{ZmpV} mWR

Input: U = 2D string, V = magnification

Uy               map over columns of U...
    Z{ZmpV}        a function that repeats each char V times
  W=               assign this function to W
            m    and map again...
              R    over rows...
             W     the function W

JS's Assign-Anywhere™ trick in action.

K (ngn/k), 17 bytes
{,/+x#,+,/+x#,+y}

Try it online!

Japt -R, 10 9 bytes
·cÈVÇXmpV

Try it
·cÈVÇXmpV     :Implicit input of string U and integer V
·             :Split U on newlines
 c            :Flat map
  È           :By passing each X through the following function
   VÇ         :  Map the range [0,V)
     Xm       :    Map each character in X
       pV     :      Repeat V times
              :Implicit output joined with newlines

05AB1E, 12 bytes
U|εSX×JXи}˜»

Try it online.
Explanation:
U               # Take the integer input, and store it in variable `X`
                #  i.e. 3
 |              # Take the rest of the input-lines as list
                #  i.e. ["ab","cd"]
  ε      }      # Map each line to:
   S            #  Convert the line to a list of characters
                #   i.e. "ab" → ["a","b"]
    X×          #  And repeat each character `X` amount of times
                #   i.e. ["a","b"] and 3 → ["aaa","bbb"]
      J         #  Join the line back together
                #   i.e. ["aaa","bbb"] → "aaabbb"
       Xи       #  And repeat that line `X` amount of times
                #   i.e. "aaabbb" and 3 → ["aaabbb","aaabbb","aaabbb"]
          ˜     # Flatten the list of lists
                #  i.e. [["aaabbb","aaabbb","aaabbb"],["cccddd","cccddd","cccddd"]]
                #   → ["aaabbb","aaabbb","aaabbb","cccddd","cccddd","cccddd"]
           »    # And join by newline (which we implicitly output)
                #  i.e. ["aaabbb","aaabbb","aaabbb","cccddd","cccddd","cccddd"]
                #   → "aaabbb\naaabbb\naaabbb\ncccddd\ncccddd\ncccddd"

PHP, 115 bytes
function f($s,$l){foreach(explode("
",$s)as$a)for($i=$l;$i--;)echo preg_replace('/./',str_repeat('$0',$l),$a)."
";}

Try it online!

JavaScript (Node.js), 78 bytes
n=>k=>n.split`
`.map(e=>(e.replace(/./g,l=>l.repeat(k))+`
`).repeat(k)).join``

Try it online!
No JavaScript answer yet, so decided to try it out.


text:
Mechanical Coding
The goal is to calculate the output speed of a series of cogs.  The winner will be chosen by popular vote.
The arrangement of cogs is defined in an ASCII-art string:

O  large cog
o  medium cog
*  small cog
-  axle (one or more in a row)
=  chain (one or more in a row)

An example input is:
o*-O*==oO

o medium cog, meshed with * small cog, attached by - axle to O large cog, meshed with * small cog, connected by == chain to medium cog, meshed with O large cog.

The code takes five inputs by command line argument, standard in, or function parameter:

Arrangement
  Number of teeth on large cogs
  Number of teeth on medium cogs
  Number of teeth on small cogs
  Left-side speed in teeth per second (+ve is clockwise, -ve is anti-clockwise)

And outputs:

Right-side speed in teeth per second

Interactions between cogs and other components occur as follows:

SL = Speed of left cog
  SR = Speed of right cog
  TL = Teeth of left cog
  TR = Teeth of right cog
Two meshed cogs
O*
  SR = -SL
Two cogs connected by a chain of any length
O===*
  SR = SL
Two cogs connected by an axle of any length
O---*
  SR = SL * TR / TL

Any invalid arrangement can throw an error or return 0.
Test Cases
arrangement     O   o   *  speed  =>  speed

*-Oo-O         50  30  10    3.0  =>  -25.0
o*-O*==oO      50  30  10   -3.0  =>   15.0
O---*oO=O*-oo  15  12   8   10.0  =>    8.0
=o*            50  30  10   10.0  =>  error
o*-            50  30  10   10.0  =>  error
o-=*           50  30  10   10.0  =>  error
o *            50  30  10   10.0  =>  error

Javascript – animated version
Playing on with canvas again. Adding a sample going far out of the scope of the task. But, anyhow, here it is. It is an animated / paint version.
Issues
Can be a resource hog. In some quick tests it runs best in Chrome, worse in Opera and worst in Firefox. There is also an issue with movement as on relatively high speeds as the turn on each frame gets too big.
If one use small value for Teeth Width, it performs OK in various cases. Decor also has an impact.
By choice the use of Animation Frame or interval can be selected, and while using interval frames per second (FPS) can be tweaked. FPS can easily be lower then set if painting one frame takes longer.
If it only hogs, one can also use it to simply paint still images. Press Stop button and enter string to be parsed. With full decor it can be for a nice picture ;)
Try it out in this Fiddle.

Javascript code:
It could definitively have been tidied up some more and refactored.
requestAnimationFrame polyfill removed in this post due to limit of body length on SO.
var PI  = Math.PI,
    P2  = PI*2,
    cos = Math.cos,
    sin = Math.sin;

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function isNumbers(a) {
    var i;
    for (i = 0; i < a.length; ++i)
        if (!isNumber(a[i]))
            return 0;
    return 1;
}

function CogWheels() {
    this.can    = document.getElementById('can');
    this.ctx    = this.can.getContext("2d");
    this.cm = {
        main:{can: document.createElement('CANVAS'),ok:0}
        //gear:{can: document.createElement('CANVAS'),ok:0}
    };
    this.cm.main.ctx = this.cm.main.can.getContext("2d");

    this.ofs    = {x:10, y:50};
    this.grect  = null;

    this.parts  = [];
    this.pix    = {wheel:[],axle:[],chain:[]};

    this.sz     = {rb:100, rm:75, rs:50};
    this.dir    = 1;
    this.last   = null;
    this.tw     = 4;
    this.tl     = this.tw + 1;
    this.navcr  = 7.5;

    this.tsp    = null; // Timestamp previus frame
    this.raf    = 0;    // Use requestAnimationFrame
    this.mode   = 0;    // 1=Auto start
    this.decor  = 3;    // Decoration level
    this.shade  = 1;    // Use shading
    this.pin    = 1;    // Paint "pin"
    this.clr = {
        wheel: '#321',
        axle : '#852',
        chain: '#842',
        axis : '#a50',
        teeth: '#1a1108',
        pin  : '#f00',
        dec1 : '#321'
    };
}

var CW = CogWheels.prototype;

CW.getShadow = function() {
    return {
        x:this.ctx.shadowOffsetX,
        y:this.ctx.shadowOffsetY,
        b:this.ctx.shadowBlur,
        c:this.ctx.shadowColor.match(/\((.*)\)/)[1]
    };
};

CW.setShadow = function(p) {
    this.ctx.shadowOffsetX  = p.x || 0;
    this.ctx.shadowOffsetY  = p.y || 0;
    this.ctx.shadowBlur     = p.b || 5;
    this.ctx.shadowColor    = p.c ? "rgba("+p.c+")" : "rgba(0,0,0,.8)";
};

CW.noShadow = function() {
    this.setShadow({x:0, y:0, b:0, c:"0,0,0,0"});
};

/*
 * Drawings for static buffer.
 *
 * * */
CW.drawBulb = function(x, y, r) {
    var gradient = this.ctx.createRadialGradient(x, y, 0, x, y, r);
    gradient.addColorStop(1.00, 'rgba(0, 0, 0, 0)');
    gradient.addColorStop(0.95, 'rgba(40, 40, 40, 1)');
    gradient.addColorStop(0.85, 'rgba(85, 85, 85, 1)');
    gradient.addColorStop(0.70, 'rgba(170, 170, 170, 1)');
    gradient.addColorStop(0.40, 'rgba(250, 250, 250, 1)');
    gradient.addColorStop(0.00, 'rgba(255, 255, 255, 1)');
    this.ctx.fillStyle = gradient;
    this.ctx.globalCompositeOperation = 'source-over';
    this.ctx.fillRect(x - r, y - r, x + r, y + r);
    this.ctx.fillStyle = "#000";
};

CW.drawWheel = function(p) {
    this.ctx.save();
    this.ctx.globalCompositeOperation = 'source-over';
    this.ctx.lineWidth      = this.tw;
    this.ctx.strokeStyle    = this.clr.wheel;
    this.ctx.moveTo(p.a[0], p.a[1]);
    this.ctx.beginPath();
    this.ctx.arc(p.a[0], p.a[1], p.r, 0, P2, p.d);
    this.ctx.stroke();
    if (this.decor > 0 && p.r > 10) {
        this.ctx.beginPath();
        this.ctx.strokeStyle = '#444';
        this.ctx.lineWidth = 1;//0.8;
        this.ctx.arc(p.a[0], p.a[1], p.r / 1.15, 0, P2, p.d === 1);
        this.ctx.stroke();
    }

    // Axis
    this.ctx.beginPath();
    this.ctx.globalCompositeOperation = 'xor';
    this.ctx.lineWidth = 1.5;
    this.ctx.strokeStyle = this.clr.axis;
    this.ctx.arc(p.a[0], p.a[1], this.navcr, 0, P2);
    this.ctx.stroke();
    this.ctx.restore();
    //this.ctx.globalCompositeOperation = 'source-over';
};

CW.drawLinep = function(a) {
    this.ctx.beginPath();
    this.ctx.moveTo(a[0][0], a[0][1]);
    this.ctx.lineTo(a[0][2], a[0][3]);
    this.ctx.moveTo(a[1][0], a[1][1]);
    this.ctx.lineTo(a[1][2], a[1][3]);
    this.ctx.stroke();
};

CW.drawAxle = function(p) {
    this.ctx.save();
    this.ctx.shadowOffsetX  = -this.tw/2;
    this.ctx.shadowOffsetY  = this.tw/2;
    this.ctx.globalCompositeOperation = 'source-over';
    this.ctx.lineWidth = 2;
    this.ctx.strokeStyle = this.clr.axle;

    this.drawLinep(p.a);

    this.noShadow();
    /* Nav left wheel. */
    this.ctx.beginPath();
    this.ctx.lineWidth = 3;
    this.ctx.globalCompositeOperation = 'xor';
    this.ctx.arc(p.a[0][0], p.pp[1], this.navcr, 0, P2);
    this.ctx.stroke();

    /* Nav right wheel. */
    this.ctx.beginPath();
    this.ctx.arc(p.a[0][2], p.pp[1], this.navcr, 0, P2);
    this.ctx.stroke();

    this.ctx.restore();
};

CW.drawChain = function(p) {
    this.ctx.save();
    this.ctx.lineWidth = 2;
    this.ctx.strokeStyle = this.clr.chain;
    this.ctx.globalCompositeOperation = 'destination-over';
    this.ctx.shadowOffsetX  = -this.tw/2;
    this.ctx.shadowOffsetY  = this.tw/2;

    this.drawLinep(p.a);

    this.ctx.restore();
};

CW.circleTangents = function(x1, y1, r1, x2, y2, r2) {
    var d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)),
        vx = (x2 - x1) / d,
        vy = (y2 - y1) / d,
        s1, s2, c, h,
        nx, ny, a, re = [], i = 0;
    for (s1 = 1; s1 >= -1; s1 -= 2) {
        c = (r1 - s1 * r2) / d;
        if (c*c > 1.0)
            continue;
        h = Math.sqrt(Math.max(0.0, 1.0 - c * c));
        for (s2 = 1; s2 >= -1; s2 -= 2) {
            nx = vx * c - s2 * h * vy;
            ny = vy * c + s2 * h * vx;
            a = [];
            a[0] = x1 + r1 * nx;
            a[1] = y1 + r1 * ny;
            a[2] = x2 + s1 * r2 * nx;
            a[3] = y2 + s1 * r2 * ny;
            re[i++] = a;
        }
    }
    return re;
};

/*
 * Paint gear base to static buffer.
 *
 * */
CW.drawStatic = function() {
    var sh;

    if (this.cm.main.ok) {
        sh = this.getShadow();
        this.noShadow();
        this.ctx.drawImage(
            this.cm.main.can,
            this.cm.main.x,
            this.cm.main.y
        );
        this.setShadow(sh);
        return;
    }
};

CW.genStatic = function() {
    var i, e,
        p   = this.parts,
        ix  = this.pix;

    this.ctx.save();
    if (this.shwheel) {
        for (i = 0; i < ix.wheel.length; ++i) {
            e = p[ix.wheel[i]];
            this.drawBulb(e.a[0], e.a[1], e.r);
        }
    }
    for (i = 0; i < ix.wheel.length; ++i) {
        this.drawWheel(p[ix.wheel[i]]);
        //setTimeout(this.drawWheel.bind(this, p[ix.wheel[i]]), (tt+=500));
    }
    for (i = 0; i < ix.axle.length; ++i) {
        this.drawAxle(p[ix.axle[i]]);
        //setTimeout(this.drawAxle.bind(this, p[ix.axle[i]]), (tt+=500));
    }
    for (i = 0; i < ix.chain.length; ++i) {
        this.drawChain(p[ix.chain[i]]);
        //setTimeout(this.drawChain.bind(this, p[ix.chain[i]]), (tt+=500));
    }
    for (i = 0; i < p.length; ++i) {
        this.ctx.globalCompositeOperation = 'source-over';
        this.ctx.strokeSyle = "#000";
        this.ctx.font="10px sans-serif";
        if (this.navcr > 10)
            this.ctx.fillText(i, p[i].pp[0], p[i].pp[1]);
        else if (p[i].w === 'wheel')
            this.ctx.fillText('x', p[i].pp[0], p[i].pp[1]);
    }
    this.cm.main.can.width  = this.grect.w - this.ofs.x + 20;
    this.cm.main.can.height = this.br * 2 + 40;
    // Could have painted directly on memory canvas, but due to coordinates
    // and post-implementation of memory canvas, it is here for now.
    this.cm.main.ctx.drawImage(
        this.can,                       // image
        0,                              // dx
        0,                              // dy
        this.grect.w - this.ofs.x,      // dw
        this.br * 2 + 60,               // dh WHY 60 HERE ????
        -this.ofs.x + 20,               // sx
        -this.ofs.y + 20,               // sy
        this.grect.w - this.ofs.x ,     // sw
        this.br * 2 + 60                // sh WHY 60 HERE ????
    );
    this.cm.main.x = this.ofs.x - 20;
    this.cm.main.y = this.ofs.y - 20;
    this.cm.main.ok = 1;
    this.ctx.restore();
};

/*
 * Drawings for moving parts.
 *
 * * */
CW.spikes = function(x1, y1, spikes, r0, r1, skew_0, skew_1, con) {
    var t = PI / 2 * 3,
        x = x1,
        y = y1,
        step = PI / spikes,
        i, r2 = con ? r1 - 10 : r1;

    this.ctx.beginPath();
    this.ctx.moveTo(x1, y1 - r0);
    for (i = 0; i < spikes; ++i) {
        x = x1 + cos(t)*r0;
        y = y1 + sin(t)*r0;
        this.ctx.lineTo(x, y);
        if (skew_0) {
            t += step / 2;
            x = x1 + cos(t)*r0;
            y = y1 + sin(t)*r0;
            this.ctx.lineTo(x, y);
            t += (step - step/2);
        } else {
            t += step;
        }

        if (skew_1) {
            x = x1 + cos(t - step/18) * r2;
            y = y1 + sin(t - step/18) * r2;
            this.ctx.lineTo(x, y);
            if (con) {
                x = x1 + cos(t - step/8) * r1;
                y = y1 + sin(t - step/8) * r1;
                this.ctx.lineTo(x, y);
                x = x1 + cos(t + step/8) * r1;
                y = y1 + sin(t + step/8) * r1;
                this.ctx.lineTo(x, y);
            }
            x = x1 + cos(t + step/18) * r2;
            y = y1 + sin(t + step/18) * r2;
            this.ctx.lineTo(x, y);
        } else {
            x = x1 + cos(t) * r1;
            y = y1 + sin(t) * r1;
            this.ctx.lineTo(x, y);
        }

        if (skew_0) {
            t += step / 2;
            x = x1 + cos(t)*r0;
            y = y1 + sin(t)*r0;
            this.ctx.lineTo(x, y);
            t += step - step/2;
        } else {
            t += step;
        }
    }
    this.ctx.lineTo(x1, y1 - r0);
    this.ctx.stroke();
    this.ctx.closePath();
};

CW.drawTeeth = function(p) {
    var i, th = p.h, x, y;
    for (i = 0; i < p.t; ++i) {
        x = p.pp[0] + p.r * cos(th);
        y = p.pp[1] + p.r * sin(th);
        this.ctx.moveTo(x, y);
        this.ctx.lineTo(x + cos(th) * this.tl, y + sin(th) * this.tl);
        th += p.thi;
    }
    return th;
};

CW.drawPin = function(p) {
    var x = p.pp[0] + p.r * cos(p.h),
        y = p.pp[1] + p.r * sin(p.h);
    this.ctx.moveTo(
        p.pp[0] + (this.navcr) * cos(p.h),
        p.pp[1] + (this.navcr) * sin(p.h)
    );
    this.ctx.lineTo(x + cos(p.h) * this.tl, y + sin(p.h) * this.tl);
};

CW.drawDecor1 = function(p) {
    var i, x, y,
        th = p.h,
        dd = p.r / 1.15 * 0.63,
        rr = (p.r / this.spk) * 1.125;

    this.ctx.strokeStyle = this.clr.dec1;
    this.ctx.lineWidth = 2;
    this.ctx.globalCompositeOperation = 'source-over';

    for (i = 0; i < this.spk; ++i) {
        x = p.pp[0] + dd * cos(th);
        y = p.pp[1] + dd * sin(th);
        this.ctx.moveTo(x, y);
        this.ctx.beginPath();
        this.ctx.arc(x, y, rr, 0, P2);
        this.ctx.stroke();
        th += PI/this.spk*2;
    }
    //return th;
};

CW.drawDecor2 = function(p) {
    var theta = p.h;
    this.ctx.save();
    this.ctx.translate(p.pp[0], p.pp[1]);
    this.ctx.rotate(theta - (PI / 2 * 3));
    if (this.shade)
        this.setShadow({c:"12,17,23,1",b:17, x:-2, y:2});
    this.ctx.lineWidth = 2;
    if (this.star)
        this.spikes(0, 0, this.spk, p.r / 6 /*this.navcr*/, p.r / 1.19);
    else if (p.r > 50)
        this.spikes(0, 0, this.spk, p.r / 6 /*this.navcr*/, p.r / 1.15, 1, 1, 1);
    else
        this.spikes(0, 0, this.spk, p.r / 6 /*this.navcr*/, p.r / 1.19, 1, 1);
    this.ctx.restore();
};

CW.drawAnim = function(tt) {
    var i, j,
        p = this.parts,
        ix = this.pix,
        sh = this.getShadow();

    this.ctx.save();

    if (this.decor > 1) {
        for (i = 0; i < ix.wheel.length; ++i) {
            if (p[ix.wheel[i]].r < this.navcr * 2)
                continue;
            if ((this.decor === 2 || this.decor > 3))
                this.drawDecor1(p[ix.wheel[i]]);
            if ((this.decor > 2))
                this.drawDecor2(p[ix.wheel[i]]);
        }
    }

    this.ctx.lineWidth = this.tw;

    this.noShadow();
    if (this.pin) {
        this.ctx.beginPath();
        this.ctx.strokeStyle = this.clr.pin;
        this.ctx.globalCompositeOperation = 'darker';
        for (i = 0; i < ix.wheel.length; ++i)
            this.drawPin(p[ix.wheel[i]]);
        this.ctx.stroke();
    }

    this.ctx.globalCompositeOperation = 'destination-over';
    this.ctx.strokeStyle = this.clr.teeth;
    this.ctx.beginPath();
    for (i = 0; i < ix.wheel.length; ++i) {
        j = ix.wheel[i];
        this.drawTeeth(p[j]);
        p[j].h += p[j].s * tt * p[j].d;
    }
    this.ctx.stroke();
    this.setShadow(sh);

    this.ctx.restore();
};

/*
 * Build functions.
 *
 * * */
CW.add = function(a) {
    var e = {
            w: a.type,
            r: a.rad,
            s: a.speed,
            d: this.dir,
            h: a.theta,
        };
    if (a.type === 'wheel') {
        if (this.last === 'wheel')
            this.dir = -this.dir;
        e.t     = a.teeth;
        e.d     = this.dir;
        // Theta increment
        e.thi   = PI / a.teeth * 2;
    } else if (a.type === 'axle' || a.type === 'chain') {
        e.t     = 30;
    } else {
        // Throw error
        return null;
    }
    e.hs = e.h; // Starting angle
    this.last = a.type;
    this.parts.push(e);
    this.grect.w += e.r * 2 + this.tl * 2;
    return this;
};

/*
 * Various calculations that is the same for each frame.
 *
 * */
CW.postBuild = function() {
    var i,
        x1 = this.ofs.x, x2,
        y1 = this.ofs.y + this.br, y2,
        p  = this.parts,
        c  = this.navcr,
        a, d, txl = this.navcr > 10 ? 5 : 15,
        tf = this.tw < 2 ? 2 : 3;

    this.ctx.textBaseline = "middle";
    this.ctx.fillText("tps:", 2, this.grect.h + txl);
    txl += 20;
    this.ctx.fillText("Hz:", 2, this.grect.h + txl);
    txl -= 10;
    this.ctx.textAlign = "center";

    for (i = 0; i < p.length; ++i) {
        if (p[i].w === 'wheel') {
            x1 += p[i].r;
            p[i].a = [x1, y1];
            p[i].tps = (1 / ((P2 / p[i].t) / p[i].s) * p[i].d).toFixed(1);
            if (this.navcr <= 10)
                this.ctx.fillText(i, x1, this.grect.h + 5);
            this.ctx.fillText(p[i].tps, x1, this.grect.h + txl);
            this.ctx.fillText((Math.abs(p[i].tps)/p[i].t).toFixed(tf) ,
                              x1, this.grect.h + txl + 20);
            this.pix.wheel.push(i);
        } else if (p[i].w === 'axle') { // AXLE
            x1 -= p[i-1].r + c;
            x2 = x1 + p[i-1].r + c + p[i].r*2 + c + p[i + 1].r;
            a = [];
            // Left - right nav, top
            a[0] = [x1, y1 - c, x2, y1 - c];
            // Left - right nav, bottom
            a[1] = [x1, y1 + c, x2, y1 + c];
            p[i].a = a;
            // Real center + radius
            d = x2 - x1;
            p[i].cc = [(x1+x2)/2, y1, d / 2];
            p[i].t  = d * 2 / this.tw;
            x1 += p[i - 1].r + c + p[i].r;
            this.pix.axle.push(i);
        } else if (p[i].w === 'chain') {  // CHAIN
            x1 -= p[i-1].r + c;
            x2 = x1 + p[i-1].r + c + p[i].r*2 + c + p[i + 1].r;
            y2 = y1 - p[i+1].r - c ;
            p[i].a = this.circleTangents(x1, y1, p[i-1].r, x2, y1, p[i+1].r);
            x1 += p[i - 1].r + c + p[i].r;
            this.pix.chain.push(i);
        }
        p[i].pp = [x1, y1];
        x1 += p[i].r + c;
    }
    document.getElementById('tps_e').value = p[--i].tps;
};

/*
 *
 * @a   Arrangement
 * @tb  Teeth O wheel
 * @tm  Teeth o wheel
 * @ts  Teeth * wheel
 * @tps Teeth per second leftmost wheel
 * */
CW.build = function(a, tb, tm, ts, tps) {
    var i, w, c,
        rb, rm, rs, // Radius
        ob, om, os, // Odd/even flag
        sp = null,  // Speed
        pr = '',    // Previous
        th,         // theta
        hor = 0,    // If last wheel has right most tooth horizontal.
        xcw;        // Axel / Chain base width.

    if (a.match(/^[=-]|[=-]$|-=|=-/))
        return 1;
    clearInterval(this.iv);
    this.tsp    = null;
    this.parts  = [];
    this.pix    = {wheel:[],axle:[],chain:[]};
    this.imgm   = 0;
    //this.ctx.clearRect(0, 0, this.can.width, this.can.height);
    this.can.width = this.can.width;

    this.spk    = parseInt(document.getElementById('spikes').value);
    this.tw     = parseFloat(document.getElementById('teeth_w').value);

    if (!isNumbers([tb, tm, ts, tps, this.tw, this.spk]))
        return 1;
    if (tb < 1 || tm < 1 || ts < 1 /*|| tps === 0*/ || this.tw <= 0)
        return 1;

    this.tl     = this.tw + 2;
    this.navcr  = this.tl * 1.5;
    xcw         = this.tl * 2;

    this.sz.rb = rb = this.tw * tb / PI;
    this.sz.rm = rm = this.tw * tm / PI;
    this.sz.rs = rs = this.tw * ts / PI;

    // Biggest radius
    this.br = rb > rm ? rb : rm;
    if (rs > this.br)
        this.br = rs;

    ob = tb % 2;
    om = tm % 2;
    os = ts % 2;

    // Offset x:left, y:center first wheel
    this.ofs = {
        x: this.tl * 3,
        y: /*this.br +*/ 50
    };
    // Repaint rectangle
    this.grect = {
        w: this.ofs.x,
        h: this.br * 2 + 100
    };

    this.dir  = tps > 0 ? 1 : -1;
    tps = Math.abs(tps);
    this.last = null;

    for (i = 0; i < a.length; ++i) {
        th = 0;
        switch ((c = a.charAt(i))) {
        case 'O':
            if (sp === null) {
                sp = (P2 / tb) * tps;
            } else if (pr === 'o') {
                sp = sp / rb * rm;
            } else if (pr === '*') {
                sp = sp / rb * rs;
            }
            // ODD + HOR = no skew
            // If odd result is skew
            if ((hor && ob) || (!hor && !ob)) {
                hor = 1;
            } else {
                th = this.tw / rb;
                hor = 0;
            }
            this.add({type:'wheel', rad:rb, teeth:tb, speed:sp, theta:th});
            break;
        case 'o':
            if (sp === null) {
                sp = (P2 / tm) * tps;
            } if (pr === 'O') {
                sp = sp / rm * rb;
            } else if (pr === '*') {
                sp = sp / rm * rs;
            }
            if ((hor && om) || (!hor && !om)) {
                hor = 1;
            } else {
                th = this.tw / rm;
                hor = 0;
            }
            this.add({type:'wheel', rad:rm, teeth:tm, speed:sp, theta:th});
            break;
        case '*':
            if (sp === null) {
                sp = (P2 / ts) * tps;
            } if (pr === 'O') {
                sp = sp / rs * rb;
            } else if (pr === 'o') {
                sp = sp / rs * rm;
            }
            if ((hor && os) || (!hor && !os)) {
                hor = 1;
            } else {
                th = this.tw / rs;
                hor = 0;
            }
            this.add({type:'wheel', rad:rs, teeth:ts, speed:sp, theta:th});
            break;
        case '-':
            for (w = 1; a.charAt(i + 1) === '-'; ++i, ++w)
                ;
            this.add({type:'axle', rad:w * xcw, speed:sp, theta:th});
            hor = 1;
            break;
        case '=':
            for (w = 1; a.charAt(i + 1) === '='; ++i, ++w)
                ;
            this.add({type:'chain', rad: w * xcw, speed:sp, theta:th});
            hor = 1;
            break;
        default:
            this.parts = [];
            return 1;
        }
        if (c !== '=')
            pr = a.charAt(i);
    }
    if (!this.parts.length)
        return 1;
    // Hack to prevent stray borders in page.
    this.can.style.display = 'none';
    this.can.width = this.can.width + 50;

    this.can.width  = this.grect.w;
    this.can.height = this.grect.h + 50;
    this.can.style.display = 'block';

    this.postBuild();
    if (this.shade) {
        //this.setShadow({x:-1,y:1,b:13});
        this.setShadow({c:"0,0,0,.6", x:-4, y:4, b:13});
        this.setShadow({c:"0,0,0,.8", x:0, y:0, b:this.tw*2});
        //this.ctx.shadowBlur = 17;
    } else {
        this.ctx.shadowBlur = 0;
    }
    this.genStatic();
    this.step();
};

/*
 * Runtime functions.
 *
 * * */
CW.tick = function(tt) {
    this.ctx.clearRect(0, 0, this.grect.w, this.grect.h);
    this.noShadow();
    this.ctx.textAlign = "left";
    this.ctx.fillText("F: " + tt, 15, 15);
    this.ctx.textAlign = "center";
    if (this.shade) {
        this.setShadow({c:"0,0,0,.8",x:0,y:0,b:this.tw*2});
    }
    this.drawStatic();
    this.drawAnim(tt);
};

CW.step = function () {
    if (this.parts.length)
        this.tick((1/this.fps).toFixed(3));
};

CW.run_raf = function(ts) {
    if (this.tsp === null) {
        this.tsp = ts;
    }
    this.tsp = ts - this.tsp;
    this.tick(this.tsp/1000);
    requestAnimationFrame(this.run.bind(this));
    this.tsp = ts;
};

CW.run_iv = function() {
    var ts, that = this, ic = this.fps;
    this.tsp = +Date.now();
    this.iv = setInterval(function() {
        ts  = +Date.now() - that.tsp;
        that.tsp = +Date.now();
        that.tick(ts/1000);
        if (ic !== that.fps) {
            clearInterval(that.iv);
            that.run_iv();
        }
    }, 1000 / this.fps);
};

CW.stop = function () {
    clearInterval(this.iv);
    this.mode = 0;
};

CW.run = function () {
    this.stop();
    if (!this.parts.length)
        return this.ui_build_run;
    this.mode = 1;
    this.raf = !document.getElementById('run_iv').checked;
    if (this.raf)
        requestAnimationFrame(this.run_raf.bind(this));
    else
        this.run_iv();
};

/*
 * UI functions
 *
 * * */
CW.ui_build = function() {
    if (this.build(
        document.getElementById('arr').value,
        +document.getElementById('teeth_b').value,
        +document.getElementById('teeth_m').value,
        +document.getElementById('teeth_s').value,
        +document.getElementById('tps_1').value
    ))
        return 1;
};

CW.ui_build_run = function() {
    if (this.ui_build())
        return 1;
    if (this.mode > 0)
        this.run();
};

/*
 * This should have been refactored.
 * * */
CW.ui_init = function() {
    var i, cw = this,
    e   = document.getElementById('fps'),
    fv  = document.getElementById('fpsv'),
    dv  = document.getElementById('decorv');

    this.fps = +e.value;
    fv.innerHTML = this.fps.toFixed(1);
    e.addEventListener('change', function(e) {
        cw.fps = parseFloat(e.target.value);
        fv.innerHTML = cw.fps.toFixed(1);
    });

    e  = document.getElementById('decor');
    this.decor = +e.value;
    dv.innerHTML = this.decor;
    e.addEventListener('change', function(e) {
        cw.decor = parseInt(e.target.value);
        dv.innerHTML = cw.decor;
        cw.ui_build_run();
    });

    e  = document.getElementById('pin');
    this.pin = !!e.checked;
    e.addEventListener('change', function(e) {
        cw.pin = e.target.checked;
        cw.ui_build_run();
    });
    e  = document.getElementById('shadow');
    this.shade = !!e.checked;
    e.addEventListener('change', function(e) {
        cw.shade = e.target.checked;
        cw.ui_build_run();
    });

    e  = document.getElementById('shwheel');
    this.shwheel = !!e.checked;
    e.addEventListener('change', function(e) {
        cw.shwheel = e.target.checked;
        cw.ui_build_run();
    });

    e  = document.getElementById('star');
    this.star = !!e.checked;
    e.addEventListener('change', function(e) {
        cw.star = e.target.checked;
        cw.ui_build_run();
    });

    e = document.getElementById('run_iv');
    cw.raf = !e.checked;

    document.getElementById('build').addEventListener(
        'click', cw.ui_build.bind(cw));
    document.getElementById('stop').addEventListener(
        'click', cw.stop.bind(cw));
    document.getElementById('step').addEventListener(
        'click', cw.step.bind(cw));
    document.getElementById('run').addEventListener(
        'click', cw.run.bind(cw));

    e = document.getElementsByTagName('INPUT');
    for (i = 0; i < e.length; ++i) {
        if (e[i].type === 'text') {
            e[i].addEventListener('keyup', cw.ui_build_run.bind(cw));
        } else if (e[i].type === 'radio') {
            e[i].addEventListener('change', cw.ui_build_run.bind(cw));
        }
    }
};

document.addEventListener("DOMContentLoaded", function () {
    var cw = new CogWheels();
    cw.ui_init();
    cw.ui_build_run();
});

Julia
chain(s) = all((c)->c=='=',s)
axle(s) = all((c)->c=='-',s)
direct(s) = s==""

function mechanical(arrangment,O,o,x,speed_l)
    teeth = {"O"=>O, "o"=>o, "*"=>x}
    process(c) = direct(c[2]) ? -1 : chain(c[2]) ? 1 : axle(c[2]) ? teeth[c[3]]/teeth[c[1]] : 0
    matches = collect(eachmatch(r"([Oo*])([-=]*)([Oo*])",arrangment,true))
    length(matches) == 0 ? 0 : speed_l*prod([process(m.captures) for m in matches])
end

# test cases
println(mechanical("*-Oo-O",50,30,10,3))
println(mechanical("o*-O*= =oO",50,30,10,-3))
println(mechanical("O---*oO=O*-oo",15,12,8,10))
println(mechanical("O *",50,30,10,10))

Gives correct output. r"stuff" is a regex.

Java
import java.util.Scanner;

/**
 *
 * @author Quincunx
 */
public class MechanicalCoding {
    final static int[] teeth = new int[3];

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Input the arrangement:");
        String layout = scan.nextLine();

        System.out.println("Input the:");
        System.out.print("\tNumber of teeth on large gear:\n\t");
        teeth[2] = scan.nextInt();
        scan.nextLine();
        System.out.print("\tNumber of teeth on medium gear:\n\t");
        teeth[1] = scan.nextInt();
        scan.nextLine();
        System.out.print("\tNumber of teeth on small gear:\n\t");
        teeth[0] = scan.nextInt();
        scan.nextLine();

        System.out.println("Input the speed of the left hand side:");
        double speed = scan.nextDouble();

        layout = layout.replaceAll("([-=])+", "$1");

        char lastC = ' ';
        boolean mustBeNext = false;
        for (char c : layout.toCharArray()){
            switch (c){
                case 'O':
                case 'o':
                case '*':
                    if (lastC == '=' || lastC == ' '){
                        break;
                    }
                    if (lastC == '-'){
                        speed *= 1.*teeth(c)/teeth(lastC);
                        break;
                    }
                    speed *= -1;
                    break;
                case '-':
                case '=':
                default:
                    if (lastC == ' '){
                        System.exit(1);
                    }
            }
            lastC = c;
        }
        if (lastC == '-' || lastC == '='){
            System.exit(1);
        }
        System.out.println(speed);
    }
    public static int teeth(char c){
        return teeth[c=='O'?2:c=='o'?1:0];
    }
}

What a relief to be able to use Java! Sample run:
Input the arrangement:
o*-O*==oO
Input the:
    Number of teeth on large gear:
    50
    Number of teeth on medium gear:
    30
    Number of teeth on small gear:
    10
Input the speed of the left hand side:
-3.0
15.0

C#, 396 bytes
Golfed for fun with added indentation.  I'm sure the same code would be smaller in a loosely-typed language.
namespace System.Text.RegularExpressions{
    class P{
        static void Main(string[]a){
            var s=Regex.IsMatch(a[0],"^[-=]|[-=]$|-=|=-|[^-=Oo*]")?0:double.Parse(a[4]);
            foreach(Match m in Regex.Matches(a[0],"[Oo*]{2,}"))
                s*=m.Length%2*2-1;
            foreach(Match m in Regex.Matches(a[0],"[Oo*]-+[Oo*]"))
                s*=double.Parse(a[" Oo*".IndexOf(m.Value[m.Length-1])])/double.Parse(a[" Oo*".IndexOf(m.Value[0])]);
            Console.Write(s);
        }
    }
}

159 Bytes - Javascript
This uses ECMAScript 6 Features so will only work in browsers that support those - Firefox is one.
(g,l,m,s,v,n)=>{for(a={'O':l,'o':m,'*':s};n!=g&&(n=g);g=g.replace(/[Oo*](-*|=*)([Oo*])/,(w,y,z)=>((v*=y?(y[0]=='='?1:a[z]/a[w[0]]):-1)-v)||z));return a[g]?v:0}

Defines an anonymous function that takes the parameters arrangement O o * speed and returns the speed of the last cog for a valid arrangement, and zero otherwise.
Can test all test cases in firefox with:
[((g,l,m,s,v,n)=>{for(a={'O':l,'o':m,'*':s};n!=g&&(n=g);g=g.replace(/[Oo*](-*|=*)([Oo*])/,(w,y,z)=>((v*=y?(y[0]=='='?1:a[z]/a[w[0]]):-1)-v)||z));return a[g]?v:0}).apply(0,a) for each (a in [['*-Oo-O',50,30,10,3],['o*-O*==oO',50,30,10,-3],['O---*oO=O*-oo',15,12,8,10],['=o*',50,30,10,-3],['o*-',50,30,10,-3],['o-=*',50,30,10,-3],['o *',50,30,10,-3]])]


text:
Light up a Roguelike
Given a board, write the shortest program or function to display or return which characters are in sight of the player. A character is in sight if is possible to draw a line between it and the player, without crossing any characters that block vision.
Input:

@ represents the player's position. There will only be one of these in the input.
any character that matches the regex [#A-Z] blocks vision.
any character that matches [ a-z] allows vision.
there will be no invalid characters
you are guaranteed a rectangular input

Lines are defined as follows:

define vector to be a magnitude and a direction
a direction is one of N,NE,E,SE,S,SW,W,NW
a magnitude is how many chars along that direction to count
let the initial vector be called d1; the second vector be called d2
one of d1 or d2 must have a magnitude of 1; the other may have whatever magnitude
d1's direction must be adjacent to d2's direction (e.g: N and NE)

A line is defined to be all chars along the path marked by applying d1, then d2, d1, d2 ....
Sample line (given by the .s):
d1 = (magnitude: 4, direction: E)
d2 = (magnitude: 1, direction NE)
               .....
          .....
     .....
@....

Output:

each visible character in the right position, . substitutes for space.
Space for each non-visible character.

Sample input:
@
    K
 J

    L

         o

Corresponding output:
@.........
....K.....
.J.....
..........
.. .L.....
..  . ....
... .. ...
...  .. ..
...   .  .
....  ..

Sample Input:
 B###M#  by
 #Q   # Zmpq
 # # aaa
@  m #
# ##P#
# ####
# ####
#M ###
######

Corresponding Output:
.B  #M
.# ..   Z pq
.#.#.aaa..
@..m.#
#.##P#
 .#
 .#
 M.
  #

Sample input:
  w

     O  l   gg  rT
   QQL      Ag  #b
   qqqqq         XqQ
 x     V# f@aa
   Y        aaa
   uU  E  l TaKK
  e  dd  FF d opi
   e       d

Corresponding output:
   ..........  .....
    ......... .....
     O..l...gg..rT
...QQL......Ag..#b..
...qqqqq.........XqQ
        #.f@aa......
   Y........aaa.....
...uU..E..l.TaKK....
      d..FF.d.op
     .... .d. ...

OK... bats, all kind of funghi, molds and snakes and even wraiths block the line of view, but giant mimics, hill orcs, mastodons, all kinds of other creatures or even fire vortices don't?

@JanDvorak I was lazy and chose capital letters for blocking. Sort of like TALL monsters vs short monsters; which would you be able to see over. So yes.

Those last two test cases gave me the chills...

I don't know about quantum mechanics, but the bat and the gnome mummy might be an easy deal. The mimic might complicate things further, though. Also, those three ants might be fun, and the large group of assorted monsters on the north-east might already know about you. Yeah... it might be nasty. As for #3 - where's my teleporation scroll? Oops, that was destroy armor.

I'm starting to work on an implementation (my first ever golf!), but I don't quite match your solution. Can you tell me, in the first test, what d1 and d2 are to reach the last . in the J row?

Now that I've implemented a first version I can see more light than in your output. E.g. in the first case if I choose direction 1 E 8 SE there are two more dots in the lower right corner.

@Chowlett You may choose 1 SE 2 E and after two full steps you are there.

@Howard - aha, yes; I'd managed to miss that either d1 or d2 had to be magnitude 1. I was always stepping with the non-mag-1 component first.

...and I now match @Howard in having extra visible dots.

@Howard Oops, missed those two dots; I filled it out by hand.

@Quincunx Posted my current version (although it might be possible to golf further). The results are different from your examples (first and third one) - found some light paths which you seem to miss.

@Howard After verifying your results by hand, I believe they are correct. Thanks.

Just a curious observation, but if I understand your definition of "line" right, it looks like there are some squares that won't be visible even without any obstacles. For example, if the player is at (0, 0), then the square at (5, 12) can't be reached by any line. It might've made more sense to, say, specify some canonical implementation of Bresenham's line algorithm for drawing a line between any two points, and define a square as obscured if the line between it and the player intersects an obstacle.

@IlmariKaronen - you're right. I'll edit in the vision pattern out to (40,40) into my answer.

@IlmariKaronen You are absolutely correct. That is just how I like it. :-).

GolfScript, 171 characters
.n?):L)[n*.]*1/:I'@'?{\+[{1$+}*]..{I=26,{65+}%"#
"+\?)}??)<}+{[L~.).)1L)L.(-1L~]>2<`{[.[~\]]{1/~2$*+L*.-1%}%\;~}+L,%~}8,%%{|}*`{1$?)I@=.n=@|\.' '={;'.'}*' 'if}+I,,%''*n%n*

The input must be provided on STDIN.
The output for the examples given above is slightly different. I verified the responses by hand and think they are correct.
Example 1:
@.........
....K.....
.J.....
..........
.. .L.....
..  . ....
... .. ...
...  .. ..
...   .  .
....  ..

Example 2:
.B  #M
.# ..   Z pq
.#.#.aaa..
@..m.#
#.##P#
 .#
 .#
 M.
  #

Example 3:
   ..........  .....
    ......... .....
     O..l...gg..rT
...QQL......Ag..#b..
...qqqqq.........XqQ
        #.f@aa......
   Y........aaa.....
...uU..E..l.TaKK....
      d..FF.d.op
     .... .d. ...

This doesn't seem to work for single line inputs (which are valid rectangles...)

@Quincunx The code assumes that you finalise your input with a newline. Alternatively prepend n+ to the code.

Ruby - 510 chars
Quite a mammoth; but it is my first ever attempt at a golf.
m=$<.read;w,s,o,p=m.index(?\n)+1,m.size,m.dup.gsub(/[^@\n]/,' '),m.index(?@);d=[-w,1-w,1,w+1,w,w-1,-1,-1-w];0.upto(7){|i|x=d[i];[i-1,i+1].each{|j|y=d[j%8];[1,nil].each{|l|t=0;catch(:a){loop{c,f,r=p,1,nil;catch(:b){loop{(l||r)&&(1.upto(t){|u|c+=x;n=!(0...s).include?(c)||m[c]==?\n;n&&throw(f ?:a: :b);o[c]=m[c]==" "??.: m[c];a=m[c]=~/[#A-Z]/;a&&throw(f ?:a: :b)};f=nil);r=1;c+=y;n=!(0...s).include?(c)||m[c]==?\n;n&&throw(f ?:a: :b);o[c]=m[c]==" "??.: m[c];a=m[c]=~/[#A-Z]/;a&&throw(f ?:a: :b)}};t+=1}}}}};$><<o

Input is by file specified as argument; I assume the input file to consist of a rectangular block of characters (so, trailing spaces included), and to have a trailing newline.
This version makes extensive use of catch-throw to exit deep loops; I can possibly improve matters with bounds-checked loops instead.
Unobfuscated code:
# Read the map in
map = $<.read

# Determine its width and size
width = map.index("\n")+1
size = map.size

# Create a blank copy of the map to fill in with visible stuff
output = map.dup.gsub /[^@\n]/,' '

# Locate the player
player = map.index('@')

dirs = [
  -width,   # N
  1-width,  # NE
  1,        # E
  width+1,  # SE
  width,    # S
  width-1,  # SW
  -1,       # W
  -1-width  # NW
]

0.upto(7) do |i1|
  d1 = dirs[i1]
  [i1-1, i1+1].each do |i2|
    d2 = dirs[i2%8]

    # Stepping by 0,1,2... in d1, work along the line.
    # Write the cell value into the duplicate map, then break if it's
    # a "solid" character.
    #
    # Extensive use of catch-throw lets us exit deep loops.

    # For convenience of notation, instead of having either d1 or d2
    # be magnitude 1, and always doing d1,d2,d1... - I have d2 always
    # being magnitude 1, and doing either d1,d2,d1 or d2,d1,d2...

    # Loop twice - first with d1,d2,d1... second with d2,d1,d2...
    [true,false].each do |long_first|
      step = 0

      catch(:all_done) do
        # This loop increments step each iteration, being the magnitude of d1
        loop do
          cell = player
          first = true  # True until we've done the first d1
          later = false # True once we've done the first d2

          catch(:done) do
            # This loop repeatedly applies d1 and d2
            loop do
              if long_first || later  # Don't apply d1 first if starting with d2
                1.upto(step) do |dd1|
                  cell += d1 # Move one cell in d1
                  invalid = !(0...size).include?(cell) || map[cell]=="\n" # Out of range
                  throw :all_done if first && invalid # No point trying a longer step if the
                                                      # first application of d1 is out of range
                  throw :done if invalid # No point continuing with this step length

                  output[cell]=map[cell] == " " ? '.' : map[cell] # Transfer visble character
                  wall = map[cell]=~/[#A-Z]/  # Hit a wall?
                  throw :all_done if first && wall # Drop out as before
                  throw :done if wall
                end
                first = false
              end
              later=true

              # Now repeat above for the single d2 step
              cell += d2
              invalid = !(0...size).include?(cell) || map[cell]=="\n"
              throw :all_done if first && invalid
              throw :done if invalid
              output[cell]=map[cell] == " " ? '.' : map[cell]
              wall = map[cell]=~/[#A-Z]/
              throw :all_done if first && wall
              throw :done if wall
            end
          end
          step += 1
        end
      end
    end
  end
end

puts output

Edit
Ilmari Karonen notes in the question comments that the given vision algorithm doesn't see all squares, even when there's no obstacle. Here's a demonstration of that, out to (40,40) away from the player.
@.......................................
........................................
........................................
........................................
........................................
............ ...........................
..............  ........................
............ ...   ..... ...............
.............. ...    .....  ...........
...............  ...     .....   .......
.................  ...      .....    ...
..................   ...       .....
..... . ............   ...        .....
.....................    ...         ...
...... . ..............    ...
...... .. ..............     ...
....... . ................     ...
....... .. ............. ..      ...
.......  .  .................      ...
........ .. ............... ..       ...
........  .  ............... ...       .
........  ..  ................ ..
.........  .  ................. ...
.........  ..  .................  ..
....... .   .   . ................ ...
..........  ..  ...................  ..
..........   .   ...................  ..
........ .   ..   . ..................
........ ..   .   .. ..................
...........   ..   .....................
......... .    .    . ..................
......... ..   ..   .. .................
......... ..    .    .. ................
.......... .    ..    . ................
.......... ..    .    .. ...............
.......... ..    ..    .. ..............
..........  .     .     .  .............
........... ..    ..    .. .............
........... ..     .     .. ............
...........  .     ..     .  ...........

Hmm. This fails test 3. Needs debugging.

are you sure? I could have made a mistake...

Pretty sure - I can see the V behind the wall! I think I'm not detecting the newline after the previous line.

Definitely should not be seeing that...

Ah, it was a problem with my input; I had an extra space after XqQ. That said, your given answer for 3 doesn't match the testcase at all - it at least has an extra line at the top, and only one space between the O and l.

Strange; I specifically inserted an extra line between the first and second lines. I wonder where it went...