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

                    From: <a href="http://talideon.com/weblog/2005/02/detecting-broken-images-js.cfm">http://talideon.com/weblog/2005/02/detecting-broken-images-js.cfm</a>.

Called in an onload listener to see if an image object has managed to load properly.
function isImageOk(img) {
    // During the onload event, IE correctly identifies any images
    // that weren't downloaded as not complete. Others should too.
    // Gecko-based browsers act like NS4 in that they report this
    // incorrectly: they always return true.
    if (!img.complete) {
        return false;
    }

    // However, they do have two very useful properties: naturalWidth
    // and naturalHeight. These give the true size of the image. If
    // it failed to load, either of these should be zero.
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }

    // No other way of checking: assume it's ok.
    return true;
}
Works fine in IE and Gecko. Not tested (as yet) in Opera or Safari.                
                    Sometimes while I'm editing, I want to convert a region to HTML. I use Perl's HTML::FromText. First I create this script and call it <em>tohtml</em>.

#!/usr/bin/perl

 use HTML::FromText;
 use strict;

 my $text = join '',<>;
 my $html = text2html($text, urls => 1, email => 1, bold=>1, paras => 1, allcaps => 1, tables => 1, bullets => 1, underline=>1);

print $html;

Then from within Emacs, I select the region and do

C-x ESC-1 ESC-| tohtml RET
                
                    use with caution!  This script will copy your pub key to a remote host so you can login or run remote scripts without a password.  IMPORTANT: if you need to run a single script on the remote host, it would be better to authorize a key for just that script.

#!/bin/bash
# kumar.mcmillan -at- farmdev.com

function usage()
{
    echo ""
    echo "Authorizes a host for automatic SSH use by sending your key to the remote host ..."
    echo "Usage: $0 remote_host_to_authorize [username:=defaults to current username]"
    echo ""
}

function cleanup()
{
    if [ -f $TEMP_PUB_KEY_XFER ]
    then
        rm $TEMP_PUB_KEY_XFER
    fi
}

function exit_on_error()
{
    cleanup
    exit 1
}

if [ $# -lt 1 -o "$1" = "-h" -o "$1" = "--help" ]
then
    usage
    exit 0
fi

PUB_KEY=~/.ssh/id_dsa.pub
if [ $# -eq 2 ]; then
    USER=$2
else
    USER=`whoami`
fi
HOST_TO_AUTH=$1
TEMP_PUB_KEY_XFER=/tmp/$USER"_TEMP_KEY"

echo "checking for $PUB_KEY ..."
if [ ! -f $PUB_KEY ]; then
    echo "generating your dsa public key (leave passphrase blank and save to $PUB_KEY when prompted) ..."
    ssh-keygen -t dsa
    if [ $? -ne 0 ]; then
        echo "ssh-keygen failed"
        exit_on_error
    fi
fi
echo "OK"

echo "for the following commands you will be asked to supply your password for $HOST_TO_AUTH :"

echo "copying a temp pub key to $HOST_TO_AUTH ..."
cat $PUB_KEY > $TEMP_PUB_KEY_XFER
chmod 700 $TEMP_PUB_KEY_XFER
echo "OK"

remote_key=`basename $TEMP_PUB_KEY_XFER`
scp $TEMP_PUB_KEY_XFER $USER@$HOST_TO_AUTH:~/$remote_key
if [ $? -ne 0 ]; then
    echo "scp failed"
    exit_on_error
fi
    
echo "authorizing $HOST_TO_AUTH for automatic SSH use ..."
ssh $USER@$HOST_TO_AUTH "cat ~/$remote_key >> ~/.ssh/authorized_keys; rm ~/$remote_key"
if [ $? -ne 0 ]; then
    echo "ssh failed"
    exit_on_error
fi
echo "OK"

cleanup
echo "authorization successful!  you can now login automatically to $HOST_TO_AUTH"
exit 0
                
                    
Object[] array = new Object[]{"12","23","34"};
java.util.List list = Arrays.asList(array);
                
                    If you use vi to edit files, it leaves your backup copies with tildes at the end.  Adding this to your .htaccess file (or virtual host directive in your apache conf) stops people being able to access them.

(Requires mod_rewrite)

RewriteEngine on
RewriteRule  ~$   - [F]

                
                    
require 'digest/sha1'
sha1 = Digest::SHA1.hexdigest('something secret')
                
                    I put this in 
profile.d/
:

 ####################
#limit amount of virtula memory, 
#CPU time and number of processes
#used by normal users.
#
if [ $UID -ge 500 ]
then
    ulimit -m 1000000
    ulimit -v 1000000
    ulimit -u 150
fi
#####################
 

With this script, I am able to survive http://www.bigbold.com/snippets/posts/show/78                
                    A PHP cgi binary compiled with fcgi support

> /usr/local/www/cgi-bin/php5-fcgi -v
PHP 5.0.3 (cgi-fcgi) (built: Dec 30 2004 22:44:32)

Central config in httpd.conf

<IfModule mod_fastcgi.c>
FastCgiIpcDir /usr/local/www/fcgi_ipc/tmp
AddHandler fastcgi-script .fcgi
FastCgiSuexec /usr/local/sbin/suexec
FastCgiConfig -singleThreshold 100 -killInterval 300 -autoUpdate -idle-timeout 240 -pass-header HTTP_AUTHORIZATION
</IfModule>
<Location /php-fastcgi/>
Options ExecCGI        
SetHandler fastcgi-script
</Location>

In a virtual host

SuexecUserGroup ${USER} ${GROUP}
ScriptAlias /php-fastcgi/ ${HOME}/php-fastcgi/ 
AddType application/x-httpd-fastphp .php
Action application/x-httpd-fastphp /php-fastcgi/php5-fcgi

And then the ${HOME}/php-fastcgi/php5-fcgi wrapper	

#!/bin/sh 
PHPRC="/usr/local/etc" 
export PHPRC 
PHP_FCGI_CHILDREN=8 
export PHP_FCGI_CHILDREN 
PHP_FCGI_MAX_REQUESTS=5000 
export PHP_FCGI_MAX_REQUESTS 
exec /usr/local/www/cgi-bin/php5-fcgi 

The PHPRC environment sets the directory where php.ini is to be found                
                    a generic object type thing for perl where you can use setanything and getanything to set and get properties via the AUTOLOAD method.
package thing;

use strict;

sub new {
	my %self;
	my ($class,@rest) = @_;
	unless ($#rest%2) { die "Odd parameter count\n"}
	for (my $k=0; $k<@rest; $k+=2) {
		my $wotsit = lc($rest[$k]);
		$wotsit =~ s/-//;
		$self{$wotsit} = $rest[$k+1];
		}
	bless \%self,$class;
}

sub AUTOLOAD {
        my ($where,$val) = @_;
        our $AUTOLOAD;
        $AUTOLOAD =~ s/.*://;
        my ($dirn,$what) = ($AUTOLOAD =~ /(...)(.*)/);
        if ($dirn eq "get") {
                return $$where{lc($what)};
        } elsif ($dirn eq "set") {
                $$where{lc($what)} = $val;
        }
        return 1;
}

1;


Here's a quick example of usage
use thing

$house = new thing("type","building","rooms",12,"foundations", "yes");

print $house -> gettype();
$house -> settype("tree");
print " " . $house -> gettype();

                
                    Suppose that you have a draggable list as described at http://tool-man.org/examples/sorting.html. To send that list from a form, do

function listToXml(){
	var vList = document.getElementById('phonetic');
        var vLen  = vList.childNodes.length;
	var vXml  = "<ul>";
        for(var i = 0; i < vLen - 1; i++){
	  if(vList.childNodes[i].innerHTML){
	    vXml = vXml + '<li>' + vList.childNodes[i].innerHTML + '</li>';
	  }
        }
	vXml = vXml + '</ul>';
	document.myform.listfield.value = vXml;
}

...

	<ul id="phonetic" class="sortable boxy" style="margin-left: 1em;">
		<li>alpha</li>
		<li>bravo</li>
		<li>charlie</li>
		<li>delta</li>
		<li>echo</li>
		<li>foxtrot</li>
        </ul>

<form name="myform">
<input type="text" name="listfield" value="" size="60">
<input type="button" value="submit2" name="submit2" onClick="listToXml()">
</form>