Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

String equality tester

If you want to test the equality of two strings and don't want the overhead of strcmp(), then this is the function for you.
_Bool strequals(char* a, char* b) {
 if (!a || !b) return 0;
 do {if (*a != *b) return 0; } while (*a++ && *b++);
 return 1;
}

JavaScript String Comparison

// Example use
// if (isSameString(tags, "_none_")) ...

      function isSameString( s1, s2 )
      {
        alert( "s1: " + s1.toString() );
        alert( "s2: " + s2.toString() );

      	if ( s1.toString() == s2.toString() )
        {
      	  return true;
        }
        else
        {
          return false;
        }
      }

Is a value between two other values?

between?: func [
    value bound-1 bound-2
    /exclusive
    /local low-bound high-bound
][
    set [low-bound high-bound] sort reduce [bound-1 bound-2]
    either exclusive [
        all [(value > low-bound) (value < high-bound)]
    ][
        ;-- Inclusive comparison
        all [(value >= low-bound) (value <= high-bound)]
    ]
]

limit - limit a value between boundary values

limit: func [
    "Make sure val falls between lower and upper bounds, inclusive"
    val lower upper
][
    max min val upper lower
]

All Exceptions Created Equal

All exceptions are created equal. But what if you have a very good and pressing reason to serialize one to save it in a database? For instance, you had a collection of checks you wanted to run against some data, and save the results?

Ah, that's easy! serialize() was made for that! So off you trot, you make a few changes to the code, add a blank line here, a blank line there, and suddenly your code can't find the exact matches of the serialized object in the database.

HUH? What's going on? You're the exact same Exception I just threw three minutes ago, and you've sporadically broken?

It took me a while to twig. When you create an exception ($e = new Exception("foo");), it's shiny and new and listens when you do equality comparisions (==).

But things go awry: you throw a new Exception from your filter, catch it, and serialize it. You haven't remembered that...


$a = new Exception("foo");
try {
    throw $a; //Line 1
} catch (Exception $e) {
    throw $a; //Line 10;
}



will result in two difference traces. One saying "I was thrown on on line 1", the other "I was thrown on on line 10"...

Fuck oath, hello stupid coder. You've been wracking your brains wondering why every time you go off and edit a different bit of code it serializes differently; and there you have it.

How the hell do I fix it? Going to __sleep() on the job actually helps.



<?php
class DumbException extends Exception {
    /**
     * Cleanup anything we need before serialisation
     *
     * @return  string[]    An array of member varible names to serialize
     * @see     http://php.planetmirror.com/manual/en/language.oop5.magic.php
     */
    public function __sleep() {
        return array('string','code');
    }

    /**
     * Compare against another DumbException for equality.
     *
     * Since two exceptions can be !== because the trace / line / file
     * information is different, we need to do this.
     */
    public function cmp(DumbException $e) {
        return (serialize($e) == serialize($this));
    }
}

print '<pre>';
$a = new DumbException();
$b = new DumbException();


try {
    try {
        throw $b;
    } catch (Exception $e) {
        throw $a;
    }
} catch (Exception $e) {

    var_dump($a === $b);
    var_dump($a == $b);
    var_dump($b === $e);
    var_dump($b == $e);
    var_dump($a === $e);
    var_dump($a == $e);

    var_dump($b->cmp($e));
    var_dump($a->cmp($e));
}
print '</pre>';
?>

Comparing path.py with os.path

Taken from Simon Willson's blog post.
# with os.path.walk
def delete_backups(arg, dirname, names):
    for name in names:
        if name.endswith('~'):
            os.remove(os.path.join(dirname, name))

os.path.walk(os.environ['HOME'], delete_backups, None)

# with os.path, if (like me) you can never remember how os.path.walk works
def walk_tree_delete_backups(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)
        if os.path.isdir(path):
            walk_tree_delete_backups(path)
        elif name.endswith('~'):
            os.remove(path)

walk_tree_delete_backups(os.environ['HOME'])

# with path
dir = path(os.environ['HOME'])
for f in dir.walk():
    if f.isfile() and f.endswith('~'):
        os.remove(f)

Comparing pygame and pys60

I take the pygame code from here. Then, write my own pys60 part.
# pygame's typical beginning
import pygame
from pygame.locals import *

# pys60
import e32, graphics
from appuifw import *

Setting up the screen
# pygame
window = pygame.display.set_mode((468, 60)) 

# pys60
app.screen = 'full'   # or 'normal', 'large'

Get screen or canvas
# pygame
screen = pygame.display.get_surface() 

# pys60
app.body = canvas = Canvas(None, key.handle_event) 
# you need to create key (a Keyboard instance) before this

Loading image
# pygame
monkey_image = pygame.image.load(file_name)

# pys60
monkey_image = graphics.Image.open(file_name)

Drawing image onto the screen
# pygame
screen.blit(monkey_image, (0,0))
pygame.display.flip()  

# pys60
canvas.blit(monkey_image, target=(0,0))
# we may add a buffer, which will need buffer.blit(image)
# and canvas.blit(buffer) for equivalent steps

Loading and playing sound
# pygame
sound = pygame.mixer.Sound(fullname)
sound.play()

# pys60
import audio
sound = audio.Sound.open(fullname)
sound.play()


For Rect and Sprite, there is no pys60 equivalence yet.
I may write an equivalent class someday.
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS