views:

1729

answers:

41

I am sure that at some point we all come up with a way of doing something that make us proud. It may not be something "worthy of production" because of performance or whatever, but you still like the concept. So, SOers, what is that snippet you are most proud of?

[EDIT] I had forgotten to mark it as community wiki...fixed that

+22  A: 
10 PRINT "MY NAME IS TOMMY"
20 GOTO 10

(I was 7 years old)

DrJokepu
oh c'mon you must not have had a little brother! Mine was "Dean is Stupid" on an infinite loop, Commadore 64 style. Boy was he mad he could never figure out how to do that. Thoug adding a semicolon at the end of the pront statement made it more visually effective ;)
Neil N
(Calculon from Futurama): Do you have an extra GOTO 10 line? I said get out of here!
Grant
That was my first program too at 8. I just used "Hello" though, without prior knowledge of "Hello World!" no less.
DavGarcia
+5  A: 

Recursive addition from my entry in the Daily WTF's contest in 2007 (http://thedailywtf.com/Articles/OMGWTF-Finalist-04-TerseCalc.aspx):

/*
 * Fast addition is implemented using a recursive bitwise
 * algorithm, similar to machine addition. This algorithm
 * is pre-optimized so as to not confuse the compiler.
 */
void Addition::operate(VECTOR args) {
    unsigned int addend, other, carry, sum;

    try { args[0]->getValue(); } catch (int result) { addend = result; }
    try { args[1]->getValue(); } catch (int result) { other = result; }
    carry = SHIFT(other & addend);
    sum = other ^ addend;
    if (carry == 0) {
     char buffer[13];
     sprintf(buffer,"%i",sum);
     throw new string(buffer);
    }
    VECTOR v;
    v.push_back(new Number(carry));
    v.push_back(new Number(sum));
    this->operate(v);
    throw new string(ERROR);
}
Welbog
+1, I remember that contest!
Malfist
That is the nastiest piece of code I've seen all day... (Sadly, I've seen worse in the last month.)
epochwolf
A: 

For me it was when I was first learning generics. I wrote a generic method that would pull the specified value from the AppSettings and cast it to the required type. If the desired appsetting was not there (or was not of the expected type), it would return a default value.

Joe
+9  A: 

I'm proud of this because it's been used about 6 or 7 times now.

I wrote a bit of code that would turn an integer into english words.

It took the integer (eg: 1234567) and took 3 digits at a time from the right and fed these into a function that would return it as english: 1 = One, 234 = Two hundred and Thirty Four, 567 = Five hundred and Sixty Seven

And then put it all together as One Million Two hundred and Thirty Four Thousand Five hundred and Sixty Seven.

I've used it in many places in code over the years, from printing cheques to producing insurance documentation.

John
Hehe: this was a problem we had to solve in my _first_ CS course in college. Brings back memories.
Joel Coehoorn
You know, 'and' is generally referred to many mathematical circles as the decimal separator. So that could be misinterpreted as as 1,234,500.67. Just fyi. :)
Robert P
@Robert P: It's a UK/US thing... 'nine-hundred and ninety-nine' is 999 in the UK, and 900.99 in the [email protected]: Some interesting ones in here: http://stackoverflow.com/questions/309884/
jTresidder
So... where's the code?In addition to "and" only being used where the decimal would go, the comma character should be inserted in text wherever it would be in the number.
Andrew Arnott
Oh, and then you need hyphens between the compound words like thirty-four.
Andrew Arnott
In the UK, children are taught to pronounce 900.99 as “nine hundred point nine nine”, which is not ambiguous with “nine hundred and ninety-nine” at all.
Donal Fellows
+2  A: 

I started created a $page[] array on every major .php page (index.php, article.php, etc) that would have entries like:

$page["title"] = "Welcome to my site. This is the index page.";
$page["scripts"] = array("jquery.js","index.js");
$page["styles"] = array("main.css","index.css");

And then include my header:

include("header.php");

Within my header.php I would build the data into markup.

It's more separation than I used to have in my pages. This way I could add unique sets of style-sheets, and scripts for every page without having to compromise my template. The old way was just to have a general title, and ALL style-sheets in my header.php. That was stupid for obvious reasons.

Of lately, I've decided to abandon this style though and go with the MVC Model, for even greater separation of logic/design/markup.

It's nothing impressive, but it was a major step-up from where I was before.

Jonathan Sampson
A: 
putint:
    # 2400
    # 2400 / 10 =  240 |  0
    # z  x y
    pushl %ebp

    movl %esp, %ebp

    movl $0, %ebx
    movl $0, %eax

    movl 8(%ebp), %eax

    movl %eax, dividend

    movl $INT_TEMP_BUFFERT, %ecx

    movl $0, INT_TEMP_SIZE

    movl $0, %edx

    loop_while_have_ints:

     movl dividend, %eax

     movl dividend+4, %edx


                divl divisor
                movl %eax, quotient
                movl %edx, remainder  
     movl %eax, dividend

     # Convert to char
     add $48, remainder

     movb remainder, %dl
     movb %dl, (%ecx)

     inc %ecx

     add $1, INT_TEMP_SIZE

     cmp $0, quotient
     jle putintdone

    jmp loop_while_have_ints

    putintdone:

    add INT_TEMP_SIZE, %ecx   
    # In case someone played with this crap..
    movl $0, %ecx
    movl $0, %ebx
    movl $0, %edx

    movl $BUFFERT, %ebx
    add BUFFERT_POS_WRITING, %ebx

    movl $0, %eax 

    movl INT_TEMP_SIZE, %eax

    sub $1, %eax 

    putintdone_loop:

     # Add in correct order
     cmp $0, INT_TEMP_SIZE
     jle putintcleanup

     movl $INT_TEMP_BUFFERT, %ecx
     add %eax, %ecx

     movb (%ecx), %dl
     movb %dl, (%ebx)

     add $1, BUFFERT_POS_WRITING

     inc %ebx

     sub $1, %eax

     sub $1, INT_TEMP_SIZE 

    jmp putintdone_loop

    putintcleanup:

    movl %ebp, %esp

    popl %ebp

    ret

This code is something i wrote in a course at my university, its a library for handling input and output. This was the hardest part and i swore A LOT over this peice of crap code :) whole source here, manual here

Filip Ekberg
+19  A: 

Not mine, but I love this one in Javascript:

String.prototype.supplant = function (o) {
 return this.replace(/{([^{}]*)}/g,
   function (a, b) {
       var r = o[b];
       return typeof r === 'string' ? r : a;
   }
 );
};

To do things like :

var template =
  '<table border="{border}">' +
  '<tbody><tr><th>Last</th><td>{last}</td></tr>' +
  '<tr><th>First</th><td>{first}</td></tr>' +
  '</tbody></table>';

var data = {
  first: "John",
  last: "Smith",
  border: 2
};

mydiv.innerHTML = template.supplant(data);
Guido
Crockford, 2006 [http://www.json.org/fatfree.html]
Crescent Fresh
+1  A: 

In my college days. I was getting some Exception at some line. What I did is:

try{

}catch(ExceptionIamGetting e){
    Remaining part of the code
}

Everyone was wondering, that they did not even get this thought, which made me proud at that time and laugh everytime I tell someone.

Techmaddy
What would be extra fesh would be to dotry{}catch(ExceptionIamGetting e){//swallow}finally{Remaning part of the code}that way if it DID pass for some reason, it would still work. :p
Joe
ya.. This is also funny. :)
Techmaddy
+1  A: 

I kinda like my Haskell proggie to change a number's base to a 26-number system, represented by the letter a to z:

out x
    | x >= base = foldl (++) [] $ map (\f -> out $ f x base) [mod,div]
    | x < base = digit
    where
        range = ['a'..'z']
        digit = [range!!(fromIntegral x)]
        base = fromIntegral $ length range
flq
+7  A: 

while (1) fork();

tkotitan
Did the sysadmin hunt you down?
Calyth
I love the bash syntax (not mine, 'though): ":(){ :|::"
Joachim Sauer
@saua: I always thought the bash syntax kinda looked like a puking smiley.
Branan
+1  A: 
#ifdef <insert debug predefine here>
void debug_print(const char *format, ...);
#else
#define debug_print sizeof
#endif
MSN
A: 

From 1999, AutoLisp


(setq sNew (substr (apply 'strcat
                          (mapcar '(lambda (x) (strcat "-" x))
                                   (reverse (cons "00"
                                                  (cdr (reverse
                                                  (tokenize (cdr (assoc 1 ed))
                                                            "-"))))))) 2))
crashmstr
(wow ((lisp)(((kinda))has(a((lot of ))))))) brackets))
thomasrutter
Any reason not to mention what this code *does*?
Kevin Bourrillion
A: 

I don't have a specific snipplet in mind, but my Introduction to Cryptography and Computer Algebra courses were some of the pieces of Maple code that I was the most proud of.

Mostly because it was very satisfying to get things working.

Calyth
-1 If you don't have a snippet, you probably shouldn't post.
Outlaw Programmer
+1 no one else is posting snippets ;p
Element
There are tons of snippets, or at least links to code. This response is "I don't have anything to show you but trust me, I do have good code written somewhere."
Outlaw Programmer
Go look around, there are posts with no code too. Why don't you just go and rep down on all of them?I can't post one cause they're not with me at the moment.
Calyth
A: 

After writing awful PHP code for years I finally forced myself to start using MVC. Now it all looks like this on the surface, but the bit I'm proud of is the view class, which is barely 100 lines of code. (I posted it somewhere on this site but can't find it now...)

Ant P.
+1  A: 

I got a Sudoku book for a Christmas a few years ago. After working a few the easier puzzles I sat down at my computer and in 3 hours I had a working solver written, using the same logic rules I was using to solve the puzzles. The next day I updated it to use a few other techniques I figured out and it could solve 98% of what I threw at it. It was pretty quick, too.

I did this having only worked about 6 puzzles total and without looking up any other algorithms, just to see if I could. So of course I was pretty proud of myself when the solver actually worked.

When I look at the code now, it's really (and I mean really) bad. I've since re-written it to be much faster and use a better algorithm rather than hard-coding my own derived rules. But I'm still proud of that old code.

Joel Coehoorn
It's STILL NP Complete you know....
Brian Postow
It's not hard to brute-force recurse it. My newer code finishes in 3.6 seconds for the toughest puzzle I could find doing that + a little sanity filtering on the recursive paths.
Joel Coehoorn
+1  A: 

This is paraphrased a bit since I don't work on the code anymore, but it was roughly...

if(isotopeAnalysis.getCategory() == Category.SNM) {
   message.setPriorty(Priority.CRITICAL);
   message.setText("Special Nuclear Materials Detected");
   message.setResponseType(ResponseType.SHOOT_FIRST_ASK_LATER);
} else if( ... ) {
   //bla blah
}
notifier.send(message);
James Schek
A: 

Years and years ago I wrote a little ASP program to graph simple functions for me.

Spencer Ruport
+5  A: 

I have had one experience in my life where I wrote out a nontrivial programming assignment in a single editor session, compiled it, and it compiled without error and worked perfectly the first time.

It was written in C, for a Computational Linguistics class I took in 1988. It was a program to validate morphological structure of words in a Central American language called Tzotzil. I designed a domain-specific language to describe the rules for valid word structure, and a state machine to apply the rules to input data. And of course all the I/O glue to run it, report results, etc.

It was only 500 lines of C code in six files, but I think it's still pretty remarkable that it worked the first time. That's the only time this has ever happened to me, and I expect it will be the only time in my life.

Bill Karwin
Any time that happens to me, lots of code compiling on the first try, it terrifies me.
Herms
Indeed! I thought at first it was more likely I was in the wrong directory or something, and I was inadvertently compiling some stub version of the code.
Bill Karwin
I love it when that happens!
Ray Hidayat
My only complex code that compiled and worked at first try was an editor that created blinking text-based background like the ones you saw after you exited a DOS game. It was written in Pascal ten-ty years ago. I still remember the feeling, it was heavenly.
Germstorm
A: 

I didn't write it, but I felt a massive sense of achievement when I understood this:

case '[':
 for( b=1,d=c; b && *c; c++ )
  b+=*c=='[', b-=*c==']';
 if(!b) {
  c[-1]=0;
  while( a[p] )
   interpret(d); /* the function this code was found in */
  c[-1]=']';
  break;
 }
case ']':
 puts("UNBALANCED BRACKETS"), exit(0);

I knew what it did, but that for() loop is unnecessarily dense and does way too much in two lines, and it took me forever to understand what the assignments to c[-1] were for. (This is code from the original brainfuck interpreter, for those who are wondering what it's for.)

Chris Lutz
A: 

I did not write it, but I was very happy when I got the double pointer linked list iteration idiom (no, it was before SO :) ).

Arkadiy
A: 

I came up with a neat way of splitting up the code for my website recently: I defined Python classes representing each individual resource that contributes to a page - template files, data files, database queries, etc. - along with functions to link them (the classes, yes) together using boolean short-circuiting logic. It took something like two days just teaching myself about metaclasses to figure out how to do it, but the end result was pretty cool: I just construct the overall structure of my website like this:

handler_tree = 
    handlers.standard.CSInitHandler
    & handlers.standard.CommonDataHandler
    & (
        (
            handlers.standard.DefaultContentTypeHandler
            & handlers.DateHeaderHandler
            & (
                handlers.accounts.LoginHandler
                | handlers.accounts.LogoutHandler
                | handlers.accounts.RegistrationHandler
                | (
                    handlers.standard.AuthenticationHDFProcessor
                    & (
                        handlers.publish.BlogHandler
                        | handlers.standard.TutorialHandler
                        | handlers.standard.ProgramLoader
                        | (
                            URIPrefixFilter.derive(prefix = '/devweb')
                            & TabBarHandler.derive(node = 'devel')
                            & handlers.standard.StandardLoader
                        )
                        | handlers.standard.StandardLoader
                    )
                )
            )
            & handlers.standard.BaseTemplateReader
            & handlers.ETagProcessor
        )
        | handlers.publish.LinkbackHandler
        | handlers.publish.BlogAJAXHandler
    )
    & handlers.standard.RenderingHandler
    & handlers.standard.TidyProcessor
    & handlers.standard.GzipCompressor
    & handlers.standard.WriteHandler
)

So, for example, at the innermost level, the AuthenticationHDFProcessor runs, followed by one of the BlogHandler or the TutorialHandler or the ProgramLoader or, for request URIs beginning with /devweb, the TabBarHandler followed by the StandardLoader, or just the StandardLoader by itself. Anyway, maybe the most satisfying part is that the function that starts it all off is nothing more than

def handler(req):
    hndl = handler_tree(req)
    if hndl is None:
        return apache.HTTP_NOT_FOUND
    hndl.check_auth()
    hndl.cache_control()
    req.set_last_modified()
    status = req.meets_conditions()
    if status != apache.OK:
        return status # probably 304 not modified
    hndl.generate()
    return apache.OK

All the code I wrote to make that possible is something like 1300 lines, though, so I figured I shouldn't post it in full ;-)

David Zaslavsky
+3  A: 
(defun bp-folgers-crystalize ()
"secretly replaces the meta-sytactic variable foo with folgers_crystals"
  (interactive)
  (let (
    (i (point)))
    (beginning-of-buffer)
    (while (search-forward "foo" nil t)
      (replace-match "folgers_crystals" nil t))
    (goto-char i)))

In ELisp.

Brian Postow
+2  A: 

I wrote a variant of the Mersenne Twister random number generator last year, in assembly for a special purpose 80 MHz 24 bit processor in an FPGA. It produces a 24 bit random number in about 50 cycles. According to the specification a random action needed to be taken at every microsecond, so there were very few cycles to spare.

I even tested a few variants to find one with good random properties, using the Diehard tests. I would be even more proud if I had succeeded in checking irreducibility of the corresponding polynomial as well, to ensure a maximal period.

Management would have been satisfied with something a lot worse ...

starblue
+3  A: 
10 X = 0
20 X = X^2 - 1.6
30 PRINT X
40 GOTO 20

This was on a programmable calculator in a maths lesson at school. At first I figured something funny was going on, but then it got really interesting when I plotted the output.

Peter Hilton
I just plotted it. Interested pattern you got there.
Ray Hidayat
What's the starting value for X?
Andrew Szeto
Ah, good point - edit…
Peter Hilton
A: 

I like the perl oneliners. This kind of stuff:

    perl -ane 'if(scalar @F>1){++$c{$F[1]}} END{foreach(sort keys %c){print "$_ $c{$_}\n"}}'
+3  A: 

It'd be hard to pick what I'm the most proud of after all these years (it varies based on the language involved, too) but here's the first thing I put in my .bashrc file on any new machine:

PS1='[$( (((${#PWD} > 38)) && echo "...${PWD: -38}") || echo "\w" )]\$ '

This truncates the leftmost side of my bash prompt so that it never exceeds 42 characters (ellipsis + path + $). It's not rocket-science, but every attempt I'd seen prior was overly complex. I was determined to make my solution a one-liner. (My idea of one-liner is anything less than 80 characters.)

+25  A: 

'Lazy block comments' which I haven't seen anywhere else and came up with it while being ultra lazy.

Some code
/*/
Commented code
//*/
More code

And to uncomment I simply add another "/" effectively commenting out the block comment itself.

Some code
//*/
Uncommented code
//*/
More code
aleemb
I do this all the time too. Dang, I thought I was the only one.
Ooooh this is clever. Would be confusing without syntax highlighting though.
thomasrutter
+5  A: 

I made this C# extension method that adds an indexed ForEach method to the IEnumerable interface. On many occasions I've wanted a reference to an index with foreach, but adding a counter variable was messy. This is much more terse.

public static void ForEach<T>(this IEnumerable<T> self, Action<T, int> action)
{
    int index = 0;
    foreach (var item in self)
    {
        action(item, index);
        index++;
    }
}

Then you can just do:

myList.ForEach((item, index) =>
{
    doSomething(item);
    Console.WriteLine("Item number " + index);
});
Matt Olenik
I do this also. I tend to call it indexedforeach to differentiate
Steve
+6  A: 

In June 08 I needed a function that combined two lists in C#. I remembered Zip from Haskell and so I wrote an iterator to do the same thing.

    public static IEnumerable<TResult> Zip<T1, T2, TResult>(
        this IEnumerable<T1> source1, 
        IEnumerable<T2> source2, 
        Func<T1, T2, TResult> combine)
    {
        IEnumerator<T1> data1 = source1.GetEnumerator();
        IEnumerator<T2> data2 = source2.GetEnumerator();
        while (data1.MoveNext() && data2.MoveNext())
        {
            yield return combine(data1.Current, data2.Current);
        }
    }

I wanted the function to only need existing classes, rather than relying on a tuple class, so I wrote it to take a combining function that would handle the zipping of two items.

Later on .NET 4.0 is announced, and it includes a new function called Zip...

public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>( 
    this IEnumerable<TFirst> first,  
    IEnumerable<TSecond> second,  
    Func<TFirst, TSecond, TResult> func)

I was proud that I'd managed to get the signature the same (with different names).

Cameron MacFarland
A: 

Date-parsing.

When the user can enter the date using almost any separator ( . or / or -) and any length numbers (such as 1 or 12 or 01) for the day, month and year numbers, such that '1/3.9' becomes '01-03-2009' or even '2009-03-01' when handed to the program which requires it.

shortbaldman
A: 
smcameron
A: 

The following patch against Nexuiz, an open source first-person shooter. The patch is an opt-in handicap system (i.e. it makes the game harder for you to win):

  1. You ask for a damage multiplier (at least 1)
  2. Nexuiz remembers it
  3. Whenever you're dealt damage, multiply it by your damage multiplier.

The code is short and to the point :)

Index: data/qcsrc/server/defs.qh
===================================================================
--- data/qcsrc/server/defs.qh   (revision 2761)
+++ data/qcsrc/server/defs.qh   (working copy)
@@ -259,6 +259,7 @@
 .float has_zoomed;

 .float() customizeentityforclient;
+.float cvar_cl_handicap;
 .float cvar_cl_zoomfactor;
 .float cvar_cl_zoomspeed;
 .float cvar_cl_playerdetailreduction;
Index: data/qcsrc/server/miscfunctions.qc
===================================================================
--- data/qcsrc/server/miscfunctions.qc  (revision 2761)
+++ data/qcsrc/server/miscfunctions.qc  (working copy)
@@ -484,6 +484,8 @@
 }
 void GetCvars(float f)
 {
+   GetCvars_handleFloat(f, cvar_cl_handicap, "cl_handicap");
+   self.cvar_cl_handicap = max(self.cvar_cl_handicap, 1.0);
    GetCvars_handleFloat(f, autoswitch, "cl_autoswitch");
    GetCvars_handleFloat(f, cvar_cl_hidewaypoints, "cl_hidewaypoints");
    GetCvars_handleFloat(f, cvar_cl_zoomfactor, "cl_zoomfactor");
Index: data/qcsrc/server/cl_player.qc
===================================================================
--- data/qcsrc/server/cl_player.qc  (revision 2761)
+++ data/qcsrc/server/cl_player.qc  (working copy)
@@ -218,6 +218,8 @@
 {
    local float take, save, waves, sdelay;

+   damage = damage * self.cvar_cl_handicap;
+
    te_blood (hitloc, force, damage);
    if (self.pain_finished < time)  //Don't switch pain sequences like crazy
    {
Jonas Kölker
A: 

Toggling comment blocks:

/**
$someCode = "goes here";
etc();
/*/
$someOther = "code goes here";
andSoOn()
//*/

And then add a single slash to the first line and you get this:

/**/
$someCode = "goes here";
etc();
/*/
$someOther = "code goes here";
andSoOn()
//*/
nickf
A: 

for(int i=0; i<=700;i++) {

print "My younger brother wets the bed every night"; }

I was very young that time and learned this for loop and just to tease my brother i printed this on my computer screen and showed it to every one :-)

and since then it became my favourite code :-)

Dont want to share what he did to me after that ;-) .............

developer
A: 

When displaying a 32 bit hex number that happens to be stored as two 16 bit integers, rather than something like

int msw = 0x1234;
int lsw = 0x5678;

long combined = (msw << 16) | lsw;
printf(" 0x%08X", combined);

.. you can eliminate the shifting and OR'ing and just do

printf(" 0x%04X%04X", msw, lsw);

and let the user's cortex do the combination =)

JustJeff
A: 

Maybe not what I am most proud of, but it's the only thing I can think of at the moment. It's a smarty output filter that allows templates designers to easily use OpenX ads calls that link to multiple zones without assigning OA_zones manually.

function smarty_outputfilter_openx($source, &$smarty) {
  $matches = array();

  if (preg_match_all('/<[^<>]*script.*src.*?=.*?["\'](.*?spcjs.php.*?)["\'].*?\/?>/im', $source, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE)) {
    $scriptIncludeTag = $matches[0][0];

    $matches = array();

    if (preg_match_all('/<[^<>]*?script.*?>.*?OA_show\(([0-9]+)\).*?<.*?\/.*?script[^<>]*>/im', $source, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE)) {
      $OA_ShowCalls = $matches[1];

      $OA_zones = array();

      foreach ($OA_ShowCalls as $key => $call) {
        $rand = "";

        do {
          $rand = sprintf('%x', rand(4026531840, 4294967295));
        } while (array_key_exists($rand, $OA_zones));

        $OA_ShowCalls[$key][2] = $rand;

        $OA_zones[$rand] = (int)$call[0];
      }

      if (count($OA_zones) > 0) {
        $reps = array();
        $offset = 0;

        $reps[] = array
          (
          'len' => 0,
          'offset' => $scriptIncludeTag[1],
          'with' => '<script type="text/javascript">var OA_zones = ' . json_encode($OA_zones) . ';</script>'
          );

        foreach ($OA_ShowCalls as $call) {
          $reps[] = array
            (
            'len' => strlen($call[0]),
            'offset' => $call[1],
            'with' => '\'' . $call[2] . '\''
            );
        }

        foreach ($reps as $rep) {
          $source = substr($source, 0, $rep['offset'] + $offset) . $rep['with'] . substr($source, $rep['offset'] + $offset + $rep['len']);
          $offset += strlen($rep['with']) - $rep['len'];
        }
      }
    }
  }

  return $source;
}
Andrew Moore
A: 

My first ever four lines of code in Javascript, aged 7:

<script>
for(i=1;i<8;i++) {
 if(i != 7) {
  document.write(i + " - My name is James!<br>");
 }else{
  document.write("My name is James and I am " + i + " years old!");
 }
}
</script>

Kept safe on a floppy disk!

James Brooks
A: 

Actually, I do have another piece of code which I am proud of... It's an error handling class which I use in an in-house framework. It allows to trigger errors within classes and return the calling line versus the line where the error has been triggered. It also allows to log the error to the display/email/logfile depending of the server type (Production or Dev). Completely replaces the crappy PHP error handler on anything other than syntax errors.

define('HANDLER_NORMAL', 0);

define('HANDLER_EXIT_FUNCTION', 1);
define('HANDLER_EXIT_CLASS', 2);

require_once ABSPATH . "includes/framework/functions/SiteLog.php";

class ErrorHandler {
    public static $DBfatal = true;
    public static $DBsilent = false;

    public static function custom_error_handler($code, $message, $type = 0) {
     ErrorHandler::handle($code, $message, ErrorHandler::get_backtrace($type));
    }

    public static function php_error_handler($code, $message) {
     ErrorHandler::handle($code, $message, ErrorHandler::get_backtrace(0));
    }

    public static function pear_error_handler($err) {
     if (@is_a($err, 'MDB2_Error')) {
      if(!ErrorHandler::$DBsilent) {
       $level = (ErrorHandler::$DBfatal) ? E_USER_ERROR : E_USER_WARNING;

       if ($err->userinfo) {
        ErrorHandler::log(PEAR_LOG_NOTICE, trim(str_replace(array
         (
         "\n",
         "\r"
         ), array
         (
         ' ',
         ''
         ), $err->userinfo)));
       }

       ErrorHandler::handle($level, $err->message, ErrorHandler::get_backtrace(HANDLER_EXIT_CLASS));
      }
     } else ErrorHandler::handle($err->level, $err->message, ErrorHandler::get_backtrace(HANDLER_EXIT_CLASS));
    }

    private static function get_backtrace($type = 0) {
     $regEx = "/^" . preg_quote(ABSPATH, '/') . '/' . ((server_is_windows()) ? 'i' : '');

     $tmp = debug_backtrace();
     $backtrace = array();

     for ($i = 0; $i < count($tmp); $i++) {
      unset($tmp[$i]['object']);

      if ($tmp[$i]['file']) {
       $tmp[$i]['file'] = str_replace('\\', '/', $tmp[$i]['file']);

       if (preg_match($regEx, $tmp[$i]['file'])) {
        $tmp[$i]['file'] = preg_replace($regEx, '', $tmp[$i]['file']);
       }
      }

      if (count($backtrace) == 0) {
       $isMyHandler = ($tmp[$i]['file'] == 'includes/framework/functions/ErrorHandler.php' || $tmp[$i]['class'] == 'ErrorHandler' || $tmp[$i]['function'] == 'trigger_php_error');
       $isPearError = (!is_null($tmp[$i]['class']) && ($tmp[$i]['class'] == 'PEAR_Error' || is_subclass_of($tmp[$i]['class'], 'PEAR_Error')));
       $isCallback = ($tmp[$i]['function'] == 'call_user_func' && (is_array($tmp[$i]['args'][0]) && $tmp[$i]['args'][0][0] == 'ErrorHandler'));
       $isSomeHandler = (!is_null($tmp[$i]['function']) && stripos($tmp[$i]['function'], 'error') !== FALSE);
       $isLast = ($i == (count($tmp) - 1));

       if(!($isMyHandler || $isPearError || $isCallback || $isSomeHandler) || $isLast) {
        $backtrace[] = $tmp[$i];
       }
      } else {
       $backtrace[] = $tmp[$i];
      }
     }

     switch ($type)
      {
      case HANDLER_EXIT_FUNCTION:
       array_shift($backtrace);
       break;

      case HANDLER_EXIT_CLASS:
       $orgClass = $backtrace[0]['class'];

       if(!is_null($orgClass)) {
        while (count($backtrace) > 1 && $backtrace[1]['class'] == $orgClass) {
         array_shift($backtrace);
        }
       }
       break;
      }

     return $backtrace;
    }

    private static function handle($code, $message, $backtrace) {
     $logPriority = PEAR_LOG_INFO;

     switch ($code)
      {
      case E_ERROR:
      case E_USER_ERROR:
       if ((error_reporting() & E_ERROR) == 0) exit(1);

       $logPriority = PEAR_LOG_ERR;
       break;

      case E_WARNING:
      case E_USER_WARNING:
       if ((error_reporting() & E_WARNING) == 0) return;

       $logPriority = PEAR_LOG_WARNING;
       break;

      case E_USER_NOTICE:
       if ((error_reporting() & E_NOTICE) == 0) return;

       $logPriority = PEAR_LOG_NOTICE;
       break;

      default:
       return;

       break;
      }

     $message = strip_tags($message);
     $logText = $message . ' in ' . $backtrace[0]['file'] . ' at line ' . $backtrace[0]['line'];

     ErrorHandler::log($logPriority, $logText);
     ErrorHandler::write_dump($code, $message, $backtrace);

     if ($code == E_USER_ERROR || $code == E_ERROR) exit(1);
    }

    private static function log($priority, $message) {
     $logger = &SiteLog::get('php_sapi', true, SERVERTYPE == 'PROD');
     $logger->log($message, $priority);
    }

    private static function write_dump($code, $message, $backtrace) {
     global $argv;

     $filename = date('YmdHis');
     $codeName = 'Unknown';

     switch ($code)
      {
      case E_ERROR:
      case E_USER_ERROR:
       $codeName = 'Error';
       break;

      case E_WARNING:
      case E_USER_WARNING:
       $codeName = 'Warning';
       break;

      case E_NOTICE:
      case E_USER_NOTICE:
       $codeName = 'Notice';
       break;

      default:
       break;
      }

     $loginfo['type'] = $codeName;
     $loginfo['msg'] = $message;
     $loginfo['cli'] = ISCLI;

     if ($loginfo['cli']) {
      $loginfo['argv'] = $argv;
     }
     else {
      $loginfo['request'] = @substr($_SERVER['REQUEST_URI'], strlen(RELADDR));
      $loginfo['get'] = $_GET;
      $loginfo['post'] = $_POST;
     }

     $loginfo['backtrace'] = $backtrace;

     $logstr = Spyc::YAMLDump($loginfo, false, 0);

     file_put_contents(sprintf("%sautomation/logs/error_dumps/%s_%s.log", ABSPATH, $filename, sha1($logstr)), $logstr);
    }
}

function trigger_php_error($message, $level, $mode = 0) {
    ErrorHandler::custom_error_handler($level, $message, $mode);
}

ini_set('track_errors', 1);
set_error_handler(array('ErrorHandler', 'php_error_handler'));
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('ErrorHandler', 'pear_error_handler'));
Andrew Moore
A: 

adding a

`#DEFINE if while'

to a friends code and watching him get very frustrated afterwards. Ended up buying him a beer afterwards to remain friends haha.

Kyle_109
+1  A: 

Code to easily support flag operation on Enum in C# :

public static class EnumExtensions
{
    public static T Append<T>(this System.Enum type, T value)
    {
     return (T)(object)(((int)(object)type | (int)(object)value));
    }

    public static T Remove<T>(this System.Enum type, T value)
    {
     return (T)(object)(((int)(object)type & ~(int)(object)value));
    }

    public static bool Has<T>(this System.Enum type, T value)
    {
     return (((int)(object)type & (int)(object)value) == (int)(object)value);
    }

}

For example for this enumeration :

[Flags]
public enum ErrorTypes : int
{
    None = 0,
    MissingPassword = 1,
    MissingUsername = 2,
    PasswordIncorrect = 4
}

These tests pass :

ErrorTypes error = ErrorTypes.MissingPassword;
Assert.IsTrue(error.Has(ErrorTypes.MissingPassword));
error = error.Append(ErrorTypes.MissingUsername);
Assert.IsTrue(error.Has(ErrorTypes.MissingPassword));
Assert.IsTrue(error.Has(ErrorTypes.MissingUsername));
Assert.IsTrue(error.Has(ErrorTypes.MissingPassword.Append(ErrorTypes.MissingUsername)));
error = error.Remove(ErrorTypes.MissingPassword);
Assert.IsFalse(error.Has(ErrorTypes.MissingPassword));
Assert.IsTrue(error.Has(ErrorTypes.MissingUsername));

Not a big deal but I'm proud of that

Nicolas Dorier
Good one, I was waiting for something like this to come along!It is a shame that the bit shift is an ignored operator by the new breed of programmers nowadays.
Binoj Antony
A: 

A Python class called EightfoldPath() (now lost, but simple enough to recreate).

I was re-programming a hydrologic modeling framework by someone else. Each "block" had 8 surrounding blocks (a 3x3 grid). The program could only move water downhill to/from ONE of the surrounding blocks. In the real world, water might be routed to/from multiple blocks (into a ditch, for instance).

Solution: Put each block into a subclassed python dictionary that was indexed using binary arithmetic. Each surrounding block's dictionary key was a factor 2 number (1,2,4,8,16,32, etc.)

Routing water simultaneously was easy.

box = EightfoldPath(8) # initiate a box with 8 surrounding boxes (center of 3x3 grid)
.... # Fill dictionary with references to surrounding boxen.
     # Numbering starts top center and proceeds clockwise in powers of 2
upper_box = box[1] # return box at top center
lower_box = box[16] # return box at bottom center
this_box = box[0] # zero index is this box (center)
down_boxes = box[14] # return all boxes on right (2, 4, & 8) to pour water into
hill_boxes = box[255] # return all boxes surrounding us
up_boxes = box[-224] # NEGATIVE! return all boxes on left (128, 64, 32) to take water FROM.

I could have managed this differently, but changing the spaghetti code to allow multiple box routing was a nightmare compared to just staying with a single "box" (i.e. number) and making THAT work.

JohnMetta