text:
/*!	SWFMini - a SWFObject 2.2 cut down version for webshims
 *
 * based on SWFObject v2.2 <http://code.google.com/p/swfobject/>
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

var swfmini = function() {
	var wasRemoved = function(){webshims.error('This method was removed from swfmini');};
	var UNDEF = "undefined",
		OBJECT = "object",
		webshims = window.webshims,
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		FLASH_MIME_TYPE = "application/x-shockwave-flash",

		win = window,
		doc = document,
		nav = navigator,

		plugin = false,
		domLoadFnArr = [main],

		isDomLoaded = false,
		autoHideShow = true,

	/* Centralized function for browser feature detection
		- User agent string detection is only used when no good alternative is possible
		- Is executed directly for optimal performance
	*/
	ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
			u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
				plugin = true;
				ie = false; // cascaded feature detection for Internet Explorer
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			try {
				var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
				if (a) { // a will return null when ActiveX is disabled
					d = a.GetVariable("$version");
					if (d) {
						ie = true; // cascaded feature detection for Internet Explorer
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
			}
			catch(e) {}
		}
		return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
	}();

	function callDomLoadFunctions() {
		if (isDomLoaded) { return; }
		isDomLoaded = true;
		var dl = domLoadFnArr.length;
		for (var i = 0; i < dl; i++) {
			domLoadFnArr[i]();
		}
	}

	function addDomLoadEvent(fn) {
		if (isDomLoaded) {
			fn();
		}
		else {
			domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
		}
	}

	/* Main function
		- Will preferably execute onDomLoad, otherwise onload (as a fallback)
	*/
	function main() {
		if (plugin) {
			testPlayerVersion();
		}
	}

	/* Detect the Flash Player version for non-Internet Explorer browsers
		- Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
		  a. Both release and build numbers can be detected
		  b. Avoid wrong descriptions by corrupt installers provided by Adobe
		  c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
		- Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
	*/
	function testPlayerVersion() {
		var b = doc.getElementsByTagName("body")[0];
		var o = createElement(OBJECT);
		o.setAttribute("type", FLASH_MIME_TYPE);
		var t = b.appendChild(o);
		if (t) {
			var counter = 0;
			(function(){
				if (typeof t.GetVariable != UNDEF) {
					var d = t.GetVariable("$version");
					if (d) {
						d = d.split(" ")[1].split(",");
						ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				else if (counter < 10) {
					counter++;
					setTimeout(arguments.callee, 10);
					return;
				}
				b.removeChild(o);
				t = null;
			})();
		}
	}

	function createElement(el) {
		return doc.createElement(el);
	}

	/* Flash Player and SWF content version matching
	*/
	function hasPlayerVersion(rv) {
		var pv = ua.pv, v = rv.split(".");
		v[0] = parseInt(v[0], 10);
		v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
		v[2] = parseInt(v[2], 10) || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	}

	webshims.ready('DOM', callDomLoadFunctions);

	webshims.loader.addModule('swfmini-embed', {d: ['swfmini']});
	var loadEmbed = hasPlayerVersion('9.0.0') ?
		function(){
			webshims.loader.loadList(['swfmini-embed']);
			return true;
		} :
		webshims.$.noop
	;

	if(!webshims.support.mediaelement){
		loadEmbed();
	} else {
		webshims.ready('WINDOWLOAD', loadEmbed);
	}

	return {
		/* Public API
			- Reference: http://code.google.com/p/swfobject/wiki/documentation
		*/
		registerObject: wasRemoved,

		getObjectById: wasRemoved,

		embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
			var args = arguments;
			if(loadEmbed()){
				webshims.ready('swfmini-embed', function(){
					swfmini.embedSWF.apply(swfmini, args);
				});
			} else if(callbackFn) {
				callbackFn({success:false, id:replaceElemIdStr});
			}
		},

		switchOffAutoHideShow: function() {
			autoHideShow = false;
		},

		ua: ua,

		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		},

		hasFlashPlayerVersion: hasPlayerVersion,

		createSWF: function(attObj, parObj, replaceElemIdStr) {
			if (ua.w3) {
				return createSWF(attObj, parObj, replaceElemIdStr);
			}
			else {
				return undefined;
			}
		},

		showExpressInstall: wasRemoved,

		removeSWF: wasRemoved,

		createCSS: wasRemoved,

		addDomLoadEvent: addDomLoadEvent,

		addLoadEvent: wasRemoved,

		// For internal usage only
		expressInstallCallback: wasRemoved
	};
}();

webshims.isReady('swfmini', true);
;(function(webshims){
	"use strict";
	var support = webshims.support;
	var hasNative = support.mediaelement;
	var supportsLoop = false;
	var bugs = webshims.bugs;
	var swfType = 'mediaelement-jaris';
	var loadSwf = function(){
		webshims.ready(swfType, function(){
			if(!webshims.mediaelement.createSWF){
				webshims.mediaelement.loadSwf = true;
				webshims.reTest([swfType], hasNative);
			}
		});
	};

	var wsCfg = webshims.cfg;
	var options = wsCfg.mediaelement;
	var isIE = navigator.userAgent.indexOf('MSIE') != -1;
	if(!options){
		webshims.error("mediaelement wasn't implemented but loaded");
		return;
	}

	if(hasNative){
		var videoElem = document.createElement('video');
		support.videoBuffered = ('buffered' in videoElem);
		support.mediaDefaultMuted = ('defaultMuted' in videoElem);
		supportsLoop = ('loop' in videoElem);
		support.mediaLoop = supportsLoop;

		webshims.capturingEvents(['play', 'playing', 'waiting', 'paused', 'ended', 'durationchange', 'loadedmetadata', 'canplay', 'volumechange']);

		if( !support.videoBuffered || !supportsLoop || (!support.mediaDefaultMuted && isIE && 'ActiveXObject' in window) ){
			webshims.addPolyfill('mediaelement-native-fix', {
				d: ['dom-support']
			});
			webshims.loader.loadList(['mediaelement-native-fix']);
		}
	}

	if(support.track && !bugs.track){
		(function(){
			if(!bugs.track){

				if(window.VTTCue && !window.TextTrackCue){
					window.TextTrackCue = window.VTTCue;
				} else if(!window.VTTCue){
					window.VTTCue = window.TextTrackCue;
				}

				try {
					new VTTCue(2, 3, '');
				} catch(e){
					bugs.track = true;
				}
			}
		})();
	}

webshims.register('mediaelement-core', function($, webshims, window, document, undefined, options){
	var hasSwf = swfmini.hasFlashPlayerVersion('11.3');
	var mediaelement = webshims.mediaelement;
	var allowYtLoading = false;

	mediaelement.parseRtmp = function(data){
		var src = data.src.split('://');
		var paths = src[1].split('/');
		var i, len, found;
		data.server = src[0]+'://'+paths[0]+'/';
		data.streamId = [];
		for(i = 1, len = paths.length; i < len; i++){
			if(!found && paths[i].indexOf(':') !== -1){
				paths[i] = paths[i].split(':')[1];
				found = true;
			}
			if(!found){
				data.server += paths[i]+'/';
			} else {
				data.streamId.push(paths[i]);
			}
		}
		if(!data.streamId.length){
			webshims.error('Could not parse rtmp url');
		}
		data.streamId = data.streamId.join('/');
	};

	var getSrcObj = function(elem, nodeName){
		elem = $(elem);
		var src = {src: elem.attr('src') || '', elem: elem, srcProp: elem.prop('src')};
		var tmp;

		if(!src.src){return src;}

		tmp = elem.attr('data-server');
		if(tmp != null){
			src.server = tmp;
		}

		tmp = elem.attr('type') || elem.attr('data-type');
		if(tmp){
			src.type = tmp;
			src.container = $.trim(tmp.split(';')[0]);
		} else {
			if(!nodeName){
				nodeName = elem[0].nodeName.toLowerCase();
				if(nodeName == 'source'){
					nodeName = (elem.closest('video, audio')[0] || {nodeName: 'video'}).nodeName.toLowerCase();
				}
			}
			if(src.server){
				src.type = nodeName+'/rtmp';
				src.container = nodeName+'/rtmp';
			} else {

				tmp = mediaelement.getTypeForSrc( src.src, nodeName, src );

				if(tmp){
					src.type = tmp;
					src.container = tmp;
				}
			}
		}

		tmp = elem.attr('media');
		if(tmp){
			src.media = tmp;
		}
		if(src.type == 'audio/rtmp' || src.type == 'video/rtmp'){
			if(src.server){
				src.streamId = src.src;
			} else {
				mediaelement.parseRtmp(src);
			}
		}
		return src;
	};

	var hasYt = !hasSwf && ('postMessage' in window) && hasNative;

	var loadTrackUi = function(){
		if(loadTrackUi.loaded){return;}
		loadTrackUi.loaded = true;
		if(!options.noAutoTrack){
			webshims.ready('WINDOWLOAD', function(){
				loadThird();
				webshims.loader.loadList(['track-ui']);
			});
		}
	};

	var loadYt = (function(){
		var loaded;
		return function(){
			if(loaded || !hasYt){return;}
			loaded = true;
			if(allowYtLoading){
				webshims.loader.loadScript("https://www.youtube.com/player_api");
			}
			$(function(){
				webshims._polyfill(["mediaelement-yt"]);
			});
		};
	})();
	var loadThird = function(){
		if(hasSwf){
			loadSwf();
		} else {
			loadYt();
		}
	};

	webshims.addPolyfill('mediaelement-yt', {
		test: !hasYt,
		d: ['dom-support']
	});

	mediaelement.mimeTypes = {
		audio: {
				//ogm shouldn´t be used!
				'audio/ogg': ['ogg','oga', 'ogm'],
				'audio/ogg;codecs="opus"': 'opus',
				'audio/mpeg': ['mp2','mp3','mpga','mpega'],
				'audio/mp4': ['mp4','mpg4', 'm4r', 'm4a', 'm4p', 'm4b', 'aac'],
				'audio/wav': ['wav'],
				'audio/3gpp': ['3gp','3gpp'],
				'audio/webm': ['webm'],
				'audio/fla': ['flv', 'f4a', 'fla'],
				'application/x-mpegURL': ['m3u8', 'm3u']
			},
			video: {
				//ogm shouldn´t be used!
				'video/ogg': ['ogg','ogv', 'ogm'],
				'video/mpeg': ['mpg','mpeg','mpe'],
				'video/mp4': ['mp4','mpg4', 'm4v'],
				'video/quicktime': ['mov','qt'],
				'video/x-msvideo': ['avi'],
				'video/x-ms-asf': ['asf', 'asx'],
				'video/flv': ['flv', 'f4v'],
				'video/3gpp': ['3gp','3gpp'],
				'video/webm': ['webm'],
				'application/x-mpegURL': ['m3u8', 'm3u'],
				'video/MP2T': ['ts']
			}
		}
	;

	mediaelement.mimeTypes.source =  $.extend({}, mediaelement.mimeTypes.audio, mediaelement.mimeTypes.video);

	mediaelement.getTypeForSrc = function(src, nodeName){
		if(src.indexOf('youtube.com/watch?') != -1 || src.indexOf('youtube.com/v/') != -1){
			return 'video/youtube';
		}

		if(!src.indexOf('mediastream:') || !src.indexOf('blob:http')){
			return 'usermedia';
		}

		if(!src.indexOf('webshimstream')){
			return 'jarisplayer/stream';
		}

		if(!src.indexOf('rtmp')){
			return nodeName+'/rtmp';
		}
		src = src.split('?')[0].split('#')[0].split('.');
		src = src[src.length - 1];
		var mt;

		$.each(mediaelement.mimeTypes[nodeName], function(mimeType, exts){
			if(exts.indexOf(src) !== -1){
				mt = mimeType;
				return false;
			}
		});
		return mt;
	};

	mediaelement.srces = function(mediaElem){
		var srces = [];
		mediaElem = $(mediaElem);
		var nodeName = mediaElem[0].nodeName.toLowerCase();
		var src = getSrcObj(mediaElem, nodeName);

		if(!src.src){
			$('source', mediaElem).each(function(){
				src = getSrcObj(this, nodeName);
				if(src.src){srces.push(src);}
			});
		} else {
			srces.push(src);
		}
		return srces;
	};

	mediaelement.swfMimeTypes = ['video/3gpp', 'video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/aac', 'audio/mp4', 'audio/x-m4a', 'audio/m4a', 'audio/mp3', 'audio/x-fla', 'audio/fla', 'youtube/flv', 'video/jarisplayer', 'jarisplayer/jarisplayer', 'jarisplayer/stream', 'video/youtube', 'video/rtmp', 'audio/rtmp'];

	mediaelement.canThirdPlaySrces = function(mediaElem, srces){
		var ret = '';
		if(hasSwf || hasYt){
			mediaElem = $(mediaElem);
			srces = srces || mediaelement.srces(mediaElem);
			$.each(srces, function(i, src){
				if(src.container && src.src && ((hasSwf && mediaelement.swfMimeTypes.indexOf(src.container) != -1) || (hasYt && src.container == 'video/youtube'))){
					ret = src;
					return false;
				}
			});

		}

		return ret;
	};

	var nativeCanPlayType = {};
	mediaelement.canNativePlaySrces = function(mediaElem, srces){
		var ret = '';
		if(hasNative){
			mediaElem = $(mediaElem);
			var nodeName = (mediaElem[0].nodeName || '').toLowerCase();
			var nativeCanPlay = (nativeCanPlayType[nodeName] || {prop: {_supvalue: false}}).prop._supvalue || mediaElem[0].canPlayType;
			if(!nativeCanPlay){return ret;}
			srces = srces || mediaelement.srces(mediaElem);

			$.each(srces, function(i, src){
				if(src.type == 'usermedia' || (src.type && nativeCanPlay.call(mediaElem[0], src.type)) ){
					ret = src;
					return false;
				}
			});
		}
		return ret;
	};
	var emptyType = (/^\s*application\/octet\-stream\s*$/i);
	var getRemoveEmptyType = function(){
		var ret = emptyType.test($.attr(this, 'type') || '');
		if(ret){
			$(this).removeAttr('type');
		}
		return ret;
	};
	mediaelement.setError = function(elem, message){
		if($('source', elem).filter(getRemoveEmptyType).length){
			webshims.error('"application/octet-stream" is a useless mimetype for audio/video. Please change this attribute.');
			try {
				$(elem).mediaLoad();
			} catch(er){}
		} else {
			if(!message){
				message = "can't play sources";
			}
			$(elem).pause().data('mediaerror', message);
			webshims.error('mediaelementError: '+ message +'. Run the following line in your console to get more info: webshim.mediaelement.loadDebugger();');
			setTimeout(function(){
				if($(elem).data('mediaerror')){
					$(elem).addClass('media-error').trigger('mediaerror');
				}
			}, 1);
		}

	};

	var handleThird = (function(){
		var requested;
		var readyType = hasSwf ? swfType : 'mediaelement-yt';
		return function( mediaElem, ret, data ){
			//readd to ready

			webshims.ready(readyType, function(){
				if(mediaelement.createSWF && $(mediaElem).parent()[0]){
					mediaelement.createSWF( mediaElem, ret, data );
				} else if(!requested) {
					requested = true;
					loadThird();

					handleThird( mediaElem, ret, data );
				}
			});
			if(!requested && hasYt && !mediaelement.createSWF){
				allowYtLoading = true;
				loadYt();
			}
		};
	})();

	var activate = {
		native: function(elem, src, data){
			if(data && data.isActive == 'third') {
				mediaelement.setActive(elem, 'html5', data);
			}
		},
		third: handleThird
	};

	var stepSources = function(elem, data, srces){
		var i, src;
		var testOrder = [{test: 'canNativePlaySrces', activate: 'native'}, {test: 'canThirdPlaySrces', activate: 'third'}];
		if(options.preferFlash || (data && data.isActive == 'third') ){
			testOrder.reverse();
		}
		for(i = 0; i < 2; i++){
			src = mediaelement[testOrder[i].test](elem, srces);
			if(src){
				activate[testOrder[i].activate](elem, src, data);
				break;
			}
		}

		if(!src){
			mediaelement.setError(elem, false);
			if(data && data.isActive == 'third') {
				mediaelement.setActive(elem, 'html5', data);
			}
		}
	};
	var stopParent = /^(?:embed|object|datalist|picture)$/i;
	var selectSource = function(elem, data){
		var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {});
		var _srces = mediaelement.srces(elem);
		var parent = elem.parentNode;

		clearTimeout(baseData.loadTimer);
		$(elem).removeClass('media-error');
		$.data(elem, 'mediaerror', false);

		if(!_srces.length || !parent || parent.nodeType != 1 || stopParent.test(parent.nodeName || '')){return;}
		data = data || webshims.data(elem, 'mediaelement');
		if(mediaelement.sortMedia){
			_srces.sort(mediaelement.sortMedia);
		}
		stepSources(elem, data, _srces);

	};
	mediaelement.selectSource = selectSource;

	$(document).on('ended', function(e){
		var data = webshims.data(e.target, 'mediaelement');
		if( supportsLoop && (!data || data.isActive == 'html5') && !$.prop(e.target, 'loop')){return;}
		setTimeout(function(){
			if( $.prop(e.target, 'paused') || !$.prop(e.target, 'loop') ){return;}
			$(e.target).prop('currentTime', 0).play();
		});

	});

	var handleMedia = false;

	var initMediaElements = function(){
		var testFixMedia = function(){

			if(webshims.implement(this, 'mediaelement')){
				selectSource(this);
				if(!support.mediaDefaultMuted && $.attr(this, 'muted') != null){
					$.prop(this, 'muted', true);
				}

			}
		};

		webshims.ready('dom-support', function(){
			handleMedia = true;

			if(!supportsLoop){
				webshims.defineNodeNamesBooleanProperty(['audio', 'video'], 'loop');
			}

			['audio', 'video'].forEach(function(nodeName){
				var supLoad;
				supLoad = webshims.defineNodeNameProperty(nodeName, 'load',  {
					prop: {
						value: function(){
							var data = webshims.data(this, 'mediaelement');

							selectSource(this, data);
							if(hasNative && (!data || data.isActive == 'html5') && supLoad.prop._supvalue){
								supLoad.prop._supvalue.apply(this, arguments);
							}
							if(!loadTrackUi.loaded && this.querySelector('track')){
								loadTrackUi();
							}
							$(this).triggerHandler('wsmediareload');
						}
					}
				});

				nativeCanPlayType[nodeName] = webshims.defineNodeNameProperty(nodeName, 'canPlayType',  {
					prop: {
						value: function(type){
							var ret = '';
							if(hasNative && nativeCanPlayType[nodeName].prop._supvalue){
								ret = nativeCanPlayType[nodeName].prop._supvalue.call(this, type);
								if(ret == 'no'){
									ret = '';
								}
							}
							if(!ret && hasSwf){
								type = $.trim((type || '').split(';')[0]);
								if(mediaelement.swfMimeTypes.indexOf(type) != -1){
									ret = 'maybe';
								}
							}
							if(!ret && hasYt && type == 'video/youtube'){
								ret = 'maybe';
							}
							return ret;
						}
					}
				});
			});

			webshims.onNodeNamesPropertyModify(['audio', 'video'], ['src', 'poster'], {
				set: function(){
					var elem = this;
					var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {});
					clearTimeout(baseData.loadTimer);
					baseData.loadTimer = setTimeout(function(){
						selectSource(elem);
						elem = null;
					}, 9);
				}
			});

			webshims.addReady(function(context, insertedElement){
				var media = $('video, audio', context)
					.add(insertedElement.filter('video, audio'))
					.each(testFixMedia)
				;
				if(!loadTrackUi.loaded && $('track', media).length){
					loadTrackUi();
				}
				media = null;
			});
		});

		if(hasNative && !handleMedia){
			webshims.addReady(function(context, insertedElement){
				if(!handleMedia){
					$('video, audio', context)
						.add(insertedElement.filter('video, audio'))
						.each(function(){
							if(!mediaelement.canNativePlaySrces(this)){
								allowYtLoading = true;
								loadThird();
								handleMedia = true;
								return false;
							}
						})
					;
				}
			});
		}
	};

	mediaelement.loadDebugger = function(){
		webshims.ready('dom-support', function(){
			webshims.loader.loadScript('mediaelement-debug');
		});
	};

	if(({noCombo: 1, media: 1})[webshims.cfg.debug]){
		$(document).on('mediaerror', function(e){
			mediaelement.loadDebugger();
		});
	}
	//set native implementation ready, before swf api is retested
	if(hasNative){
		webshims.isReady('mediaelement-core', true);
		initMediaElements();
		webshims.ready('WINDOWLOAD mediaelement', loadThird);
	} else {
		webshims.ready(swfType, initMediaElements);
	}
	webshims.ready('track', loadTrackUi);

	if(document.readyState == 'complete'){
		webshims.isReady('WINDOWLOAD', true);
	}
});

})(webshims);


text:
local obj={}
obj.__index = obj

-- Metadata
obj.name = "URLDispatcher"
obj.version = "0.1"
obj.author = "Diego Zamboni <diego@zzamboni.org>"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"

--- URLDispatcher.default_handler
--- Variable
--- Bundle ID for default URL handler. (Defaults to `"com.apple.Safari"`)
obj.default_handler = "com.apple.Safari"

--- URLDispatcher.decode_slack_redir_urls
--- Variable
--- If true, handle Slack-redir URLs to apply the rule on the destination URL. Defaults to `true`
obj.decode_slack_redir_urls = true

--- URLDispatcher.url_patterns
--- Variable
--- URL dispatch rules.
--- A table containing a list of dispatch rules. Each rule should be its own table in the format: `{ "url pattern", "application bundle ID", "function" }`, and they are evaluated in the order they are declared. Note that the patterns are [Lua patterns](https://www.lua.org/pil/20.2.html) and not regular expressions. Defaults to an empty table, which has the effect of having all URLs dispatched to the `default_handler`. If "application bundle ID" is specified, that application will be used to open matching URLs. If no "application bundle ID" is specified, but "function" is provided (and is a Lua function) it will be called with the URL.
obj.url_patterns = { }

--- URLDispatcher.logger
--- Variable
--- Logger object used within the Spoon. Can be accessed to set the default log level for the messages coming from the Spoon.
obj.logger = hs.logger.new('URLDispatcher')

-- Local functions to decode URLs
function hex_to_char(x)
   return string.char(tonumber(x, 16))
end

function unescape(url)
   return url:gsub("%%(%x%x)", hex_to_char)
end

--- URLDispatcher:dispatchURL(scheme, host, params, fullUrl)
--- Method
--- Dispatch a URL to an application according to the defined `url_patterns`.
---
--- Parameters (according to the [httpCallback](http://www.hammerspoon.org/docs/hs.urlevent.html#httpCallback) specification):
---  * scheme - A string containing the URL scheme (i.e. "http")
---  * host - A string containing the host requested (e.g. "www.hammerspoon.org")
---  * params - A table containing the key/value pairs of all the URL parameters
---  * fullURL - A string containing the full, original URL
function obj:dispatchURL(scheme, host, params, fullUrl)
   local url = fullUrl
   self.logger.df("Dispatching URL '%s'", url)
   if self.decode_slack_redir_urls then
      local newUrl = string.match(url, 'https://slack.redir.net/.*url=(.*)')
      if newUrl then
         url = unescape(newUrl)
      end
   end
   for i,pair in ipairs(self.url_patterns) do
      local p = pair[1]
      local app = pair[2]
      local func = pair[3]
      if string.match(url, p) then
         id = app
         if id ~= nil then
            self.logger.df("Match found, opening with '%s'", id)
            hs.application.launchOrFocusByBundleID(id)
            hs.urlevent.openURLWithBundle(url, id)
            return
         end
         if func ~= nil then
            self.logger.df("Match found, calling func '%s'", func)
            func(url)
            return
         end
      end
   end
   self.logger.df("No match found, opening with default handler '%s'", self.default_handler)
   hs.application.launchOrFocusByBundleID(self.default_handler)
   hs.urlevent.openURLWithBundle(url, self.default_handler)
end

--- URLDispatcher:start()
--- Method
--- Start dispatching URLs according to the rules
function obj:start()
   if hs.urlevent.httpCallback then
      self.logger.w("An hs.urlevent.httpCallback was already set. I'm overriding it with my own but you should check if this breaks any other functionality")
   end
   hs.urlevent.httpCallback = function(...) self:dispatchURL(...) end
   hs.urlevent.setDefaultHandler('http')
   --   hs.urlevent.setRestoreHandler('http', self.default_handler)
   return self
end

return obj

redpajama_set_name: RedPajamaGithub


text:
myModule.config(function ($routeProvider) {
    $routeProvider.when("/", {
        templateUrl: "pages/login.html",
        controller: loginController
    }).when("/ActivityList", {
            templateUrl: "pages/activity_list.html",
            controller: ActivityListController
        }).when("/CreateActivityList", {
            templateUrl: "pages/create_activity_list.html",
            controller: CreateActivityListController
        }).when("/ActivityEnroll", {
            templateUrl: "pages/activity_enroll.html",
            controller: ActivityEnrollController
        }).when("/BidList", {
            templateUrl: "pages/bid_list.html",
            controller: BidListController
        }).when("/BidSignUp", {
            templateUrl: "pages/bid_sign_up.html",
            controller: BidSignUpController
        }).when("/BidResult", {
            templateUrl: "pages/bid_result.html",
            controller: BidResultController
        }).when("/BidAnalysis", {
            templateUrl: "pages/bid_analysis.html",
            controller: BidAnalysisController
        })
        .otherwise({
            redirectTo: "/"
        });

    //routing generate
    //routing generated over
});

/** Here is example
 myModule.config(function($routeProvider) {
    $routeProvider.when("/", {
        templateUrl: "pages/activity_list_page.html",
        controller: ActivityListController
    }).when("/activity/create", {
            templateUrl: "pages/activity_create_page.html",
            controller: ActivityCreateController
        }).when("/sign_ups/list/:activity_name", {
            templateUrl: "pages/apply_page.html",
            controller: SignUpListController
        }).otherwise({
            redirectTo: "/"
        });
});
 **/


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../openssl_sys/fn.BIO_meth_set_ctrl.html">

Redirecting to ../../openssl_sys/fn.BIO_meth_set_ctrl.html...


text:
import isDate from 'lodash-es/isDate.js';
import removeDateFromSlug from './removeDateFromSlug.js';

/**
 * Return the required date format in slug (YYYY/MM/DD)
 *
 * @param  {Date} date
 *
 * @returns {string} YYYY/MM/DD formated date
 */
function formatSlugDate(date) {
  const year = date.getFullYear();

  let month = date.getMonth() + 1;
  if (month < 10) {
    month = `0${month}`;
  }

  let day = date.getDate();
  if (day < 10) {
    day = `0${day}`;
  }

  return `${year}/${month}/${day}`;
}

/**
 * Returns the slug with the date prepended to it.
 *
 * @param {string} slug
 * @param {?Date}  [date]
 *
 * @returns {?string}
 */
export default function addDateToSlug(slug, date = null) {
  let d = date;
  if (!isDate(d)) {
    d = new Date();
  }

  return `${formatSlugDate(d)}/${removeDateFromSlug(slug)}`;
}


text:
package com.browserup.harreader.model;

import java.util.HashMap;
import java.util.Map;

public enum HttpStatus {

    UNKNOWN_HTTP_STATUS(0),

    OK(200), CREATED(201), ACCEPTED(202), NO_CONTENT(204), RESET_CONTENT(205),
    PARTIAL_CONTENT(206), MULTI_STATUS(207), ALREADY_REPORTED(208), IM_USED(226),

    MOVED_PERMANENTLY(301), FOUND(302), SEE_OTHER(303), NOT_MODIFIED(304),
    USE_PROXY(305), TEMPORARY_REDIRECT(307), PERMANENT_REDIRECT(308),

    BAD_REQUEST(400), UNAUTHORIZED(401), PAYMENT_REQUIRED(402), FORBIDDEN(403),
    NOT_FOUND(404), METHOD_NOT_ALLOWED(405), NOT_ACCEPTABLE(406),
    PROXY_AUTHENTICATION_REQUIRED(407), REQUEST_TIMEOUT(408),
    CONFLICT(409), GONE(410), LENGTH_REQUIRED(411), PRECONDITION_FAILED(412),
    REQUEST_ENTITY_TOO_LARGE(413), REQUEST_URI_TOO_LONG(414),
    UNSUPPORTED_MEDIA_TYPE(415), REQUESTED_RANGE_NOT_SATISFIABLE(416),
    EXPECTATION_FAILED(417), MISDIRECTED_REQUEST(421),
    UNPROCESSABLE_ENTITY(422), LOCKED(423), FAILED_DEPENDENCY(424),
    UPGRADE_REQUIRED(426), PRECONDITION_REQUIRED(428), TOO_MANY_REQUESTS(429),
    REQUEST_HEADER_FIELDS_TOO_LARGE(431), UNAVAILABLE_FOR_LEGAL_REASONS(451),

    INTERNAL_SERVER_ERROR(500), NOT_IMPLEMENTED(501),
    BAD_GATEWAY(502), SERVICE_UNAVAILABLE(503), GATEWAY_TIMEOUT(504),
    HTTP_VERSION_NOT_SUPPORTED(505), VARIANT_ALSO_NEGOTIATES(506),
    INSUFFICIENT_STORAGE(507), LOOP_DETECTED(508),
    NOT_EXTENDED(510), NETWORK_AUTHENTICATION_REQUIRED(511);

    private static final Map<Integer, HttpStatus> CODE_MAP = new HashMap<>();

    static {
        for (HttpStatus status : HttpStatus.values()) {
            CODE_MAP.put(status.getCode(), status);
        }
    }

    private int code;

    private HttpStatus(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static HttpStatus byCode(int code) {
        HttpStatus status = CODE_MAP.get(code);
        if (status == null) {
            return UNKNOWN_HTTP_STATUS;
        }
        return status;
    }

}


text:
/* Author: pupius@google.com (Daniel Pupius) */
/* Author: cibu@google.com (Cibu Johny) */

.goog-char-picker {
  background-color: #ddd;
  padding: 16px;
  border: 1px solid #777;
}

/* goog.ui.HoverCard */
.goog-char-picker-hovercard {
  border: solid 5px #ffcc33;
  min-width: 64px;
  max-width: 160px;
  padding: 16px;
  background-color: white;
  text-align: center;
  position: absolute;
  visibility: hidden;
}

.goog-char-picker-name {
  font-size: x-small;
}

.goog-char-picker-unicode {
  font-size: x-small;
  color: GrayText;
}

.goog-char-picker-char-zoom {
  font-size: xx-large;
}

/*
 * grid
 */
.goog-char-picker-grid-container {
  border: 1px solid #777;
  background-color: #fff;
  width: 272px;
}

.goog-char-picker-grid {
  overflow: hide;
  height: 250px;
  width: 250px;
  position: relative;
}

.goog-stick {
  width: 1px;
  overflow: hidden;
}
.goog-stickwrap {
  width: 17px;
  height: 250px;
  float: right;
  overflow: auto;
}

.goog-char-picker-recents {
  border: 1px solid #777;
  background-color: #fff;
  height: 25px;
  width: 275px;
  margin: 0 0 16px 0;
  position: relative;
}

.goog-char-picker-notice {
  font-size: x-small;
  height: 16px;
  color: GrayText;
  margin: 0 0 16px 0;
}

/*
 * Hex entry
 */

.goog-char-picker-uplus {
}

.goog-char-picker-input-box {
  width: 96px;
}

.label-input-label {
  color: GrayText;
}

.goog-char-picker-okbutton {
}

/*
 * Grid buttons
 */
.goog-char-picker-grid .goog-flat-button {
  position: relative;
  width: 24px;
  height: 24px;
  line-height: 24px;
  border-bottom: 1px solid #ddd;
  border-right: 1px solid #ddd;
  text-align: center;
  cursor: pointer;
  outline: none;
}

.goog-char-picker-grid .goog-flat-button-hover {
  background-color: #ffcc33;
}

/*
 * goog.ui.Menu
 */

/* State: resting. */
.goog-char-picker-button {
  border-width: 0px;
  margin: 0;
  padding: 0;
  position: absolute;
  background-position: center left;
}

/* State: resting. */
.goog-char-picker-menu {
  background-color: #fff;
  border-color: #ccc #666 #666 #ccc;
  border-style: solid;
  border-width: 1px;
  cursor: default;
  margin: 0;
  outline: none;
  padding: 0;
  position: absolute;
  max-height: 400px;
  overflow-y: auto;
  overflow-x: hide;
}

/*
 * goog.ui.MenuItem
 */

/* State: resting. */
.goog-char-picker-menu .goog-menuitem {
  color: #000;
  list-style: none;
  margin: 0;
  /* 28px on the left for icon or checkbox; 10ex on the right for shortcut. */
  padding: 1px 32px 1px 8px;
  white-space: nowrap;
}

.goog-char-picker-menu2 .goog-menuitem {
  color: #000;
  list-style: none;
  margin: 0;
  /* 28px on the left for icon or checkbox; 10ex on the right for shortcut. */
  padding: 1px 32px 1px 8px;
  white-space: nowrap;
}

.goog-char-picker-menu .goog-subtitle {
  color: #fff !important;
  background-color: #666;
  font-weight: bold;
  list-style: none;
  margin: 0;
  /* 28px on the left for icon or checkbox; 10ex on the right for shortcut. */
  padding: 3px 32px 3px 8px;
  white-space: nowrap;
}

/* BiDi override for the resting state. */
.goog-char-picker-menu .goog-menuitem-rtl {
  /* Flip left/right padding for BiDi. */
  padding: 2px 16px 2px 32px !important;
}

/* State: hover. */
.goog-char-picker-menu .goog-menuitem-highlight {
  background-color: #d6e9f8;
}
/*
 * goog.ui.MenuSeparator
 */

/* State: resting. */
.goog-char-picker-menu .goog-menuseparator {
  border-top: 1px solid #ccc;
  margin: 2px 0;
  padding: 0;
}


text:
@implementation NSArray (PEGKitAdditions)

- (NSArray *)reversedArray {
    return [[self reversedMutableArray] copy];
}

- (NSMutableArray *)reversedMutableArray {
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:[self count]];
    for (id obj in [self reverseObjectEnumerator]) {
        [result addObject:obj];
    }
    return result;
}

@end


text:
namespace Google.Analytics.Admin.V1Alpha.Snippets
{
    // [START analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListFirebaseLinks_sync_flattened_resourceNames]
    using Google.Analytics.Admin.V1Alpha;
    using Google.Api.Gax;
    using System;

    public sealed partial class GeneratedAnalyticsAdminServiceClientSnippets
    {
        /// <summary>Snippet for ListFirebaseLinks</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListFirebaseLinksResourceNames()
        {
            // Create client
            AnalyticsAdminServiceClient analyticsAdminServiceClient = AnalyticsAdminServiceClient.Create();
            // Initialize request argument(s)
            PropertyName parent = PropertyName.FromProperty("[PROPERTY]");
            // Make the request
            PagedEnumerable<ListFirebaseLinksResponse, FirebaseLink> response = analyticsAdminServiceClient.ListFirebaseLinks(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (FirebaseLink item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListFirebaseLinksResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (FirebaseLink item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<FirebaseLink> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (FirebaseLink item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_ListFirebaseLinks_sync_flattened_resourceNames]
}


text:
namespace ohmu {

template <class T, class U>
inline bool isa(const U* p) { return T::classof(p); }

template <class T, class U>
inline T* cast(U* p) {
  assert(T::classof(p));
  return static_cast<T*>(p);
}

template <class T, class U>
inline const T* cast(const U* p) {
  assert(T::classof(p));
  return static_cast<const T*>(p);
}

template <class T, class U>
inline T* dyn_cast(U* p) {
  if (!T::classof(p))
    return 0;
  return static_cast<T*>(p);
}

template <class T, class U>
inline const T* dyn_cast(const U* p) {
  if (!T::classof(p))
    return 0;
  return static_cast<const T*>(p);
}

template <class T, class U>
inline T* dyn_cast_or_null(U* p) {
  if (!p || !T::classof(p))
    return 0;
  return static_cast<T*>(p);
}

template <class T, class U>
inline const T* dyn_cast_or_null(const U* p) {
  if (!p || !T::classof(p))
    return 0;
  return static_cast<const T*>(p);
}

class StringRef {
public:
  StringRef(const char* s)
    : str_(s), len_(static_cast<unsigned>(strlen(s)))
  { }
  StringRef(const char* s, unsigned len)
    : str_(s), len_(len)
  { }
  // Warning -- lifetime of s must be longer than this stringref.
  explicit StringRef(const std::string& s)
    : str_(s.c_str()), len_(s.length())
  { }

  const char* c_str()  const { return str_; }

  size_t      size()   const { return len_; }
  const char* data()   const { return str_; }

  std::string str() const {
    if (!str_) return std::string();
    return std::string(str_, len_);
  }

  bool operator<(const StringRef& s) const {
    return strncmp(str_, s.str_, min(len_, s.len_)) < 0;
  }

  bool operator<=(const StringRef& s) const {
    return strncmp(str_, s.str_, min(len_, s.len_)) <= 0;
  }

  bool operator>(const StringRef& s) const {
    return strncmp(str_, s.str_, min(len_, s.len_)) > 0;
  }

  bool operator>=(const StringRef& s) const {
    return strncmp(str_, s.str_, min(len_, s.len_)) >= 0;
  }

  bool operator==(const StringRef& s) const {
    return (len_ == s.len_) &&
           strncmp(str_, s.str_, min(len_, s.len_)) == 0;
  }

  bool operator!=(const StringRef& s) const {
    return (len_ != s.len_) ||
           strncmp(str_, s.str_, min(len_, s.len_)) != 0;
  }

private:
  static unsigned min(unsigned x, unsigned y) {
    return (x <= y) ? x : y;
  }

  const char* str_;
  size_t      len_;
};

template<class T>
class ArrayRef {
public:
  typedef T* iterator;
  typedef const T* const_iterator;

  ArrayRef() : data_(nullptr), len_(0) { }
  ArrayRef(T* dat, size_t sz) : data_(dat), len_(sz) { }
  ArrayRef(T* begin, T* end)  : data_(begin), len_(end-begin) { }

  size_t size() const { return len_; }
  T& operator[](size_t i) { return data_[i]; }
  const T& operator[](size_t i) const { return data_[i]; }

  iterator begin() { return data_; }
  const_iterator begin() const { return begin(); }
  const_iterator cbegin() const { return begin(); }

  iterator end() { return data_ + len_; }
  const_iterator end() const { return end(); }
  const_iterator cend() const { return end(); }

private:
  T* data_;
  size_t len_;
};

template<class K, class V>
class DenseMap {
public:
  typedef typename std::unordered_map<K,V>::iterator iterator;
  typedef typename std::unordered_map<K,V>::const_iterator const_iterator;

  iterator       begin()       { return map_.begin(); }
  const_iterator begin() const { return map_.begin(); }
  iterator       end()         { return map_.end();   }
  const_iterator end() const   { return map_.end();   }

  iterator find(const K& k) {
    return map_.find(k);
  }
  const_iterator find(const K& k) const {
    return map_.find(k);
  }

  void insert(const std::pair<K, V> &KV) {
    map_.insert(KV);
  }
  void insert(std::pair<K, V> &&KV) {
    map_.insert(KV);
  }

  void shrink_and_clear() { map_.clear(); }

private:
  std::unordered_map<K, V> map_;
};

// Copies s to mem, and returns a StringRef of mem.
// Mem must have space for at least s.length()+1 bytes of data.
inline StringRef copyStringRef(char* mem, StringRef s) {
  unsigned len = s.size();
  strncpy(mem, s.c_str(), len);
  mem[len] = 0;
  return StringRef(mem, len);
}

inline std::ostream& operator<<(std::ostream& ss, const StringRef str) {
  return ss.write(str.data(), str.size());
}

} // end namespace ohmu

// Must be included after the above.
#include "base/DiagnosticEmitter.h"

#endif  // OHMU_BASE_LLVM_DEPENDENCIES_H


text:
import Preferences from 'src/client/preferences.js';

const AEXPR_IDENTIFIER_NAME = 'aexpr';
const FLAG_SHOULD_NOT_REWRITE_IDENTIFIER = Symbol('FLAG: should not rewrite identifier');

export default function({ types: t, template, traverse }) {
  const GENERATED_IMPORT_IDENTIFIER = Symbol("generated import identifier");

  function addCustomTemplate(file, name) {
    let declar = file.declarations[name];
    if (declar) return declar;

    let identifier = file.declarations[name] = file.addImport("active-expression-proxies", name, name);
    identifier[GENERATED_IMPORT_IDENTIFIER] = true;
    identifier[FLAG_SHOULD_NOT_REWRITE_IDENTIFIER] = true;
    return identifier;
  }

  return {
    visitor: {
      Program: {
        enter(path, state) {
          function hasDirective(path, name) {
            let foundDirective = false;
            path.traverse({
              Directive(path) {
                if(path.get("value").node.value === name) {
                  foundDirective = true;
                }
              }
            });
            return foundDirective;
          }

          function shouldTransform() {
            const proxyDirective = hasDirective(path, 'use proxies for aexprs');
            const proxyPreference = typeof Preferences == 'undefined' ? true : Preferences.get('UseProxiesForAExprs');
            const inWorkspace = state.opts.executedIn === 'workspace';
            const inFile = state.opts.executedIn === 'file';

            if (inWorkspace) {
              return proxyPreference;
            } else if (inFile) {
              return proxyDirective;
            }
            return true;
            // throw new Error('This should not be possible');
          }

          if (!shouldTransform()) { return; }

          function replaceNode(path, wrapType, unwrap = false) {
            // do not wrap the same object twice
            if (path.node.__already_transformed__) { return; }
            path.node.__already_transformed__ = true;

            let transformed;
            if (unwrap){
              transformed = t.callExpression(
                addCustomTemplate(state.file, 'unwrap'), [path.node])

            } else {
              transformed = t.callExpression(
                addCustomTemplate(state.file, 'wrap'), [t.stringLiteral(wrapType),path.node]
              );
            }
            path.replaceWith(transformed);
          }

          path.traverse({
            ObjectExpression(path) {
              // do not replace objects in calls to Object.defineProperty
              try {
                if(path.parent.callee.property.name === "defineProperty") {
                  return;
                }
              } catch(e) {
                // Once we can use the new ecma script2020 syntax this try-catch can be replaced by optional chaining
                // https://iolap.com/2019/09/27/whats-next-for-javascript-top-5-new-features-for-2020/
              }
              replaceNode(path, 'Object')
            },

            CallExpression(path) {
              // unwrap proxies in Object.defineProperty
              try {
                if(path.node.callee.property.name === "defineProperty" && path.node.arguments[2].type === "Identifier") {
                  path.node.arguments[2].__should_unwrap__ = true;
                }
              } catch(e) {
                // Once we can use the new ecma script2020 syntax this try-catch can be replaced by optional chaining
                // https://iolap.com/2019/09/27/whats-next-for-javascript-top-5-new-features-for-2020/
              }
            },

            NewExpression(path) {
              replaceNode(path, path.node.callee.name)

            },

            ArrayExpression(path) {
              replaceNode(path, 'Array')
            },

            Identifier(path) {
              if (path.node[FLAG_SHOULD_NOT_REWRITE_IDENTIFIER]) {
                return;
              }

              // Check for a call to undeclared aexpr:
              if (
                t.isCallExpression(path.parent) &&
                path.node.name === AEXPR_IDENTIFIER_NAME &&
                !path.scope.hasBinding(AEXPR_IDENTIFIER_NAME)
              ) {
                //logIdentifier("call to aexpr", path);
                path.replaceWith(
                  addCustomTemplate(state.file, AEXPR_IDENTIFIER_NAME)
                );
                return;
              }

              try {
                if(path.parent.callee.property.name === "defineProperty" && path.parent.arguments[2] === path.node) {
                  replaceNode(path, 'Proxy', true);
                }
              } catch(e) {
                // Once we can use the new ecma script2020 syntax this try-catch can be replaced by optional chaining
                // https://iolap.com/2019/09/27/whats-next-for-javascript-top-5-new-features-for-2020/
              }
            }
          })
        }
      }
    }
  };
}


text:
using System;

namespace Nonagon.Modular.DynamicForm.Service.ServiceInterface
{
	public class DynamicFormService : ServiceStack.ServiceInterface.Service
	{
		private DynamicFormInterface dynamicFormInterface =
			ModuleManager.GetInstance<DynamicFormModule>().GetModuleInterface();

		public Object Get(GetForms param)
		{
			if(param == null)
				throw new ArgumentException("param");

			return dynamicFormInterface.GetForms(param);
		}

		public Object Get(GetFormDetails param)
		{
			if(param == null)
				throw new ArgumentException("param");

			return dynamicFormInterface.GetFormDetails(param);
		}

		public Object Get(GetFormInstanceDetails param)
		{
			if(param == null)
				throw new ArgumentException("param");

			return dynamicFormInterface.GetFormInstanceDetails(param);
		}

		public Object Get(GetFormInstanceDetailsByRef param)
		{
			if(param == null)
				throw new ArgumentException("param");

			return dynamicFormInterface.GetFormInstanceDetails(param);
		}

		public Object Post(StoreForm param)
		{
			if(param == null)
				throw new ArgumentException("param");

			return dynamicFormInterface.StoreForm(param);
		}

		public Object Post(StoreFormInstance param)
		{
			if(param == null)
				throw new ArgumentException("param");

			return dynamicFormInterface.StoreFormInstance(param);
		}

		public Object Delete(DeleteForm param)
		{
			if(param == null)
				throw new ArgumentException("param");

			return dynamicFormInterface.DeleteForm(param);
		}

		public Object Delete(DeleteFormInstace param)
		{
			if(param == null)
				throw new ArgumentException("param");

			return dynamicFormInterface.DeleteFormInstance(param);
		}
	}
}


text:
<?php

namespace RandomLibTest\Mocks\Random;

use SecurityLib\Strength;

/**
 * The Random Number Source interface.
 *
 * All random number sources must implement this interface
 *
 * @category   PHPPasswordLib
 * @package    Random
 * @author     Anthony Ferrara <ircmaxell@ircmaxell.com>
 */
class Source extends \RandomLibTest\Mocks\AbstractMock implements \RandomLib\Source {

    public static $strength = null;

    public static function init() {
        static::$strength = new Strength(Strength::VERYLOW);
    }

    /**
     * Return an instance of Strength indicating the strength of the source
     *
     * @return Strength An instance of one of the strength classes
     */
    public static function getStrength() {
        return static::$strength;
    }

    /**
     * Generate a random string of the specified size
     *
     * Note: If the source fails to generate enough data, the result must be
     * padded to the requested length.
     *
     * @param int $size The size of the requested random string
     *
     * @return string A string of the requested size
     */
    public function generate($size) {
        return $this->__call('generate', array($size));
    }

}


text:
import React from 'react';
import * as UI from 'editor-ui-lib';

class Input extends React.Component {
    render() {
        return (

                <UI.fontPicker title="Input"
                               wix-param="design_input">
                </UI.fontPicker>

                <UI.fontPicker title="Input placeholder"
                               wix-param="design_input_placeholder">
                </UI.fontPicker>

        )
    }
}

export default Input;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="screen_width">1280dp</dimen>
</resources>


text:
package org.bitcoins.core.script.stack

import org.bitcoins.core.script.ScriptOperationFactory
import org.bitcoins.core.script.constant.ScriptOperation

/** Created by chris on 1/6/16.
  */
sealed trait StackOperation extends ScriptOperation

/** Puts the input onto the top of the alt stack. Removes it from the main stack.
  */
case object OP_TOALTSTACK extends StackOperation {
  override val opCode: Int = 107
}

/** Puts the input onto the top of the main stack. Removes it from the alt stack.
  */
case object OP_FROMALTSTACK extends StackOperation {
  override val opCode: Int = 108
}

/** If the top stack value is not 0, duplicate it.
  */
case object OP_IFDUP extends StackOperation {
  override val opCode: Int = 115
}

/** Puts the number of stack items onto the stack.
  */
case object OP_DEPTH extends StackOperation {
  override val opCode: Int = 116
}

/** Removes the top stack item
  */
case object OP_DROP extends StackOperation {
  override val opCode: Int = 117
}

/**  Duplicates the top stack item.
  */
case object OP_DUP extends StackOperation {
  override val opCode: Int = 118
}

/** Removes the second-to-top stack item.
  */
case object OP_NIP extends StackOperation {
  override val opCode: Int = 119
}

/**  Copies the second-to-top stack item to the top.
  */
case object OP_OVER extends StackOperation {
  override val opCode: Int = 120
}

/** The item n back in the stack is copied to the top.
  */
case object OP_PICK extends StackOperation {
  override val opCode: Int = 121
}

/** The item n back in the stack is moved to the top.
  */
case object OP_ROLL extends StackOperation {
  override val opCode: Int = 122
}

/** The top three items on the stack are rotated to the left.
  */
case object OP_ROT extends StackOperation {
  override val opCode: Int = 123
}

/**  The top two items on the stack are swapped.
  */
case object OP_SWAP extends StackOperation {
  override val opCode: Int = 124
}

/** The item at the top of the stack is copied and inserted before the second-to-top item.
  */
case object OP_TUCK extends StackOperation {
  override val opCode: Int = 125
}

/**  Removes the top two stack items.
  */
case object OP_2DROP extends StackOperation {
  override val opCode: Int = 109
}

/** Duplicates the top two stack items
  */
case object OP_2DUP extends StackOperation {
  override val opCode: Int = 110
}

/** Duplicates the top 3 stack items
  */
case object OP_3DUP extends StackOperation {
  override val opCode: Int = 111
}

/** Copies the pair of items two spaces back in the stack to the front.
  */
case object OP_2OVER extends StackOperation {
  override val opCode: Int = 112
}

/** The fifth and sixth items back are moved to the top of the stack.
  */
case object OP_2ROT extends StackOperation {
  override val opCode: Int = 113
}

/**  Swaps the top two pairs of items.
  */
case object OP_2SWAP extends StackOperation {
  override val opCode: Int = 114
}

object StackOperation extends ScriptOperationFactory[StackOperation] {

  override val operations =
    Vector(
      OP_DUP,
      OP_TOALTSTACK,
      OP_FROMALTSTACK,
      OP_IFDUP,
      OP_DEPTH,
      OP_DEPTH,
      OP_DROP,
      OP_NIP,
      OP_OVER,
      OP_ROLL,
      OP_ROT,
      OP_SWAP,
      OP_TUCK,
      OP_2DROP,
      OP_2DUP,
      OP_3DUP,
      OP_2OVER,
      OP_2ROT,
      OP_2SWAP,
      OP_PICK
    )
}


text:
package com.yandex.money.api.net;

import java.io.IOException;
import java.io.InputStream;

/**
 * HTTP client must wrap its response in this interface.
 */
public interface HttpClientResponse {

    /**
     * Gets the HTTP status code.
     *
     * @return HTTP status code
     */
    int getCode();

    /**
     * Gets the HTTP status message.
     *
     * @return HTTP status message
     */
    String getMessage();

    /**
     * Request URL used to get a response.
     *
     * @return url
     */
    String getUrl();

    /**
     * Gets header by its name. Returns {@code null} if no value is present for this header.
     *
     * @param name name of the header
     * @return value or {@code null} if no header found for this name
     */
    String getHeader(String name);

    /**
     * Returns body as UTF-8 string.
     *
     * @return body
     * @throws IOException if unable to read response stream
     */
    String getBody() throws IOException;

    /**
     * Gets byte stream of the response.
     *
     * @return byte stream
     */
    InputStream getByteStream();
}


text:
import * as React from "react";
import {
  DataToolbarChip,
  DataToolbarGroup,
  DataToolbarFilter,
  DataToolbarItem,
  DataToolbarToggleGroup,
  DataToolbar,
  DataToolbarContent
} from "@patternfly/react-core/dist/js/experimental";
import {
  Dropdown,
  DropdownToggle,
  DropdownItem,
  InputGroup,
  Button,
  ButtonVariant,
  Badge,
  SelectOption,
  SelectOptionObject,
  Select,
  SelectVariant
} from "@patternfly/react-core";
import { FilterIcon, SearchIcon } from "@patternfly/react-icons";
import useWindowDimensions from "components/common/WindowDimension";
import { ISortBy } from "@patternfly/react-table";
import { SortForMobileView } from "components/common/SortForMobileView";
import { useApolloClient } from "@apollo/react-hooks";
import { RETURN_ALL_CONNECTIONS_HOSTNAME_AND_CONTAINERID_OF_ADDRESS_SPACES_FOR_TYPEAHEAD_SEARCH } from "queries";
import { IConnectionListNameSearchResponse } from "types/ResponseTypes";
import {
  TypeAheadMessage,
  TYPEAHEAD_REQUIRED_LENGTH,
  MAX_ITEM_TO_DISPLAY_IN_TYPEAHEAD_DROPDOWN,
  NUMBER_OF_RECORDS_TO_DISPLAY_IF_SERVER_HAS_MORE_DATA,
  FetchPolicy
} from "constants/constants";
import { getSelectOptionList, ISelectOption } from "utils";

interface IConnectionListFilterProps {
  filterValue?: string | null;
  setFilterValue: (value: string) => void;
  hostnames: Array<any>;
  setHostnames: (value: Array<any>) => void;
  containerIds: Array<any>;
  setContainerIds: (value: Array<any>) => void;
  sortValue?: ISortBy;
  setSortValue: (value: ISortBy) => void;
  totalConnections: number;
  addressSpaceName?: string;
  namespace?: string;
}
export const ConnectionListFilter: React.FunctionComponent<IConnectionListFilterProps> = ({
  filterValue,
  setFilterValue,
  hostnames,
  setHostnames,
  containerIds,
  setContainerIds,
  totalConnections,
  sortValue,
  setSortValue,
  addressSpaceName,
  namespace
}) => {
  const { width } = useWindowDimensions();
  const client = useApolloClient();
  const [filterIsExpanded, setFilterIsExpanded] = React.useState(false);
  const onFilterSelect = (event: any) => {
    setFilterValue(event.target.value);
    setFilterIsExpanded(!filterIsExpanded);
  };
  const [
    isSelectHostnameExpanded,
    setIsSelectHostnameExpanded
  ] = React.useState<boolean>(false);
  const [
    isSelectContainerExpanded,
    setIsSelectContainerExpanded
  ] = React.useState<boolean>(false);
  const [hostnameSelected, setHostnameSelected] = React.useState<string>();
  const [containerSelected, setContainerSelected] = React.useState<string>();
  const [hostNameInput, setHostNameInput] = React.useState<string>("");
  const [containerInput, setContainerInput] = React.useState<string>("");
  const [hostnameOptions, setHostnameOptions] = React.useState<
    Array<ISelectOption>
  >();
  const [containerOptions, setContainerOptions] = React.useState<
    Array<ISelectOption>
  >();

  const filterMenuItems = [
    { key: "filterHostName", value: "Hostname" },
    { key: "filterContainer", value: "Container" }
  ];

  const sortMenuItems = [
    { key: "hostname", value: "Hostname", index: 0 },
    { key: "containerId", value: "Container ID", index: 1 },
    { key: "protocol", value: "Protocol", index: 2 },
    { key: "messageIn", value: "Message In", index: 3 },
    { key: "messageOut", value: "Message Out", index: 4 },
    { key: "sender", value: "Senders", index: 5 },
    { key: "receiver", value: "Receivers", index: 6 }
  ];

  const onClickSearchIcon = (event: any) => {
    if (filterValue)
      if (filterValue === "Container") {
        if (
          containerSelected &&
          containerSelected.trim() !== "" &&
          containerIds
        ) {
          if (
            containerIds
              .map(filter => filter.value)
              .indexOf(containerSelected.trim()) < 0
          ) {
            setContainerIds([
              ...containerIds,
              { value: containerSelected.trim(), isExact: true }
            ]);
          }
          setContainerSelected(undefined);
        }
        if (
          !containerSelected &&
          containerInput &&
          containerInput.trim() !== "" &&
          containerIds
        ) {
          if (
            containerIds
              .map(filter => filter.value)
              .indexOf(containerInput.trim()) < 0
          )
            setContainerIds([
              ...containerIds,
              { value: containerInput.trim(), isExact: false }
            ]);
          setContainerSelected(undefined);
        }
      } else if (filterValue === "Hostname") {
        if (hostnameSelected && hostnameSelected.trim() !== "" && hostnames) {
          if (
            hostnames.map(filter => filter.value).indexOf(hostnameSelected) < 0
          ) {
            setHostnames([
              ...hostnames,
              { value: hostnameSelected.trim(), isExact: true }
            ]);
          }
          setHostnameSelected(undefined);
        }
        if (!hostnameSelected && hostNameInput.trim() !== "" && hostnames) {
          if (hostnames.map(filter => filter.value).indexOf(hostNameInput) < 0)
            setHostnames([
              ...hostnames,
              { value: hostNameInput.trim(), isExact: false }
            ]);
          setHostnameSelected(undefined);
        }
      }
  };

  const onHostnameSelectToggle = () => {
    setIsSelectHostnameExpanded(!isSelectHostnameExpanded);
  };

  const onContainerSelectToggle = () => {
    setIsSelectContainerExpanded(!isSelectContainerExpanded);
  };

  const onChangeHostnameData = async (value: string) => {
    setHostnameOptions(undefined);
    if (value.trim().length < TYPEAHEAD_REQUIRED_LENGTH) {
      setHostnameOptions([]);
      return;
    }
    const response = await client.query<IConnectionListNameSearchResponse>({
      query: RETURN_ALL_CONNECTIONS_HOSTNAME_AND_CONTAINERID_OF_ADDRESS_SPACES_FOR_TYPEAHEAD_SEARCH(
        true,
        value.trim(),
        addressSpaceName,
        namespace
      ),
      fetchPolicy: FetchPolicy.NETWORK_ONLY
    });
    if (
      response &&
      response.data &&
      response.data.connections &&
      response.data.connections.connections &&
      response.data.connections.connections.length > 0
    ) {
      const obtainedList = response.data.connections.connections.map(
        (connection: any) => {
          return connection.spec.hostname;
        }
      );
      //get list of unique records to display in the select dropdown based on total records and 100 fetched objects
      const uniqueList = getSelectOptionList(
        obtainedList,
        response.data.connections.total
      );
      if (uniqueList.length > 0) setHostnameOptions(uniqueList);
    }
  };

  const onHostnameSelectFilterChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    setHostNameInput(e.target.value);
    onChangeHostnameData(e.target.value);
    const options: React.ReactElement[] = hostnameOptions
      ? hostnameOptions.map((option, index) => (
          <SelectOption key={index} value={option} />
        ))
      : [];
    return options;
  };

  const onChangeContainerData = async (value: string) => {
    setContainerOptions(undefined);
    if (value.trim().length < TYPEAHEAD_REQUIRED_LENGTH) {
      setContainerOptions([]);
      return;
    }
    const response = await client.query<IConnectionListNameSearchResponse>({
      query: RETURN_ALL_CONNECTIONS_HOSTNAME_AND_CONTAINERID_OF_ADDRESS_SPACES_FOR_TYPEAHEAD_SEARCH(
        false,
        value.trim(),
        addressSpaceName,
        namespace
      ),
      fetchPolicy: FetchPolicy.NETWORK_ONLY
    });
    if (
      response &&
      response.data &&
      response.data.connections &&
      response.data.connections.connections &&
      response.data.connections.connections.length > 0
    ) {
      const obtainedList = response.data.connections.connections.map(
        (connection: any) => {
          return connection.spec.containerId;
        }
      );
      //get list of unique records to display in the select dropdown based on total records and 100 fetched objects
      const uniqueList = getSelectOptionList(
        obtainedList,
        response.data.connections.total
      );
      if (uniqueList.length > 0) setContainerOptions(uniqueList);
    }
  };
  const onContainerSelectFilterChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    setContainerInput(e.target.value);
    onChangeContainerData(e.target.value);
    const options: React.ReactElement[] = containerOptions
      ? containerOptions.map((option, index) => (
          <SelectOption key={index} value={option} />
        ))
      : [];
    return options;
  };

  const onHostnameSelect = (
    event: any,
    selection: string | SelectOptionObject
  ) => {
    setHostnameSelected(selection.toString());
    setIsSelectHostnameExpanded(false);
  };

  const onContainerSelect = (
    event: any,
    selection: string | SelectOptionObject
  ) => {
    setContainerSelected(selection.toString());
    setIsSelectContainerExpanded(false);
  };

  const onDelete = (
    type: string | DataToolbarChip,
    id: string | DataToolbarChip
  ) => {
    let index;

    switch (type) {
      case "Hostname":
        if (hostnames && id) {
          index = hostnames.map(filter => filter.value).indexOf(id.toString());
          if (index >= 0) hostnames.splice(index, 1);
          setHostnames([...hostnames]);
        }
        break;
      case "Container":
        if (containerIds && id) {
          const containers = containerIds;
          index = containerIds
            .map(filter => filter.value)
            .indexOf(id.toString());
          if (index >= 0) containers.splice(index, 1);
          setContainerIds([...containers]);
        }
        break;
    }
  };
  const clearAllFilters = () => {
    setHostnames([]);
    setContainerIds([]);
  };

  const checkIsFilterApplied = () => {
    if (
      (containerIds && containerIds.length > 0) ||
      (hostnames && hostnames.length > 0)
    ) {
      return true;
    }
    return false;
  };

  const toggleGroupItems = (
    <>
      <DataToolbarGroup variant="filter-group">
        <DataToolbarFilter categoryName="Filter">
          <Dropdown
            id="cl-filter-dropdown"
            position="left"
            onSelect={onFilterSelect}
            isOpen={filterIsExpanded}
            toggle={
              <DropdownToggle onToggle={setFilterIsExpanded}>
                <FilterIcon />

                {filterValue && filterValue.trim() !== ""
                  ? filterValue
                  : "Filter"}
              </DropdownToggle>
            }
            dropdownItems={filterMenuItems.map(option => (
              <DropdownItem
                id={`cl-filter-dropdown-item${option.key}`}
                key={option.key}
                value={option.value}
                itemID={option.key}
                component={"button"}
              >
                {option.value}
              </DropdownItem>
            ))}
          />
        </DataToolbarFilter>
        <DataToolbarItem>
          <DataToolbarFilter
            chips={hostnames.map(filter => filter.value)}
            deleteChip={onDelete}
            categoryName="Hostname"
          >
            {filterValue && filterValue === "Hostname" && (
              <InputGroup>
                <Select
                  id="cl-filter-select-hostname"
                  variant={SelectVariant.typeahead}
                  aria-label="Select a hostname"
                  onToggle={onHostnameSelectToggle}
                  onSelect={onHostnameSelect}
                  onClear={() => {
                    setHostnameSelected(undefined);
                    setIsSelectHostnameExpanded(false);
                  }}
                  maxHeight="200px"
                  selections={hostnameSelected}
                  onFilter={onHostnameSelectFilterChange}
                  isExpanded={isSelectHostnameExpanded}
                  ariaLabelledBy={"typeahead-select-id"}
                  placeholderText="Select Hostname"
                  isDisabled={false}
                  isCreatable={false}
                >
                  {hostnameOptions && hostnameOptions.length > 0 ? (
                    hostnameOptions.map((option, index) => (
                      <SelectOption
                        key={index}
                        value={option.value}
                        isDisabled={option.isDisabled}
                      />
                    ))
                  ) : hostNameInput.trim().length <
                    TYPEAHEAD_REQUIRED_LENGTH ? (
                    <SelectOption
                      key={"invalid-input-length"}
                      value={TypeAheadMessage.MORE_CHAR_REQUIRED}
                      disabled={true}
                    />
                  ) : (
                    <SelectOption
                      key={"no-results-found"}
                      value={TypeAheadMessage.NO_RESULT_FOUND}
                      disabled={true}
                    />
                  )}
                  {/* {} */}
                </Select>
                <Button
                  id="cl-filter-search-btn"
                  variant={ButtonVariant.control}
                  aria-label="search button for search input"
                  onClick={onClickSearchIcon}
                >
                  <SearchIcon />
                </Button>
              </InputGroup>
            )}
          </DataToolbarFilter>
        </DataToolbarItem>
        <DataToolbarItem>
          <DataToolbarFilter
            chips={containerIds.map(filter => filter.value)}
            deleteChip={onDelete}
            categoryName="Container"
          >
            {filterValue && filterValue === "Container" && (
              <InputGroup>
                <Select
                  id="cl-filter-select-address"
                  variant={SelectVariant.typeahead}
                  aria-label="Select a Address"
                  onToggle={onContainerSelectToggle}
                  onSelect={onContainerSelect}
                  onClear={() => {
                    setContainerSelected(undefined);
                    setIsSelectContainerExpanded(false);
                  }}
                  maxHeight="200px"
                  selections={containerSelected}
                  onFilter={onContainerSelectFilterChange}
                  isExpanded={isSelectContainerExpanded}
                  ariaLabelledBy={"typeahead-select-id"}
                  placeholderText="Select Container"
                  isDisabled={false}
                  isCreatable={false}
                >
                  {containerOptions && containerOptions.length > 0 ? (
                    containerOptions.map((option, index) => (
                      <SelectOption
                        key={index}
                        value={option.value}
                        isDisabled={option.isDisabled}
                      />
                    ))
                  ) : containerInput.trim().length <
                    TYPEAHEAD_REQUIRED_LENGTH ? (
                    <SelectOption
                      key={"invalid-input-length"}
                      value={TypeAheadMessage.MORE_CHAR_REQUIRED}
                      disabled={true}
                    />
                  ) : (
                    <SelectOption
                      key={"no-results-found"}
                      value={TypeAheadMessage.NO_RESULT_FOUND}
                      disabled={true}
                    />
                  )}
                  {/* {} */}
                </Select>
                <Button
                  id="cl-filter-search"
                  variant={ButtonVariant.control}
                  aria-label="search button for search input"
                  onClick={onClickSearchIcon}
                >
                  <SearchIcon />
                </Button>
              </InputGroup>
            )}
          </DataToolbarFilter>
        </DataToolbarItem>
      </DataToolbarGroup>
    </>
  );
  const toolbarItems = (
    <>
      <DataToolbarToggleGroup
        toggleIcon={
          <>
            <FilterIcon />
            {checkIsFilterApplied() && (
              <Badge key={1} isRead>
                {totalConnections}
              </Badge>
            )}
          </>
        }
        breakpoint="xl"
      >
        {toggleGroupItems}
      </DataToolbarToggleGroup>
      {width < 769 && (
        <SortForMobileView
          sortMenu={sortMenuItems}
          sortValue={sortValue}
          setSortValue={setSortValue}
        />
      )}
    </>
  );
  return (
    <>
      <DataToolbar
        id="data-toolbar-with-filter"
        className="pf-m-toggle-group-container"
        collapseListedFiltersBreakpoint="md"
        clearAllFilters={clearAllFilters}
      >
        <DataToolbarContent>{toolbarItems}</DataToolbarContent>
      </DataToolbar>
    </>
  );
};


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Hie.Core.Endpoints
{
	[TestClass]
	public class TcpReceiveEndpointTest
	{
		[TestMethod]
		public void EndpointInterfaceLifecycleTest()
		{
			// Host
			var host = new Mock<IApplicationHost>();

			// Endpoint to test
			TcpReceiveEndpoint receiveEndpoint = new TcpReceiveEndpoint();

			receiveEndpoint.Initialize(host.Object, new TcpReceieveOptions() { Endpoint = new IPEndPoint(IPAddress.Any, 6799), NoDelay = true, ReceiveBufferSize = 8192 });
			receiveEndpoint.StartProcessing();

			// Try connection two clients and process messages

			Stopwatch watch = new Stopwatch();
			watch.Start();
			{
				TcpClient client = new TcpClient();
				client.NoDelay = true;
				client.Connect(IPAddress.Loopback, 6799);
				client.GetStream().Write(new byte[] { TcpReceieveOptions.SOH }, 0, 1);

				// Lets try a bit more message .. just for the fun of it ..
				for (int i = 0; i < 100; i++)
				{
					client.GetStream().Write(new byte[] { TcpReceieveOptions.STX, 0x41, 0x41, 0x41, 0x41, TcpReceieveOptions.ETX }, 0, 6);
					receiveEndpoint.WaitForMessage();
				}
				client.GetStream().Write(new byte[] { TcpReceieveOptions.EOT }, 0, 1);
				client.Close();
			}

			//Assert.IsFalse(true, "{0}", watch.ElapsedMilliseconds);

			{
				TcpClient client = new TcpClient();
				client.NoDelay = true;
				client.Connect(IPAddress.Loopback, 6799);
				client.GetStream().Write(new byte[] { TcpReceieveOptions.SOH }, 0, 1);
				client.GetStream().Write(new byte[] { TcpReceieveOptions.STX, 0x41, 0x41, 0x41, 0x41, TcpReceieveOptions.ETX }, 0, 6);
				receiveEndpoint.WaitForMessage();
				client.GetStream().Write(new byte[] { TcpReceieveOptions.STX, 0x41, 0x41, 0x41, 0x41, TcpReceieveOptions.ETX }, 0, 6);
				receiveEndpoint.WaitForMessage();
				client.GetStream().Write(new byte[] { TcpReceieveOptions.EOT }, 0, 1);
				client.Close();
			}

			receiveEndpoint.StopProcessing();
			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.IsNotNull<byte[]>()), Times.Exactly(102));
			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.Is<byte[]>(indata => indata.SequenceEqual(new byte[] { 0x41, 0x41, 0x41, 0x41 }))));
		}

		[TestMethod]
		public void TcpReceiveEndpointSingleByteDelimitersTest()
		{
			var options = new TcpReceieveOptions();
			TcpReceiveEndpoint endpoint = new TcpReceiveEndpoint(new IPEndPoint(IPAddress.Any, 6789), options);
			var host = new Mock<IApplicationHost>();
			endpoint.Initialize(host.Object, options);

			StateObject state = new StateObject(null);

			List<byte> data = new List<byte>();
			data.AddRange(new byte[] { TcpReceieveOptions.SOH });
			data.AddRange(new byte[] { TcpReceieveOptions.STX, 0x41, 0x41, 0x41, 0x41, TcpReceieveOptions.ETX });
			data.AddRange(new byte[] { TcpReceieveOptions.EOT });
			data.CopyTo(state.Buffer, 0);

			bool isEot = endpoint.ProcessIncomingStream(state.Buffer.Length, state);

			Assert.IsTrue(isEot);
			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.IsNotNull<byte[]>()), Times.Once);
			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.Is<byte[]>(indata => indata.SequenceEqual(new byte[] { 0x41, 0x41, 0x41, 0x41 }))));
		}

		[TestMethod]
		public void TcpReceiveEndpointMultiByteDelimitersTest()
		{
			var options = new TcpReceieveOptions();
			options.SohDelimiters = new byte[] { TcpReceieveOptions.SOH, 0x06 };
			options.StxDelimiters = new byte[] { TcpReceieveOptions.STX, 0x06 };
			options.EtxDelimiters = new byte[] { TcpReceieveOptions.ETX, 0x06 };
			options.EotDelimiters = new byte[] { TcpReceieveOptions.EOT, 0x07 };
			//BUG: If the end-delimiter of STX and EOT match it will not detect EOT
			//options.EOTDelimiters = new byte[] {TcpReceiveEndpoint.EOT, 0x06};

			TcpReceiveEndpoint endpoint = new TcpReceiveEndpoint(new IPEndPoint(IPAddress.Any, 6789), options);
			var host = new Mock<IApplicationHost>();
			endpoint.Initialize(host.Object, options);

			StateObject state = new StateObject(null);

			List<byte> data = new List<byte>();
			data.AddRange(options.SohDelimiters);
			data.AddRange(options.StxDelimiters);
			data.AddRange(new byte[] { 0x41, 0x41, 0x41, 0x41 });
			data.AddRange(options.EtxDelimiters);
			data.AddRange(options.EotDelimiters);
			data.CopyTo(state.Buffer, 0);

			bool isEot = endpoint.ProcessIncomingStream(state.Buffer.Length, state);

			Assert.IsTrue(isEot);
			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.IsNotNull<byte[]>()), Times.Once);
			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.Is<byte[]>(indata => indata.SequenceEqual(new byte[] { 0x41, 0x41, 0x41, 0x41 }))));
		}

		[TestMethod]
		public void TcpReceiveEndpointMultiByteDelimitersSplittedBufferTest()
		{
			var options = new TcpReceieveOptions();
			options.SohDelimiters = new byte[] { TcpReceieveOptions.SOH, 0x06 };
			options.StxDelimiters = new byte[] { TcpReceieveOptions.STX, 0x06 };
			options.EtxDelimiters = new byte[] { TcpReceieveOptions.ETX, 0x06 };
			options.EotDelimiters = new byte[] { TcpReceieveOptions.EOT, 0x07 };

			TcpReceiveEndpoint endpoint = new TcpReceiveEndpoint(new IPEndPoint(IPAddress.Any, 6789), options);
			var host = new Mock<IApplicationHost>();
			endpoint.Initialize(host.Object, options);

			StateObject state = new StateObject(null);

			List<byte> data = new List<byte>();
			data.AddRange(options.SohDelimiters);
			data.AddRange(options.StxDelimiters);
			data.AddRange(new byte[] { 0x41, 0x41, 0x41, 0x41 });
			data.AddRange(options.EtxDelimiters);
			data.AddRange(options.EotDelimiters);

			bool isEot = false;

			for (int i = 0; i < data.Count; i++)
			{
				state.State = StateObject.FrameState.FindSoh;

				int noBytesInFirstBuffer = i;
				data.CopyTo(0, state.Buffer, 0, noBytesInFirstBuffer);

				isEot = endpoint.ProcessIncomingStream(noBytesInFirstBuffer, state);
				Assert.IsFalse(isEot);

				data.CopyTo(noBytesInFirstBuffer, state.Buffer, 0, data.Count - noBytesInFirstBuffer);
				isEot = endpoint.ProcessIncomingStream(data.Count - noBytesInFirstBuffer, state);
				Assert.IsTrue(isEot);
			}

			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.IsNotNull<byte[]>()), Times.AtLeast(3));
			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.Is<byte[]>(indata => indata.SequenceEqual(new byte[] { 0x41, 0x41, 0x41, 0x41 }))));
		}

		[TestMethod]
		public void TcpReceiveEndpointMissingTransmissionDelimitersTest()
		{
			var options = new TcpReceieveOptions();
			options.SohDelimiters = new byte[] { };
			options.EotDelimiters = new byte[] { };

			TcpReceiveEndpoint endpoint = new TcpReceiveEndpoint(new IPEndPoint(IPAddress.Any, 6789), options);
			var host = new Mock<IApplicationHost>();
			endpoint.Initialize(host.Object, options);

			StateObject state = new StateObject(null);

			List<byte> data = new List<byte>();
			data.AddRange(options.SohDelimiters);
			data.AddRange(options.StxDelimiters);
			data.AddRange(new byte[] { 0x41, 0x41, 0x41, 0x41 });
			data.AddRange(options.EtxDelimiters);
			data.AddRange(options.EotDelimiters);
			data.CopyTo(state.Buffer, 0);

			bool isEot = endpoint.ProcessIncomingStream(state.Buffer.Length, state);

			Assert.IsFalse(isEot);

			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.IsNotNull<byte[]>()), Times.Once);
			host.Verify(app => app.ProcessInPipeline(It.IsAny<TcpReceiveEndpoint>(), It.Is<byte[]>(indata => indata.SequenceEqual(new byte[] { 0x41, 0x41, 0x41, 0x41 }))));
		}
	}
}


text:
function ApplicationTabGroup(Window) {
	//create module instance
	var self = Ti.UI.createTabGroup();

	//create app tabs
	var winCatalog = new Window(L('catalog')),
		winCart = new Window(L('cart')),
		winAccount = new Window(L('account')),
		winFavorites = new Window(L('favorites'));

	var tabCatalog = Ti.UI.createTab({
		title: L('catalog'),
		icon: '/images/KS_nav_ui.png',
		window: winCatalog
	});
	winCatalog.containingTab = tabCatalog;

	var tabFavorites = Ti.UI.createTab({
		title: L('favorites'),
		icon: '/images/KS_nav_views.png',
		window: winFavorites
	});
	winFavorites.containingTab = tabFavorites;

	var tabCart = Ti.UI.createTab({
		title: L('cart'),
		icon: '/images/KS_nav_views.png',
		window: winCart
	});
	winCart.containingTab = tabCart;

	var tabAccount = Ti.UI.createTab({
		title: L('account'),
		icon: '/images/KS_nav_views.png',
		window: winAccount
	});
	winAccount.containingTab = tabAccount;

	self.addTab(tabCatalog);
	self.addTab(tabFavorites);
	self.addTab(tabCart);
	self.addTab(tabAccount);

	return self;
};

module.exports = ApplicationTabGroup;


text:
function [data fs] = sndfile_load (filename)

if (nargin != 1),
	error ("Need an input filename") ;
	endif

samplerate = -1 ;
samplingrate = -1 ;
wavedata = -1 ;

eval (sprintf ('load -f %s', filename)) ;

if (samplerate > 0),
	fs = samplerate ;
elseif (samplingrate > 0),
	fs = samplingrate ;
else
	error ("Not able to find sample rate.") ;
	endif

if (max (size (wavedata)) > 1),
	data = wavedata ;
else
	error ("Not able to find waveform data.") ;
	endif

endfunction


text:
{% extends "base.html" %}
{% comment %}

{% endcomment %}

{% block navigation %}
        admin
{% endblock %}

{% block content %}

    {% for project in project_list %}

{{project}}

                View

    {% endfor %}

{% endblock %}

{% block footer %}

gm_pr

View on Github

About Genymobile

{% endblock %}


text:
import React, {Component} from "react";
import boards from "./data.json";
import "./styles.scss";
import Game from "./game";

class App extends Component {
  state = {
    dragging: null,
  };
  render() {
    const {dragging} = this.state;
    const board = boards.find(
      b => b.id === this.props.id.replace("robozzle-", ""),
    );
    return (
      <div className={`robozzle-root ${dragging ? "dragging" : ""}`}>
        {board && (
          <Game
            key={this.props.id}
            setDragging={which => this.setState({dragging: which})}
            board={board}
            onWin={this.props.onWin || (() => {})}
          />
        )}
      </div>
    );
  }
}
export default App;


text:
"""A test module to exercise the Ceilometer API with gabbi

For the sake of exploratory development.
"""

import os

from gabbi import driver

from ceilometer.tests.functional.gabbi import fixtures as fixture_module

TESTS_DIR = 'gabbits'

def load_tests(loader, tests, pattern):
    """Provide a TestSuite to the discovery process."""
    test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
    return driver.build_tests(test_dir, loader, host=None,
                              intercept=fixture_module.setup_app,
                              fixture_module=fixture_module)


text:
#ifndef __HTML_EXPORT_H__
#define __HTML_EXPORT_H__

#include <iostream>
#include <fstream>

#include "String.h"
#include "wx.h"
#include "callsign.h"
#include "adress.h"
#include "destin.h"
#include "zeit.h"

#define EXPORT_MASK_NO         0
#define EXPORT_MASK_DX         1
#define EXPORT_MASK_WX         2
#define EXPORT_MASK_PRIV       4
#define EXPORT_MASK_BUL        8
#define EXPORT_MASK_CONDX     16

#define EXPORT_MASK_ID_DX      'D'
#define EXPORT_MASK_ID_WX      'W'
#define EXPORT_MASK_ID_PRIV    'P'
#define EXPORT_MASK_ID_BUL     'B'
#define EXPORT_MASK_ID_CONDX   'C'

class Error_could_not_initialize_exportsystem
{
#ifdef _DEBUG_EXEC_
 public:
  Error_could_not_initialize_exportsystem()
    {
      cerr << "Error_could_not_initialize_exportsystem" << endl;
    }
#endif
};

class Error_could_not_open_export_file
{
#ifdef _DEBUG_EXEC_
 public:
  Error_could_not_open_export_file()
    {
      cerr << "Error_could_not_open_export_file" << endl;
    }
#endif
};

class Error_wrong_id_in_exportmask
{
#ifdef _DEBUG_EXEC_
 public:
  Error_wrong_id_in_exportmask()
    {
      cerr << "Error_wrong_id_in_exportmask" << endl;
    }
#endif
};

class Error_in_exportmask_syntax
{
#ifdef _DEBUG_EXEC_
 public:
  Error_in_exportmask_syntax()
    {
      cerr << "Error_in_exportmask_syntax" << endl;
    }
#endif
};

class export_sys
{
 protected:
  unsigned int maske;
  String exportpfad;

 protected:
  void get_file( ofstream&, char );

 public:
  export_sys( void );

  String get_mask( void );
  void set_mask( String  );

#ifdef COMPILE_CLUSTER
  void write_dx( const String& );
  void write_condx( const String& );
#endif
#ifdef COMPILE_WX
  void write_wx( const wx_meldung & );
#endif
  void write_user(const callsign&, const callsign&, zeit, adress, String, bool, const destin&, unsigned int );
  void write_bul( const callsign&, zeit, int, int, String, bool, const destin&, unsigned int, bool = false);
};

#endif // __HTML_EXPORT_H__