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

                    Reading remote data is easy in python.

from urllib import *
url = 'http://example.com/index.html'
html = urlretrieve(url).read()
                
                    I am trying to use the site.
Here's my first program.

print "hello world"
                
                    this is a very basic script for seperating out values and units.  this is helpful for changing values such as style.top or border.

if element.style.top => '15px'
splitUnit( element.style.top ) => [15,'px']

function splitUnit(e)
/*
*	takes a string and seperates 'px or 'em' from it
*
*	could be streamlined to simply seperate the last two characters, but that could cause errors if used sloppily
*/
{
	if( e && ( length = e.search( /px/ ) ) ) {var eUnit = 'px'; var eValue = e.substr( 0, length );}
	else if( e && ( length = e.search( /em/ ) ) ) {var eUnit = 'em'; var eValue = e.substr( 0, length );}
	else return false;
	
	return new Array( eValue, eUnit );
}
                
                    An equivalent of the other find-replace, except it's a one-liner that generates no temp files, and is more flexible:

perl -pi -e 's/find/replace/g' *.txt

Or, to change matching files in a hierarchy:

find . -name '*.txt' |xargs perl -pi -e 's/find/replace/g'
                
                    Assuming you have mod_rewrite and AllowOverride activated, throw this in the .htaccess file for the directory you don't want to be Slashdotted:

RewriteEngine On
RewriteCond %{HTTP_REFERER} ^.*slashdot.*$
RewriteRule .* - [F]

This all assumes the editors actually check the links before posting the story, but this should reasonably mean no-one on Slashdot can link to you, even if it's a bit over the top.                
                    This will output the data from a URL to a file and then display the data in that file.

wget -q -O file "url"; cat file
                
                    a function to convert common used bbcode tags to html... as usually used in message boards and some blog software.

it handles img, email, link, b, u and i tags...

for example
[b]test[/b]
[url=http://blah.com]blah[/url]
will become:
<strong>test</strong>
<a href="http://blah.com" target="_blank">blah</a>

function ubbcode($posting) {
	$posting=eregi_replace("\[img\]([^\[]+)\[/img\]","<img src=\"\\1\" border=\"0\">",$posting);
	$posting=eregi_replace("\[email\]([^\[]+)\[/email\]","<a href=\"mailto:\\1\">\\1</a>",$posting);
	$posting=eregi_replace("\[email=([^\[]+)\]([^\[]+)\[/email\]","<a href=\"mailto:\\1\">\\2</a>",$posting);
	$posting=eregi_replace("\[url=([^\[]+)\]([^\[]+)\[/url\]","<a href=\"\\1\" target=\"_blank\">\\2</a>",$posting);
	$posting=eregi_replace("\[url\]([^\[]+)\[/url\]","<a href=\"\\1\" target=\"_blank\">\\1</a>",$posting);
    $posting=eregi_replace("\[b\]","<strong>",$posting);
    $posting=eregi_replace("\[/b\]","</strong>",$posting);
    $posting=eregi_replace("\[u\]","<u>",$posting);
    $posting=eregi_replace("\[/u\]","</u>",$posting);
    $posting=eregi_replace("\[i\]","<em>",$posting);
    $posting=eregi_replace("\[/i\]","</em>",$posting);

    return $posting;
}
                
                    
find . -type f \! -path "*svn*" -exec dos2unix {} \;

My local dev box is Windows but my prod server is BSD. To make sure all files are in the correct format (LF rather than CRLF), I run this after doing my svn update on the server.

Hat tip: Ryan @ Textdrive.                
                    TrashCanMorph subclass: #SmartTrashCanMorph
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'SqueakRos'

initialize
	"Initialize the receiver's graphics, name, and balloon-help"
	super initialize.
	self image: TrashPicOn;
		 offImage: TrashPic;
		 pressedImage: TrashPicOn.
	self setNameTo: 'SmartTrash'.
	self setBalloonText: 'Drag some morph here . Removes all morph of same class'

acceptDroppingMorph: aMorph event:  evt 
 ActiveWorld submorphs copy do: [:each | (each class  == aMorph class ) ifTrue: [each delete]].

                
                    This needs more work to be complete.  Will it ever be useful?

public class MixinTest
{
  /*
   * The Demo
   */
  interface Chimera extends Lion, Goat, Serpent, Animal {}

  public static void main(String[] args)
  {
    Chimera chimera = (Chimera) MixinFactory.create(Chimera.class, new AnimalImpl());
    System.out.println("The Chimera: ");
    chimera.roar();
    chimera.stomp();
    chimera.slither();
    chimera.action("Sing a song");
  }

  /*
   * The Interfaces
   */
  public interface Lion
  {
    void roar();
  }

  public interface Goat
  {
    void stomp();
  }

  public interface Serpent
  {
    void slither();
  }

  public interface Animal
  {
    void action(String description);
  }

  /*
   * The Implementations
   */
  public static class LionImpl implements Lion
  {
    private Animal animal;

    public LionImpl(Animal animal)
    {
      this.animal = animal;
    }

    public void roar()
    {
      animal.action("Roars with lion head");
    }
  }

  public static class GoatImpl implements Goat
  {
    private Animal animal;

    public GoatImpl(Animal animal)
    {
      this.animal = animal;
    }

    public void stomp()
    {
      animal.action("Stomps with goat foot");
    }
  }

  public static class SerpentImpl implements Serpent
  {
    private Animal animal;

    public SerpentImpl(Animal animal)
    {
      this.animal = animal;
    }

    public void slither()
    {
      animal.action("Slithers with serpent tail");
    }
  }

  public static class AnimalImpl implements Animal
  {
    public void action(String description)
    {
      System.out.println(description);
    }
  }

  /*
   * The Guts
   */
  public static class MixinFactory
  {
    private static class MixinInvocationHandler implements InvocationHandler
    {
      private Map implMap = new HashMap();
      public MixinInvocationHandler(Class clazz, Object core)
      {
        for (int i = 0; i < clazz.getInterfaces().length; i++)
        {
          Class anInterface = clazz.getInterfaces()[i];
          try
          {
            Class delegateClass = Class.forName(anInterface.getName()+"Impl");
            Constructor delegateConstructor = findBestMatchConstrustor(delegateClass, core.getClass());
            if(delegateConstructor != null)
            {
              implMap.put(anInterface, delegateConstructor.newInstance(new Object[] {core}));
            }
            else
            {
              implMap.put(anInterface, core);
            }
          }
          catch(Exception e)
          {
            throw new RuntimeException(e);
          }
        }
      }
      public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
      {
        Object delegate = implMap.get(method.getDeclaringClass());
        return delegate.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes()).invoke(delegate, args);
      }
      private static Constructor findBestMatchConstrustor(Class delegateClass, Class coreClass)
      {
        if(coreClass == null)
        {
          return null;
        }
        try
        {
          return delegateClass.getConstructor(new Class[] {coreClass});
        }
        catch (NoSuchMethodException e)
        {
          Class[] interfaces = coreClass.getInterfaces();
          for (int i = 0; interfaces != null && i < interfaces.length; i++)
          {
            Class interfaceClass = interfaces[i];
            Constructor delegateConstructor = findBestMatchConstrustor(delegateClass, interfaceClass);
            if(delegateConstructor != null)
            {
              return delegateConstructor;
            }
          }
          Constructor delegateConstructor = findBestMatchConstrustor(delegateClass, coreClass.getSuperclass());
          if(delegateConstructor != null)
          {
            return delegateConstructor;
          }
        }
        return null;
      }
    }
    public static Object create(Class clazz, Object core)
    {
      return Proxy.newProxyInstance(clazz.getClassLoader(), new Class [] {clazz}, new MixinInvocationHandler(clazz, core));
    }
  }
}