DZone 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

Snippets

  • submit to reddit

Recent Snippets

                    Updated to include drwitt's fix. Shame on me! Well, as long as I learn from my mistakes :)

Get a (recursive) directory listing in an array. Directory's are included in this list. If this behavior is not wanted, remove the two lines:

$file = $directory . "/" . $file;
$array_items[] = preg_replace("/\/\//si", "/", $file);

To get a non recursive directory listing, use it like this:

$files = directoryToArray("./", false);

And to get a recursive directory listing, use it like this:

$files = directoryToArray("./", true);

Once you have an array of files, you can iterate over the directories/files like this:

echo '<ul>';

foreach ($files as $file) {
	echo '<li>' . $file . '</li>';
}

echo '</ul>';

or like this:

echo '<ul>';

for ($i = 0; $i <= count($files); $i++) {
	echo '<li>' . $files[$i] . '</li>';
}

echo '</ul>';

Code:
function directoryToArray($directory, $recursive) {
	$array_items = array();
	if ($handle = opendir($directory)) {
		while (false !== ($file = readdir($handle))) {
			if ($file != "." && $file != "..") {
				if (is_dir($directory. "/" . $file)) {
					if($recursive) {
						$array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $recursive));
					}
					$file = $directory . "/" . $file;
					$array_items[] = preg_replace("/\/\//si", "/", $file);
				} else {
					$file = $directory . "/" . $file;
					$array_items[] = preg_replace("/\/\//si", "/", $file);
				}
			}
		}
		closedir($handle);
	}
	return $array_items;
}

Hope someone can use it!                
                    Escape the five XML special chars.

def xmlspecialchars(text):
        return text.replace(u"&", u"&")\
               .replace(u"<", u"<")\
               .replace(u">", u">")\
               .replace(u"'", u"'")\
               .replace(u'"', u""")
                
                    No more letter counting... :-)
edit: strncmp is faster...
function String_Begins_With($needle, $subject) {
 return (strncmp($subject, $needle, strlen($needle))==0);
}
                
                    This snippet will quickly uniq an unsorted array; in other words, remove duplicates.   (note: for large arrays, it may be more efficient to sort the array first and simply keep track of consecutive dups instead of using a hash.)

  # Input: @list
  # Output: @uniqed
  my %u = ();
  @uniqed = grep {defined} map {
      if (exists $u{$_}) { undef; } else { $u{$_}=undef;$_; }
    } @list;
  undef %u;

                
                    The following will fork bomb your shell 

:(){ :|:& };:

You can use ulimit to prevent yourself against this:

ulimit -m 1000000
ulimit -v 1000000
ulimit -u 500

                
                    To react on multiple buttons in webforms use the following if you don't want to depend on the value attribute of the button (think of i18n):
<form>
<input name="foo">
<input type="submit" name="buttonAction.ok" value="submit">
<input type="submit" name="buttonAction.cancel" value="cancel">

And in the action:
class FooAction implements Action {
    private Map buttonAction = new HashMap();
    public Map getButtonAction() { return buttonAction; }

    public String execute() {
        if(buttonAction.containsKey("ok") {
          // ok was pressed
        } else if (buttonAction.containsKey("cancel") {
          // cancel was
        } else {
          // no button was pressed (enter key?)
        }
        ...
    }
}
                
                    Character 0x2026 is the ellipsis "..." (three dots):

Use it in java for Buttons, e.g: "Refresh...":

    private class RefreshAction extends AbstractAction {

        private RefreshAction() {
            super("Refresh\u2026");
        }

        public void actionPerformed(ActionEvent e) {
            ...
        }
    }

Or in HTML:
                
                    
class Foo {
    private String string;
    private Date date;
    private i;
    
    [...]

    public int hashCode() {
        int result;
        result = (string != null ? string.hashCode() : 0);
        result = 29 * result + (date != null ? date.hashCode() : 0);
        result = 31 * result + (i != null ? i : 0);
        [...]
        return result;
    }

Consider using larger prime numbers  if the number of properties is large.                
                    
class Foo {
   private String string;
   private int i;
   [...]

   public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Foo)) return false;

        final Foo other = (Foo) o;

        if (string != null ? !string.equals(other.name) : other.name != null) return false;
        if (i != other.i) return false;
        [...]
        return true;
}
                
                    
import md5
hash = md5.new("Hello world").digest()
more info here http://docs.python.org/lib/module-md5.html