<commit_before>udefine(['../graphics'], function(Graphics) {

  Graphics.init = function(container, width, height) {
    Graphics.renderer = 'DOM';

    if (container.indexOf('#') === 0) {
      container = container.slice(1);
    }

    width = width || 600;
    height = height || 480;

    Graphics.container = container;
    Graphics.element = document.getElementById(container);

    if (Graphics.element == null) {
      var element = document.createElement('div');
      element.id = container;
      document.body.appendChild(element);

      Graphics.element = element;
    }
  };

  Graphics.on('add', function(obj) {
    // Remove previous elements of the same id
    if (document.getElementById(obj.name) != null) {

    }

    var parent = obj.parent;

    var parentElem = (function() {
      if ((parent && parent.isRoot) || parent == null) {
        return Graphics.element;
      } else {
      	var parentId = obj.parent.id.toLowerCase();
        var element = document.getElementById(parentId);
        if (element == null) {
          return Graphics.element;
        } else {
          return element;
        }
      }
    })();

    /*if (parent == null) {
      console.warn('Parent (' + obj.parent.name + ') for object (' + obj.name + ') does not exist. Aborting render call for this object.');
      return;
    }*/

    var element = document.createElement('div');
    element.id = obj.id.toLowerCase();
    element.className = [obj.type.toLowerCase(), obj.name.toLowerCase()].join(' ');
    element.style.position = 'absolute';

    switch (obj.type) {
    case 'Scene':
      break;
    case 'GameObject':
      element.style.left = obj.x + 'px';
      element.style.top = obj.y + 'px';
      break;
    default:
      break;
    }

    parentElem.appendChild(element);
  });

  Graphics.on('render', function(obj) {
    // Update element attributes

    switch (obj.type) {
    case 'GameObject':
      break;
    default:
      break;
    }

  });

  return Graphics;

});
<commit_msg>Fixes rendering for GameObjects<commit_after>udefine(['../graphics'], function(Graphics) {

  var pixelize = function(num) {
    return num + 'px';
  };

  var unpixelize = function(str) {
    return parseFloat(str) || 0;
  };

  Graphics.init = function(container, width, height) {
    Graphics.renderer = 'DOM';

    if (container.indexOf('#') === 0) {
      container = container.slice(1);
    }

    width = width || 600;
    height = height || 480;

    Graphics.container = container;
    Graphics.element = document.getElementById(container);

    if (Graphics.element == null) {
      var element = document.createElement('div');
      element.id = container;
      document.body.appendChild(element);

      Graphics.element = element;
    }

    Graphics.element.style.width = pixelize(width);
    Graphics.element.style.height = pixelize(height);

  };

  Graphics.on('add', function(obj) {
    // Remove previous elements of the same id
    if (document.getElementById(obj.name) != null) {

    }

    var parent = obj.parent;

    var parentElem = (function() {
      if ((parent && parent.isRoot) || parent == null) {
        return Graphics.element;
      } else {
        var parentId = obj.parent.id.toLowerCase();
        var element = document.getElementById(parentId);
        if (element == null) {
          return Graphics.element;
        } else {
          return element;
        }
      }
    })();

    var element = document.createElement('div');
    element.id = obj.id.toLowerCase();
    element.className = [obj.type.toLowerCase(), obj.name.toLowerCase()].join(' ');
    element.style.position = 'absolute';

    switch (obj.type) {
    case 'Scene':
      break;
    case 'GameObject':
      element.style.left = pixelize(obj.x);
      element.style.top = pixelize(obj.y);
      element.style.width = pixelize(obj.width);
      element.style.height = pixelize(obj.height);
      break;
    default:
      break;
    }

    parentElem.appendChild(element);
  });

  Graphics.on('texture-loaded', function(obj, texture) {
    var element = document.getElementById(obj.id.toLowerCase());

    if (element != null) {
      element.style.backgroundImage = 'url(' + texture.filename + ')';
      element.style.width = pixelize(obj.width);
      element.style.height = pixelize(obj.height);
    }
  });

  Graphics.on('render', function(obj) {
    // Update element attributes
    var element = document.getElementById(obj.id.toLowerCase());

    if (element != null) {
      switch (obj.type) {
      case 'GameObject':
        var elemX = unpixelize(element.style.left);
        var elemY = unpixelize(element.style.top);
        var elemWidth = unpixelize(element.style.width);
        var elemHeight = unpixelize(element.style.height);

        if (elemX !== obj.x) {
          element.style.left = pixelize(obj.x);
        }

        if (elemY !== obj.y) {
          element.style.top = pixelize(obj.y);
        }

        if (elemWidth !== obj.width) {
          element.style.width = pixelize(obj.width);
        }

        if (elemHeight !== obj.height) {
          element.style.height = pixelize(obj.height);
        }

        // Set background color
        if (!obj.texture.filename) {
        	element.style.backgroundColor = obj.texture.color;
        }
        break;
      case 'Game':
      	break;
      default:
      	break;
      }

    }

  });

  return Graphics;

});
<|endoftext|>


<commit_before>/**!
 * Part of the jMediaelement-Project | http://github.com/aFarkas/jMediaelement
 * @author Alexander Farkas
 * Copyright 2010, Alexander Farkas
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */

(function($){
	var doc = document,
		rep = /^jwPlayer-/
	;

	function getAPI(id){
		id = id.replace(rep, '');
		return $.data(doc.getElementById(id), 'mediaElemSupport').apis.jwPlayer;
	}
	var privJwEvents = {
		View: {
			PLAY: function(obj){
				var api = obj.state && getAPI(obj.id);
				if(!api){return;}
				api._trigger('play');
			}
		},
		Model: {
			META: function(obj){
				if(obj.type === 'metadata'){
					var api = getAPI(obj.id);
					if(!api){return;}
					api._trigger({
						type: 'loadedmeta',
						duration: obj.duration
					});
				}

			},
			TIME: function(obj){
				var api = getAPI(obj.id),
					e 	= {
							type: 'timechange',
							time: obj.position
						}
				;
				if(!api){return;}

				//workaround: meta isn´t triggered on audio | ToDo: Is this needed with jwplayer 5.1.x?
				if(!api.loadedmeta){
					api._trigger({
						type: 'loadedmeta',
						duration: obj.duration
					});
				}

				api.currentPos = obj.position;
				if(obj.duration){
					e.duration = obj.duration;
					e.timeProgress = obj.position / obj.duration * 100;
				}
				if(obj.position && api.data.playFirstFrame && !api.data.playThrough){
					api.pause();
					api.data.playThrough = true;
				}
				api._trigger(e);
			},
			STATE: function(obj){
				if(obj.newstate === 'IDLE'){
					return false;
				}
				var api = getAPI(obj.id),
					type
				;
				if(!api){return false;}
				switch(obj.newstate) {
					case 'PLAYING':
						type = 'playing';
						break;
					case 'PAUSED':
						type = 'pause';
						break;
					case 'COMPLETED':
						type = 'ended';
						break;
					case 'BUFFERING':
						type = 'waiting';
					break;
				}

				if(type){
					api._trigger(type);
				}
				return type;
			}
		},
		Controller: {
			VOLUME: function(obj){
				var api = getAPI(obj.id);
				if(!api){return;}
				api._trigger({type: 'volumelevelchange', volumelevel: obj.percentage});
			},
			MUTE: function(obj){
				var api = getAPI(obj.id);
				if(!api){return;}
				api._trigger({type: 'mute', isMuted: obj.state});
			}
		}
	};
	window.jwEvents = {
		four: $.extend(true, {}, privJwEvents, {
			Model: {
				LOADED: function(obj){
					var api = getAPI(obj.id);
					if(!api){return;}
					var evt = {
						type: 'progresschange',
						lengthComputable: !!(obj.total)
					};
					if(obj.total){
						$.extend(evt, {
							relLoaded: obj.total / obj.loaded * 100
						});
						api._buffered = evt.relLoaded;
					}
					api._trigger(evt);
				}
			}

		}),
		five: $.extend(true, {}, privJwEvents, {
			Model: {
				BUFFER: function(obj){
					var api = getAPI(obj.id);
					if(!api){return;}
					var evt = {
						type: 'progresschange',
						relLoaded: obj.percentage,
						relStart: 0
					};
					api._buffered = obj.percentage;
					api._trigger(evt);
				},
				STATE: function(obj){
					var state = privJwEvents.Model.STATE(obj);
					if(state === 'playing'){
						var api = getAPI(obj.id);
						if(!api){return;}
						api._trigger('play');
					}
				}
			}
		})
	};

	window.playerReady = function (obj) {

		var api = getAPI(obj.id);
		if(api){

			//https://bugzilla.mozilla.org/show_bug.cgi?id=90268 every html5video shim has this problem fix it!!!
			if(api.isAPIReady){
				if(!api.apiElem.sendEvent){
					this._reInit();
					return;
				} else if(api._lastLoad && api.isAPIActive){
					api._mmload(api._lastLoad);
				}
			}

			var apiVersion = (parseInt(obj.version, 10) > 4)? 'five' : 'four';
			//add events
			$.each(jwEvents[apiVersion], function(mvcName, evts){
				$.each(evts, function(evtName){
					api.apiElem['add'+ mvcName +'Listener'](evtName, 'jwEvents.'+ apiVersion +'.'+ mvcName +'.'+ evtName);
				});

			});

			api._trigger('mmAPIReady');
		}
	};

	var jwAPI = {
		_init: function(){
			this._buffered = this._buffered || 0;
		},
		_reInitCount: 0,
		_reInitTimer: false,
		_reInit: function(){
			var that = this;

			if(this._reInitCount < 3){
				var overflow = this.visualElem[0].style.overflow;
				this.visualElem[0].style.overflow = 'hidden';
				setTimeout(function(){
					that.visualElem[0].style.overflow = 'visible';
					that.visualElem[0].style.overflow = overflow;
				}, 0);
			}
			this._reInitCount++;

			if(!this._reInitTimer){
				this._reInitTimer = true;
				setTimeout(function(){
					that._reInitCount = 0;
					that._reInitTimer = false;
				}, 30000);
			}
		},
		play: function(){
			this.data.playThrough = true;
			this.apiElem.sendEvent('PLAY', 'true');
			this._trigger('play');
		},
		pause: function(){
			this.apiElem.sendEvent('PLAY', 'false');
		},
		_isPlaying: function(){
			var cfg = this.apiElem.getConfig();
			return (cfg) ? (cfg.state === 'PLAYING' ) : undefined;
		},
		_mmload: function(src, poster){
			this._lastLoad = {
				file: src,
				image: poster || false
			};
			this.apiElem.sendEvent('LOAD', this._lastLoad);
			if (!$.attr(this.element, 'autoplay')) {
				this.apiElem.sendEvent('PLAY', 'false');
			} else {
				this.apiElem.sendEvent('PLAY', 'true');
			}
		},
		muted: function(state){
			if(typeof state !== 'boolean'){
				var cfg = this.apiElem.getConfig();
				return (cfg || {}).mute;
			}
			this.apiElem.sendEvent('mute', (state) ? 'true' : false);
		},
		_isSeekable: function(t){
			var file = this.getCurrentSrc();

			if(this._buffered === 100 || (file.indexOf('http') !== 0 && file.indexOf('file') !== 0)){
				return true;
			}

			var dur = this.getDuration();
			if(!dur){
				return false;
			}

			return (t / dur * 100 < this._buffered);
		},
		currentTime: function(t){
			if(!isFinite(t)){
				return this.currentPos || 0;
			}
			var api 			= this,
				wantsPlaying 	= (/PLAYING|BUFFERING/.test( this.apiElem.getConfig().state)),
				doSeek 			= function(){
					api.apiElem.sendEvent('SEEK', t);
					api.currentPos = t;
					api._trigger({type: 'timechange', time: t});
				},
				unbind 			= function(){
					$(api.element).unbind('.jwseekrequest');
				}
			;
			if(!wantsPlaying){
				this.apiElem.sendEvent('PLAY', 'true');
				this.apiElem.sendEvent('PLAY', 'false');
			}
			clearTimeout(this._seekrequestTimer);
			unbind();
			if(this._isSeekable(t)){
				doSeek();
			} else {
				this.apiElem.sendEvent('PLAY', 'false');
				this._trigger('waiting');
				$(this.element)
					.bind('progresschange.jwseekrequest', function(){
						if(api._isSeekable(t)){
							unbind();
							clearTimeout(api._seekrequestTimer);
							if(wantsPlaying){
								api.apiElem.sendEvent('PLAY', 'true');
							}
							api._seekrequestTimer = setTimeout(doSeek, 99);
						}
					})
					.bind('mediareset.jwseekrequest', unbind)
					.bind('play.jwseekrequest', unbind)
					.bind('pause.jwseekrequest', unbind)
				;
				//seek failed
				this._seekrequestTimer = setTimeout(unbind, 9999);
			}

		},
		getDuration: function(){
			var t = this.apiElem.getPlaylist()[0].duration || 0;
			return t < 0 ? 0 : t;
		},
		volume: function(v){
			if(!isFinite(v)){
				return parseInt(this.apiElem.getConfig().volume, 10);
			}
			this.apiElem.sendEvent('VOLUME', ''+v);
		},
		getCurrentSrc: function(){
			return (this.apiElem.getConfig() || {}).file || '';
		}
	};

	$.multimediaSupport.add('jwPlayer', 'video', jwAPI);
	$.multimediaSupport.add('jwPlayer', 'audio', jwAPI);
})(jQuery);
<commit_msg>fixed bug with reinitzialized flash in firefox<commit_after>/**!
 * Part of the jMediaelement-Project | http://github.com/aFarkas/jMediaelement
 * @author Alexander Farkas
 * Copyright 2010, Alexander Farkas
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */

(function($){
	var doc = document,
		rep = /^jwPlayer-/
	;

	function getAPI(id){
		id = id.replace(rep, '');
		return $.data(doc.getElementById(id), 'mediaElemSupport').apis.jwPlayer;
	}
	var privJwEvents = {
		View: {
			PLAY: function(obj){
				var api = obj.state && getAPI(obj.id);
				if(!api){return;}
				api._trigger('play');
			}
		},
		Model: {
			META: function(obj){
				if(obj.type === 'metadata'){
					var api = getAPI(obj.id);
					if(!api){return;}
					api._trigger({
						type: 'loadedmeta',
						duration: obj.duration
					});
				}

			},
			TIME: function(obj){
				var api = getAPI(obj.id),
					e 	= {
							type: 'timechange',
							time: obj.position
						}
				;
				if(!api){return;}

				//workaround: meta isn´t triggered on audio | ToDo: Is this needed with jwplayer 5.1.x?
				if(!api.loadedmeta){
					api._trigger({
						type: 'loadedmeta',
						duration: obj.duration
					});
				}

				api.currentPos = obj.position;
				if(obj.duration){
					e.duration = obj.duration;
					e.timeProgress = obj.position / obj.duration * 100;
				}
				if(obj.position && api.data.playFirstFrame && !api.data.playThrough){
					api.pause();
					api.data.playThrough = true;
				}
				api._trigger(e);
			},
			STATE: function(obj){
				if(obj.newstate === 'IDLE'){
					return false;
				}
				var api = getAPI(obj.id),
					type
				;
				if(!api){return false;}
				switch(obj.newstate) {
					case 'PLAYING':
						type = 'playing';
						break;
					case 'PAUSED':
						type = 'pause';
						break;
					case 'COMPLETED':
						type = 'ended';
						break;
					case 'BUFFERING':
						type = 'waiting';
					break;
				}

				if(type){
					api._trigger(type);
				}
				return type;
			}
		},
		Controller: {
			VOLUME: function(obj){
				var api = getAPI(obj.id);
				if(!api){return;}
				api._trigger({type: 'volumelevelchange', volumelevel: obj.percentage});
			},
			MUTE: function(obj){
				var api = getAPI(obj.id);
				if(!api){return;}
				api._trigger({type: 'mute', isMuted: obj.state});
			}
		}
	};
	window.jwEvents = {
		four: $.extend(true, {}, privJwEvents, {
			Model: {
				LOADED: function(obj){
					var api = getAPI(obj.id);
					if(!api){return;}
					var evt = {
						type: 'progresschange',
						lengthComputable: !!(obj.total)
					};
					if(obj.total){
						$.extend(evt, {
							relLoaded: obj.total / obj.loaded * 100
						});
						api._buffered = evt.relLoaded;
					}
					api._trigger(evt);
				}
			}

		}),
		five: $.extend(true, {}, privJwEvents, {
			Model: {
				BUFFER: function(obj){
					var api = getAPI(obj.id);
					if(!api){return;}
					var evt = {
						type: 'progresschange',
						relLoaded: obj.percentage,
						relStart: 0
					};
					api._buffered = obj.percentage;
					api._trigger(evt);
				},
				STATE: function(obj){
					var state = privJwEvents.Model.STATE(obj);
					if(state === 'playing'){
						var api = getAPI(obj.id);
						if(!api){return;}
						api._trigger('play');
					}
				}
			}
		})
	};

	window.playerReady = function (obj) {

		var api = getAPI(obj.id);
		if(api){

			//https://bugzilla.mozilla.org/show_bug.cgi?id=90268 every html5video shim has this problem fix it!!!
			if(api.isAPIReady){
				if(!api.apiElem.sendEvent){
					this._reInit();
					return;
				} else if(api._lastLoad && api.isAPIActive){
					api._mmload(api._lastLoad.file, api._lastLoad.image);
				}
			}

			var apiVersion = (parseInt(obj.version, 10) > 4)? 'five' : 'four';
			//add events
			$.each(jwEvents[apiVersion], function(mvcName, evts){
				$.each(evts, function(evtName){
					api.apiElem['add'+ mvcName +'Listener'](evtName, 'jwEvents.'+ apiVersion +'.'+ mvcName +'.'+ evtName);
				});

			});

			api._trigger('mmAPIReady');
		}
	};

	var jwAPI = {
		_init: function(){
			this._buffered = this._buffered || 0;
		},
		_reInitCount: 0,
		_reInitTimer: false,
		_reInit: function(){
			var that = this;

			if(this._reInitCount < 3){
				var overflow = this.visualElem[0].style.overflow;
				this.visualElem[0].style.overflow = 'hidden';
				setTimeout(function(){
					that.visualElem[0].style.overflow = 'visible';
					that.visualElem[0].style.overflow = overflow;
				}, 0);
			}
			this._reInitCount++;

			if(!this._reInitTimer){
				this._reInitTimer = true;
				setTimeout(function(){
					that._reInitCount = 0;
					that._reInitTimer = false;
				}, 30000);
			}
		},
		play: function(){
			this.data.playThrough = true;
			this.apiElem.sendEvent('PLAY', 'true');
			this._trigger('play');
		},
		pause: function(){
			this.apiElem.sendEvent('PLAY', 'false');
		},
		_isPlaying: function(){
			var cfg = this.apiElem.getConfig();
			return (cfg) ? (cfg.state === 'PLAYING' ) : undefined;
		},
		_mmload: function(src, poster){
			this._lastLoad = {
				file: src,
				image: poster || false
			};
			this.apiElem.sendEvent('LOAD', this._lastLoad);
			if (!$.attr(this.element, 'autoplay')) {
				this.apiElem.sendEvent('PLAY', 'false');
			} else {
				this.apiElem.sendEvent('PLAY', 'true');
			}
		},
		muted: function(state){
			if(typeof state !== 'boolean'){
				var cfg = this.apiElem.getConfig();
				return (cfg || {}).mute;
			}
			this.apiElem.sendEvent('mute', (state) ? 'true' : false);
		},
		_isSeekable: function(t){
			var file = this.getCurrentSrc();

			if(this._buffered === 100 || (file.indexOf('http') !== 0 && file.indexOf('file') !== 0)){
				return true;
			}

			var dur = this.getDuration();
			if(!dur){
				return false;
			}

			return (t / dur * 100 < this._buffered);
		},
		currentTime: function(t){
			if(!isFinite(t)){
				return this.currentPos || 0;
			}
			var api 			= this,
				wantsPlaying 	= (/PLAYING|BUFFERING/.test( this.apiElem.getConfig().state)),
				doSeek 			= function(){
					api.apiElem.sendEvent('SEEK', t);
					api.currentPos = t;
					api._trigger({type: 'timechange', time: t});
				},
				unbind 			= function(){
					$(api.element).unbind('.jwseekrequest');
				}
			;
			if(!wantsPlaying){
				this.apiElem.sendEvent('PLAY', 'true');
				this.apiElem.sendEvent('PLAY', 'false');
			}
			clearTimeout(this._seekrequestTimer);
			unbind();
			if(this._isSeekable(t)){
				doSeek();
			} else {
				this.apiElem.sendEvent('PLAY', 'false');
				this._trigger('waiting');
				$(this.element)
					.bind('progresschange.jwseekrequest', function(){
						if(api._isSeekable(t)){
							unbind();
							clearTimeout(api._seekrequestTimer);
							if(wantsPlaying){
								api.apiElem.sendEvent('PLAY', 'true');
							}
							api._seekrequestTimer = setTimeout(doSeek, 99);
						}
					})
					.bind('mediareset.jwseekrequest', unbind)
					.bind('play.jwseekrequest', unbind)
					.bind('pause.jwseekrequest', unbind)
				;
				//seek failed
				this._seekrequestTimer = setTimeout(unbind, 9999);
			}

		},
		getDuration: function(){
			var t = this.apiElem.getPlaylist()[0].duration || 0;
			return t < 0 ? 0 : t;
		},
		volume: function(v){
			if(!isFinite(v)){
				return parseInt(this.apiElem.getConfig().volume, 10);
			}
			this.apiElem.sendEvent('VOLUME', ''+v);
		},
		getCurrentSrc: function(){
			return (this.apiElem.getConfig() || {}).file || '';
		}
	};

	$.multimediaSupport.add('jwPlayer', 'video', jwAPI);
	$.multimediaSupport.add('jwPlayer', 'audio', jwAPI);
})(jQuery);
<|endoftext|>


<commit_before>const urban = require("urban");
const config = require("../configuration/Configuration");
const logger = require("../logger/Logger");

module.exports.CommandName = "urban";

module.exports.HandleRequest = function(request, response, next){
  logger.LogInfoData("Received post for command 'urban'", request.params);
  if(request.params.token == config.data.slackToken) {
    if(request.params.text && request.params.text.length > 0) {
      logger.LogInfo(`Looking up definition ${request.params.text}`);
      urban(request.params.text).first(function(json) {
        response.json(200, {
          response_type: "in_channel",
          text: json.definition,
          attachments: [
            {
              text: json.example
            },
            {
              text: json.permalink
            }
          ]
        });
      });
    }
    else {
      logger.LogInfo("Looking up random definition");
      urban.random().first(function(json) {
        response.json(200, {
          response_type: "in_channel",
          text: json.definition,
          attachments: [
            {
              text: json.example
            },
            {
              text: json.permalink
            }
          ]
        });
      });
    }

    // response.json(200, {
    //   response_type: "in_channel",
    //   text: "Slack's POST data: " + JSON.stringify(request.params)
    // });
  }
  return next();
};<commit_msg><commit_after>const urban = require("urban");
const config = require("../configuration/Configuration");
const logger = require("../logger/Logger");

module.exports.CommandName = "urban";

module.exports.HandleRequest = function(request, response, next){
  logger.LogInfoData("Received post for command 'urban'", request.params);
  if(request.params.token == config.data.slackToken) {
    if(request.params.text && request.params.text.length > 0) {
      logger.LogInfo(`Looking up definition ${request.params.text}`);
      urban(request.params.text).first(function(json) {
        if(json) {
          response.json(200, FormatSlackAttachmentMessage(true, json));
        }
        else {
          response.json(200, FormatSlackMessage(false, `Could not find a definition for ${request.params.text}.`));
        }
      });
    }
    else {
      logger.LogInfo("Looking up random definition");
      urban.random().first(function(json) {
        if(json) {
          response.json(200, FormatSlackAttachmentMessage(true, json));
        }
        else {
          response.json(200, FormatSlackMessage(false, "Could not find a random definition."));
        }
      });
    }
  }
  return next();
};

function FormatSlackAttachmentMessage(sendToChannel, jsonData) {
  return {
    response_type: sendToChannel ? "in_channel" : "ephemeral",
    text: undefined,
    attachments: [{
      title: jsonData.title,
      title_link: jsonData.permalink,
      text: jsonData.definition
    },
    {
      text: `Example:\n ${jsonData.example}`
    }]
  }
}

function FormatSlackMessage(sendToChannel, text) {
  return {
    response_type: sendToChannel ? "in_channel" : "ephemeral",
    text: text
  }
}

//example
// {
// 	definition: 'The ultimate self promoter. He makes good beats but barely says anything in his songs.  He always wants you to listen, but does not have alot to say. Anywhere you see him, either on tv or on a truck or billboard he will be sayin- buy my album.  \r\n \r\n',
// 	permalink: 'http://dj-khaled.urbanup.com/2561463',
// 	thumbs_up: 970,
// 	author: 'Tdowns',
// 	word: 'DJ khaled',
// 	defid: 2561463,
// 	current_vote: '',
// 	example: 'Dj Khaled:  Lisssttennnn\r\nMe: im listening\r\nDj Khaled: We da best!',
// 	thumbs_down: 330
// }<|endoftext|>


<commit_before>'use strict';

const Command = require('../../models/Command.js');
const PrimeAccessEmbed = require('../../embeds/NewsEmbed.js');

/**
 * Displays the currently active warframe prime access news
 */
class PrimeAccess extends Command {
  /**
   * Constructs a callable command
   * @param {Genesis} bot  The bot object
   */
  constructor(bot) {
    super(bot, 'warframe.worldstate.primeaccess', 'primeaccess', 'Display the currently active prime access news');
    this.regex = new RegExp('^prime\\s?access(?:\\s+on\\s+([pcsxb14]{2,3}))?$', 'i');
  }

  async run(message) {
    const platformParam = message.strippedContent.match(this.regex)[1];
    const platform = platformParam || await this.settings.getChannelSetting(message.channel, 'platform');
    const ws = await this.bot.worldStates[platform.toLowerCase()].getData();
    const news = ws.news.filter(n => n.primeAccess);
    await this.messageManager.embed(message, new PrimeAccessEmbed(this.bot, news, 'primeaccess', platform), true, false);
    return this.messageManager.statuses.SUCCESS;
  }
}

module.exports = PrimeAccess;
<commit_msg>use context<commit_after>'use strict';

const Command = require('../../models/Command.js');
const PrimeAccessEmbed = require('../../embeds/NewsEmbed.js');

/**
 * Displays the currently active warframe prime access news
 */
class PrimeAccess extends Command {
  /**
   * Constructs a callable command
   * @param {Genesis} bot  The bot object
   */
  constructor(bot) {
    super(bot, 'warframe.worldstate.primeaccess', 'primeaccess', 'Display the currently active prime access news');
    this.regex = new RegExp('^prime\\s?access(?:\\s+on\\s+([pcsxb14]{2,3}))?$', 'i');
  }

  async run(message, ctx) {
    const platformParam = message.strippedContent.match(this.regex)[1];
    const platform = platformParam || ctx.platform;
    const ws = await this.bot.worldStates[platform.toLowerCase()].getData();
    const news = ws.news.filter(n => n.primeAccess);
    await this.messageManager.embed(message, new PrimeAccessEmbed(this.bot, news, 'primeaccess', platform), true, false);
    return this.messageManager.statuses.SUCCESS;
  }
}

module.exports = PrimeAccess;
<|endoftext|>


<commit_before>// our modules
import {api} from '../../utils';
import env from './assignConfig';
import setPrompt from './prompt';
import createRequestBody from './createRequestBody';
import checkAssigned from './checkAssigned';
import checkFeedbacks from './checkFeedbacks';

const checkPositions = async () => {
  const positions = await api({
    task: 'position',
    id: env.submission_request.id,
  });
  env.positions = positions.body;
};

const createNewSubmissionRequest = async () => {
  const submissionRequest = await api({
    task: 'create',
    body: createRequestBody(),
  });
  env.submission_request = submissionRequest.body;
  env.requestIds.push(env.submission_request.id);
  env.tick = 0;
};

const refreshSubmissionRequest = async () => {
  const submissionRequest = await api({
    task: 'refresh',
    id: env.submission_request.id,
  });
  env.submission_request = submissionRequest.body;
};

async function requestLoop() {
  if (env.update) {
    try {
      // We have to check for new assignments every time, to account for edge
      // cases where, for instance, a review is completed and a new one is
      // assigned, all between updates.
      await checkAssigned();
      // We only need to deal with the submission request and the queue if we
      // haven't got max number of submissions assigned.
      if (env.assigned.length < 2) {
        const res = await api({task: 'get'});
        const submissionRequest = res.body[0];
        // If a submission_request exists, we save it and check if it should be
        // refreshed.
        if (submissionRequest) {
          env.submission_request = submissionRequest;
          if (env.refresh && env.tick !== 0) {
            await refreshSubmissionRequest();
          }
        } else {
          await createNewSubmissionRequest();
        }
        if (env.updatePositions) {
          await checkPositions();
        }
      }
      // Check if the info needs to update
      if (env.updateFeedbacks && env.flags.feedbacks) {
        checkFeedbacks();
      }
      if (env.flags.ui) {
        setPrompt();
      }
    } catch (e) {
      env.error = e;
    }
  }
  // Set/reset to the default update intervals.
  env.update = env.tick % env.updateInterval === 0;
  env.refresh = env.tick % env.refreshInterval === 0;
  env.updatePositions = env.tick % env.updatePositionsInterval === 0;
  env.updateFeedbacks = env.tick % env.updateFeedbacksInterval === 0;
  env.tick += 1;
  setTimeout(async () => {
    await requestLoop();
  }, 1000);
}

export default requestLoop;
<commit_msg>Change max assigned submissions to 5<commit_after>// our modules
import {api} from '../../utils';
import env from './assignConfig';
import setPrompt from './prompt';
import createRequestBody from './createRequestBody';
import checkAssigned from './checkAssigned';
import checkFeedbacks from './checkFeedbacks';

const checkPositions = async () => {
  const positions = await api({
    task: 'position',
    id: env.submission_request.id,
  });
  env.positions = positions.body;
};

const createNewSubmissionRequest = async () => {
  const submissionRequest = await api({
    task: 'create',
    body: createRequestBody(),
  });
  env.submission_request = submissionRequest.body;
  env.requestIds.push(env.submission_request.id);
  env.tick = 0;
};

const refreshSubmissionRequest = async () => {
  const submissionRequest = await api({
    task: 'refresh',
    id: env.submission_request.id,
  });
  env.submission_request = submissionRequest.body;
};

async function requestLoop() {
  if (env.update) {
    try {
      // We have to check for new assignments every time, to account for edge
      // cases where, for instance, a review is completed and a new one is
      // assigned, all between updates.
      await checkAssigned();
      // We only need to deal with the submission request and the queue if we
      // haven't got max number of submissions assigned.
      if (env.assigned.length < 5) {
        const res = await api({task: 'get'});
        const submissionRequest = res.body[0];
        // If a submission_request exists, we save it and check if it should be
        // refreshed.
        if (submissionRequest) {
          env.submission_request = submissionRequest;
          if (env.refresh && env.tick !== 0) {
            await refreshSubmissionRequest();
          }
        } else {
          await createNewSubmissionRequest();
        }
        if (env.updatePositions) {
          await checkPositions();
        }
      }
      // Check if the info needs to update
      if (env.updateFeedbacks && env.flags.feedbacks) {
        checkFeedbacks();
      }
      if (env.flags.ui) {
        setPrompt();
      }
    } catch (e) {
      env.error = e;
    }
  }
  // Set/reset to the default update intervals.
  env.update = env.tick % env.updateInterval === 0;
  env.refresh = env.tick % env.refreshInterval === 0;
  env.updatePositions = env.tick % env.updatePositionsInterval === 0;
  env.updateFeedbacks = env.tick % env.updateFeedbacksInterval === 0;
  env.tick += 1;
  setTimeout(async () => {
    await requestLoop();
  }, 1000);
}

export default requestLoop;
<|endoftext|>


<commit_before>/**
 * The Geopoint Field class
 *
 * @constructor
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.2.0
 * @version  1.1.0
 */
var Geopoint = Function.inherits('Alchemy.Field', function Geopoint(schema, name, options) {
	Geopoint.super.call(this, schema, name, options);

	// Add the 2dsphere index
	this.schema.addIndex(this, {name: name + '_geopoint', order: '2dsphere'});
});

/**
 * Set the datatype name
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.2.0
 * @version  1.1.0
 */
Geopoint.setDatatype('object');

/**
 * This field value is self-contained
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    1.1.0
 * @version  1.1.0
 */
Geopoint.setSelfContained(true);

/**
 * Cast the given value to this field's type
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.2.0
 * @version  0.2.0
 *
 * @param    {Mixed}   value
 *
 * @return   {Date}
 */
Geopoint.setMethod(function cast(value) {

	var coordinates,
	    result;

	if (value == null) {
		return value;
	}

	if (Array.isArray(value)) {
		coordinates = value;
	} else if (Array.isArray(value.coordinates)) {
		coordinates = value.coordinates;
	}

	// Should be like {type: 'Point', coordinates: [51,3]}
	return {
		type: 'Point',
		coordinates: coordinates
	};
});<commit_msg>Add workaround so geopoint fields can be an array<commit_after>/**
 * The Geopoint Field class
 *
 * @constructor
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.2.0
 * @version  1.1.0
 */
var Geopoint = Function.inherits('Alchemy.Field', function Geopoint(schema, name, options) {

	Geopoint.super.call(this, schema, name, options);

	let index_options = {
		name  : name + '_geopoint',
		order : '2dsphere'
	};

	if (this.is_array) {
		index_options.db_property = 'point';
	}

	// Add the 2dsphere index
	this.schema.addIndex(this, index_options);
});

/**
 * Set the datatype name
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.2.0
 * @version  1.1.0
 */
Geopoint.setDatatype('object');

/**
 * This field value is self-contained
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    1.1.0
 * @version  1.1.0
 */
Geopoint.setSelfContained(true);

/**
 * Cast the given value to this field's type
 *
 * @author   Jelle De Loecker   <jelle@develry.be>
 * @since    0.2.0
 * @version  1.1.0
 *
 * @param    {Mixed}   value
 *
 * @return   {Date}
 */
Geopoint.setMethod(function cast(value, to_datasource) {

	var coordinates,
	    result;

	if (!value) {
		return null;
	}

	// Normalize array-value format fields
	if (value.point) {
		value = value.point;
	}

	if (Array.isArray(value)) {
		coordinates = value;
	} else if (Array.isArray(value.coordinates)) {
		coordinates = value.coordinates;
	}

	// Should be like {type: 'Point', coordinates: [51,3]}
	result = {
		type: 'Point',
		coordinates: coordinates
	};

	// Arrayable fields need to be wrapped, otherwise it thinks it's a legacy coordinate
	if (to_datasource && this.is_array) {
		result = {
			point: result
		};
	}

	return result;
});<|endoftext|>


<commit_before>jQuery.fn.buildSearchText = function () {
    "use strict";

    var
        searchBox = null
        ,searchTextBox = null
        ,listBox = null
        ,searchBox = null
        ,optionsBox = null

        ,inputText = null
        ,wrapper = null
        ,foundsList = null
        ,optText = null
        ,searchIndex = null
        ,prevSliceTextNoSearch = null
        ,sliceFound = null
        ,remainderSliceTextNoSearch = null
        ,newOpt = null
        ,spanSliceFound = null
        ,options = null
    ;

    $(this).each(function (i, select) {
        optionsBox = $(select).closest('.custom-select').find('.options-box');

        searchBox = $('

');
        searchBox.addClass('search-box');
        searchTextBox = $('<input></input>');
        searchTextBox.attr('type', 'text');
        searchBox.append(searchTextBox);

        optionsBox.prepend(searchBox);

        searchTextBox.on('keyup', function (e) {

            inputText = $(this);
            wrapper = inputText.closest('.custom-select');
            options = wrapper.find('ul.select li');

            optionsBox = inputText.closest('.options-box');

            // cria a lista das opções e a caixa de texto, dinamicamente, e apenas após a pesquisa. Caso ela já tenha sido criada, ela não é recriada, ela é apenas limpa.
            if(wrapper.find('ul.founds-list').length === 0) {
                foundsList = $('

').addClass('founds-list');
                optionsBox.append(foundsList);
                foundsList.insertAfter( wrapper.find('.search-box') );
            } else {
                foundsList = optionsBox.find('.founds-list');
                foundsList.empty();
            }

            if(inputText.val() !== '') {

                options.each(function (i, option) {

                    optText = option.textContent.trim();
                    searchIndex = optText.toLowerCase().search( inputText.val().toLowerCase() );
                    if(searchIndex > -1) {
                        foundsList.show();
                        options.parent().hide();

                        prevSliceTextNoSearch = optText.slice(0, searchIndex);

                        sliceFound = optText.slice(prevSliceTextNoSearch.length, prevSliceTextNoSearch.length + inputText.val().length);

                        remainderSliceTextNoSearch = optText.slice(prevSliceTextNoSearch.length + sliceFound.length, optText.length);

                        newOpt = $('

');
                        spanSliceFound = $('');

                        newOpt.append(prevSliceTextNoSearch);
                        newOpt.append(spanSliceFound);
                        spanSliceFound.addClass('slice-found');
                        spanSliceFound.text(sliceFound);
                        newOpt.append(remainderSliceTextNoSearch);
                        newOpt.attr( 'data-value', $(option).data('value') );

                        foundsList.prepend(newOpt);
                    }

                });

                // setActionToSelect();

            } else {
                options.parent().show();
                foundsList.hide();
            }
        });
    });

}

jQuery.fn.build = function (params) {

    var
        caption = null
        ,captionText = null
        ,listBox = null
        ,searchBox = null
        ,searchTextBox = null
        ,list = null
        ,select = null
        ,wrapper = null
    ;

    $(this).each(function (i, select) {
        select = $(select);
        select.hide();
        wrapper = $('

');
        wrapper.addClass('custom-select');
        select.parent().append(wrapper);
        wrapper.append(select);

        caption = $('

');
        captionText = $('

');
        listBox = $('

');

        list = $('

');

        caption.addClass('caption retracted');
        captionText.addClass('text');
        listBox.addClass('options-box');
        list.addClass('select');

        wrapper.append(caption);
        caption.append(captionText);
        wrapper.append(listBox);
        listBox.append(list);

        buildOpts(list);

        // toggle
        caption.on('click', function () {
            wrapper = $(this).closest('.custom-select');
            wrapper.find('.options-box').toggle();
            toggleCaptionClass( $(this) );
        });

        setActionToSelect(list);
    });

    return $(this);

}

var buildOpts = function (jqObj) {
    "use strict";

    var
        wrapper = jqObj.closest('.custom-select')
        ,select = wrapper.find('select')
        ,list = wrapper.find('ul.select')
        ,options = select.find('option')
        ,captionText = wrapper.find('.caption .text')
        ,option = null
        ,li = null
    ;

    options.each(function (i, tag) {
        option = $(tag);
        li = $('

');

        li.attr( 'data-value', option.attr('value') );
        li.text( option.text() );
        list.append(li);

        if( option.attr('selected') ) {
            captionText.text( option.text() );
        }
    });

}

var toggleCaptionClass = function (jqObj) {
    "use strict";
    jqObj.toggleClass('expanded', 'retracted');
}

// click out
$(document).click(function (e) {

    var
        wrapper = $('.custom-select')
        ,optionsBoxes = wrapper.find('.options-box')
        captions = wrapper.find('.caption');
    ;

    if( $(e.target).closest('.custom-select').length === 0 ) {

        if( optionsBoxes.is(':visible') ) {
            optionsBoxes.hide();
            captions.removeClass('expanded');
        }

    }

});

//select onclick
var setActionToSelect = function (jqObj) {
    "use strict";

    jqObj.find('li').on('click', function () {
        var
            wrapper = jqObj.closest('.custom-select')
            ,caption = wrapper.find('.caption')
            ,value = $(this).data('value')
            ,select = wrapper.find('select')
            ,captionText = wrapper.find('.caption .text')
            ,selected = null
        ;

        // remove selection
        select.find('option:selected').attr('selected', false);

        // select
        selected = select.find('option[value="' + value + '"]');
        selected.attr('selected', true);

        captionText.text( selected.text() );

        // esconde opções
        wrapper.find('.options-box').hide();

        toggleCaptionClass(caption);
    });
}
;<commit_msg>seta ação em action click na lista de encontrados<commit_after>jQuery.fn.buildSearchText = function () {
    "use strict";

    var
        searchBox = null
        ,searchTextBox = null
        ,listBox = null
        ,searchBox = null
        ,optionsBox = null

        ,inputText = null
        ,wrapper = null
        ,foundsList = null
        ,optText = null
        ,searchIndex = null
        ,prevSliceTextNoSearch = null
        ,sliceFound = null
        ,remainderSliceTextNoSearch = null
        ,newOpt = null
        ,spanSliceFound = null
        ,options = null
    ;

    $(this).each(function (i, select) {
        optionsBox = $(select).closest('.custom-select').find('.options-box');

        searchBox = $('

');
        searchBox.addClass('search-box');
        searchTextBox = $('<input></input>');
        searchTextBox.attr('type', 'text');
        searchBox.append(searchTextBox);

        optionsBox.prepend(searchBox);

        searchTextBox.on('keyup', function (e) {

            inputText = $(this);
            wrapper = inputText.closest('.custom-select');
            options = wrapper.find('ul.select li');

            optionsBox = inputText.closest('.options-box');

            // cria a lista das opções e a caixa de texto, dinamicamente, e apenas após a pesquisa. Caso ela já tenha sido criada, ela não é recriada, ela é apenas limpa.
            if(wrapper.find('ul.founds-list').length === 0) {
                foundsList = $('

').addClass('founds-list');
                optionsBox.append(foundsList);
                foundsList.insertAfter( wrapper.find('.search-box') );
            } else {
                foundsList = optionsBox.find('.founds-list');
                foundsList.empty();
            }

            if(inputText.val() !== '') {

                options.each(function (i, option) {

                    optText = option.textContent.trim();
                    searchIndex = optText.toLowerCase().search( inputText.val().toLowerCase() );
                    if(searchIndex > -1) {
                        foundsList.show();
                        options.parent().hide();

                        prevSliceTextNoSearch = optText.slice(0, searchIndex);

                        sliceFound = optText.slice(prevSliceTextNoSearch.length, prevSliceTextNoSearch.length + inputText.val().length);

                        remainderSliceTextNoSearch = optText.slice(prevSliceTextNoSearch.length + sliceFound.length, optText.length);

                        newOpt = $('

');
                        spanSliceFound = $('');

                        newOpt.append(prevSliceTextNoSearch);
                        newOpt.append(spanSliceFound);
                        spanSliceFound.addClass('slice-found');
                        spanSliceFound.text(sliceFound);
                        newOpt.append(remainderSliceTextNoSearch);
                        newOpt.attr( 'data-value', $(option).data('value') );

                        foundsList.prepend(newOpt);
                    }

                });

                setActionToSelect(foundsList);

            } else {
                options.parent().show();
                foundsList.hide();
            }
        });
    });

}

jQuery.fn.build = function (params) {

    var
        caption = null
        ,captionText = null
        ,listBox = null
        ,searchBox = null
        ,searchTextBox = null
        ,list = null
        ,select = null
        ,wrapper = null
    ;

    $(this).each(function (i, select) {
        select = $(select);
        select.hide();
        wrapper = $('

');
        wrapper.addClass('custom-select');
        select.parent().append(wrapper);
        wrapper.append(select);

        caption = $('

');
        captionText = $('

');
        listBox = $('

');

        list = $('

');

        caption.addClass('caption retracted');
        captionText.addClass('text');
        listBox.addClass('options-box');
        list.addClass('select');

        wrapper.append(caption);
        caption.append(captionText);
        wrapper.append(listBox);
        listBox.append(list);

        buildOpts(list);

        // toggle
        caption.on('click', function () {
            wrapper = $(this).closest('.custom-select');
            wrapper.find('.options-box').toggle();
            toggleCaptionClass( $(this) );
        });

        setActionToSelect(list);
    });

    return $(this);

}

var buildOpts = function (jqObj) {
    "use strict";

    var
        wrapper = jqObj.closest('.custom-select')
        ,select = wrapper.find('select')
        ,list = wrapper.find('ul.select')
        ,options = select.find('option')
        ,captionText = wrapper.find('.caption .text')
        ,option = null
        ,li = null
    ;

    options.each(function (i, tag) {
        option = $(tag);
        li = $('

');

        li.attr( 'data-value', option.attr('value') );
        li.text( option.text() );
        list.append(li);

        if( option.attr('selected') ) {
            captionText.text( option.text() );
        }
    });

}

var toggleCaptionClass = function (jqObj) {
    "use strict";
    jqObj.toggleClass('expanded', 'retracted');
}

// click out
$(document).click(function (e) {

    var
        wrapper = $('.custom-select')
        ,optionsBoxes = wrapper.find('.options-box')
        captions = wrapper.find('.caption');
    ;

    if( $(e.target).closest('.custom-select').length === 0 ) {

        if( optionsBoxes.is(':visible') ) {
            optionsBoxes.hide();
            captions.removeClass('expanded');
        }

    }

});

//select onclick
var setActionToSelect = function (jqObj) {
    "use strict";

    jqObj.find('li').on('click', function () {
        var
            wrapper = jqObj.closest('.custom-select')
            ,caption = wrapper.find('.caption')
            ,value = $(this).data('value')
            ,select = wrapper.find('select')
            ,captionText = wrapper.find('.caption .text')
            ,selected = null
        ;

        // remove selection
        select.find('option:selected').attr('selected', false);

        // select
        selected = select.find('option[value="' + value + '"]');
        selected.attr('selected', true);

        captionText.text( selected.text() );

        // esconde opções
        wrapper.find('.options-box').hide();

        toggleCaptionClass(caption);
    });
}
;<|endoftext|>


<commit_before>Divvy.Preview = {};

Divvy.Preview.init = function ()
{
	this.win = Ti.UI.createWindow({
		barColor: Divvy.winBarColor,
		backButtonTitle: 'Thumbnails',
		orientationModes: [
			Titanium.UI.PORTRAIT,
    		Titanium.UI.LANDSCAPE_LEFT,
    		Titanium.UI.LANDSCAPE_RIGHT,
		]
	});

	this.win.addEventListener('close', function(e) {
		Divvy.Preview.close();
	});
/*
	this.toolbar = Ti.UI.createToolbar({

	});

	this.win.add(this.toolbar);
*/
	this.photo = Ti.UI.createImageView();

	this.win.add(this.photo);

	this.activityIndicator = Ti.UI.createActivityIndicator();
	this.activityIndicator.show();
};

Divvy.Preview.open = function (currentNum, totalNum, imageId)
{
	this.win.title = currentNum + ' of ' + totalNum;

	this.win.add(this.activityIndicator);

	Network.cache.run(
		Divvy.url + 'image/'+imageId,
		Network.CACHE_INVALIDATE, //1 week
		Divvy.Preview.onImageUrlSuccess,
		Divvy.Preview.onImageUrlError,
		Divvy.Preview.photo
	);

	Divvy.open(this.win);
};

Divvy.Preview.close = function()
{
	this.photo.image = null;
};

Divvy.Preview.onImageUrlSuccess = function(data, date, status, user, xhr)
{
	try
	{
		data = JSON.parse(data);
	}
	catch (excp)
	{
		Divvy.Preview.onImageUrlError(Network.PARSE_ERROR, 0);
		return;
	}

	if (data.status == 'error')
	{
		Divvy.Preview.onImageUrlError(data.error, 0);
		return;
	}

	Network.cache.run(
		data.url,
		168, //1 week
		Divvy.Preview.onImageSuccess,
		Divvy.Preview.onImageError,
		user
	);
};

Divvy.Preview.onImageUrlError = function(status, httpStatus)
{
	// do nothing
	Divvy.Preview.win.remove(Divvy.Preview.activityIndicator);
};

Divvy.Preview.onImageSuccess = function(data, date, status, user, xhr)
{
	user.image = data;
	Divvy.Preview.win.remove(Divvy.Preview.activityIndicator);
};

Divvy.Preview.onImageError = function(status, httpStatus)
{
	//do nothing
	Divvy.Preview.win.remove(Divvy.Preview.activityIndicator);
};
<commit_msg>Some testings to preview.<commit_after>Divvy.Preview = {};

Divvy.Preview.init = function ()
{
	this.win = Ti.UI.createWindow({
		barColor: Divvy.winBarColor,
		backButtonTitle: 'Thumbnails',
		orientationModes: [
			Titanium.UI.PORTRAIT,
    		Titanium.UI.LANDSCAPE_LEFT,
    		Titanium.UI.LANDSCAPE_RIGHT,
		],
		translucent: false
	});

	this.win.addEventListener('close', function(e) {
		Divvy.Preview.close();
	});
/*
	this.scrollView = Ti.UI.createScrollView({
		width: 320,
		height: 480,
		maxZoomScale: 2.0,
		isFullScreen: false
	});

/*
	this.scrollView.addEventListener('singletap', function(e) {
		if (Divvy.Preview.scrollView.isFullScreen) {
//			Ti.UI.iPhone.showStatusBar();
//			Divvy.Preview.win.showNavBar();
		} else {
//			Ti.UI.iPhone.hideStatusBar();
//			Divvy.Preview.win.hideNavBar();
		}

		Divvy.Preview.scrollView.isFullScreen = !Divvy.Preview.scrollView.isFullScreen;
	});

	this.scrollView.addEventListener('doubletap', function(e) {
    	Divvy.Preview.scrollView.zoomScale = 2.0;
	});
/*
	this.toolbar = Ti.UI.createToolbar({

	});

	this.win.add(this.toolbar);
*/
	this.photo = Ti.UI.createImageView({
		backgroundColor: '#000',
		top: 0,
	});

	this.win.add(this.photo);

	this.activityIndicator = Ti.UI.createActivityIndicator();
	this.activityIndicator.show();
};

Divvy.Preview.open = function (currentNum, totalNum, imageId)
{
	this.win.title = currentNum + ' of ' + totalNum;

	this.win.add(this.activityIndicator);

	Network.cache.run(
		Divvy.url + 'image/'+imageId,
		Network.CACHE_INVALIDATE, //1 week
		Divvy.Preview.onImageUrlSuccess,
		Divvy.Preview.onImageUrlError,
		Divvy.Preview.photo
	);

	Divvy.open(this.win);
};

Divvy.Preview.close = function()
{
	this.photo.image = null;
};

Divvy.Preview.onImageUrlSuccess = function(data, date, status, user, xhr)
{
	try
	{
		data = JSON.parse(data);
	}
	catch (excp)
	{
		Divvy.Preview.onImageUrlError(Network.PARSE_ERROR, 0);
		return;
	}

	if (data.status == 'error')
	{
		Divvy.Preview.onImageUrlError(data.error, 0);
		return;
	}

	Network.cache.run(
		data.url,
		168, //1 week
		Divvy.Preview.onImageSuccess,
		Divvy.Preview.onImageError,
		user
	);
};

Divvy.Preview.onImageUrlError = function(status, httpStatus)
{
	// do nothing
	Divvy.Preview.win.remove(Divvy.Preview.activityIndicator);
};

Divvy.Preview.onImageSuccess = function(data, date, status, user, xhr)
{
	user.image = data;
	Divvy.Preview.win.remove(Divvy.Preview.activityIndicator);
};

Divvy.Preview.onImageError = function(status, httpStatus)
{
	//do nothing
	Divvy.Preview.win.remove(Divvy.Preview.activityIndicator);
};
<|endoftext|>


<commit_before>(function (window) {
	'use strict';

	var HearingTest = Object.create(null);

	HearingTest.init = function init() {
		var context = new window.AudioContext();

		this.sound = this.createSound(context);
		this.sound.connect(context.destination);

		return this;
	}

	HearingTest.createSound = function createSound(context) {
		return context.createOscillator();
	};

	HearingTest.startSound = function startSound(delay) {
		delay = delay || 0;
		this.sound.start(delay);
	};

	HearingTest.stopSound = function stopSound(delay) {
		delay = delay || 0;
		this.sound.stop(delay);
	};

	window.HearingTest = HearingTest;
	return HearingTest;
}(window));
<commit_msg>Removed context.createOscilator().connect(context.destination) in init()<commit_after>(function (window) {
	'use strict';

	var HearingTest = Object.create(null);

	HearingTest.init = function init() {
		this.context = new window.AudioContext();
		this.sound = this.createSound(this.context);

		return this;
	}

	HearingTest.createSound = function createSound(context) {
		return context.createOscillator();
	};

	HearingTest.startSound = function startSound(delay) {
		delay = delay || 0;
		this.sound.start(delay);
	};

	HearingTest.stopSound = function stopSound(delay) {
		delay = delay || 0;
		this.sound.stop(delay);
	};

	window.HearingTest = HearingTest;
	return HearingTest;
}(window));
<|endoftext|>


<commit_before>var ioc = require("../container"),
  WinJS = require('winjs'),
  config = require('../configuration');

exports.pageDefine = function(viewKey, templateUri, baseClassDef) {
  var existingBaseClass = WinJS.UI.Pages.define(templateUri);
  if (baseClassDef && existingBaseClass != baseClassDef) {
    var extendedClassDef = WinJS.UI.Pages.define(templateUri, {}, baseClassDef);
    ioc.overrideView(viewKey, extendedClassDef);

    // Add the config entry for the navigation service pre-nav validation
    config.set("pages:" + viewKey + ":template", templateUri);

    return extendedClassDef;
  }
  return existingBaseClass;
};

exports.markForProcessing = function(subject) {
  var _self = this;
  for (var _property in subject)
    if (subject.hasOwnProperty(_property)) {
      if (typeof subject[_property] == "object" && _property[0] != "_") {
        exports.markForProcessing(subject[_property]);
      } else
      if (subject[_property] instanceof Function && !subject[_property]["supportedForProcessing"]) {
        WinJS.Utilities.markSupportedForProcessing(subject[_property]);
      }
    }
};
<commit_msg>Removed unused code<commit_after>var ioc = require("../container"),
  WinJS = require('winjs'),
  config = require('../configuration');

exports.markForProcessing = function(subject) {
  var _self = this;
  for (var _property in subject)
    if (subject.hasOwnProperty(_property)) {
      if (typeof subject[_property] == "object" && _property[0] != "_") {
        exports.markForProcessing(subject[_property]);
      } else
      if (subject[_property] instanceof Function && !subject[_property]["supportedForProcessing"]) {
        WinJS.Utilities.markSupportedForProcessing(subject[_property]);
      }
    }
};
<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */
import File from './File';

export default class Package extends File {
  get mergedContent() {
    return Promise.all([this.originalContent(), this.templateContent()]).then(contents => {
      const target = JSON.parse(contents[0]);
      const template = JSON.parse(contents[1]);

      const properties = this.context.properties;

      if (target.module && !target.module.match(/\{\{module\}\}/)) {
        properties.module = target.module;
      }

      properties.main = target.main && !target.main.match(/\{\{main\}\}/) ? target.main : 'dist/index.js';

      const deepPropeties = ['scripts', 'devDependencies', 'engines'];

      let extraBuild, buildOutput, specialTest;

      if (target.scripts) {
        if (target.scripts.test) {
          if (target.scripts.test.match(/rollup/)) {
            // TODO how to detect special rollup test config ?
            specialTest = target.scripts.test;
          }
        }

        if (target.scripts.build) {
          let m = target.scripts.build.match(/--output=([^\s]+)/);
          if (m) {
            buildOutput = m[1];
          }

          m = target.scripts.build.match(/\&\&\s*(.+)/);
          if (m) {
            extraBuild = m[1];
          }
        }
      }

      deepPropeties.forEach(p => {
        if (target[p] === undefined) {
          target[p] = {};
        }
        Object.assign(target[p], template[p]);
      });

      Object.keys(target.devDependencies).forEach(d => {
        console.log(`${d} ${target.devDependencies[d]} ${template.devDependencies[d]}`);
        if (template.devDependencies[d] === '-') {
          delete ds[d];
        }
      });

      Object.keys(template).forEach(p => {
        if (p !== 'template') {
          if (target[p] === undefined) {
            target[p] = template[p];
          }
        }
      });

      if (buildOutput !== undefined) {
        target.scripts.build = target.scripts.build.replace(/--output=([^\s]+)/, `--output=${buildOutput}`);
      }

      if (specialTest !== undefined) {
        target.scripts.test = specialTest;
      }

      if (extraBuild !== undefined) {
        target.scripts.build += ` && ${extraBuild}`;
      }

      if (target.module === '{{module}}') {
        delete target.module;
      }

      if (target.contributors !== undefined && target.author !== undefined) {
        const m = target.author.match(/(^[^<]+)<([^>]+)>/);
        if (m !== undefined) {
          const name = String(m[1]).replace(/^\s+|\s+$/g, '');
          const email = m[2];

          if (target.contributors.find(c => c.name === name && c.email === email)) {
            delete target.author;
          }
        }
      }

      if (template.template && template.template.keywords) {
        Object.keys(template.template.keywords).forEach(r =>
          addKeyword(target, new RegExp(r), template.template.keywords[r])
        );
      }

      const rcj = this.context.files.get('rollup.config.js');

      let first;
      if (rcj) {
        first = rcj.mergedContent.then(c => {
          if (c) {
            if (!c.match(/rollup-plugin-node-resolve/)) {
              delete target.devDependencies['rollup-plugin-node-resolve'];
            }
            if (!c.match(/rollup-plugin-commonjs/)) {
              delete target.devDependencies['rollup-plugin-commonjs'];
            }
          }
        });
      } else {
        first = Promise.resolve();
      }

      return first.then(() => JSON.stringify(this.context.expand(target), undefined, 2));
    });
  }
}

function addKeyword(pkg, regex, keyword) {
  if (pkg.name.match(regex)) {
    if (!pkg.keywords.find(k => k === keyword)) {
      pkg.keywords.push(keyword);
    }
  }
}
<commit_msg>fix: remove dev-dependencies if version = '-' in template<commit_after>/* jslint node: true, esnext: true */
import File from './File';

export default class Package extends File {
  get mergedContent() {
    return Promise.all([this.originalContent(), this.templateContent()]).then(contents => {
      const target = JSON.parse(contents[0]);
      const template = JSON.parse(contents[1]);

      const properties = this.context.properties;

      if (target.module && !target.module.match(/\{\{module\}\}/)) {
        properties.module = target.module;
      }

      properties.main = target.main && !target.main.match(/\{\{main\}\}/) ? target.main : 'dist/index.js';

      const deepPropeties = ['scripts', 'devDependencies', 'engines'];

      let extraBuild, buildOutput, specialTest;

      if (target.scripts) {
        if (target.scripts.test) {
          if (target.scripts.test.match(/rollup/)) {
            // TODO how to detect special rollup test config ?
            specialTest = target.scripts.test;
          }
        }

        if (target.scripts.build) {
          let m = target.scripts.build.match(/--output=([^\s]+)/);
          if (m) {
            buildOutput = m[1];
          }

          m = target.scripts.build.match(/\&\&\s*(.+)/);
          if (m) {
            extraBuild = m[1];
          }
        }
      }

      deepPropeties.forEach(p => {
        if (target[p] === undefined) {
          target[p] = {};
        }
        Object.assign(target[p], template[p]);
      });

      Object.keys(target.devDependencies).forEach(d => {
        if (template.devDependencies[d] === '-') {
          delete target.devDependencies[d];
        }
      });

      Object.keys(template).forEach(p => {
        if (p !== 'template') {
          if (target[p] === undefined) {
            target[p] = template[p];
          }
        }
      });

      if (buildOutput !== undefined) {
        target.scripts.build = target.scripts.build.replace(/--output=([^\s]+)/, `--output=${buildOutput}`);
      }

      if (specialTest !== undefined) {
        target.scripts.test = specialTest;
      }

      if (extraBuild !== undefined) {
        target.scripts.build += ` && ${extraBuild}`;
      }

      if (target.module === '{{module}}') {
        delete target.module;
      }

      if (target.contributors !== undefined && target.author !== undefined) {
        const m = target.author.match(/(^[^<]+)<([^>]+)>/);
        if (m !== undefined) {
          const name = String(m[1]).replace(/^\s+|\s+$/g, '');
          const email = m[2];

          if (target.contributors.find(c => c.name === name && c.email === email)) {
            delete target.author;
          }
        }
      }

      if (template.template && template.template.keywords) {
        Object.keys(template.template.keywords).forEach(r =>
          addKeyword(target, new RegExp(r), template.template.keywords[r])
        );
      }

      const rcj = this.context.files.get('rollup.config.js');

      let first;
      if (rcj) {
        first = rcj.mergedContent.then(c => {
          if (c) {
            if (!c.match(/rollup-plugin-node-resolve/)) {
              delete target.devDependencies['rollup-plugin-node-resolve'];
            }
            if (!c.match(/rollup-plugin-commonjs/)) {
              delete target.devDependencies['rollup-plugin-commonjs'];
            }
          }
        });
      } else {
        first = Promise.resolve();
      }

      return first.then(() => JSON.stringify(this.context.expand(target), undefined, 2));
    });
  }
}

function addKeyword(pkg, regex, keyword) {
  if (pkg.name.match(regex)) {
    if (!pkg.keywords.find(k => k === keyword)) {
      pkg.keywords.push(keyword);
    }
  }
}
<|endoftext|>


<commit_before>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
//
// ## Description
//
// This class implements various types of modifiers to notes (e.g. bends,
// fingering positions etc.)

import { Vex } from './vex';
import { StaveNote } from './stavenote';
import { Dot } from './dot';
import { FretHandFinger } from './frethandfinger';
import { Accidental } from './accidental';
import { GraceNoteGroup } from './gracenotegroup';
import { Stroke } from './strokes';
import { StringNumber } from './stringnumber';
import { Articulation } from './articulation';
import { Ornament } from './ornament';
import { Annotation } from './annotation';
import { Bend } from './bend';
import { Vibrato } from './vibrato';

// To enable logging for this class. Set `Vex.Flow.ModifierContext.DEBUG` to `true`.
function L() { if (ModifierContext.DEBUG) Vex.L("Vex.Flow.ModifierContext", arguments); }

export class ModifierContext {
  constructor() {
    // Current modifiers
    this.modifiers = {};

    // Formatting data.
    this.preFormatted = false;
    this.postFormatted = false;
    this.width = 0;
    this.spacing = 0;
    this.state = {
      left_shift: 0,
      right_shift: 0,
      text_line: 0,
      top_text_line: 0
    };

    // Add new modifiers to this array. The ordering is significant -- lower
    // modifiers are formatted and rendered before higher ones.
    this.PREFORMAT = [
      StaveNote,
      Dot,
      FretHandFinger,
      Accidental,
      GraceNoteGroup,
      Stroke,
      StringNumber,
      Articulation,
      Ornament,
      Annotation,
      Bend,
      Vibrato
    ];

    // If post-formatting is required for an element, add it to this array.
    this.POSTFORMAT = [ StaveNote ];
  }

  addModifier(modifier) {
    var type = modifier.getCategory();
    if (!this.modifiers[type]) this.modifiers[type] = [];
    this.modifiers[type].push(modifier);
    modifier.setModifierContext(this);
    this.preFormatted = false;
    return this;
  }

  getModifiers(type) { return this.modifiers[type]; }
  getWidth() { return this.width; }
  getExtraLeftPx() { return this.state.left_shift; }
  getExtraRightPx() { return this.state.right_shift; }
  getState() { return this.state; }

  getMetrics() {
    if (!this.formatted) throw new Vex.RERR("UnformattedModifier",
        "Unformatted modifier has no metrics.");

    return {
      width: this.state.left_shift + this.state.right_shift + this.spacing,
      spacing: this.spacing,
      extra_left_px: this.state.left_shift,
      extra_right_px: this.state.right_shift
    };
  }

  preFormat() {
    if (this.preFormatted) return;
    this.PREFORMAT.forEach(function(modifier) {
      L("Preformatting ModifierContext: ", modifier.CATEGORY);
      modifier.format(this.getModifiers(modifier.CATEGORY), this.state, this);
    }, this);

    // Update width of this modifier context
    this.width = this.state.left_shift + this.state.right_shift;
    this.preFormatted = true;
  }

  postFormat() {
    if (this.postFormatted) return;
    this.POSTFORMAT.forEach(function(modifier) {
      L("Postformatting ModifierContext: ", modifier.CATEGORY);
      modifier.postFormat(this.getModifiers(modifier.CATEGORY), this);
    }, this);
  }
}
<commit_msg>User arrow functions and const in modifiercontext.js<commit_after>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
//
// ## Description
//
// This class implements various types of modifiers to notes (e.g. bends,
// fingering positions etc.)

import { Vex } from './vex';
import { StaveNote } from './stavenote';
import { Dot } from './dot';
import { FretHandFinger } from './frethandfinger';
import { Accidental } from './accidental';
import { GraceNoteGroup } from './gracenotegroup';
import { Stroke } from './strokes';
import { StringNumber } from './stringnumber';
import { Articulation } from './articulation';
import { Ornament } from './ornament';
import { Annotation } from './annotation';
import { Bend } from './bend';
import { Vibrato } from './vibrato';

// To enable logging for this class. Set `Vex.Flow.ModifierContext.DEBUG` to `true`.
function L() { if (ModifierContext.DEBUG) Vex.L("Vex.Flow.ModifierContext", arguments); }

export class ModifierContext {
  constructor() {
    // Current modifiers
    this.modifiers = {};

    // Formatting data.
    this.preFormatted = false;
    this.postFormatted = false;
    this.width = 0;
    this.spacing = 0;
    this.state = {
      left_shift: 0,
      right_shift: 0,
      text_line: 0,
      top_text_line: 0
    };

    // Add new modifiers to this array. The ordering is significant -- lower
    // modifiers are formatted and rendered before higher ones.
    this.PREFORMAT = [
      StaveNote,
      Dot,
      FretHandFinger,
      Accidental,
      GraceNoteGroup,
      Stroke,
      StringNumber,
      Articulation,
      Ornament,
      Annotation,
      Bend,
      Vibrato
    ];

    // If post-formatting is required for an element, add it to this array.
    this.POSTFORMAT = [ StaveNote ];
  }

  addModifier(modifier) {
    const type = modifier.getCategory();
    if (!this.modifiers[type]) this.modifiers[type] = [];
    this.modifiers[type].push(modifier);
    modifier.setModifierContext(this);
    this.preFormatted = false;
    return this;
  }

  getModifiers(type) { return this.modifiers[type]; }
  getWidth() { return this.width; }
  getExtraLeftPx() { return this.state.left_shift; }
  getExtraRightPx() { return this.state.right_shift; }
  getState() { return this.state; }

  getMetrics() {
    if (!this.formatted) throw new Vex.RERR("UnformattedModifier",
        "Unformatted modifier has no metrics.");

    return {
      width: this.state.left_shift + this.state.right_shift + this.spacing,
      spacing: this.spacing,
      extra_left_px: this.state.left_shift,
      extra_right_px: this.state.right_shift
    };
  }

  preFormat() {
    if (this.preFormatted) return;
    this.PREFORMAT.forEach((modifier) => {
      L("Preformatting ModifierContext: ", modifier.CATEGORY);
      modifier.format(this.getModifiers(modifier.CATEGORY), this.state, this);
    });

    // Update width of this modifier context
    this.width = this.state.left_shift + this.state.right_shift;
    this.preFormatted = true;
  }

  postFormat() {
    if (this.postFormatted) return;
    this.POSTFORMAT.forEach((modifier) => {
      L("Postformatting ModifierContext: ", modifier.CATEGORY);
      modifier.postFormat(this.getModifiers(modifier.CATEGORY), this);
    });
  }
}
<|endoftext|>