<commit_before>//Language & messages configuration
//Note: also see /config/messages.json for further messages configuration
var lsmsg = {
    "defaultLanguage" : "en",
    "msgs": {
        "en":{
              privateMessage: 'Private',
              settings: 'Settings',
              uploadImagesTitle: 'Upload images.',
              uploadImagesTitleSorry: 'Sorry image uploads are only supported on IE10+, or any other browser.',
              sendTo: 'Send to',
              emoticonsTitle: 'Emoticons',
              helpURL: 'https://atomjump.com/wp/user-guide/',
              helpTitle: 'Help'
        },
        "es":{
              privateMessage: 'Privado',
              settings: 'Ajustes',
              uploadImagesTitle: 'Sube imágenes.',
              uploadImagesTitleSorry: 'La subida de imágenes Lo siento, sólo se admiten en IE10+, o cualquier otro navegador.',
              sendTo: 'Enviar a',
              emoticonsTitle: 'Emoticonos',
              helpURL: 'https://atomjump.com/wp/user-guide/',
              helpTitle: 'Ayuda'
        }
    }
}
var lang = lsmsg.defaultLanguage;

function myTrim(x)
{
	return x.replace(/^\s+|\s+$/gm,'');
}

function getCookie(cname)
{
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++)
	{
		var c = myTrim(ca[i]);// ie8 didn't support .trim();
		if (c.indexOf(name)==0) return c.substring(name.length,c.length);
	}
	return "";
}

function cookieOffset()
{
  //Should output: Thu,31-Dec-2020 00:00:00 GMT
  var cdate = new Date;
  var expirydate=new Date();
  expirydate.setTime(expirydate.getTime()+(365*3*60*60*24*1000))
  var write = expirydate.toGMTString();

  return write;
}

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1;
}

var commentLayer="comments";
var ssshoutFreq = 5000;
var ssshoutHasFocusOuter = true;
var myLoopTimeout;
var whisperOften = "1.1.1.1:2"; //defaults to admin user's ip and id
var cs = 2438974;
var ssshoutServer = "https://atomjump.com/api";  //https://atomjump.com/api  normally
var sameDomain = "atomjump.com";		//string in url to signify this is the same domain (for Safari cross-domain check)
var emailPlugin = "/plugins/shortmail/index.php";
var myUrl = window.location.href;
var emailCheck;
var cssFeedback = "";
var cssStrap = "";

function initAtomJumpFeedback(params)
{
	commentLayer = params.uniqueFeedbackId;
	whisperOften = params.myMachineUser;
	if(params.server){
	  ssshoutServer = params.server;
 }
 if(params.cssFeedback) {
   cssFeedback = params.cssFeedback;
 }
 if(params.cssBootstrap) {
   cssStrap = params.cssBootstrap;
 }

}

function updateEmail()
{
	//Check if any custom user/passwords which have been entered in this session
	var custom = "";
	if((typeof customUser !== 'undefined') && (typeof customPass !== 'undefined')) {
		custom = "&u=" + encodeURIComponent(customUser) + "&p=" + encodeURIComponent(customPass) + "&w=" + encodeURIComponent(customWhisper) + "&fe=" + encodeURIComponent(customFeed) + "&fr=" + customFreq + "&mail_id=" + customMailId;
	}

	//Run a refresh on the server side
	 jQuery.ajax({
		url: ssshoutServer + emailPlugin + "?callback=?",
		data: "refresh=" + commentLayer + custom,
		crossDomain: true,
		dataType: "jsonp"
	}).done(function(response) {
		//Refreshed
	});

}

var currentWindow = {
	"_this": null,
	"forumId": null,
	"emailRefreshFlag": null

}

function openPopup(_this, forumId, emailRefreshFlag)
{
		//Save status for a screen resize
		currentWindow._this = _this;
		currentWindow.forumId = forumId;
		currentWindow.emailRefreshFlag = emailRefreshFlag;

		//Bring up a popup window (if Safari desktop only)
		//to ensure that we have the security permissions to set the session
		//from within the iframe. But only do this the first time (and
		//save this knowledge in a local cookie)
		//From then onwards, we just open all the way
		var isMacLike = navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) ? true:false;
		var is_safari = navigator.userAgent.indexOf("Safari") > -1;
		if(myUrl.indexOf(sameDomain) == -1) {
			if((is_safari) && (isMacLike == true)) {
				var firstView = getCookie("safari-first-view");
				if(!firstView) {
						var myWindow = window.open(ssshoutServer + "/init-sessions.php", "", "width=1,height=1");
						document.cookie = 'safari-first-view=false; path=/; expires=' + cookieOffset() + ';';
				}
			}
		}

		if(forumId) {
			//This is 1st option - we had it passed into the function
			commentLayer = forumId;

		} else {
			if(jQuery(_this).data('useid')) {
				//Use the ID option
				if(jQuery(_this).attr('id')) {
					//2nd option base the forum name on an id
					commentLayer = jQuery(_this).attr('id');
				}
			}

		}

		if(jQuery(_this).data('notifyurl')) {
			myUrl = jQuery(_this).data('notifyurl');		//Allow for user-created
															//URLs for the current page. Used by e.g. sites behind password protection, so that notification 'open forum' links can be sent to a lead-up page which allows a login.
		}

		if(jQuery(_this).data('uniquefeedbackid')) {
			//If we have a unique feedback id for this link in the data properties, rest the globals.
			commentLayer = jQuery(_this).data('uniquefeedbackid');
			whisperOften = jQuery(_this).data('mymachineuser');

			if(jQuery(_this).data('shortmail')) {
				updateEmail();

				emailCheck = setInterval("updateEmail();", 60000);

			}

		}

		if(emailRefreshFlag) {
			if(emailRefreshFlag == true) {
				//If we are mail refreshing
				updateEmail();
				emailCheck = setInterval("updateEmail();", 60000);
			}

		}

		//Dynamically readjust window to current screen height
		var screenWidth = jQuery(window).width();
		var screenHeight = jQuery(window).height();
		jQuery('#comment-popup-container').width(Math.floor(screenWidth) + "px");
		jQuery('#comment-popup-container').height(Math.floor(screenHeight) + "px");

		jQuery("#comment-in-here").html('');

		jQuery('#comment-popup-container').fadeIn(400,function(){

			var wid = (jQuery("#comment-in-here").width() - 5);		//5 is to ensure scroll bar always accounted for
			var hei = (jQuery("#comment-popup-text-container").height() - 10);

			jQuery("#comment-in-here").html('<iframe id="comment-iframe" src="' + ssshoutServer + '/search-secure.php?width=' + wid + '&height=' + hei + '&uniqueFeedbackId=' + commentLayer + '&myMachineUser=' + whisperOften + '&cssFeedback=' + encodeURIComponent(cssFeedback) + '&cssBootstrap=' + encodeURIComponent(cssStrap) + '&server=' + encodeURIComponent(ssshoutServer) + '&clientremoteurl=' + encodeURIComponent(myUrl) + '" frameBorder="0" scrolling="no" width="' + wid + '" height="' + hei + '" onload="jQuery(\'#comment-loading\').hide();" allowfullscreen>');

		});

}

function writeCommentHolder(screenWidth, screenHeight, ssshoutServer, settings, uploadStr, emoticonsStr, privateMessage, helpStr) {

	jQuery("#comment-holder").html('
\

\

\
			 	  \

\
			 		 	\

\

\

\

\

\

\

\

\

\

\

\

\
				 			  ' + settings + '' + uploadStr + emoticonsStr + '      ' + privateMessage + '' + helpStr + '\

\

\

\

');
}

//Run automatically
if(typeof ajFeedback !== 'undefined') {
	initAtomJumpFeedback(ajFeedback);
}

jQuery(document).ready(function() {
			var screenWidth = jQuery(window).width();
			var screenHeight = jQuery(window).height();
			var setLang = getCookie("lang");
			if(setLang) {
			    lang = setLang;
			}

			//If IE10 or above, or any other browser
			if(window.atob) {
				var uploadStr = '  ';
			} else {
				var uploadStr = '  ';
			}

			var emoticonsStr = '  ';

			if(!lsmsg.msgs[lang].helpURL) {
				var helpURL = "https://atomjump.com/wp/user-guide/";
			} else {
				var helpURL = lsmsg.msgs[lang].helpURL;
			}

			if(!lsmsg.msgs[lang].helpTitle) {
				var helpTitle = "Help";
			} else {
				var helpTitle = lsmsg.msgs[lang].helpTitle;
			}
			var helpStr = '  ';

			jQuery(window).resize(function() {
				//On a Window resize, rewrite the comment-holder
				screenWidth = jQuery(window).width();
				screenHeight = jQuery(window).height();
				writeCommentHolder(screenWidth, screenHeight, ssshoutServer, lsmsg.msgs[lang].settings, uploadStr, emoticonsStr, lsmsg.msgs[lang].privateMessage, helpStr);

				openPopup(currentWindow._this, currentWindow.forumId, currentWindow.emailRefreshFlag);

			});

			//Write the holder
			writeCommentHolder(screenWidth, screenHeight, ssshoutServer, lsmsg.msgs[lang].settings, uploadStr, emoticonsStr, lsmsg.msgs[lang].privateMessage, helpStr);

				jQuery('a[href^="#comment-open-"]').click(function() {
					//First base the forum name on an href eg. #comment-open-forumname
					openPopup(this, this.href.split('#comment-open-')[1]);
				});

				jQuery('a[href^="#shortmail-open-"]').click(function() {
					//First base the forum name on an href eg. #shortmail-open-forumname
					openPopup(this, this.href.split('#shortmail-open-')[1], true);
				});

				jQuery('.comment-open').click(function() {
					//A more traditional class link click
					openPopup(this, null);

				});

				jQuery('#comment-close-popup').click(function() {
					//blank out the iframe, kicking in the onbeforeupdate event
					var iframe = document.getElementById('comment-iframe');
					iframe.parentNode.removeChild(iframe);

					if(emailCheck) {			//if we have a timer on the email
						clearTimeout(emailCheck);

					}

					jQuery("#comment-popup-container").fadeOut(400, function() {

						//Tell iframe to stop searching
						var ifr = document.getElementById('comment-iframe');
						if(ifr) {
							var receiver =  ifr.contentWindow;
							if(receiver) {
								receiver.postMessage('stop', ssshoutServer);
							}
						}

						jQuery("#comment-in-here").html('');

						jQuery("#comment-popup-container").hide();
						jQuery('#comment-holder').focus();
						jQuery('#comment-loading').show();
					});
					ssshoutHasFocusOuter = false;	//stop seekin new search terms;
					window.focus();

				});

				jQuery('#comment-options-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('toggle', ssshoutServer);

				});

				jQuery('#comment-upload-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('upload', ssshoutServer);

				});

				jQuery('#comment-emoji-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('emojis', ssshoutServer);

				});

				jQuery('#chat-input-block').append('<input' + ' type="hidden" ' + 'name="cs" ' + ' value="'+ cs + '">');

		});

function whisper(whisper_to, targetName)
{
	whisperOften = whisper_to;		//set global
	jQuery('#private-button').html(lsmsg.msgs[lang].sendTo + " " + targetName);

}

cs += 9585328;

cs += 124856;

cs += 9484320;

<commit_msg>make dynamically refreshing<commit_after>//Language & messages configuration
//Note: also see /config/messages.json for further messages configuration
var lsmsg = {
    "defaultLanguage" : "en",
    "msgs": {
        "en":{
              privateMessage: 'Private',
              settings: 'Settings',
              uploadImagesTitle: 'Upload images.',
              uploadImagesTitleSorry: 'Sorry image uploads are only supported on IE10+, or any other browser.',
              sendTo: 'Send to',
              emoticonsTitle: 'Emoticons',
              helpURL: 'https://atomjump.com/wp/user-guide/',
              helpTitle: 'Help'
        },
        "es":{
              privateMessage: 'Privado',
              settings: 'Ajustes',
              uploadImagesTitle: 'Sube imágenes.',
              uploadImagesTitleSorry: 'La subida de imágenes Lo siento, sólo se admiten en IE10+, o cualquier otro navegador.',
              sendTo: 'Enviar a',
              emoticonsTitle: 'Emoticonos',
              helpURL: 'https://atomjump.com/wp/user-guide/',
              helpTitle: 'Ayuda'
        }
    }
}
var lang = lsmsg.defaultLanguage;

function myTrim(x)
{
	return x.replace(/^\s+|\s+$/gm,'');
}

function getCookie(cname)
{
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++)
	{
		var c = myTrim(ca[i]);// ie8 didn't support .trim();
		if (c.indexOf(name)==0) return c.substring(name.length,c.length);
	}
	return "";
}

function cookieOffset()
{
  //Should output: Thu,31-Dec-2020 00:00:00 GMT
  var cdate = new Date;
  var expirydate=new Date();
  expirydate.setTime(expirydate.getTime()+(365*3*60*60*24*1000))
  var write = expirydate.toGMTString();

  return write;
}

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1;
}

var commentLayer="comments";
var ssshoutFreq = 5000;
var ssshoutHasFocusOuter = true;
var myLoopTimeout;
var whisperOften = "1.1.1.1:2"; //defaults to admin user's ip and id
var cs = 2438974;
var ssshoutServer = "https://atomjump.com/api";  //https://atomjump.com/api  normally
var sameDomain = "atomjump.com";		//string in url to signify this is the same domain (for Safari cross-domain check)
var emailPlugin = "/plugins/shortmail/index.php";
var myUrl = window.location.href;
var emailCheck;
var cssFeedback = "";
var cssStrap = "";

function initAtomJumpFeedback(params)
{
	commentLayer = params.uniqueFeedbackId;
	whisperOften = params.myMachineUser;
	if(params.server){
	  ssshoutServer = params.server;
 }
 if(params.cssFeedback) {
   cssFeedback = params.cssFeedback;
 }
 if(params.cssBootstrap) {
   cssStrap = params.cssBootstrap;
 }

}

function updateEmail()
{
	//Check if any custom user/passwords which have been entered in this session
	var custom = "";
	if((typeof customUser !== 'undefined') && (typeof customPass !== 'undefined')) {
		custom = "&u=" + encodeURIComponent(customUser) + "&p=" + encodeURIComponent(customPass) + "&w=" + encodeURIComponent(customWhisper) + "&fe=" + encodeURIComponent(customFeed) + "&fr=" + customFreq + "&mail_id=" + customMailId;
	}

	//Run a refresh on the server side
	 jQuery.ajax({
		url: ssshoutServer + emailPlugin + "?callback=?",
		data: "refresh=" + commentLayer + custom,
		crossDomain: true,
		dataType: "jsonp"
	}).done(function(response) {
		//Refreshed
	});

}

var currentWindow = {
	"_this": null,
	"forumId": null,
	"emailRefreshFlag": null

}

function openPopup(_this, forumId, emailRefreshFlag)
{
		//Save status for a screen resize
		currentWindow._this = _this;
		currentWindow.forumId = forumId;
		currentWindow.emailRefreshFlag = emailRefreshFlag;

		//Bring up a popup window (if Safari desktop only)
		//to ensure that we have the security permissions to set the session
		//from within the iframe. But only do this the first time (and
		//save this knowledge in a local cookie)
		//From then onwards, we just open all the way
		var isMacLike = navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) ? true:false;
		var is_safari = navigator.userAgent.indexOf("Safari") > -1;
		if(myUrl.indexOf(sameDomain) == -1) {
			if((is_safari) && (isMacLike == true)) {
				var firstView = getCookie("safari-first-view");
				if(!firstView) {
						var myWindow = window.open(ssshoutServer + "/init-sessions.php", "", "width=1,height=1");
						document.cookie = 'safari-first-view=false; path=/; expires=' + cookieOffset() + ';';
				}
			}
		}

		if(forumId) {
			//This is 1st option - we had it passed into the function
			commentLayer = forumId;

		} else {
			if(jQuery(_this).data('useid')) {
				//Use the ID option
				if(jQuery(_this).attr('id')) {
					//2nd option base the forum name on an id
					commentLayer = jQuery(_this).attr('id');
				}
			}

		}

		if(jQuery(_this).data('notifyurl')) {
			myUrl = jQuery(_this).data('notifyurl');		//Allow for user-created
															//URLs for the current page. Used by e.g. sites behind password protection, so that notification 'open forum' links can be sent to a lead-up page which allows a login.
		}

		if(jQuery(_this).data('uniquefeedbackid')) {
			//If we have a unique feedback id for this link in the data properties, rest the globals.
			commentLayer = jQuery(_this).data('uniquefeedbackid');
			whisperOften = jQuery(_this).data('mymachineuser');

			if(jQuery(_this).data('shortmail')) {
				updateEmail();

				emailCheck = setInterval("updateEmail();", 60000);

			}

		}

		if(emailRefreshFlag) {
			if(emailRefreshFlag == true) {
				//If we are mail refreshing
				updateEmail();
				emailCheck = setInterval("updateEmail();", 60000);
			}

		}

		//Dynamically readjust window to current screen height
		var screenWidth = jQuery(window).width();
		var screenHeight = jQuery(window).height();
		jQuery('#comment-popup-container').width(Math.floor(screenWidth) + "px");
		jQuery('#comment-popup-container').height(Math.floor(screenHeight) + "px");

		jQuery("#comment-in-here").html('');

		jQuery('#comment-popup-container').fadeIn(400,function(){

			var wid = (jQuery("#comment-in-here").width() - 5);		//5 is to ensure scroll bar always accounted for
			var hei = (jQuery("#comment-popup-text-container").height() - 10);

			jQuery("#comment-in-here").html('<iframe id="comment-iframe" src="' + ssshoutServer + '/search-secure.php?width=' + wid + '&height=' + hei + '&uniqueFeedbackId=' + commentLayer + '&myMachineUser=' + whisperOften + '&cssFeedback=' + encodeURIComponent(cssFeedback) + '&cssBootstrap=' + encodeURIComponent(cssStrap) + '&server=' + encodeURIComponent(ssshoutServer) + '&clientremoteurl=' + encodeURIComponent(myUrl) + '" frameBorder="0" scrolling="no" width="' + wid + '" height="' + hei + '" onload="jQuery(\'#comment-loading\').hide();" allowfullscreen>');

		});

}

function writeCommentHolder(screenWidth, screenHeight, ssshoutServer, settings, uploadStr, emoticonsStr, privateMessage, helpStr) {

	jQuery("#comment-holder").html('
\

\

\
			 	  \

\
			 		 	\

\

\

\

\

\

\

\

\

\

\

\

\
				 			  ' + settings + '' + uploadStr + emoticonsStr + '      ' + privateMessage + '' + helpStr + '\

\

\

\

');

				jQuery('a[href^="#comment-open-"]').click(function() {
					//First base the forum name on an href eg. #comment-open-forumname
					openPopup(this, this.href.split('#comment-open-')[1]);
				});

				jQuery('a[href^="#shortmail-open-"]').click(function() {
					//First base the forum name on an href eg. #shortmail-open-forumname
					openPopup(this, this.href.split('#shortmail-open-')[1], true);
				});

				jQuery('.comment-open').click(function() {
					//A more traditional class link click
					openPopup(this, null);

				});

				jQuery('#comment-close-popup').click(function() {
					//blank out the iframe, kicking in the onbeforeupdate event
					var iframe = document.getElementById('comment-iframe');
					iframe.parentNode.removeChild(iframe);

					if(emailCheck) {			//if we have a timer on the email
						clearTimeout(emailCheck);

					}

					jQuery("#comment-popup-container").fadeOut(400, function() {

						//Tell iframe to stop searching
						var ifr = document.getElementById('comment-iframe');
						if(ifr) {
							var receiver =  ifr.contentWindow;
							if(receiver) {
								receiver.postMessage('stop', ssshoutServer);
							}
						}

						jQuery("#comment-in-here").html('');

						jQuery("#comment-popup-container").hide();
						jQuery('#comment-holder').focus();
						jQuery('#comment-loading').show();
					});
					ssshoutHasFocusOuter = false;	//stop seekin new search terms;
					window.focus();

				});

				jQuery('#comment-options-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('toggle', ssshoutServer);

				});

				jQuery('#comment-upload-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('upload', ssshoutServer);

				});

				jQuery('#comment-emoji-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('emojis', ssshoutServer);

				});

				jQuery('#chat-input-block').append('<input' + ' type="hidden" ' + 'name="cs" ' + ' value="'+ cs + '">');

}

//Run automatically
if(typeof ajFeedback !== 'undefined') {
	initAtomJumpFeedback(ajFeedback);
}

jQuery(document).ready(function() {
			var screenWidth = jQuery(window).width();
			var screenHeight = jQuery(window).height();
			var setLang = getCookie("lang");
			if(setLang) {
			    lang = setLang;
			}

			//If IE10 or above, or any other browser
			if(window.atob) {
				var uploadStr = '  ';
			} else {
				var uploadStr = '  ';
			}

			var emoticonsStr = '  ';

			if(!lsmsg.msgs[lang].helpURL) {
				var helpURL = "https://atomjump.com/wp/user-guide/";
			} else {
				var helpURL = lsmsg.msgs[lang].helpURL;
			}

			if(!lsmsg.msgs[lang].helpTitle) {
				var helpTitle = "Help";
			} else {
				var helpTitle = lsmsg.msgs[lang].helpTitle;
			}
			var helpStr = '  ';

			jQuery(window).resize(function() {
				//On a Window resize, rewrite the comment-holder
				screenWidth = jQuery(window).width();
				screenHeight = jQuery(window).height();
				writeCommentHolder(screenWidth, screenHeight, ssshoutServer, lsmsg.msgs[lang].settings, uploadStr, emoticonsStr, lsmsg.msgs[lang].privateMessage, helpStr);

				openPopup(currentWindow._this, currentWindow.forumId, currentWindow.emailRefreshFlag);

			});

			//Write the holder
			writeCommentHolder(screenWidth, screenHeight, ssshoutServer, lsmsg.msgs[lang].settings, uploadStr, emoticonsStr, lsmsg.msgs[lang].privateMessage, helpStr);

		});

function whisper(whisper_to, targetName)
{
	whisperOften = whisper_to;		//set global
	jQuery('#private-button').html(lsmsg.msgs[lang].sendTo + " " + targetName);

}

cs += 9585328;

cs += 124856;

cs += 9484320;

<|endoftext|>


<commit_before>const hash = require('object-hash');

function cache(func) {
  return (root, args, context) => {
    if (!context.resolverCache) {
      throw new Error('Missing resolverCache property on the Graphql context.');
    }

    const key = `${hash(root)}:${hash(args)}`;
    return (
      context.resolverCache
        .get(key)
        .then(result => (result ? result : func(root, args, context)))
        // Error
        .catch(() => func(root, args, context))
    );
  };
}

module.exports = cache;
<commit_msg>feature/cache: Add cache set feature<commit_after>const hash = require('object-hash');

function cache(func, options) {
  return (root, args, context) => {
    if (!context.resolverCache) {
      throw new Error('Missing resolverCache property on the Graphql context.');
    }

    const key = `${hash(root)}:${hash(args)}`;
    const executeAndCache = () =>
      Promise.resolve(func(root, args, context)).then(value =>
        context.resolverCache.set(key, value, options)
      );

    return (
      context.resolverCache
        .get(key)
        .then(value => (value ? value : executeAndCache()))
        // Error
        .catch(() => executeAndCache())
    );
  };
}

module.exports = cache;
<|endoftext|>


<commit_before>'use strict';

var _cache = [];

function EventHandler(token, eventName, handler, enabled) {
  this.elementToken = token;
  this.eventName = 'click.namespacename';
  this.eventType = 'click';
  this.namespace = 'namespace';
  this.handler = handler;
  this.enabled = enabled;
}

module.exports = {
  add : function(token, eventName, handler) {
    _cache.push(new EventHandler(token, eventName, handler, true));
  },
  removeHandler : function(token, eventName, handler) {
    var index = _cache.findIndex(function(entry) {
      return entry.elementToken === token && entry.eventName === eventName && entry.handler === handler;
    });
    _cache.splice(index, 1);
  },
  getHandlers : function(token, eventName) {
    return _cache.reduce(function(acc, entry) {
      if (entry.elementToken === token && entry.eventName === eventName) {
        acc.push(entry.handler);
      }
    }, []);
  }
};
<commit_msg>splitting out eventType and namespcae from the eventName in the cache object<commit_after>'use strict';

var _cache = [];

function EventHandler(token, eventName, handler, enabled) {
  var eventNameSplit = eventName.split('.');
  this.elementToken = token;
  this.eventName = eventName;
  this.handler = handler;
  this.enabled = enabled;
  this.eventType = eventNameSplit[0];
  this.namespace = eventNameSplit[1];
}

module.exports = {
  add : function(token, eventName, handler) {
    _cache.push(new EventHandler(token, eventName, handler, true));
  },
  removeHandler : function(token, eventName, handler) {
    var index = _cache.findIndex(function(entry) {
      return entry.elementToken === token && entry.eventName === eventName && entry.handler === handler;
    });
    _cache.splice(index, 1);
  },
  getHandlers : function(token, eventName) {
    return _cache.reduce(function(acc, entry) {
      if (entry.elementToken === token && entry.eventName === eventName) {
        acc.push(entry.handler);
      }
    }, []);
  }
};
<|endoftext|>


<commit_before>function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function backToTop() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

function passwordsMatch() {
  console.log("passwordsMatch()");

  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");
    $('#passwordError').addClass("hidden");

    return true;
  }

  $('#passGroup').addClass("has-error");
  $('#passwordError').removeClass("hidden");

  backToTop();

  return false;
}

function onMessageChange() {
    console.log("onMessageChange()");
    var m = $('#message');

    $("#count").text( m.val().length  );

    m.autosize({ append: '\n'});
    m.trigger('autosize.resize');
}

function messageUpdated() {
  $('#message').select();
  onMessageChange();
}

function clearMessage() {
  bootbox.confirm("Clear message?", function(result) {
    if(result == true) {
      $('#message').val('');
      onMessageChange();
    }
  });
}

function pageEncrypt() {
  console.log("pageEncrypt()");
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

function pageDecrypt() {
  console.log("pageDecrypt()");
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

$( function() {

  $("#message").change( onMessageChange );
  $("#message").keyup( onMessageChange );

  $('#encrypt').click( pageEncrypt );
  $('#decrypt').click( pageDecrypt );

  $('#backToTop').click( backToTop );
  $('#clearMessage').click( clearMessage );

  onMessageChange();

  $('#splashscreen').delay( 1000 ).fadeOut('slow');

  console.log('Core loaded');
});
<commit_msg>Update core.js<commit_after>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function backToTop() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

function passwordsMatch() {
  console.log("passwordsMatch()");

  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");
    $('#passwordError').addClass("hidden");

    return true;
  }

  $('#passGroup').addClass("has-error");
  $('#passwordError').removeClass("hidden");

  backToTop();

  return false;
}

function onMessageChange() {
    console.log("onMessageChange()");
    var m = $('#message');

    $("#count").text( m.val().length  );

    m.autosize({ append: '\n'});
    m.trigger('autosize.resize');
}

function messageUpdated() {
  $('#message').select();
  onMessageChange();
}

function clearMessage() {
  bootbox.confirm("Clear message?", function(result) {
    if(result == true) {
      $('#message').val('');
      onMessageChange();
    }
  });
}

function pageEncrypt() {
  console.log("pageEncrypt()");
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

function pageDecrypt() {
  console.log("pageDecrypt()");
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

$( function() {

  $("#message").change( onMessageChange );
  $("#message").keyup( onMessageChange );

  $('#encrypt').click( pageEncrypt );
  $('#decrypt').click( pageDecrypt );

  $('#backToTop').click( backToTop );
  $('#clearMessage').click( clearMessage );

  onMessageChange();

  $('#splashscreen').delay( 1000 ).fadeOut('slow');

  console.log('Core loaded');
});
<|endoftext|>


<commit_before>/** tipiX - TIme PIcture eXplorer
 *
 * Copyright (c) 2013 TIPIX <adalca@mit.edu>
 *
 * tipiX is licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * See LICENSE file for more information
 *
 * Author: Adrian V. Dalca, http://www.mit.edu/~adalca/
 */

/** Launch display of a set given a set choice
 *
 * @param choice - String - a set choice (see cases for options).
 * @returns {Array} - 1d or 2d pictureBox objects
 */
function launchDisplay(choice, evt) {
	switch (choice) {
		case "boston4day":
			loadObj = loadBoston4Day();
			break;
		case "lupus":
			loadObj = lupus();
			break;
		case "emerald":
			loadObj = loadEmerald();
			break;
		case "bostonStorm":
			loadObj = loadBostonStorm();
			break;
		case "vermontDrive":
			loadObj = loadVermontDrive();
			break;
		case "lakePlacidDrive":
			loadObj = loadLakePlacidDrive();
			break;
		case "userSet":
			loadObj = loadUserSet();
			break;
		case "userSetLocal":
			loadObj = loadUserSetLocal(evt);
			break;
		default:
			alert('Not a valid case');
			break;
	}

	// get the images according to the sources.
	pictureBoxes = loadImages(loadObj);

	// canvas should be turned on
	canvasOn = true;

	var canvas = document.getElementById(DRAW_CANVAS_NAME); // main canvas
	canvas.getContext('2d').clearRect(0,0,canvas.width,canvas.height);
	drawLogo();

	// close nav
	nav(currentTab);

	// TODO: initiate loading canvas
	xSize = document.getElementById("loadingCanvas").width;
	binsPerPixel = loadObj.xBins / xSize;

	if (loadObj.yBins == undefined)
		yBins = 1;
	else
		yBins = loadObj.yBins;

	ySize = Math.ceil(yBins / binsPerPixel);
	ySize = Math.max(ySize, 10);
	ySize = Math.min(ySize, 300); //TODO hardcoded?
	document.getElementById("loadingCanvas").height = ySize;
	document.getElementById("loadMatrix").height = ySize;
	//TODO get also the loading parent to be that big!

	// force a reshape of window on first picture draw.
	fixedAspectRatio = 0;

	// return the images
	return pictureBoxes;
}

function loadBoston4Day() {
	loadObj.type = "web";
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 24;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/boston4day/average_img_%d_%d.jpg';
	return loadObj;
}

function lupus() {
	loadObj.type = "web";
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 56;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/lupus/lupus_%d_%d.jpg';
	return loadObj;
}

function loadBoston5Day() {
	loadObj.type = "web";
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 24;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/boston5day/l_average_img_%d_%d.jpg';
	return loadObj;
}

function loadBostonStorm() {
	loadObj.type = "web";
	loadObj.nDims = 1;
	loadObj.xBins = 30;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/bostonStorm/l_average_img_%d.jpg';
	return loadObj;
}

function loadVermontDrive() {
	loadObj.type = "web";
	loadObj.nDims = 1;
	loadObj.xBins = 60;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/vermontDrive/l_average_img_%d.jpg';
	return loadObj;
}

function loadLakePlacidDrive() {
	loadObj.type = "web";
	loadObj.nDims = 1;
	loadObj.xBins = 26;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/lakePlacidDrive/l_average_img_%d.jpg';
	return loadObj;
}

function loadEmerald() {
	loadObj.type = "web";
	loadObj.nDims = 1;
	loadObj.xBins = 337;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/emerald/img (%d).jpg';
	return loadObj;
}

function loadUserSet() {
	var oForm = document.getElementById('userSet');

	var radios = document.getElementsByName('nDims');
	for (var i = 0, length = radios.length; i < length; i++) {
		if (radios[i].checked) {
			loadObj.nDims = radios[i].value;
		}
	}

	loadObj.xBins = parseInt(oForm.elements['xBins'].value);
	if (loadObj.nDims == 2) {
		loadObj.yBins = parseInt(oForm.elements['yBins'].value);
	}
	loadObj.fileName = oForm.elements['filename'].value;
	loadObj.type = "web";
	return loadObj;
}

/******************************************************************************
 * Execution
 *****************************************************************************/

// original settings and global variables
var DRAW_CANVAS_NAME = 'mainDisplay';
var MAX_CANVAS_WIDTH = 1200;
var MAX_CANVAS_HEIGHT = 900;
var MAX_EMPTY_CANVAS_WIDTH = 600;
var MAX_EMPTY_CANVAS_HEIGHT = 450;
var MIN_CANVAS_WIDTH = 400;
var MIN_CANVAS_HEIGHT = 300;
var canvasOn = false;
var currentX = 0;
var currentY = 0;
var pictureBoxes = [];
var startTime = 0;
var loadObj = new Object();
var curPictureBox = null;
var currentTab = 'about';
var currentLoadTab = 'local';
var currentTabState = false;
var CORE_SET_PATH = 'http://www.mit.edu/~adalca/tipiX';
var logoImage;
var lockx = false;
var locky = false;
var global_x = -1;
var fixedAspectRatio = 0;

// key presses
$(document).keyup(function(e) {
  if (e.keyCode == 88) {
  	lockx = !lockx;
	document.getElementById('lockx').innerHTML = lockx;
	}   // x
  if (e.keyCode == 89) {
  	locky = !locky;
	document.getElementById('locky').innerHTML = locky;
	}   // x
  if (e.keyCode == 27) {
  	lockx = false;
  	locky = false;
	document.getElementById('lockx').innerHTML = lockx;
	document.getElementById('locky').innerHTML = locky;
	}   // esc
	if (e.keyCode == 67) { //c
		nav('about');
	}
	if (e.keyCode == 73) { //i
		onOff('info-clip');
		updownContainer('info-container');
	}
});

// files listener. TODO: why is this like this, can't it be a click event?
document.getElementById('files').addEventListener('change', handleFileSelect, false);

// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelectDrop, false);

var dropZoneMain = document.getElementById('drop_zone_main');
dropZoneMain.addEventListener('dragover', handleDragOver, false);
dropZoneMain.addEventListener('drop', handleFileSelectDrop, false);

// canvas and listener
var canvas = document.getElementById(DRAW_CANVAS_NAME); // main canvas

canvas.onclick = function () { console.log((global_x+1).toString()); };
canvas.addEventListener('mousemove', function(evt) {
	if (canvasOn) {
		var mousePos = getMousePos(canvas, evt);
		drawImageAtPosition(mousePos);
	}
}, false);
<commit_msg>fixed loading bug with loadingMatrix<commit_after>/** tipiX - TIme PIcture eXplorer
 *
 * Copyright (c) 2013 TIPIX <adalca@mit.edu>
 *
 * tipiX is licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * See LICENSE file for more information
 *
 * Author: Adrian V. Dalca, http://www.mit.edu/~adalca/
 */

/** Launch display of a set given a set choice
 *
 * @param choice - String - a set choice (see cases for options).
 * @returns {Array} - 1d or 2d pictureBox objects
 */
function launchDisplay(choice, evt) {
	switch (choice) {
		case "boston4day":
			loadObj = loadBoston4Day();
			break;
		case "lupus":
			loadObj = lupus();
			break;
		case "emerald":
			loadObj = loadEmerald();
			break;
		case "bostonStorm":
			loadObj = loadBostonStorm();
			break;
		case "vermontDrive":
			loadObj = loadVermontDrive();
			break;
		case "lakePlacidDrive":
			loadObj = loadLakePlacidDrive();
			break;
		case "userSet":
			loadObj = loadUserSet();
			break;
		case "userSetLocal":
			loadObj = loadUserSetLocal(evt);
			break;
		default:
			alert('Not a valid case');
			break;
	}

	// get the images according to the sources.
	pictureBoxes = loadImages(loadObj);

	// canvas should be turned on
	canvasOn = true;

	var canvas = document.getElementById(DRAW_CANVAS_NAME); // main canvas
	canvas.getContext('2d').clearRect(0,0,canvas.width,canvas.height);
	drawLogo();

	// close nav
	nav(currentTab);

	// TODO: initiate loading canvas
	/*xSize = document.getElementById("loadingCanvas").width;
	binsPerPixel = loadObj.xBins / xSize;

	if (loadObj.yBins == undefined)
		yBins = 1;
	else
		yBins = loadObj.yBins;

	ySize = Math.ceil(yBins / binsPerPixel);
	ySize = Math.max(ySize, 10);
	ySize = Math.min(ySize, 300); //TODO hardcoded?
	document.getElementById("loadingCanvas").height = ySize;
	document.getElementById("loadMatrix").height = ySize;*/
	//TODO get also the loading parent to be that big!

	// force a reshape of window on first picture draw.
	fixedAspectRatio = 0;

	// return the images
	return pictureBoxes;
}

function loadBoston4Day() {
	loadObj.type = "web";
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 24;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/boston4day/average_img_%d_%d.jpg';
	return loadObj;
}

function lupus() {
	loadObj.type = "web";
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 56;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/lupus/lupus_%d_%d.jpg';
	return loadObj;
}

function loadBoston5Day() {
	loadObj.type = "web";
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 24;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/boston5day/l_average_img_%d_%d.jpg';
	return loadObj;
}

function loadBostonStorm() {
	loadObj.type = "web";
	loadObj.nDims = 1;
	loadObj.xBins = 30;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/bostonStorm/l_average_img_%d.jpg';
	return loadObj;
}

function loadVermontDrive() {
	loadObj.type = "web";
	loadObj.nDims = 1;
	loadObj.xBins = 60;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/vermontDrive/l_average_img_%d.jpg';
	return loadObj;
}

function loadLakePlacidDrive() {
	loadObj.type = "web";
	loadObj.nDims = 1;
	loadObj.xBins = 26;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/lakePlacidDrive/l_average_img_%d.jpg';
	return loadObj;
}

function loadEmerald() {
	loadObj.type = "web";
	loadObj.nDims = 1;
	loadObj.xBins = 337;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/emerald/img (%d).jpg';
	return loadObj;
}

function loadUserSet() {
	var oForm = document.getElementById('userSet');

	var radios = document.getElementsByName('nDims');
	for (var i = 0, length = radios.length; i < length; i++) {
		if (radios[i].checked) {
			loadObj.nDims = radios[i].value;
		}
	}

	loadObj.xBins = parseInt(oForm.elements['xBins'].value);
	if (loadObj.nDims == 2) {
		loadObj.yBins = parseInt(oForm.elements['yBins'].value);
	}
	loadObj.fileName = oForm.elements['filename'].value;
	loadObj.type = "web";
	return loadObj;
}

/******************************************************************************
 * Execution
 *****************************************************************************/

// original settings and global variables
var DRAW_CANVAS_NAME = 'mainDisplay';
var MAX_CANVAS_WIDTH = 1200;
var MAX_CANVAS_HEIGHT = 900;
var MAX_EMPTY_CANVAS_WIDTH = 600;
var MAX_EMPTY_CANVAS_HEIGHT = 450;
var MIN_CANVAS_WIDTH = 400;
var MIN_CANVAS_HEIGHT = 300;
var canvasOn = false;
var currentX = 0;
var currentY = 0;
var pictureBoxes = [];
var startTime = 0;
var loadObj = new Object();
var curPictureBox = null;
var currentTab = 'about';
var currentLoadTab = 'local';
var currentTabState = false;
var CORE_SET_PATH = 'http://www.mit.edu/~adalca/tipiX';
var logoImage;
var lockx = false;
var locky = false;
var global_x = -1;
var fixedAspectRatio = 0;

// key presses
$(document).keyup(function(e) {
  if (e.keyCode == 88) {
  	lockx = !lockx;
	document.getElementById('lockx').innerHTML = lockx;
	}   // x
  if (e.keyCode == 89) {
  	locky = !locky;
	document.getElementById('locky').innerHTML = locky;
	}   // x
  if (e.keyCode == 27) {
  	lockx = false;
  	locky = false;
	document.getElementById('lockx').innerHTML = lockx;
	document.getElementById('locky').innerHTML = locky;
	}   // esc
	if (e.keyCode == 67) { //c
		nav('about');
	}
	if (e.keyCode == 73) { //i
		onOff('info-clip');
		updownContainer('info-container');
	}
});

// files listener. TODO: why is this like this, can't it be a click event?
document.getElementById('files').addEventListener('change', handleFileSelect, false);

// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelectDrop, false);

var dropZoneMain = document.getElementById('drop_zone_main');
dropZoneMain.addEventListener('dragover', handleDragOver, false);
dropZoneMain.addEventListener('drop', handleFileSelectDrop, false);

// canvas and listener
var canvas = document.getElementById(DRAW_CANVAS_NAME); // main canvas

canvas.onclick = function () { console.log((global_x+1).toString()); };
canvas.addEventListener('mousemove', function(evt) {
	if (canvasOn) {
		var mousePos = getMousePos(canvas, evt);
		drawImageAtPosition(mousePos);
	}
}, false);
<|endoftext|>


<commit_before>/*!
 * Arenite JavaScript Library v0.0.2
 * https://github.com/lcavadas/jarenite
 *
 * Copyright 2014, Luís Serralheiro
 */
/* global Arenite:true */
// Arenite is an implementation of the Sandbox and Module patterns. It was designed to,
// unlike most of the existing module libraries, not affect your code making it dependant on the module library itself.
//
// Base of the arenite sandbox object. Creates the base services in the arenite sandbox object.
//
// Using the Namespace and MVP (or MVC) patterns is strongly recommended but not mandatory.
//
// You can create further extensions to the sandbox by providing new services or overriding already imported ones.
//
// There are a few extensions included in this repository and you can read more about them here.
//
// For more information about the mentioned patterns consult the book "Javascript Patterns"
// by Stoyan Stefanov from O'Reilly Media which discusses these patterns in detail.
//
// ## Configuration
// The documentation for the configuration is presented in the website.
Arenite = function (config) {
  //### Arenite.Object
  // Instance of the Sandbox is started with the Arenite.Object module witch gives us access to the extend function used.
  var arenite = new Arenite.Object(arenite);
  //### Arenite.Async
  // Extend the instance with the Arenite.Async extension providing the asynchronous tools (Latch Pattern) used by the Loader extension.
  arenite = arenite.object.extend(arenite, new Arenite.Async());
  //### Arenite.Url
  // Extend the instance with the Arenite.Url extension which provides functions for analysis of query parameters.
  arenite = arenite.object.extend(arenite, new Arenite.Url());
  //### Arenite.DI
  // Extend the instance with the Arenite.DI extension which provides
  // the injector functionality.
  arenite = arenite.object.extend(arenite, new Arenite.DI(arenite));
  //### Arenite.Loader
  // Extend the instance with the Arenite.Loader extension which provides
  // the script and resource loading functionality to the sandbox.
  arenite = arenite.object.extend(arenite, new Arenite.Loader(arenite));
  // Initialize the injector by having it read the configuration object passed into this constructor.
  arenite.di.loadConfig(config);
};<commit_msg>project rename clenup<commit_after>/*!
 * Arenite JavaScript Library v0.0.2
 * https://github.com/lcavadas/arenite
 *
 * Copyright 2014, Luís Serralheiro
 */
/* global Arenite:true */
// Arenite is an implementation of the Sandbox and Module patterns. It was designed to,
// unlike most of the existing module libraries, not affect your code making it dependant on the module library itself.
//
// Base of the arenite sandbox object. Creates the base services in the arenite sandbox object.
//
// Using the Namespace and MVP (or MVC) patterns is strongly recommended but not mandatory.
//
// You can create further extensions to the sandbox by providing new services or overriding already imported ones.
//
// There are a few extensions included in this repository and you can read more about them here.
//
// For more information about the mentioned patterns consult the book "Javascript Patterns"
// by Stoyan Stefanov from O'Reilly Media which discusses these patterns in detail.
//
// ## Configuration
// The documentation for the configuration is presented in the website.
Arenite = function (config) {
  //### Arenite.Object
  // Instance of the Sandbox is started with the Arenite.Object module witch gives us access to the extend function used.
  var arenite = new Arenite.Object(arenite);
  //### Arenite.Async
  // Extend the instance with the Arenite.Async extension providing the asynchronous tools (Latch Pattern) used by the Loader extension.
  arenite = arenite.object.extend(arenite, new Arenite.Async());
  //### Arenite.Url
  // Extend the instance with the Arenite.Url extension which provides functions for analysis of query parameters.
  arenite = arenite.object.extend(arenite, new Arenite.Url());
  //### Arenite.DI
  // Extend the instance with the Arenite.DI extension which provides
  // the injector functionality.
  arenite = arenite.object.extend(arenite, new Arenite.DI(arenite));
  //### Arenite.Loader
  // Extend the instance with the Arenite.Loader extension which provides
  // the script and resource loading functionality to the sandbox.
  arenite = arenite.object.extend(arenite, new Arenite.Loader(arenite));
  // Initialize the injector by having it read the configuration object passed into this constructor.
  arenite.di.loadConfig(config);
};<|endoftext|>


<commit_before>'use strict'

/*
 * adonis-framework
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

const nodeRes = require('node-res')
const nodeReq = require('node-req')
const nodeCookie = require('node-cookie')
const Macroable = require('macroable')

const SECRET = 'app.secret'

/**
 * @module Adonis
 * @submodule framework
 */

/**
 * A facade over Node.js HTTP `res` object, making it
 * easier and simpler to make HTTP response. You can
 * access the original **response** object as
 * `response.response`
 *
 * @namespace Adonis/Src/Response
 *
 * @class Response
 */
class Response extends Macroable {
  constructor (request, response, Config) {
    super()
    /**
     * Refrence to native HTTP request object
     *
     * @attribute request
     * @type {Object}
     */
    this.request = request

    /**
     * Refrence to native HTTP response object
     *
     * @attribute response
     * @type {Object}
     */
    this.response = response

    /**
     * Here we store the body of the response and wait
     * for the entire HTTP life-cycle to finish unless
     * we end the response. This gives a chance to
     * modify the response via middlewares executed
     * after the route handler or controller method.
     *
     * @attribute _lazyBody
     *
     * @type {Object}
     * @private
     */
    this._lazyBody = {
      method: 'send',
      content: null,
      args: []
    }

    /**
     * Flag to know whether a file was sent as the response. In this
     * case the response will be closed immediately once stream is
     * finished
     *
     * @attribute _sentFile
     *
     * @type {Boolean}
     * @private
     */
    this._sentFile = false

    this.Config = Config
  }

  /**
   * lazyBody to be set as the response body.
   *
   * @method lazyBody
   *
   * @return {Object}
   */
  get lazyBody () {
    return this._lazyBody
  }

  /**
   * returns whether request has been
   * finished or not
   *
   * @attribute finished
   *
   * @return {Boolean}
   */
  get finished () {
    return this.response.finished
  }

  /**
   * returns whether request headers
   * have been sent or not
   *
   * @attribute headersSent
   *
   * @return {Boolean}
   */
  get headersSent () {
    return this.response.headersSent
  }

  /**
   * returns whether a request is pending
   * or not
   *
   * @attribute isPending
   *
   * @return {Boolean}
   */
  get isPending () {
    return (!this.headersSent && !this.finished)
  }

  /**
   * Set the response status code.
   *
   * @method status
   *
   * @param  {Number} statusCode
   *
   * @chainable
   */
  status (statusCode) {
    nodeRes.status(this.response, statusCode)
    return this
  }

  /**
   * Set HTTP response header. Resetting same header
   * multiple times will append to the existing
   * value.
   *
   * @method header
   *
   * @param  {String} key
   * @param  {String} value
   *
   * @chainable
   */
  header (key, value) {
    nodeRes.header(this.response, key, value)
    return this
  }

  /**
   * Set HTTP response header only if it does not
   * exists already
   *
   * @method safeHeader
   *
   * @param  {String}   key
   * @param  {String}   value
   *
   * @chainable
   */
  safeHeader (key, value) {
    nodeRes.safeHeader(this.response, key, value)
    return this
  }

  /**
   * Remove the existing HTTP response header.
   *
   * @method removeHeader
   *
   * @param  {String}     key
   *
   * @chainable
   */
  removeHeader (key) {
    nodeRes.removeHeader(this.response, key)
    return this
  }

  /**
   * Returns the value of header for a given key.
   *
   * @method getHeader
   *
   * @param  {String}  key
   *
   * @return {Mixed}
   */
  getHeader (key) {
    return nodeRes.getHeader(this.response, key)
  }

  /**
   * Stream a file to the client as HTTP response.
   *
   * Options are passed directly to [send](https://www.npmjs.com/package/send)
   *
   * @method download
   *
   * @param  {String} filePath
   * @param  {Object} options
   *
   * @return {void}
   */
  download (filePath, options = {}) {
    this._sentFile = true
    nodeRes.download(this.request, this.response, filePath, options)
  }

  /**
   * Force download the file by setting `Content-disposition`
   * header.
   *
   * @method attachment
   *
   * @param  {String}   filePath
   * @param  {String}   [name]
   * @param  {String}   [disposition]
   * @param  {Object}   [options = {}]
   *
   * @return {void}
   */
  attachment (filePath, name, disposition, options = {}) {
    this._sentFile = true
    nodeRes.attachment(this.request, this.response, filePath, name, disposition, options)
  }

  /**
   * Set the `Location` header on HTTP response.
   *
   * @method location
   *
   * @param  {String} url
   *
   * @chainable
   */
  location (url) {
    nodeRes.location(this.response, url)
    return this
  }

  /**
   * Redirect the request by setting the `Location`
   * header and ending the response
   *
   * @method redirect
   *
   * @param  {String} url
   * @param  {Number} [status = 302]
   *
   * @return {void}
   */
  redirect (url, status) {
    nodeRes.redirect(this.request, this.response, url, status)
  }

  /**
   * Add the HTTP `Vary` header
   *
   * @method vary
   *
   * @param  {String} field
   *
   * @chainable
   */
  vary (field) {
    nodeRes.vary(this.response, field)
    return this
  }

  /**
   * Sets the `Content-type` header based on the
   * type passed to this method.
   *
   * @method type
   *
   * @param  {String} type
   * @param  {String} [charset = 'utf-8']
   *
   * @chainable
   */
  type (type, charset = 'utf-8') {
    nodeRes.type(this.response, type, charset)
    return this
  }

  /**
   * Sets the response body for the HTTP request.
   *
   * @method send
   *
   * @param  {Mixed} body
   *
   * @return {void}
   */
  send (body) {
    this._lazyBody = {
      method: 'send',
      content: body,
      args: []
    }
  }

  /**
   * Sets the response body for the HTTP request with
   * explicit `content-type` set to `application/json`.
   *
   * @method json
   *
   * @param  {Object} body
   *
   * @return {void}
   */
  json (body) {
    this._lazyBody = {
      method: 'json',
      content: body,
      args: []
    }
  }

  /**
   * Sets the response body for the HTTP request with
   * explicit `content-type` set to `text/javascript`.
   *
   * @method jsonp
   *
   * @param  {Object} body
   * @param  {String} [callbackFn = 'callback'] - Callback name.
   *
   * @return {void}
   */
  jsonp (body, callbackFn) {
    callbackFn = callbackFn || nodeReq.get(this.request).callback || 'callback'
    this._lazyBody = {
      method: 'jsonp',
      content: body,
      args: [callbackFn]
    }
  }

  /**
   * Ends the response by setting the `_lazyBody` as the
   * response body.
   *
   * @method end
   *
   * @return {void}
   */
  end () {
    if (!this._sentFile) {
      const method = this._lazyBody.method || 'send'
      const args = [this.request, this.response, this._lazyBody.content].concat(this._lazyBody.args)
      nodeRes[method].apply(nodeRes, args)
    }
  }

  /**
   * Send cookie with the http response
   *
   * @method cookie
   *
   * @param  {String} key
   * @param  {Mixed} value
   * @param  {Object} [options = {}]
   *
   * @return {void}
   */
  cookie (key, value, options = {}) {
    nodeCookie.create(this.response, key, value, options, this.Config.get(SECRET), true)
  }

  /**
   * Set plain cookie HTTP response
   *
   * @method plainCookie
   *
   * @param  {String}    key
   * @param  {Mixed}    value
   * @param  {Object}    [options = {}]
   *
   * @return {void}
   */
  plainCookie (key, value, options) {
    nodeCookie.create(this.response, key, value, options)
  }
}

/**
 * Defining _macros and _getters property
 * for Macroable class
 *
 * @type {Object}
 */
Response._macros = {}
Response._getters = {}

/**
 * Setting descriptive methods on the response prototype.
 */
nodeRes.descriptiveMethods.forEach((method) => {
  Response.prototype[method] = function (content) {
    this._lazyBody = { method, content, args: [] }
  }
})

module.exports = Response
<commit_msg>feat(response): add support for clear existing cookie<commit_after>'use strict'

/*
 * adonis-framework
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

const nodeRes = require('node-res')
const nodeReq = require('node-req')
const nodeCookie = require('node-cookie')
const Macroable = require('macroable')

const SECRET = 'app.secret'

/**
 * @module Adonis
 * @submodule framework
 */

/**
 * A facade over Node.js HTTP `res` object, making it
 * easier and simpler to make HTTP response. You can
 * access the original **response** object as
 * `response.response`
 *
 * @namespace Adonis/Src/Response
 *
 * @class Response
 */
class Response extends Macroable {
  constructor (request, response, Config) {
    super()
    /**
     * Refrence to native HTTP request object
     *
     * @attribute request
     * @type {Object}
     */
    this.request = request

    /**
     * Refrence to native HTTP response object
     *
     * @attribute response
     * @type {Object}
     */
    this.response = response

    /**
     * Here we store the body of the response and wait
     * for the entire HTTP life-cycle to finish unless
     * we end the response. This gives a chance to
     * modify the response via middlewares executed
     * after the route handler or controller method.
     *
     * @attribute _lazyBody
     *
     * @type {Object}
     * @private
     */
    this._lazyBody = {
      method: 'send',
      content: null,
      args: []
    }

    /**
     * Flag to know whether a file was sent as the response. In this
     * case the response will be closed immediately once stream is
     * finished
     *
     * @attribute _sentFile
     *
     * @type {Boolean}
     * @private
     */
    this._sentFile = false

    this.Config = Config
  }

  /**
   * lazyBody to be set as the response body.
   *
   * @method lazyBody
   *
   * @return {Object}
   */
  get lazyBody () {
    return this._lazyBody
  }

  /**
   * returns whether request has been
   * finished or not
   *
   * @attribute finished
   *
   * @return {Boolean}
   */
  get finished () {
    return this.response.finished
  }

  /**
   * returns whether request headers
   * have been sent or not
   *
   * @attribute headersSent
   *
   * @return {Boolean}
   */
  get headersSent () {
    return this.response.headersSent
  }

  /**
   * returns whether a request is pending
   * or not
   *
   * @attribute isPending
   *
   * @return {Boolean}
   */
  get isPending () {
    return (!this.headersSent && !this.finished)
  }

  /**
   * Set the response status code.
   *
   * @method status
   *
   * @param  {Number} statusCode
   *
   * @chainable
   */
  status (statusCode) {
    nodeRes.status(this.response, statusCode)
    return this
  }

  /**
   * Set HTTP response header. Resetting same header
   * multiple times will append to the existing
   * value.
   *
   * @method header
   *
   * @param  {String} key
   * @param  {String} value
   *
   * @chainable
   */
  header (key, value) {
    nodeRes.header(this.response, key, value)
    return this
  }

  /**
   * Set HTTP response header only if it does not
   * exists already
   *
   * @method safeHeader
   *
   * @param  {String}   key
   * @param  {String}   value
   *
   * @chainable
   */
  safeHeader (key, value) {
    nodeRes.safeHeader(this.response, key, value)
    return this
  }

  /**
   * Remove the existing HTTP response header.
   *
   * @method removeHeader
   *
   * @param  {String}     key
   *
   * @chainable
   */
  removeHeader (key) {
    nodeRes.removeHeader(this.response, key)
    return this
  }

  /**
   * Returns the value of header for a given key.
   *
   * @method getHeader
   *
   * @param  {String}  key
   *
   * @return {Mixed}
   */
  getHeader (key) {
    return nodeRes.getHeader(this.response, key)
  }

  /**
   * Stream a file to the client as HTTP response.
   *
   * Options are passed directly to [send](https://www.npmjs.com/package/send)
   *
   * @method download
   *
   * @param  {String} filePath
   * @param  {Object} options
   *
   * @return {void}
   */
  download (filePath, options = {}) {
    this._sentFile = true
    nodeRes.download(this.request, this.response, filePath, options)
  }

  /**
   * Force download the file by setting `Content-disposition`
   * header.
   *
   * @method attachment
   *
   * @param  {String}   filePath
   * @param  {String}   [name]
   * @param  {String}   [disposition]
   * @param  {Object}   [options = {}]
   *
   * @return {void}
   */
  attachment (filePath, name, disposition, options = {}) {
    this._sentFile = true
    nodeRes.attachment(this.request, this.response, filePath, name, disposition, options)
  }

  /**
   * Set the `Location` header on HTTP response.
   *
   * @method location
   *
   * @param  {String} url
   *
   * @chainable
   */
  location (url) {
    nodeRes.location(this.response, url)
    return this
  }

  /**
   * Redirect the request by setting the `Location`
   * header and ending the response
   *
   * @method redirect
   *
   * @param  {String} url
   * @param  {Number} [status = 302]
   *
   * @return {void}
   */
  redirect (url, status) {
    nodeRes.redirect(this.request, this.response, url, status)
  }

  /**
   * Add the HTTP `Vary` header
   *
   * @method vary
   *
   * @param  {String} field
   *
   * @chainable
   */
  vary (field) {
    nodeRes.vary(this.response, field)
    return this
  }

  /**
   * Sets the `Content-type` header based on the
   * type passed to this method.
   *
   * @method type
   *
   * @param  {String} type
   * @param  {String} [charset = 'utf-8']
   *
   * @chainable
   */
  type (type, charset = 'utf-8') {
    nodeRes.type(this.response, type, charset)
    return this
  }

  /**
   * Sets the response body for the HTTP request.
   *
   * @method send
   *
   * @param  {Mixed} body
   *
   * @return {void}
   */
  send (body) {
    this._lazyBody = {
      method: 'send',
      content: body,
      args: []
    }
  }

  /**
   * Sets the response body for the HTTP request with
   * explicit `content-type` set to `application/json`.
   *
   * @method json
   *
   * @param  {Object} body
   *
   * @return {void}
   */
  json (body) {
    this._lazyBody = {
      method: 'json',
      content: body,
      args: []
    }
  }

  /**
   * Sets the response body for the HTTP request with
   * explicit `content-type` set to `text/javascript`.
   *
   * @method jsonp
   *
   * @param  {Object} body
   * @param  {String} [callbackFn = 'callback'] - Callback name.
   *
   * @return {void}
   */
  jsonp (body, callbackFn) {
    callbackFn = callbackFn || nodeReq.get(this.request).callback || 'callback'
    this._lazyBody = {
      method: 'jsonp',
      content: body,
      args: [callbackFn]
    }
  }

  /**
   * Ends the response by setting the `_lazyBody` as the
   * response body.
   *
   * @method end
   *
   * @return {void}
   */
  end () {
    if (!this._sentFile) {
      const method = this._lazyBody.method || 'send'
      const args = [this.request, this.response, this._lazyBody.content].concat(this._lazyBody.args)
      nodeRes[method].apply(nodeRes, args)
    }
  }

  /**
   * Send cookie with the http response
   *
   * @method cookie
   *
   * @param  {String} key
   * @param  {Mixed} value
   * @param  {Object} [options = {}]
   *
   * @return {void}
   */
  cookie (key, value, options = {}) {
    nodeCookie.create(this.response, key, value, options, this.Config.get(SECRET), true)
  }

  /**
   * Set plain cookie HTTP response
   *
   * @method plainCookie
   *
   * @param  {String}    key
   * @param  {Mixed}    value
   * @param  {Object}    [options = {}]
   *
   * @return {void}
   */
  plainCookie (key, value, options) {
    nodeCookie.create(this.response, key, value, options)
  }

  /**
   * Remove existing cookie using it's key
   *
   * @method clearCookie
   *
   * @param  {String}    key
   *
   * @return {void}
   */
  clearCookie (key) {
    nodeCookie.clear(this.response, key)
  }
}

/**
 * Defining _macros and _getters property
 * for Macroable class
 *
 * @type {Object}
 */
Response._macros = {}
Response._getters = {}

/**
 * Setting descriptive methods on the response prototype.
 */
nodeRes.descriptiveMethods.forEach((method) => {
  Response.prototype[method] = function (content) {
    this._lazyBody = { method, content, args: [] }
  }
})

module.exports = Response
<|endoftext|>


<commit_before>// Glas overlay SVG
var glas = "<?xml version='1.0' encoding='UTF-8' standalone='no'?> <svg xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:cc='http://creativecommons.org/ns#' xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' xmlns:svg='http://www.w3.org/2000/svg' xmlns='http://www.w3.org/2000/svg' xmlns:sodipodi='http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd' xmlns:inkscape='http://www.inkscape.org/namespaces/inkscape' version='1.1' id='svg' width='300' height='530' inkscape:version='0.91 r13725' sodipodi:docname='glas2.svg'> <sodipodi:namedview pagecolor='#ffffff' bordercolor='#666666' borderopacity='1' objecttolerance='10' gridtolerance='10' guidetolerance='10' inkscape:pageopacity='0' inkscape:pageshadow='2' inkscape:window-width='1680' inkscape:window-height='1028' id='namedview7' showgrid='false' inkscape:zoom='1.1557412' inkscape:cx='154.98487' inkscape:cy='268.40797' inkscape:window-x='1912' inkscape:window-y='22' inkscape:window-maximized='1' inkscape:current-layer='svg' units='px' inkscape:snap-page='true' inkscape:object-nodes='true' /> <defs id='defs4' /> <metadata id='metadata7'> <rdf:RDF> <cc:Work rdf:about=''> <dc:format>image/svg+xml</dc:format> <dc:type rdf:resource='http://purl.org/dc/dcmitype/StillImage' /> <dc:title></dc:title> </cc:Work> </rdf:RDF> </metadata> <path inkscape:connector-curvature='0' style='display:inline;opacity:1;fill:#1a1a1a;fill-opacity:1;stroke:none;stroke-width:0.17716534;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:3.4000001;stroke-dasharray:0.70866138, 1.41732275;stroke-dashoffset:0.49606296;stroke-opacity:1' d='M 0,0 0,530 300,530 300,0 0,0 Z m 51.086852,46.583586 78.873488,0 c 1.90716,0 3.44209,1.53232 3.44209,3.434033 l 0,79.343171 c 0,1.90172 -1.53493,3.43225 -3.44209,3.43225 l -78.873488,0 c -1.907171,0 -3.443896,-1.53053 -3.443896,-3.43225 l 0,-79.343171 c 0,-1.901713 1.536725,-3.434033 3.443896,-3.434033 z m 116.900138,0 78.87348,0 c 1.90717,0 3.4439,1.53232 3.4439,3.434033 l 0,79.343171 c 0,1.90172 -1.53673,3.43225 -3.4439,3.43225 l -78.87348,0 c -1.90717,0 -3.44211,-1.53053 -3.4421,-3.43225 l 0,-79.343171 c 0,-1.901713 1.53493,-3.434033 3.4421,-3.434033 z M 51.086852,162.73514 l 78.873488,0 c 1.90716,0 3.44209,1.53055 3.44209,3.43224 l 0,79.3432 c 0,1.90171 -1.53493,3.43224 -3.44209,3.43224 l -78.873488,0 c -1.907171,0 -3.443896,-1.53053 -3.443896,-3.43224 l 0,-79.3432 c 0,-1.90169 1.536725,-3.43224 3.443896,-3.43224 z m 116.900138,0 78.87348,0 c 1.90717,0 3.4439,1.53055 3.4439,3.43224 l 0,79.3432 c 0,1.90171 -1.53673,3.43224 -3.4439,3.43224 l -78.87348,0 c -1.90717,0 -3.44211,-1.53053 -3.4421,-3.43224 l 0,-79.3432 c 0,-1.90169 1.53493,-3.43224 3.4421,-3.43224 z m -116.900138,117.19648 78.873488,0 c 1.90716,0 3.44209,1.53054 3.44209,3.43225 l 0,79.34319 c 0,1.90172 -1.53493,3.43404 -3.44209,3.43404 l -78.873488,0 c -1.907171,0 -3.443896,-1.53232 -3.443896,-3.43404 l 0,-79.34319 c 0,-1.90171 1.536725,-3.43225 3.443896,-3.43225 z m 116.900138,0 78.87348,0 c 1.90717,0 3.4439,1.53054 3.4439,3.43225 l 0,79.34319 c 0,1.90172 -1.53673,3.43404 -3.4439,3.43404 l -78.87348,0 c -1.90717,0 -3.44211,-1.53232 -3.4421,-3.43404 l 0,-79.34319 c 0,-1.90171 1.53493,-3.43225 3.4421,-3.43225 z m -116.900138,116.34694 78.873488,0 c 1.90716,0 3.44209,1.53057 3.44209,3.43224 l 0,79.34317 c 0,1.90173 -1.53493,3.43225 -3.44209,3.43225 l -78.873488,0 c -1.907171,0 -3.443896,-1.53052 -3.443896,-3.43225 l 0,-79.34317 c 0,-1.90171 1.536725,-3.43224 3.443896,-3.43224 z m 116.900138,0 78.87348,0 c 1.90717,0 3.4439,1.53055 3.4439,3.43224 l 0,79.34317 c 0,1.90173 -1.53673,3.43225 -3.4439,3.43225 l -78.87348,0 c -1.90717,0 -3.44211,-1.53052 -3.4421,-3.43225 l 0,-79.34317 c 0,-1.90171 1.53493,-3.43224 3.4421,-3.43224 z' id='glas' /> </svg> ";
<commit_msg>Delete data.js<commit_after><|endoftext|>


<commit_before>/**
* Dodo
*
* @author: Ivan Cvetomirov Ivanov
* @License: MIT
* @version: 1.0.3
**/

(function($) {
    var userAgent = navigator.userAgent.toLowerCase(),
        match,
        browsers = [
            /(chrome)[ \/]([\w.]+)/,
            /(safari)[ \/]([\w.]+)/,
            /(opera)(?:.*version)?[ \/]([\w.]+)/,
            /(msie) ([\w.]+)/,
            /(mozilla)(?:.*? rv:([\w.]+))?/
        ],
		platforms = [
            /(ip\w+).*?os ([\w_]+)/,
            /(android)[ \/]([\w.]+)/,
            /(blackberry)(?:\d*?\/|.*?version\/)([\w.]+)/,
            /(windows phone)( os)? ([\w.]+)/,
            /(symbian)(?:os\/([\w.]+))?/
        ];

        b = browsers.length;
		p = platforms.length;

		$.browser = {} || 0;
		 $.platforms = {} || 0;

		while ( b-- ) {
			if ( (match = browsers[b].exec( userAgent )) && match[1] ) {
				$.browser[ match[1] ] = true;
				$.browser.version = match[2] || "0";
				break;
			}
		}
		while ( p-- ) {
			if ( (match = platforms[p].exec( userAgent )) && match[1] ) {
				$.platforms[ match[1].replace(" p", "P") ] = true;
				$.platforms.version = match[2].split("_").join(".") || "0";
				break;
			}
		}
})( window.jQuery || window );

(function($) {
	function Dodo() {
		this._curHash = '';
		this._callback = function(hash){};
	};

	$.extend(Dodo.prototype, {
		init: function(callback) {
			this._callback = callback;
			this._curHash = location.hash;

			if($.browser.msie) {
				if (this._curHash == '') {
					this._curHash = '#';
				}

				$("body").prepend('');
				var iframe = $("#jQuery_Dodo")[0].contentWindow.document;
				iframe.open();
				iframe.close();
				iframe.location.hash = this._curHash;
			} else if ($.browser.safari) {
				this._DodoBackStack = [];
				this._DodoBackStack.length = Dodo.length;
				this._DodoForwardStack = [];
				this._isFirst = true;
				this._dontCheck = false;
			}

			this._callback(this._curHash.replace(/^#/, ''));
			setInterval(this._check, 100);
		},
		add: function(hash) {
			this._DodoBackStack.push(hash);
			this._DodoForwardStack.length = 0;
			this._isFirst = true;
		},
		_check: function() {
			if($.browser.msie) {
				var iDodo = $("#jQuery_Dodo")[0];
				var iframe = iDodo.contentDocument || iDodo.contentWindow.document;
				var current_hash = iframe.location.hash;

				if(current_hash != $.Dodo._curHash) {
					location.hash = current_hash;
					$.Dodo._curHash = current_hash;
					$.Dodo._callback(current_hash.replace(/^#/, ''));
				}
			} else if ($.browser.safari) {
				if (!$.Dodo._dontCheck) {

					var DodoDelta = Dodo.length - $.Dodo._DodoBackStack.length;

					if (DodoDelta) {
						$.Dodo._isFirst = false;
						if (DodoDelta < 0) {
							for (var i = 0; i < Math.abs(DodoDelta); i++) $.Dodo._DodoForwardStack.unshift($.Dodo._DodoBackStack.pop());
						} else {
							for (var i = 0; i < DodoDelta; i++) $.Dodo._DodoBackStack.push($.Dodo._DodoForwardStack.shift());
						}
					var cachedHash = $.Dodo._DodoBackStack[$.Dodo._DodoBackStack.length - 1];
					if (cachedHash != undefined) {
						$.Dodo._curHash = location.hash;
						$.Dodo._callback(cachedHash);
					}
				} else if ($.Dodo._DodoBackStack[$.Dodo._DodoBackStack.length - 1] == undefined && !$.Dodo._isFirst){
					if (document.URL.indexOf('#') >= 0) {
						$.Dodo._callback(document.URL.split('#')[1]);
					} else {
						$.Dodo._callback('');
					}
					$.Dodo._isFirst = true;
				}
			}
		} else {
			var current_hash = location.hash;
			if(current_hash != $.Dodo._curHash) {
				$.Dodo._curHash = current_hash;
				$.Dodo._callback(current_hash.replace(/^#/, ''));
			}
		}
	},
	load: function(hash) {
		var newhash;

		if ($.browser.safari) {
			newhash = hash;
		} else {
			newhash = '#' + hash;
			location.hash = newhash;
		}
		this._curHash = newhash;

		if ($.browser.msie) {
			var iDodo = $("#jQuery_Dodo")[0];
			var iframe = iDodo.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			this._callback(hash);
		}
		else if ($.browser.safari) {
			this._dontCheck = true;
			this.add(hash);
			var fn = function() {$.Dodo._dontCheck = false;};
			window.setTimeout(fn, 200);
			this._callback(hash);
			location.hash = newhash;
		}
		else {
		  this._callback(hash);
		}
	}
});

$(document).ready(function() {
	$.Dodo = new Dodo();
});
})(jQuery);<commit_msg>ver 1.0.4<commit_after>/*
	* Dodo
	* @author: Ivan Cvetomirov Ivanov
	* @License: MIT
	* @version: 1.0.4
*/

(function($) {
    var userAgent = navigator.userAgent.toLowerCase();
    var match;
    var	browsers = [
        /(chrome)[ \/]([\w.]+)/,
        /(safari)[ \/]([\w.]+)/,
        /(opera)(?:.*version)?[ \/]([\w.]+)/,
        /(msie) ([\w.]+)/,
        /(mozilla)(?:.*? rv:([\w.]+))?/
    ];
	var platforms = [
        /(ip\w+).*?os ([\w_]+)/,
        /(android)[ \/]([\w.]+)/,
        /(blackberry)(?:\d*?\/|.*?version\/)([\w.]+)/,
        /(windows phone)( os)? ([\w.]+)/,
        /(symbian)(?:os\/([\w.]+))?/
    ];

    b = browsers.length;
    p = platforms.length;

	$.browser = {} || 0;
	$.platforms = {} || 0;

	while ( b-- ) {
		if ( (match = browsers[b].exec( userAgent )) && match[1] ) {
			$.browser[ match[1] ] = true;
			$.browser.version = match[2] || "0";
			break;
		}
	}
	while ( p-- ) {
		if ( (match = platforms[p].exec( userAgent )) && match[1] ) {
			$.platforms[ match[1].replace(" p", "P") ] = true;
			$.platforms.version = match[2].split("_").join(".") || "0";
			break;
		}
	}
})(jQuery || window );

(function($) {
	function Dodo() {
		this._curHash = '';
		this._callback = function(hash){};
	};

	$.extend(Dodo.prototype, {
		init: function(callback) {
			this._callback = callback;
			this._curHash = location.hash;

			if($.browser.msie) {
				if (this._curHash == '') {
					this._curHash = '#';
				}

				$("body").prepend('');

				var iframe = $("#Dodo")[0].contentWindow.document;

				iframe.open();
				iframe.close();
				iframe.location.hash = this._curHash;
			} else if ($.browser.safari) {
				this._DodoBackStack = [];
				this._DodoBackStack.length = Dodo.length;
				this._DodoForwardStack = [];
				this._isFirst = true;
				this._dontCheck = false;
			}

			this._callback(this._curHash.replace(/^#/, ''));
			setInterval(this._check, 100);
		},
		add: function(hash) {
			this._DodoBackStack.push(hash);
			this._DodoForwardStack.length = 0;
			this._isFirst = true;
		},
		_check: function() {
			if($.browser.msie) {
				var iDodo = $("#Dodo")[0];
				var iframe = iDodo.contentDocument || iDodo.contentWindow.document;
				var current_hash = iframe.location.hash;

				if(current_hash != $.Dodo._curHash) {
					location.hash = current_hash;
					$.Dodo._curHash = current_hash;
					$.Dodo._callback(current_hash.replace(/^#/, ''));
				}
			} else if ($.browser.safari) {
				if (!$.Dodo._dontCheck) {

					var DodoDelta = Dodo.length - $.Dodo._DodoBackStack.length;

					if (DodoDelta) {
						$.Dodo._isFirst = false;
						if (DodoDelta < 0) {
							for (var i = 0; i < Math.abs(DodoDelta); i++) $.Dodo._DodoForwardStack.unshift($.Dodo._DodoBackStack.pop());
						} else {
							for (var i = 0; i < DodoDelta; i++) $.Dodo._DodoBackStack.push($.Dodo._DodoForwardStack.shift());
						}
					var cachedHash = $.Dodo._DodoBackStack[$.Dodo._DodoBackStack.length - 1];
					if (cachedHash != undefined) {
						$.Dodo._curHash = location.hash;
						$.Dodo._callback(cachedHash);
					}
				} else if ($.Dodo._DodoBackStack[$.Dodo._DodoBackStack.length - 1] == undefined && !$.Dodo._isFirst){
					if (document.URL.indexOf('#') >= 0) {
						$.Dodo._callback(document.URL.split('#')[1]);
					} else {
						$.Dodo._callback('');
					}
					$.Dodo._isFirst = true;
				}
			}
		} else {
			var current_hash = location.hash;
			if(current_hash != $.Dodo._curHash) {
				$.Dodo._curHash = current_hash;
				$.Dodo._callback(current_hash.replace(/^#/, ''));
			}
		}
	},
	load: function(hash) {
		var newhash;

		if ($.browser.safari) {
			newhash = hash;
		} else {
			newhash = '#' + hash;
			location.hash = newhash;
		}

		this._curHash = newhash;

		if ($.browser.msie) {
			var iDodo = $("#Dodo")[0];
			var iframe = iDodo.contentWindow.document;
		iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			this._callback(hash);
		}
		else if ($.browser.safari) {
			this._dontCheck = true;
			this.add(hash);

			var fn = function() {$.Dodo._dontCheck = false;};

			window.setTimeout(fn, 200);
			this._callback(hash);
			location.hash = newhash;
		}
		else {
		  this._callback(hash);
		}
	}
});

$(document).ready(function() {
	$.Dodo = new Dodo();
});

})(jQuery);<|endoftext|>


<commit_before>(function(module) {

  formHandler = {};
  formHandler.userName = '';
  formHandler.el = {};
  formHandler.el.$nameAlert = $('#nameAlert');
  formHandler.el.$output = $('#output');
  formHandler.el.$outputText = $('#outputText');
  formHandler.el.$nameForm = $('#nameForm');
  formHandler.el.$locationForm = $('#locationForm');
  formHandler.el.$submitName = $('#submitName');
  formHandler.el.$submitLocation = $('#submitLocation');

  formHandler.init = function(){
    if (localStorage.currentUser) {
      console.log('Name was already there.');
      userName = localStorage.currentUser;
      formHandler.el.$nameForm.hide();
      formHandler.el.$locationForm.show();
      formHandler.showRec();
    };
    $('button').click(function(e){
      e.preventDefault();
      userName = $('input:text').val();
      useName(userName);
      localStorage.currentUser = userName;
      formHandler.showRec();

    });
  };

  formHandler.recommendation= function(temp){
    var response = '';
    if (temp < 50){
      response = 'cold';
    } else if (temp <=50 && temp < 75) {
      response = 'good';
    } else {
      resonse = 'hot';
    }

    return response;
  };

  formHandler.showRec = function (){
    formHandler.el.$output.text(formHandler.recommendation(userLocation[0].temperature));
  };

  // function useName(currentUser, goodDayOrBadDay) { //params of currentUser and what kind of day it is
  //   var makeGoodorBad = function(goodOrBad) {  //makeGoodorBad - to display correct kind of day later
  //     formHandler.el.$output.append('
' + formHandler.el.$outputText.text() + '
'); // adds a
 to the output section
  //     formHandler.el.$outputText.text('Hey ' + currentUser + ', ' + goodOrBad); // adds the message text to the output

  //   };
  //   return makeGoodorBad;
  // }
  //
  // //here cometh the Closure 😱
  // function message (currentUser){
  //   var goodDay = useName(currentUser, 'itsgood');
  //   goodDay('what a great day for biking!');
  //   var badDay = useName(currentUser, 'itsbad');
  //   badDay('maybe leave the bike at home today....');
  //   var soSoDay = useName(currentUser, 'itssoso');
  //   soSoDay('Conditions are not ideal. Depends on you, dude...');
  // };

  //Event Listeners for Submit Button
  formHandler.el.$submitName.click(validateUserName);

  function validateUserName(e) {
    e.preventDefault();
    // $nfValidator.element('#fname');
    var userName = document.forms['nameInput']['fname'].value;
    if (!userName) { // if userName is falsy
      formHandler.el.$nameAlert.show();
      // $output.hide();
    }else {
      message(userName);
      formHandler.el.$nameAlert.hide();
      formHandler.el.$nameForm.hide();
      // $output.show();
      formHandler.el.$locationForm.show();
    }
  };

  //Event Listener for Submit Button2
  formHandler.el.$submitLocation.click(validateLocation);

  //Validating the input for the Location Form

  function validateLocation(e){
    e.preventDefault();

    var locationDataForm = document.forms['locationData'];
    var inputLocation = {};
    var locationName = locationDataForm['flocationname'].value;

    if (!locationName){ // if location name falsy
      $('#locationNameAlert').show();
    } else {
      inputLocation.locationName = locationName;
    };

    var streetAddress = locationDataForm['fstreetaddress'].value;
    if (!streetAddress) { // if location address falsy
      $('#locationAddressAlert').show();
    } else {
      inputLocation.streetAddress = streetAddress;
    };

    var city = locationDataForm['fcity'].value;
    if (!city) { // if location city falsy
      $('#locationCityAlert').show();
    } else {
      inputLocation.city = city;
    };

    var state = locationDataForm['fstate'].value;
    if (!state) { // if location state falsy
      $('#locationStateAlert').show();
    } else {
      inputLocation.state = state;
    };

    var zipcode = locationDataForm['fzip'].value;
    if (!zipcode) { // if location zipcode falsy
      $('#locationZipAlert').show();
    } else {
      inputLocation.zipcode = zipcode;
    };
    var obj = new userLocation(inputLocation);
    obj.insertRecord(userLocation.merge);
  };

//tooltips

  // var $nfValidator = $('#nameForm').validate({
  //   debug: true,
  //   showErrors: function(errorMap, errorList) {
  //     console.log('got to showErrors.');
  //     $.each(this.validElements(), function (index, element) {
  //       var $element = $(element);
  //       $element.data('title', '')
  //       .removeClass('error')
  //       .tooltip('destroy');
  //     });
  //
  //     $.each(errorList, function (index, error) {
  //       var $element = $(error.element);
  //       $element.parent().addClass('has-error');
  //       $element.tooltip('destroy')
  //       .data('title', error.message)
  //       // .addClass('error')
  //       .tooltip();
  //     });
  //   },
  //   submitHandler: function(form) {
  //     alert('This is a valid form!');
  //   }
  // });

  module.formHandler = formHandler;
})(window);
<commit_msg>working on the recs some more<commit_after>(function(module) {

  formHandler = {};
  formHandler.userName = '';
  formHandler.el = {};
  formHandler.el.$nameAlert = $('#nameAlert');
  formHandler.el.$output = $('#output');
  formHandler.el.$outputText = $('#outputText');
  formHandler.el.$nameForm = $('#nameForm');
  formHandler.el.$locationForm = $('#locationForm');
  formHandler.el.$submitName = $('#submitName');
  formHandler.el.$submitLocation = $('#submitLocation');

  formHandler.init = function(){
    if (localStorage.currentUser) {
      console.log('Name was already there.');
      userName = localStorage.currentUser;
      formHandler.el.$nameForm.hide();
      formHandler.el.$locationForm.show();
      formHandler.showRec();
    };
    $('button').click(function(e){
      e.preventDefault();
      userName = $('input:text').val();
      useName(userName);
      localStorage.currentUser = userName;
      formHandler.showRec();

    });
  };

  formHandler.recommendation= function(temp){
    var response = '';
    if (temp < 50){
      response = 'cold';
    } else if ((temp >= 50) && (temp < 75)) {
      response = 'good';
    } else {
      resonse = 'hot';
    }

    return response;
  };

  formHandler.showRec = function (){
    formHandler.el.$output.text(formHandler.recommendation(userLocation[0].temperature));
  };

  // function useName(currentUser, goodDayOrBadDay) { //params of currentUser and what kind of day it is
  //   var makeGoodorBad = function(goodOrBad) {  //makeGoodorBad - to display correct kind of day later
  //     formHandler.el.$output.append('
' + formHandler.el.$outputText.text() + '
'); // adds a
 to the output section
  //     formHandler.el.$outputText.text('Hey ' + currentUser + ', ' + goodOrBad); // adds the message text to the output

  //   };
  //   return makeGoodorBad;
  // }
  //
  // //here cometh the Closure 😱
  // function message (currentUser){
  //   var goodDay = useName(currentUser, 'itsgood');
  //   goodDay('what a great day for biking!');
  //   var badDay = useName(currentUser, 'itsbad');
  //   badDay('maybe leave the bike at home today....');
  //   var soSoDay = useName(currentUser, 'itssoso');
  //   soSoDay('Conditions are not ideal. Depends on you, dude...');
  // };

  //Event Listeners for Submit Button
  formHandler.el.$submitName.click(validateUserName);

  function validateUserName(e) {
    e.preventDefault();
    // $nfValidator.element('#fname');
    var userName = document.forms['nameInput']['fname'].value;
    if (!userName) { // if userName is falsy
      formHandler.el.$nameAlert.show();
      // $output.hide();
    }else {

      formHandler.el.$nameAlert.hide();
      formHandler.el.$nameForm.hide();
      // $output.show();
      formHandler.el.$locationForm.show();
    }
  };

  //Event Listener for Submit Button2
  formHandler.el.$submitLocation.click(validateLocation);

  //Validating the input for the Location Form

  function validateLocation(e){
    e.preventDefault();

    var locationDataForm = document.forms['locationData'];
    var inputLocation = {};
    var locationName = locationDataForm['flocationname'].value;

    if (!locationName){ // if location name falsy
      $('#locationNameAlert').show();
    } else {
      inputLocation.locationName = locationName;
    };

    var streetAddress = locationDataForm['fstreetaddress'].value;
    if (!streetAddress) { // if location address falsy
      $('#locationAddressAlert').show();
    } else {
      inputLocation.streetAddress = streetAddress;
    };

    var city = locationDataForm['fcity'].value;
    if (!city) { // if location city falsy
      $('#locationCityAlert').show();
    } else {
      inputLocation.city = city;
    };

    var state = locationDataForm['fstate'].value;
    if (!state) { // if location state falsy
      $('#locationStateAlert').show();
    } else {
      inputLocation.state = state;
    };

    var zipcode = locationDataForm['fzip'].value;
    if (!zipcode) { // if location zipcode falsy
      $('#locationZipAlert').show();
    } else {
      inputLocation.zipcode = zipcode;
    };
    var obj = new userLocation(inputLocation);
    obj.insertRecord(userLocation.merge);
  };

//tooltips

  // var $nfValidator = $('#nameForm').validate({
  //   debug: true,
  //   showErrors: function(errorMap, errorList) {
  //     console.log('got to showErrors.');
  //     $.each(this.validElements(), function (index, element) {
  //       var $element = $(element);
  //       $element.data('title', '')
  //       .removeClass('error')
  //       .tooltip('destroy');
  //     });
  //
  //     $.each(errorList, function (index, error) {
  //       var $element = $(error.element);
  //       $element.parent().addClass('has-error');
  //       $element.tooltip('destroy')
  //       .data('title', error.message)
  //       // .addClass('error')
  //       .tooltip();
  //     });
  //   },
  //   submitHandler: function(form) {
  //     alert('This is a valid form!');
  //   }
  // });

  module.formHandler = formHandler;
})(window);
<|endoftext|>


<commit_before>(function($) {
  $(document).ready(function() {
    $(".signupForm").submit(function(event) {
      var formData = {
        'phoneNumber': $('input[name=phoneNumber]').val()
      }

      $.ajax({
        type: 'POST',
        url: 'https://autolotto-backend-production.herokuapp.com/api/v1/pre/signup',
        data: formData,
        dataType: 'json',
        crossDomain: true,
        encode: true
      }).done(function() {
        window.parent.location.href = "http://a6n2jd5.autolotto.com/confirmation";
      }).fail(function() {
        alert('Please enter a valid US phone number!');
      });

      event.preventDefault();
    });
  });
})(jQuery);
<commit_msg>autolotto wpengine<commit_after>(function($) {
  $(document).ready(function() {
    $(".signupForm").submit(function(event) {
      var formData = {
        'phoneNumber': $('input[name=phoneNumber]').val()
      }

      $.ajax({
        type: 'POST',
        url: 'https://autolotto-backend-production.herokuapp.com/api/v1/pre/signup',
        data: formData,
        dataType: 'json',
        crossDomain: true,
        encode: true
      }).done(function() {
        window.parent.location.href = "http://autolotto.wpengine.com/confirmation/";
      }).fail(function() {
        alert('Please enter a valid US phone number!');
      });

      event.preventDefault();
    });
  });
})(jQuery);
<|endoftext|>


<commit_before>var Game = function(boardString){
  var board = '';
  this.board = '';
  if (arguments.length === 1) {
    this.board = this.toArray(boardString);
  } else {
    function random() {
      return Math.floor(Math.random() * 10 + 6);
    };
    var firstTwo = random(), secondTwo = random();
    for ( var i = 0; i < 16; i++ ) {
      if (i === firstTwo || i === secondTwo) {
        board += '2';
      } else {
        board += '0';
      };
    };
    this.board = this.toArray(board);
  }
};

Game.prototype = {

  toString: function() {
    this.board.forEach(function(row) {
      console.log(row.join(''));
    });
  },

  toArray: function(chars) {
    var boardArray = [];
    for( var i = 0; i < 16; i += 4) {
      var subarray = chars.slice(i, 4 + i);
      boardArray.push(subarray.split(''));
    }
    return boardArray;
  },

    filterNonZeros: function(matrix) {
    filtered = [];
    matrix.forEach(function(row) {
      filtered.push(row.filter(function(value) {
        return value === '0';
      }));
    });
    return filtered
  },

  randomNumber: function() {
    var randoNumber = (Math.random() < .8) ? '2' : '4';
    return randoNumber
  },

  spawn: function(matrix) {
    var index = matrix.length;
    var slicedArrays = matrix.slice(Math.floor(Math.random() * index));
    var insertArray = slicedArrays[slicedArrays.length - 1];
    insertArray.splice(Math.floor(Math.random() * insertArray.length), 1, this.randomNumber());

  },

  filterZeros: function(matrix) {
    filtered = []
    matrix.forEach(function(row) {
      filtered.push(row.filter(function(value) {
        return value !== '0';
      }));
    });
    return filtered
  },

  leftAddNumbers: function(subarrays) {
    subarrays.forEach(function(arr) {
      if (arr.length > 1){
        for(var i = 0; i < arr.length; i++){
          if (arr[i] === arr[i+1]){
            arr[i] = (parseInt(arr[i]) + parseInt(arr[i+1])).toString();
            arr.splice(i+1, 1);
          }
        }
      }
    })
    return subarrays;
  },

  rightAddNumbers: function(subarrays) {
    subarrays.forEach(function(arr) {
      if (arr.length > 1){
        for(var i = arr.length - 1; i > 0; i--) {
          if (arr[i] === arr[i-1]){
            arr[i] = (parseInt(arr[i]) + parseInt(arr[i-1])).toString();
            arr.splice(i-1, 1);
          }
        }
      }
    })
    return subarrays;

  },

  move: function(dir) {
    switch (dir) {
      case 'left':
        this.board = this.leftAddNumbers(this.filterZeros(this.board))
        this.board.forEach(function(row) {
          for( var i = 0; row.length < 4; i++ ) {
            row.push('0');
          }
        })
        break;
      case 'right':
        this.board = this.rightAddNumbers(this.filterZeros(this.board));
        this.board.forEach(function(row) {
          for( var i = 0; row.length < 4; i++ ) {
            row.unshift('0');
          }
        })
        break;
      case 'up':
        var transposedArray = _.zip.apply(null, this.board);
        transposedArray = this.leftAddNumbers(this.filterZeros(transposedArray));
        transposedArray.forEach(function(row) {
          for( var i = 0; row.length < 4; i++ ) {
            row.push('0');
          }
        })
        this.board = _.zip.apply(null, transposedArray);
        break;
      case 'down':
        var transposedArray = _.zip.apply(null, this.board);
        transposedArray = this.rightAddNumbers(this.filterZeros(transposedArray));
        transposedArray.forEach(function(row) {
          for( var i = 0; row.length < 4; i++ ) {
            row.unshift('0');
          }
        })
        this.board = _.zip.apply(null, transposedArray);
        break;
    }
  }
};

<commit_msg>fixes bugs in spawn function using underscore library, and adds spawning at the end of move function<commit_after>var Game = function(boardString){
  var board = '';
  this.board = '';
  if (arguments.length === 1) {
    this.board = this.toArray(boardString);
  } else {
    function random() {
      return Math.floor(Math.random() * 10 + 6);
    };
    var firstTwo = random(), secondTwo = random();
    for ( var i = 0; i < 16; i++ ) {
      if (i === firstTwo || i === secondTwo) {
        board += '2';
      } else {
        board += '0';
      };
    };
    this.board = this.toArray(board);
  }
};

Game.prototype = {

  toString: function() {
    this.board.forEach(function(row) {
      console.log(row.join(''));
    });
  },

  toArray: function(chars) {
    var boardArray = [];
    for( var i = 0; i < 16; i += 4) {
      var subarray = chars.slice(i, 4 + i);
      boardArray.push(subarray.split(''));
    }
    return boardArray;
  },

    filterNonZeros: function(matrix) {
    filtered = [];
    matrix.forEach(function(row) {
      filtered.push(row.filter(function(value) {
        return value === '0';
      }));
    });
    return filtered
  },

  randomNumber: function() {
    var randoNumber = (Math.random() < .8) ? '2' : '4';
    return randoNumber
  },

  spawn: function() {
      var index = (Math.floor(Math.random() * 4));
      var sampledArray = _.sample(this.board);
      if (sampledArray[index] === "0") {
        sampledArray.splice(index, 1, this.randomNumber());
      } else {
        this.spawn();
      }

  },

  filterZeros: function(matrix) {
    filtered = []
    matrix.forEach(function(row) {
      filtered.push(row.filter(function(value) {
        return value !== '0';
      }));
    });
    return filtered
  },

  leftAddNumbers: function(subarrays) {
    subarrays.forEach(function(arr) {
      if (arr.length > 1){
        for(var i = 0; i < arr.length; i++){
          if (arr[i] === arr[i+1]){
            arr[i] = (parseInt(arr[i]) + parseInt(arr[i+1])).toString();
            arr.splice(i+1, 1);
          }
        }
      }
    })
    return subarrays;
  },

  rightAddNumbers: function(subarrays) {
    subarrays.forEach(function(arr) {
      if (arr.length > 1){
        for(var i = arr.length - 1; i > 0; i--) {
          if (arr[i] === arr[i-1]){
            arr[i] = (parseInt(arr[i]) + parseInt(arr[i-1])).toString();
            arr.splice(i-1, 1);
          }
        }
      }
    })
    return subarrays;

  },

  move: function(dir) {
    that = this;
    switch (dir) {
      case 'left':
        this.board = this.leftAddNumbers(this.filterZeros(this.board))
        this.board.forEach(function(row) {
          for( var i = 0; row.length < 4; i++ ) {
            row.push('0');
          }
        })
        break;
      case 'right':
        this.board = this.rightAddNumbers(this.filterZeros(this.board));
        this.board.forEach(function(row) {
          for( var i = 0; row.length < 4; i++ ) {
            row.unshift('0');
          }
        })
        break;
      case 'up':
        var transposedArray = _.zip.apply(null, this.board);
        transposedArray = this.leftAddNumbers(this.filterZeros(transposedArray));
        transposedArray.forEach(function(row) {
          for( var i = 0; row.length < 4; i++ ) {
            row.push('0');
          }
        })
        this.board = _.zip.apply(null, transposedArray);
        break;
      case 'down':
        var transposedArray = _.zip.apply(null, this.board);
        transposedArray = this.rightAddNumbers(this.filterZeros(transposedArray));
        transposedArray.forEach(function(row) {
          for( var i = 0; row.length < 4; i++ ) {
            row.unshift('0');
          }
        })
        this.board = _.zip.apply(null, transposedArray);
        break;
    }
  that.spawn()
  }
};

<|endoftext|>


<commit_before>class Dice extends React.Component {
  constructor() {
    super();
    this.state = {
      words: this.parseInput(this.getParams(location.search)['var']),
      div: document.createElement("div")
		};

    this.handleSubmit = this.handleSubmit.bind(this);
    this.parseInput = this.parseInput.bind(this);
    this.getParams = this.getParams.bind(this);
    this.appendWord = this.appendWord.bind(this);
    this.appendImg = this.appendImg.bind(this);
  }

  getParams(query){
    if (!query) {
      return { };
    }
    return (/^[?#]/.test(query) ? query.slice(1) : query)
      .split('&')
      .reduce((params, param) => {
        let [ key, value ] = param.split('=');
        params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
        return params;
      }, { });
  };

  parseInput(input) {
    return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
  }

  image(word) {

  }

  appendWord(text) {
    var p = document.createElement("p");
    p.appendChild(document.createTextNode(text));
    return p;
  }

  appendImg(src) {
    var img = document.createElement("img");
    img.className = 'img';
    img.src = src;
    return img;
  }

  handleSubmit() {
      var div = this.state.div;
      while (div.hasChildNodes()) {
        div.removeChild(div.lastChild);
      }
      var words = this.state.words;
      for(var i = 0; i < words.length; i++) {
        var random = words[i][Math.floor(Math.random()*(words[i].length-1))];
        if (this.image(random)) {
          div.appendChild(this.appendImg(random));
        }
        else {
          div.appendChild(this.appendWord(random));
        }
      }
      document.body.appendChild(div);
  }

  render() {
    return (

        <input type="button" value="Throw dice" onClick={this.handleSubmit}/>

    );
  }
}

ReactDOM.render(
  <Dice />,
  document.getElementById('root')
);<commit_msg>Add function that checks if an image is a URL<commit_after>class Dice extends React.Component {
  constructor() {
    super();
    this.state = {
      words: this.parseInput(this.getParams(location.search)['var']),
      div: document.createElement("div")
		};

    this.handleSubmit = this.handleSubmit.bind(this);
    this.parseInput = this.parseInput.bind(this);
    this.getParams = this.getParams.bind(this);
    this.appendWord = this.appendWord.bind(this);
    this.appendImg = this.appendImg.bind(this);
  }

  getParams(query){
    if (!query) {
      return { };
    }
    return (/^[?#]/.test(query) ? query.slice(1) : query)
      .split('&')
      .reduce((params, param) => {
        let [ key, value ] = param.split('=');
        params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
        return params;
      }, { });
  };

  parseInput(input) {
    return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
  }

  image(word) {
    var expr = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
    var regex = new RegExp(expr);
    return word.match(regex);

  }

  appendWord(text) {
    var p = document.createElement("p");
    p.appendChild(document.createTextNode(text));
    return p;
  }

  appendImg(src) {
    var img = document.createElement("img");
    img.className = 'img';
    img.src = src;
    return img;
  }

  handleSubmit() {
      var div = this.state.div;
      while (div.hasChildNodes()) {
        div.removeChild(div.lastChild);
      }
      var words = this.state.words;
      for(var i = 0; i < words.length; i++) {
        var random = words[i][Math.floor(Math.random()*(words[i].length-1))];
        if (this.image(random)) {
          div.appendChild(this.appendImg(random));
        }
        else {
          div.appendChild(this.appendWord(random));
        }
      }
      document.body.appendChild(div);
  }

  render() {
    return (

        <input type="button" value="Throw dice" onClick={this.handleSubmit}/>

    );
  }
}

ReactDOM.render(
  <Dice />,
  document.getElementById('root')
);<|endoftext|>