11

I was thinking about this today while reading great answers to a question I had about the next language I should learn:

What's the most insane looking method/function you've ever written (proud OR horrified)? Dont forget to tell us which language it is.

Just to get the ball rolling, I propose this (C#):

  public sealed class ModelSimplication<T, U> where U: IARModelSimplifier<T>, new() {
    public static U[] Simplify(IEnumerable<T> pObjects) {
      List<U> olist = new List<U>();
      foreach (T o in pObjects) {
        U obj = new U();
        obj.Use(o);
        olist.Add(obj);
      }
      return olist.ToArray();
    }
  }
21

I wrote a program which converts an XML document to XXML (Extensible XML) - the ultimate format for a truly extensible markup language! ;) It was inspired by this post at the Daily WTF.

What it does is that it takes an XML document such as

<foo bar="gazonk">xyz</foo>

and converts it into

<element name="foo">
  <attribute name="bar">gazonk</attribute>
  <characters>xyz</characters>
</element>

Notice how this format reduces duplication, as you don't need to type "foo" anymore twise in both the opening can the closing tags, but you can type it only once as an attribute.

In case you want to incorporate this marvelous new format into your enterprise system, the source code is available here.

21 accepted

I think my mircscript to 'compress' channel modes was the craziest thing I've written.


alias mode {
  haltdef
  if (#?* iswm $1) && ($me !isop $1) return
  if $1 == * { mode $2- | return }
  var %t = m $+ $1, %o = $hget($1,m) | hadd -m $1 m $+($token(%o,1,32),$2,$chr(32),$token(%o,2-,32),$chr(32),$3-)
  if (!%mode.delay) set %mode.delay 2
  if (!$timer(%t)) .timer $+ %t 1 %mode.delay v $1
}
alias mode.delay if ($1 !isnum) || (. isin $1) || ($1 < 1) { echo -at * mode delay error: mode delay can only be a positive value 1 or greater. | return } | set %mode.delay $1 | echo -at * mode delay set to $1 second
alias -l x %i = 1 | while $ibl($1,%i) { if ($v1 == $2) return 1 | inc %i }
alias -l m return $iif($2 isincs $iif($1 == $me,$usermode,$chan($1).mode),1,0)
alias -l v {
  var %i = 0, %t = $hget($1,m), %m = $token(%t,1,32), %p = $token(%t,2-,32), %z = "", %u = 0, %n = 0, %k = "", %y1 = rtuipsdDxRwcCnNm, %y2 = obvlk | hfree $1
  while %i <= $len(%m) {
    inc %i
    var %j = $mid(%m,%i,1)
    if $istok(+ -,%j,32) { %o = %j | continue }
    var %f = %o $+ %j
    if (%j isincs %y1) {
      if ((%f isincs %z) || (%o == + && $m($1,%j)) || (%o == - && !$m($1,%j))) continue | var %n = $calc(%n +1), %z = %z $+ %f
    }
    elseif (%j isincs %y2) {
      var %u = $calc(%u +1), %e = $token(%p,%u,32)
      if ((%f == +v && %e isvoice $1) || (%f == -v && %e !isvoice $1) || (%f == +o && %e isop $1) || (%f == -o && %e !isop $1) || (%f == +b && $x(%e)) || (%f == -b && !$x(%e))) continue
      if (%f isincs %z) && (* %e * iswm * %k *) continue
      var %n = $calc(%n +1), %k = %k %e, %z = %z $+ %f
    }
    if $modespl == %n { mode * $1 %z %k | var %z = "", %k = "", %n = 0 }
  }
  if (%z) mode * $1 %z %k
}
21
10 X = 3000000
20 X = X + 1
30 If X < X + 1 goto 20
40 Print "X = X + 1"

A joke? No--this was serious. I ended up demonstrating it to most every teacher in the department, none of which believed it would terminate.

(The initial seed is simply to make it terminate in a reasonable period of time.)

This came about because a teacher gave an assignment that had two logical approaches. The brute-force approach would work, the thinking approach would fall victim to rounding errors and not work. What's crazy about it is that I needed to do it.

Followup for those who don't see what's going on:

X is floating point. Eventually it will run out of precision and there will be a roundoff error that makes X actually equal X + 1. On the system in question this point is reached not too far past 3 million.

None of the teachers realized this would happen which means they did not understand the nature of floating point numbers.

Edit: Goto isn't needed, any conditional looping construct can be used--it's just when I wrote this goto is what we had. It will eventually terminate with any floating point type but it could take an extremely long time to do so if there is a lot of precision and you don't seed it to something near the termination point.

10

I think my code for modeling HP Lovecraft's shoggoths, or shoggothim as I pluralize them, as a playable race in a computer RPG may qualify, largely because of how much of the source code is in the Cthulhu-language Ngaathgl, as in this (live and working) LPC code sample:

void shoggoth_check_vorgaal() {
    int new_vorgaal_current = round(owner_bulk * owner->query_real_hit_points() / owner->query_real_max_hit_points());
    if(new_vorgaal_current == vorgaal_current)
        return;
    vorgaal_current = new_vorgaal_current;
    int vorgaal_over = vorgaal_used - vorgaal_current;
    if(vorgaal_over <= 0)
        return;
    mapping lose = ([]);
    foreach(struct flgath : query_flgathu()) {
        int stability = flgath[Shoggoth_Race_Flgath_Glithmrul] - flgath[Shoggoth_Race_Flgath_Fungmrul];
        int limb = flgath[Shoggoth_Race_Flgath_Limb_Index];
        if(limb == Null)
            stability = round(stability * owner->query_real_hit_points() / owner->query_real_max_hit_points());   
        else
            stability = round(stability * owner->query_real_limb_hp(limb) / owner->query_real_max_limb_hp(limb)); 
        lose[flgath] = Shoggoth_Race_Flgath_Loss_Base - stability;
    }
    while(vorgaal_over > 0) {
        struct flgath = random_element(lose);
        if(!flgath)
            break;
        if(member(query_flgathu(), flgath) != Null) {
            shoggoth_uvgulth(flgath, Shoggoth_Race_Flgathl_Flag_Involuntary);
            vorgaal_over -= flgath[Shoggoth_Race_Flgath_Vorgaal];
        }
        map_delete(lose, flgath);
    }
}
8
10 PRINT CRAZY
20 GOTO 10
8

Several years ago for fun, I wrote an 8 queens solver that only used one 32-bit int in C. It's on my website if you want an explanation.

#include <stdio.h>

#define X ((S&255)>>5)
#define Y ((S&31)>>2)
#define I ((S&255)>>4)
#define J ((S&15))
#define P(R) ((S>>(8+((R)*3)))&7)

int main()
{
    int S = 0;
    while (S != -256) {
        S |= 2;
        do {
            S = (S & ~28) | ((X + 1) << 2);
            while (Y) {
                if (!(P(Y)-P(X)) || !(P(Y)-P(X)-Y+X) || !(P(Y)-P(X)+Y-X))
                    S &= ~2;
                S += 4;
            }
        } while (X < 7);
        if (S & 2) {
            S = (S & 0xffffff00) | 136;
            while (I) {
                while (J) {
                    putchar((!(P(I-1)-J+1)) ? 'Q' : '-');
                    putchar(' ');
                    S = (S & ~15) | (J - 1);
                }
                putchar(' ');
                S = (S & ~255) | ((I - 1) << 4) | 8;
            }
            putchar(' ');
            S = (S & 0xffffffe0) | 0xe0;
        }
        S += 32;
    }
    return 0;
}
5

I remember entering a programming contest once to design a slow sort algorithm.

The idea was to write a sort algorithm which would terminate in the maximum possible time. Extra points for style.

My entry was what I called the 'Flight of Cards', similar to throwing a pack of cards in the air, picking them all up, looking to see if they were in the correct order. If not repeat the process. If your random() is truly random(), this will eventually terminate.

4

One time I wrote a recursive function in Javascript that produced multiple anonymous recursive functions for iterating down tree nodes.

It was horrible, but made me giggle inside.

4

I needed to get the product of some numbers in a database. Since SQL doesn't have that function built in, I had a little fun:

SELECT CriteriaField, exp(Sum(log(DataField))) AS Product
FROM SomeTable
GROUP BY CriteriaField;

High school math comes in handy again!

3

For the JumpingSteve visualizer this is a part verbatim from the code...

It creates the swinging iPod cord. I wasn't sure how many particle links that was sufficient so I made a macro and copy-pasted a bunch of ADD lines so it looked appropriate in length in the editor :) The tmp2 and tmp3 is the splitted parts that went to the ears. Horrible code...yah, but I love it, and it works

chain *tmp1 = new chain;
chain *tmp2, *tmp3;

visualPluginData->ipodChain = tmp1;
#define ADD \
  tmp2 = new chain; \
  tmp1->add(tmp2); \
  tmp1 = tmp2;

ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
ADD;
tmp3 = tmp1;
ADD;
ADD;
ADD;
ADD;
ADD;
tmp2->x = -3.2;
tmp2->y = 18.2;
tmp1 = tmp3;
ADD;
ADD;
ADD;
ADD;
ADD;
tmp2->x =  1.7;
tmp2->y = 18.3;
3

In the dot-com 1990s, pre-YouTube video website Atom Films had a promotional contest: who could watch the most Atom Film videos in a 24 hour period? The prize was something dumb like a DVD player.

I wrote a Perl script to crawl their website, parsing their HTML to find the videos' length. My script sorted the videos from shortest to longest. That would be the optimal ordering to "bin pack" the most videos in a 24 hour period.

oh yeah: my Perl script would "watch" the videos, not me. :) My script was supposed to load each videos' URL, pretend to watch the video by waiting for the known video length, then proceed to the next video.

Unfortunately, when the contest day came, my Perl script had some trouble parsing their inconsistent HTML and loading the pages in a timely manner. :( A sad day indeed..

3

An incomplete, inefficient and probably buggy SK combinator compiler/jit-compiler/interpreter (not sure what to call it). 64-bit gnu asm, combinators accept an argument and return a result in %rax.

This program evaluates (((S K) K) hello). Hello isn't a real combinator.

To build: as -o sk.o sk.s && ld -o sk sk.o

sk.s:

.text
.globl _start
_start: /* init: ds = es = cs, %edi points to empty space */
        mov     %cs, %rax
        mov     %rax, %ds
        mov     %rax, %es
        movq    $buff, %rdi

mprotect: /* allow writing to code segment */
        mov     $125, %eax /* mprotect */
        mov     $_start, %ebx
        and     $0xfffff000, %ebx
        mov     $prog_len, %ecx /* length */
        mov     $7, %edx /* rwx */
        int     $0x80
        test    %eax, %eax
        js      smc_error

eval:   /* (((S K) K) hello) */
        movq    $k, %rax
        call    s
        movq    %rax, %rbx   /* rbx = (S K) */
        movq    $k, %rax
        call    *%rbx
        movq    %rax, %rbx   /* rbx = ((S K) K) */
        movq    $hello, %rax
        call    *%rbx        /* rax = (((S K) K) hello) */
        jmp     *%rax

hello:  
        movl    $4, %eax    /* system call number (sys_write) */
        movl    $1, %ebx    /* file descriptor (stdout) */
        movl    $msg, %ecx  /* message to write */
        movl    len, %edx   /* message length */
        int     $0x80       /* call kernel */

        movl    $1, %eax    /* system call number (sys_exit) */
        xorl    %ebx, %ebx  /* return value success */
        int     $0x80       /* call kernel */

smc_error:
        mov     $1, %eax
        mov     $1, %ebx
        int     $0x80

/*
        (define k
          (lambda (x)
            (lambda (y)
              x)))
*/

k: /* arg in eax */
        pushq   %rdi
        movq    $k1, %rsi
        movq    %rax, k1_x     /* patch k1 */
        movq    $k1_len, %rcx
        rep     movsb          /* copy k1 */
        popq    %rax           /* return the new k1 */
        ret

k1_x = . + 2
k1:
        movq    $0x1111111111111111, %rax /* 0x111... is a placeholder for x */
        ret
k1_len = . - k1

/*
        (define s
          (lambda (x)
            (lambda (y)
              (lambda (z)
                ((x z) (y z))))))
*/

s:
        pushq   %rdi
        movq    $s1, %rsi
        movq    %rax, s1_x /* patch s1 */
        movq    $s1_len, %rcx
        rep     movsb
        popq    %rax
        ret

s1:
        pushq   %rdi
        movq    $s2, %rsi
s1_x = . + 2
        movq    $0x1111111111111111, %rbx
        movq    %rbx, s2_x
        movq    %rax, s2_y
        movq    $s2_len, %rcx
        rep     movsb
        popq    %rax
        ret
s1_len = . - s1

s2:
        pushq   %rax                       /* save z */
s2_x = . + 2
        movq    $0x1111111111111111, %rdx
        callq   *%rdx                      /* rax = (x z) */
        xchg    %rax, (%rsp)               /* restore z, save (x z) */
s2_y = . + 2
        movq    $0x2222222222222222, %rdx
        callq   *%rdx                      /* rax = (y z) */
        ret     /* really a jmp to (x z) which is on the stack */
s2_len = . - s2


msg:
        .string "Hello World!\n"
len:
        .long   13

buff: /* for runtime generated code */
.org 0x1000, 0

prog_len = . - _start
2

I once wrote some CSV parsing code in XSLT templates (complete with quoting support), all so I could avoid "polluting" XSLT with a call out to Javascript or VBScript. Probably wasted a couple of days making it work properly, all of it pointless. But it felt like the "right" way to do it at a time.

Some times you need to take step back and look at what you are doing and why.

2

In 2005 I wrote (in C++) a class template that derived from a specialization of itself:

struct none
{
    struct value_type {};
};

// Forward declaration of record
template <
    class T0 = none, class T1 = none,
    class T2 = none, class T3 = none,
    class T4 = none, class T5 = none,
    class T6 = none, class T7 = none,
    class T8 = none, class T9 = none,
    class TA = none, class TB = none,
    class TC = none, class TD = none,
    class TE = none, class TF = none
    >
struct record;

// Specialization for all fields none
template <>
struct record<
        none, none, none, none,
        none, none, none, none,
        none, none, none, none,
        none, none, none, none
        >
{
    // continues...
};

template <
    class T0, class T1, class T2, class T3,
    class T4, class T5, class T6, class T7,
    class T8, class T9, class TA, class TB,
    class TC, class TD, class TE, class TF
    >
struct record : 
    public record<T1, T2, T3, T4, T5, T6, T7, T8, 
            T9, TA, TB, TC, TD, TE, TF, none>
{
   // continues...

The tricky part was getting it to compile on Visual C++ (it never worked on v6), Sun Forte C++ for Solaris, IBM Visual Age C++ for AIX and GNU C++ for Linux.

1

I wrote a C# search algorithm for a larger Job board out in the NW that involved taking a single search string that may or may not have included operators (OR, AND, AND NOT) and formatting that string into an accepatable value for a Sql Server CONTAINSTABLE query.

The first prototype made my co-workers eyes blurry ;-)

1

Raytheon had a minicomputer called the RDS-500. It had an instruction JSX (Jump and Set indeX) that could be used for simple subroutine calls:

JSX foo ; jump to foo, and set index register to .+1 (i.e. subroutine call)

JSX * ; means jump to where index register points, and set index to .+1

So you could write the following code:

 ; co-routines
A: JSX B
   JSX *
   JSX *
   ...

B: JSX *
   JSX *
   JSX *
   ...

which would create co-routines between A and B.

Then if you wrote:

    ; 2-forward-1-back
   JSX .+2
   JSX *
   JSX *
   JSX *
   ...

It would go 2 steps forward, 1 step back, etc. etc.

That was fun.

1

It's not the "craziest" piece of code I do but I'm not a PHP guy and this made me smile :

ini_set('memory_limit', '64M');
1

I once recreated Myst in PennMUSH. I may not have known the scripting language well, but I suspect that all code for a specific object had to be on a single line and that the language did not support comments.

Here's a dump of the code for one object (the map of the Myst island in the library), written many many years ago:

The Map Of The Isle Of Myst(#1438TV)
The map depicts the isle. There is a circle at the east end of the map.
%r%rOn the map, you can see: %r- The
tower[switch(get(#7152/state),up,%r- The boat at the
dock)][switch(get(#10009/state),up,%r- The
observatory)][switch(get(#10330/state),up,%r- The giant
gears)][switch(get(#10023/state),up,%r- The fountain and the
pillars)][switch(get(#10331/state),up,%r- The wooden
cabin)][switch(get(#10333/state),up,%r- The stone
building)][switch(get(#10334/state),up,%r- The clock
tower)][switch(get(#10594/state),up,%r- The rocket)]%r%r(To use: "lock
map on <object>")

CMD_LOCKMAPON [#9265]: $lock map on *:@switch %0=gears,{@switch
get(#10330/state)=up,[ufun(DO_LOCKMAPON_GEARS)],down,[ufun(
DO_LOCKMAPON_SOUTH)],},giant gears,{@switch
get(#10330/state)=up,[ufun(DO_LOCKMAPON_GEARS)],down,[ufun(
DO_LOCKMAPON_SOUTH)],},boat,{@switch
get(#7152/state)=up,[ufun(DO_LOCKMAPON_BOAT)],down,[ufun(
DO_LOCKMAPON_SOUTHSOUTHWEST)],},pier,{@switch
get(#7152/state)=up,[ufun(DO_LOCKMAPON_BOAT)],down,[ufun(
DO_LOCKMAPON_SOUTHSOUTHWEST)],},tree, {@switch
get(#10331/state)=up,{&LOCKED_ON map=tree;@pemit %#=You let the red beam
sweep over the isle, and stop it as it turns red pauses on the giant
tree for a second. The beam is now locked on the tree. As you move your
hand away from the map, a rumble can be heard, coming from above.
},down,{&LOCKED_ON map=sw;@pemit %#=You let the red beam sweep over the
isle, and stop it as it slides over the gears. As you move your hand
away from the map, a rumble can be heard, coming from above.}},giant
tree, {@switch get(#10331/state)=up,{&LOCKED_ON map=tree;@pemit %#=You
let the red beam sweep over the isle, and stop it as it turns red pauses
on the giant tree for a second. The beam is now locked on the tree. As
you move your hand away from the map, a rumble can be heard, coming from
above. },down,{&LOCKED_ON map=sw;@pemit %#=You let the red beam sweep
over the isle, and stop it as it slides over the gears. As you move your
hand away from the map, a rumble can be heard, coming from
above.}},rocket, {@switch get(#10594/state)=up,{&LOCKED_ON
map=rocket;@pemit %#=You let the red beam sweep over the isle, and stop
it as it turns red pauses on the rocket for a second. The beam is now
locked on the rocket. As you move your hand away from the map, a rumble
can be heard, coming from above. },down,{&LOCKED_ON map=n;@pemit %#=You
let the red beam sweep over the isle, and stop it as it slides over the
rocket. As you move your hand away from the map, a rumble can be heard,
coming from above.}},@pemit %#=You can't lock the map on that!

DO_LOCKMAPON_BOAT [#9265]: [pemit(%#,You let the red beam sweep over the
isle\, and stop it as it turns red pauses on the boat for a second. The
beam is now locked on the boat at the pier. As you move your hand away
from the map\, a rumble can be heard\, coming from above.)][oemit(%#,%N
moves his hand away from the map he has been playing with\, and a rumble
can be heard\, coming from above.)][remit(#10472,Suddenly\, there is a
loud noise and the tower rotates!)][remit(#10595,Suddenly\, there is a
loud noise and the tower rotates!)][remit(#10598,Suddenly\, there is a
loud noise and the tower rotates!)][name(#10596,The Eye Ladder
<SSW>;southsouthwest;ssw;eye ladder;eye)][name(#10597,The Eye Ladder
<NNE>;northnortheast;nne;eye ladder;eye;down;d;out;o)][name(#10599,The
Book Ladder <NNE>;northnortheast;nne;book ladder;book)][name(#10600,The
Book Ladder <SSW>;southsouthwest;ssw;book
ladder;book;down;d;out;o)][set(#10595,describe:You're standing on one of
the platforms inside the top of the tower. A metal ladder leads down
back to the middle of the tower where the elevator shaft is. %r%rThe
metal wall here is divided in two parts. In the middle of the wall\,
there is a long gap\, starting at the floor and ending at the ceiling.
Looking through it\, you can see the Isle of Myst from above. In the
middle of your view is the boat at the dock.%r%rThe metal ladder to the
northnortheast leads down the middle of the tower.
)][set(#10598,describe:You're standing on one of the platforms inside
the top of the tower. A metal ladder leads down back to the middle of
the tower where the elevator shaft is. There is a square gap in the
metal wall here\, starting at the floor and ending at the roof of the
tower. Behind the gap is a concrete wall\, with a small golden plaque
attached to it. The plaque reads: %r%r\[center(ansi(h,OCTOBER 11\,
1984),78)\]%r\[center(ansi(h,10:04 AM),78)\]%r%r\[center(ansi(h,JANUARY
17\,1207),78)\]%r\[center(ansi(h,5:46
AM),78)\]%r%r\[center(ansi(h,NOVEMBER 23\,
9791),78)\]%r\[center(ansi(h,6:57 PM),78)\]%r%rThe metal ladder to the
southsouthwest leads down the middle of the tower. )]

DO_LOCKMAPON_GEARS [#9265]: [pemit(%#,You let the red beam sweep over
the isle\, and stop it as it turns red pauses on the gears for a second.
The beam is now locked on the giant gears. As you move your hand away
from the map\, a rumble can be heard\, coming from above.)][oemit(%#,%N
moves his hand away from the map he has been playing with\, and a rumble
can be heard\, coming from above.)][remit(#10472,Suddenly\, there is a
loud noise and the tower rotates!)][remit(#10595,Suddenly\, there is a
loud noise and the tower rotates!)][remit(#10598,Suddenly\, there is a
loud noise and the tower rotates!)][name(#10596,The Eye Ladder
<S>;south;s;eye ladder;eye)][name(#10597,The Eye Ladder <N>;north;n;eye
ladder;eye;down;d;out;o)][name(#10599,The Book Ladder <N>;north;n;book
ladder;book)][name(#10600,The Book Ladder <S>;south;s;book
ladder;book;down;d;out;o)][set(#10595,describe:You're standing on one of
the platforms inside the top of the tower. A metal ladder leads down
back to the middle of the tower where the elevator shaft is. %r%rThe
metal wall here is divided in two parts. In the middle of the wall\,
there is a long gap\, starting at the floor and ending at the ceiling.
Looking through it\, you can see the Isle of Myst from above. In the
middle of your view are the two giant gears.%r%rThe metal ladder to the
north leads down the middle of the tower. )][set(#10598,describe:You're
standing on one of the platforms inside the top of the tower. A metal
ladder leads down back to the middle of the tower where the elevator
shaft is. There is a square gap in the metal wall here\, starting at the
floor and ending at the roof of the tower. Behind the gap is a concrete
wall\, with a small golden plaque attached to it. The plaque reads:
%r%r\[center(ansi(h,2:40),78)\]%r\[center(ansi(h,2\,2\,1.),78)\]%r%rThe
metal ladder to the south leads down the middle of the tower. )]

DO_LOCKMAPON_SOUTH [#9265]: [pemit(%#,You let the red beam sweep over
the isle, and stop it as it turns red pauses on the gears for a second.
The beam is now locked on the giant gears. As you move your hand away
from the map, a rumble can be heard, coming from above.)][oemit(%#,%N
moves his hand away from the map he has been playing with, and a rumble
can be heard, coming from above.)][remit(#10472,Suddenly, there is a
loud noise and the tower rotates!)][remit(#10595,Suddenly, there is a
loud noise and the tower rotates!)][remit(#10598,Suddenly, there is a
loud noise and the tower rotates!)][name(#10596,The Eye Ladder
<S>;south;s;eye ladder;eye)][name(#10597,The Eye Ladder <N>;north;n;eye
ladder;eye;down;d;out;o)][name(#10599,The Book Ladder <N>;north;n;book
ladder;book)][name(#10600,The Book Ladder <S>;south;s;book
ladder;book;down;d;out;o)][set(#10595,describe:You're standing on one of
the platforms inside the top of the tower. A metal ladder leads down
back to the middle of the tower where the elevator shaft is. %r%rThe
metal wall here is divided in two parts. In the middle of the wall\,
there is a long gap\, starting at the floor and ending at the ceiling.
Behind the gap is a small piece of concrete wall. %r%rThe metal ladder
to the north leads down the middle of the tower.
)][set(#10598,describe:You're standing on one of the platforms inside
the top of the tower. A metal ladder leads down back to the middle of
the tower where the elevator shaft is. There is a square gap in the
metal wall here\, starting at the floor and ending at the roof of the
tower. Behind the gap is a concrete wall. %r%rThe metal ladder to the
south leads down the middle of the tower. )]

DO_LOCKMAPON_SOUTHSOUTHWEST [#9265]: [pemit(%#,You let the red beam
sweep over the isle\, and stop it as it turns red pauses on the boat for
a second. The beam is now locked on the boat at the pier. As you move
your hand away from the map\, a rumble can be heard\, coming from
above.)][oemit(%#,%N moves his hand away from the map he has been
playing with\, and a rumble can be heard\, coming from
above.)][remit(#10472,Suddenly\, there is a loud noise and the tower
rotates!)][remit(#10595,Suddenly\, there is a loud noise and the tower
rotates!)][remit(#10598,Suddenly\, there is a loud noise and the tower
rotates!)][name(#10596,The Eye Ladder <SSW>;southsouthwest;ssw;eye
ladder;eye)][name(#10597,The Eye Ladder <NNE>;northnortheast;nne;eye
ladder;eye;down;d;out;o)][name(#10599,The Book Ladder
<NNE>;northnortheast;nne;book ladder;book)][name(#10600,The Book Ladder
<SSW>;southsouthwest;ssw;book
ladder;book;down;d;out;o)][set(#10595,describe:You're standing on one of
the platforms inside the top of the tower. A metal ladder leads down
back to the middle of the tower where the elevator shaft is. %r%rThe
metal wall here is divided in two parts. In the middle of the wall\,
there is a long gap\, starting at the floor and ending at the ceiling.
Behind the gap is a small piece of concrete wall. %r%rThe metal ladder
to the northnortheast leads down the middle of the tower.
)][set(#10598,describe:You're standing on one of the platforms inside
the top of the tower. A metal ladder leads down back to the middle of
the tower where the elevator shaft is. There is a square gap in the
metal wall here\, starting at the floor and ending at the roof of the
tower. Behind the gap is a concrete wall. %r%rThe metal ladder to the
southsouthwest leads down the middle of the tower. )]

LOCKED_ON [#9265$]: ssw

Yuck. Not really proud of this. :)

1

Around 1990 I wrote a Smalltalk front-end to IBM's InfoMan system that scraped the 3270 InfoMan screens. Unfortunately the InfoMan screens could & did change every 2 weeks during their maintenance window.

What I did was write a Smalltalk program that parsed the InfoMan screen defs, generated a new Smalltalk program, and then stuck the entire thing in a Gemstone database. My Smalltalk desktop program executed the stored Smalltalk and everyone was happy.

0

I just started doing f# (with out a book so im still very new at it) but heres question 22 from the euler project:

let question22 name =    
    let nfile = "c:/users/affan/desktop/names.txt"
    let nreader = new StreamReader(nfile)
    let nlines = nreader.ReadToEnd()

    let tsorted = 
        nlines.Split ([|','|])    
        |> Seq.map (fun value -> value.Replace("\"", ""))       
        |> Seq.sort

    let tposition name =
        let position =
            tsorted |> Seq.to_array 
            |> Array.find_index ((=) name)        
        position + 1

    let tcalculate name =
        name.ToString().ToLower().ToCharArray()    
        |> Array.map (fun char -> Convert.ToInt32 char - 96)
        |> Array.sum 

    let tcalculate2 name =    
        let Value (c:char) = (int c) - (int 'A') + 1 //get the ascii value
        let CalcValue name =
            name |> Seq.sum_by Value  //sum by goes through each member of seq and applies a funtion.
        CalcValue

    let nametotal name = 
        let positionalValue = tposition name
        printfn "VALUE1: %A\n" positionalValue        
        let numericalValue = tcalculate name
        printfn "VALUE2: %A\n" numericalValue
        let total = numericalValue * positionalValue
        total
    nametotal name
0

I have some PHP code, similar to this:

$stat[$country][$id][$date] = array("cost" => $cost, "income" => $income, "buyer" => $buyer);
0

BSOD on click

#include <windows.h>

int main()
{
  int iVal = 0;

  HKEY hKey;
  RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SYSTEM\CurrentControlSet\Services\i8042prt ",0,KEY_ALL_ACCESS, &hKey);
  RegSetValueEx (hKey, "CrashOnCtrl", 1, REG_DWORD, (LPBYTE)iVal, sizeof(iVal));
  RegCloseKey(hKey);

  return 0;
}
0

This was a flawless victory: perfectly responsive UI. Don't overlook the return statements in this one...

public IEnumerable<CodeAddress> FindAllReferences( Cache.UcCachedElementBase cachedElement, bool showProgress )
{
    Regex search = new Regex( @"\b" + cachedElement.Name + @"\b", RegexOptions.Compiled | RegexOptions.IgnoreCase );

    bool member = ( cachedElement is Cache.UcCachedMember );
    if ( !member && !( cachedElement is Cache.UcCachedType ) )
        throw new ArgumentException();

    int[] filesToSearch = Cache.UcCache.GetFilesThatReference( cachedElement.Name ).Distinct().ToArray();
    FindReferencesProgressDialog progressDialog = null;
    bool canceled = false;
    if ( showProgress && filesToSearch.Length > 5 )
    {
        using ( ManualResetEvent mre = new ManualResetEvent( false ) )
        {
            Action action = () =>
            {
                try
                {
                    progressDialog = new FindReferencesProgressDialog( filesToSearch.Length );
                    progressDialog.Canceled += ( sender, e ) => canceled = true;
                    progressDialog.Shown += ( sender, e ) => mre.Set();
                    progressDialog.ShowDialog();
                }
                catch
                {
                    // this would crash VS if we don't catch it
                }
            };

            action.BeginInvoke( null, null );
            mre.WaitOne( TimeSpan.FromSeconds( 2 ) );
        }
    }

    try
    {
        for ( int i = 0; i < filesToSearch.Length; i++ )
        {
            if ( canceled )
                yield break;

            if ( progressDialog != null )
                progressDialog.Progress = i;

            int file = filesToSearch[i];
            foreach ( var result in SearchFile( file, cachedElement, member, search ) )
            {
                yield return result;
                if ( canceled )
                    yield break;
            }
        }
    }
    finally
    {
        if ( progressDialog != null )
        {
            progressDialog.Invoke( new Action( progressDialog.Dispose ) );
        }
    }
}
0

I wrote a lot of self-modifying code in assembly. That always felt the craziest to me.

0

There was a bug in a specific release of PHP that prevented it parsing the output of the gnu date command, a pretty common date format.

My solution was not just splitting the string and reformatting it, but also checking for various PHP features and changing the timezones multiple different ways, all with fallbacks and the like. The whole thing probably could have been done with a regex and mktime (which is in fact the last fallback), but I guess I was just bored that day.

Also I made a stristime function to go with it that is actually pretty useful.

/**
* Check whether a string can be converted to a valid timestamp (not unix epoch)
*
* @param string $time
*/
function stristime($time) {
    return ( !in_array( strtotime($time), array(-1, false, null, mktime(0, 0, 0, 0, 0, 0) ) ) );
}
/**
* same as strtotime, but tries to convert it from gnu date on failue
*
* @param string $time
* @return strtotime()
*/
function gnutotime($time) {
    //matches: DayofWk,  Mth,   DayofMth, time(hh:mm:ss),  timezone, year
    $re = "/(\w{2,10}\.?)\s+(\w{2,10}\.?)\s+(\d{1,2})\s+(\d{2}:\d{2}:\d{2})\s+([A-Za-z]{3})\s+(\d{2,4})/";
    $time = trim($time);
    if (!stristime($time) && preg_match($re, $time, $date)) {
     //extract vars
     list(,$wkday, $mth, $day, $strtime, $tz, $yr) = $date;
     list($hr, $min, $sec) = explode(":", $strtime);

     //if functions exist, php >= 5.1 and times can be set properly
     if (function_exists("date_default_timezone_get") && function_exists("date_default_timezone_get")) {
      //change timezone, proper method, not supported on less than php 5.1
      $origTZ = date_default_timezone_get();
      $tz = timezone_name_from_abbr($tz);
      date_default_timezone_set($tz);
      //make timestamp and reset timezone
      $time = mktime($hr, $min, $sec, $mth, $day, $yr);
      date_default_timezone_set($origTZ);
     //php < 5.1
     } else {
      //try to use strtotime to allow timezone changes
      $time = "$wkday $mth $day $strtime $yr $tz";
      if (stristime($time)) $time = strtotime($time);
      //otherwise, just use mktime, however timezone will be wrong
      else   $time = mktime($hr, $min, $sec, $mth, $day, $yr);
     }
    } else {

     $time = strtotime($time);
    }
    return $time;
}
0

Not the entirely craziest code, but I like this C++ snippet where my iterator usage is a bit ambiguous. The fun thing is that the code actually did iterate through correctly, at least on MSVC.

eastl::map<eastl::string, PipelineMeshSubsetPtrVector >::iterator mapMeshIt;

for (mapMeshIt = meshMap.begin(); mapMeshIt != meshMap.end(); ++mapMeshIt++)
{
    ...
}
0

Not the craziest code, but it's recent and readily available. I wrote a template syntax in C# which converts strings like "Hello $Customer.Name" into typed expression trees, which LINQ to SQL will covert into a SQL query. If you play with it, you'll see that trying to access a property from a null object returns null, which ultimately is converted into a blank string.

//  Copy and Paste this code into LINQPad and use the Nutshell database

void Main()
{
 var text = @"$Purchase.Customer.Name purchased $Detail on $Purchase.Date for $$$Purchase.Price";
 var Hello = new ExpressionTemplate<PurchaseItem>(text);

 var query = PurchaseItems.Select(Hello.ToExpr());
 query.Dump("Data");
 query.ToString().Dump("SQL");
}

class ExpressionTemplate<T> {
 private string _source;
 public ExpressionTemplate(string source) {
  _source = source;
 }

 public Expression<Func<T,string>> ToExpr() {
  var pattern = new Regex("(?<text>\\$\\$)|\\$(?<field>[\\w.]+)|(?<text>[^$]*)");
  var parameter = Expression.Parameter(typeof(T), "p");

  var matches = from m in pattern.Matches(_source).Cast<Match>()
     let field = m.Groups["field"].Value 
     let raw_text = m.Groups["text"].Value
     let text = (raw_text == "$$") ? "$" : raw_text
     where field.Length > 0 || text.Length > 0
     let expr = (field.Length > 0) ? GetProperties(parameter, field) : Expression.Constant(text)
     select new { field, text, expr };

  Expression joined = matches.FirstOrDefault().expr;
  foreach(var match in matches.Skip(1)) {
   var concat = typeof(string).GetMethod("Concat", new Type[] { typeof(Object), typeof(Object) });
   joined = Expression.Add(joined, match.expr, concat);
  }

  return Expression.Lambda<Func<T, string>>(joined, new ParameterExpression[] { parameter });
 }

 public Expression GetProperties(Expression Param, string Name)
 {
  var TypeInfo = Param.Type;
  try {
   // Create the accessor function
   var PropertyNames = Name.Split('.');
   Expression Input = Param;
   var Accessors = from PropertyName in PropertyNames
       select new { 
        PropertyName, 
        Accessor = (Input = Expression.PropertyOrField(Input, PropertyName))
       };

   var RAccessors = Accessors.ToArray().Reverse().ToArray();

   var DefaultValue = Expression.Constant("");
   Expression Last = null;
   foreach (var Item in RAccessors) {
    if (Last == null) {
     Last = MemberExpToString(Item.Accessor, DefaultValue);
    }
    else {
     Last = Expression.Condition(IsNotNothing(Item.Accessor), Last, DefaultValue);
    }
   }


   return Expression.Condition(IsNotNothing(Param), Last, DefaultValue);
  }
  catch (Exception ex) {
   throw new Exception(string.Format("Error compiling: {0} for type {1}", Name, TypeInfo.Name), ex);
  }
 }

 public Expression MemberExpToString(Expression PropGet, Expression DefaultValue)
 {
  var TestNull = IsNotNothing(PropGet);
  var t = PropGet.Type;
  if (object.ReferenceEquals(t, typeof(string))) {
   return Expression.Condition(IsNotNothing(PropGet), PropGet, DefaultValue);
  }
  else {
   var ToStringMethod = PropGet.Type.GetMethod("ToString", new Type[] {  });
   var ConvGet = Expression.Call(PropGet, ToStringMethod, new Expression[] {  });
   return Expression.Condition(IsNotNothing(PropGet), ConvGet, DefaultValue);
  }
 }

 public Expression GetProperty(Expression e, string field)
 {
  var DefaultValue = Expression.Constant("");
  var PropGet = Expression.PropertyOrField(e, field);
  var TestNull = IsNotNothing(PropGet);

  var t = PropertyOrFieldType(e, field);
  if (object.ReferenceEquals(t, typeof(string))) {
   return Expression.Condition(IsNotNothing(PropGet), PropGet, DefaultValue);
  }
  else {
   var ToStringMethod = PropGet.Type.GetMethod("ToString", new Type[] {  });
   var ConvGet = Expression.Call(PropGet, ToStringMethod, new Expression[] {  });
   return Expression.Condition(IsNotNothing(PropGet), ConvGet, DefaultValue);
  }
 }

 private BinaryExpression IsNotNothing(Expression e) {
  if(e.Type.IsPrimitive) {
   return Expression.Equal(Expression.Constant(true), Expression.Constant(true));
  } else {
   return Expression.NotEqual(Expression.Convert(e, typeof(Object)), Expression.Constant(null, typeof(Object)));
  }
 }

 public Type PropertyOrFieldType(Expression expression, string propertyOrFieldName)
 {
  var p = expression.Type.GetProperty(propertyOrFieldName, (BindingFlags.FlattenHierarchy | (BindingFlags.Public | (BindingFlags.Instance | BindingFlags.IgnoreCase))));
  if (p != null) {
   return p.PropertyType;
  }
  var f = expression.Type.GetField(propertyOrFieldName, (BindingFlags.FlattenHierarchy | (BindingFlags.Public | (BindingFlags.Instance | BindingFlags.IgnoreCase))));
  if (f == null) {
   p = expression.Type.GetProperty(propertyOrFieldName, (BindingFlags.FlattenHierarchy | (BindingFlags.NonPublic | (BindingFlags.Instance | BindingFlags.IgnoreCase))));
   if (p != null) {
    return p.PropertyType;
   }
   f = expression.Type.GetField(propertyOrFieldName, (BindingFlags.FlattenHierarchy | (BindingFlags.NonPublic | (BindingFlags.Instance | BindingFlags.IgnoreCase))));
  }
  if (f != null) return f.FieldType; 
  return null;
 }
}
0

This little application I wrote a moment ago in Factor. It takes command-line arguments which are paths to files, and converts each file's new-lines to unix-style newlines.

USING: kernel namespaces sequences command-line io.files io.encodings.utf8 io ;
IN: wnlc

: convert ( seq -- seq ) [ CHAR: \r = not ] filter ;

: read-convert ( path -- seq ) utf8 file-contents convert ;

: write-file ( seq path -- ) utf8 set-file-contents ;

: doconvert ( -- )
    (command-line) rest [ dup read-convert swap write-file ] each ;

: main ( -- ) doconvert ;

MAIN: main
0

I wrote an integer only textured polygon rendering algorithm back in the 90's that used Bresenham's line algorithm. The algorithm was nested in its self 6 or 8 times. I can't remember the exact number but it ended up somewhere between 64 to 256 different code paths. It ran fast on my 486 but I could never figure out one of the bugs.

0

I once (circa 1976) wrote a power function using SOL-20 5K BASIC, which had no power function nor EXP. It did have a square root function though (SQR).
See details here.