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 (or not, you can keep them private!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

Top Tags and Latest Posts

rails
  old deprecated legacy plugins repository for Rai..
  rails console - add module methods
  Capistrano task to load production data

ruby
  Capistrano task to load production data
  Сортировка массива с горо�..
  Calculate the number of working days between two..

php
  Get remote file size, following redirects (PHP)
  Facebook Status Updater using cURL
  Output all PHP variables

javascript
  UTF8 encode/decode helper library
  Never render the full layout in a Rails view whe..
  Javascript Numbers Only

osx
  Delete all Dreamweaver notes directories
  Install RdbiPgSQL package for R on OS X
  Clear DNS lookup / IP address cache on OS X Tige..

shell
  Latest file to download
  Convert Mac to Unix line endings in VI
  Interactive LAME-ifyer to convert WAV or AIFF fi..

css
  CSS image floats no text wrap
  Cross-browser solution for adding hover border t..
  Standard CSS helpers

mysql
  Limit equivelent for MSSQL
  add mysql symbolic link to OS X MacPorts install..
  mysql on OS X

linux
  grep - search for a string within files within a..
  Human Readable ls and df commands
  postfix - flush queues / logs

lighttpd
  Common Lighttpd rewrite requests
  Lighttpd redirect snippet
  one rails app, multiple domains (via alias domai..

ssh
  SSH dynamic forward (Linux)
  Access subversion repository on Textdrive via ss..
  linux ubuntu ssh login

html
  Standard CSS helpers
  PHP State-Array Generator
  US States Pop-up

Top Tags Alphabetically

actionscript (18)
administration (29)
ajax (23)
apache (27)
applescript (15)
backup (10)
bash (35)
cli (23)
css (44)
delphi (21)
dns (15)
dom (16)
effect (12)
email (16)
expressionengine (23)
fastcgi (14)
flash (16)
freebsd (11)
html (36)
image (21)
java (14)
javascript (96)
lighttpd (43)
linux (44)
mac (30)
mysql (44)
osx (77)
perl (13)
php (100)
prototype (15)
python (18)
rails (113)
recipe (16)
regex (19)
ruby (109)
rubyonrails (17)
shell (74)
sql (26)
ssh (42)
subversion (21)
svn (28)
sysadmin (10)
terminal (23)
textdrive (15)
textpattern (13)
tiger (11)
ubuntu (11)
unix (20)
utility (10)
xhtml (10)

« Newer Snippets
Older Snippets »
849 total  XML / RSS feed 

JBossCache test

// description of your code here

import org.jboss.cache.pojo.PojoCache;
import org.jboss.cache.pojo.PojoCacheFactory;
import org.jboss.cache.Fqn;

public class JDBCCacheTest {

    public static final String CONF_FILE = "jboss-cache.xml";
    public static void main(String[] args) {
        PojoCache cache = PojoCacheFactory.createCache(CONF_FILE, true);
        cache.getCache().removeNode(Fqn.fromString("C"));
        for (int i = 0; i < 100; i++) {
            cache.attach("C/"+ Integer.toString(i), Integer.toString(i));
            System.out.println("added "+i+" dummy node to Jboss cache.");
        }
    }
}

test test

// description of your code here

/**
 * create and maintain metadata for the the events list
 */
function EventsListMetadataFactory() {
    this._metadataForView = {};
}

EventsListMetadataFactory.prototype._className = "EventsListMetadataFactory";
EventsListMetadataFactory.prototype._metadataForView;

EventsListMetadataFactory._instance;

EventsListMetadataFactory.GROUPING_BY_CASE_STATUS = "TRACKING_STATE_TYPE_COL";

EventsListMetadataFactory.getInstance = function() {
    if (!EventsListMetadataFactory._instance) {
        EventsListMetadataFactory._instance = new EventsListMetadataFactory();
    }
    return EventsListMetadataFactory._instance;
}

/**
 * get the metadata
 */
EventsListMetadataFactory.prototype.getMetadata = function() {
    // todo: apply caching
    return this._createMetadata();
}

/**
 * create the metadata
 */
EventsListMetadataFactory.prototype._createMetadata = function() {
    var metadata = this._metadata = new VerixTreeMetadata();

    var columnsMetadata = getUserView().getViewData().getDisplayData().getColumnsMetadata();
    if (columnsMetadata && columnsMetadata.length>0) {
        for (var i=0; i<columnsMetadata.length; i++) {
            var columnMetadata = columnsMetadata[i];

            metadata.addCol(this.getColMetadataByLogicalName(columnMetadata));
        }

    } else {

        metadata.addCol(new EventTitleColMetadata());

        if (getCommonPropertie("eventsList.showPinColumn")=="true") {
            metadata.addCol(new EventNodePropertyColMetadata(getNodePropertyManager().getNodePropertyOfMainPin(),false));
        }

        if (getCommonPropertie("eventsList.showDiscoveryNDateColumn")=="true") {
            metadata.addCol(new EventDiscoveryTimeColMetadata());
        }

        if (getCommonPropertie("eventsList.showStateColumn")=="true") {
            metadata.addCol(new EventStateColMetadata());
        }

        // handle column highlighting for node properties
        var highlightedColumns = getCommonPropertyArray("eventsList.highlightedColumns");
        var highlightedColumnsMap = {};
        if (highlightedColumns) {
            for (var i = 0; i < highlightedColumns.length; i++) {
                highlightedColumnsMap[highlightedColumns[i]] = true;
            }
        }

        // add node properties
        var nodeProperties = getNodePropertyManager().getNodePropertiesByIds(getCommonPropertyArray("eventLists.columns"));
        for (var i = 0; i < nodeProperties.length; i++) {
            var nodeProperty = nodeProperties[i];
            // decide upon highlighting
            var isHighlighted = false;
            if (highlightedColumnsMap[i]) {
                isHighlighted = true;
            }
            // add column
            metadata.addCol(new EventNodePropertyColMetadata(nodeProperty,isHighlighted));
        }

        if (getCommonPropertie("eventsList.showRelatedEventColumn")=="true") {
            metadata.addCol(new EventRelatedColMetadata());
        }
        if (isDebug()) {
            metadata.addCol(new EventTagIconColMetadata());
            metadata.addCol(new EventIdColMetadata());
        }

        // add dimensions
        var dNameKeys = getApplicationCodeTableManager().getKeys("D_NAME");
        dNameKeys.sort(function compare(a, b) {
            return a - b;
        });
        //create map of the required dimensions in regular mode
        var requiredDimensionMap = {};
        var requiredDimensions = getCommonPropertyArray("eventLists.dimensionColumns");
        for (var i = 0; i < requiredDimensions.length; i++){
            requiredDimensionMap[requiredDimensions[i]] = true;
        }
        for (var i = 0; i < dNameKeys.length; i++) {
            var dimensionId = dNameKeys[i];
            if (isDebug() || requiredDimensionMap[dimensionId] != null) {
                metadata.addCol(new EventDimensionColMetadata(dimensionId));
            }
        }
    }

    return metadata;
}

/**
 * create the col meta data according to the passed logical name
 */
EventsListMetadataFactory.prototype.getColMetadataByLogicalName = function(columnMetadata) {
    var logicalName = columnMetadata.logicalName;
    var width = columnMetadata.width;
    var colMetadata = eval("new " + logicalName + "()");
    if (width) {
        colMetadata.setWidth(width)
    }
    return colMetadata;
}

IPSMS Template

// Template for IPSMS metadata (http://www.gov.ie/webstandards/metastandards/index.html)





<meta name="DC.Title" content="">
<meta name="DC.Creator" content="">
<meta name="DC.Subject" content="">
<meta name="DC.Subject" content="">
<meta name="DC.Subject" content="">
<meta name="DC.Subject" content="">

<meta name="DC.Publisher" content="">
<meta name="DC.Date.created" scheme="ISO 8601" content="">
<meta name="DC.Date.modified" scheme="ISO 8601" content="">

<meta name="DC.Identifier" content="">
<meta name="DC.Type" scheme="IPSDT" content="">




<meta name="DC.Title.alternative" content="">
<meta name="DC.Description" content="">
<meta name="DC.Contributor" content="">
<meta name="DC.Type" content="">
<meta name="DC.Format" content="text/html">
<meta name="DC.Source" content="">
<meta name="DC.Language" scheme="ISO 639-1" content="en">

<meta name="DC.Relation" content="">
<meta name="DC.Coverage" content="">
<meta name="DC.Rights" content="© Government of Ireland">





// Sample from Dept of Social Welfare (http://www.welfare.ie/)

<meta name="DC.Title" content="Search page for the website of the Department of Social and Family Affairs, Ireland" />
<meta name="DC.Creator" content="Department of Social and Family Affairs, Ireland" />
<meta name="DC.Subject" content="Irish Government Social Ministry Information Search Facility" />
<meta name="DC.Description" content="This page provides the search facility for the Department of Social and Family 
Affairs website." />
<meta name="DC.Publisher" content="Information Services Section, Department of Social and Family Affairs, Ireland" />
<meta name="DC.Contributor" content="Information Services Section, Department of Social and Family Affairs, Ireland" />
<meta name="DC.Date.created" content="2003-09-19" />
<meta name="DC.Date.modified" content="2004-02-24" />
<meta name="DC.Type" content="index" />
<meta name="DC.Format" content="text/html" />
<meta name="DC.Identifier" content="http://www.welfare.ie/search.html" />
<meta name="DC.Source" content="http://www.welfare.ie" />
<meta name="DC.Language" content="en" />
<meta name="DC.Rights" content="© Department of Social and Family Affairs 2004" />

JS Regex's for sourcecode

Extracted from SyntaxHilighter

        MultiLineCComments : new RegExp('/\\*[\\s\\S]*?\\*/', 'gm'),
        SingleLineCComments : new RegExp('//.*$', 'gm'),
        SingleLinePerlComments : new RegExp('#.*$', 'gm'),
        DoubleQuotedString : new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'),
        SingleQuotedString : new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'", 'g')

CSS image floats no text wrap

Credit goes to:

http://ghettocooler.net/2005/11/13/image-floats-without-the-text-wrap/

.callout {
float:left;
width:275px;
}

.callout h3 {
width:115px;
height:65px;
float:left;
text-indent:-8008px;
background:transparent url(team-report.gif) no-repeat 0 0;
}

.callout * {
width:160px;
float:right;
}

.callout * * {
width:auto;
float:none;
}


PHAWN Interpreter

// description of your code here

import sys
import time

debug = 0
source = []
stack = []
px = 0
py = 0
pd = 1
mode = 0
register = 0

def Initialize():
    
    global source
    global px
    global py
    
    path = raw_input("PHAWN source file: ")
    
    try: file = open(path, "r")
    except IOError:
        print "Failed to open file!"
        return 0
    else: print "File opened successfully!"
    
    for line in file:
        source.append(line.strip("\n"))
        try: px = line.index("$")
        except: continue
        else: py = source.index(line.strip("\n"))
        
    return 1

def Run():
    
    global debug
    global source
    global stack
    global px
    global py
    global pd
    global mode
    global register
    
    try: instruction = source[py][px]
    except:
        print "--- Pointer moved into an unknowned region."
        return 0
    
    if debug == 1: print "Instr:", instruction, " Pos:(", px, ",", py, ")", " Dir:", pd
    
    oy = py
    
    if instruction == "#":
        return 0
    elif instruction == ">":
        if pd > 0:
            stack.append(register)
        elif len(stack) > 0:
            register = stack.pop()
    elif instruction == "<":
        if pd < 0:
            stack.append(register)
        elif len(stack) > 0:
                register = stack.pop()
    elif instruction == "}":
        if pd > 0:
            Input()
        else:
            Output()
    elif instruction == "{":
        if pd < 0:
            Input()
        else:
            Output()
    elif instruction == "/":
        if pd > 0:
            px += 1
            while (source[py][px].isdigit() and source[py][px+1].isdigit()):
                px += 1
    elif instruction == "\\":
        if pd < 0:
            px -= 1
            while (source[py][px].isdigit() and source[py][px-1].isdigit()):
                px -= 1
    elif instruction == "^":
        py -= 1
    elif instruction == "_":
        py += 1
    elif instruction == "~":
        if len(stack) > 1:
            if stack[len(stack) - 1] > stack[len(stack) - 2]:
                py -= 1
            else:
                py += 1
    elif instruction == "+":
        if len(stack) > 1:
            val1 = stack.pop()
            val2 = stack.pop()
            stack.append(val1 + val2)
    elif instruction == "-":
        if len(stack) > 1:
            val1 = stack.pop()
            val2 = stack.pop()
            stack.append(val2 - val1)
    elif instruction == "&":
        mode = 1 - mode
    elif instruction == "%":
        if len(stack) > 1:
            val1 = stack.pop()
            val2 = stack.pop()
            stack.append(val1)
            stack.append(val2)
    elif instruction.isdigit() == True:
        ReadInteger()      
        
    if pd > 0 and px + pd > len(source[py]) - 1:
        pd = -1
    if pd < 0 and px + pd < 0:
        pd = 1
    
    if oy == py:
        px += pd
    
    return 1
    
def Input():
    
    global stack
    
    data = raw_input("Input: ")
    if data.isdigit() == False:
        stack.append(ord(data[0]))
    else:
        stack.append((int(data)))
        
def Output():
    
    global mode
    
    if len(stack) > 0:
        data = stack.pop()
        if mode == 0:
            print data
        else:
            print chr(data)
            
def ReadInteger():
    
    global source
    global stack
    global px
    global py
    global pd
    global register
    
    data = source[py][px]
    
    if pd > 0:
        while (source[py][px + 1].isdigit() == True):
            try:
                px += 1
                data += source[py][px]
            except: break
    else:
        while (source[py][px - 1].isdigit() == True):
            try:
                px -= 1
                data = source[py][px] + data
            except: break
            
    register = int(data)
            
    if px > len(source[py]) - 1:
        px = len(source[py]) - 1
    if px < 0:
        px = 0
        
debug = raw_input("Debug Mode? (1 = Yes / 0 = No) ")
if debug.isdigit() == True: debug = int(debug)

if Initialize() == 1:
    start = time.clock()
    while(Run() == 1):
        if debug == 1:
            print "Stack: ", stack
            raw_input("Pressed  To Continue.")
        else: continue
    print "Executed in ", time.clock() - start, " seconds."
else: print "--- Exited without execution."    
raw_input("Press  to exit.") 

Selected items from a multiple select or checkboxes in VB.net

My co-worker found this code for VB.net that is used to access selected items from check boxes or multiple select boxes. If you've been wondering how to do this, this may help :)

The URL is http://dotnetjunkies.com/weblog/davetrux/archive/2003/11/14/3557.aspx

// The results of a mulitple-select list are also a NameValueCollection
Request.Form.GetValues(i)
// and the individual items are accessed like this:
Request.Form.GetValues(i)(j)

Visual Studio 2005 regex search & replace

// Visual Studio 2005 regex search & replace

find what = data\[{:z}\t{:z}      // :z is number, \t is tab, {} is a tagged expression
replace with = data\[\1\] =\t\2;  // \n is the nth tagged match

Bind AutoRecovery

Actually it can be any services, but I take Bind(named) under the spot. It's "/etc/init.d/named start" because I'm Fedora user.

#!/bin/sh

PSAW=`ps -o "%p" -C named --no-heading`
PSW=`echo $PSAW | cut -d" " -f 1`

if [ -z "$PSW" ]; then
    echo "Named not running!"
    . /etc/init.d/named start
fi

exit

Latest file to download

Perl script using shell command to get(/grep) the lastest file on directory for download.

Just Create .htaccess (DirectoryIndex .latest.cgi) for more automations, so to get the latest files, just point your download link to: "yoursite.com/files/"

#!/usr/bin/perl
#This is .latest.cgi
$|++; my @file = `ls -1 -t -p | grep -v -P '/'`; 
print "Location: $file[0]\n\n";
exit;
« Newer Snippets
Older Snippets »
849 total  XML / RSS feed