working on it ...

Filters

Explore Public Snippets

Sort by

Found 5,180 snippets matching: pattern

    public by sTiLL-iLL @ SniPitz-KND  444538  3  8  24

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

    Signals.js... A fast and efficient event system in javascript.: Signals.js
    // Signalz.js
    
    var Signals = (function () {
    	'use strict';
    	var sigCache = {},
    	addReceiver = function(eventName, func) {
    		return wen(eventName, function(evnt){
    			return func(evnt);
    		});
    	},
    	signalReceived = function(eventName, func) {
    		return wen(eventName, function(evnt){
    			return func(evnt);
    		});
    	},
    	dropReceivers = function (eventName) {
    		if (!eventName) {
    			sigCache = {};
    			return this;
    		}
    		if (sigCache && sigCache[eventName]) {
    			sigCache[eventName] = null;
    		}
    		return this;
    	},    
    	signalOnce = function (eventName, func) {
    		var slf = this;
    		setSingleRV(true);
    		function onit () {
    			dropReceiver(eventName, wen);
    			func.apply(this, arguments);
    		};
    		wen.receiver = onit;	
    		return this;
    	},
    	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;
    	},  
    	setSingleRV = function (val) {
    		singleRtnVal = val;
    		return this;
    	},  
    	getSingleRV = function() {
    		if (receivers.hasOwnProperty('singleRtnVal')) {
    			return singleRtnVal;
    		}
    		else {
    			return true;
    		}
    	},	 
    	castSignal = function(eventName, args) {
    		var recvrLst = receiverObjects(eventName),
    		k, recvr, i, 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 (isArry(sigCache[eventName])) {
    			sigCache[eventName].push(func);
    		} 
    		else {
    			sigCache[eventName] = [sigCache[eventName], func];
    		}	
    		return;
    	};
    	return {
    		signal: castSignal,
    		signaled: signalReceived,
    		receive: addReceiver,
    		receiveOnce: signalOnce,
    		signaledOnce: signalOnce,
    		dropReceiver: dropReceiver,
    		assignReceiver: addReceiver,
    		receivers: receivers,
    		dropReceivers: dropReceivers
    	};
    }());
    
    exports.Signals = Signals;
    
    
                

    public by sTiLL-iLL  203281  1  8  27

    kWetntz.js ... next in line please...

    sequential async execution... NEXT!!! *** idk if this even werks, havent tried yet! ***
    //  sequential execution....
    
    var kWentz = (function() {
        var roster = {}, lastTime = {}, slf = this,
            signal = function(name, arg) {
               var idx=0, kall = {};
               if(roster[name]) {
                   for(idx; kall=roster[name][idx]; idx++) {
                       kall(arg);
                   }
               }
            },
            receive = function(name, receiver) {
               if(!roster[name]) {
                  roster[name] = [];
               }
               roster[name].push(receiver);
               return slf;
            },
            drop = function(name, receiver) {
               if(roster[name]) {
                   var lst = [], kall = {}, idx = 0;
                   for(idx; kall=roster[name][idx]; idx++) {
                       if(kall !== receiver) {
                           lst.push(kall);
                       }
                   }
                   roster[name] = lst;
               }
               return slf;
            },
            exec = function() {
              if(arguments.length > 0) {
                var cbks = [], kall = {}, elm = {}, idx = 0;
                for(idx; kall=arguments[idx]; idx++) {
                   cbks.push(kall);
                }
                elm = cbks.shift();
                if(typeof elm === 'function') {
                   elm(lastTime, function(dta) {
                         lastTime = dta;
                         exec.apply(slf, cbks);
                   });
                } 
                else if(typeof elm === 'object' && elm.length > 0) {
                   var kall = elm.shift(),
                      callBK = function(dta) {
                         lastTime = dta;
                         exec.apply(slf, cbks);
                      };
                   kall.apply(kall, elm.concat([callBK]));
                }
             } 
             else {
                  signal("done", lastTime);
             }
             return slf;
          };
          return {
              execute: exec,
              receive: receive,
              drop: drop
          };
    })();            

    public by sTiLL-iLL @ SniPitz-KND  183869  1  8  23

    EventDelagateAsyncContextMessageBuzzWordObject

    does it work? IDK... havent tried.. the idea is solid... itll prolly work... without to much effort...
    // polyfill first... just in case
    
    if(!window.CustomEvent) {
      (function(wdw) {
        function CustomEvent ( event, params ) {
          params = params || { bubbles: false, cancelable: false, detail: undefined };
          var evt = document.createEvent( 'CustomEvent' );
          evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
          return evt;
        }
        CustomEvent.prototype = window.Event.prototype;
        wdw.CustomEvent = CustomEvent;
      }(window));
    }
    
    function ContextConnection_ChannelBroker(document) {
    	var slf = this;
    	this.create = function (evtName, obj) {
    	  var eventChannel = new CustomEvent(eventName, 
    	    {
    	      bubbles: true,
    	      cancelable: true,
    	      detail: obj
    	     });
    	     
    	  this.fwdResult = function (rslt) {
    			obj.dispatchEvent(evtName, rslt);
    		};
    		
    		this.objPxy = (function(fwdResult) {
    			this.eventChannel.call(slf);
    			obj.addEventListener(evtName, function (ev) {
    				ev.preventDefault();
    				return obj.bind(fwdResult(ev));
    			});
    			return obj;
    		}());
    		
    		return objPxy;
    	};
    	
    	objPxy.prototype = Object.create(obj.prototype,	{ 
    	  constructor: {
    	    value: objPxy,
    	    enumerable: false
    	  }
    	});
    	objPxy.prototype.on = function (n,fnc) {
    		obj.addEventListener(n, function(e) {
    			fnc(e.data);
    		});
    	};
    	objPxy.prototype.emit = function (n,obj) {
    		obj.dispatchEvent(n, obj);
    	};	
    	return {
    		onSignaled: on,
    		emitSignal:	emit,
    		createContextChannel: create
    	}
    };

    public by mprisznyak  229519  0  6  3

    Observer

    a tongue-in-cheek example for the observer pattern
    # -*- coding: utf-8 -*-
    
    """
    a tongue-in-cheek example for the observer pattern
    
    Hungary elects today :)
    """
    
    # let's use a decorator
    def observe(f):
        def decorated(self, something):
            for obs in self.observers:
                obs.notify(self, f.func_name, something)
            return f(self, something)
        return decorated
    
    
    class Observer(object):
    
        def __init__(self, name):
            self.name = name
    
        def notify(self, observed, action, something):
            name = self.name
            observed_name = observed.name
            print "{name} reports that {observed_name} {action} {something}".format(**locals())
    
    
    class Voter(object):
    
        def __init__(self, name):
            self.name = name
            self.observers = []
    
        def add_observers(self, *observers):
            self.observers.extend(observers)
    
        @observe
        def votes(self, party):
            print "{name} votes for {party}".format(name=self.name, party=party)
    
        @observe
        def eats(self, food):
            print "{name} eats {food}".format(name=self.name, food=food)
    
        def digests(self, food):
            print "{name} digests {food}".format(name=self.name, food=food)
    
    
    if __name__ == "__main__":
        # observers
        OSCE = Observer("Organization for Security and Co-operation in Europe")
        UNO  = Observer("United Nations")
        God  = Observer("God")
        # poor voter
        jani = Voter("Kovács János")
        jani.add_observers(OSCE, UNO, God)
        jani.votes("Fidesz")
        print
        jani.eats("Sunday lunch")
        # luckily digestion is not observed
        print
        jani.digests("Sunday lunch")

    public by lbottaro  2797  1  7  5

    Observer Listener Design Pattern implementation in java

    The code shows how to realize a simple listener in java, implementing the observer design pattern. The listener defines a callback method, which arguments has the Observes annotation. The observed event is the invocation of methods annotated with annotation IPersonMethodInvoke. In this way the observer will be notified every time the observed me
    package com.test.example.person.listener;
    
    import javax.enterprise.event.Observes;
    
    import com.test.example.interfaces.*;
    
    public class PersonListener {
    
    	public void OnEvent(@Observes @IPersonMethodInvoke String s)
    	{
    		System.out.println("Event callback: " + s);
    	}
    
    }
    

    public by lbottaro  3809  1  6  1

    Java Qualifier - Implementing Observer Design Pattern using interface

    This code shows a simple java interface. The Qualifier annotation allows to specify this interface as used by other class. This will allow to implement the Observer / Listener Design pattern.
    package com.test.example.interfaces;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    import javax.inject.Qualifier;
    
    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
    public @interface IPersonMethodInvoke {
    
    }
    

    public by lbottaro  4524  5  7  5

    How to sort a Javascript array parsing elements using regex pattern

    The Javascript Array.sort() method accepts a callback function to compare two elements of the array using a specific logic. The callback function below may help you in sorting an array matching a particular regular expression pattern. The format of elements in array is x/y/z, where x, y and z are integers, eg "5/10/2". I need to sort the eleme
    var myCompare = function(a,b) {
    	var matchPattern_A = /^([0-9]+)\/([0-9]+)\/([0-9]+)$/g.exec(a);
    	var matchPattern_B = /^([0-9]+)\/([0-9]+)\/([0-9]+)$/g.exec(b);
    
    	if(matchPattern_A && matchPattern_B)
    	{
    		//Apply regex sort
    		//I need to sort based on match[1], match[2], match[3]
    		console.log('Apply regex sort');
    
    		if (parseInt(matchPattern_A[1], 10) < parseInt(matchPattern_B[1], 10))
    			return -1;
    		if (parseInt(matchPattern_A[1], 10) > parseInt(matchPattern_B[1], 10))
    			return 1;
    		else {
    			if (parseInt(matchPattern_A[2], 10) < parseInt(matchPattern_B[2], 10))
    				return -1;
    			if (parseInt(matchPattern_A[2], 10) > parseInt(matchPattern_B[2], 10))
    				return 1;
    			else {
    				if (parseInt(matchPattern_A[3], 10) < parseInt(matchPattern_B[3], 10))
    					return -1;
    				if (parseInt(matchPattern_A[3], 10) > parseInt(matchPattern_B[3], 10))
    					return 1;
    				return 0;
    			}
    		}
    	}
    	else {
    		//Apply basic lexicographic sort
    		console.log('Apply basic lexicographic sort');
    		if (a < b)
    			return -1;
    		if (a > b)
    			return 1;
    		return 0;
    	}
    };
    
    var myArr = [ '5/4/30', '5/10/2', '5/4/3', '1/3/8'];
    console.log(myArr);
    myArr.sort(this.myCompare);
    console.log(myArr);
    
    /*  Example,
        having an array as
        ['5/4/30', '5/10/2', '5/4/3', '1/3/8']
        it will be sorted as
        ['1/3/8', '5/4/3', '5/4/30', '5/10/2']
    */            

    public by lbottaro  3684  2  7  3

    Java stateless EJB implementing Observer design pattern

    This java code shows how to implement a simple stateless EJB 3.0, which implements both a remote interface and the Observer design pattern. The annotation Stateless defines the bean as stateless. The annotation Remote defines which remote interface will be implemented. The EJB will handle request to manage a simple POJO class, named Person, acce
    package com.test.example.ejb;
    
    import java.util.Collection;
    import java.util.List;
    
    import javax.ejb.LocalBean;
    import javax.ejb.Remote;
    import javax.ejb.Stateless;
    import javax.enterprise.event.Event;
    import javax.inject.Inject;
    
    import com.test.example.interfaces.*;
    import com.test.example.person.Person;
    import com.test.example.person.manager.PersonManager;
    
    /**
     * Session Bean implementation class PersonEJB
     */
    @Stateless
    @LocalBean
    @Remote(IPerson.class)
    public class PersonEJB implements IPerson{
    
    	@Inject
    	private PersonManager pm;
    	
    	@Inject
    	@IPersonMethodInvoke
    	private Event<String> eventFire;
    
    	/**
    	 * Default constructor.
    	 */
    	public PersonEJB() {
    		// TODO Auto-generated constructor stub
    	}
    
    	@Override
    	public Person addPerson(Person p) {
    		p = pm.addPerson(p);
    		return p;
    	}
    
    	@Override
    	public Person updatePerson(Person p) {
    		p = pm.updatePerson(p);
    		return p;
    	}
    
    	@Override
    	public void deletePerson(int id) {
    		pm.deletePerson(id);
    	}
    
    	@Override
    	public List<Person> getPersonList() {
    		List<Person> personList = pm.getPersonList();
    		eventFire.fire(new String("pippo"));
    		return personList;
    	}
    
    	@Override
    	public Person getPerson(int id) {
    		return pm.getPerson(id);
    	}
    
    	@Override
    	public Collection<Person> searchPersons(String completeName) {
    		return pm.searchPersons(completeName);
    	}
    
    
    }
    

    public by sTiLL-iLL @ SniPitz-KND  2654  0  8  22

    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 cghersi  3156  1  6  0

    Create a usage pattern for several heterogeneous methods

    Let's say we have several methods implemented in the same way but that should invoke different operations inside their implementation. e.g. we have a wrapper of API, and each API should be checked for the reload of endpoint if failed... Under these circumstances, C# lambda expressions should be very useful, but what about Java? Here there is a so
    public interface CallableOp<T> {
    	T exec();
    }
    
    /**
     * This is the generic method that provides the common implementation for several methods,
     * which are implemented in exec() method of the given input
     * @param op object of anonymous class that implement the internal logic of the method
     * @param clazz class of the returning object
     */
    public <T> T execOp(CallableOp<T> op, Class<T> clazz) {
    	try{
    		return op.exec();
    	}catch(WebServiceException webSerExc){
    		if (checkReloadEndpoint(webSerExc)) {
    			//with this exception we prepare reload endpoints and try again invoking ws
    			forcedReloaded = true;
    			return op.exec();
    		}else{
    			//forward the exception
    			throw webSerExc;
    		}
    	}
    }
    
    public void test() {
    	//here you don't need any cast nor reflection!
    	boolean res = execOp(new CallableOp<Boolean>() {
    		public Boolean exec() {
    			//parameters and other business logic may be implemented here 
    			//or directly in the test() method
    			int param1 = 1;
    			String param2 = "test";
    			return apiInvocation(param1, param2); // thi is the API invocation method 
    		}
    	}, Boolean.class);
    }
    • Public Snippets
    • Channels Snippets