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 11-20 of 20 total

Adler32.py

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="21 Dec 2005 - 17 Jul 2006"
__copyright__="Copyright 2006 Andrew Pennebaker"
__license__="GPL"
__version__="0.3"
__URL__="http://snippets.dzone.com/posts/show/2889"

import HashFunction

class Adler32(HashFunction.HashFunction):
	BLOCK_SIZE=1
	DIGEST_SIZE=2

	INIT=0x0001
	SUM_REQ="Sum >= 0"

	BASE=65521

	TEST_DATA="abc"
	TEST_HASH=0x24d0127

	def __init__(self, sum=0x0001):
		self.sum=sum

	def sumValid(self, sum):
		return sum>=0

	def _update(self, b):
		s1=self.sum&0xffff
		s2=(self.sum>>16)&0xffff

		s1=(s1+(b&0xff))%self.BASE
		s2=(s1+s2)%self.BASE

		self.sum=(s2<<16)|s1

	def digest(self):
		return self.sum

	def formatDigest(self):
		return "%02x" % (self.digest())

	def unformatDigest(self, hash):
		return int(hash, 16)

if __name__=="__main__":
	HashFunction.main(Adler32, "Adler32.py")

Math Parser //JavaScript Class


This class is able to parse math expressions and also run user defined functions.

On JavaScript there's the "eval" function, that can do such things well, but this code objective was just to give me fun or a new challenge =)~

[UPDATED CODE AND HELP CAN BE FOUND HERE]

Usage:

x = new MathProcessor;
try{alert(x.parse("1+2-(3*4) + medium(2,3) - frac( 2.2231)"));}
catch(e){alert(e);}


It's possible to add more functions to the class, just add them into the "methods" property ;]

Well, that's it :)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/math-processor [v1.0]

MathProcessor = function(){ //v1.0
    var o = this;
    o.o = {
        "+": function(a, b){ return +a + b; },
        "-": function(a, b){ return a - b; },
        "%": function(a, b){ return a % b; },
        "/": function(a, b){ return a / b; },
        "*": function(a, b){ return a * b; },
        "^": function(a, b){ return Math.pow(a, b); },
        "~": function(a, b){ return Math.sqrt(a, b); }
    };
    o.s = { "^": 3, "~": 3, "*": 2, "/": 2, "%": 1, "+": 0, "-": 0 };
    o.u = {"+": 1, "-": -1}, o.p = {"(": 1, ")": -1};
};

MathProcessor.prototype.parse = function(e){
    for(var n, x, o = [], s = [x = this.RPN(e.replace(/ /g, "").split(""))]; s.length;)
        for((n = s[s.length-1], --s.length); n[2]; o[o.length] = n, s[s.length] = n[3], n = n[2]);
    for(; (n = o.pop()) != undefined; n[0] = this.o[n[0]](isNaN(n[2][0]) ? this.f(n[2][0]) : n[2][0], isNaN(n[3][0]) ? this.f(n[3][0]) : n[3][0]));
    return +x[0];
};

MathProcessor.prototype.methods = {
    "div": function(a, b){ return parseInt(a / b); },
    "frac": function(a){ return a - parseInt(a); },
    "sum": function(n1, n2, n3, n){ for(var r = 0, a, l = (a = arguments).length; l; r += a[--l]); return r; },
    "medium": function(a, b){ return (a + b) / 2; }
};

MathProcessor.prototype.error = function(s){
    throw new Error("MathProcessor: " + (s || "Erro na expressão"));
}

MathProcessor.prototype.RPN = function(e){
    var _, r, c = r = [, , , 0];
    if(e[0] in this.u || !e.unshift("+"))
        for(; e[1] in this.u; e[0] = this.u[e.shift()] * this.u[e[0]] + 1 ? "+" : "-");
    (c[3] = [this.u[e.shift()], c, , 0])[1][0] = "*", (r = [, , c, 0])[2][1] = r;
    (c[2] = this.v(e))[1] = c;
    (!e.length && (r = c)) || (e[0] in this.s && ((c = r)[0] = e.shift(), !e.length && this.error()));
     while(e.length){
        if(e[0] in this.u){
            for(; e[1] in this.u; e[0] = this.u[e.shift()] * this.u[e[0]] + 1 ? "+" : "-");
            (c = c[3] = ["*", c, , 0])[2] = [-1, c, , 0];
        }
        (c[3] = this.v(e))[1] = c;
        e[0] in this.s && (c = this.s[e[0]] > this.s[c[0]] ?
            ((c[3] = (_ = c[3], c[2]))[1][2] = [e.shift(), c, _, 0])[2][1] = c[2]
            : r == c ? (r = [e.shift(), , c, 0])[2][1] = r
            : ((r[2] = (_ = r[2], [e.shift(), r, ,0]))[2] = _)[1] = r[2]);
    }
    return r;
};

MathProcessor.prototype.v = function(e){
    if("0123456789.".indexOf(e[0]) + 1){
        for(var i = -1, l = e.length; ++i < l && "0123456789.".indexOf(e[i]) + 1;);
        return [+e.splice(0,i).join(""), , , 0];
    }
    else if(e[0] == "("){
        for(var i = 0, l = e.length, j = 1; ++i < l && (e[i] in this.p && (j += this.p[e[i]]), j););
        return this.RPN(l = e.splice(0,i), l.shift(), !j && e.shift());
    }
    else{
        var i = 0, c = e[0].toLowerCase();
        if((c >= "a" && c <= "z") || c == "_"){
            while(((c = e[++i].toLowerCase()) >= "a" && c <= "z") || c == "_" || (c >= 0 && c <= 9));
            if(c == "("){
                for(var l = e.length, j = 1; ++i < l && (e[i] in this.p && (j += this.p[e[i]]), j););
                return [e.splice(0,i+1).join(""), , , 0];
            }
        }
    }
    this.error();
}

MathProcessor.prototype.f = function(e){
    var i = 0, n;
    if(((e = e.split(""))[i] >= "a" && e[i] <= "z") || e[i] == "_"){
        while((e[++i] >= "a" && e[i] <= "z") || e[i] == "_" || (e[i] >= 0 && e[i] <= 9));
        if(e[i] == "("){
            !this.methods[n = e.splice(0, i).join("")] && this.error("Função \"" + n + "\" não encontrada"), e.shift();
            for(var a = [], i = -1, j = 1; e[++i] && (e[i] in this.p && (j += this.p[e[i]]), j);)
                j == 1 && e[i] == "," && (a.push(this.parse(e.splice(0, i).join(""))), e.shift(), i = -1);
            a.push(this.parse(e.splice(0,i).join(""))), !j && e.shift();
        }
        return this.methods[n].apply(this, a);
    }
};

uploader.func.php

// Uploader.func.php, called by: uploader();

<?
function uploader($num_of_uploads=1, $file_types_array=array("mp3"), $max_file_size=10485760, $upload_dir="../mp3s/"){
  if(!is_numeric($max_file_size)){
   $max_file_size = 10485760;  // 10MB
  }
  if(!isset($_POST["submitted"])){
   $form = "<form action='".$PHP_SELF."' method='post' enctype='multipart/form-data'>";
   $form .= "<p><span class=artist>Artist:</span><br><input type='text' name='artist' value=\"".htmlentities(stripslashes($row['artist']))."\"></p>";
   $form .= "<p><span class=artist>Song:</span><br><input type='text' name='song' value=\"".htmlentities(stripslashes($row['song']))."\"></p>";
   $form .= "<p><span class=artist>Genre:</span><br><input type='text' name='genre' value=\"".htmlentities(stripslashes($row['genre']))."\"></p>";
   $form .= "<p><span class=artist>MP3:</span><br><input type='hidden' name='submitted' value='TRUE' id='".time()."'><input type='hidden' name='MAX_FILE_SIZE' value='".$max_file_size."'>";
  // Upload files:<br /><input type='hidden' name='submitted' value='TRUE' id='".time()."'><input type='hidden' name='MAX_FILE_SIZE' value='".$max_file_size."'>";
   
   
   for($x=0;$x<$num_of_uploads;$x++){
     $form .= "<input type='file' name='file[]'><br />";
   }
   $form .= "<br />Depending on the size of the MP3, this may take several minutes!<br /><br /><input type='submit' value='Submit Entry'> Valid file type(s): ";
   for($x=0;$x<count($file_types_array);$x++){
     if($x<count($file_types_array)-1){
       $form .= $file_types_array[$x].", ";
     }else{
       $form .= $file_types_array[$x].".";
     }
   }
   $form .= "</form>";
   echo($form);
  }else{
   foreach($_FILES["file"]["error"] as $key => $value){
     if($_FILES["file"]["name"][$key]!=""){
       if($value==UPLOAD_ERR_OK){
       	
       	 $origfilename = $_FILES["file"]["name"][$key];
         $filename = explode(".", $_FILES["file"]["name"][$key]);
         $filenameext = $filename[count($filename)-1];
         unset($filename[count($filename)-1]);
         $filename = implode(".", $filename);
       //  $filename = substr($filename, 0, 15).".".$filenameext;
      $date = date("mdY"); 
  			$time = date("His");
    //  $artist = $_POST['artist'];
    //  $song = $_POST['song'];
      
       $filename = $date.$time.".".$filenameext;
       // $filename = $artist."-".$song.".".$filenameext;
         $file_ext_allow = FALSE;
         for($x=0;$x<count($file_types_array);$x++){
           if($filenameext==$file_types_array[$x]){
             $file_ext_allow = TRUE;
           }
         }
         if($file_ext_allow){
           if($_FILES["file"]["size"][$key]<$max_file_size){
             if(move_uploaded_file($_FILES["file"]["tmp_name"][$key], $upload_dir.$filename)){
             	
             	//	$mp3_upload = $_FILES['mp3_name'];
           	$file_size = $_FILES['file']['size'][$key];
           	
           //	$date = date("mdY"); 
  			//$time = date("His");
  			//$mp3_dir = "mp3";
           	
           $filename = $date.$time.".mp3";
			// Store the orignal file
			//copy($mp3_upload, $mp3_dir."/".$filename);
             	
             	
             	  $query = "INSERT INTO music_archives SET "
  				." artist='".addslashes($_POST['artist'])."'"
				.", song='".addslashes($_POST['song'])."'"
				.", genre='".addslashes($_POST['genre'])."'"
				.", mp3_name='$filename'"
				.", mp3_size='$file_size'"
				.", entry=now()";
  $result = mysql_query($query) or die("Error: ".mysql_error());
         ?>
         
          <script language="JavaScript">

  var count= 0



  function wait() {

    count ++

    if(count == 1 ){

      window.document.location.href='adminadd.php'

    }

    else{

      setTimeout("wait()",1000)

    }

  }



  wait();

  </script>

         
         <?    	
              // echo("File uploaded successfully. - <a href='".$upload_dir.$filename."' target='_blank'>".$filename."</a><br />");
             }else{
               echo($origfilename." was not successfully uploaded<br />");
             }
           }else{
             echo($origfilename." was too big, not uploaded<br />");
           }
         }else{
           echo($origfilename." had an invalid file extension, not uploaded<br />");
         }
       }else{
         echo($origfilename." was not successfully uploaded<br />");
       }
     }
   }
  }
}
?>

ubb function

// description of your code here

Function UBB(str) 

dim i,temp ‘声明�� 

i=1 

temp="" 

do while instr(i,str,"[/"]>=1 ‘如果没有达到字符串的末尾 

if trim(temp)="" then 

temp=ReplaceTest("(\)(\S+)(\ )",str,"<i>$2</i>")  ‘进行UBB代�的模版匹�与替� 

else 

temp=ReplaceTest("(\)(\S+)(\ )",temp,"<i>$2</i>")  ‘进行UBB代�的模版匹�与替� 

end if 

temp=ReplaceTest("(\)(\S+)(\ )",temp,"<b>$2</b>")  ‘进行UBB代�的模版匹�与替� 

temp=ReplaceTest("(\[big])(\S+)(\[/big])",temp,"<big>$2</big>") ‘进行UBB代�的模版匹�与替� 

temp=ReplaceTest("(\[strike])(\S+)(\[/strike])",temp,"<strike>$2</strike>")‘进行UBB代�的模版匹�与替� 

temp=ReplaceTest("(\[sub])(\S+)(\[/sub])",temp,"<sub>$2</sub>")‘进行UBB代�的模版匹�与替� 

temp=ReplaceTest("(\[sup])(\S+)(\[/sup])",temp,"<sup>$2</sup>") 

temp=ReplaceTest("(\[pre])(\S+)(\[/pre])",temp,"<pre>$2</pre>") 

temp=ReplaceTest("(\[u])(\S+)(\[/u])",temp,"<u>$2</u>") 

temp=ReplaceTest("(\[small])(\S+)(\[/small])",temp,"<small>$2</small>") 

temp=ReplaceTest("(\[h1])(\S+)(\[/h1])",temp,"<h1>$2</h1>") 

temp=ReplaceTest("(\[h2])(\S+)(\[/h2])",temp,"<h2>$2</h2>") 

temp=ReplaceTest("(\[h3])(\S+)(\[/h3])",temp,"<h3>$2</h3>") 

temp=ReplaceTest("(\[h4])(\S+)(\[/h4])",temp,"<h4>$2</h4>") 

temp=ReplaceTest("(\[h5])(\S+)(\[/h5])",temp,"<h5>$2</h5>") 

temp=ReplaceTest("(\[h6])(\S+)(\[/h6])",temp,"<h6>$2</h6>") 

temp=ReplaceTest("(\[red])(\S+)(\[/red])",temp,"<font color=red>$2</font>") 

'这里�以增加新的UBB代�的实现模版 

temp=ReplaceTest("(\[email])(\S+)(\[/email])",temp,"<a href=""mailto:$2"" target=_top>$2</a>") 

temp=ReplaceTest("(\[img])(\S+)(\[/img])",temp,"<img src=""$2"">") 

temp=ReplaceTest("(\[url])(\S+)(\[/url])",temp,"<a href=""$2"" target=_top>$2</a>") 

temp=ReplaceTest("(\[#(\S+)])(\S+)(\[/#])",temp,"<font color=$1>$3</font>")‘进行UBB代�的模版匹�与替� 

i=i+1 

loop 

if trim(temp)<>"" then 

UBB=temp ‘将�过UBB代�过滤�的字符串传出 

else 

UBB=str  ‘将�过UBB代�过滤�的字符串传出 

end if 

end function 

Variable-length argument list in PHP

See the document for
func_num_args(), func_get_arg(), and func_get_args().
function foo()
{
   $numargs = func_num_args();
   echo "Number of arguments: $numargs<br />\n";
   if ($numargs >= 2) {
       echo "Second argument is: " . func_get_arg(1) . "<br />\n";
   }
   $arg_list = func_get_args();
   for ($i = 0; $i < $numargs; $i++) {
       echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
   }
}

foo(1, 2, 3);

Basic ruby assert function

A very simple way to add assert capability to function.
def assert
  raise "Assertion failed !" unless yield if $DEBUG
end

Usage :
def aFunc(i)
  assert { i < 10 }
  # ...
end

$DEBUG = true
# Ok.
aFunc(5)
# Raise Assert Exception.
aFunc(15)

$DEBUG = false
# Ok.
aFunc(5)
aFunc(15)

Function Overloader //JavaScript Class


This class allows javascript functions to be overloaded.

[UPDATED CODE AND HELP CAN BE FOUND HERE]




Usage:

myFunction = new Overloader;

myFunction.overload(function(x){
	document.write("Receives: NUMBER<br />");
}, Number);

myFunction.overload(function(x){
	document.write("Receives: STRING<br />");
}, String);

myFunction.overload(function(x,y){
	document.write("Receives: FUNCTION, NUMBER<br />");
}, Function, Number);

myFunction.overload(function(x,y){
	document.write("Receives: NUMBER, STRING<br />");
}, Number, String);

//test...
myFunction(function(){}, 123); //function + number version
myFunction(123); //number version
myFunction("ABC"); //string version
myFunction(123, "ABC"); //number + string version
myFunction({}); /*There's no Object version, so the function will choose the one that has more arguments in common and if there isnt a "best match", it will use the first function that was overloaded...*/



Here's the code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/overloader [v1.0]

Overloader = function(){ //v1.0
	var f = function(args){
		var i, h = "#";
		for(i in args = [].slice.call(arguments))
			h += args[i].constructor;
		if(!(h = f._methods[h])){
			var x, j, k, m = -1;
			for(i in f._methods){
				for(j in args.length > (k = 0, x = f._methods[i][1]).length ? x : args)
					(args[j] instanceof x[j] || args[j].constructor == x[j]) && ++k;
				k > m && (h = f._methods[i], m = k);
			}
		}
		return h ? h[0].apply(f, args) : undefined;
	};
	f._methods = {};
	f.overload = function(f, args){
		this._methods["#" + (args = [].slice.call(arguments, 1)).join("")] = [f, args];
	};
	f.unoverload = function(args){
		return delete this._methods["#" + [].slice.call(arguments).join("")];
	};
	return f;
};

Function.prototype.bench

AOP style benchmark.
Function#bench to attach the benchmark to an existing function.
Function.prototype.bench = function(st){
	var self = this;
	return function(){
		var start = new Date();
		var res = self.apply(this,arguments);
		var end = new Date();
		// to customize
		window.status = st + " : " + (end-start);
		return res;
	}
}
// example
var func = function(){
	var array = [];
	for(var i=0;i<100000;i++){
		array.push(i)
	}
}
// create [benchmark enabled] function
var func_bench = func.bench("create Array(100000)");
func_bench();

you can also
// works in transparent
func = func.bench()

Adding a function to SQLite in python

Copy from David S's code here
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/438802
def _sign(val):
    if val:
        if val > 0: return 1
        else: return -1
    else:
        return val

#get your db connection, conn
conn.create_function("sign", 1, _sign)

...

>>cur = c.conn.cursor()
>>cur.execute("select test, val from test")
>>cur.fetchall()
[(u'a', None)]

>>cur.execute("select sign(test), sign(val), sign(0), sign(-99), sign(99) from test")
>>cur.fetchall()
[(1, None, 0, -1, 1)

php glob_rsort_modtime()

<?php
/**
 FUNCTION: glob_rsort_modtime()
 * Glob reverse sorted by file modification time.
 *
 * Returns an array of files matching the given glob pattern, sorted 
 * by their modification times in descending order.  The array keys
 * hold the filepath and the values hold the mtime.  On error, array
 * will be indexed and contain 'false' and an error message.
 *
 * {@source}
 *
 * @param string $patt Pattern to search, including glob braces.
 * @return array filename => mtime OR false, 'errormsg'.
 */
function glob_rsort_modtime( $patt ) {
    if ( ( $files = @glob($patt, GLOB_BRACE) ) === false ) {
        return array( false, 'Glob error.');
    }
    if ( !count($files) ) {
        return array( false, 'No files found.');
    }
    $rtn = array();
    foreach ( $files as $filename ) {
        $rtn[$filename] = filemtime($filename);
    }
    arsort($rtn);
    reset($rtn);
    return $rtn;
}

$files = glob_rsort_modtime( './*' ) ;
echo'<pre>'.print_r($files, true).'</pre>';
?>