Confess HN: Share your Immoral Hacks, Codes or Tweaks

55 points by dryicerx ↗ HN
You know you weren't suppose to do it. It was a immoral and sinful hack or tweak, but you did it anyways. A goto? A linked list of function pointers? Even committed it? What nasty hacks have you do lately?

69 comments

[ 2.7 ms ] story [ 134 ms ] thread
The cleaner script was written in python working along side the C fastcgi app running atop Apache. I made the C fcgid app spawn the python script as a child. :(
I used a bash script to query a mySQL database because we weren't allowed to use "unapproved" libraries and the last time I tried to get permission to use a CPAN module, it took 8 weeks.

I am ashamed.

I used blocking disk I/O from a theoretically non-blocking event loop.
Getting into the neighbor's WEP. There wasn't even much to it in the end. My desktop didn't have a wireless card so I had to pipe the connection from a half dead laptop I had lying around.
I used a boot to download twitter following pages because it was not allowed to a "non browser" and "non logged user"; it's so bad and some kind of spamming, but i did it any way! :'( :'(
Gotos aren't necessarily bad - for example when you have a large amount of nested loops and need to break out of a certain number of them.
Also good for exception/error handling for languages that don't have that capability built in.

E.g. the SQL script I've been working on today has a number of gotos in it.

What you really want are continuations.
What you really want are continuations.
Pardon my presumed ignorance, but how is that?
You implement your loop macro such that it binds some variable to a continuation, that when invoked, exits the loop. Then when you want to exit the loop, you invoke the continuation.

(Loop exits, exceptions, returns from functions, etc. are all special cases of continuations.)

This is an improvement over something like Perl's "last LABEL" statement, because you can pass the continuation around and exit the loop from anywhere you desire.

Overkill. Something really simple like Common Lisp's block/return-from would do...
...built on top of proper continuation support.
(comment deleted)
this is solved ore cleanly with escape continuation/exceptions.

Perl also provides 'last LABEL', which is handy (lets you break out of any level of nesting).

I guess in a language like C where you can have neither and function calls are slow so the 'return' escape continuation is also unusable there is a reason to use goto for this.

In C/C++ I have longed for a parametrized break statement with value indicating number of nested loops to break at once. I'm sure this goes against some kind of lambda calculus CS ethos though.
I find i can write almost anything never having to use more than two loops.
I wanted to adapt someone's command-line-based program into a library, but it wasn't designed as such. The program was strewn with calls to exit(), and on encountering one of these I would just want to return to the function that called into the library rather than exiting the whole program. So I did a setjmp() prior to calling into it, and used the preprocessor to turn exit() into longjmp().
I don't get it. Why not just remove the exit() and have the function return to where it was called, as standard?
Because, presumably, the program wasn't written as one big main() function, and at least one of the exit()s wasn't in main() — hence the use of longjmp() to jump out of all the layers of function calls back to the caller of the `library'.
A year ago I wrote a half-assed map/reduce in PHP. I partitioned a day's worth of logs across hundreds of gzipped CSV files by key hash, so I could run four reducers (the box has four cores) and each could suck a partition into 1/4 of physical memory.

After about six months of pathological random access (and what I assume to be epic fragmentation), the disk failed. I hope to migrate to our shiny new Hadoop cluster while the replacement disk lasts.

Damnit, most of my best hacks could be considered proprietary, though I seriously doubt any of the companies involved would care. One that I can share:

I architected a game-creation platform so that all the game runtime code was both legal Flash and legal JavaScript, such that the same code could be inserted verbatim in both the JavaScript editor and the Flash compiled version.

Well, here's one that, erhm a friend of mine, did.

dating has moved online, and the key to getting laid is basically to get as many contacts going as you can. It's like a funnel: The more you put in at the top the more comes out at the bottom. The problem of course is that all that initial contact and writing back and forth with potential subjects is somewhat timeconsuming.

Enter the magic of webscraping and hacking.

It's not hard to make a program that will send a standard message to a chosen group of profiles on a dating site based on search criteria. It's not hard to make an interface that let's you do the initial round of communication with the people that respond in an interface that's somewhat more optimised for communicating with a lot of users at the same time. Once you get past the first three or four messages it's time to move on to the more personal aspects of communication. It saves a lot of time, and you only spend time on girls that have actually shown some interest.

Some of my Israeli mates here in London tore through the JDate website selection.

They would have debriefings on successful strategies and accuracy of photo-to-reality. They took turns and had harsh debates about who was first with the hottest ones.

They analysed which girls knew each other so that they could keep disjoint social scenes going at the one time.

It was amazing how many they got through.

They eventually fucked themselves out (and JDate too). They're married now, to a man.

All of them married to the same man?
Obviously I mean 'they are all married to women', but your interpretation is much more amusing.

Too much sex with women leads to marriage with men?? LOL

Sounds marketable, especially if you include a markov chain to grab variables off the scraped page and insert them into your email (ie, "I love #{favorite_band} too!").
I used ctypes to change the base class of Python's GeneratorExit from Exception to BaseException because the official patch didn't make it in until 2.6.

import __builtin__, ctypes

class ImvuGeneratorExit(BaseException): pass

__builtins__['GeneratorExit'] = ImvuGeneratorExit

__builtin__.GeneratorExit = ImvuGeneratorExit

ctypes.c_void_p.in_dll(ctypes.pythonapi, 'PyExc_GeneratorExit').value = id(ImvuGeneratorExit)

#1

Using a negative index on an array in order to get around a signed 16 bit limitation. Just stuck another blank array of the same size in front of it in the memory map and kept going.

For all I know that code is still running :)

It was quite hard to convince the compiler that I wanted to keep the never referenced/read array.

Stupid mainframes and their limits...

#2

In the 386 days you could get a separate co-processor, the 387 for float work (or a weitek if you had the money). The clock line between the two of them was shared but I found out that you could disconnect the clock pin of the 387 and connect it to its own oscillator to overclock it. That way even if the rest of the board could not be overclocked at least the float processor was. By carefully interleaving float and co processor opcodes you could then run a lot faster than you would have been able to otherwise.

I'd love to see a full narrative on #2, that sounds front-page-post worthy. I can't even imagine asynchronously overclocking part of a CPU and still being able to boot the normal OS.
The reason I did it was because I'd been asked by an Amsterdam cultural center (the meervaart) to show the people living near it during a presentation how the situation would change upon expanding the meervaart.

The director (Han Hogeland) had asked me to do the presentation in exchange for - no laughing please - an old French car that I'd wanted to buy of him (Citroen DS).

This made me very motivated to make it work, only my 16 Mhz 386/387 combo really wasn't fast enough to make it work and I didn't have enough dough for a weitek.

So, from desperation this little hack was born. After I found out that it worked (much to my surprise, actually, testing on 20 MHz) I went to a friend who had a computer store and went through several trays of 387's before finding one that would still run at 40 Mhz, and with a large cooling element attached it even stayed reasonably cool (no fan).

The hardest part really was to cut the line on the mb without damage to other lines (this was a multi layer board), eventually I traced the line to a so called 'via' where I could scratch out the connection topside and use the remains of the via to connect the xtal oscillator (in a socket so I could try various frequencies).

The whole thing worked pretty good even if it looked absolutely terrible (imagine an ic socket piggy backed on top of a ttl IC for power and ground, then a wire running to a via next to a severed trace).

It's a pity I didn't make any pictures of the whole thing, I do still have the aerial photographs we bought of the cartographic institution that were digitized to get the layout in to the software, then extrusion by estimated building height created a fairly realistic view of the area.

The shading was quite primitive, framerate about 2-3 frames / second depending on the amount of stuff in the field of view. The graphics board was a 3x5 bits 512x512 pixels affair whose name escapes me atm.

And I got the car :)

...:: Hacking World Cup Tickets for Germany 06 ::...

Australia was a late qualifier for the tournament. The ticket submission was via email. Tickets were allocated on a first email received basis after 09:00. There was a countdown webpage which advertised the time.

--- Preparation

* I telneted to port 25 of the destination and saw via EHLO that the mail server clock was 1 minute faster than advertised on the webpage, giving a start time advantage

* I pre crafted the SMTP message into a text file. This had the sending time as 09:00:01

* Before the day I checked out how long the mail server would keep open any connections without any input (10 minutes)

---

Cometh the day:

* I opened up several telnet sessions to port 25 , 10 minutes before.

* when the time came, I did several EHLO messages to check my session was alive

* I cut'n'pasted my SMTP message into the server

* I closed all my connections (other people were bouncing at this point as the server connection pool was exhausted)

---

I got my tickets.

> the server connection pool was exhausted

Why ? Did you TCP-flooded SMTP server after you connected ?

Have you considered that it might be very simple to track you down since you'd be one of few people who got the tickets that day through this channel ?

The flood was of all of the other Oz applicants hitting SEND on their email clients. That was why I allocated myself two channels before. There were many more than 2 channels available.

I could have DDOSed the server to ensure only I got tickets, but that sounds like an ugly thing to do.

I am writing PHP in Common Lisp, and my codebase is litered with the following:

  (defun make-record (&rest args) ; insert &allow-other-keys ;-)
    (let ((*db-auto-sync* t))
          (object (make-instance 'record args)))
       (when object
         (update-records-from-instance object))))
Both the LET binding of db-auto-sync and the update-records call do the EXACT same thing. However, due to weirdness I don't grok quite yet, the calls to the db driver get in only half the time, even with query caching disabled.

That's for record insertion.

For record update, I have something far more sinster. Every accessor has an :after method with explicit SQL inside. Allow me to explain this: Imagine if you had to write a function that does something as a side-effect everytime an assignment is made! E.g. I have a macro that generates explicit slot serializer for ever accessor; I managed this by wrapping defclass twice and now I program in a weird, session-oriented php-like dialect that's just too fucking brittle.

We will go over it after our first demo :-P

[Edit:

I wrote the following database agnostic routines and I deal with the db strictly through them.

LIST-OBJECTS type

LIST-OBJECTS-WHERE type slot value

FIND-OBJECT type slot value

FIND-OBJECT-WHERE type slot value

UPDATE-OBJECT-WHERE type slot value new-value

DELETE-OBJECT-WHERE type slot value

type is both a Lisp class and SQL table name. Slot and value are used in WHERE clauses, e.g. (select [*] type :where [= slot value])

]

I've always wanted to do sort of the opposite... That is to say, I've always wanted to compile Scheme to PHP. I make the claim that PHP is the web's assembly language. Or, at least it's portable assembly language.
Yeah, "apt-get install php" is much easier to type than "apt-get install sbcl perl ghc python ruby ..."... (The other langauges also all run faster, use less memory, and have more features.)

(And no, you should not compile your app into your frontend webserver. Use FastCGI or a reverse proxy!)

Javascript is the web's assembly language. PHP is the web's BASIC, down to its distribution method. BASIC was typed down from magazines and tutorials, PHP is google, cut and pasted.
UPDATE!

I hope no one was misled by the above false alarm; It seems like I have perfected a problem-solving technique known as "debugging through public embarassment". I just seem to catch agonizing problems the moment I write about them online or tell someone about them.

CLSQL:UPDATE-RECORDS-FROM-INSTANCE should NOT be fucked with; I am not sure how it's supposed to operate, but under MySQL, it will update all the records in a table and set them to the same slot-values as the instance. I.e. all identical records!

The feature I needed is cleanly implemented using WITH-TRANSACTIONS. Again, embarassed and sorry for the confusion.

I created a callback from PowerBuilder to C++ by using some PBNI (like JNI, but for PowerBuilder) trickery. Basically, the PowerBuilder application ran and loaded the external C++ library to handle expensive calculations. From the C++ DLL, I hooked into the PowerBuilder virtual machine, looked up a particular custom object and method, and then used the method as a callback. This wasn't the evil or immoral part though.

The hack was cool, but utterly stupid and pointless (the C++ was used for speed - calling back into PowerBuilder defeated the purpose). The only reason I did it was because the consultant who originally created the C++ DLL managed to convince my boss that the application would run much faster if PowerBuilder supported callbacks. So naturally my boss instructed me to do the impossible. I didn't complain because it seemed like a fun challenge at the time. I didn't tell him that it actually slowed the app down a bit though >:)

Instead of fixing a MySQL query that took minutes, I wrote a mechanize script that logged into the host admin and deleted the query warning.

  // we don't even pretend to work on anything but i386 and LE arm
  const unsigned char c[] = { 0x78, 0x56, 0x34, 0x12 };
  assert(sizeof(int) == 4 && *((int*)c) == 0x12345678);
Could you explain what this does to those of us who're C/C++ challenged ? :)
The software will assert out (bomb, hard) if it's running on a platform which isn't 32-bit (that's the sizeof), and little endian (checked by putting the individual bytes of 0x12345678 into memory in little-endian order, and making sure that when read as an integer, the value is correct).

Except it doesn't even do that well. Traditionally the C "int" type was the largest word size a machine could comfortably work with. But most 64-bit platforms have adopted the "LP64" and "LLP64" conventions - where "int" remains a 32-bit type. One reason to do this is that most values fit comfortably into 32 bits, so a 64-bit "int" wastes memory. Another reason is to keep shoddy code like this running!

(comment deleted)
HTML in a DB Stored Procedure...

Select '<a href="/tickets/ticket/'||i.ticket_id||'">'||lvar_title||'</a><br />' from tickets where ...

because I was to lazy to do it in the proper layer...

I didn't have very many permissions from my sysadmin to do inserts (I'm a BI guy) but I had create temporary table permissions. I needed to take about 5000 system ids with corresponding region identifiers from one system that I could only access via screen. So I wrote an auto hotkey script to screen scrap them all and place them into a notepad file. I then opened the notepad file with excel and added a column of

"union select " 233455 ", " "usa"

"union select " 233455 ", " "canada"

Then puttied into my linux shell, opened emacs and added "create temporary table select 23456 as 'systemid', 'usa' as 'region'

Then pasted the entire csv of union selects. Did my joins, etc... Got the report out on time. I know now that I could have done it with an emacs macro, but just didn't have time to figure it out.

shudder

Signing up for classes at FSU was always a huge pain. The session started at 8am and good classes filled up quickly. If a class was full you had to continually type in the registration number and submit the form to see if anyone had dropped it (there was a lot of turnover as people loaded up their schedule and then called their friends to see what timeslots they were in.)

I had just taught myself php and wrote a curl script with the classes I wanted, and the few timeslots I wanted, in order. After a brief struggle I finally realized I needed to hit port 443 instead of 80 and, voila, my initial class registration was complete. A few were full but it kept hammering the site every 10 seconds and over the next few hours I got emails whenever it successfully registered me with a class.

I actually thought about charging $5 to handle other students' registrations because they hated dragging out of bed at 8am and refreshing their browser for an hour. Somehow I decided the university wouldn't approve....

This is not a very impressive hack compared to the other submissions here. But still here is my 'hack', if you want to call it that way.

When I was doing my graduate course in Computer Engineering, we had to submit loads of assignments each semester for each paper. "Assignment" means something that we should write by hand (print-outs not allowed) on any arbitrary topic provided by the lecturers. There was no problem solving ability required here, it was just answering questions like "What are the features of Java?", "Explain the layers in the TCP/IP model" etc.

As you can assume, this was a rather boring and useless exercise. In the first two years I made some girls from my class to write the assignments (which I am not interested in) for me in exchange for helping them in the computer lab and projects (which they were not much interested in).

By the end of second year, I found out another way to do this. I wrote a program that wrote the assignment for me. Here is how it worked: I will fetch the data from websites like Wikipedia etc and paste it in the program and the program will make it look like my handwriting. I click print and it will print the result to A4 sized papers and I submitted those.

I scanned my handwriting and separated each character and made it look like natural when paragraphs etc were constructed with this program.

The results were so impressive that later when I told this story and showed an assignment to one of my lecturers, he thought that I was just joking!

This hack even though trivial, saved me a lot of time in college.

That sounds like me. I'm still at the 'get girls to write your assignment' stage.

Tell me you're from TN (India)

I am. And I did that too :-)

(Man, girls really like to write, for whatever reason)

This is a lame hack, but I used to play lots of Red Faction on the LAN with my buddies. They where all better than me and I got tired of it so I hacked the config file and changed the power of most of the common weapons and gave myself a homing rocket launcher that you could basically fire and forget. On the open maps you cold fire it up in the air and maybe 30-40 seconds later it would see somebody and you'd get a kill.
Opening port 0 on NT4 would lock up the machine, I wrote a script to do it to all the dial-up ISPs running NT at 18:03