text:
Calculate n % 12
Calculate n modulo 12 for an unsigned 32 bit integer.
The Rules:

Must work for all n between 0 and 23. Other numbers optional.
Must only use any of the operators +-*, ~&^| or <<, >> as commonly defined on 32 bit uints.
May use arbitrary number of constant uints.
May not use any form of pointers, including arrays, or any if statements, including things that compile to if statements such as ternary operators or "greater than" operators.

The scoring:

Operators + - and the bitwise operators ~ & ^ | << >> (NOT, AND, XOR, OR, bit shifts) give a score of 1, * gives a score of 2.
Lowest total score wins.

You might want to define the operators for users of languages other than C/Java. I understand +-* are add, subtract, multiply; ~&^| are bitwise NOT,AND,XOR,OR; and << >> are bitshifts.

@steveverrill - thanks. That is indeed the intention.

Can I use for i in x:y:z, .dostuff?

Can I set a variable equal to a value to use in a expression?

@Ourous - not unless you want to count the for increments in the score.

@xnor - you can use any uint32.

most compilers will optimize n % 12 to a multiplication and a shift like in hacker's delight, so this is trivial, just output the assembly and see

Can I use -=?

Can I use multiple lines and the assignment operator?

@Ourous I doubt that it helps. a -= b can be replaced with a = a - b which has no higher a score by the questions scoring system.

@LưuVĩnhPhúc http://stackoverflow.com/questions/8021772/assembly-language-how-to-do-modulo Apparently, they just use a builtin.

@isaacg they'll do it with multiply and shift like this, this, this or this instead of simple divisions like that

Would be better to just say "may not use ternary or comparison operators", rather than assuming that they actually compile to conditional branch instructions in the underlying assembly.

What if my language uses * as the modulo operator?

This question's score is currently equal to the highest number supported by many answers.

4
(Language is irrelevant)
n-((48&(11-n))>>2)

Woo! Got to 4.
11-n will ensure all of the high order bits are set if and only if n>= 12.
48&(11-n) == if n>11 then 48 else 0
(48&(11-n))>>2 == if n>11 then 12 else 0
n-((48&(11-n))>>2) is the answer

Aww shucks, you beat me to this approach! I was only moments away from posting n - (((11 - n) & 0xC0000000) >> 28). Well done, I don't think it can be done in less than four.

@Runner112 Yeah, I was hoping no one would beat me to it as I posted it. Well done on finding it for yourself, though

Awesome :) 4 is indeed an accomplishment.

4
A solution with a lookup table (it looks up i ^ (i % 12)):
i ^ (0x1d4c000 >> (i & 0xfc) & 30)

4
Here's another solution with 4 operations:
i - ((0xffff >> (i - 12)) & 12)

It assumes that the count operand of bitshifts is implicitly taken mod 32, i.e. x >> -1 is the same as x >> 31.
5
Another approach, using a lookup table:
i - (16773120 >> i & 1) * 12

bash – 1
echo `seq 0 11` `seq 0 11` | awk '{print $(number+1)}'

e.g.
$ echo `seq 0 11` `seq 0 11` | awk '{print $(0+1)}'
0

$ echo `seq 0 11` `seq 0 11` | awk '{print $(11+1)}'
11

$ echo `seq 0 11` `seq 0 11` | awk '{print $(12+1)}'
0

$ echo `seq 0 11` `seq 0 11` | awk '{print $(23+1)}'
11

This isn't valid because it uses pointers.

@curiousdannii What pointers are you referring to? The stdin and stdout streams? Sure, internally, they are pointers, but then we might as well disqualify Java because it uses the Integer class internally for a lot of things.

Isn't $() effectively equivalent to a pointer?

@curiousdannii - awk documentation says they're built-in variables.

C, little-endian - 2
This is probably cheating but I think it satisfies the rules...
union {
    int i;
    struct {
        int a:4;
        int b:2;
        int c:10;
    } s;
    struct {
        int a:2;
        int b:14;
    } t;
} u;

u.i = 11-n;
u.s.a = 0;
u.s.c = 0;
result = n-u.t.b;

How does it work?

Sorta cheating, since you're using = 0  instead of & 0x0, which should count as an additional 2 operations. But +1 for the creativity :)

PHP - score 0
I wonder how is it possible that noone came with this before me!!!
$n = 18;
$s = str_repeat("a", $n);
$s2 = preg_replace('/aaaaaaaaaaaa/', '', $s);
echo strlen($s2);

Nice. I think there may be an issue though, since arrays are disallowed. Really nice though.

@AJMansfield One could argue this doesn't have arrays but strings (yes, at low level strings are byte arrays). :)

@seequ One could also argue that this invalid because of it's use of RAM (yes, at low level, ram is technically an indexed array) ¯_(ツ)_/¯

C, score 5
Works up to 23, not guaranteed above that.
( ((n+4)>>2)&4 ) + n & 15

((n+4)>>2)&4 returns 4 for n>=12. Add it to n and you get the right answer in the least significant 4 bits, then truncate the other bits.

Well done!! Now let's see if someone can get to 4..

whatever language: 5
not going to win, but participating because fun and maybe because it's easier to understand then others:
n - ((n+20)>>5)*12

this is equivalent to
n - (n>11)*12

this is equivalent because when you add 20 to 12, you get 32, thus the 5th bit becomes 1. This is only when n > 1 as 32 is the smallest number where the 5th bit becomes 1.
also note that is easily expandable for a higher range, as you can do
n - ((n+20)>>5)*12 - ((n+41)>>5)*12

to reach a range until 35

C - 6
(n - (((n * 0xAAAB) >> 19)) * 12 )

This should either be part of the question or just another answer. I suggest the latter.

@Jwosty - changed.

Python 2.x - 4
j=input();m=lambda a,b:a*b;a=(m(j,357913942)>>32);print j-m(12,a)

Is = an operator?
In that case the score is 6.
j-12*(j*357913942>>32)

BTW @steveverrill 's solution can be directly used in Python as well.
Works for the range 0 .. 23
So whats going on ? Multiply by 357913942 and divide by 2^32 (or right shift 32)

I like how you used a function to multiplicate only once. but imho you just renamed multiplication to the function m(,), which for me means you used it twice.

depends how the rules are interpreted, but you have a valid point

Kona - 5
Might be invalid because I'm not sure if the floor operator is allowed, but I've got two * and a minus:
mod:{x-(_0.08333*x)*12}

Which should work for any integer.

I'm not sure about the floor operation, but I'm definitely sure that the first multiplication is operating on something other than 32-bit integers.

@Runer112: OP says input must be 32 bit and operators are as defined they normally are with 32 bit uints; it says nothing about non-integer values in the code.

Unless I'm misunderstanding something, 0.08333*x doesn't seem like multiplication as defined on 32-bit uints, because 0.08333 is not a 32-bit uint.

@Runer112: Actually, the way I read it is that &|~ >> << are as defined with 32 bit uints (as it doesn't really make sense to do 1.0 << 3, does it?).

If you have to floor it, I know that, at least in JavaScript, n|0 is equivalent to a floor function

"May use arbitrary number of constant uints." - i.e. cannot use arbitrary floats.

@nbubis: that line does not actually put a restriction on floats.

Cobra - 2 (or 3)
def modulo12(n as uint32) as uint32
        for i in 11:n to int64:12,n-=12
        return n

This might be bending the rules a bit, but I've asked and was allowed to use this.
It also works for any number.


text:
Generate all possible integers
Input: you are given 2 integers, n and k. n is a positive (>= 1) integer, and k an integer, which is the number of times you are allowed to use n.
Output: output all of the non-negative integers that can be formed using at most k n's using these mathematical operations: +, -, *, /, and parentheses.
Edit: if your language supports removing elements from an array/set/etc., the requirement of non-negative integers is required. If not, then it is not required.
The only numerical value that can exist in the expression is n (however many times). If the value of the expression exceeds the maximum value of whatever data storage you have (such as int or long, etc.), you have to compensate for it (there is no maximum value that can be given for n).
Speed is not important, but shortest code wins!
Bonuses:

-50: include exponentiation in the list of mathematical operations. Exponentiation is defined to be that the base is some expression of n, not e = 2.71828...
-50: include the floor (or ceiling) functions if a given possible operation is not an integer.

Examples
> 2 2
0 1 4
> 4 3
3 4 5 12 20 64 ...

(Sample inputs/outputs do not necessarily include bonuses)

if "k is the maximum" then in example 1 you can use one 2 so 2 should be included in the output. 2. by exponentiation you mean raising to a power, not e^x? 3. if you want code-golf (shortest code) then the code-challenge tag is redundant.

@steveverrill: I concur on point 1, that needs to be clarified. I think most people call 2^x (or 2**x) as exponentiation, whereas exp(x) is the exponential. As per 3, that was part of an edit I was making, so that's removed now

I meant that the base must be some expression of n (and not e). The only numerical value that can exist in the expression is n.

Ryan, welcome to Programming Puzzles and Code Golf. Setting a well-specified challenge is difficult, so you always get a load of helpful comments. The idea is to make sure there is an unambiguous winner. This is a nice simple challenge. If you want to do a more complex one, you can use http://meta.codegolf.stackexchange.com/q/1596/15599 but I would also encourage you to take a look around and answer some questions, to get a feel of what we're about.

Wait, what if total score will be negative due to bonus?

@nicael Then the score is negative. That happens.

Is outputting only non-negative integers a hard requirement or is it okay if we also output negative results?

Related: Four fours, Obtaining target from given numbers

There is also the question of how we deal with operator precendence. For instance does 4 + 4 / 4 give 5 or 2? Is that up to us to decide?

@m.buettner I think we should use the common algebraic rules, the OP speaks of parenthese too

@edc65 oh damn, the parentheses actually complicate things a lot

@m.buettner It is a hard requirement if your language supports modifying arrays/sets/etc. (since removing negative elements from an array isn't that hard to do). If your language does not support that, then it is not a hard requirement.

Should be better not changing the rules during the challenge

@m.buettner I don't know Mathematica, but I wouldn't be surprised if it has an operator for non-precedented string evaluation, which is basically equal to parentheses

@Ryan There are still a few things that are unclear. For instance, do we need to use exactly k instances of n or at most? You've written the latter, but using one 2 I can produce 2 (which is not in your list) and using two 4s I can produce 0 (which is not in your list). Furthermore, my last question still stands: if we're to support parentheses, why is 2 not in your list for 4 3? And if not, which operator precendence should we use? Currently the submissions generate vastly different results because of different interpretations of these questions.

Javascript (E6) 215 (315 - 2*50 bonus) 252
Edit Simplified. Correct bug of 0 missing
Defined as a function, then counting 10 more byte for output using alert()
Important Really this one is not valid according to the rules, because javascript can not handle big numbers. For instance with parameters 2,5 it can't find 2^2^2^2^2 (ie 2^65536). A number this big is 'Infinity' in javascript.
Golfed
F=(n,k,g={})=>{k+=k-1;for (l=i=1;x=i.toString(6),l+=!!x[l],l<k;i++)if(x.split(0).length*2==l+1){for(s=[n,n],p=l;o=x[--p];)
if(-o)b=s.pop(),a=s.pop(),s.push(o<2?a+b:o<3?a-b:o<4?a*b:o<5?a/b:Math.pow(a,b));else s.push(x[p]=n);
r=Math.floor(s.pop());r>=0&isFinite(r)&!isNaN(r)&!g[r]&&(g[r]=x)}return Object.keys(g)};

To be golfed. I have an idea I want to share: use a postfix notation. In postfix any type of expression is made just of values and operators - no parentheses needed.
The postfix notation can be translated to usual algebraic infix notation - but that's out of scope in this challenge.
Usage
alert(F(4,3))

Output 1,2,3,4,5,8,12,16,20,32,64,252,256,260,1024,4096,65536,4294967296,1.3407807929942597e+154
Ungolfed
F=(n, k, g={})=>{
  k += k - 1;
  // Count in base 6 - '0' means Value, '1'..'5' means operators
  // A valid expression starts with Value twice, then n operators intermixed with n-1 Values
  // x: Coded expression, l: Expression length, k Expression limit length from param
  for (l = i = 1; x = i.toString(6), l += !!x[l], l<k; i++)
    if (x.split(0).length*2 == l+1) // check balancing values/operators
    {
      for (s = [n,n], p = l; o = x[--p];) // Calc stack starts with N,N
        if (-o) // If not '0'
          b=s.pop(),a=s.pop(), // Do calc
          s.push(o<2 ? a+b : o<3 ? a-b : o<4 ? a*b : o<5 ? a/b : Math.pow(a,b))
        else // Push value
          s.push(n) //
      r = Math.floor(s.pop()); // Last result in stack
      r >= 0 & isFinite(r) & !isNaN(r) & !g[r] && (g[r]=x) // Put in hashtable avoiding duplicates
    }
  // Uncomment this to see the postfix expression list
  // for (i in g) console.log(i, [n,n,...[...g[i]].reverse().map(v=>v>0?'x+-*/^'[v]:n)])
  return Object.keys(g) // Retust list of hashtable keys
}

First version this is more complicated but maybe easier to follow
Display the postfix expression for each number
F=(n,k)=> {
  var i,l,s;
  var cmd;
  var op='n+-*/^'
  var bag = {}
  function Calc(val,pos,stack)
  {
    while (c = cmd[pos])
    {
        if (c == 0)
        {
            stack.push(n);
            cmd[pos] = n
            pos++
        }
        else
        {
            var b=stack.pop(), a=stack.pop();
            stack.push(c < 2 ? a+b : c < 3 ? a-b : c < 4 ? a*b : c < 5 ? a/b
               : Math.pow(a,b))
            cmd[pos]=op[c]
            pos++
        }
    }
    var res = Math.floor(stack.pop())
    if (res > 0 && isFinite(res) && !isNaN(res) && !bag[res])
    {
       bag[res] = cmd
    }
  }
  k=k+k-3;
  for (i=1;s=i.toString(6), !s[k]; i++)
  {
       l=s.split(0).length;
       if (l+l-1==s.length)
       {
          var cmd = (s+'00').split('').reverse()
          Calc(n, 0, [], cmd.map(c=>op[c]).join(' '))
       }
  }

  for (i in  bag)
  {
    console.log(bag[i],'=', i)
  }
}

Usage
F(4,3)

Output
[4, 4, "/"] = 1
[4, 4, "+", 4, "/"] = 2
[4, 4, 4, "/", "-"] = 3
[4, 4, "-", 4, "+"] = 4
[4, 4, "/", 4, "+"] = 5
[4, 4, "+"] = 8
[4, 4, "+", 4, "+"] = 12
[4, 4, "*"] = 16
[4, 4, "*", 4, "+"] = 20
[4, 4, "+", 4, "*"] = 32
[4, 4, "*", 4, "*"] = 64
[4, 4, "^", 4, "-"] = 252
[4, 4, "^"] = 256
[4, 4, "^", 4, "+"] = 260
[4, 4, "^", 4, "*"] = 1024
[4, 4, "+", 4, "^"] = 4096
[4, 4, "*", 4, "^"] = 65536
[4, 4, "^", 4, "^"] = 4294967296
[4, 4, 4, "^", "^"] = 1.3407807929942597e+154

It's ES6, not E6.

Python 2, 249 characters - 50 bonus = 199
from operator import*
n,k=input()
def g(a):
 if len(a)==1:yield a[0]
 else:
  for i in range(1,len(a)):
   for l in g(a[:i]):
    for r in g(a[i:]):
     for o in[add,sub,mul,pow]:
      yield o(l,r)
     if r:yield l/r
print set(map(abs,g([n]*k)))

Sample runs:
2,2
set([0, 1, 4])
4,3
set([32, 65536, 2, 3, 4, 5, 0, 1, 64, 252, 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096L, 12, 1024, 4096, 20, 4294967296L, -252, -12, -4, -3, 260])

This claims the exponentiation bonus of -50 points. Allowing exponentiation can give some staggeringly large results for small inputs (remove pow from the list of operators to try without exponentiation).

I think we're supposed to output only non-negative integers.

See the edit above on non-negative integers.

Now, you have 0 and I miss it (my fault). But you miss 8 and 16 and in general the combinations of less then 3 numbers

I think you can mitigate 8 and 16 (and others) by doing a for loop on i=1 to range(k+1) and union all of set(g([n]*i)) or something like that.

The question says "k an integer, which is the number of times you are allowed to use n" so I'm going to stick with that. If you wish to clarify the question, please do so before solutions have been posted.

Mathematica, 105 bytes - 100 bonus = 5
Note: This does not currently support parentheses. Fixing once the OP clarifies the challenge.
If negative integers are okay, too, this scores 1 instead.
f[n_,k_]:=Union@Abs@Floor@ToExpression[ToString@n&~Array~k~Riffle~#<>""&/@Tuples[Characters@"*+/-^",k-1]]

Somewhat ungolfed:
f[n_, k_] :=
 Union@Abs@Floor@
    ToExpression[
     ToString@n &~Array~k~Riffle~# <> "" & /@
      Tuples[Characters@"*+/-^", k - 1]
     ]

I'm claiming both bonuses for including exponentiation and flooring non-integer results.
Examples:
f[2, 2]
f[4, 3]

Out[1] = {0, 1, 4}
Out[2] = {0, 3, 4, 5, 12, 20, 64, 252, 260, 1024, 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096}

Python 2.x: 32 (132-(50+50))
from itertools import*
l=list("+-*/")+["**"]
f=lambda n,k:{abs(eval(j)) for j in(`k`+`k`.join(i)+`k`for i in product(l,repeat=n-1))}

I'll claim both bonuses: x/y behaves like you would expect floor(x/y) to behave, and it does support powers.
Demo:
from itertools import*
l=list("+-*/")+["**"]
f=lambda n,k:{abs(eval(j)) for j in(`k`+`k`.join(i)+`k`for i in product(l,repeat=n-2))}

f(2,2)
Out[2]: {0, 1, 2, 3, 6, 8, 16}

f(2,3)
Out[3]: {0, 2, 3, 4, 6, 9, 12, 24, 27, 30, 81, 7625597484987L}

f(3,2)
Out[4]: {0, 1, 2, 3, 4, 5, 6, 8, 10, 14, 16, 18, 32, 65536}

f(4,2)
Out[5]:
{0,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 12,
 14,
 15,
 16,
 17,
 18,
 20,
 30,
 32,
 34,
 64,
 32768,
 65534,
 65538,
 131072,
 [encoded data, 19730 characters]}

Whoops, my mistake... Should be fixed now.

+1 The abs is clever, I think I'm stealing that as reward for pointing out the mistake ;)

@m.buettner Go right ahead :)

How do you get the long number for the 4,3 case though? 4^4^4 starts with 13407....

@m.buettner 2**2**2**2**2, because I had one repeat too many. f(5,2) should still give that answer.

Ohhh, you've got n and k the other way round, I didn't look at the code properly.

@m.buettner You know, alphabetical order and all that ;)

And I only just noticed we're supposed to support parentheses, too.

@m.buettner That's going to lengthen things...

Can you fix the values in the demo? I don't undertstand that last huge number ... uh ok 2^65536

Haskell, 35
I'm not sure whether a function is enough or an actual program is required, so I'm posting two versions, both with 100 bonus.
As a program, score of 80:
import Data.List
d x=[flip x,x]
n#1=[n]
n#k=[(+),(-),(*),(/),(**)]>>=d>>=($n#(k-1)).map.($n)
g[n,k]=filter(>0)$[1..read k::Int]>>=map floor.(read n#)
main=interact$show.nub.g.words

or as a function, score of 35:
import Data.List
d x=[flip x,x]
n#1=[n]
n#k=[(+),(-),(*),(/),(**)]>>=d>>=($n#(k-1)).map.($n)
n%k=nub.filter(>0)$[1..k]>>=map floor.(n#)

sample output, for (4%3) or echo 4 3|codegolf.exe, sorted for your conveneince:
[1,2,3,4,5,8,12,16,20,32,64,252,256,260,1024,4096,65536,4294967296,13407807929942597099574024998205846127479365820592393
377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096,17976931348623159
077293051907890247336179769789423065727343008115773267580550096313270847732240753602112011387987139335765878976881441662
249284743063947412437776789342486548527630221960124609411945308295208500576883815068234246288147391311054082723716335051
0684586298239947245938479716304835356329624224137216]

The only thing that is a little weird about this is that the floating-point number Infinity floors to a humongous integer, but I hope this doesn't matter too much.

J: -23 (77-50*2)
This doesn't work for n<=2 yet, not sure why. I'll look into fixing this, but if anyone knows an anwer, please say so in the comments.
~.>.|"."1 k,~"1 k,"1((,~(,&k=:'x',~":k))~)/"1((5^n),n)$;{;/(n=:n-1)#,:'*%+-^'

J, -43 (53-2*50)
[:~.[:<.[:|[:;(#~&x:)4 :'y/x'L:1[:([:{(<<"0'-+%*^')#~<:)]

This doesn't always work, because J tries to prevent calculations with numbers that are too large. If we are allowed to use (machine) floats, which simply get set to infinity on an overflow, we get the following, slightly shorter, for a score of 52-100 = -48:
[:~.[:<.[:|[:;#~4 :'y/x'L:1[:([:{(<<"0'-+%*^')#~<:)]

This is a version not in any way shape or from inspired by my previous J answer, so I'm posting it as a separate answer. Trivia: this might be the first time I've had to use an explicit function in a J answer.
Usage (Yes, the little boxes are actual data structures in J, and are actually displayed like this.):
   f =: [:~.[:<.[:|[:;(#~&x:)4 :'y/x'L:1[:([:{(<<"0'-+%*^')#~<:)]
   g =: [:~.[:<.[:|[:;#~4 :'y/x'L:1[:([:{(<<"0'-+%*^')#~<:)]
   test =: (/:~ L: 0) @: (g ; f) f. NB. Make a list of the result of both functions, and sort the answers.

   5!:4 <'f'
  ┌─ [:
  ├─ ~.
  │    ┌─ [:
──┤    ├─ <.
  │    │    ┌─ [:
  └────┤    ├─ |
       │    │    ┌─ [:
       └────┤    ├─ ;
            │    │           ┌─ ~ ─── #
            │    │    ┌─ & ──┴─ x:
            └────┤    │            ┌─ 4
                 │    │      ┌─ : ─┴─ ,:'y/x'
                 │    ├─ L: ─┴─ 1
                 └────┤
                      │      ┌─ [:
                      │      │     ┌─ [:
                      │      │     ├─ {
                      └──────┼─────┤         ┌─ <'-';'+';'%';'*';'^'
                             │     └─────────┼─ ~ ──────────────────── #
                             │               └─ <:
                             └─ ]

   2 test 2
┌─────┬─────┐
│0 1 4│0 1 4│
└─────┴─────┘
   4 test 3
┌────────────────────────────────────────────────────────────────┬──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────...
│0 1 3 4 5 12 20 32 64 252 260 1024 65536 4.29497e9 1.34078e154 _│0 1 3 4 5 12 20 32 64 252 260 1024 65536 4294967296 134078079299425970995740249982058461274793658205923933777235614437217640300735469768018742981669034276900318581864860508537538828119465699...
└────────────────────────────────────────────────────────────────┴──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────...

   /:~ 4 g 4 NB. _ is infinity in J.
0 1 2 3 4 5 7 8 9 12 16 20 24 28 36 48 60 64 68 80 128 248 256 264 1008 1020 1024 1028 1040 4096 65532 65540 262144 1.67772e7 4.29497e9 4.29497e9 1.71799e10 1.09951e12 1.84467e19 3.40282e38 1.34078e154 5.36312e154 3.4324e156 _
   4 f 4
|limit error
|       y/x

Python 2 - 212 bytes (262-50)
Second ever code golf!
a,c,j=raw_input(),['+','-','*','/','**'],set()
def e(f):
    for g in c:
        h=f.replace('.',g,1)
        if '.' in h:e(h)
        else:
            i=eval(h)
            if i>=0:j.add(i)
for d in range(1,input()+1):e(((a+'.')*d)[:d*2-1])
print(j)

EDIT: Ok with brackets is gets a little larger:
With brackets - 354 bytes (404-50)
a,c,j=raw_input(),['+','-','*','/','**','+(','-(','*(','/(','**(',')+',')-',')*',')/',')**',')+(',')-(',')*(',')/(',')**(','(',')'],set()
def e(f):
    for g in c:
        h=f.replace('.',g,1)
        if '.' in h:e(h)
        else:
            try:
                i=eval(h)
                if i>=0:j.add(i)
            except:pass
for d in range(1,input()+1):e(((a+'.')*d)[:d*2-1])
print(j)

Haskell - 235 bytes - 100 bonus = 135
import Control.Monad
import Data.List (nub,sort)
r(l:h:_)=filter(>=0)$sort$nub$map(floor.foldr(\op m->n`op`m)n)$replicateM(k-1)[(+),(-),(*),(/),(**)]
 where n=fromIntegral l;k=fromIntegral h
main=interact(\s->show$r$map read$words s)

Tested with
$ printf "4 3" | ./pi
[0,1,3,4,5,12,20,32,64,260,1024,65536,4294967296,13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096,179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216]

This result is achieved using replicateM. If we use the input 4 3, replicateM will give us the following arrays of functions : [[(+),(+)],[(+),(-)],[(+),(*)],[(+),(/)],[(+),(**)],[(-),(+)],[(-),(-)],[(-),(*)],[(-),(/)],[(-),(**)],[(*),(+)],[(*),(-)],[(*),(*)],[(*),(/)],[(*),(**)],[(/),(+)],[(/),(-)],[(/),(*)],[(/),(/)],[(/),(**)],[(**),(+)],[(**),(-)],[(**),(*)],[(**),(/)],[(**),(**)]], or more simply, [[a->a->a]]. Each array is then folded from the right using n as input : [(+),(+)] = 4+(4+4) = 12. Note that there is no operator precedence here : [(*),(+)] = 4*(4+4) != (4*4)+4.
The given numbers are then floored, nubed, sorted and filtered for numbers less than 0.

If you have no operator precedence, how come 2 is missing? (like (4+4)/4)

C, dc & bash utils – 259 (source) + 21 (to run) - 100 bonuses = 180
Save as calc.c:
#include <stdio.h>
#define X printf
int main(int c,char*v[]){int n,k,l,t,i,j;char*O="+-*/^";if(c!=3)return 0;n=atoi(v[1]);k=atoi(v[2]);for(l=1,t=k;t>1;t--)l*=5;for(i=0;i<l;i++){t=i;X("%d ",n);for(j=1;j<k;j++){X("%d%c",n,O[t%5]);t/=5;}X("d*vp\n");}return 1;}

Compile:
gcc -o calc calc.c

This will output permutations of dc compatible input. dc is a unlimited precision calculator, so can generate large numbers, it also has exponentiation. dc in default mode uses integer arithmetic so that's floor builtin, and the common commands d*v near the end effectively take the absolute value to increase the number of possible valid outputs.
Running alone just generates a lot of output, e.g.
$ ./calc 6 2
6 6+d*vp
6 6-d*vp
6 6*d*vp
6 6/d*vp
6 6^d*vp

So to get the results, tie this into dc | sort -n | uniq | xargs to get the desired output, e.g.
$ ./calc 2 2 |dc|sort -n|uniq|xargs
0 1 4

$ ./calc 2 3 |dc|sort -n|uniq|xargs
0 1 2 3 6 8 16

$ ./calc 2 4 |dc|sort -n|uniq|xargs
0 1 2 3 4 5 6 8 9 10 12 14 16 18 32 36 64 256

$ ./calc 3 3 |dc|sort -n|uniq|xargs
0 1 2 3 4 6 9 12 18 24 27 30 81 216 729 19683

The highest k it can handle is 13, but then you'll be waiting a long time for the results!
$ ./calc 2 8 |dc|sort -n|uniq|xargs
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 87 88 92 94 95 96 97 98 99 100 101 102 104 106 108 110 112 114 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 136 138 140 142 143 144 145 146 148 150 152 154 156 158 159 160 161 162 163 164 165 166 167 168 169 170 171 180 190 192 194 195 196 197 198 199 200 201 202 204 206 208 223 224 225 227 238 240 242 244 246 248 250 252 253 254 255 256 257 258 259 260 262 264 266 268 272 280 282 284 286 287 288 289 290 291 292 294 296 304 310 311 312 313 314 316 318 320 322 323 324 325 326 328 330 332 338 359 361 363 364 384 386 388 390 391 392 393 394 396 398 400 402 404 408 441 448 449 450 451 452 480 482 484 486 496 500 502 504 506 508 509 510 511 512 513 514 515 516 518 520 522 524 527 528 529 531 544 568 572 574 576 577 578 579 580 584 621 623 624 625 627 629 640 642 644 645 646 647 648 649 650 651 652 654 656 674 676 678 720 721 722 723 724 727 729 731 776 780 782 784 786 788 792 796 798 800 802 804 841 896 898 900 902 904 959 961 963 968 1008 1012 1014 1016 1018 1020 1022 1023 1024 1025 1026 1028 1030 1032 1034 1036 1040 1058 1087 1089 1091 1148 1150 1152 1154 1156 1158 1160 1200 1225 1246 1248 1250 1252 1254 1288 1290 1292 1294 1295 1296 1297 1298 1300 1302 1304 1352 1369 1440 1442 1444 1446 1448 1458 1521 1564 1566 1568 1570 1572 1598 1600 1602 1640 1681 1764 1796 1798 1800 1802 1804 1920 1921 1922 1923 1924 1936 2032 2040 2042 2044 2045 2046 2047 2048 2049 2050 2051 2052 2054 2056 2064 2116 2176 2177 2178 2179 2180 2209 2302 2304 2306 2308 2310 2312 2314 2316 2399 2401 2403 2450 2498 2500 2502 2584 2586 2588 2590 2591 2592 2593 2594 2596 2598 2600 2601 2704 2738 2884 2886 2888 2890 2892 2916 3120 3134 3136 3138 3200 3278 3279 3280 3281 3282 3364 3444 3598 3600 3602 3840 3842 3844 3846 3848 3969 4088 4090 4092 4094 4095 4096 4097 4098 4100 4102 4104 4225 4352 4354 4356 4358 4360 4608 4622 4624 4626 4802 4898 4900 4902 4998 4999 5000 5001 5002 5041 5176 5180 5182 5184 5186 5188 5192 5202 5329 5474 5476 5478 5774 5776 5778 5929 6084 6239 6241 6243 6272 6400 6557 6559 6560 6561 6563 6565 6887 6889 6891 7200 7225 7320 7684 7686 7688 7690 7692 7938 8064 8184 8186 8188 8190 8191 8192 8193 8194 8196 8198 8200 8320 8450 8708 8710 8712 8714 8716 9216 9248 9409 9602 9604 9606 9800 9801 9996 9998 10000 10002 10004 10082 10364 10366 10367 10368 10369 10370 10372 10402 10404 10406 10658 10816 10952 11552 12482 12544 13118 13120 13122 13124 13126 13778 14161 14400 14639 14641 14643 14884 15129 15374 15376 15378 15625 15874 15876 15878 16127 16129 16131 16376 16380 16382 16383 16384 16385 16386 16388 16392 16639 16641 16643 16898 16900 16902 17161 17422 17424 17426 17956 18496 18818 19206 19207 19208 19209 19210 19600 19602 19996 19998 20000 20002 20004 20162 20164 20166 20732 20734 20736 20738 20740 20808 21314 21316 21318 21904 23104 24964 25600 25921 26242 26244 26246 26569 26896 27556 28561 29282 30752 31752 32256 32257 32258 32259 32260 32764 32765 32766 32767 32768 32769 32770 32771 32772 33280 33281 33282 33283 33284 33800 34848 36864 37634 37636 37638 38412 38414 38416 38418 38420 39202 39204 39206 39998 40000 40002 40328 40804 41468 41470 41472 41474 41476 41616 42632 50625 51842 52486 52487 52488 52489 52490 53138 58564 61504 62500 63502 63504 63506 64512 64514 64516 64518 64520 65025 65530 65532 65534 65535 65536 65537 65538 65540 65542 66049 66560 66562 66564 66566 66568 67598 67600 67602 68644 69696 75272 76828 76830 76832 76834 76836 78408 80000 80656 81796 82942 82944 82946 83521 84100 85264 97344 102400 103682 103684 103686 104972 104974 104976 104978 104980 106274 106276 106278 107584 127008 129028 129030 129032 129034 129036 130050 130321 131064 131066 131068 131070 131071 131072 131073 131074 131076 131078 131080 132098 133124 133126 133128 133130 133132 135200 150544 152100 153662 153664 153666 155236 156816 158404 159998 160000 160002 161604 165888 195312 202500 207368 209948 209950 209952 209954 209956 212552 234256 254016 256036 258062 258064 258066 260098 260100 260102 261121 262136 262140 262142 262144 262146 262148 262152 263169 264194 264196 264198 266254 266256 266258 268324 270400 279841 307328 320000 329476 331774 331776 331778 334084 388129 390623 390625 390627 393129 405000 414736 417316 418609 419902 419904 419906 421201 422500 425104 456976 516128 520200 521284 522242 524284 524286 524287 524288 524289 524290 524292 526338 528392 531441 532512 611524 614654 614656 614658 617796 640000 663552 668168 781250 806404 809998 810000 810002 813604 837218 839806 839807 839808 839809 839810 842402 923521 1032256 1040400 1042568 1044482 1044484 1044486 1048572 1048574 1048576 1048578 1048580 1052674 1052676 1052678 1056784 1065024 1185921 1229312 1327104 1331716 1336334 1336336 1336338 1340964 1562500 1620000 1669264 1674434 1674436 1674438 1679612 1679614 1679616 1679618 1679620 1684802 1684804 1684806 1690000 2079364 2085134 2085136 2085138 2088968 2090916 2097148 2097150 2097152 2097154 2097156 2105352 2458624 2560000 2672672 3240000 3348872 3359228 3359230 3359232 3359234 3359236 3369608 3694084 4170272 4177936 4186116 4190209 4194302 4194304 4194306 4198401 4202500 4210704 4743684 5308416 5345344 5764801 6250000 6697744 6708100 6718462 6718464 6718466 6728836 6739216 7388168 8340544 8380418 8388606 8388607 8388608 8388609 8388610 8396802 9487368 9834496 10758400 12960000 13436928 14760964 14776334 14776336 14776338 14791716 16744464 16760834 16760836 16760838 16777212 16777214 16777216 16777218 16777220 16793602 16793604 16793606 16810000 18957316 18974734 18974736 18974738 18992164 21381376 21523360 24010000 25000000 26853124 26873854 26873856 26873858 26894596 29552672 29986576 33362176 33521672 33554428 33554430 33554432 33554434 33554436 33587208 37949472 38950081 43020481 43046719 43046721 43046723 43072969 47458321 50000000 53747712 59105344 67043344 67076100 67108862 67108864 67108866 67141636 67174416 75898944 86093442 92236816 99960004 99999998 100000000 100000002 100040004 107495424 108243216 134217728 172186884 200000000 214358881 214990848 236421376 252047376 260144641 268369924 268435454 268435456 268435458 268500996 276922881 285610000 303595776 368947264 400000000 406586896 429898756 429981694 429981696 429981698 430064644 454371856 536870912 688747536 737894528 859963392 1040578564 1073610756 1073676289 1073741822 1073741824 1073741826 1073807361 1073872900 1107691524 1416468496 1475635396 1475789054 1475789056 1475789058 1475942724 1536953616 1600000000 1719926784 2081157128 2147352578 2147483646 2147483647 2147483648 2147483649 2147483650 2147614722 2215383048 2754990144 2951578112 4032758016 4162056196 4162314254 4162314256 4162314258 4162572324 4294443024 4294705154 4294705156 4294705158 4294967292 4294967294 4294967296 4294967298 4294967300 4295229442 4295229444 4295229446 4295491600 4430499844 4430766094 4430766096 4430766098 4431032356 4569760000 5509980288 5903156224 6879707136 8324628512 8589410312 8589934588 8589934590 8589934592 8589934594 8589934596 8590458888 8861532192 10750371856 11019540676 11019960574 11019960576 11019960578 11020380484 11294588176 16649257024 17178820624 17179344900 17179869182 17179869184 17179869186 17180393476 17180917776 17723064384 22039921152 23612624896 25600000000 34359738368 44079842304 66597028096 67652010000 68718428164 68719476734 68719476736 68719476738 68720525316 69799526416 70892257536 110075314176 137438953472 152587890625 176319369216 274877906944 377801998336 549755813888 656100000000 705277476864 1090946826256 1099507433476 1099511627774 1099511627776 1099511627778 1099515822084 1108126760976 1410554953728 1785793904896 2199023255552 2803735918096 2821103188996 2821109907454 2821109907456 2821109907458 2821116625924 2838564518416 4347792138496 4398046511104 5642219814912 11284439629824 17592186044416 45137758519296 70368744177664 140737488355328 218340105584896 280925623418896 281474909601796 281474976710654 281474976710656 281474976710658 281475043819524 282025135308816 360040606269696 562949953421312 722204136308736 1125899906842624 1853020188851841 4503599627370496 10000000000000000 72057594037927936 184884258895036416 1152921504606846976 2177953337809371136 4611686018427387904 9223372036854775808 17324859965700833536 18444492376972984336 18446744056529682436 18446744073709551614 18446744073709551616 18446744073709551618 18446744090889420804 18448995976604549136 19631688197463081216 36893488147419103232 73786976294838206464 121439531096594251776 295147905179352825856 4722366482869645213696 1208925819614629174706176 7958661109946400884391936 79228162514264337593543950336 340282366920938463463374607431768211456

Right now, it follows a strict # # op # op # op ... pattern, but you can get more numbers by switching the pattern around, e.g.:
(2 * 2 * 2) / (2 + 2) → 2 2 * 2 * 2 2 + /

The way this could be done is to treat the numbers and operators as symbols and permute them alike. You would get a lot of sequences not legal in dc, but let dc figure that out. Results pending...

A suggestion: try the method in my answer. I generate valid permutation of 6 symbols (n+-*/^) counting in base 6, dropping if the number of N is not balanced with other symbols.

HASKELL 98 (198-100 bonus)
edit: I'd comment, but I can't, I'd suggest to treat unlimited range as a bonus
It seems to me that a few answer miss a point: using at most k n.
This means that f(4,3) can generate (4/4) = 1 or (4*4)=16.
Anyway that's my answer.
I assume int/int to behave as floor. Exponentiation is included.
import Data.List
f=[(+),(-),div,(*),(^)]
a y f=f y
o n x=filter(>0).map(a n.a x)$f++map flip f
t[n,k]=(0:).nub.concat.take(fromInteger k)$iterate(>>=o n)[n]
main=interact$show.sort.t.map read.words

HASKELL 111 (211-100 bonus)
import Data.List
f=[(+),(-),div,(*),(^)]
c=concatMap
a y f=f y
o n x=map(a n.a x)$f++map flip f
l 1 _ s=0:s
l k o s=c(l(k-1)o.filter(>0))[c o s,s]
t[n,k]=l k(o n)[n]
main=interact$show.sort.nub.t.map read.words

Haksell is fun. Also, welcome to PPCG.SE! I would recommend adding <!-- language: lang-haskell --> two lines before the code for syntax highlighting.

To me, it seems that the OP himself is missing that point (if you look at his examples).

Or just add <!-- language-all: lang-haskell --> somewhere before the first code block, a trick I learned some days ago.

Ruby 181 - 50 - 50 = 81
def p(k,n);k<=1?[n]:(1...k).reduce([]){|a,s|a+[:+,:-,:*,:/,:**].reduce([]){|a,o|b=p(s,n);b+a+b.product(p(k-s,n)).map{|a|a.reduce(&o) rescue nil}.compact}}.uniq.find_all{|k|k>=0};end

source: Stack Exchange

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

sort: votes


text:
It's not who votes that counts; it's who counts the votes
The scenario
You live in a country that is having a presidential election.  Each voter gets one vote, and therefore there is a firmly-entrenched two-party system.  (Third parties exist, but get hardly any votes).
The latest opinion poll shows the race in a dead heat:

49%: Alberto Arbusto
49%: Jorge Sangre
2%: various minor candidates

The program requirements
You have been hired by the government to write part of the vote counting software.  You will be given, on standard input, an unordered list of one precinct’s votes, one per line, like this:
Alberto Arbusto
Jorge Sangre
Jorge Sangre
Alberto Arbusto
Jorge Sangre
Alberto Arbusto
Alberto Arbusto
Jorge Sangre
Juan Perez
Jorge Sangre
Alberto Arbusto
Alberto Arbusto
…

and, after it has read all the votes, outputs a summary of how many votes each candidate got, sorted in descending order by number of votes, like this:
492 Jorge Sangre
484 Alberto Arbusto
 18 Juan Perez
  6 Mickey Mouse

The underhanded part
You're a partisan hack who wants to steal the election for one of the two main candidates (you can choose which one).  So, your program must deliberately print incorrect vote counts, with a systematic bias towards your favorite candidate.
Of course, you must do this is such a way that a person looking at your code or its output would likely not recognize the incorrect behavior.

How about let the person running the program choose who he/she wants to bias to? This 1: makes the challenge less broad (a good thing), 2: makes the answers more interesting (IMO)

...you can choose which one... Can I choose the one whose name is the first?

@user80551: You mean the first in the file?  Yeah, I suppose that could work, with a concerted effort to tell members of your party "Make sure you're the first in line at the voting booth."

@dan04 I think user80551 really talks about the one ACTUALLY winning xD

By "biased" you mean that the candidate we prefer must be elected, or thar the program will simply output and higher number of votes for him than the one actually contained in the input file?

It might be difficult to justify a long program in Bash, given that a non-underhanded program to count votes in this format would literally just be sort|uniq -c...

not quite actually, probably sort|uniq -c|sort -gr

@Alessandro: It simply needs to output a higher number of votes for him (and/or a lower number of votes for his opponent) than what's actually in the input.  The election is assumed to be close enough that a small error could swing it.

Can you put a file of names so that we're working with the same data?

does the sum of the counted votes must match the real number of total votes?

@bolov: It doesn't need to match exactly, but it should be close enough to not be obviously wrong.

I'm voting to close this question as off-topic because underhanded challenges are no longer on-topic on this site. http://meta.codegolf.stackexchange.com/a/8326/20469

Scala
Long live Alberto Arbusto!
import scala.io.Source
import java.util.concurrent.atomic.LongAdder

object Votes extends App {
  val votes = Source.stdin.getLines.toIndexedSeq
  val registeredCandidates = Seq(
    "Alberto Arbusto",
    "Juan Perez",
    "Mickey Mouse",
    "Jorge Sangre"
  )

  val summaries = registeredCandidates map (Summary.apply(_, new LongAdder))

  var currentCandidate: String = _

  for (vote <- votes.par) {
    currentCandidate = vote
    summaries.find(s => s.candidate == currentCandidate).map(_.total.increment)
  }

  for (summary <- summaries.sortBy(-_.total.longValue)) {
    println(summary)
  }
}

case class Summary(candidate: String, total: LongAdder) {
  override def toString = s"${total.longValue} ${candidate}"
}

Alberto Arbusto will almost always come out slightly ahead of Jorge Sangre, provided enough votes are cast (~10,000). There's no need to tamper with the votes themselves.

 There's a race condition. And by putting Alberto Arbusto earlier in the list, we increase his chances of winning the race.

Side note: This code is loosely based on a "custom" connection pool that I encountered on a project. It took us weeks to figure out why the application was perpetually out of connections.

I like this one because of the plausible deniability it gives.

Ruby
vote_counts = $<.readlines.group_by{|s|s}.collect{ |name, votes| [votes.count, name] }

formatted_count_strings = vote_counts.map do |row,
  formatter = PrettyString.new|"%#{formatter[1][/[so]/]||'s'} %s"%
  [row,formatter]
end

sorted_count_strings = formatted_count_strings.sort_by(&:to_i).reverse

puts sorted_count_strings

Jorge Sangre will get a substantial boost in his vote count (for example, 492 votes will be reported as 754). Alberto's votes will be reported accurately.

 As you might guess, it's not who counts the votes but who formats the votes. I've tried to obscure it (PrettyString.new isn't a real thing and never gets called), but formatter is actually the name string. If the second letter of the name is 'o', the vote count will be printed out in octal instead of decimal.

Bash
(Does this meet the specification?)
uniq -c|sort -rk2,2|uniq -f1|sort -gr

As always, this takes extra precautions to ensure valid output.
uniq -c prefixes each line with the number of times it occurs. This basically does all the work.
Just in case uniq -c does something wrong, we now sort its output by the names of candidates in reverse order, then run it through uniq -f1 (don't print duplicate lines, ignoring the first field [the number of votes]) to remove any duplicate candidates. Finally we use sort -gr to sort in "General Numeric" and "Reverse" order (descending order by number of votes).

uniq -c counts consecutive occurences, not occurences over the whole file. The winner will be the candidate with the most consecutive votes.

How does this bias any particular candidate. You've simply changed the winning condition of the election. (this would be chaos if this how elections were actually decided :). You'd get giant internet groups organizing to vote sequentially)

@Cruncher in the comments on the question, the asker says that it's fine to pick the first name in the file somehow, so this is probably fine as well

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        var candidates = new SortedDictionary<string, int>();
        string candidate;
        using (var sr = new StreamReader("candidates.txt"))
        {
            while ((candidate = sr.ReadLine()) != null)
            {
                if (candidates.ContainsKey(candidate))
                    candidates[candidate]++;
                else
                    candidates.Add(candidate, 1);
            }
        }

        // order by the votes
        var votes = candidates.OrderByDescending(k => k.Value).Select(x => x.Value);

        Console.WriteLine("Candidate | Votes");
        for (int i = 0; i < candidates.Count; i++)
        {
            Console.WriteLine(candidates.ElementAt(i).Key + " " + votes.ElementAt(i));
        }

        Console.ReadKey();
    }
}

The first candidate in the text file will always win!
It will make Alberto Arbusto the winner!

 The candidates' names are ordered alphabetically in the dictionary, but the votes are ordered by number.

So will this just hand the election to the first candidate alphabetically, or can it be manipulated to prefer any candidate we like?

It doesn't sort the candidates alphabetically. It only sorts the votes. You can manipulate any candidate to win. Just make sure he is the first one in the the text file.

But IIUC SortedDictionary will sort the candidates alphabetically.

Oh, I see. There might be a mistake here. Let me test it again.

@James_pic good spot! I used SortedDictionary as a smokescreen but it actually would make Alberto Arbusto always win. I have changed it to Dictionary. Now, the first entry in the text file will win.

I'm not too hot on C#, but Dictionary looks like a plain hash table, so it wouldn't keep track of which entry was added first. I know that there are hash tables out there that keep track of insertion order (like Java's LinkedHashMap), but http://stackoverflow.com/questions/486948/linkedhashmap-in-c-sharp-3-0 suggests there's no equivalent in C#.

Wait, I stand corrected. System.Collections.Specialized.OrderedDictionary should do what you need.

You are right James_pic. There's something new that I learned today. Unfortunately, implementation of OrderedDictionary is a bit of a hassle. So, as the rules allow me, I will change this solution to make Alberto Arbusto win.

@James_pic: The hash table of the Dictionary<TK,TV> class, as implemented, stores indices into a backing array of actual items.  A Dictionary<TK,TV> from which no items are ever deleted will enumerate elements in the order they were added; such behavior is not specified, but it's been in place sufficiently long I would not expect MS to ever change it.

C
#include <stdio.h>

#define NCANDIDATES 4
static const char * const cand_list[NCANDIDATES] = {
    "Alberto Arbusto",
    "Juan Perez",
    "Mickey Mouse",
    "Jorge Sangre"
};

#define BUFFER_SIZE 100

int
main(int argc, char **argv)
{
    int votes[NCANDIDATES];
    int candidate;
    size_t name_start;
    int i;
    int j;
    int place;
    int max;
    size_t bytes;
    char buffer[BUFFER_SIZE];

    /*
    Make sure input is read in text mode, so we don't have to
    worry about whether line endings are LF or CRLF.
    */
    freopen(NULL, "rt", stdin);

    /* Initialize vote tally. */
    for (candidate = 0; candidate < NCANDIDATES; candidate++) {
        votes[candidate] = 0;
    }

    /* Read and process vote file. */
    do {
        /* Read a block of data. */
        bytes = fread(buffer, 1, BUFFER_SIZE, stdin);

        /* Loop over the data, finding and counting the votes. */
        name_start = 0;
        for (i = 0; i < bytes; i++) {
            if (buffer[i] == '\n') {
                /* Found name. */
                buffer[i] = '\0'; // nul-terminate name so strcmp will work
                /* Look up candidate. */
                for (j = 0; j < NCANDIDATES; j++) {
                    if (strcmp(&buffer[name_start], cand_list[j]) == 0) {
                        candidate = j;
                        break;
                    }
                }
                /* Count vote. */
                ++votes[candidate];

                /* Next name starts at next character */
                name_start = i + 1;
            }
        }
    } while (bytes > 0);

    /* Output the candidates, in decreasing order of votes. */
    for (place = 0; place < NCANDIDATES; place++) {
        max = -1;
        for (j = 0; j < NCANDIDATES; j++) {
            if (votes[j] > max) {
                candidate = j;
                max = votes[j];
            }
        }
        printf("%8d %s\n", votes[candidate], cand_list[candidate]);
        votes[candidate] = -1; // Remove from consideration for next place.
    }

    return 0;
}

Favors Jorge Sangre.
In testing with randomly generated vote files, even when Alberto Arbusto receives up to 1.4% more of the actual votes (49.7% vs 48.3% for Jorge Sangre), my man Jorge Sangre usually wins the count.

Reading the data in fixed-size blocks often splits a line across two blocks.

The fragment of the line at the end of the first block doesn't get counted because it doesn't have a newline character.

The fragment in the second block does generate a vote, but it doesn't match any of the candidate's names so the 'candidate' variable doesn't get updated. This has the effect of transferring a vote from the candidate whose name was split to the candidate who received the previous vote.

A longer name is more likely to be split across blocks, so Alberto Arbusto ends up being a vote "donor" more often than Jorge Sangre does.

Python
from collections import defaultdict

def count_votes(candidate, votes=defaultdict(int)):
    with open('votes.txt') as f:
        for line in f:
            votes[line.strip()] += 1

    return votes[candidate]

if __name__ == '__main__':
    candidates = [
        'Mickey Mouse',
        'Juan Perez',
        'Alberto Arbusto',
        'Jorge Sangre'
    ]

    results = {candidate: count_votes(candidate) for candidate in candidates}

    for candidate in sorted(results, key=results.get, reverse=True):
        print results[candidate], candidate

The vote counts will favour candidates closer to the end of the list.

 In Python, mutable default arguments are created and bound to the function at definition. So the votes will be maintained between function calls and carried over for subsequent candidates. The number of votes will be counted twice for the second candidate, three times for the third, and so on.

Except for the fact that the total vote count is no longer consistent with the input data, this one had me.

tr | sed | dc
tr ' [:upper:]' '\n[:lower:]' <votes |\
sed -e '1i0sa0ss0sp' -e \
    '/^[asp]/!d;s/\(.\).*/l\1 1+s\1/
    ${p;c[Alberto Arbusto: ]P lap[Jorge Sangre: ]P lsp[Juan Perez: ]P lpp
    }' | dc

This counts my buddy Alberto twice every time.
"Oh - tr? Well, it's just necessary because computers aren't very good with capital letters - better if they're all lowercase.... Yeah, I know, computers are crazy."
OUTPUT
Alberto Arbusto: 12
Jorge Sangre: 5
Juan Perez: 1

Here's another version that gives Juan Perez's vote to Jorge Sangre:
tr '[:upper:]' '[:lower:]' <votes |\
sed -e '1i0sj0sa1so' -e \
    's/\(.\).*/l\1 1+s\1/
    ${p;c[Alberto Arbusto: ]P lap[Jorge Sangre: ]P ljp[Others: ]P lop
    }' | dc

OUTPUT
Alberto Arbusto: 6
Jorge Sangre: 6
Others: 1

JavaScript
    function Election(noOfVoters) {
    candidates = ["Albert", "Jorge", "Tony", "Chip"];
    votes = [];

    for (i = 1; i <= noOfVoters; i++) {

        votes.push(prompt("1 - Albert, 2 - Jorge, 3 - Tony , 4 - Chip"))

    }
    votes.sort();
    WinningOrder = count(votes);

    var placement = [];

    for (x = 0; x < candidates.length; x++) {
        placement.push(x + " place with " + WinningOrder[x] + " votes is " + candidates[x] + "\n");
    }
    placement.reverse();
    alert(placement)
}

function count(arr) {
    var a = [],
        b = [],
        prev;

    arr.sort();
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] !== prev) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length - 1]++;
        }
        prev = arr[i];
    }

    b.sort();

    return b;
}

The last person in the candidates list will always win.

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


text:
Make a for loop repeat forever
for loops are useful in python in many ways, but one of the most common usages associated with a for loop is it's ability to repeat a certain amount of times. Like this:
for times in range(50):
    print "I'm repeating this 50 times..."

The challenge I propose to you is to make a for repeat forever. If you can find a way to do it without using a recursion, kudos to you. You can use any major version of Python. Just specify which one you are using. The goal is to do this in the smallest file size you can get, and a method that won't "break" after a while. Good luck!

Ewwww, language-specific challenges. (See http://meta.codegolf.stackexchange.com/a/234/3 for my stance on this.) (This is unrelated to the reason why I closed the question, which is a site rule and not just a personal opinion.)

@ChrisJester-Young I personally think it's fair for programming-puzzles, as they usually tend to work around some feature of a specific language. You could have told the OP though, that your closing the question has nothing to do with your not liking language-specific challenges. So, @ Some Guy, the question is closed because you did not indicate who (among several correct solutions) you will pick the winner of the challenge. Votes? Code-length? Something else?

@m.buettner There, I edited my comment to say that now. Thanks! :-)

Befunge will surely win if this is non-language-specific code-golf.

@user23013 Of course. It was the winning entry in my stack overflow code golf. ;-)

@ChrisJester-Young I have added basic criteria to help decided a winner. This probably isn't enough to re-open the question though... Sorry to the users who answered this question before I added goals in order to choose a winner.

@SomeGuy Thank you. I have retagged the question as a code golf since the winning criterion is shortest code.

Here's an idea to make this non-language-specific: "implement a foreach loop that repeats forever"

@TheRare Changing the accepted answer is absolutely legitimate if a new winner comes along (by the specified criteria). Therefore, the currently accepted answer isn't even the correct one, actually.

@m.buettner Well then, I take your word on that.

Wait... is this [tag:code-golf] or [tag:popularity-contest]? I'm confused.

@Iszi Pop contest.

The question and one tag state that it's code-golf. The previous comment and another tag state that it's pop-con. It can't be both.

It's code golf, but it would have been far better as an underhanded popularity contest.

@ChrisJester-Young Eww, here's another language-specific challenge. Doesn't look like it's getting hate for that.

@DatEpicCoderGuyWhoPrograms King-of-the-Hill contests are a special exception, to make concessions for OPs who want to test out the entries and not have to install many language runtimes in order to do so. However, there are still ways to run language-independent KotH contests (e.g., using virtual machines), and I still encourage people to do it.

perl6 -e 'for 0..* {print "$_\r"}' only 11 required characters, or perl6 -e 'print "$_\r" for 0..*' only 10 chars required ( there has to be something before for separated by whitespace 0 for 0..*)

I didn't know you had time for code-golfing, M. Putin.

Because this was turned to a codegolf, have a 48 bytes version as a one-liner. 3 bytes could be removed from both by replacing print i with pass.
for i in __import__('itertools').count():print i

Or a 47 bytes version with two lines.
from itertools import*
for i in count():print i

Old message:
Easy it is.
def f(i = 0):
    while True:
        yield i
        i += 1
for i in f():
    print(i)

This can be done quite easily by abusing floating point addition.
def frange(start, stop, step):
    r = start
    while r < stop:
        yield r
        r += step

for x in frange(0, 1e16, 1):
    print (x)

IEEE754 64-bit floats have 53 bits of mantissa (including the implicit bit), so if x > 1<<53 then x + 1 == x. 1 << 53 is approximately 9e15.

Are you sure this won't transform to a long?

@TheRare, why would it transform to a long? That aside, a simple test shows arithmetic behaving as expected.

That is actually pretty interesting.

This is an interesting way of doing it (32 chars for class x, 46 not counting the print):
class x:__iter__=next=lambda s:s
for i in x():print "Hello"

This defines an iterable whose next method never raises a StopIteration

Actually, the next method is the __iter__ method (which is supposed to return the iterable). Both return self (s)

for i in iter(lambda : 0, 1):
    print (i) # prints 0 forever

The iter function is normally used to create an iterator from an iterable.
The iter function can also take two arguments, a callable and a sentinel value. In that case it returns an iterator that yields the result of the callable until the callable returns the sentinel value.
In this case, the callable is a lambda that always returns 0. Since it never can return the sentinel value (1), this will loop forever.
Since this is code golf, this version is 28 characters and only one line:
for i in iter(lambda:0,1):i

I don't usually golf in Python, probably some reason people haven't already done posted this 23-character solution.
x=[1]
for i in x:
 x+=x

Much less memory-hungry if you do x+=[i] instead. Either one hangs my 2.7.5

"and a method that won't "break" after a while." So that's why no one has done this. Or maybe it's because no one was smart enough to think of it.

Well, this does explode the memory very quickly, because the memory usage raises exponentially.

Yeah, the +=[i] version seems almost legitimate though, I don't know if that would break within any reasonable amount of time. Either way, not as interesting a solution as the others.

It would probably break eventually, when the list reaches sys.maxsize items.

28 bytes, infinite, and no itertools
for x in iter(int,1):print 1

Shouldn't end without system program cutoffs (i.e. not my fault).
22 bytes without printing anything:
for x in iter(int,1):1

Itertools, to the rescue:
from itertools import count
for i in count():
    print i

or
from itertools import repeat
for i in repeat(42):
    print i

Just an fyi, itertools.count is the same as my answer and itertools.repeat is almost the same as my original answer.

@TheRare I suppose, but I'd rather use itertools.count in an production environment than something home-brew.

Absolutely. Just wanted to inform that the implementation is the same.

39 Characters, no itertools and no crashing
def f():
 while 1:yield
for i in f():1

Itertools is unnecessary, you can define your own generator.

You don't need to use pass - 1 or i will do just as well.

Python 2 & 3: 37 characters
class P:__getitem__=id
for t in P():1

¡No infinite memory required!

Python 3.3: 2 lines, 29 characters
j=[1]
for i in j: j.append(1)

Does this break? I've run it for a short while, doesn't seem to hang.

This will run out of memory, just like histocrat's version.

@m.buettner indeed it will. Hmm.


text:
Minimalist Hex Clock
Your challenge is to create a clock that displays the time as a hex number, and the background color as the hex color code of the time.
Requirements: No input. In the center of your output you should display the number sign and the current time in 24 hour format as "#hhmmss". The program should update to the current time at least once every second. The text must be centered and white (or a light color that stands out). The background should be entirely the color of the hex code. Shortest code wins, but creative answers are encouraged.
Live example. Idea from r/InternetIsBeautiful.

I liked the idea, but it'd be better as a popularity contest imo

@WilliamBarbosa I believe the result is way too simple for a popularity contest to be useful.

You may want to point out that the IIB post is an x-post from /r/minimalism. But heh.

python3 (142) or (123 with flickering)
import time;from turtle import*;tracer(0)
while 1:reset();ht();color([1]*3);a=time.strftime("#%H%M%S");write(a,0,"center");bgcolor(a);update()

using turtles, 142 bytes, will probably not be the shortest, but I simply wanted to use play with turtles again.
This example updates the screen often enough en does what is asked, but it is not pretty, as it goes on and off. Then it is only 123 bytes. (not a specified quality)
import time;from turtle import*
while 1:reset();ht();color([1]*3);a=time.strftime("#%H%M%S");write(a,0,"center");bgcolor(a)

ungolfed:
import time
from turtle import*
tracer(0)                           #1 not every change should be propagated immediatly
while 1:
    reset()                         #2 remove previous drawing
    ht()                            #3 hide the turtle
    color([1]*3)                   #4 set color to snow, which is white for as far I can see
    a=time.strftime("#%H%M%S")      #5 generate the color from time
    write(a,0,"center")             #6 print time
    bgcolor(a)                      #7 change bgcolor
    update()                        #8 propagate changes

btw, because of the while 1, I'd recommend running it from terminal. As it can be quite difficult to close :D (you'll need ctrl+c)

You can reduce your character count by combining all of the lines in the while loops using semicolons.

@isaacg thank you, I adapted it.

You can reduce your character count by 9 by removing the final call to update() as bgcolor() calls update() (ignoring tracer setting) already. You can save another character by using color([1]*3) instead of "snow".

@cdlane I removed the update() in the second answer (second codeblock), I didn't think it was right to let that be my final answer as that code caused a flickering screen back then and as it doesn't remove the previous numbers making it ugly if let run for a long time. the  """color([1]*3)""" is very nifty trick indeed!

HTML/CSS/JavaScript 207 183 180 161 152
Tested and working in the latest Firefox and Chrome browsers.
<body id=b onload=setInterval("b.innerHTML=b.bgColor=Date().replace(/.*(..):(..):(..).*/,'#$1$2$3')",0) text=#fff style=position:fixed;top:50%;left:47%>

Demo Here

as far as I see, your code perfectly works without the  at least in safari/jsfiddle

@Pinna_be Good catch. I was trying out a few different ways of vertically centering the text and that was left over from another method.

I know I'm braking some rules by making this comment, but, damn this body tag is pure beauty.

Processing, 162 bytes
void draw()
{
 int h=hour(),m=minute(),s=second();
 background(color(h,m,s));
 textAlign(CENTER);
 text("#"+(h<10?"0"+h:h)+(m<10?"0"+m:m)+(s<10?"0"+s:s),50,50);
}

Screenshot:

I don't know if it's against the rules, but the actual drawing area is the 100x100px square on the center of the window. For some reason, Processing can't scale down the window to that size, so it adds the gray margins around the drawing area. Here's another version without the gray margins, but slightly larger (198 bytes):
void setup()
{
 size(200,200);
}

void draw()
{
 int h=hour(),m=minute(),s=second();
 background(color(h,m,s));
 textAlign(CENTER);
 text("#"+(h<10?"0"+h:h)+(m<10?"0"+m:m)+(s<10?"0"+s:s),100,100);
}

are the newlines and the spaces at the beginning mandatory? Because you could shave off some characters over there.

SmileBASIC, 65 bytes
T$=TIME$T$[2]="
LOCATE 21,14T$[4]"
GCLS VAL("&H"+T$)?"#";T$EXEC.

HTML + Javascript (184)
This uses the => notation which is currently only supported in Firefox. It does not use any libraries.
<body text=white onload='(b=document.body).bgColor=b.innerHTML="#"+[(d=new Date()).getHours(),d.getMinutes(),d.getSeconds()].map(x=>("00"+x).slice(-2)).join("");setTimeout(b.onload)'>

With indentation:
<body
 text=white
 onload='
       (b=document.body).bgColor =
       b.innerHTML =
             "#"+[ (d=new Date()).getHours(),
                    d.getMinutes(),
                    d.getSeconds()].map(
                        x=>("00"+x).slice(-2)
                    ).join("");
       setTimeout(b.onload)
'>

shouldn't the output be in the center of the screen?

C# 357, 325 with minor cheating
Yea, C# isn't gonna win many codegolf prizes against other languages. Still, fun!
Cheating (not exactly centre, and only centre with .NET 4.5's default form size of 300x300, Mono may do other funny stuff):
using System.Windows.Forms;using System.Drawing;class P:Form{static void Main(){new P().ShowDialog();}public P(){var l=new Label(){Top=125,Left=120,ForeColor=Color.White};Controls.Add(l);new Timer(){Enabled=true,Interval=1}.Tick+=(s,e)=>{BackColor=ColorTranslator.FromHtml(l.Text=System.DateTime.Now.ToString("#HHmmss"));};}}

Golfed:
using System.Windows.Forms;using System.Drawing;class P:Form{static void Main(){new P().ShowDialog();}public P(){var l=new Label(){Dock=(DockStyle)5,TextAlign=(ContentAlignment)32,ForeColor=Color.White};Controls.Add(l);new Timer(){Enabled=true,Interval=1}.Tick+=(s,e)=>{BackColor=ColorTranslator.FromHtml(l.Text=System.DateTime.Now.ToString("#HHmmss"));};}}

Ungolfed:
using System.Windows.Forms;
using System.Drawing;

class P : Form
{
    static void Main()
    {
        new P().ShowDialog();
    }

    public P()
    {
        var l = new Label() { Dock = (DockStyle)5, TextAlign = (ContentAlignment)32, ForeColor = Color.White };
        Controls.Add(l);
        new Timer() { Enabled = true, Interval = 1 }.Tick += (s, e) =>
        {
            BackColor = ColorTranslator.FromHtml(l.Text = System.DateTime.Now.ToString("#HHmmss"));
        };
    }
}

Python 3, 122 characters
from turtle import*
import time
color(1,1,1)
ht()
while 1:_=time.strftime("#%H%M%S");bgcolor(_);write(_,0,"center");undo()

Takes advantage of Python 3 turtle's undo() capability to clear just the previous text.  Doesn't exhibit the intense flickering of turtle reset() caused by it resetting everything about the turtle.


text:
What time is it?
I really hate looking up to the top right of the screen to look at the time on OS X's clock widget; I'd much rather keep my eyes at least somewhere near my workspace to check the time. I also hate other people using my clock to check the time as they walk by -- after all, it's called a personal computer, right? But we've got a great community here that can surely help me out, right? So here's my really really so much very hard challenge for you guys that would help me so much: write me a clock app. It can be analog or digital or whatever other amazing forms you can think of. Minimum requirements:

It should be very visible
It should display the time in a format that not many people would comprehend (the less people, the better)

This is a popularity contest, so fulfill these requirements creatively, and go above and beyond! Ready... Set... Go!

This question appears to be off-topic because it appears to be a clock design question, not a programming question.

How is this a puzzle or code golf?

Gah. This question is seriously off-topic for this site, and I originally wanted to delete it. But some of the answers were pretty nice, and I don't want to lose them, either. :-(

Bash
#!/bin/bash

T="The time is now:"

case $1 in
--12)    F=82;M=0;S=%r;;
--24)    F=120;M=100;S=%R;;
--ipv6)  F=112;M=0;S=%H::%M:%S;T="Started download from:";;
--posix) F=82;M=0;S=%s;;
esac

watch 'notify-send "'"$T"'" "

    $(date +'"$S"')
"'

Displays the current time as a desktop notification, updating every two seconds.
Usage
whattimeisit FORMAT

--12     May be understood by Australians, Chinese and North Americans.
--24     May be understood by everyone else.
--ipv6   May be understood by illiterates.
--posix  May be understood by nerds.

Example output

What OS is that? Looks KDE-based (given Kate & Kile)

@KyleKanos: Fedora 20 Scientific KDE, with a lot of modifications.

That looks pretty nice. What kind of mods are you talking about?

@KyleKanos: Nothing fancy, just a lot of them. Custom theme (mainly Oxygen, but with Air widgets), Oxygen Blue cursor theme, reduced the task bar to notification area and clock (I use Present Windows for navigation), got rid of the hot corners (replaced by extra mouse button/touchpad edges), Application Launcher (QML) widget on the desktop, Ubuntu font, improved font rendering, Elarun wallpaper, Title bar button menu style, borderless windows, etc.

Okay. I was just wondering if you had made mods to the kernel or if you meant prettyifying it (which it does like very nice).

Javascript
This encodes the hours, minutes, and seconds, as hex, and sets the background color of the page to the concatenation of the string. For example, for the time 9:18:13 PM, the background color would be set to #15120D. It is right on a webpage for you, all you have to do is drag a little bit of the window to a different place on the screen or flip tabs. Here is a JSFiddle demo.
To tell the time, you can use your handy color-picking and base changing skills.
function hex(number) {
    return number.toString(16).length == 1 ? "0" + number.toString(16): number.toString(16);
}
var display = function() {

    var now = new Date();
    var base = "00"
    var hours = hex(now.getHours());
    var minutes = hex(now.getMinutes());
    var seconds = hex(now.getSeconds());
    document.body.style.background = "#" + hours + minutes + seconds;
    console.log("#" + hours + minutes + seconds)
}

setInterval(display, 1000);

Finally! An application for my accurate hex color intuition

HTML + CSS + JavaScript
I made a binary clock, pretty self-explanatory. I have a binary watch and even those who know what binary numbers are may have a hard time telling what time it is sometimes. Like scrblnrd3 said in his answer, all you have to do is position your browser window properly to make it visible. Here's a fiddle of clock in action.
P.S.: The hour part has 5 positions in order to support 24 hour format.
JavaScript
function pad(number, digits) {
    return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}

var updateClock = function() {
    var date = new Date();

    var childDivs = [
        document.getElementsByClassName('hours')[0].children,
        document.getElementsByClassName('minutes')[0].children,
        document.getElementsByClassName('seconds')[0].children
    ];

    var binaryTime = [
        pad(date.getHours().toString(2), 5),
        pad(date.getMinutes().toString(2), 6),
        pad(date.getSeconds().toString(2), 6)
    ];

    for(i=0; i < childDivs.length; i++) {
        for(j=0; j < childDivs[i].length; j++) {
            childDivs[i][j].className = binaryTime[i][j] == '1' ? 'highlight' : '';
        }
     }
}

setInterval(updateClock, 1000);

CSS
.wrapper div {
    width: 30px;
    height: 30px;
    border-radius: 50px;
    border: 1px solid black;
    display: inline-block;
    margin: auto;
}

.highlight {
    background-color: green;
}

HTML

C
I have been finding it annoying, that though computers can easily keep time with an accuracy of a few ms by using NTP, some software displaying time haven't bothered with updating it at the right time. For example if you display time with hours and minutes by simply displaying the time and then sleep for 60 seconds in a loop, the displayed clock will on average be 30 seconds behind.
Here is my suggestion on how to implement a highly accurate clock (which displays time as seconds since midnight GMT in octal).
#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int main()
{
  struct timeval tv;
  struct timespec ts;
  while (1) {
    do {
      gettimeofday(&tv,NULL);
    } while ((ts.tv_nsec=((999999-tv.tv_usec)*1000)-1)<1);
    printf("\x0d%lo    ", tv.tv_sec%86400);
    fflush(stdout);
    ts.tv_sec=0;
    nanosleep(&ts,NULL);
  }
}

 Replace the printf with s=ctime(&tv.tv_sec); c=strchr(s,'\n'); if (c) *c=0; printf("\x0d%s ",s); if you want human readable output.

Javascript
This is an ASCII clock with A=0.

0