sTiLL2iLL
sTiLL2iLL
Reputation Top 1%
Heath Dernovich
21 Snippets  (34th place)
Published
1 Channel
Created
2 Channels
Following
476 points  (68th place)
Reputation
Top 5% Publisher
Junior Code Generator
Serious Code Generator
Senior Code Generator
Junior Popular Coder
Serious Popular Coder
Senior Popular Coder
Master Popular Coder
Junior Autobiographer
Senior Autobiographer
Master Autobiographer
Serious Famous Coder
Senior Wise Coder

Recent Snippets See all snippets by sTiLL2iLL

public by sTiLL-iLL  7599  9  4  0

my nonblocking, threadsafe file writer/appender for nodejs. works great with clustered servers, and child processes that write to shared or static file-stores

my nonblocking, threadsafe file writer/appender for nodejs. works great with clustered servers, and child processes that write to shared or static file-stores: scribbles.js
// scribbles.js a nonblocking, threadsafe file writer/appender for nodejs

var fs = require('fs'),
	pth = require('path'),
	cueMngr = {};

function Scribbles(fileNm) {
	this.handle = fileNm;
	this.canWrite = false;
	this.actionsRoster = [];
};

var scribbles = Scribbles.prototype;

scribbles.action = function (err, dta, actionCue) {
	if (err) {
		throw err;
	}
	return actionCue();
}

scribbles.assign = function (func) {
	this.action = func;
	return this;
}

scribbles.scribble = function (dta, func) {
	if (this.canWrite) {
		this.actionCue = dta;
		if (func) {
			this.actionsRoster.push(func);
		}
	} 
	else {
		this.canWrite = true;
		var slf = this,
			taskProxy = {};
		fs.appendFile(this.handle, dta, function (err) {
			function actionCue() {
				slf.canWrite = false;
				if (slf.actionCue) {
					var dta = slf.actionCue;
					slf.scribble(dta);
					slf.actionCue = null;
				}
			}
			slf.action(err, dta, actionCue);
			while (taskProxy = slf.actionsRoster.shift()) {
				return taskProxy(err);
			}
			if (func) {
				return func(err);
			}
		});
	}
	return this;
};

module.exports = function (fil) {
	var nm = pth.resolve(fil);
	return (cueMngr[nm] = cueMngr[nm] || new Scribbles(fil));
}

;

public by cynarasys  488701  9  4  1

AJAX Request

AJAX Request: ajax.php
<script type="text/javascript">
    $('form').submit(function () {
        $('form button').attr("disabled", "disabled");
        $('#loading').fadeIn();
        $('#msj').html('');
        $.post('<?php echo Flight::base_url('contacto'); ?>', $('form').serializeArray(), function (d) {
            $('#loading').fadeOut();
            $('form button').removeAttr('disabled');
            $('#msj').html(d.msj);
            $('html, body').animate({scrollTop: $("#msj").offset().top}, 500);
            if (d.status === true) {
                $('form').slideUp();
            } else {
                $('#captcha').attr('src','<?php echo Flight::base_url('captcha'); ?>?' + Math.random());
            }
        }, 'json');
        return false;
    });
</script>

;

public by HeathDernovich  3276  0  4  2

kacher.js A basic static resource cache module for node.js

kacher.js A basic static resource cache module for node.js: kacher.js

// kacher.js ... this uses my Signals.js event module as a dependency

var signalCaster = require("./signals").Signals,
	fs = require('fs'),
	url = require("url"),
	path = require("path"),
	config = {
		cache: [], 
		cachedFilesMaximum: function (maxFiles) {
			var f = maxFiles || 500;
			return f;
		},
		cacheInterval: function (interval) {
			var v = interval || 1550; // 1/2 hour
			return v;
		}, 
		mimeTypes: {
			".txt": "text/plain",
			".css": "text/css",
			".js": "text/javascript",
			".htm": "text/html",
			".html": "text/html",
			".jpeg": "image/jpeg",
			".jpg": "image/jpeg",
			".png": "image/png",
			".gif": "image/gif",
			".ico": "image/x-icon",
			".xml": "text/xml",
			".rss": "application/rss+xml",
			".json": "application/json",
			".zip": "application/zip, application/octet-stream",
			".rar": "application/x-rar-compressed, application/octet-stream",
			".exe": "application/octet-stream"
	  	}
};
 
function strt(interval, fileMax) {
	config.cacheInterval(interval);
	config.cachedFilesMaximum(fileMax);
	setInterval(function(){
		for (var pth in config.cache) {
			performCacheAssessment(pth);
		}
	}, config.cacheInterval());
}
 
function addToCache(fPth, dta){
    if(config.cache.length < config.cachedFilesMaximum()) {
        config.cache[fPth] = {data:dta, mtime:0};
    }
	return;
}
 
function performCacheAssessment(pth) {
    fs.stat(pth, function(err, sts){   
        if(!err){
            if(config.cache[pth].mtime != sts.mtime.getTime()){
                fs.readFile(pth, function(err, dta){
                    if(!err){
                        config.cache[pth].data = dta;
                        config.cache[pth].mtime = sts.mtime.getTime();
                    }
                });
            }    
        }
    });
    return;
}
 
// the srv method is passed to the caller when "startCache" is called. That way, serving the file can still -
// be explicitly invoked by the caller to issue the response, but all the cache mechanics are abstracted away.
 
function serve(pnm, request, response) {
	var fn =  path.basename(pnm),
	    xt = path.extname(request.url),
	    dn = path.dirname(request.url),
	    fPth = path.join(__dirname+dn, fn);
	
	if(config.cache[fPth] !== undefined) {
	    response.writeHead(200, { "Content-Type": config.mimeTypes[xt] });
		response.end(config.cache[fPth].data);
		signalCaster.signal("FileServed_Cache", fPth + ": served from the cache...");
		return;
	} 
	else {
		fs.readFile(fPth, function(err, dta){
			if(!err){
				addToCache(fPth, dta, config.mimeTypes[xt]);
				signalCaster.signal("FileServed_Disk", fPth + ": served from the disk...");
				response.writeHead(200, {"Content-Type":config.mimeTypes[xt]});
				response.end(dta);
				signalCaster.signal("FileCached", fPth + ": placed in cache...");
			}
			else{
				response.writeHead(404, {"Content-Type": "text/html"});
				response.end("file aint here... Sorry you suck.")
				console.log(err);
			}
		});
		return;
	}
}
 
exports.startCache = function(i, m) {
	strt(i,m);
	return serve;
}


;

public by HeathDernovich  2106  0  4  1

Another version of my "Signals" event system.

Another version of my "Signals" event system.: SignalsV2.js

// SignalsV2.js

(function () {
	
	'use strict';
	
	function Signals () {};
	var exports = this,
		signalsMap = {},
		_signalRtnVal_ = {},
		signals = Signals.prototype;
  
	function isAry(obj) {
		return (obj.constructor === Array);
	};
	
	function _setSignalOnceRV (val) {
		_signalRtnVal_ = val;
		return this;
	};
	
	function _getSignalOnceRV () {
		if (_signalRtnVal_) {
			return _signalRtnVal_;
		}
		else {
			return true;
		}
	};
		
	function wen(nam, func) {
		if (!signalsMap) {
			signalsMap = {};
		}
		if (!signalsMap[nam]) {
			signalsMap[nam] = func;
		} 
		else if (isAry(signalsMap[nam])) {
			signalsMap[nam].push(func);
		} 
		else {
			signalsMap[nam] = [signalsMap[nam], func];
		}	
		return this;
	};
	  
	signals.signaled = function(nam, func) {
		return wen(nam, function(evnt){
			return func(evnt);
		});
	};

	signals.dropReceivers = function (nam) {
		if (!nam) {
			signalsMap = {};
			return this;
		}
		if (signalsMap && signalsMap[nam]) {
			signalsMap[nam] = null;
		}
		return this;
	};
	  
	signals.receiverObjects = function (nam) {
		var recvrLst = this.receivers(nam), rspns;	
		if (isAry(recvrLst)) {
			rspns = {};
			rspns[nam] = recvrLst;
		}	
		return rspns || recvrLst;
	};
	  
	signals.receivers = function (nam) {
		if (!signalsMap) {
			signalsMap = {};
		}
		if (!signalsMap[nam]) {
			signalsMap[nam] = [];
		}
		if (!isAry(signalsMap[nam])) {
			signalsMap[nam] = [signalsMap[nam]];
		}
		return signalsMap[nam];
	};
		
	signals.addReceiver = function(nam, func) {
		return wen(nam, function(evnt){
			return func(evnt);
		});
	};
	
	signals.signaledOnce = function (nam, func) {
		var slf = this;
		function onit () {
			slf.dropReceiver(nam, wen);
			func.apply(this, args);
		};
		wen.receiver = func;
		this.onit(nam, wen);	
		return this;
	};
	
	signals.receiveOnce = function(nam, func) {
		return signaledOnce(nam, function(evnt) {
			return func(evnt);
		});
	};

	signals.dropReceiver = function (nam, func) {
		if (signalsMap && signalsMap[nam]) {
			var sigLst = signalsMap[nam];	
			if (isAry(sigLst)) {
				var idx = -1;
				for (var i = 0, l = sigLst.length; i < l; i++) {
					if (sigLst[i] === func || (sigLst[i].receiver && sigLst[i].receiver === func)) {
						idx = i;
						break;
					}
				}
				if (idx < 0) {
					return this;
				}
				sigLst.splice(idx, 1);
				if (!sigLst.length) {
					delete signalsMap[nam];
				}
			} 
			else if (sigLst === func || (sigLst.receiver && sigLst.receiver === func)) {
				delete signalsMap[nam];
			}
		}
		return this;
	};
	 
	signals.signal = function (nam, args) {
		var recvrLst = this.receiverObjects(nam),
		k, recvr, i, rspns;
		for (k in recvrLst ) {
			if (recvrLst.hasOwnProperty(k)) {
				i = recvrLst[k].length;		
				while (i--) {
					recvr = recvrLst[k][i];
					if (recvr.signaledOnce === true) {
						this.dropReceiver(nam, recvr);
					}	
					rspns = recvr.call(this, args || []);
					if (rspns === _getSignalOnceRV()) {
						this.dropReceiver(nam, recvr);
					}
				}
			}
		}
		return this;
	};

	if (typeof module === 'object' && module.exports) {
		module.exports = Signals;
	}
	else if (typeof define === 'function' && define.amd) {
		define(function () {
			return Signals;
		});
	}
	else {
		exports.Signals = Signals;
	}
	
}.call(this));

;

public by HeathDernovich  3781  0  4  1

Signals.js... A fast and efficient event system in javascript.

Signals.js... A fast and efficient event system in javascript.: Signals.js
 // SignalsBest2.js   8;]
    
    var Signals = (function() {
        'use strict';
        var sigCache = {}, singleRtnVal = false, 
        received = function(eventName, func) {
            return wen(eventName, function(evnt) {
                return func(evnt);
            });
        }, 
        dropReceivers = function(eventName, func) {
            if (eventName && func && typeof func === "function") {
		    dropReceiver(eventName, func);
		    return this;
	        }
            if (!eventName) {
                sigCache = {};
                return this;
            }
            if (sigCache && sigCache[eventName]) {
                sigCache[eventName] = null;
            }
            return this;
        }, 
        setSingleRV = function(val) {
            singleRtnVal = val;
            return this;
        }, 
        getSingleRV = function() {
            if (receivers.hasOwnProperty('singleRtnVal')) {
                return singleRtnVal;
            } 
            else {
                return true;
            }
        }, 
        dropReceiver = function(eventName, func) {
            if (sigCache && sigCache[eventName]) {
                var sigLst = sigCache[eventName];
                if (isAry(sigLst)) {
                    var idx = -1;
                    for (var i = 0, l = sigLst.length; i < l; i++) {
                        if (sigLst[i] === func || (sigLst[i].receiver && sigLst[i].receiver === func)) {
                            idx = i;
                            break;
                        }
                    }
                    if (idx < 0) {
                        return this;
                    }
                    sigLst.splice(idx, 1);
                    if (!sigLst.length) {
                        delete sigCache[eventName];
                    }
                } 
                else if (sigLst === func || (sigLst.receiver && sigLst.receiver === func)) {
                    delete sigCache[eventName];
                }
            }
            return this;
        }, 
        signalOnce = function(eventName, func) {
            var slf = this;
            setSingleRV(true);
            wen.receiver = function onit() {
                dropReceiver(eventName, this);
                func.apply(slf, arguments);
            };
            wen(eventName, onit);
            return this;
        }, 
        castSignal = function(eventName, args) {
            var recvrLst = receiverObjects(eventName), 
            k = {}, recvr = [], i = 0, rspns = {};
            for (k in recvrLst) {
                if (recvrLst.hasOwnProperty(k)) {
                    i = recvrLst[k].length;
                    while (i--) {
                        recvr = recvrLst[k][i];
                        if (recvr.signalOnce === true) {
                            dropReceiver(eventName, recvr);
                        }
                        rspns = recvr.call(this, args || []);
                        if (rspns === getSingleRV()) {
                            dropReceiver(eventName, recvr);
                        }
                    }
                }
            }
            return this;
        };
        function isAry(obj) {
            return (obj.constructor === Array);
        };
        function receiverObjects(eventName) {
            var recvrLst = receivers(eventName), rspns;
            if (isAry(recvrLst)) {
                rspns = {};
                rspns[eventName] = recvrLst;
            }
            return rspns || recvrLst;
        };
        function receivers(eventName) {
            if (!sigCache) {
                sigCache = {};
            }
            if (!sigCache[eventName]) {
                sigCache[eventName] = [];
            }
            if (!isAry(sigCache[eventName])) {
                sigCache[eventName] = [sigCache[eventName]];
            }
            return sigCache[eventName];
        };
        function wen(eventName, func) {
            if (!sigCache) {
                sigCache = {};
            }
            if (!sigCache[eventName]) {
                sigCache[eventName] = func;
            } 
            else if (isAry(sigCache[eventName])) {
                sigCache[eventName].push(func);
            } 
            else {
                sigCache[eventName] = [sigCache[eventName], func];
            }
            return this;
        };
        return {
            signal: castSignal,
            signaled: received,
            receive: received,
            receiveOnce: signalOnce,
            receivers: receivers,
            dropReceivers: dropReceivers
        };
    }());

// exports.Signals = Signals;   //<-- for nodejs


// use it...

var signals = Signals;

signals.receive("myEvent", function(dta) {
	console.log(dta);	
});

signals.signal("myEvent", "data to send in event...");

// note: this will drop just this receiver.
// If there are no arguments included it drops all the receivers

signals.dropReceivers("myEvent");

// you can also use inheritance to bake the signals functionality into your own objects

function usrID(uId) {
	var id = uId.toString(),
	slf = this;
	this.setId = function(val) {
		if(id !== val){
			id = val.toString();
			slf.signal("change", this);
		}
		else {
			return;	
		}
	};
	
	this.getId = function() {
		var x = id;
		return x;
	}
}

usrID.prototype = Signals;
usrID.constructor = usrID;

// now use it and abuse it!

var oID = new usrID("sytw94pt8");

oID.receive("change", function(dta) {
	alert("'change' signal data: " + dta);
});

oID.getId();   //  sytw94pt8

// executing this will trigger the alert box defined in the "receive" callback

oID.setId("000XXX");   //   "000XXX" 

// you can also observe the signals of any/all signalCasters using the static Signals object you inherited from
// It knows all and receives all signals....  So backing up a bit, we could do something like this...

userID.prototype = Signals;
userID.constructor = userID;

// now use it and abuse it!

var uID = new userID("sytw94pt8");

uID.receive("change", function(dta) {
	alert("'change' signal data from uID Object: " + dta);
});

// AND SOMEWHERE ELSE IN THE CODE AN OBSERVER....   *LoL

Signals.receive("change", function(dta) {
	alert("I also heard " + dta.target + "'s 'change' signal data: " + dta);
});

uID.getId();   //  sytw94pt8

// executing this will trigger the BOTH alert boxs defined above

uID.setId("000XXX");   //   "000XXX"

// ENJOY!!!    --sTiLL-iLL--




;