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 74 total

removeDir //PHP Function

Removes a folder, including its subfolders and files in a efficient way without recursion, returns Boolean.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

function removeFolder($dir){
	if(!is_dir($dir))
		return false;
	for($s = DIRECTORY_SEPARATOR, $stack = array($dir), $emptyDirs = array($dir); $dir = array_pop($stack);){
		if(!($handle = @dir($dir)))
			continue;
		while(false !== $item = $handle->read())
			$item != '.' && $item != '..' && (is_dir($path = $handle->path . $s . $item) ?
			array_push($stack, $path) && array_push($emptyDirs, $path) : unlink($path));
		$handle->close();
	}
	for($i = count($emptyDirs); $i--; rmdir($emptyDirs[$i]));
}

HTTPRequest //JavaScript Class


Class to make remote requests, which can be used on the popular "AJAX".

[UPDATED CODE AND HELP CAN BE FOUND HERE]



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

HTTPRequest = function(){};
with({$: HTTPRequest.prototype}){
	$.isSupported = function(){
		return !!this.getConnection();
	};
	$.events = ["start", "open", "send", "load", "end"];
	$.filter = encodeURIComponent;
	$.getConnection = function(){
		var i, o = [function(){return new ActiveXObject("Msxml2.XMLHTTP");},
		function(){return new ActiveXObject("Microsoft.XMLHTTP");},
		function(){return new XMLHttpRequest;}];
		for(i = o.length; i--;) try{return o[i]();} catch(e){}
		return null;
	};
	$.formatParams = function(params){
		var i, r = [];
		for(i in params) r[r.length] = i + "=" + (this.filter ? this.filter(params[i]) : params[i]);
		return r.join("&");
	};
	$.get = function(url, params, handler, waitResponse){
		return this.request("GET", url + (url.indexOf("?") + 1 ? "&" : "?") + this.formatParams(params), null, handler, null, waitResponse);
	};
	$.post = function(url, params, handler, waitResponse){
		return this.request("POST", url, params = this.formatParams(params), handler, {
			"Connection": "close",
			"Content-Length": params.length,
			"Method": "POST " + url + " HTTP/1.1",
			"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
		}, waitResponse);
	};
	$.request = function(method, url, params, handler, headers, waitResponse){
		var i, o = this.getConnection(), f = handler instanceof Function;
		try{
			o.open(method, url, !waitResponse);
			waitResponse || (o.onreadystatechange = function(){
				var s = $.events[o.readyState];
				f ? handler(o) : s in handler && handler[s](o);
			});
			o.setRequestHeader("HTTP_USER_AGENT", "XMLHttpRequest");
			for(i in headers)
				o.setRequestHeader(i, headers[i]);
			o.send(params);
			waitResponse && (f ? handler(o) : handler["end"] && handler["end"](o));
			return true;
		}
		catch(e){
			return false;
		}
	};
}


Example

<fieldset>
	<legend>HTTPRequest example</legend>
	<input type="button" value="POST request with generic listener and params passage" onclick="genericHandler()" />
	<br /><input type="button" value="GET request with specific listener (binded on load and end)" onclick="specificHandler()" />

<script type="text/javascript">
//<![CDATA[

var r = new HTTPRequest;

function myHandler(o){
	alert("Current event = " + r.events[o.readyState] +
	"\nAvailable \"responseText.length\" = " + o.responseText.length);
}
function genericHandler(){
	r.post(location.href, {param: "abcde", name: "Jonas", site: "http://jsfromhell.com"}, myHandler);
}
function specificHandler(){
	r.get(location.href, null, {"load": myHandler, "end": myHandler});
}
document.write(
	"<br />Supports XMLHTTPRequest = ".bold() + r.isSupported(),
	"<br />Encoded with the default filter (\"encodeURIComponent\") = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"})
);

r.filter = escape;
document.write("<br />Encoded with \"escape\" filter = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));

r.filter = null;
document.write("<br />Encoded with no filtering = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));

//]]>
</script>
</fieldset>

Array.indexOf fix //JavaScript Function

Just an idiot fix to increase the number of my posts =b

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
[].indexOf || (Array.prototype.indexOf = function(v){
       for(var i = this.length; i-- && this[i] !== v;);
       return i;
});


example

var x = [0,1,2,3];

alert(x.indexOf(2));
alert(x.indexOf(4));

Bézier Curve //JavaScript Class


Calculates the points for a bézier curve.

[UPDATED CODE AND HELP CAN BE FOUND HERE]


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

function Bezier(p0, p1, c0, c1){//v1.0
	var o = this;
	o.x0 = p0.x, o.y0 = p0.y, o.x1 = p1.x, o.y1 = p1.y,
	o.cx0 = c0.x, o.cy0 = c0.y, o.cx1 = c1.x, o.cy1 = c1.y;
};
with({$: Bezier, o: Bezier.prototype}){
	$.point = function(x, y){
		return {x: x, y: y};
	};
	o.getCoordinates = function(t){
		var i = 1 - t, x = t * t, y = i * i, a = x * t,
		b = 3 * x * i, c = 3 * t * y, d = y * i, o = this;
		return Bezier.point(a * o.x0 + b * o.cx0 + c * o.cx1 + d * o.x1,
		a * o.y0 + b * o.cy0 + c * o.cy1 + d * o.y1);
	};
	o.plot = function(c){
		var r, x = (x = this.x0 - this.x1) * x, y = (y = this.y0 - this.y1) * y,
		l = l = Math.ceil(Math.sqrt(x + y)), i = l + 1;
		while(c(this.getCoordinates(r = --i / l), r), i);
	};
}



Usage

var bezier = new Bezier(Bezier.point(0, 50), Bezier.point(100, 20), Bezier.point(50, 0), Bezier.point(50, 50));
bezier.plot(function(p, r){
	document.write("x: ", p.x >> 0, " y: ", p.y >> 0, " at ", (r * 100).toFixed(1), "%<br />");
});

Request Adapter //PHP Class

A simple class providing a cute adapter for get/post requests.

Usage
$r = &new Request(POST_METHOD | GET_METHOD);
#$r = &new Request(POST_METHOD); //just post
#$r = &new Request(GET_METHOD); //just get =b

if($r->has('name'))
  echo $r->get('name'), $r->name;

echo $r->get('year', '2006');

if($r->isPosted())
  echo 'This was a post =b';


if($r->isFile('file'))
  if($r->file->isUploaded()){
    echo 'The file was uploaded';
    if($r->file->hasError())
      echo 'And there was an error when uploading';
    else{
      echo 'Moving ' . $r->file->path;
      $r->file->save('uploads/' . $r->file->name)
    }
  }




<?php
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

define('GET_METHOD', 1);
define('POST_METHOD', 2);

class PostedFile{
	var $file, $name, $type, $size, $path, $error;

	function PostedFile(&$f){
		$this->file = &$f;
		$this->name = $f['name'];
		$this->type = $f['type'];
		$this->size = $f['size'];
		$this->path = $f['tmp_name'];
		$this->error = $f['error'];
	}

	function hasError(){
		return $this->isUploaded() && $this->error != UPLOAD_ERR_OK;
	}

	function isUploaded(){
		return $this->error != UPLOAD_ERR_NO_FILE;
	}

	function save($path){
		return @move_uploaded_file($this->path, $path);
	}
}

class Request{
	function &Request($method){
		if(GET_METHOD & $method)
			foreach($_GET as $n=>$v)
				$this->$n = $v;
		if(POST_METHOD & $method){
			foreach($_POST as $n=>$v)
				$this->$n = $v;
			foreach($_FILES as $n=>$v)
				$this->$n = &new PostedFile($v);
		}
		return $this;
	}

	function isFile($name){
		return is_a($this->get($name), 'PostedFile');
	}

	function has($name){
		if(is_array($name)){
			foreach($name as $n)
				if(!isset($this->$n))
					return false;
			return true;
		}
		else
			return isset($this->$name);
	}

	function get($name, $default = null){
		if($this->has($name))
			return $this->$name;
		else
			return $default;
	}

	function isPosted(){
		return $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'];
	}
}
?>

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);
    }
};

BigNumber //JavaScript Class


Offers a extremely high precision level to make mathematical operations. For integers there is no limits and for floating point numbers, the class allows setting the maximum precision.

[UPDATED CODE AND HELP CAN BE FOUND HERE]

The class always returns new instances of BigNumber on the operations, so to the set value of a object, use the "set" method.


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

BigNumber = function(n, p, r){
    var o = this, i;
    if(n instanceof BigNumber){
        for(i in {precision: 0, roundType: 0, _sign: 0, _dec: 0}) o[i] = n[i];
        o._buffer = n._buffer.slice();
        return;
    }
    o.precision = isNaN(p = Math.abs(p)) ? BigNumber.defaultPrecision : p;
    o.roundType = isNaN(r = Math.abs(r)) ? BigNumber.defaultRoundType : r;
    o._sign = (n += "").charAt(0) == "-";
    o._dec = ((n = n.replace(/[^\d.]/g, "").split(".", 2))[0] = n[0].replace(/^0+/, "") || "0").length;
    for(i = (n = o._buffer = (n.join("") || "0").split("")).length; i; n[--i] = +n[i]);
    o.round();
};
with({$: BigNumber, o: BigNumber.prototype}){
    $.ROUND_HALF_EVEN = ($.ROUND_HALF_DOWN = ($.ROUND_HALF_UP = ($.ROUND_FLOOR = ($.ROUND_CEIL = ($.ROUND_DOWN = ($.ROUND_UP = 0) + 1) + 1) + 1) + 1) + 1) + 1;
    $.defaultPrecision = 40;
    $.defaultRoundType = $.ROUND_HALF_UP;
    o.add = function(