text:
Write a polyglot that prints the language's name
Your task is to write a program that executes in as many languages as possible, with as few characters as you can. To avoid trivial solutions, the program must print the name of the language it was run in.
Scoring
Your program has to work in at least 5 languages. A program's score is given as:
$$\frac {\text{(number of languages)}^{1.5}} {\text{(length of program)}}$$
The highest score wins.

Would using a solution like using print() for Perl, Python, PHP, Processing and R be considered trivial or is it acceptable?

A can't see a problem with it. The difficulty would be switching print's input per language.

I should have given a higher weight to the number of languages... it seems choosing to have exactly 5 is the most optimal. I wonder how many languages would have been in the winner entry if the score were n * n / length

I was going to suggest that too.  Based on the answers provided, I don't believe I interpreted your question properly.

Bash, C, C++, Obj-C, Obj-C++, Perl, PHP, Ruby, 183 chars
score ~ 0.1236
For the C and C-like codes I owe a debt to @baby-rabbit. The others are inspired by the recognition that many languages have an eval statement that will grudgingly accept invalid syntax.
Outputs the language name to standard output. Sometimes generates a lot of error messages on standard error, so suppress them with 2>/dev/null as you run them.
#if 0
'PHP<?/*';eval "print\$=?'Perl':'Ruby';echo Bash";exit
__END__
#endif
#include <stdio.h>
main(){puts(
#ifdef __OBJC__
"obj-"
#endif
"C"
#ifdef __cplusplus
"++"
#endif
);}//*/?>'

The php solution outputs 'PHP' (including the single quotes), which may be bending the rules a little bit.
Last edit: shaved 12 chars from insight that $= is false in Ruby, 60 in Perl, and print$=?... is almost surely an error in Bash. Shaved 7 more from insight the Perl/Ruby/Bash test can now go into a single eval statement.
If the rules can tolerate more bending, I present this 8 language, 43 character solution (score 0.5262)
print("phperluarscriptrubypythoncatebg13");

for which the output includes the name of the interpreter for php, perl, lua, rscript, ruby, python, cat, and rot13.

TI-Basic supports the last one; just add 6 characters and get print("phperluarscriptrubypythontibasicatebg13");

@Timtech no, TI-Basic uses the Disp or Output( or text( tokens, there is no print( command. And including a string as part of an otherwise real-valued expression results in an ERR:INVALID SYNTAX, not the display of the string (not even as a return value). (Also, there is no ;; TI-Basic uses :)

@AJMansfield Too true, how could I forget :?

Can you replace echo Bash with ps -ocomm= -p$$?  This will output the name of the shell for at least bash, zsh, ksh, csh and tcsh, maybe others.

C, C++, BF, BASH and Ruby; 280 chars
Score is about 0.040
#include "stdio.h"
#define s "C"
#ifdef __cplusplus
#define s "C++"
#endif
#ifndef s
#"+++++++++[>++++++++++>+++++++++<<-]>>-.<++++.>-.++++++++.<----.>---.<+++++++.>---.++++++++.<<++++++++++.[-]"
if [ 1 == 2 ];then
puts "Ruby"
exit
fi
echo "BASH"
exit
end
#endif
main(){puts(s);}

Note that I am using a Linux system.
The code is run or compiled with the following commands (the file's name is test.c)
C:
gcc test.c

When run with ./a.out, output is C
C++:
c++ test.c

When run with ./a.out, output is C++
BASH:
./test.c

Outputs: BASH
Ruby:
ruby test.c

Outputs: Ruby
BrainF***:
Verified using the following:

A JS debugger

A free interpreter

My interpreter

Outputs: brainfuck
Note that if the JS debugger is used, then the first two minus signs need to be removed. They were included to offset the plus signs in the string literal "C++". This was a very fun project, I'm working on adding more languages.
Just to add further clarity, here are my interpreter's/compiler's specs:

gcc version 4.6.3

ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]

GNU bash, version 4.2.24(1)-release (x86_64-pc-linux-gnu)

SIDE NOTE
Using @baby-rabbit's trick I was able to extend my code to be executable in 7 languages (objective-C and objective-c++ being added). This is not my solution since I did copy some, but I thought I would show it off.
Update 9.12
Added SmallTalk run with gnu-smalltalk!
SmallTalk, C, C++, Objective-C, Objective-C++, BASH, BF, Ruby; 384 chars (Score: 0.059)
#if (a)
##(true) ifTrue: ['SmallTalk' printNl]
##(ObjectMemory quit)
#"+++++++++++[>++++++++++>+++++++++<<-]>>-.<++++.>-.++++++++.<----.>---.<+++++++.>---.++++++++.<<++++++++++.[-]"
if [ 1 == 2 ];then
puts 'Ruby'
exit
fi
echo 'BASH'
exit
end
=begin
#endif
#include "stdio.h"
main(){puts(
#ifdef __OBJC__
"Objective-"
#endif
"C"
#ifdef __cplusplus
"++"
#endif
);}
#ifdef b
=end
#endif

In the above code you will need to rename the file to produce the langauge's name for objective-c, obj-c++, c and c++.

would it be shorter if you output brainf***?

Yes it would, I believe.

You should use if [ 1 = 2 ] instead of if [ 1 == 2 ], because scripts without a hashbang are executed by sh, not bash. sh may or may not be bash, on Debian it's dash.

bash, c, c++, obj-c, obj-c++; 134 chars; score=0.083
#if x
echo "bash"
exit
#endif
#include <stdio.h>
int main(){puts(
#ifdef __OBJC__
"obj-"
#endif
"c"
#ifdef __cplusplus
"++"
#endif
);}

rename file and run/compile as:

sh file.sh
cc file.c
cc file.cpp
cc file.m
cc file.mm

(where cc is clang-421.10.42)

+1 since many other upvoted answers were inspired by yours.

Lua, Ruby, VimL, Sed, Befunge (129 chars; ~0.087 points)
Not sure if this one counts--the sed-part is embedded in the shebang line which is arguably a hack to get around the restriction.  This also means that it should be run as an executable and not directly with sed.
I was lucky that all the other languages (sans Befunge) automagically ignores the shebang line (though apparently Ruby refuses to run the file if it has a shebang line that doesn't contain the string 'ruby' in it).
#!sed sanava;s/.*/sed/;q;ruby
--"".to_i#>"egnufeB">:#,_@
if 0
then
if IO
then
puts"Ruby"
else
print"Lua"
end
else
echo"VimL"
end

Sample usage:
% lua tmp/glot.poly
Lua
% ruby tmp/glot.poly
Ruby
% ./tmp/glot.poly
sed
% cfunge tmp/glot.poly       # Requires Befunge-98
Befunge

:source tmp/glot.poly        # from vim
VimL                         # displayed as message

Wow, a solution that does not include C

AsciiDots, Befunge-93, C, C++, ><>, Funge-98, GolfScript, lua, MinkoLang, Python 2, Python 3, Ruby, vi (0.170444 points)
#/* ["39-egnufeB">:|;ooo"><>"
n,n=1,1--[[],0][1]#>52*,@
"""""GolfScript"
puts"Ruby\n"
__END__
:puts{"""
print("Python %d"%(3/2*2));
"""stoDiicsA"$\<ESC>dggivi<ESC>ZZ*/
#include<stdio.h>
main(){puts(sizeof'a'-1?"C":"C++");}
//>"Minkolang"9[O]."
//^}>"89-egnuF"#[v,<]"]]print"lua"--"""

<ESC> stands for the literal escape character 27
I know this is an old post, but it was interesting so I had to give it a shot :P

BF, Bash, Batch, C, vi (163 characters; score ≈ .0686)
(<ESC> stands for ASCII code 27.)
rem (){ ((0));};true /*
rem ;goto(){ rem;}
rem ivi<ESC>ZZ'++++++++[>NUL ++++++++<NUL -]>NUL ++.++++.*/;main(){puts("C");}/*'
goto a
echo Bash
exit
:a
echo Batch
rem */

I tested this, as a batch file, with the MS-DOS 6.22 version of COMMAND.COM. By default, that interpreter mixes lines of source code with the output. To prevent that from happening, execute echo off before running the batch file.
To execute the vi code, which I have only tested using Vim, use the following command:
cat /dev/null > tmpfile && vi -s polyglot.sh tmpfile > /dev/null 2>&1 && cat tmpfile

You could use touch tmpfile or : > tmpfile instead of cat /dev/null > tmpfile.

Every Python Release, 18.37291 points
import sys
print('Python '+'.'.join(map(str,sys.version_info[:-2])))

Technically valid, if you consider all the python versions to be different languages. There are currently 116 python versions, which I believe gives me a score of around 18.37291.
(Also I understand if this isn't considered a valid answer, this was just for fun)

you still get my +1 just for fun.

Is printing the complete version number viable? (This golfs down 4 bytes and extends the possible Python versions.)

Also is this okay? https://tio.run/##K6gsycjPM/7/PzO3IL@oRKG4spiroCgzr0RDPQAspa5dXFKkARTWK0stKs7Mz4vPzEvLj7bSNYrV1Pz/HwA

bash, zsh, ksh, csh, tcsh, 15 chars, score 0.745
This one's a bit of a stretch since they're all related languages, but there are differences:
ps -ocomm= -p$$

What about dash?

@Elliota List of languages that worked on tio.run: Bash, Dash, ksh, OSH, tcsh, Zsh. bosh displayed sh and yash displayed ps.

16 languages, 348 bytes, score: 0.183908046
#include <stdio.h>
#if 0
#replace "C(gcc)" "C(ecpp)"
#replace "C++(gcc)" "C++(ecpp)"
#endif
#ifdef __clang__
#define d 2
#elif __TINYC__
#define d 4
#else
#define d 0
#endif // rk:start print: "rk" \
ps -ocomm= -p$$; exit;
int x=sizeof('a')%2+d;char*arr[]={"C(gcc)","C++(gcc)","C(clang)","C++(clang)","C(tcc)"};int main(){puts(arr[x]);}

This works in C(gcc), C++(gcc), C(ecpp), C++(ecpp), C(clang), C++(clang), C(tcc), sh, dash, bash, zsh, ksh, csh, tcsh, rk, and SIL.

Bash, C, Gawk, Perl, vi (145 characters; score ≈ .077)
(<BS> stands for ASCII code 8. <ESC> stands for ASCII code 27.)
#define echo//<BS><BS><BS>vi<ESC>ZZ
#define BEGIN A()
#define B\
{
echo Bash ;exit;
#define C\
}
BEGIN {printf(A=="A"?"Perl":"Gawk");exit;}
main(){puts("C");}

To execute the vi code, which I have only tested using Vim, use this command:
cat /dev/null > tmpfile && vi -s polyglot.sh tmpfile > /dev/null 2>&1 && cat tmpfile

Java, Lisp, Whitespace, Intercal, PHP, Befunge-98; score =.0189
This was originally an answer to this.
 ;\\0"egnufeB">:#,_@SSSTTTSTTTL
;TL
;SSSSSTTSTSSSL
;TL
;SSSSSTTSTSSTL
;TL
;SSSSSTSTSTSSL
;TL
;SSSSSTTSSTSTL
;TL
;SSSSSTSTSSTTL
;TL
;SSSSSTTTSSSSL
;TL
;SSSSSTTSSSSTL
;TL
;SSSSSTTSSSTTL
;TL
;SSSSSTTSSTSTL
;SSL
;L
;L
;L
;public class H{ public static void main(String []a){System.out.println("JAVA");}}
;/*
(print "LISP")
;*/
;//<?php
; echo "PHP"
;//?>
;/*
#|
DO ,1 <- #8
DO ,1 SUB #1 <- #110
DO ,1 SUB #2 <- #32
DO ,1 SUB #3 <- #72
DO ,1 SUB #4 <- #136
DO ,1 SUB #5 <- #88
DO ,1 SUB #6 <- #136
PLEASE DO ,1 SUB #7 <- #64
DO ,1 SUB #8 <- #80
PLEASE READ OUT ,1
PLEASE NOTE |#
;*/
;// PLEASE GIVE UP

This won't work in Java; every line until public class... will cause a compiler problem.

Interesting... I distinctly remember testing this in a compiler and it working... or perhaps my memory fails me...

@Ypnypn Remember that "T" is a tab,"S" is a space, and "L" is a line feed in white-space, which is why it does not cause a compiler error.

Oh; that makes sense.

Befunge, 05AB1E (legacy), Vyxal, Red, Python 1, Vim, Zsh - 71.5 / 114 characters ≈ 0.164 score
'a;# "egnufeB"\\,,,,,,,@"05AB1E",q', 2>2
'a;`Vyxal`,Q', 2>2#;echo Zsh
print 'Red quit;' * 0+'Python', 1>0#<0x1B>}dHiVim

Try it in Befunge! 05AB1E! Vyxal! Red! Python! Vim! Zsh!

This is a cheap selection of languages, but here goes:
CoffeeScript, JScript, Mozilla Javascript (≈ JavaScript 1.3), ECMAScript Edition 5, ECMAScript Edition 3, 223 chars, score ≈ 0.0501)
a="undefined"
x="ECMAScript 3"
if(Array.prototype.map)
 x="ECMAScript 5"
if(typeof CoffeeScript!=a)
 x="CoffeeScript"
if(typeof uneval!=a)
 x="Mozilla JavaScript"
if(typeof WScript!=a)
 WScript.echo("JScript")
else alert(x)

JavaScript, JavaScript, JavaScript (≈ JavaScript), JavaScript, JavaScript, 263 chars, (score ≈ 0). you can also make it shorter a="undefined";if(typeof arguments!=a)...else if(typeof WScript!=a... oh and you can also try golfing it....

@tryingToGetProgrammingStraight Putting everything on one line like that is not valid syntax in CoffeeScript (which is a separate language from Javascript). The others are arguable, but since it wasn't specified how different the languages have to be, I think the fact that the different implementations have different specified behaviors allows them to be treated as separate.

i also cant write a multi-line comment, the only golfing you seem to have used is leaving out {/}/;... the idea is to use a to avoid reusing "undefined", you could also do b=alert and then b("this is also still just javascript"). anyway The golden rule of CoffeeScript is: "It's just JavaScript" (from http://coffeescript.org/), you can also use some jquery to add a sixth language....

@tryingToGetProgrammingStraight Adding jQuery would be absurd, since jQuery is a library, not a language. CoffeeScript is definitely not the same language as ECMAScript. The definition of a language is a set of finite strings over a finite alphabet. The set of strings representing valid CoffeeScript programs is not the same as the set of strings representing valid ECMAScript.

Can you do [].map instead of Array.prototype.map?

Can you replace undefined with void 0?

Windows Batch, TI-Basic, Golf-Basic 84, Quomplex, and GTB 5*2/93 = 0.11
::¤Quomplex¤:"'*[]'":~"GTB":g;1:d`"GOLF-BASIC 84":g`1:"TI-BASIC":Lbl 1:End
echo Windows Batch

How it works
Windows Batch was the easiest, because :: starts a comment. Fairly simple to implement.
TI-Basic doesn't support lowercase letters or backticks, causing it to skip the statements d`"GOLF-BASIC 84":g`1, which Golf-Basic evaulates, Displaying the message and forwarding to Label 1, where it is promptly ended. This is similar for GTB, with its handy display character, ~. By the way, a string with no display will be put in Ans. If there are no Display commands following it, Ans will be outputted (not the case here).
Quomplex was snuck in at the beginning because its complex syntax won't allow for much to be skipped. All it does is add "Quomplex" to the output, and then for the mastery of the program...
The Mastery of the Programming Syntax
:"'*[]'"

Pure genius. Quomplex ignores : and takes "' and '" as strings, leaving it to output the stack and perish in an infinite while loop ([]). Meanwhile, Golf-Basic and TI-Basic take the whole "'*[]'" as a string, because ' is a mathematical operator, not a string operator.

Strictly speaking, : indicates a label in a batch file, not a comment.  It's true that it doesn't execute anything on its own, though.

@Mark True, but is is :: (still a label though). I'd rather use it than REM, especially since it is required in TI-Basic.

Right - I was just being pedantic.  Also, +1 for using batch files in the first place. :-)

JScript, EcmaScript Edition 3, 5, 6, 2016, Node, Mozilla JavaScript (score ≈ 0.1342)
This answer is originally based off Peter Olson's answer, but minus the CoffeeScript (as whitespace-significant languages can be horrible for golfing).
I also added Node, ES6 and ES2016 and golfed the code a little, almost tripling the original score.
$=this,y="EcmaScript ",x=$.module?"Node":$.uneval?"Mozilla JavaScript":"".padStart?y+2016:$.Map?y+6:[].map?y+5:y+3,($.WScript||$.alert)(x)

PE/bash/x86/C/Ruby/Python2, 330 bytes
score ≈ 0.0445
xxd:
00000000: 4d5a 7544 3d27 5c27 273b 0a23 2f2a 0a27  MZuD='\'';.#/*.'
00000010: 3b65 6368 6f20 6261 7368 2023 273b 7072  ;echo bash #';pr
00000020: 696e 7420 2830 616e 6427 5275 6279 2729  int (0and'Ruby')
00000030: 6f72 2750 7974 686f 6e32 2723 4000 0000  or'Python2'#@...
00000040: 5045 0000 4c01 0100 b802 00cd 10b8 0013  PE..L...........
00000050: eb2e 0000 7000 0301 0b01 0000 7075 7473  ....p.......puts
00000060: 0000 0065 7869 7400 f000 0000 6d73 7663  ...exit.....msvc
00000070: 7274 0000 0000 4000 0400 0000 0400 0000  rt....@.........
00000080: bb0f 00bd 8c7c eb58 0400 0000 7838 3600  .....|.X....x86.
00000090: 0004 0000 0100 0000 0000 0000 0300 0000  ................
000000a0: 0000 0000 0000 0000 0000 0000 0000 0000  ................
000000b0: 0000 0000 0200 0000 0000 0000 0000 0000  ................
000000c0: 0d01 0000 0000 0000 2e74 6578 7400 0000  .........text...
000000d0: 4500 0000 f000 0000 4500 0000 f000 0000  E.......E.......
000000e0: b903 00ba 0000 cd10 ebfe 0000 0000 0000  ................
000000f0: 6840 0040 00ff 1501 0140 00ff 1505 0140  h@.@.....@.....@
00000100: 005a 0000 0061 0000 0000 0000 0000 0000  .Z...a..........
00000110: 0000 0000 0000 0000 006c 0000 0001 0100  .........l......
00000120: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000130: 0000 0000 002a 2f0d 6d61 696e 2829 7b70  .....*/.main(){p
00000140: 7574 7328 2243 2229 3b7d                 uts("C");}

source:
; nasm

base equ 0x400000

;
; DOS header
;
; The only two fields that matter are e_magic and e_lfanew

mzhdr:
    dw "MZ"              ; DOS e_magic
    jnz a
    db "='\'';",10,"#/*",10,"';echo bash #';print (0and'Ruby')or'Python2'#"
    times 64 - 4 - ($-$$) db 0
    dd 64                ; DOS e_lfanew

;
; NT headers
;

PE: dd "PE"              ; PE signature

;
; NT file header
;

filehdr:
    dw 0x014C            ; Machine (Intel 386)
    dw 1                 ; NumberOfSections
;    dd 0                 ; TimeDateStamp UNUSED
;    dd 0                 ; PointerToSymbolTable UNUSED
;    dd 0                 ; NumberOfSymbols UNUSED
a:
    mov ax,2        ; 3 bytes
    int 0x10        ; 2 bytes  ; clear screen
    mov ax,0x1300   ; 3 bytes
    jmp b           ; 2 bytes
    dw 0            ; 2 bytes

    dw opthdrsize        ; SizeOfOptionalHeader
    dw 0x103             ; Characteristics

;
; NT optional header
;

opthdr:
    dw 0x10B                    ; Magic (PE32)
;    db 0                        ; MajorLinkerVersion UNUSED
;    db 0                        ; MinorLinkerVersion UNUSED
;    dd 0                        ; SizeOfCode UNUSED
;    dd 0                        ; SizeOfInitializedData UNUSED
;    dd 0                        ; SizeOfUninitializedData UNUSED
puts_: db 0,0,"puts",0
exit_: db 0,0,"exit",0
    dd start                    ; AddressOfEntryPoint
;    dd 0                        ; BaseOfCode UNUSED
;    dd 0                        ; BaseOfData UNUSED
crt: db "msvcrt",0,0
    dd base                     ; ImageBase
    dd 4                        ; SectionAlignment
    dd 4                        ; FileAlignment
;    dw 0                        ; MajorOperatingSystemVersion UNUSED
;    dw 0                        ; MinorOperatingSystemVersion UNUSED
;    dw 0                        ; MajorImageVersion UNUSED
;    dw 0                        ; MinorImageVersion UNUSED
b:
    mov bx,0xF           ; 3 bytes  ; video page, video attribute
    mov bp,0x7C00+x86    ; 3 bytes
    jmp c                ; 2 bytes

    dw 4                        ; MajorSubsystemVersion
    dw 0                        ; MinorSubsystemVersion UNUSED
;    dd 0                        ; Win32VersionValue UNUSED
x86: db "x86",0
    dd 1024                     ; SizeOfImage
    dd 1                        ; SizeOfHeaders          nonzero for Windows XP
    dd 0                        ; CheckSum UNUSED
    dw 3                        ; Subsystem (Console)
    dw 0                        ; DllCharacteristics UNUSED
    dd 0                        ; SizeOfStackReserve
    dd 0                        ; SizeOfStackCommit
    dd 0                        ; SizeOfHeapReserve
    dd 0                        ; SizeOfHeapCommit UNUSED
    dd 0                        ; LoaderFlags UNUSED
    dd 2                        ; NumberOfRvaAndSizes    for Windows 10; UNUSED in Windows XP

;
; Data directories (part of optional header)
;
    dd 0, 0                     ; Export Table UNUSED
    dd idata, 0                 ; Import Table

opthdrsize equ $ - opthdr

;
; Code section header
;

    db ".text", 0, 0, 0         ; Name
    dd codesize                 ; VirtualSize
    dd code                     ; VirtualAddress
    dd codesize                 ; SizeOfRawData
    dd code                     ; PointerToRawData
;    dd 0                        ; PointerToRelocations UNUSED
;    dd 0                        ; PointerToLinenumbers UNUSED
;    dw 0                        ; NumberOfRelocations UNUSED
c:
    mov cx,3      ; 3 bytes  ; text length
    mov dx,0      ; 3 bytes  ; text position
    int 0x10      ; 2 bytes  ; print text
    jmp $         ; 2 bytes  ; enter infinite loop

    dw 0                        ; NumberOfLinenumbers UNUSED
    dd 0                        ; Characteristics UNUSED

;
; Code section data
;

align 4, db 0

code:

;
; Entry point
;

bits 32
start:
    push base + PE
    call [base + puts]
    call [base + exit]

;
; Import address table (array of IMAGE_THUNK_DATA structures)
;

iat:
puts:   dd puts_                ; Import puts by name
exit:   dd exit_                ; Import exit by name
        dd 0                    ; terminator

;
; Import table (array of IMAGE_IMPORT_DESCRIPTOR structures)
;

idata:
    dd 0                        ; OriginalFirstThunk UNUSED
    dd 0                        ; TimeDateStamp UNUSED
    dd 0                        ; ForwarderChain UNUSED
    dd crt                      ; Name
    dd iat                      ; FirstThunk
    times 5 dd 0                ; terminator

codesize equ $ - code

db "*/",13,"main(){puts(",34,"C",34,");}"

Try it online
in bash/C/Ruby/Python2.
Portable Executable polyglot.exe was tested on Windows 10 2004 64-bit and Windows XP SP3 32-bit.
Raw x86 was tested in QEMU 6.2.0: qemu-system-x86_64 -no-fd-bootchk -fda polyglot.
Inspired by/based on αcτµαlly pδrταblε εxεcµταblε, which is a PE/bash/x86 polyglot.
Also based on this hello world PE.
Portable Executable
Main differences from hello world:

DOS and NT headers don't overlap here, NT header immediately follows DOS header
puts and exit are imported by name

As mentioned in hello world PE answer, the minimal distance between the start of NT headers and end of file on Windows 10 is 264 bytes,
so minimal PE file size with non-overlapping DOS and NT headers on Windows 10 is 64+264=328 bytes (64 == sizeof(IMAGE_DOS_HEADER)).
It means that all but 2 bytes of C code at the end of the file are required for this file to work on Windows 10.
The program prints its own PE signature, which is kinda cute.
x86
αpε uses jno 0x4a jo 0x4a to jump to the main boot code. I ran out of space in the DOS header
and didn't want to rearrange the code, so I use the less robust single jnz a instruction. This means I rely on BIOS to not set
bp to 1 before calling boot sector (M in MZ is dec bp). QEMU and Bochs set bp to 0. Unconditional jmp is not used
because its code is 0xEB, on the other hand almost all short conditional jumps have ASCII
codes, see here.
Main code:
    mov ax,2
    int 0x10            ; clear screen

    mov ax,0x1300
    mov bx,0xF          ; video page, video attribute
    mov bp,0x7C00+x86
    mov cx,3            ; text length
    mov dx,0            ; text position
    int 0x10            ; print text

    jmp $               ; enter infinite loop

    x86: db "x86"

This code is split into 3 parts (a:,b:,c:) to fit inside unused fields of NT headers.
It looks like both b and c would fit inside section header, but it breaks PE on Windows XP for some reason.
bash/C/Ruby/Python2
MZuD='\'';
#/*
';echo bash #';print (0and'Ruby')or'Python2'# ... */␍main(){puts("C");}

Pretty standard stuff:

bash: \ inside '' does not escape
C: allows single # on a line
Ruby: 0 is truthy

Also, I used the fact that C treats \r as newline, unlike bash/Ruby/Python2 (link).
This allows to use just # in bash/Ruby/Python2 to comment out the rest of the polyglot.

JScript, EcmaScript Edition 3, 5, 6, 2016, 2017, Node, Mozilla JavaScript (score = .174193548387), CoffeeScript (as whitespace-significant languages can be horrible for golfing).
$=this,y="EcmaScript ",($.WScript||alert)(x=Object.values?y+2017:$.module?"Node":$.uneval?"Mozilla JavaScript":[].includes?y+2016:$.Map?y+6:[].map?y+5:y+3)


text:
Write a CFG acceptor
Write a program that, given a context free grammar and a string, returns whether the string is a word of the language defined by the grammar.
Input
Your program should read a context free grammar and an input string in an implementation defined way during runtime. Hardcoding the input is acceptable as long as it is trivial to change the input.
The context free grammar is a set of rules as defined by the regex [A-Z][a-zA-Z]*, that is: One capital letter denoting the nonterminal to be replaced and an arbitrary number of terminals (minuscules) and nonterminals (capitals) to replace it. The grammar may contain up to 256 rules. The initial symbol is always S. You may not assume that the grammar is unambigous. The grammar must contain at least one production rule for S.
The input string must match the regex [a-z]*. It has a length of no more than 65536 characters.
Output
Output is to be done in an implementation defined manner. Your program must output whether the input string is a word of the language defined by the grammar.
Constraints

Your program must terminate in reasonable time
You may not use any libraries that provide parsers or parser generators
You may not run any program that generates a parser
You may not use compression utilities or libraries

Scoring
This is code-golf. The submission with the smallest number of bytes wins
Example
The rules
S
SaSb

represent a grammar which defines the language anbn for n≥0. So given string aaabbb it would indicate that it accepts it, but given string aaabb it would indicate that it does not accept it.
The ruleset
S
SaSbS
ScSdS

describes the Dyck language. It describes the language of all balanced pairs of ab's. and cd's. For instance, string ababacabdb matches but cabdacb doesn't.

Python 2.7, 325 chars
R=['S','SaSb']
I='aaabbb'

L=len(I)
def P(x,y,n):
 if n<3:return[[x,y]][:n>1or x==y]
 return[[x]+w for z in range(x,y+1)for w in P(z,y,n-1)]
S={(i,i+1,c):1for i,c in enumerate(I)}
T=0
while S!=T:
 T=dict(S)
 for r in R:
  for a,x,y,b in P(0,L,4):
   if any(all(t in S for t in zip(p,p[1:],r[1:]))for p in P(x,y,len(r))):S[x,y,r[0]]=1
print(0,L,'S')in S

The rules are listed in R and the input is in I.
The code uses dynamic programming, similar to the Earley algorithm.  S contains tuples (i,j,N) if the symbol N can generate the input from indexes i to j.  We iterate through all rules and indexes looking for new entries we can put in S.
P is a helper function that calculates all possible partitions of the range [x,y] into n-1 ranges (assigning one symbol in the rule to each).  For instance, P(0,7,4) contains, among many others, [0,3,6,7].
The run time is exponential in the longest rule, but shouldn't be too bad in the number of rules and length of the input.

source: Stack Exchange

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

sort: votes


text:
Create a hash from an array of arrays of key|value pairs
Starting from an array of sub-arrays, each sub-array is a 2 elements key|value pair. Example
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]

Convert this into a hash that has distinct keys from above, with values summed up, so the above would be:
output = {"A" => 17, "B" => 0, "C" => 7}

Not to nit-pick, but the title of this challenge is a little misleading. An array of arrays of key|value pairs would imply higher complexity than I think you intended. Maybe change to Create a hash from an array of key|value pairs?

Is this intended to be restricted to a very small number of languages?

Any winning criteria?

Perl
Hopefully this thread won't get tagged code-golf
use strict;
use warnings;

my $a = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]];

my %h = ();

map { $h{shift @$_} += shift @$_ } @$a;

while (my ($k, $v) = each %h)
{
  print "$k = $v $/";
}

Output:
$ perl cg-arraysum.pl
A = 17
C = 7
B = 0

Ruby
input.each_with_object(Hash.new(0)) { |(k, v), h| h[k] += v }

(see http://api.rubyonrails.org/classes/Enumerable.html#method-i-each_with_object)

k
This can probably be shortened from 17 chars but:
{+/'(*|+x)(=*+x)}

Example:
k)x:(("A";5);("B";2);("A";12);("B";-2);("C";7))
k){+/'(*|+x)(=*+x)}x
"ABC"!17 0 7

or with output in q output format:
A| 17
B| 0
C| 7

There's more than one way to do it (Perl)
Preparation:
$input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]];

I have three Perl snippets to solve the problem because the obvious code is kinda boring. It looks like this:
$output1{$_->[0]} += $_->[1] for @$input;

I'm a fan of list expressions, so here's a single list expression, I had to use map and his friend grep a lot:
%output2 = map {
    $c = $_ => sum map $_->[1] => grep $_->[0] eq $c => @$input
} keys %{{map @$_ => @$input}};

Many years I tried to find a non-trivial use-case for List::Utils reduce function which folds list elements with a given function, and finally here it is. A second single list expression, btw. \o/
$output3 = reduce {
    $a = {@$a} if ref $a eq 'ARRAY'; $a->{$b->[0]} += $b->[1]; $a;
} @$input;

i like your first solution using the for loop instead of my map. ignoring the return value of map is ugly. it also seems to be the most practical of the three

@ardnew yep, you're right, calling map in void context is considered evil. Glad you like the first solution, the second and third one are just for fun. :)

C
Assumes keys are 'A'..'Z', assumes values are numbers, assumes input format is exactly spaced/formatted as specified in example.
char*p;c[99],m[99];
main(int i,char**v){
    for(p=v[1]+1;*p==91;){
        c[p[2]]+=atoi(p+5);
        m[p[2]]=1;
        for(;*p-93;p++);
        p+=p[1]-44?1:3;
    }
    printf("{");
    for(p="";++i<99;)if(m[i])printf("%s\"%c\" => %d",p,i,c[i]),p=", ";
    printf("}\n");
}

Run as:
./a.out '[["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]'

Output:
{"A" => 17, "B" => 0, "C" => 7}

hehe, I admire your treatment of the input as a string and not simply using a proper key-value array structure

R - 20 chars
aggregate(.~k,x,sum)

where x is the input defined here:
x <- data.frame(k = c("A", "B", "A", "B", "C"),
                v = c(5, 2, 12, -2, 7))
x
#     k     v
# 1   A     5
# 2   B     2
# 3   A    12
# 4   B    -2
# 5   C     7

The output:
aggregate(.~k,x,sum)
#   k  v
# 1 A 17
# 2 B  0
# 3 C  7

Python
output = {};
for x,y in input:
    output[x] = y + ( output.get(x) or 0 )

Thanks for @Daniero's comment.

That doesn't meet the specification, and it's frankly quite crude. This one does what it's supposed to, and, with shortened variable names, it's shorter than another python answer here:
h={};for x,y in a:d[x]=y+(d.get(x)or 0) - the ';' needs to be replaced by a linebreak.

@Daniero even shorter: d={};for x,y in a:d[x]=y+(d.get(x,0))

Mathematica
In Mathematica the input array would be represented as n = {{"A", 5}, {"B", 2}, {"A", 12}, {"B", -2}, {"C", 7}};.
Code
{#[[1, 1]], Total@##[[All, 2]]} & /@ GatherBy[n, First]

{{"A", 17}, {"B", 0}, {"C", 7}}

Explanation
GatherBy[n, First] gathers the data by the first element in each subarray (sublist).

{{{"A", 5}, {"A", 12}}, {{"B", 2}, {"B", -2}}, {{"C", 7}}}

Total@##[[All, 2]] sums the second elements for each string, #[[1, 1]] (in this case, for "A", "B", and "C").

Python 52 43
{X:sum(y for Y,y in a if Y==X)for X,x in a}

The input array is in a
This is fairly inefficient because it calculates the sum of all the 'A' keys for every occurrence of the 'A' key, but it works and since there aren't really any winning criteria I decided to golf my answer as much as possible.
Edit: Removed some unnecessary brackets and indices per recommendation from Daniero

You don't need the square brackets inside sum(). Also, by "unpacking" (?) two values out of a, you don't need the indices: {X:sum(y for Y,y in a if Y==X)for X,x in a} is 9 chars shorter (untested as neither this nor the original did work with my local python 2.5.2; It seems legit though).

@Daniero okay, ill look into that. Also, dict comprehensions were introduced in python 2.7 (i think) so thats probably why it doesn't work on your 2.5 version

@Daniero that works for me. I didn't know you could do list comprehensions without brackets like that.

That would explain it; I knew I had been doing dict comprehensions before! About the brackets: If you wrap the comprehension in parentheses like (x for x in a) you get a <generator object <genexpr> at 0x107784eb0>, So I guess that's what's being sent to sum(). Or it's just a shortcut notation.

ruby, 40 (or 38)
h=Hash.new(0);input.map{|k,v|h[k]+=v}
h

h contains the result.
The 38-char solution creates the wanted result, the 40 characters solution returns the result.
The result as complete testcode:
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
output = {"A" => 17, "B" => 0, "C" => 7}

h=Hash.new(0);input.map{|k,v|h[k]+=v}
p h == output #true

A little variant (but with the same size):
h={};input.map{|k,v|h[k]=(h[k]||0)+v}

TXR
@(do (let ((h (hash :equal-based)))
       (each ((entry '(("A" 5) ("B" 2) ("A" 12) ("B" -2) ("C" 7))))
         (inc [h (first entry) 0] (second entry)))
       (format t "~a\n" h)))

Run:
$ txr sumhash.txr
#H((:equal-based) ("A" 17) ("B" 0) ("C" 7))

What if we take the question literally? The question says that the input is this:
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]

and that the output looks like this:
output = {"A" => 17, "B" => 0, "C" => 7}

Fair enough. We can make a program to transform that exact input to  that exact output, rather than massaging the data to fit the syntax of our programming language.
input = [@(coll :vars (key value))["@key", @{value /[+\-]?[0-9]+/}]@(last)]@(end)
@(bind (keyout valout) @(let ((h (hash :equal-based)))
                          (each* ((k key)
                                  (v [mapcar (op int-str @1 10) value]))
                             (inc [h k 0] v))
                          '(,(hash-keys h) ,(hash-values h))))
@(output)
output = {@(rep)"@keyout" => @valout, @(last)"@keyout" => @valout@(end)}
@(end)

Run:
$ txr sumhash2.txr -   # input read from stdin
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
<user types Ctrl-D>
output = {"A" => 17, "B" => 0, "C" => 7}

Empty case:
$ txr sumhash2.txr -
input = []
<Ctrl-D>
output = []

Invalid input:
$ txr sumhash2.txr
foo
<Ctrl-D>
false

Word false is output, termination status is failed.
Simplified version in which hashing is worked into data acquisition (side effects during pattern matching):
@(bind h @(hash :equal-based))
input = [@(coll)["@key", @{value /[+\-]?[0-9]+/}]@\
                @(do (inc [h key 0] (int-str value 10)))@\
                @(last)]@(end)
@(bind (keyout valout) (@(hash-keys h) @(hash-values h)))
@(output)
output = {@(rep)"@keyout" => @valout, @(last)"@keyout" => @valout@(end)}
@(end)

Javascript 79
function f(a){r={};for(e in a){i=a[e][0];j=a[e][1];r[i]=r[i]?r[i]+j:j}return r}

Test :
f([["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]])
Outputs :
Object {A: 17, B: 0, C: 7}

Swift 4
Optimized for clarity, not character count. Replace the input as needed or pass it in some other way (e.g. through an I/O class).
import Darwin // or Glibc if on Linux

let input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]

var output: [String: Int] = [:]

for pair in input {
    guard let key = pair[0] as? String else {
        fputs("Input error: key '\(pair[0])' is not a string\n", __stderrp)
        exit(1)
    }
    if output[key] == nil { // the first of this key
        output[key] = 0 // have to add to something, so put in 0
    }
    output[key]! += pair[1] as? Int ?? 0
}

for pair in output.sorted(by: <) {
    print("\(pair.key): \(pair.value)")
}

Bonus!

Error handling:

If you input keys that aren't strings, it will give an error message and exit.
If you input values that aren't integers, it will silently assume they're 0.

The output is sorted.

Java 8
Here's an approach that uses streams:
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Stream;
import java.util.stream.Collectors;

public static Map<?, Integer> collect(Object[][] pairs) {
    return Stream.of(pairs)
        .collect(Collectors.groupingBy(
            pair -> pair[0],
            HashMap::new,
            Collectors.reducing(
                0,
                pair -> (Integer) pair[1],
                Integer::sum
            )
        ))
    ;
}

Uses a collector that groups elements into a map based on their first element, with duplicate values reduced by addition.
Or there's the classic loop version:
public static Map<?, Integer> collect(Object[][] pairs) {
    Map<Object, Integer> map = new HashMap<>();
    for (Object[] pair : pairs) {
        Object k = pair[0];
        int v = (Integer) pair[1];
        map.put(k, map.getOrDefault(k, 0) + v);
    }
    return map;
}

Java - 71
<T> Map m(final T[][] i) {
  return new HashMap() {
    { for (T[] p : i) put(p[0], p[1]); }
  };
}

The following...
System.out.println(m(new Object[][] {
  { "A", 5 }, { "B", 2 }, { "A", 12 }, { "B", -2 }, { "C", 7 }
}));

produces:

{A=12, B=-2, C=7}

You need to read the spec more carefully. Your implementation will only store the last read value of the input array (compare your outputs to the example).

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

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


text:
calculate days of a month
I would like to see the shortest expression to calculate the days (or the last day)  of a month in any language.
Considering y as the number of year and m as month.
Basic rules

without date / time functions.
considering leap years.
there is not other rule.

C, 40 33 31 characters
Reduced length in three ways:
1. Replaced m%2^m>7 with m^m>7. The first is 0/1 in 30/31 day months, the second is even/odd. But the high bits don't matter, because their all set in 30 anyway (months with 30/31 days look like a really good idea now).
2. Used mob's idea (y%(y%100?4:400) as a leap year test)
3. Used <1 instead of ! saves parenthesis.
4. y%(y%100?4:400) -> y%(y%25?4:16) - works the same.
m-2?30|m^m>7:28|y%(y%25?4:16)<1

...:28+!(y%(y%100?4:400)) shaves 3 more

Thanks @mob, I'm taking it a bit further, will update soon.

If you're going to use y%16, why not y%8?

In fact, (y%50?4:8) or (y%25?4:8) work as well.

Thanks @mob, %16 works. %8 fails on 2200. I thought about &15, which isn't good, and somehow missed the equivalent %16

Good catch. I didn't have 2200 in my test cases.

C, 47 45 characters
30+(m>7^m&1)-(m^2?0:2-!(y%100||(y/=100),y%4))

Taken from an answer to an earlier question where I borrowed a couple of tricks from another user. Returns the length of month m in year y for the Gregorian calendar. ugoren's answer to the same question is shorter and may give a shorter answer to this question.
With thanks to mob for his leap year calculation.

Here's another trick: use the expression !(y%100||(y/=100),y%4)

@mob Wow. It's taken me a good fifteen minutes to figure out how that works (I even checked it on ideone to make sure it did). Clever.

Figured out a better one: !(y%(y%100?4:400))

@mob I think I'll leave mine as it is now - there's no way I'll catch up with ugoren's answer.

I've already answered it before in stackoverflow:
(62648012>>m*2&3)+28+(m==2&&y%4==0)

https://stackoverflow.com/questions/2675720/calculate-days-of-month/11675530#11675530
[EDIT]
Matt advertised me about leap yars below and he's asked about language. About the language: the expression works on c/c++ and maybe others.
So, the simplest form will work until 2100... but to prevents the 2100 bug :) I've copied the Matt solution to leap year:
(62648012>>m*2&3)+28+(m==2&&(y%4==0&&(y%100!=0||y%400==0)))

I'm not familiar with the language you are using so I may be incorrect, but I don't think you account for integer multiples of 100 (not leap years unless they are also integer multiples of 400) http://en.wikipedia.org/wiki/Leap_year#Gregorian_calendar for example: 2100 is not a leap year

You are right! I will fix it. thanks.

Python 64 61 59
(62648012>>m*2&3)+28+(m==2and y%4==0*(y%100>0 or y%400==0))

Based on olivecoder's solution, but accounting for multiples of 100.

VBA, 84
28+Val(Mid("303232332323",M,1))-(M=2 And Y Mod 4=0 And (Y Mod 100>0 Or Y Mod 400=0))

Python 50 54 57
29+{2:y%(y%25and 4or 16)and-1}.get(m,(1&m^m>>3)+1)

with inspiration from mob, and the interesting fact, that
a dict saves 1 byte in contrast to m==2and(..)or(...)

Mathematica 97 91 83 82 78 76
A bit long, but gets the job done.

     d
     =

       y
       ~
       Divisible
       ~
       #

      &

    ;

     30
     +

       {

        1
        ,

          Boole
          [

            d
            @
            400

           ∨

            (

              d
              @
              4

             ∧

              ¬

               d
               @
               100

            )

          ]

         -
         2

        ,
        1
        ,
        0
        ,
        1
        ,
        0
        ,
        1
        ,
        1
        ,
        0
        ,
        1
        ,
        0
        ,
        1

       }

      [

       [
       m
       ]

      ]

VB.net (89 81c)
shame about the date function restriction as VB.net at only (21c)
Date.DaysInMonth(y,m)

may have won one for a change. DAMN YOU!
So current best is 89c
    {0,31,28,31,30,31,30,31,31,30,31,30,31}(m)+(If( m=2 AndAlso (y Mod 4)=0 AndAlso (y Mod 400)>0,1,0)
{0,31,28,31,30,31,30,31,31,30,31,30,31}(m)+(If( m=2 And (y Mod 4)=0 And (y Mod 400)>0,1,0)

if we ignore the restriction on YDM, then I can beat that with Excel at only 19 characters with =DAY(DATE(y,m+1,0)) :)

Importing the Namespace System.Date would mean you can remove the first 5 chars, so that brings it down to 16c


text:
Given a number, program must return the alphabet letter correspondent
The program
Given a number, program must return the alphabet letter correspondent.
Rules

The challenge here is to make it as short as possible, everyone knows it is a very easy program to do.
The number is not zero-based, it means 1 is A, 2 is B, 3 is C and so it goes...
Any language will be accepted.

I suspect the winning answer will be tiny.

I think my answer won

@BernaMariano What does "given a number" mean?

@toothbrush If Goku gives you a 3, use 3.

@BernaMariano Well, I'm not sure what you mean, but is my answer OK, then?

DC - 6 characters
Full program including input and output.
?64+af

save to file and run with $ dc file

1 character shorter: ?64+P

Typically: dc -f file

APL (4)
(Full program)
⎕⌷⎕A

Explanation:
⎕ (user input) ⌷ (index) ⎕A (alphabet)
(They're supposed to be boxes, it's not an encoding problem.)

Brainfuck, 107 bytes
>,----------[>++++++[-<------>],----------]<[<]>>[<--[->++++++++++<]>>]+++++++[-<+++++++++>]<-.>++++++++++.

brainfuck, 64 56 50 bytes
Thanks to Dorian for saving 3 bytes and inspiring 3 more
,>,[<+[-<+>[-<]>>]<[<++<-]>++>>]<<+++[->+++++<]>+.

Try it online!
How it works
,>, Gets input
   [ if a two digit number
    <+[-<+>[-<]>>] Gets modulo 2 of first number plus 1
                  <[<++<-] Sets the fives cell to 2 if the first number is a 2
                          >++ Adds another 2 to the fives cell
                             >>]  Moves to cell after ones cell
                                <<+++ Adds 3 to fives cell
                                     [->+++++<] Multiply the fives cell by 5 and add it to the ones cell
                                               >+.  Add one and print

Can be made shorter. Instead of tens, use "fives". Increment the tens by two for each ten, then multiply by five. Saves 3 Bytes.
,>,[<[-<+>[-<]>>]>[>++>]<++[-<+++++>]]++++[-<++++>]<.

Even more. By changing the 44 routine in the end to 35+1, you can use the fives and add them to the 3. It's a bit tricky to exit the if then, but it saves another 4 Bytes. ,>,[<[-<+>[-<]>>]<<<[->+<]>+>>]<<+++[->+++++<]>+.

@Dorian Your second solution doesn't work for numbers over 20, but thanks for the bytes saved!

Oh, I'm sorry. Didn't test it well enough. I'm glad you repaired it.

R, 11 characters
LETTERS[x]

Usage:
LETTERS[21]
[1] "U"

Befunge-93, 7 6 bytes
"&++,@

Try it online!
Takes advantage of the extra spaces at the end of a wrapping string literal by adding two spaces (32*2 = 64) to the inputted number to turn it into the corresponding alphabetic character. Funnily enough, if we use a implementation that doesn’t include the wrapping spaces, we can do "&+.@ to add the @ (64) to the number instead.

J, 7 characters
a.{~64+

Usage:
   a.{~64+1
A

Perl, 20 characters
chr(($ARGV[0] + 64))

Verification :
risk@skynet:~/perl$ for x in {1..26}; do perl ./ord.pl $x; done;
ABCDEFGHIJKLMNOPQRSTUVWXYZrisk@skynet:~/perl$

TI-Basic, 34 bytes
sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",Ans,1

This is as short as it gets...

PHP, 17 bytes
<?=chr(64+$argn);

Run s pipe with -F

MATL, 4 bytes
64+c

Try it online!
Because, why not. Takes input implicitly, pushes 64 and adds it to the input number. Finally it converts the number to its ASCII-equivalent using c.

Pyth - 5 3 Bytes
@Gt

Saved two bytes thanks to ovs
Completely forgot about t and implicit Q
Explanation:
@    Index
 G   in alphabet of
  t  one less than
   Q Input (implicitly added to solve arity)

@Gt for 3 bytes

@ovs Thanks. Forgot about t and implicit Q

Ly, 6 bytes
n8:*+o

Try it online!

Husk, 4 bytes
c+64

Try it online!
Boring, but probably optimal. Adds 64 to the given number and converts it to ASCII. !¡→'A is cuter (awww, the exclamation marks are friends!) but one byte longer.

Hexagony, 10 Bytes
Try it online!
A({/'+;?/@

Expanded:
  A ( {
 / ' + ;
? / @ . .
 . . . .
  . . .

This honestly took me way longer than it should have, as it's just 2 simple reflections.

The simplest version for this problem is only 2 bytes longer
  A ( {
 . . . .
? ' + ; @
 . . . .
  . . .

PowerShell, 19 18 bytes
-1 byte thanks to @mazzy lolI don't think it'll get much shorter than this.
[char](64+"$args")

Try it online!
Takes input from a command line argument.

You can. Try this [char](64+"$args"). :)

Powershell 6, 17 bytes
('@'..'Z')[$args]

q/k (7)
As partially applied composition:
10h$64+

Ruby 1.9 (10)
(x+64).chr

Reading from STDIN and printing to STDOUT:
$><<(gets.to_i+64).chr

Burlesque (6 characters)
Assuming the number is already on the stack: 64.+L[ (see here in action.).
Does the usual: Add 64, convert to character based on ASCII value.
If number is supplied as a string via stdin to stdout (10 characters):
ri64.+L[sh
Alternative version without using ASCII value conversion:
'@'Zr@\/!!

Python 2, 9 bytes
chr(64+x)

Or, reading from stdin and printing to stdout: 21
print chr(64+input())

Submissions have to be full programs or functions, and your first solution is a "snippet". You should only include your second solution.

GolfScript, 7
64+]''+

Commentary
64    # corresponds to '@' in ASCII (65 is 'A')
+]    # add the input to 64. ']' is used for ASCII.
''+   # the conversion process

1 corresponds to A
26 corresponds to Z

It can indeed: assuming that the only thing on the stack is the number from 1 to 26, you don't need the [.

Javascript, 25 chars
String.fromCharCode(66-x);

PHP, 22 chars
echo chr(66-$argv[0])

Classic ASP (14 bytes):
<%=Chr(c+64)%>

Expects c to hold the character number.

program must return -> I see no program, I don't see c being initialized, I don't see anything returned/printed.

@RobIII OK; changed to Classic ASP. Is that what you mean?

Where does the value of c come from? You'd need something like request.form("c") or something (and the inevitable cast to int/long etc.).

@RobIII The question says "given". Perhaps we can ask for clarification?

I interpret this as "when the program is given" but asking for clarification won't hurt ;)

C# 4,50KB (196 characters)
My first time here =)
using System; namespace W { class P { static void Main(string[] args) {
            Console.WriteLine(" abcdefghijklmnopqrstuvwxyz".ToCharArray()[int.Parse(Console.ReadLine())]);
        }
    }
}

First of all, don't forget the byte count of the program. Second, there are several ways of shortening this. First, remove all unnecessary whitespace (for example, the  s after the " ",s. You could split the string " abcdefghijklmnopqrstuvwxyz". Also, rather than compile a list beforehand, it is much more efficient to choose the characters based off of ascii values.

Also: the contest explicitly mentions The program; this is not a complete program but (part of) a function. Other than that: drop the array/lookup! Ever heard of the ASCII table? ;-) And dont forget that, if you insist on a "lookup table", a string is an array of chars: string a=" abcdefghijklmnopqrstuvwxyz"; shortens your code massively.

You can drop the namespace entirely, use the args for input instead of Console.readline, shorten args to a and drop the using System and just write System.Console.WriteLine. The .ToCharArray() is also not required (a string is a char-array implicitly). Finally, the WriteLine can be shortened to Write since the challenge doesn't specify that the program needs to output a newline.

...So your entry could be shortened to 112 chars (compiled size doesn't matter, "lose" the 4,50KB) if you incorporate all these tips: class P{static void Main(string[] a){System.Console.WriteLine(" abcdefghijklmnopqrstuvwxyz"[int.Parse(a[0])]);}}. The only thing left to do to "optimize" this code further is to drop the alphabet string and just use ASCII as I did in my entry which will get you down to 88 :-)

Oh, and your entry states "196 characters"; I don't know how you counted (but I assume you looked at the filesize of the .cs file?): your entry is actually 162 chars when all non-functional(!) whitespace is removed: using System;namespace W{class P{static void Main(string[] args){Console.WriteLine(" abcdefghijklmnopqrstuvwxyz".ToCharArray()[int.Parse(Console.ReadLine())]);}}}.

Haskell, 38 bytes
main = putChar $ ('a':['a'..'z']) !! c

Where c is the number.

There is a lot of unnecessary white space: main=putChar$('a':['a'..'z'])!!c works as well. However you can not assume input to be present in a certain variable, but then again returning from a function is acceptable, so f c=('a':['a'..'z'])!!c or equivalently (('a':['a'..'z'])!!) works.

C#, 87
class P{static void Main(string[]a){System.Console.Write((char)(int.Parse(a[0])+64));}}

Complete program (not some (part of a) "function" expecting foo to be bar to work), accepts command line parameter: foo.exe 1 prints A, foo.exe 16 prints P
C#, 10
When I make the same assumptions as, for example, the 'code-golfers' that posted the VSCript Classic ASP, Python, Burlesque, Ruby, C solutions we can get it down to 10:
(char)x+64

"Assuming x is magically initialized / passed in / on the stack / whatever excuse" and the contest doesn't explicitly require me to print it, just "return" it (which most of the above solutions don't do, either).

I've changed my answer to a full Classic ASP example now.

Well, the author of the question did NOT specify how the number is given. "Given a number" is completely under-specified. Is it on stdin, is it a command line argument is it given somewhere else... You have no other choice than to make assumptions about how you get that number and how you return it.

@mroman See my comments on the Classic ASP and C answers.

Tcl, 30 bytes
puts [expr [scan $argv %c]-64]

Try it online!

BrainFuck, 66
,>,----------[<[->++++++++++<]++++++[>+++++++<-]>>]++++[<++++>-]<.

Require number ends with \n(10) and mod 256 env

Please add some explanation in the body of the answer.

Jelly, 3 bytes
ịØA

Try it online!

SmileBASIC, 18 bytes
INPUT N?CHR$(N+64)

Java 8, 15 bytes (as lambda function)
n->(char)(n+64)

Try it online.
Java 8, 84 bytes (as full program)
interface M{static void main(String[]a){System.out.printf("%c",new Byte(a[0])+64);}}

Try it online.

This works only for single digit. Double digit input will fail. ex: give 10 as input and output still comes as A. You care considering charAt(0), for double digits, you have to consider 2 characters.

@BarathVutukuri Thanks, fixed!

Haskell, 11 bytes
(['@'..]!!)

Try it online! This anonymous function indexes into the string "@ABCDEFG ...".

Fortran (GFortran), 30 bytes
READ*,I
PRINT*,ACHAR(I+64)
END

My entry in the good ol' Fortran.
Try it online!

FORTH 16 BYTES
: n 64 + EMIT ;

OUTPUT:
8 N
8 N H ok
5 N
5 N E ok
12 N
12 N L ok
12 N
12 N L ok
15 N
15 N O ok
23 N
23 N W ok
15 N
15 N O ok
18 N
18 N R ok
12 N
12 N L ok
4 N
4 N D ok

Tcl, 31 bytes
puts [format %c [incr argv 64]]

Try it online!

Japt, 2 bytes
dI

Try it or test all numbers

PHP 442
$alphabet = Array('A' => 1,'B' => 2,'C' => 3,'D' => 4,'E' => 5,'F' => 6,'G' => 7,'H' => 8,
'I' => 9,'J' => 10,'K' => 11,'L' => 12,'M' => 13,'N' => 14,'O' => 15,'P' => 16,'Q' => 17,
'R' => 18,'S' => 19,'T' => 20,'U' => 21,'V' => 22,'W' => 23,'X' => 24,'Y' => 25,'Z' => 26
)

function testInputForAlphabetCharacter($input){
    for($index = 0; $index < count($alphabet); $i = $i + 1){
        if($alphabet[$index] == $input){
            echo($index);
        }
    }
}

$input = $_GET['input'];
testInputForAlphabetCharacter($input);

@scleaver... o_0

I agree with @IanBrindley, this is serious overkill... There's no chance of shrinking this down?

echo chr(64+$input);

this is as small as i could get it


text:
A simple Knight's problem
How many ways are there to place a black and a white knight on an N * M chessboard such that they do not attack each other?
A knight can move two squares horizontally and one square vertically, or two squares vertically and one square horizontally.
The knights have to be placed on different squares and the knights attack each other if one can reach the other in one move.
Input:
The first line contains the number of test cases T. Each of the next T lines contains two integers N and M, representing the dimensions of the board.
Output:
Output T lines, one for each test case, each containing the required answer for the corresponding test case.
Sample input:
3
2 2
2 3
4 5

Sample output:
12
26
312

Constraints
    1 <= T <= 10000
    1 <= N,M <= 100000
time limit 1 sec

Source Limit:
50000 Bytes

Winning criteria
Shortest code which runs with specified time limit decides the winner

i ll leave two days time for more users to try from today

I tidied up the formatting a little on your question, I hope you don't mind. Feel free to roll back the edit if you don't like it.

@Griffin i am new here thanks for the edit ,please correct me if i make mistakes in future

You're going to want to put a winning criteria on your question before it gets down-voted by all the boring people on this site. You need to have a fairly objective way of choosing a winner. e.g. shortest code, fastest running code for a given input or some point system of your choosing.

Do we need to worry about board dimensions <= 0?

@Griffin does my winning criteria ok?

@vignesh I don't understand your answer. I was asking if a board dimension of 0 is valid inputs, and also if negative board dimensions are valid.

@Matt, the challenge is based on a very real-world game. You cannot place a knight on a board with negative or zero dimension.

@matt consider my first input sample and you can clarify it

@vignesh actually nevermind, you had included that information in the original spec and I just missed it.

Question appears to be copied from here without any attribution.

GNU Octave, 55 56 58 78 87* 93 chars
a=t(:,1);b=t(:,2);-4*max(2*(g=a.*b)-3*(a+b)+4,0)+g.*--g

Octave doesn't take input from STDIN, so you've got to provide the input in the program:
t = [
    1 7;
    2 2;
    2 3;
    4 5;
    5000 6000
];                % test cases

a=t(:,1);b=t(:,2);-4*max(2*(g=a.*b)-3*(a+b)+4,0)+g.*--g

The logic is as follows:
nchoosek(n*m, 2) gives us the number of combinations of two positions we can have on a N*M board. We then multiply it by two since we have two different knights.
Then we work out how many 3*2 blocks fit in an N*M board. For each 3*2 block there are 4 different positions our knights can be attacking each other. So we multiply it by 4 and subtract it from the value we calculated above.
*thanks to a simplification of the nchoosek I shamelessly stole from Matt.
Edit
I've just tested this on my laptop to make sure it meets the time requirements.
It will compute 500,000 10,000,000 test cases in an average of 0.918787 0.231201 seconds

I can't test yours at the moment, but my solution that was based on yours gives incorrect results for boards of size 1xn, I suspect yours does as well.

@matt, you are correct, good catch. Also I've just noticed we've come up with the same fix.

@Griffin I don't know much of the Octave, but can't you use end instead of endfor?

@ArtemIce Yes you're right, when I was learning Octave I just assumed I had to end loops like that, silly me. Though I've just realised I don't even need a loop - huge performance increase.

@griffin excellent answer ,i ll keep my question alive for more solutions if it's your's best then i ll accept it !!!

Python 105 119 112 104
for a,b in[map(int,raw_input().split())for i in[1]*input()]:print a*b*(a*b-1)-4*(max(2*a*b-3*(a+b)+4,0))

This uses the same approach as Griffin's solution.
Now appropriately handles boards of size 1xn

+1 for the a*b*(a*b-1), I forgot the simplify the maths. I might pinch that...

(a-2)*(b-1)+(a-1)*(b-2) can be expanded and simplified to 2*a*b-3*(a+b)+4

Mathematica 55 50 38 41
Second attempt
This is my rendering, in Mathematica, of  @Matt's solution.
Credit for the underlying reasoning goes to Matt.
Griffin helped me understand how Matt's approach works.
It is faster than my first approach approach but still too slow to satisfy the time constraints for boards with 10^5*10^5 cells.  The pure function (38 chars) is defined as follows:
 #1 #2 (#1 #2-1)-4 Max[2 #1 #2-3 (#1+#2)+4,0]&

Usage
#1 #2 (#1 #2-1)-4 Max[2 #1 #2-3 (#1+#2)+4,0]& @@@ {{2, 2}, {2, 3}, {4, 5}}

(* out *)
{12, 26, 312}

The symbols, @@@, apply the function to the list. I included them in the character count.

First Attempt: 50 chars but really, really slow.
I'm including it because it may be of interest to some readers.
Mathematica doesn't take input from STDIN so I used an input more to its liking. There is no need to input the number of inputs; MMA will simply act on whatever number it is given.
Code
#1*#2*(#1*#2-1)-2 EdgeCount[#1~KnightTourGraph~#2] &

Usage (with spaces for readability).
#1*#2*(#1*#2 - 1) - 2 EdgeCount[#1~KnightTourGraph~#2] &; @@@ {{2,2}, {2,3}, {4,5}}

(* out *)
{12, 26, 312}

Explanation
Below is a graph of possible knight moves in a 4 by 5 chessboard.
k = KnightTourGraph[i, j, PlotLabel -> Subscript[K, i, j]]

There are 20*19 = 380 ways to arrange the black and white knight on the board.
Below is the adjacency matrix:
AdjacencyMatrix[k] // MatrixForm

There are 68 cases in which the knights are in an attacking position. This corresponds tohow many one's there are in the matrix.  It also happens to equal two times the number of edges and sum of the degrees of the vertices.
t = 2*EdgeCount[k]
(* out *)
68

Finally, 380-68 = 312.

Timing
It takes just under one second to calculate the answer for all grids up to 15 by 15.
Note: 312 is in row 4, column 5.

Do your timings include time to ouput (which I don't think they should)? Because you need to be able to calculate answers for grids up to 100000x100000.

Time to output is not included. (The ; suppresses that.) The routine seems to be relatively slow.

Why don't you take the conditionals out? Octave (pretty much MATLAB with some syntactic sugar I prefer) is interpreted too. Maybe using a table is slowing you down?

That was my first thought but the timing without the conditionals was just the same. I'll try using an alternative to Table. Thanks.

@Griffin.  The timing is slightly faster (2x) with Do loops and no conditionals. There must be a better way.

I don't know enough about what Mathematica is optimised for to offer any suggestions. Maybe try compiling your function? http://reference.wolfram.com/mathematica/ref/Compile.html

I've been playing with compiling but I'll need some time to become proficient in compiling.  My attempts presently bail out with large tables.

It's annoying me greatly that I can't beat your 50 chars!

If it's any consolation, my first approach does not satisfy the time constraints of the problem. So, technically, my only valid approach takes 76 chars.

C++, 232 250 228 192 173 characters
#include<iostream>
int main(){long long n,x,y,i;for(std::cin>>n;n--;)std::cin>>x>>y,i=(x*2-2)*(y-2<0?0:y-2)+(y*2-2)*(x-2<0?0:x-2)<<1,x*=y,std::cout<<x*x-x-i<<"\n";return 0;}

SEE IT RUN
I don't know what hardware ideone uses, but that can run for a 10000x10000 board 10000 times in .2 seconds.
How I simplified the problem:
I started out trying to find ways I could divide the board into known regions, with a certain density of bad positions per square.  The simplest case is that if there are no edges within 2 squares of a square, that square has 8 possible failing positions.  This turned out to be really complicated near the edges of the board where more than 2 edges can sometimes come into play (if, for example, you have a board that's only 2 wide), so I decided to try to simplify it based on direction, which turned out to be very easy.
First, I considered just one direction.  On a chessboard of irrelevant length, how many moves are eliminated by the introduction of one unit of width?  I made a table:
Width of board         Number of positions eliminated
1                      0
2                      2
3                      4
4                      6
N                      2N-2

I used my E=2N-2 formula along with the knowledge that for a board of length L, L-2 rows are viable (and thus count towards the exclusion count).
The program, conceptually, makes 4 sweeps, one in each direction (in practice it does 2, and multiplies by 2.  It's a shortcut that works because of symmetry).  Each sweep represents the moves excluded that tend in the direction of the sweep.  The program then sums up each of the sweeps and subtracts from the total number of possible combinations.
Knight placement is random, but two knights cannot occupy the same space.  Therefore, the total number of positions you can place a knight is the total numbers of squares the first time, then the number of squares minus one the second time (since there is a square that's taken).
EDIT 1
fixed overflow, fixed forgetting to substract somewhere causing incorrect answers with a dimension of 1.  Also swapped out 31's for 63's in bit twiddling since it uses 64 bit data types now
EDIT 2
shortened further (introduced branching D: the non-branching version is 6 characters longer.)
GOLF SCORECARD

removed unnecessary clause: (~u>>31&(x<<1)-2) became ((x*2)-2) in 2 places, saved 16 characters (234)
swapped ~u>>63&u for u<0?0:u in 2 places, saving 2 characters (232)
swapped x-2<0?0:x-2 for u<0?0:u and removed definition of u u=x-2, in 2 places, saving 4 characters (228, shorter than original solution)
removed function f and moved functionality into main, saved 28 characters (200)
removed using namespace std; and used std::cout, std::cin, and "\n", saved 5 characters (195)
changed std::cin>>n;for(;n>0;--n) to for(std::cin>>n;n;--n), saved 3 characters (192)
removed typedef long long L; since its only used in one place now, saved 12 characters (180)
removed 4 parens from statements like ((x*2)-2), saved 4 characters (176)
removed brackets from loop by using commas instead of semicolons, compressed loop condition from std::cin>>n;n;--n to std::cin>>n;n--;, saved 3 characters (173)

This gives the wrong result for boards of size 1xn

@Matt: yeah I forgot to subtract when checking for positivity.  fixed now

Alright, I think we're maximally golfed.

I don't know too much C++ but can't y-2<0?0:y-2 be changed to max(y-2,0)?

@Griffin: I'd need to #include and use std::max.  Good suggestion though.  I always forget about little things like that that the STL provides for me and roll my own wheel.

Aha, well there is another saving. Changing <<1 to *2

@Griffin: thought of that too.  I'd need to wrap the rest of the expression in parens, so I'd gain a character.  (as it is it works because + takes precedence over <<)

Haha ok, last suggestion: http://ideone.com/zOBrg changed the loop conditional and removed the braces around the loop body by replacing all the semicolons with commas.

That one I'll add.  I've done that in all of my other golfs with c and c++, don't know why I forgot :D.  We're definitely squeezing water from the proverbial rock now. we've hit the C++ degeneracy pressure. If we compress it any further, it will decay into python. :D

You can remove int  before main and you can remove the return 0; and if you compile as 64bit, you can remove one of the longs.

See this question: http://stackoverflow.com/questions/204476/what-should-main-return-in-c-c Also, if I omit the return statement, ideone throws a signal.  The code provided is the shortest possible cross platform, standards compliant code (at least I think it is.  Disregarding the fact that I don't think long long HAS to be 64 bits, it just tends to be).

Go
package main
import "fmt"
func main() {
    var N int
    fmt.Scanln(&N)
    for ; N > 0; N-- {
        var m, n int64
        fmt.Scanln(&m, &n)
        grid := m*n
        total := grid*(grid-1)
        if m > 2 && n > 1 {
            total -= (m - 2)*(n - 1) * 4
        }
        if n > 2 && m > 1 {
            total -= (n - 2)*(m - 1) * 4
        }
        fmt.Println(total)
    }
}

Explanation

grid is number of grid
total is initialized as all the possible ways the knights could be placed. Since they have to be different grids, grid * (grid - 1)
Now we exclude the number of ways they may attack each other

Their position could be two squares difference horizontally and one square vertically. The number of ways is (m - 2)*(n - 1) when m > 2 && n > 1. The left can be higher of lower then the right, so *2. White and black are exchangable, so *2 again.
Similar to the situation for two squares vertically and one square hotizontally

Timing

4 int64 multiplication and 7 int64 plus/minus operation, should be done in 1 second.


text:
Implement half away from 0 rounding
Overview:
Using you language of choice, implement a complete "half away from 0" rounding function in the shortest amount of code possible.
Rules/Constraints:

Direct, predefined Round-like functions are not allowed.
Floor/Ceiling-type functions are allowed, if your language supports these.
Function shall be able to handle 32-bit floating-point values.
Function shall be able to correctly handle negative values (see examples).
This is Golf, so shortest code wins.
Correct rounding for this challenge is to round away from 0, such that a rounded value will have an equal or larger absolute value.

Input/Output:

Your function shall take two parameters:

The first is a float x, which is the value to round.
The second is an integer n, which is the number of decimal places to round to.
x can be a whole number or contain a decimal part, fitting within a 32-bit, single-precision float.
n can be greater than or equal to 0, and may be larger than the number of decimal places in x.

Output will be the correctly rounded x.
*In cases where the solution is not exactly representable in IEEE float format, the output should be the logical representation you would have figured if not using a computer. i.e. The output of Round(0.125, 2) should be 0.13.

Example I/O:
Round(1.23456789, 7)
1.2345679

Round(1.234, 5)
1.234 OR 1.23400 (Your choice on trailing 0)

Round(-0.5, 0)
-1 NOT 0

Round(-0.123, 2)
-0.12 NOT -0.13

Round(3.1415926535897932384626433832, 20)
3.14159265358979323846

Winning:
**Some system limitations may be present which make your function less accurate/usable. In these cases, supply the best possible calculation you can within those limitations.
For example, I have a solution in my preferred environment, VBA in Office 2003, which only allows me to round up to 307 digits, while the IDE will only let me use values up to 15 significant decimal places. (I will eventually post this example here.)
With your answer submission, please post the highest values of n and the largest number of significant decimal digits for x for which your function will run. If you cannot meet the minimum requirements, that solution is disqualified, no matter the code length. (i.e. my own solution described above is invalid)
While this is code golf, and the shortest code will generally win. If two answers exist with different maximum values for x and n, the solution which works with the highest input values (measured as x * n) will win. If these two solutions meet the same limitation while fulfilling the requirements of the challenge, then the shortest code of those two will win.
If no solutions meet the requirement, then the best limitation score (shortest code length in the event of a tie) will win.
Example submission given the rules above for my own code:
<CODE HERE>
Max n = 307
Max x digits = 15
Limitation Score (x * n) = 4605

Ehm, you say that 15 decimal places is a limitation, and you give examples like 1.23456789, but you also say that it should handle single precision floats. So which one is it?

@MrLister The spec is to be able to handle Singles. For what I am able to come up with on my own, as an example only, I am personally limited to 15 characters. In other words, my own solution is not valid for this challenge. 1.23456789 is again for example only.

What is your rounding rule for exact halves? Based on the example of -0.5 it could be away from 0 or nearest odd number; you should make it explicit because a) it's ambiguous; b) those are both weird rules. (The standard rules are half-up, half-down, or half-even).

What constitutes "correctly rounded"?

@Gaffi see: http://en.wikipedia.org/wiki/Rounding#Tie-breaking

Thanks for the link, @ardnew. I am still going to go with away from 0. Updating question...

What should we return when the rounded value isn't exactly representable?  For instance Round(.125,2).  .125 is exactly representable, but .13 isn't.

@KeithRandall I don't know that I understand... Why is .13 not a good response for that input?

@Gaffi: because it isn't exactly representable in IEEE float format.  The closest IEEE (64 bit) number to .13 is approximately 0.13000000000000000444.

@KeithRandall Thanks for explaining. In that case, the output should be the logical representation you would have figured if not using a computer. i.e. the output should be .13. I'll add to the quesiton.

That doesn't make sense as an answer to @Keith's question, assuming that the return type of Round is float. Or is it meant to return a string?

@PeterTaylor To that point, I suppose I did not specify the format of the output. My intent was to be able to read the value as would be calculated by hand (in someone's head) without the caveats that a float presents. I will say that the output can be in any data format, so long as the numeric format works within those bounds already explained (and which you correctly edited). If it is not possible - using the data type you return -  to print the value in the correct format, then another output data type will be necessary (i.e. a string, as you've pointed out).

@Gaffi The example you posted says Round(0.123, 2) should be 0.13, but I believe you meant to say Round(0.125, 2). I tried editing it for you, but it was rejected for some reason.

Floating point is tough to get right.  For instance, the IEEE 64-bit representation of 0.15 is a value close to 0.14999999999999999444, so should Round(0.15,1) be .1, or .2?  Hmmm....

@ardnew Yes, Peter Taylor corrected that for me already.

@KeithRandall Round(0.15,1) should output .2. The determination should be based on the input, not necessarily how the system interprets it.

But you can't pass in 0.15 to Round.  It isn't a representable floating-point number.  In other words, when you write Round(0.15,1) in your source, what actually gets called at runtime is Round(0.14999999999999999444,1).  You can't actually pass 0.15 to Round - the string 0.15 gets converted to a float (a.k.a. rounded to the nearest IEEE number) before the call happens.

In other words, your spec requires Round(0.15,1) and Round(0.14999999999999999444,1) to return different answers.  But to the code that implements Round, those are indistinguishable calls.

@KeithRandall I understand you. I may be outside of my league on this challenge, as I can't think of a great way to handle that. I should have taken this to the sandbox, but I thought (incorrectly) that this would be simple...
This may be a bit convoluted, and perhaps incorrect as well, but would it be viable to round the float version of x to n+1, then round that? Or would that lead to the same issue already here?

@Gaffi: I don't think that helps.  Allowing some wiggle  room might, for instance you can round either way if [x-epsilon,x+epsilon] contains the halfway point.  But then the "half away from 0" part doesn't make much sense.

@Gaffi maybe I'm being dense, but it doesn't appear to be corrected. you're referring to the last bullet under the Input/Output: section?

@ardnew That line was fixed, but not for the error you pointed out. I was being dense; you were correct. I've updated the post.

@KeithRandall This detracts a bit from the original challenge, but how about accepting a string input instead?

@Gaffi: don't worry, I'm happy with the challenge as-is.  Just have to be a bit lenient with holding people to the spec.

@ardnew, the text you added to pad your edit out to be long enough was factually incorrect (0.125 is 1/8 and so can be exactly represented in binary floating point), so I rejected it and made the two-character edit which the edit comment said was the edit you really wanted to make. Edit: doh, I missed that you also changed 0.123 to 0.125. Sorry.

@PeterTaylor oops, my mistake! thank you very much for clarifying

Q (29 Characters)
{("i"$x*10 xexp y)%10 xexp y}

Sample usage
{("i"$x*10 xexp y)%10 xexp y}[1.23456;4]

Works by multiplying your x input by 10 to the power of your y input, casting to an int and then dividing again by 10 to the power of your y input.

Deduplicate for great savings {(6h$x*i)%i:10 xexp y}.

C, 51 Characters
float round(float x, int n)
{
    return(long)(x*pow(10,n)+(x>0?0.5:-0.5))/pow(10,n);
}

Not including the function headers, it's 51 characters.

Python (153 chars, max(x)=infinite, max(n)=13)
You can input a float, however it works much, much better (max(n)=infinite instead of 13) if you input a string.
def Round(x,n):
    x=map(str,str(x))
    if n==0:x.remove('.')
    n+=1+(n!=0)+(x[0]=='-')
    if n<len(x):x[n-1]=str(int(x[n-1])+(x[n]>='5'))
    return''.join(x[:n])

Explanation:
x=map(str,str(x))
Seperate each character of x. (e.x. when x=5.4, running this makes x equal to ['5', '.', '4'].
if n==0:x.remove('.')
A hack to get around Test Case 3, Round(-0.5, 0). Removes the decimal so we don't get the output -1.
n+=1+(n!=0)+(x[0]=='-')
if n<len(x):x[n-1]=str(int(x[n-1])+(x[n]>='5'))
1 compensates for the decimal point. I think.
(n!=0): Compensates for the removal of the decimal point and allows the next line to run.
(x[0]=='-'): Makes it so that in the next line, the negative sign (an additional character) will not mess up the calculation.
if n<len(x): Accounts for Test Case 2, Round(1.234, 5), because Python errors when you try to access the nth item of a list if it's not there. (x[5] is called in the test case, and x does not have a 6th term.)
x[n-1]=str(int(x[n-1])+(x[n]>='5')): Gets the n-1th item of x (which is a string, so it needs to be turned into a number), and adds 1 to it if the nth item of x is greater than or equal to 5. Then it gets turned back into a string.
return''.join(x[:n]): Returns the concatenation of everything up to the nth item in x.

if n==0:x.remove('.') / A hack to get around Test Case 3, Round(-0.5, 0). Removes the decimal so we don't get the output -1. But we do want -1 as the output for that test case.

In line 4, try replacing n[0]=='-' with x[0]=='-'

@Gaffi: That's -1., not -1

@Matt: Oops. I originally had my function as Round(a, b), but translated it for clarity.

@beary605 Ah, I see. The period is inside the formatted string. :-)

Python, 55 46 chars
R=lambda x,n:int(10**n*x+(.5,-.5)[x<0])/10.**n

Translates the decimal point, rounds half up using int(x+.5), then translates the decimal point back.  Negative numbers use int(x-.5).
Should be as accurate as a 64-bit IEEE can get (15+ decimal digits).  n can be up to about 300 or so (less if x is big).

It doesn't work when n=0. R(3.123,0) gives 3.0 instead of 3

I think this should fix the problem (56 chars): R=lambda x,n:int(10**n*x+(.5,-.5)[x<0])/(10.,10)[n<1]**n

@lortabac: I don't understand.  3.0 and 3 are the same number.

@lortabac: Thanks for the negative number idea.

Ok, I think you are right. There are no formatting requirements in the rules.


text:
Create an acrostic
Pretty fun and simple challenge here
given any input, create an acrostic poem for that input. you may use any word list of your choosing, and include any code you want to help "smarten" up your acrostic.
EXAMPLE

Every
Xylophone
Always
Makes
Powerfully
Low
Emissions

the winner will be the code chosen by most up-votes, please up-vote for creativity, problem solving in making the acrostics make sense, and humor.
most important of all, have fun!
(please test your program using the following 3 words, and any other word or 2 you want to add - laughable ; codegolf ; loremipsum)

add more details.  Should we be reading input from standard in? from the command line? or can this just be a function that takes something and returns something?  You might also linking "acrostic poem" to its wikipedia page because people are lazy.

You are going to get panned for your subjective winning criteria (I wonder how the admin's think contests like the IOCCC are judged...). I'd recommend you add some guidelines that people should use to judge on whether or not to give their upvotes or not.

"given any input"
"please up-vote for creativity, problem solving in making the acrostics make sense, and humor."

Nice word play: if you shuffle the letters of “acrostic”, you will get “costirca”, which is a possible spelling of my surname...

Python 2.7
import random
import string
import sys
import re

class Markov(object):
    def __init__(self,filename):
        with open(filename,'r') as f:
            self._words = f.read().split()
            self._wordCount = len(self._words)

    def getWordList(self,seedWord=None,pattern=r'^.*$'):
        if seedWord is not None:
            chainWords = [self._words[i+1] for i in range(self._wordCount-1)\
                if seedWord == self._words[i].lower()]
        else:
            chainWords = self._words
        p = re.compile(pattern,re.IGNORECASE)
        return filter(p.match,chainWords)

    def getRandWord(self,seedWord=None,pattern=r'^.*$'):
        wordList = self.getWordList(seedWord,pattern)
        if len(wordList) == 0:
            return None
        return random.choice(self.getWordList(seedWord,pattern))

def main():
    list = Markov('AStudyInScarlet.txt')
    for word in sys.argv[1:]:
        poem = []
        for letter in word:
            if len(poem) == 0:
                nextWord = list.getRandWord(pattern=r'^[{0}.*$]'.format(letter))
            else:
                nextWord = list.getRandWord(poem[-1],r'^{0}.*$'.format(letter))
                if nextWord is None:
                    nextWord = list.getRandWord(pattern=r'^{0}.*$'.format(letter))
            nextWord = ''.join(ch for ch in nextWord if ch not in string.punctuation)
            poem.append(nextWord)

        print word
        print '='*len(word)
        for line in poem:
            print line
        print ''

if __name__ == '__main__':
    main()

Loads a text file called 'AStudyInScarlet.txt'. Only words used  in that document will be candidates for incorporation into the final poem. (currently there are no words starting with x in this document, I will add some soon)
This program tries to find words in the text file that follow the previous word in the poem. For example, if the acrostic word is 'pita' and so far the poem is "Private," a possible next word is "inquiry" as the two word phrase "private inquiry" is found in the text document. If no matching word pairs are found, any random word starting with the right letter is chosen.
A word is chosen from a list of words that meet the desired qualifications. If a word shows up multiple times in the list of acceptable words, it is more likely to be chosen than one that does not.
Usage
Words to create poems from should be specified as command line arguments. One poem will be printed for each word specified on the command line.
Example:
$ acrostic.py laughable codegolf loremipsum
laughable
=========
Looking
a
Union
grievous
his
agitation
be
likely
enough

codegolf
========
couple
of
discoloured
evident
goes
or
late
from

loremipsum
==========
learn
of
revenge
engine
me
it
proved
smartest
up
my

Perhaps add a comma or period when you don't find a "good" word? I think it can make the poem feel more natural.

@ugoren Yeah, I was thinking about doing something like that. I'm not sure how much that would help, but it's probably better than nothing.

another idea might be to limit the individual word length to like 4 letters or something, not sure how it might affect it, but it could help?

PHP
<?php
$dict = array(
    'a' => 'and',
    'i' => 'if',
    'o' => 'or',
    'n' => 'not',
    'l' => 'list'
);
$funcs = get_defined_functions();
$word = rtrim(fgets(STDIN), "\n");
echo "\n";
foreach(str_split($word) as $char)
    foreach($dict + $funcs['internal'] as $func)
        if($func[0] == $char){
            echo $func . "\n";
            break;
        }

I admit it does not always make sense, but I am too lazy to look for a real word list, so I used PHP function names plus a couple of PHP reserved words.
Examples:
laughable

list
and
user_error
get_class
hash
and
bzopen
list
each

codegolf

class_exists
or
define
each
get_class
or
list
func_num_args

loremipsum

list
or
restore_error_handler
each
method_exists
if
property_exists
strlen
user_error
method_exists

neurotic

not
each
user_error
restore_error_handler
or
trigger_error
if
class_exists

diplomat

define
if
property_exists
list
or
method_exists
and
trigger_error


text:
Star programming!
The challenge
Write a program or function that prints stars! The program will receive two parameters by standar input: Size of the star and number of points of the star. A star can be any size between 0 and 10 and have 3, 4 or 5 points. The input parameters are separated by a comma, for example: 5,3 means a size 5 star with 3 points. The stars are composed by asterisks *
Consider the program will only receive valid inputs.
The prints must be correctly spaced so we can see pretty stars in the output!
Parameters explanations
Points
Is the number of arms counting from the central asterisk.
3 points stars:
       *
       *
       *
     *   *
    *     *

They are composed by a vertical arms and two diagonal arms. The separation between diagonal arms is 2*size-1
4 points stars
   *     *
    *   *
      *
    *   *
   *     *

They have the form of a X and composed by two diagonal lines. The separation between lines is 2*(size-1)+1
5 points stars
     *
     *
 * * * * *
    * *
   *   *

They are composed by a vertical line and a horizontal line. Each asterisk in the horizontal line is separated by one space. Also they have two diagonal lines, with a separation between themselves of 2*(size-2)+1
Size
Size is the number of asterisks that has each arm of the star counting from the central asterisk (inclusive).
Size 1 stars are composed by a single asterisk
*

Size 2 stars examples
3 points
       *
       *
     *   *

4 points stars
    *   *
      *
    *   *

5 points stars
     *
   * * *
    * *

You have examples of the size 3 stars in the Points parameter explanation.
Winning criteria
Shortest code wins. Code have to be checked with the following input parameters: 3,2 3,3 4,2 4,3 5,2 5,3
Bonus
-25% characters count for creating a size 6 pointed with the criteria explained before (6 arms and the size is the number of asterisks counting from the central asterisk). It can be any form you want while it respect the specifications. A example of a size 6 star with size 3:
      *
      *
  * * * * *
    * * *
   *  *  *

6 points stars must be checked with the following inputs 6,2 6,3.

In your first example of a (5,3) star, should the two horizontal points each be one asterisk longer?

"My God... It's full of stars"

That should be the question title!

Mathematica 80 76 67 chars
Some would question whether this is ASCII art, but I couldn't resist.
Graphics@Table[Text["*", r {Cos@t, Sin@t}], {t,0,2π,2π/#1}, {r,0,#2-1}]&

Usage (setting the font size at 24 to make the stars appear large.)
Graphics@Table[Text["*"~Style~24, r {Cos@t, Sin@t}], {t,0,2π,2π/#1}, {r,0,#2-1}] &[6,4]

Output for the following cases:
{{3, 2}, {3, 3}, {4, 2}, {4, 3},
{5, 2}, {5, 3}, {6, 2}, {6, 3},
{7, 4}, {8, 3}, {9, 2}, {12, 4}}

How it works
(a) The first star is at the origin of a coordinate space. Let's display it.
(b) Afterwards, we'll display a point at {1,0}.
(c) Then 5 points at once. We applied a pure function onto each pair of coordinates that follows it.
(d) Use Cos and Sin to determine the coordinates
(e) Coordinates work only on unit circle; 6 is the number of  light beams.
(f)  Draw radii from 0 to 4 unit.
options = Sequence[Axes -> True, ImageSize -> 225, BaseStyle -> 14];
a = Graphics[Text["*"~Style~{28, Blue}, {0, 0}], PlotLabel -> Style["a", 20], options];

b = Graphics[Text["*"~Style~{28, Blue}, {1, 0}], PlotLabel -> Style["b", 20], options];

c = Graphics[Text["*"~Style~{28, Blue}, {#1, #2}] & @@@ {{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}}, PlotLabel -> Style["c", 20], options];

d = Graphics[Text["*"~Style~{28, Blue}, {Cos@#, Sin@#}] & /@ {0, \[Pi]/3, 2 \[Pi]/3, \[Pi], 4 \[Pi]/3, 5 \[Pi]/3}, PlotLabel -> Style["d", 20], options];

e = Graphics@Table[Text["*"~Style~24, {Cos@t, Sin@t}], {t, 0, 2 \[Pi],  2 \[Pi]/#1}] &[6];

f = Graphics@Table[Text["*"~Style~24, r {Cos@t, Sin@t}], {t, 0, 2 \[Pi], 2 \[Pi]/#1}, {r, 0, #2 - 1}] &[6, 4];

GraphicsGrid[{{a, b, c}, {d, e, f}}, Dividers -> All]

+1 Very interesting!  Could you explain how this works?

Thank you for the explanation, it's starting to make more sense.  I just wish Mathematica wasn't so "locked down" and mostly for educational purposes.  Do you have any resources that link to a Mathematica IDE demo or examples beyond the ones that Wolfram provides?

Mathematica opened up considerably with its Computable Document Format, which allows for free distribution of applets for educational, non-commercial purposes. The source code to Mathematica is largely "locked down", however.  As for resources, you may want to look at http:/demonstrations.wolfram.com and also http://mathematica.stackexchange.com/questions/18/where-can-i-find-examples-of-good-mathematica-programming-practice

Ruby, ASCII, 193 score 142 (189 chars - 25 % bonus)
def s r,d
f=->a,n{[n*Math.sin(a),n*Math.cos(a)]}
s=d*6
p=[]
s.times{|k|p<<" "*s}
c=s/2
p[c][c]=?*
r.times{|a|d.times{|l|x,y=f[6.28/r*a,d*l]
p[c+x.round][c+y.round]=?*}}
p.map{|j|puts j}
end

Test it online
I think it qualifies for the 6-rays star bonus.
      *     *

       *  *

   *  *  *  *  *

        *  *

      *     *

     * *

    * * *

     * *

      *           *

        *       *

          *   *

*   *   *   *   *   *   *

          *   *

        *       *

      *           *

Mathematica, 65 64
My take on David's method:
f@p_=Graphics@Array[Text["*",{Cos@#,Sin@#}&[2π/p[[1]]#]#2]&,p,0]

Use:
f @ {6,4}

Errors are produced because of the use of = rather than :=, and it isn't the proper way to make a definition, but it does work here.
If one were allowed to use dots instead of asterisks this could be written (52 chars):
f@p_:=Most@ListPolarPlot@Array[{2π/p[[1]]#,#2}&,p,0]

f @ {6, 4}

I like the idea of using layers of pure functions.

@Averroes you should accept this answer.

use subs qw /N W E S NW NE SE SW Circler Printer/;
($size,$points)=split(/\,/,$ARGV[0]);
my $arrsize = $size>$points ? $size : $points;
for $my (0...2*$arrsize-2) {
    $starArray[$my]=();
}
if($size == 3) {
    @armlist=('N','SW','SE');
}
elsif($size == 4) {
    @armlist=('NE','NW','SW','SE');
}
elsif($size == 5) {
    @armlist=('E','N','W','SW','SE');
}
elsif($size == 6) {
    @armlist=('E','N','W','SW','S','SE');
}
elsif($size == 7) {
    @armlist=('E','N','W','SW','S','SE','NE');
}
elsif($size == 8) {
    @armlist=('E','N','W','SW','S','SE','NE','NW');
}
Circler;
Printer;
sub Circler{
    for (@armlist) {
        &{$_};
    }
}
sub Printer{
    for $my1 (0...2*$arrsize-2) {
        for $my2 (0...2*$arrsize-2) {
            print "$starArray[$my1]->[$my2]"."\t";
        }
        print "\n\n";
    }
}
sub N {
    for $my (0...$points-1) {
        $starArray[$arrsize-1-$my]->[$arrsize-1]="*";
    }
}
sub E {
    for $my (0...$points-1) {
        $starArray[$arrsize-1]->[$arrsize-1+$my]="*";
    }
}
sub W {
    for $my (0...$points-1) {
        $starArray[$arrsize-1]->[$arrsize-1-$my]="*";
    }
}
sub S {
    for $my (0...$points-1) {
        $starArray[$arrsize-1+$my]->[$arrsize-1]="*";
    }
}
sub NW {
    for $my (0...$points-1) {
        $starArray[$arrsize-1-$my]->[$arrsize-1-$my]="*";
    }
}
sub NE {
    for $my (0...$points-1) {
        $starArray[$arrsize-1-$my]->[$arrsize-1+$my]="*";
    }
}
sub SE {
    for $my (0...$points-1) {
        $starArray[$arrsize-1+$my]->[$arrsize-1+$my]="*";
    }
}
sub SW {
    for $my (0...$points-1) {
        $starArray[$arrsize-1+$my]->[$arrsize-1-$my]="*";
    }
}
__END__;

What is that? Perl?

Can't be, I've never seen perl code that long before