<commit_before>if (typeof (require) != 'undefined') {
	var loader = require('./loader.js').loader;
}

/**
 * Module to deal with physics calculations and collisions
 */
loader.addModule('Physics',
function () {
	var physics = {};

	/**
	 * Method to know if a sphere collides with a rectangle
	 */
	physics.sphereCollidesWithRectangle = function (sphere, rectangle) {
		return sphere.y + BALL_RADIUS > rectangle.y &&
			sphere.y - BALL_RADIUS < rectangle.y + rectangle.h &&
			sphere.x  + BALL_RADIUS > rectangle.x &&
			sphere.x - BALL_RADIUS < rectangle.x + rectangle.w;
	};

	/**
	 * site and topbot are used in case of a diagonal hit, to know where
	 * the sphere has to bounce:
	 *
	 * +---++---+
	 * | S  | R |
	 * +---++---+
	 *      +---+
	 *   O  | T |
	 *      +---+
	 *
	 * where O = sphere, R = hit rectangle, S = Side (side rectangle of
	 * the hit one) and T = topbot (top or bottom rectangle of the hit
	 * one)
	 * Side is the rectangle at the previous position X of the mouse and
	 * its current Y
	 * TopBot is the rectangle at the previous position Y of the mouse and
	 * its current X
	 *
	 * if the sphere hit a rectangle next to it, TopBot === rectangle
	 * if the sphere hit a rectangle above or bellow to it, Side === rectangle
	 * if the sphere hit a rectangle in a diagonal, The 3 will be different
	 */
	physics.sphereBounceAgainstGridRectangle = function (sphere, rectangle, rectangleSide, rectangleTopBot) {
		// hit the rectangle from top or bottom
		// hit from the side
		if (rectangle != rectangleSide && rectangle == rectangleTopBot) {
			sphere.speedX *= -1;
		}
		// hit from above or below
		else if (rectangle == rectangleSide && rectangle != rectangleTopBot) {
			sphere.speedY *= -1;
		}
		// hit on a corner
		else if (rectangle != rectangleSide && rectangle != rectangleTopBot) {
			if (!(rectangleSide && rectangleSide.state === BRICK_STATE_ACTIVE && rectangleTopBot && rectangleTopBot.state === BRICK_STATE_INACTIVE)) {
				sphere.speedX *= -1;
			}
			if (!(rectangleSide && rectangleSide.state === BRICK_STATE_INACTIVE && rectangleTopBot && rectangleTopBot.state === BRICK_STATE_ACTIVE)) {
				sphere.speedY *= -1;
			}
		}
	};

	/**
	 * Make a moving sphere bouncing against a rectangle
	 *
	 * @TODO this might be too game-related
	 */
	physics.sphereBounceAgainstRectangle = function (sphere, rectangle) {
		// to change with actual physics
		sphere.speedY *= -1;

		var centerPaddleX = rectangle.x + rectangle.w / 2,
			distFromPaddleCenter = sphere.x - centerPaddleX;

		sphere.speedX = distFromPaddleCenter * 0.35;
	};

	return physics;
});

<commit_msg>tests fixed<commit_after>if (typeof (require) != 'undefined') {
	var loader = require('./loader.js').loader;
}

/**
 * Module to deal with physics calculations and collisions
 */
loader.addModule('Physics',
function () {
	var physics = {};

	/**
	 * Method to know if a sphere collides with a rectangle
	 */
	physics.sphereCollidesWithRectangle = function (sphere, rectangle) {
		return sphere.y + BALL_RADIUS > rectangle.y &&
			sphere.y - BALL_RADIUS < rectangle.y + rectangle.h &&
			sphere.x  + BALL_RADIUS > rectangle.x &&
			sphere.x - BALL_RADIUS < rectangle.x + rectangle.w;
	};

	/**
	 * site and topbot are used in case of a diagonal hit, to know where
	 * the sphere has to bounce:
	 *
	 * +---++---+
	 * | S  | R |
	 * +---++---+
	 *      +---+
	 *   O  | T |
	 *      +---+
	 *
	 * where O = sphere, R = hit rectangle, S = Side (side rectangle of
	 * the hit one) and T = topbot (top or bottom rectangle of the hit
	 * one)
	 * Side is the rectangle at the previous position X of the mouse and
	 * its current Y
	 * TopBot is the rectangle at the previous position Y of the mouse and
	 * its current X
	 *
	 * if the sphere hit a rectangle next to it, TopBot === rectangle
	 * if the sphere hit a rectangle above or bellow to it, Side === rectangle
	 * if the sphere hit a rectangle in a diagonal, The 3 will be different
	 */
	physics.sphereBounceAgainstGridRectangle = function (sphere, rectangle, rectangleSide, rectangleTopBot) {
		// hit the rectangle from top or bottom
		// hit from the side
		if (rectangle != rectangleSide && rectangle == rectangleTopBot) {
			sphere.speedX *= -1;
		}
		// hit from above or below
		else if (rectangle == rectangleSide && rectangle != rectangleTopBot) {
			sphere.speedY *= -1;
		}
		// hit on a corner
		else if (rectangle != rectangleSide && rectangle != rectangleTopBot) {
			var rectangleSideIsActive = rectangleSide !== undefined && rectangleSide.state === BRICK_STATE_ACTIVE,
				rectangleSideIsInactive = rectangleSide === undefined || rectangleSide.state === BRICK_STATE_INACTIVE,
				rectangleTopBotIsActive = rectangleTopBot !== undefined && rectangleTopBot.state === BRICK_STATE_ACTIVE,
				rectangleTopBotIsInactive = rectangleTopBot === undefined || rectangleTopBot.state === BRICK_STATE_INACTIVE;

			if (!(rectangleSideIsActive && rectangleTopBotIsInactive)) {
				sphere.speedX *= -1;
			}
			if (!(rectangleSideIsInactive && rectangleTopBotIsActive)) {
				sphere.speedY *= -1;
			}
		}
	};

	/**
	 * Make a moving sphere bouncing against a rectangle
	 *
	 * @TODO this might be too game-related
	 */
	physics.sphereBounceAgainstRectangle = function (sphere, rectangle) {
		// to change with actual physics
		sphere.speedY *= -1;

		var centerPaddleX = rectangle.x + rectangle.w / 2,
			distFromPaddleCenter = sphere.x - centerPaddleX;

		sphere.speedX = distFromPaddleCenter * 0.35;
	};

	return physics;
});

<|endoftext|>


<commit_before>var Sidebar = function(markers) {
    this.scrollCounter = 0;
    this.sidebar = null;

    this.markers = markers;
};

Sidebar.prototype.initialize = function(map) {
    this.sidebar = L.control.sidebar('sidebar', {position: 'right'}).addTo(map);
};

Sidebar.prototype.open = function() {
    this.sidebar.open('hopsPane');
};

Sidebar.prototype.tableTemplate = function(data) {
    return '
' + template.hopTemplate(data) + '
';
};

Sidebar.prototype.appendTable = function(data) {
    $('#hopsTable').append(this.tableTemplate(data));
    $('.sidebar-content').animate({scrollTop: this.scrollCounter += 500}, 1000);

    var markers = this.markers;

    var hopsTableRow = $('#hopsTable tr');
    hopsTableRow.unbind('click');
    hopsTableRow.click(function() {
        var html = $(this).html();
        var index = markers.findIndex(function(value) {
            return html.includes(value._popup._content);
        });

        if (index) {
            markers[index].openPopup();
        }
    });
};

Sidebar.prototype.clearTable = function() {
    this.scrollCounter = 0;
    $('#hopsTable').empty();
};<commit_msg>Rework table-popup binding<commit_after>var Sidebar = function(markers) {
    this.scrollCounter = 0;
    this.sidebar = null;

    this.markers = markers;
};

Sidebar.prototype.initialize = function(map) {
    this.sidebar = L.control.sidebar('sidebar', {position: 'right'}).addTo(map);
};

Sidebar.prototype.open = function() {
    this.sidebar.open('hopsPane');
};

Sidebar.prototype.tableTemplate = function(data) {
    return '
' + template.hopTemplate(data) + '
';
};

Sidebar.prototype.appendTable = function(data) {
    $('#hopsTable').append(this.tableTemplate(data));
    $('.sidebar-content').animate({scrollTop: this.scrollCounter += 500}, 1000);

    var markers = this.markers;

    var hopsTableRow = $('#hopsTable tr');
    hopsTableRow.unbind('click');
    hopsTableRow.click(function() {
        var html = $(this).html();
        var index = markers.findIndex(function(value) {
            return html.includes(value._popup._content);
        });

        if (index !== -1) {
            markers[index].openPopup();
        }
    });
};

Sidebar.prototype.clearTable = function() {
    this.scrollCounter = 0;
    $('#hopsTable').empty();
};<|endoftext|>


<commit_before>if (document.cookie.indexOf("_ptt=") < 0 ) {

  chrome.tabs.getCurrent(function(tab) {
    if (tab) {
      return;
    }
    // Move authorization process to new tab!
    chrome.tabs.create({url: document.URL});
  });
}
<commit_msg>Fix JS error chrome is undefined<commit_after>if (document.cookie.indexOf("_ptt=") < 0 &&
  typeof chrome !== 'undefined' ) {

  chrome.tabs.getCurrent(function(tab) {
    if (tab) {
      return;
    }
    // Move authorization process to new tab!
    chrome.tabs.create({url: document.URL});
  });
}
<|endoftext|>


<commit_before>function allowDrop(holder) {
  var cursorPosition = null;
  var panel = null;
  var Promise = window.Promise || RSVP.Promise;

  var guid = (function() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
    }
    return function() {
      return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
           s4() + '-' + s4() + s4() + s4();
    };
  })();

  function uploadAsset(file) {
    var loading = document.createElement('div');
    loading.className = 'assetLoading';
    loading.innerHTML = '0% uploading...';
    var currentStatus = 0;

    var progress = function progress(percent, status) {
      if (percent - currentStatus < 10) {
        currentStatus = percent;
      } else {
        currentStatus += 10;
        requestAnimationFrame(function () {
          progress(percent, status);
        });
      }

      if (loading && currentStatus > 0) {
        if (currentStatus > 97) {
          loading.innerHTML = '97% uploaded...';
          // because there's some lag between 100% and actually rendering
        } else {
          loading.innerHTML = currentStatus + '% uploaded...';
        }
      }
    };

    if (!jsbin.lameEditor) {
      panel.addWidget(cursorPosition || panel.getCursor(), loading);
    } else {
      insertTextArea(panel, 'Uploading ...', true);
    }

    var s3upload = new S3Upload({
      s3_object_name: file.name.replace(/\s+/g, '-'),
      files: [file],

      onProgress: function (percent, status) {
        if (!jsbin.lameEditor) {
          requestAnimationFrame(function () {
            progress(percent, status);
          });
        }
      },

      onError: function (reason) {
        currentStatus = -1;
        console.error('Failed to upload', reason);
        loading.innerHTML = 'Failed to complete';
        loading.style.color = 'red';
        panel = null;
        cursorPosition = null;
        if (!jsbin.lameEditor) {
          setTimeout(function () {
            loading.parentNode.removeChild(loading);
          }, 2000);
        }
      },

      onFinishS3Put: function (url) {
        if (!jsbin.lameEditor) {
          loading.parentNode.removeChild(loading);
          panel.replaceSelection(getInsertText(file.type, panel, url));
        } else {
          insertTextArea(panel, getInsertText(file.type, panel, url));
          $(document).trigger('codeChange', { panelId: panel.id });
        }
        panel = null;
        cursorPosition = null;
      }
    });
  }

  function insertTextArea(el, string, select) {
    var start = el.selectionStart;
    var end = el.selectionEnd;

    var target = el;
    var value = target.value;

    // set textarea value to: text before caret + tab + text after caret
    target.value = value.substring(0, start) + string + value.substring(end);

    // put caret at right position again (add one for the tab)
    el.selectionStart = el.selectionEnd = start + 1;

    if (select) {
      el.selectionStart -= 1;
      el.selectionEnd = el.selectionEnd + string.length;
    } else {
      el.selectionStart = el.selectionEnd = start + string.length;
    }
  }

  function getInsertText(mime, cm, url) {
    // var panel = jsbin.panels.panels[cm.id];
    var processor = jsbin.state.processors[cm.id];

    if (cm.id === 'html') {
      if (mime.indexOf('image/') === 0) {
        if (processor === 'markdown') {
          return '![' + url + '](' + url + ')';
        }

        if (processor === 'jade') {
          return 'img(src="' + url + '")';
        }

        return '';
      }

      return url;
    }

    if (cm.id === 'css') {
      if (mime.indexOf('image/') === 0) {
        return 'url(' + url + ')';
      }

      return url;
    }

    // note: js just gets the url...
    return url;
  }

  var dragging = false;

  holder.ondragover = function () {
    dragging = true;
    return false;
  };

  holder.ondragend = function () {
    dragging = false;
    return false;
  };

  function getFileData(item) {
    return new Promise(function (resolve, reject) {
      if (item.kind === 'string') {
        item.getAsString(function (filename) {
          resolve(filename);
        });
      } else {
        resolve(item.getAsFile());
      }
    });
  }

  $('#bin textarea').on('paste', function (jQueryEvent) {
    if ($(this).closest('.CodeMirror').length) {
      panel = $(this).closest('.CodeMirror')[0].CodeMirror;
    } else {
      panel = this;
    }

    var event = jQueryEvent.originalEvent;
    var items = event.clipboardData.items;

    // this means we've copied a file that's an app icon, or it's just text
    // which we don't want to kick in anyway.
    if (!items || event.clipboardData.types[0].indexOf('text/') === 0) {
      return;
    }

    var file = null;
    var promises = [];
    for (var i = 0; i < items.length; i++) {
      promises.push(getFileData(items[i]));
    }

    Promise.all(promises).then(function (data) {
      var blobname = data.sort(function (a, b) {
        return typeof a === 'string' ? 1 : -1;
      });
      var file = data[0];
      file.name = data[1] || guid() + '.' + file.type.split('/')[1];

      uploadAsset(file);
    }).catch(function (error) {
      console.log(error.stack);
    });

    // FIXME???
    jQueryEvent.preventDefault();
  });

  $('.CodeMirror').on('mousemove', function (e) {
    if (!dragging) {
      return;
    }

    panel = this.CodeMirror;
    cursorPosition = this.CodeMirror.coordsChar({ top: event.y, left: event.x });
    this.CodeMirror.setCursor(cursorPosition);
  });

  var jstypes = ['javascript', 'coffeescript', 'coffee', 'js'];
  var csstypes = ['css', 'less', 'sass', 'scss'];
  var htmltypes = ['html', 'markdown', 'plain'];

  holder.ondrop = function (e) {
    dragging = false;
    e.preventDefault();

    if ($(this).closest('.CodeMirror').length) {
      panel = $(e.target).closest('.CodeMirror')[0].CodeMirror;
    } else {
      panel = e.target;
    }

    var file = e.dataTransfer.files[0],
        reader = new FileReader();

    if (file.type.indexOf('text/') !== 0) {
      // this isn't a text file for populating the panel, try uploading instead
      uploadAsset(file);
      return;
    }

    reader.onload = function (event) {
      // put JS in the JavaScript panel
      var type = file.type ? file.type.toLowerCase().replace(/^(text|application)\//, '') : file.name.toLowerCase().replace(/.*\./g, ''),
          panelId = null,
          panel = editors[panelId],
          syncCode = event.target.result,
          scroller = null;

      if (jstypes.indexOf(type) !== -1) {
        panelId = 'javascript';
      } else if (csstypes.indexOf(type) !== -1) {
        panelId = 'css';
      } else if (htmltypes.indexOf(type) !== -1) {
        panelId = 'html';
      }

      if (panelId === null) {
        // then we have an asset upload
        return uploadAsset(file);
      }

      panel = editors[panelId];
      scroller = panel.editor.scroller;

      panel.setCode(event.target.result);
      panel.show();

      try {
        // now kick off - basically just doing a copy and paste job from @wookiehangover - thanks man! :)
        var worker = new Worker(jsbin.root + '/js/editors/sync-worker.js');

        // pass the worker the file object
        worker.postMessage(file);

        panel.$el.find('> .label').append(' (live: edit & save in your fav editor)');

        // bind onmessage handler
        worker.onmessage = function (event) {
          var top = scroller.scrollTop;
          panel.setCode(event.data.body);
          scroller.scrollTop = top;
          syncCode = event.data.body;
        };
      } catch (e) {
        // fail on the awesomeness...oh well
      }
    };

    reader.readAsText(file);

    return false;
  };
}

// test for dnd and file api first
if (!!(window.File && window.FileList && window.FileReader)) allowDrop(document.body);
<commit_msg>Fixed broken CM support<commit_after>function allowDrop(holder) {
  var cursorPosition = null;
  var panel = null;
  var Promise = window.Promise || RSVP.Promise;

  var guid = (function() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
    }
    return function() {
      return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
           s4() + '-' + s4() + s4() + s4();
    };
  })();

  function uploadAsset(file) {
    var loading = document.createElement('div');
    loading.className = 'assetLoading';
    loading.innerHTML = '0% uploading...';
    var currentStatus = 0;

    var progress = function progress(percent, status) {
      if (percent - currentStatus < 10) {
        currentStatus = percent;
      } else {
        currentStatus += 10;
        requestAnimationFrame(function () {
          progress(percent, status);
        });
      }

      if (loading && currentStatus > 0) {
        if (currentStatus > 97) {
          loading.innerHTML = '97% uploaded...';
          // because there's some lag between 100% and actually rendering
        } else {
          loading.innerHTML = currentStatus + '% uploaded...';
        }
      }
    };

    if (!jsbin.lameEditor) {
      panel.addWidget(cursorPosition || panel.getCursor(), loading);
    } else {
      insertTextArea(panel, 'Uploading ...', true);
    }

    var s3upload = new S3Upload({
      s3_object_name: file.name.replace(/\s+/g, '-'),
      files: [file],

      onProgress: function (percent, status) {
        if (!jsbin.lameEditor) {
          requestAnimationFrame(function () {
            progress(percent, status);
          });
        }
      },

      onError: function (reason) {
        currentStatus = -1;
        console.error('Failed to upload', reason);
        loading.innerHTML = 'Failed to complete';
        loading.style.color = 'red';
        panel = null;
        cursorPosition = null;
        if (!jsbin.lameEditor) {
          setTimeout(function () {
            loading.parentNode.removeChild(loading);
          }, 2000);
        }
      },

      onFinishS3Put: function (url) {
        if (!jsbin.lameEditor) {
          loading.parentNode.removeChild(loading);
          panel.replaceSelection(getInsertText(file.type, panel, url));
        } else {
          insertTextArea(panel, getInsertText(file.type, panel, url));
          $(document).trigger('codeChange', { panelId: panel.id });
        }
        panel = null;
        cursorPosition = null;
      }
    });
  }

  function insertTextArea(el, string, select) {
    var start = el.selectionStart;
    var end = el.selectionEnd;

    var target = el;
    var value = target.value;

    // set textarea value to: text before caret + tab + text after caret
    target.value = value.substring(0, start) + string + value.substring(end);

    // put caret at right position again (add one for the tab)
    el.selectionStart = el.selectionEnd = start + 1;

    if (select) {
      el.selectionStart -= 1;
      el.selectionEnd = el.selectionEnd + string.length;
    } else {
      el.selectionStart = el.selectionEnd = start + string.length;
    }
  }

  function getInsertText(mime, cm, url) {
    // var panel = jsbin.panels.panels[cm.id];
    var processor = jsbin.state.processors[cm.id];

    if (cm.id === 'html') {
      if (mime.indexOf('image/') === 0) {
        if (processor === 'markdown') {
          return '![' + url + '](' + url + ')';
        }

        if (processor === 'jade') {
          return 'img(src="' + url + '")';
        }

        return '';
      }

      return url;
    }

    if (cm.id === 'css') {
      if (mime.indexOf('image/') === 0) {
        return 'url(' + url + ')';
      }

      return url;
    }

    // note: js just gets the url...
    return url;
  }

  var dragging = false;

  holder.ondragover = function () {
    dragging = true;
    return false;
  };

  holder.ondragend = function () {
    dragging = false;
    return false;
  };

  function getFileData(item) {
    return new Promise(function (resolve, reject) {
      if (item.kind === 'string') {
        item.getAsString(function (filename) {
          resolve(filename);
        });
      } else {
        resolve(item.getAsFile());
      }
    });
  }

  $('#bin textarea').on('paste', function (jQueryEvent) {
    if ($(this).closest('.CodeMirror').length) {
      panel = $(this).closest('.CodeMirror')[0].CodeMirror;
    } else {
      panel = this;
    }

    var event = jQueryEvent.originalEvent;
    var items = event.clipboardData.items;

    // this means we've copied a file that's an app icon, or it's just text
    // which we don't want to kick in anyway.
    if (!items || event.clipboardData.types[0].indexOf('text/') === 0) {
      return;
    }

    var file = null;
    var promises = [];
    for (var i = 0; i < items.length; i++) {
      promises.push(getFileData(items[i]));
    }

    Promise.all(promises).then(function (data) {
      var blobname = data.sort(function (a, b) {
        return typeof a === 'string' ? 1 : -1;
      });
      var file = data[0];
      file.name = data[1] || guid() + '.' + file.type.split('/')[1];

      uploadAsset(file);
    }).catch(function (error) {
      console.log(error.stack);
    });

    // FIXME???
    jQueryEvent.preventDefault();
  });

  $('.CodeMirror').on('mousemove', function (e) {
    if (!dragging) {
      return;
    }

    panel = this.CodeMirror;
    cursorPosition = this.CodeMirror.coordsChar({ top: event.y, left: event.x });
    this.CodeMirror.setCursor(cursorPosition);
  });

  var jstypes = ['javascript', 'coffeescript', 'coffee', 'js'];
  var csstypes = ['css', 'less', 'sass', 'scss'];
  var htmltypes = ['html', 'markdown', 'plain'];

  holder.ondrop = function (e) {
    dragging = false;
    e.preventDefault();

    if ($(e.target).closest('.CodeMirror').length) {
      panel = $(e.target).closest('.CodeMirror')[0].CodeMirror;
    } else {
      panel = e.target;
    }

    var file = e.dataTransfer.files[0],
        reader = new FileReader();

    if (file.type.indexOf('text/') !== 0) {
      // this isn't a text file for populating the panel, try uploading instead
      uploadAsset(file);
      return;
    }

    reader.onload = function (event) {
      // put JS in the JavaScript panel
      var type = file.type ? file.type.toLowerCase().replace(/^(text|application)\//, '') : file.name.toLowerCase().replace(/.*\./g, ''),
          panelId = null,
          panel = editors[panelId],
          syncCode = event.target.result,
          scroller = null;

      if (jstypes.indexOf(type) !== -1) {
        panelId = 'javascript';
      } else if (csstypes.indexOf(type) !== -1) {
        panelId = 'css';
      } else if (htmltypes.indexOf(type) !== -1) {
        panelId = 'html';
      }

      if (panelId === null) {
        // then we have an asset upload
        return uploadAsset(file);
      }

      panel = editors[panelId];
      scroller = panel.editor.scroller;

      panel.setCode(event.target.result);
      panel.show();

      try {
        // now kick off - basically just doing a copy and paste job from @wookiehangover - thanks man! :)
        var worker = new Worker(jsbin.root + '/js/editors/sync-worker.js');

        // pass the worker the file object
        worker.postMessage(file);

        panel.$el.find('> .label').append(' (live: edit & save in your fav editor)');

        // bind onmessage handler
        worker.onmessage = function (event) {
          var top = scroller.scrollTop;
          panel.setCode(event.data.body);
          scroller.scrollTop = top;
          syncCode = event.data.body;
        };
      } catch (e) {
        // fail on the awesomeness...oh well
      }
    };

    reader.readAsText(file);

    return false;
  };
}

// test for dnd and file api first
if (!!(window.File && window.FileList && window.FileReader)) allowDrop(document.body);
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

angular.module('njax.auth.controller', [])
    .controller(
        'RegisterFormCtl',
        [
            '$scope',
			'$q',
            'AccountService',
			'NJaxBootstrap',
            function($scope, $q, AccountService, NJaxBootstrap) {

                $scope.validate = function(){
					$scope.error = null;
					var deferred = $q.defer();
					if(!$scope.password || $scope.password.length < 8){
						deferred.reject(new Error("Password length is not valid"));
					}else if($scope.password != $scope.password_confirm){
						deferred.reject(new Error("Passwords do not match"));
					}else if(!$scope.name){
						deferred.reject(new Error("Please enter a name"));
					}else if(!$scope.namespace || $scope.namespace.length < 4){
						deferred.reject(new Error("Please enter a username"));
					}else{

						AccountService.namespace_available({ namespace: $scope.namespace }).$promise.then( function(data){
							if(!data.result){
								return deferred.reject(new Error("This username has already been taken"));
							}
							return deferred.resolve(true);
						});
					}
					return deferred.promise;
                }
                $scope.register = function($event){
					$event.preventDefault();
					$scope.validate().then(function(result){
						AccountService.register({
							name:$scope.name,
							username:$scope.email,
							namespace:$scope.namespace,
							password:$scope.password,
							password_confirm:$scope.password_confirm
						}).$promise.then(function(data){
							if(!data){
								return $scope.error = new Error("An unknown error occurred");
							}
							if(data.error){
								return $scope.error = data.error;
							}
							if(data.access_token){
								var d = new Date();
								d.setTime(d.getTime() + (90*24*60*60*1000));
								var expires = "expires="+d.toUTCString();
								document.cookie ="access_token=" + data.access_token + "; " + expires + ";domain="+ NJaxBootstrap.cookie.domain +";path=/";
							}
							if($scope.onRegisterFinish){
								$scope.onRegisterFinish(data);
							}
							$scope.$broadcast('njax.register.success');

						})
						//$event.target.submit();
					},function(err){

						$scope.error = err;

					})

                }
            }
        ]
    )
	.controller(
		'LoginFormCtl',
		[
			'$scope',
			'AccountService',
			function($scope, AccountService) {

				$scope.validate = function(){

				}
				$scope.save = function(){

				}
			}
		]
	)

<commit_msg>more specific password error message<commit_after>'use strict';

/* Controllers */

angular.module('njax.auth.controller', [])
    .controller(
        'RegisterFormCtl',
        [
            '$scope',
			'$q',
            'AccountService',
			'NJaxBootstrap',
            function($scope, $q, AccountService, NJaxBootstrap) {

                $scope.validate = function(){
					$scope.error = null;
					var deferred = $q.defer();
					if(!$scope.password || $scope.password.length < 8){
						deferred.reject(new Error("Password must be at least 8 characters"));
					}else if($scope.password != $scope.password_confirm){
						deferred.reject(new Error("Passwords do not match"));
					}else if(!$scope.name){
						deferred.reject(new Error("Please enter a name"));
					}else if(!$scope.namespace || $scope.namespace.length < 4){
						deferred.reject(new Error("Please enter a username"));
					}else{

						AccountService.namespace_available({ namespace: $scope.namespace }).$promise.then( function(data){
							if(!data.result){
								return deferred.reject(new Error("This username has already been taken"));
							}
							return deferred.resolve(true);
						});
					}
					return deferred.promise;
                }
                $scope.register = function($event){
					$event.preventDefault();
					$scope.validate().then(function(result){
						AccountService.register({
							name:$scope.name,
							username:$scope.email,
							namespace:$scope.namespace,
							password:$scope.password,
							password_confirm:$scope.password_confirm
						}).$promise.then(function(data){
							if(!data){
								return $scope.error = new Error("An unknown error occurred");
							}
							if(data.error){
								return $scope.error = data.error;
							}
							if(data.access_token){
								var d = new Date();
								d.setTime(d.getTime() + (90*24*60*60*1000));
								var expires = "expires="+d.toUTCString();
								document.cookie ="access_token=" + data.access_token + "; " + expires + ";domain="+ NJaxBootstrap.cookie.domain +";path=/";
							}
							if($scope.onRegisterFinish){
								$scope.onRegisterFinish(data);
							}
							$scope.$broadcast('njax.register.success');

						})
						//$event.target.submit();
					},function(err){

						$scope.error = err;

					})

                }
            }
        ]
    )
	.controller(
		'LoginFormCtl',
		[
			'$scope',
			'AccountService',
			function($scope, AccountService) {

				$scope.validate = function(){

				}
				$scope.save = function(){

				}
			}
		]
	)

<|endoftext|>


<commit_before>
import MarkedHelper from 'helper/marked';
import CONST from 'const';

export default class InfoDisplay {
    /**
     * @author Guillaume AMAT
     * @static
     * @access public
     * @param {object} layerModel - Element's layer.
     * @param {object} feature - Element's geoJson representation.
     * @param {array} nonOsmTags - Non OSM tags related to the OSM element.
     * @param {boolean} feature - Is the user logged?
     * @returns {string}
     */
    static buildContent(layerModel, feature, nonOsmTags) {
        let content = layerModel.get('popupContent');
        let data;

        if ( !content ) {
            return '';
        }

        if ( layerModel.get('type') === CONST.layerType.overpass) {
            data = feature.properties.tags;
        }
        else if ( feature.properties.tags ) {
            data = feature.properties.tags;
        }
        else {
            data = feature.properties;
        }

        content = content.replace(
            new RegExp('{id}', 'g'),
            feature.properties.id
        );

        content = content.replace(
            new RegExp('{type}', 'g'),
            feature.properties.type
        );

        for (const i in nonOsmTags) {
            if ({}.hasOwnProperty.call(nonOsmTags, i)) {
                const tag = nonOsmTags[i];

                content = content.replace(
                    new RegExp(`{${tag.key}}`, 'g'),
                    tag.value
                );
            }
        }

        for (const k in data) {
            if ({}.hasOwnProperty.call(data, k)) {
                content = content.replace(
                    new RegExp(`{${k}}`, 'g'),
                    data[k]
                );
            }
        }

        content = content.replace( /\{(.*?)\}/g, '' );

        return MarkedHelper.render(content);
    }
}
<commit_msg>Fix a conflict between Markdown and OSM elements attributes in some cases<commit_after>
import MarkedHelper from 'helper/marked';
import CONST from 'const';

export default class InfoDisplay {
    /**
     * @author Guillaume AMAT
     * @static
     * @access public
     * @param {object} layerModel - Element's layer.
     * @param {object} feature - Element's geoJson representation.
     * @param {array} nonOsmTags - Non OSM tags related to the OSM element.
     * @param {boolean} feature - Is the user logged?
     * @returns {string}
     */
    static buildContent(layerModel, feature, nonOsmTags) {
        let content = layerModel.get('popupContent');
        let data;

        if ( !content ) {
            return '';
        }

        content = MarkedHelper.render(content);

        if ( layerModel.get('type') === CONST.layerType.overpass) {
            data = feature.properties.tags;
        }
        else if ( feature.properties.tags ) {
            data = feature.properties.tags;
        }
        else {
            data = feature.properties;
        }

        content = content.replace(
            new RegExp('{id}', 'g'),
            feature.properties.id
        );

        content = content.replace(
            new RegExp('{type}', 'g'),
            feature.properties.type
        );

        for (const i in nonOsmTags) {
            if ({}.hasOwnProperty.call(nonOsmTags, i)) {
                const tag = nonOsmTags[i];

                content = content.replace(
                    new RegExp(`{${tag.key}}`, 'g'),
                    tag.value
                );
            }
        }

        for (const k in data) {
            if ({}.hasOwnProperty.call(data, k)) {
                content = content.replace(
                    new RegExp(`{${k}}`, 'g'),
                    data[k]
                );
            }
        }

        content = content.replace( /\{(.*?)\}/g, '' );

        return content;
    }
}
<|endoftext|>


<commit_before>$(function(){

	var $table = $('table#grid_columnchooser');
	var pagerId = '#grid_columnchooser_pager';

	$table.jqGrid(
			{
				recordtext: '',
				pgbuttons: false,
				pgtext: null,
				url:'js/jqgrid/data.json',
				datatype: "json",
				width: 1000,
				height: 250,
				pager: pagerId,
				gridComplete: function(){

					$.post('load-columns-position', null, function($response){

						if( $response ){

							var colModels = $table.jqGrid('getGridParam', 'colModel');
							var $responseCols = $response.columns_position;
							var columns = [];

							if( $responseCols.length > 0 ){

								columns[0] = 0;

								$.each($responseCols, function(icol, columnIndex){

									if( icol > 0 ){

										var pos = columnIndex.index;
										var field = columnIndex.nm_campo;

										$.each(colModels, function(i, colModel){

											var colModelIndex = colModel.index;

											if( field == colModelIndex ){

												columns[icol] = i;

												if( $.parseJSON( columnIndex.isHidden ) ){
													$grid.jqGrid('hideCol', [field]);
												}
											}
										});
									}
								});

								$table.jqGrid("remapColumns", columns, true);

							}else{

								$.each(colModels, function(i, colModel){

						    		columns.push({
					    				field: colModel.index,
					    				isHidden: colModel.hidden,
					    				pos: i
					    			});
						    	});

								$.post('save-columns-position',
						    			{
						    				cols: columns,
						    				field: 'columns_position' // the field name in the table
						    			}, null);
							}
						}
					});
				},
				colNames: ['State', 'Name', 'Country', 'City', 'E-mail', 'Phone', 'Zip-Code'],
				colModel:
					[
					 {
						 name : 'state',
						 index : 'state',
						 width : 40,
						 align : 'center'
					 },
					 {
						 name:  'name',
						 index: 'name',
						 width: 40,
						 align: 'center'
					 },
					 {
						 name : 'country',
						 index : 'country',
						 width : 40,
						 align : 'center'
					 }, {
						 name : 'city',
						 index : 'city',
						 width : 40,
						 align : 'center'
					 }, {
						 name : 'email',
						 index : 'email',
						 width : 40,
						 align : 'center'
					 }, {
						 name : 'phone',
						 index : 'phone',
						 width : 40,
						 align : 'center'
					 }, {
						 name : 'zipcode',
						 index : 'zipcode',
						 width : 40,
						 align : 'center'
					 }
					 ]
			}).navGrid(pagerId,{ search: false, edit: false, add: false, del: false, view:false });

	$table.jqGrid('navButtonAdd',pagerId,{
		caption: "Select Columns",
		buttonicon: 'ui-icon-carat-2-n-s',
		title: "Reorder Columns",
		onClickButton : function (){
	    	$table.columnChooser(
	    			{
	    				done: function(perm){

	    					if( (typeof (perm) !== "undefined") ){

	    						$table.jqGrid("remapColumns", perm, true);

						    	var colModels = $table.jqGrid('getGridParam', 'colModel');
						    	var coluns = new Array();

						    	$.each(perm, function(i, columnIndex){

						    		columns.push({
					    				field: colModels[i].index,
					    				isHidden: colModels[i].hidden,
					    				pos: columnIndex
					    			});
								});

						    	$.post('save-columns-position',
						    			{
						    				cols: columns,
						    				field: 'columns_position' // the field name in the table
						    			}, null);
	    					}
	    				}
	    			});
	    }
	});

});<commit_msg>Fix - variable name.<commit_after>$(function(){

	var $table = $('table#grid_columnchooser');
	var pagerId = '#grid_columnchooser_pager';

	$table.jqGrid(
			{
				recordtext: '',
				pgbuttons: false,
				pgtext: null,
				url:'js/jqgrid/data.json',
				datatype: "json",
				width: 1000,
				height: 250,
				pager: pagerId,
				gridComplete: function(){

					$.post('load-columns-position', null, function($response){

						if( $response ){

							var colModels = $table.jqGrid('getGridParam', 'colModel');
							var $responseCols = $response.columns_position;
							var columns = [];

							if( $responseCols.length > 0 ){

								columns[0] = 0;

								$.each($responseCols, function(icol, columnIndex){

									if( icol > 0 ){

										var pos = columnIndex.index;
										var field = columnIndex.nm_campo;

										$.each(colModels, function(i, colModel){

											var colModelIndex = colModel.index;

											if( field == colModelIndex ){

												columns[icol] = i;

												if( $.parseJSON( columnIndex.isHidden ) ){
													$grid.jqGrid('hideCol', [field]);
												}
											}
										});
									}
								});

								$table.jqGrid("remapColumns", columns, true);

							}else{

								$.each(colModels, function(i, colModel){

						    		columns.push({
					    				field: colModel.index,
					    				isHidden: colModel.hidden,
					    				pos: i
					    			});
						    	});

								$.post('save-columns-position',
						    			{
						    				cols: columns,
						    				field: 'columns_position' // the field name in the table
						    			}, null);
							}
						}
					});
				},
				colNames: ['State', 'Name', 'Country', 'City', 'E-mail', 'Phone', 'Zip-Code'],
				colModel:
					[
					 {
						 name : 'state',
						 index : 'state',
						 width : 40,
						 align : 'center'
					 },
					 {
						 name:  'name',
						 index: 'name',
						 width: 40,
						 align: 'center'
					 },
					 {
						 name : 'country',
						 index : 'country',
						 width : 40,
						 align : 'center'
					 }, {
						 name : 'city',
						 index : 'city',
						 width : 40,
						 align : 'center'
					 }, {
						 name : 'email',
						 index : 'email',
						 width : 40,
						 align : 'center'
					 }, {
						 name : 'phone',
						 index : 'phone',
						 width : 40,
						 align : 'center'
					 }, {
						 name : 'zipcode',
						 index : 'zipcode',
						 width : 40,
						 align : 'center'
					 }
					 ]
			}).navGrid(pagerId,{ search: false, edit: false, add: false, del: false, view:false });

	$table.jqGrid('navButtonAdd',pagerId,{
		caption: "Select Columns",
		buttonicon: 'ui-icon-carat-2-n-s',
		title: "Reorder Columns",
		onClickButton : function (){
	    	$table.columnChooser(
	    			{
	    				done: function(perm){

	    					if( (typeof (perm) !== "undefined") ){

	    						$table.jqGrid("remapColumns", perm, true);

						    	var colModels = $table.jqGrid('getGridParam', 'colModel');
						    	var columns = new Array();

						    	$.each(perm, function(i, columnIndex){

						    		columns.push({
					    				field: colModels[i].index,
					    				isHidden: colModels[i].hidden,
					    				pos: columnIndex
					    			});
								});

						    	$.post('save-columns-position',
						    			{
						    				cols: columns,
						    				field: 'columns_position' // the field name in the table
						    			}, null);
	    					}
	    				}
	    			});
	    }
	});

});<|endoftext|>


<commit_before>(function(module){
  var eventsView = {

    //render events
    renderTemplate(event) {
      var template = Handlebars.compile($('#event-template').text());
      var htmlObject = template(event);
      return htmlObject;
    },

    //get all events
    renderAllEvents(){
      API.getAll('api/event/list', Event, function(arrayOfEvents){
        $('#all-events').empty();
        arrayOfEvents.forEach(function(event){
          event.date = moment(event.date).format('HH:mm on MM-DD-YY');
          $('#events').append(eventsView.renderTemplate(event));
        });
        eventsView.addToAgenda();
      });
    },

    //agenda control
    addToAgenda(){
      $('.agenda-btn-handler').on('click', '.agenda-btn', function(e){
        e.preventDefault();
        var eventId = $(this).attr('data');

        var userId = window.userView.userId();
        var url = '/api/agenda/' + userId;
        console.log(url);
        API.patch(url, {'event_id':eventId}, Event, function(agendaArray){
          console.log(agendaArray);
        });
      });

    },

    renderAgenda(){
      //API call --> get logged in user's agenda: GET users/:id
    }
  };

  module.eventsView = eventsView;
})(window);
<commit_msg>cleanup<commit_after>(function(module){
  var eventsView = {

    //render events
    renderTemplate(event) {
      var template = Handlebars.compile($('#event-template').text());
      var htmlObject = template(event);
      return htmlObject;
    },

    //get all events
    renderAllEvents(){
      API.getAll('api/event/list', Event, function(arrayOfEvents){
        $('#all-events').empty();
        arrayOfEvents.forEach(function(event){
          event.date = moment(event.date).format('HH:mm on MM-DD-YY');
          $('#events').append(eventsView.renderTemplate(event));
        });
        eventsView.addToAgenda();
      });
    },

    //agenda control
    addToAgenda(){
      $('.agenda-btn-handler').on('click', '.agenda-btn', function(e){
        e.preventDefault();
        var eventId = $(this).attr('data');

        var userId = window.userView.userId();
        var url = '/api/agenda/' + userId;
        console.log(url);
        API.patch(url, {'event_id':eventId}, Event, function(agendaArray){
          console.log(agendaArray);
        });
      });

      //TODO change cal btn to cal_check when added to agenda
      //TODO set up agenda view controls
    },

    renderAgenda(){
      //API call --> get logged in user's agenda: GET users/:id
    }
  };

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


<commit_before>/*
 * connect-php
 * https://github.com/ddprrt/connect-php
 *
 * Copyright (c) 2013 Stefan Baumgartner
 * Licensed under the MIT license.
 */

'use strict';
var exec = require('child_process').exec;

module.exports = function phpMiddleware(directory)
{
    // necessary to check the .php extensions
    if (typeof String.prototype.endsWith !== 'function')
    {
        String.prototype.endsWith = function(suffix)
        {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        };
    }
    return function(req, res, next)
    {
        if (req.url.indexOf('.php?') > -1)
        { // We were passed $_GET parameters
            var reqSplit = req.url.split('?');
            var params = reqSplit[1].split('&').join(' ');
            var command = 'php-cgi -f ' + directory + reqSplit[0] + ' ' + params; // eg. php-cgi -f index.php left=1058 right=1067 class=A language=English
            exec(command, function callback(error, stdout, stderr)
            {
                if (error)
                {
                    console.error(stderr);
                }
                res.write(stdout);
                res.end();
            });
        }
        else if (req.url.endsWith('.php'))
        { // We were not passed $_GET parameters
            exec('php ' + directory + req.url, function callback(error, stdout, stderr)
            {
                if (error)
                {
                    console.error(stderr);
                }
                res.write(stdout);
                res.end();
                return;
            });
        }
        else
        {
            // No .php file? Moving on ...
            next();
        }
    };
};
<commit_msg>Revert "formatting"<commit_after>/*
 * connect-php
 * https://github.com/ddprrt/connect-php
 *
 * Copyright (c) 2013 Stefan Baumgartner
 * Licensed under the MIT license.
 */

'use strict';
var exec = require('child_process').exec;

module.exports = function phpMiddleware(directory) {

    // necessary to check the .php extensions
    if (typeof String.prototype.endsWith !== 'function') {
        String.prototype.endsWith = function (suffix) {
            return this.indexOf(suffix, this.length - suffix.length) !== -1;
        };
    }
    return function (req, res, next) {
        if (req.url.indexOf('.php?') > -1) { // We were passed $_GET parameters
            var reqSplit = req.url.split('?');
            var params = reqSplit[1].split('&').join(' ');
            var command = 'php-cgi -f ' + directory + reqSplit[0] + ' ' + params; // eg. php-cgi -f index.php left=1058 right=1067 class=A language=English

            exec(command, function callback(error, stdout, stderr) {
                if (error) {
                    console.error(stderr);
                }
                res.write(stdout);
                res.end();
            });
        } else if (req.url.endsWith('.php')) { // We were not passed $_GET parameters
            exec('php ' + directory + req.url, function callback(error, stdout, stderr) {
                if (error) {
                    console.error(stderr);
                }
                res.write(stdout);
                res.end();
                return;
            });

        } else {
            // No .php file? Moving on ...
            next();
        }
    };
};
<|endoftext|>


<commit_before>const fs = require('fs-extra');
const path = require('path');
const inquirer = require('inquirer');
const crlf = require('crlf');
const glob = require('glob-promise');

const runScript = require('./libs/run-script');
const logWelcome = require('./libs/log/welcome');
const logAbort = require('./libs/log/abort');
const logFinish = require('./libs/log/finish');
const spinner = require('./packages/koot/utils/spinner');

const prePublish = async () => {
    const title = 'pre-publish';
    const waiting = spinner(title + '...');

    const packages = await glob(
        path.resolve(__dirname, 'packages/*/package.json')
    );
    const bins = [];

    // 汇总所有 bin 文件
    for (const packageJson of packages) {
        const dir = path.dirname(packageJson);
        const { bin = {} } = await fs.readJson(packageJson);
        for (const pathname of Object.values(bin)) {
            bins.push(path.resolve(dir, pathname));
        }
    }

    // 将所有 bin 文件的换行符改为 LF
    for (const file of bins) {
        await new Promise((resolve, reject) => {
            crlf.set(file, 'LF', (err, endingType) => {
                if (err) return reject(err);
                resolve(endingType);
            });
        });
    }

    // git commit
    const git = require('simple-git/promise')(__dirname);
    const { modified = [] } = await git.status();
    if (modified.length) {
        await git.add('./*');
        await git.commit(`changed all bins' line breaks to LF`);
    }

    waiting.stop();
    spinner(title).succeed();
};

const run = async () => {
    logWelcome('Publish');

    const defaultSelected = [
        // 'koot',
        // 'koot-webpack'
    ];

    const dirPackages = path.resolve(__dirname, './packages');
    const packages = (await fs.readdir(dirPackages)).filter(filename => {
        const dir = path.resolve(dirPackages, filename);
        const lstat = fs.lstatSync(dir);
        if (!lstat.isDirectory()) return false;

        // 检查 package.json
        const filePackage = path.resolve(dir, 'package.json');
        if (!fs.existsSync(filePackage)) return false;

        let p;
        try {
            p = fs.readJsonSync(filePackage);
        } catch (e) {}

        if (typeof p !== 'object') return false;

        if (p.private) return false;

        return true;
    });

    const { selected = [] } = await inquirer.prompt({
        type: 'checkbox',
        name: 'selected',
        message: 'Select package(s) to publish\n ',
        choices: packages,
        default: defaultSelected
    });
    console.log('');
    if (!selected.length) {
        logAbort('No package selected.');
        return;
    }

    const { tag = false } = await inquirer.prompt({
        type: 'list',
        name: 'tag',
        message: 'Select tag for NPM',
        choices: [
            {
                name: 'Please select a tag',
                value: false
            },
            {
                name: 'No tag (none)',
                value: ''
            },
            'next'
        ],
        default: 0
    });
    console.log('');
    if (tag === false) {
        logAbort('No tag selected.');
        return;
    }

    await prePublish();
    await runScript(
        `lerna publish` +
            ` --ignore-changes "packages/!(${selected.join('|')})/**"` +
            (tag ? ` --dist-tag ${tag}` : '')
    );

    logFinish();
};

run().catch(async e => console.error(e));
<commit_msg>update publish script<commit_after>const fs = require('fs-extra');
const path = require('path');
const inquirer = require('inquirer');
const crlf = require('crlf');
const glob = require('glob-promise');

const runScript = require('./libs/run-script');
const logWelcome = require('./libs/log/welcome');
const logAbort = require('./libs/log/abort');
const logFinish = require('./libs/log/finish');
const spinner = require('./packages/koot/utils/spinner');

const prePublish = async () => {
    const title = 'pre-publish';
    const waiting = spinner(title + '...');

    const packages = await glob(
        path.resolve(__dirname, 'packages/*/package.json')
    );
    const bins = [];

    // 汇总所有 bin 文件
    for (const packageJson of packages) {
        const dir = path.dirname(packageJson);
        const { bin = {} } = await fs.readJson(packageJson);
        for (const pathname of Object.values(bin)) {
            bins.push(path.resolve(dir, pathname));
        }
    }

    // 将所有 bin 文件的换行符改为 LF
    for (const file of bins) {
        await new Promise((resolve, reject) => {
            crlf.set(file, 'LF', (err, endingType) => {
                if (err) return reject(err);
                resolve(endingType);
            });
        });
    }

    // git commit
    const git = require('simple-git/promise')(__dirname);
    const complete = () => {
        waiting.stop();
        spinner(title).succeed();
    };
    try {
        const { modified = [] } = await git.status();
        if (modified.length) {
            await git.add('./*');
            await git.commit(`changed all bins' line breaks to LF`);
        }
        complete();
    } catch (e) {
        complete();
    }
};

const run = async () => {
    logWelcome('Publish');

    const defaultSelected = [
        // 'koot',
        // 'koot-webpack'
    ];

    const dirPackages = path.resolve(__dirname, './packages');
    const packages = (await fs.readdir(dirPackages)).filter(filename => {
        const dir = path.resolve(dirPackages, filename);
        const lstat = fs.lstatSync(dir);
        if (!lstat.isDirectory()) return false;

        // 检查 package.json
        const filePackage = path.resolve(dir, 'package.json');
        if (!fs.existsSync(filePackage)) return false;

        let p;
        try {
            p = fs.readJsonSync(filePackage);
        } catch (e) {}

        if (typeof p !== 'object') return false;

        if (p.private) return false;

        return true;
    });

    const { selected = [] } = await inquirer.prompt({
        type: 'checkbox',
        name: 'selected',
        message: 'Select package(s) to publish\n ',
        choices: packages,
        default: defaultSelected
    });
    console.log('');
    if (!selected.length) {
        logAbort('No package selected.');
        return;
    }

    const { tag = false } = await inquirer.prompt({
        type: 'list',
        name: 'tag',
        message: 'Select tag for NPM',
        choices: [
            {
                name: 'Please select a tag',
                value: false
            },
            {
                name: 'No tag (none)',
                value: ''
            },
            'next'
        ],
        default: 0
    });
    console.log('');
    if (tag === false) {
        logAbort('No tag selected.');
        return;
    }

    await prePublish();
    await runScript(
        `lerna publish` +
            ` --ignore-changes "packages/!(${selected.join('|')})/**"` +
            (tag ? ` --dist-tag ${tag}` : '')
    );

    logFinish();
};

run().catch(async e => console.error(e));
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2014 by Animatron.
 * All rights are reserved.
 */

/* Variables we get from template:
   playerDomain - a URL to player domain host, e.g. player.animatron.com
   amazonDomain — a URL to snapshot storage host, e.g. http://snapshots.animatron.com/<snapshot-id>
   width — width of the animation
   height - height of the animation
   playerVersion = player version, default 'latest'
   filename = filename of snapshot, used as amazonDomain + filename
   autostart = (boolean) autostart of movie on player load
   loop = (boolean) loop animation instead of stoping at the end
   animation = JSON object of animatron movie (currently not used)
*/

var inIFrame = false;

var _u = (function () { /* utils */

    return {

        parseQueryString: function( queryString ) {
            var params = {}, queries, temp, i, l;

            // Split into key/value pairs
            queries = queryString.split("&");

            // Convert the array of strings into an object
            for ( i = 0, l = queries.length; i < l; i++ ) {
                temp = queries[i].split('=');
                params[temp[0]] = temp[1];
            }

            return params;
        },

        extractVal: function (params, name) {
            if (!params) return null;
            var res;
            if (res = params.match(
                new RegExp('[\\?&]' + name + '=([\\w\\.\\-]+)')
            )) return (res.length && res[1]) ? res[1] : null;
        },

        injectVal: function (params, name, value) {
            if (!params) return name + '=' + value;
            var res = params.match(
                new RegExp('[\\?&]' + name + '=[\\w-]+'));
            if (!res || !res.length) return params + '&' + name + '=' + value;
            return params.replace(
                new RegExp('([\\?&])' + name + '=[\\w-]+'),
                    '$1' + name + '=' + value
            );
        },
        injectIfNotPresent: function (params, name, value) {
            if (!this.extractVal(params, name)) {
                return this.injectVal(params, name, value);
            } else {
                return params;
            }
        },

        getRequiredRect: function () {
            if (inIFrame) {
                return _u.getIframeSize();
            } else {
                return [ width, height ];
            }
        },

        getIframeSize: function () {
            var size = [0, 0];
            if (typeof window.innerWidth == 'number') {
                size = [window.innerWidth, window.innerHeight];
            } else {
                size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
            }

            return size;
        },

        reportError: function (_e) {
            if (console) console.error(_e.message || _e);
            else alert(_e.message || _e);
        },

        forcedJS: function (_path, _then) {
            var scriptElm = document.createElement('script');
            scriptElm.type = 'text/javascript';
            scriptElm.async = 'async';
            scriptElm.src = _path + '?' + (new Date()).getTime();
            scriptElm.onload = scriptElm.onreadystatechange = (function () {
                var _success = false;
                return function () {
                    if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
                        _success = true;
                        _then();
                    } else if (!_success) {
                        _u.reportError(new Error('Request failed: ' + this.readyState));
                    }
                }
            })();
            scriptElm.onerror = _u.reportError;
            var headElm = document.head || document.getElementsByTagName('head')[0];
            headElm.appendChild(scriptElm);
        }
    };

})();

var start = (function () {

    var VERSION_MASK = '^(v[0-9]+(\\.[0-9]+){0,2})$|^latest$';

    var CANVAS_ID = 'target',
        WRAPPER_CLASS = 'anm-wrapper',
        PROTOCOL = ('https:' === document.location.protocol) ? 'https://' : 'http://',
        PLAYER_VERSION_ID = playerVersion;

    if (!playerVersion || !playerVersion.match(VERSION_MASK)) {
        _u.reportError(new Error('Snapshot Version ID \'' + playerVersion + '\' is incorrect'));
        return;
    }

    inIFrame = (window.self !== window.top);

    var _params_ = location.search, parsedParams = _u.parseQueryString(_params_.substring(1));
    var rect = _u.getRequiredRect();
    if (rect) {
        if (_params_) {
            _params_ = _u.injectIfNotPresent(_params_, "w", rect[0]);
            _params_ = _u.injectIfNotPresent(_params_, "h", rect[1]);
        } else {
            _params_ = '?w=' + rect[0] + '&' + 'h=' + rect[1];
        }

        if (parsedParams.w) {
            rect[0] = parsedParams.w;
        }
        if (parsedParams.h) {
            rect[1] = parsedParams.h;
        };
    }
    if (autostart) {
        _params_ = _u.injectIfNotPresent(_params_, "t", 0);
    }
    if (loop) {
        _params_ = _u.injectIfNotPresent(_params_, "r", 1);
    }

    var _snapshotUrl_ = amazonDomain + '/' + filename + (_params_ || '');

    var temp_v = null;
    if (temp_v = _u.extractVal(_params_, 'v')) {
        if (!temp_v.match(VERSION_MASK)) {
            _u.reportError(new Error('Player Version ID \'' + temp_v + '\' is incorrect'));
            return;
        }

        PLAYER_VERSION_ID = temp_v;
    }

    return function () {
        try {
            if (!inIFrame && !rect) {
                document.body.className = 'no-iframe no-rect';
            } else if (!inIFrame) {
                document.body.className = 'no-iframe';
            }
            var stylesTag = document.createElement('style');
            stylesTag.type = 'text/css';

            var head = document.getElementsByTagName("head")[0];
            if (!head) throw new Error('No head element in document');
            head.appendChild(stylesTag);

            var styles = stylesTag.sheet,
                rules = styles.cssRules || styles.rules;

            var noIFrameRule = rules[(styles.insertRule || styles.addRule).call(styles,
                                     'body.no-iframe .anm-wrapper {}', rules.length)],
                noRectRule   = rules[(styles.insertRule || styles.addRule).call(styles,
                                     'body.no-rect .anm-wrapper {}', rules.length)],
                noPlayerRule = rules[(styles.insertRule || styles.addRule).call(styles,
                                     'body.no-iframe canvas#target:not([anm-player]) {}', rules.length)],
                // there is a version of player where `anm-state-loading` and `anm-state-resources-loading` classes
                // were incorrectly named `anm-loading`, `anm-resources-loading`, this case is temporary (!) hacked out here
                wrapperRule  = rules[(styles.insertRule || styles.addRule).call(styles,
                                     'body.no-iframe div.anm-state-nothing, body.no-iframe div.anm-state-error, '+
                                     'body.no-iframe div.anm-loading, body.no-iframe div.anm-state-loading, ' +
                                     'body.no-iframe div.anm-resources-loading, body.no-iframe div.anm-state-resources-loading ' +
                                     '{}', rules.length)];

            function ruleForWrapperStyle(rule) {
                rule.style.borderWidth = '1px';
                rule.style.borderStyle = 'solid';
                rule.style.borderColor = '#ccc';
                rule.style.display = 'block';
                rule.style.position = 'absolute';
                rule.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.5)';
                rule.style.overflow = 'hidden';
            }

            ruleForWrapperStyle(noIFrameRule);
            ruleForWrapperStyle(noPlayerRule);
            ruleForWrapperStyle(wrapperRule);

            if (rect) {
                function ruleForCanvasPosition(rule) {
                    rule.style.width = rect[0] + 'px';
                    rule.style.height = rect[1] + 'px';
                    if (!inIFrame) {
                        rule.style.top  = '50%';
                        rule.style.left = '50%';
                        rule.style.marginLeft = -Math.floor(rect[0] / 2) + 'px';
                        rule.style.marginTop  = -Math.floor(rect[1] / 2) + 'px';
                    }
                }

                ruleForCanvasPosition(noIFrameRule);
                ruleForCanvasPosition(noPlayerRule);
            }

            noRectRule.style.top  = '10%';
            noRectRule.style.left = '10%';

            if (rect) {
                var canvas = document.getElementById(CANVAS_ID);
                canvas.style.width  = rect[0] + 'px';
                canvas.style.height = rect[1] + 'px';
            }

            _u.forcedJS(PROTOCOL + playerDomain + '/' + PLAYER_VERSION_ID + '/bundle/animatron.min.js',
                function () {
                      anm.Player.forSnapshot(CANVAS_ID, _snapshotUrl_, anm.createImporter('animatron'));
                }
            );
        } catch (e) {
            _u.reportError(e);
        }
    }

})();
<commit_msg>renamed canvasId to targetId<commit_after>/*
 * Copyright (c) 2011-2014 by Animatron.
 * All rights are reserved.
 */

/* Variables we get from template:
   playerDomain - a URL to player domain host, e.g. player.animatron.com
   amazonDomain — a URL to snapshot storage host, e.g. http://snapshots.animatron.com/<snapshot-id>
   width — width of the animation
   height - height of the animation
   playerVersion = player version, default 'latest'
   filename = filename of snapshot, used as amazonDomain + filename
   autostart = (boolean) autostart of movie on player load
   loop = (boolean) loop animation instead of stoping at the end
   animation = JSON object of animatron movie (currently not used)
*/

var inIFrame = false;

var _u = (function () { /* utils */

    return {

        parseQueryString: function( queryString ) {
            var params = {}, queries, temp, i, l;

            // Split into key/value pairs
            queries = queryString.split("&");

            // Convert the array of strings into an object
            for ( i = 0, l = queries.length; i < l; i++ ) {
                temp = queries[i].split('=');
                params[temp[0]] = temp[1];
            }

            return params;
        },

        extractVal: function (params, name) {
            if (!params) return null;
            var res;
            if (res = params.match(
                new RegExp('[\\?&]' + name + '=([\\w\\.\\-]+)')
            )) return (res.length && res[1]) ? res[1] : null;
        },

        injectVal: function (params, name, value) {
            if (!params) return name + '=' + value;
            var res = params.match(
                new RegExp('[\\?&]' + name + '=[\\w-]+'));
            if (!res || !res.length) return params + '&' + name + '=' + value;
            return params.replace(
                new RegExp('([\\?&])' + name + '=[\\w-]+'),
                    '$1' + name + '=' + value
            );
        },
        injectIfNotPresent: function (params, name, value) {
            if (!this.extractVal(params, name)) {
                return this.injectVal(params, name, value);
            } else {
                return params;
            }
        },

        getRequiredRect: function () {
            if (inIFrame) {
                return _u.getIframeSize();
            } else {
                return [ width, height ];
            }
        },

        getIframeSize: function () {
            var size = [0, 0];
            if (typeof window.innerWidth == 'number') {
                size = [window.innerWidth, window.innerHeight];
            } else {
                size = [document.documentElement.clientWidth, document.documentElement.clientHeight];
            }

            return size;
        },

        reportError: function (_e) {
            if (console) console.error(_e.message || _e);
            else alert(_e.message || _e);
        },

        forcedJS: function (_path, _then) {
            var scriptElm = document.createElement('script');
            scriptElm.type = 'text/javascript';
            scriptElm.async = 'async';
            scriptElm.src = _path + '?' + (new Date()).getTime();
            scriptElm.onload = scriptElm.onreadystatechange = (function () {
                var _success = false;
                return function () {
                    if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
                        _success = true;
                        _then();
                    } else if (!_success) {
                        _u.reportError(new Error('Request failed: ' + this.readyState));
                    }
                }
            })();
            scriptElm.onerror = _u.reportError;
            var headElm = document.head || document.getElementsByTagName('head')[0];
            headElm.appendChild(scriptElm);
        }
    };

})();

var start = (function () {

    var VERSION_MASK = '^(v[0-9]+(\\.[0-9]+){0,2})$|^latest$';

    var TARGET_ID = 'target',
        WRAPPER_CLASS = 'anm-wrapper',
        PROTOCOL = ('https:' === document.location.protocol) ? 'https://' : 'http://',
        PLAYER_VERSION_ID = playerVersion;

    if (!playerVersion || !playerVersion.match(VERSION_MASK)) {
        _u.reportError(new Error('Snapshot Version ID \'' + playerVersion + '\' is incorrect'));
        return;
    }

    inIFrame = (window.self !== window.top);

    var _params_ = location.search, parsedParams = _u.parseQueryString(_params_.substring(1));
    var rect = _u.getRequiredRect();
    if (rect) {
        if (_params_) {
            _params_ = _u.injectIfNotPresent(_params_, "w", rect[0]);
            _params_ = _u.injectIfNotPresent(_params_, "h", rect[1]);
        } else {
            _params_ = '?w=' + rect[0] + '&' + 'h=' + rect[1];
        }

        if (parsedParams.w) {
            rect[0] = parsedParams.w;
        }
        if (parsedParams.h) {
            rect[1] = parsedParams.h;
        };
    }
    if (autostart) {
        _params_ = _u.injectIfNotPresent(_params_, "t", 0);
    }
    if (loop) {
        _params_ = _u.injectIfNotPresent(_params_, "r", 1);
    }

    var _snapshotUrl_ = amazonDomain + '/' + filename + (_params_ || '');

    var temp_v = null;
    if (temp_v = _u.extractVal(_params_, 'v')) {
        if (!temp_v.match(VERSION_MASK)) {
            _u.reportError(new Error('Player Version ID \'' + temp_v + '\' is incorrect'));
            return;
        }

        PLAYER_VERSION_ID = temp_v;
    }

    return function () {
        try {
            if (!inIFrame && !rect) {
                document.body.className = 'no-iframe no-rect';
            } else if (!inIFrame) {
                document.body.className = 'no-iframe';
            }
            var stylesTag = document.createElement('style');
            stylesTag.type = 'text/css';

            var head = document.getElementsByTagName("head")[0];
            if (!head) throw new Error('No head element in document');
            head.appendChild(stylesTag);

            var styles = stylesTag.sheet,
                rules = styles.cssRules || styles.rules;

            var noIFrameRule = rules[(styles.insertRule || styles.addRule).call(styles,
                                     'body.no-iframe .anm-wrapper {}', rules.length)],
                noRectRule   = rules[(styles.insertRule || styles.addRule).call(styles,
                                     'body.no-rect .anm-wrapper {}', rules.length)],
                noPlayerRule = rules[(styles.insertRule || styles.addRule).call(styles,
                                     'body.no-iframe canvas#target:not([anm-player]) {}', rules.length)],
                // there is a version of player where `anm-state-loading` and `anm-state-resources-loading` classes
                // were incorrectly named `anm-loading`, `anm-resources-loading`, this case is temporary (!) hacked out here
                wrapperRule  = rules[(styles.insertRule || styles.addRule).call(styles,
                                     'body.no-iframe div.anm-state-nothing, body.no-iframe div.anm-state-error, '+
                                     'body.no-iframe div.anm-loading, body.no-iframe div.anm-state-loading, ' +
                                     'body.no-iframe div.anm-resources-loading, body.no-iframe div.anm-state-resources-loading ' +
                                     '{}', rules.length)];

            function ruleForWrapperStyle(rule) {
                rule.style.borderWidth = '1px';
                rule.style.borderStyle = 'solid';
                rule.style.borderColor = '#ccc';
                rule.style.display = 'block';
                rule.style.position = 'absolute';
                rule.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.5)';
                rule.style.overflow = 'hidden';
            }

            ruleForWrapperStyle(noIFrameRule);
            ruleForWrapperStyle(noPlayerRule);
            ruleForWrapperStyle(wrapperRule);

            if (rect) {
                function ruleForCanvasPosition(rule) {
                    rule.style.width = rect[0] + 'px';
                    rule.style.height = rect[1] + 'px';
                    if (!inIFrame) {
                        rule.style.top  = '50%';
                        rule.style.left = '50%';
                        rule.style.marginLeft = -Math.floor(rect[0] / 2) + 'px';
                        rule.style.marginTop  = -Math.floor(rect[1] / 2) + 'px';
                    }
                }

                ruleForCanvasPosition(noIFrameRule);
                ruleForCanvasPosition(noPlayerRule);
            }

            noRectRule.style.top  = '10%';
            noRectRule.style.left = '10%';

            if (rect) {
                var target = document.getElementById(TARGET_ID);
                target.style.width  = rect[0] + 'px';
                target.style.height = rect[1] + 'px';
            }

            _u.forcedJS(PROTOCOL + playerDomain + '/' + PLAYER_VERSION_ID + '/bundle/animatron.min.js',
                function () {
                      anm.Player.forSnapshot(TARGET_ID, _snapshotUrl_, anm.createImporter('animatron'));
                }
            );
        } catch (e) {
            _u.reportError(e);
        }
    }

})();
<|endoftext|>


<commit_before>'use strict';
var Posts = module.parent.parent.require('./posts');
var Settings = module.parent.parent.require('./settings');
var Meta = module.parent.parent.require('./meta');
var Controllers = {};

Controllers.getPost = function(req, res, next){
			console.log("err:",err);
		var allowOrigin = mySettings.origins.split(',').map(function(value){
			return value.trim();
		});
		if(allowOrigin.includes(req.headers.origin) || mySettings.onlyxhr=="off"){
			res.header("Access-Control-Allow-Origin", req.headers.origin);
			res.header("Access-Control-Allow-Headers", "X-Requested-With");
			Posts.getPostData(req.params.pid,function(err,result){
				res.send(result);
			});
		}else{
			res.send("permission denied");
		}
	});
};
Controllers.renderAdminPage = function (req, res, next) {
	res.render('admin/plugins/ccmtpostinfo', {});
};
Controllers.categoriesPage = function(req, res, next){
	var defaultSetting = {};
	var mySettings = Meta.settings.get('ccmtpostinfo', function(err,mySettings){
		if(err)
			console.log("err:",err);
		res.render('plugins/ccmtpostinfo/categories', mySettings);
	});
}
module.exports = Controllers;

<commit_msg>fix single quote<commit_after>'use strict';
var Posts = module.parent.parent.require('./posts');
var Settings = module.parent.parent.require('./settings');
var Meta = module.parent.parent.require('./meta');
var Controllers = {};

Controllers.getPost = function(req, res, next){
	console.log("err:",err);
	var allowOrigin = mySettings.origins.split(',').map(function(value){
		return value.trim();
	});
	if(allowOrigin.includes(req.headers.origin) || mySettings.onlyxhr=="off"){
		res.header("Access-Control-Allow-Origin", req.headers.origin);
		res.header("Access-Control-Allow-Headers", "X-Requested-With");
		Posts.getPostData(req.params.pid,function(err,result){
			res.send(result);
		});
	}else{
		res.send("permission denied");
	}
};

Controllers.renderAdminPage = function (req, res, next) {
	res.render('admin/plugins/ccmtpostinfo', {});
};

Controllers.categoriesPage = function(req, res, next){
	var defaultSetting = {};
	var mySettings = Meta.settings.get('ccmtpostinfo', function(err,mySettings){
		if(err)
		console.log("err:",err);
		res.render('plugins/ccmtpostinfo/categories', mySettings);
	});
}
module.exports = Controllers;

<|endoftext|>


<commit_before>//Kanye Quest

// MAKE BRANCH FOR:
//(PROM EDITION) - 3 keys, once collected go to boss door
//                 Fight enemy to save princess, defeat
//                 enemy,
//(SPACE THEMED) - Explore the universe and go to prom with me (or something like that I guess)

var GRAVITY = .4; //Constant
var JUMP = -10; //constant
var GROUND, BG, PLAYER, BOSS_CASTLE, ENEMIES, FIRE, STRUCTURES, CLOUDS; //Sprites
var GroundImg, BgImg, PlayerImg, EnemyImg, FireImg; //Images

var FireCounter = 100;
var FireStatus;
var PlayerHealth = 100;
function preload() {

    // GroundImg = loadImage('http://i.imgur.com/p6L1baG.png');
    // FireImg = loadImage('http://i.imgur.com/0NUZboL.png');
    // PlayerImg = loadImage('http://i.imgur.com/AljRUIL.png');

}

function setup() {
  createCanvas(700,600);
  //Length of game strip: 4,000 pixels
  //start @ x = 0
  //end @ x = 4000

  //Sizing is tmp for mechanics:      width height
  GROUND = createSprite(width/2, 550, 1400, 100);
  // GROUND.addImage(GroundImg);

  //BG = createSprite();

  PLAYER = createSprite(width/2, 475, 50, 50);
  // PLAYER.addImage(PlayerImg);
  PLAYER.setCollider("circle", 0,0,50);

  BOSS_CASTLE = createSprite(3500, 475, 400, 400);
  BOSS_CASTLE.setCollider();

  FireStatus = createSprite(125, 50, 200, 50);
  PlayerHealth = createSprite(125, 110, 200, 50);

  ENEMIES = new Group();
  FIRE = new Group();
  STRUCTURES = new Group();
  CLOUDS = new Group();

}

function draw() {
  background(100, 150, 200);
  textAlign(CENTER);
  PLAYER.velocity.y += GRAVITY;

  //Player GUI movement
  FireStatus.position.x = camera.position.x + (FireCounter - 100) - width/2 + 125;
  PlayerHealth.position.x = camera.position.x - width/2 + 125;

  FireStatus.width = FireCounter * 2;

  FireStatus.depth = 3;
  PlayerHealth.depth = 3;
  //PLAYER and CAMERA bounds
    //  Says that CAMERA will always follow PLAYER except out of bounds
  if(PLAYER.position.x >= 3850){
    camera.position.x = 3850;
  } else if(PLAYER.position.x <= 350){
    camera.position.x = 350;
  } else {
    camera.position.x = PLAYER.position.x;
  }

    //  bounding for PLAYER
  if(PLAYER.position.x < 50) {
    PLAYER.position.x = 50;
  } else if(PLAYER.position.x > 3850) {
    PLAYER.position.x = 3850;
  }

  if(PLAYER.position.y < 250) {
     PLAYER.position.y = 250;
  }

  /*

  End of PLAYER | CAMERA | GUI bounding

  */

  //Wrap ground

    //  My better-than-alex's attempt to get the ground to wrap with movement
  if(camera.position.x > GROUND.position.x + width / 4) {
    GROUND.position.x += GROUND.width / 6;
  } else if(camera.position.x < GROUND.position.x - width / 4) {
    GROUND.position.x -= GROUND.width / 6;
  }
  /*

  End of ground wrapping.

  */

  //Abilities

    //  Left | Right
  if(keyDown(65)) {
    PLAYER.position.x -= playerStep;
    PLAYER.mirrorX(1);
  } else if(keyDown(68)) {
    PLAYER.position.x += playerStep;
    PLAYER.mirrorX(-1);
  }

    //  Jump
  if(keyWentDown(87)) {
    PLAYER.velocity.y = JUMP;
  }

    //  Sprinting
  if(keyDown(16)) { //SHIFT keycode = 16
    playerStep = 9;
  } else {
    playerStep = 4;
  }

  if(FireCounter < 100) {
    FireCounter += .1;
  }

  //  Player spits fire
  if(keyWentDown(32) && FireCounter >= 10) {
      var fire = createSprite(PLAYER.position.x - 20 * PLAYER.mirrorX(), PLAYER.position.y);
      //fire.addImage(FireImg);
      fire.life = 40;
      fire.setSpeed(-(11 + playerStep) * PLAYER.mirrorX(), 0);
      fire.mirrorX(-1 * PLAYER.mirrorX());
      FIRE.add(fire);

      FireCounter -= 10;
  }

  //Prevents player from falling through ground (?)
  if(PLAYER.collide(GROUND)) {
    PLAYER.velocity.y = 0;
  }

  /*

  End of PLAYER code.

  */

  //Check values here
  console.log("FireStatus.position.x: " + FireStatus.position.x);

  //Environment sprites

    //  Create Enemies
  for(var i = ENEMIES.length; i < 2; i++) {
    var posX = random(PLAYER.position.x - (width/2), PLAYER.position.x + (width/2));
    var posY = 475;
    createEnemy(posX, posY);

    // if(ENEMIES.get(i).overlap(STRUCTURES)) {
    //   if(ENEMIES.get(i).getDirection == 180) {
    //     ENEMIES.get(i).setSpeed(1, 0);
    //   } else {
    //     ENEMIES.get(i).setSpeed(-1, 0)
    //   }
    // }
  }

    //  Remove Enemies
  for (var i = 0; i < ENEMIES.length; i++) {
    if(ENEMIES[i].position.x + (ENEMIES[i].width / 2) < PLAYER.position.x - (width / 2) || ENEMIES[i].position.x - (ENEMIES[i].width / 2) > PLAYER.position.x + (width / 2)) {
      ENEMIES[i].remove();
    }
  }

    //  Structures
  if(frameCount % 60 == 0) {

  }

  var min = camera.position.x - width / 2 - 75;
  var max = camera.position.x + width / 2 + 75;

  //Clouds

    //  Create Clouds
  for(var i = CLOUDS.length; i < 21; i++) {

    var posY = random(height / 3, 0);

    if(i <= 10) {
      // generates an x position that is onscreen
      var posX = random(min, max);

    } else {
      // generates an x position to the next screen over, depending on which way the player is facing
      var posX = random(min - width * PLAYER.mirrorX(), max - width * PLAYER.mirrorX());
    }
    createCloud(posX, posY);
  }

    //  Remove Clouds
  for(var i = 0; i < CLOUDS.length; i++) {
    if(CLOUDS[i].position.x + (CLOUDS[i].width / 2) < min - width - (width * PLAYER.mirrorX()) || CLOUDS[i].position.x - (CLOUDS[i].width / 2) > max + width - (width * PLAYER.mirrorX())) {
      CLOUDS[i].remove();
    }
  }

  //Debug
  GROUND.debug = true;
  PLAYER.debug = true;
  BOSS_CASTLE.debug = true;

  drawSprites();
}

//Creates an enemy
function createEnemy(x, y) {
  var enemy = createSprite(x, y, 50, 50);
  //add img for enemy here (?)

  enemy.setSpeed(-1, 0);
  enemy.debug = true;
  enemy.setCollider("circle", 0,0,50);
  ENEMIES.add(enemy);

  return enemy;
}

//Creates a cloud
function createCloud(x, y) {
  var newCloud = createSprite(x ,y, random(50, 75), random(16, 32));
      newCloud.depth = y / 100;
  // newCloud.setCollider("rectangle");
  CLOUDS.add(newCloud);

  return newCloud;
}
<commit_msg>0.33<commit_after>//Kanye Quest

// MAKE BRANCH FOR:
//(PROM EDITION) - 3 keys, once collected go to boss door
//                 Fight enemy to save princess, defeat
//                 enemy,
//(SPACE THEMED) - Explore the universe and go to prom with me (or something like that I guess)

var GRAVITY = .4; //Constant
var JUMP = -10; //constant
var GROUND, BG, PLAYER, BOSS_CASTLE, ENEMIES, FIRE, STRUCTURES, CLOUDS; //Sprites
var GroundImg, BgImg, PlayerImg, EnemyImg, FireImg; //Images

var FireCounter = 100;
var FireStatus;
var PlayerHealth = 100;
var EnemyHealth;
function preload() {

    // GroundImg = loadImage('http://i.imgur.com/p6L1baG.png');
    // FireImg = loadImage('http://i.imgur.com/0NUZboL.png');
    // PlayerImg = loadImage('http://i.imgur.com/AljRUIL.png');

}

function setup() {
  createCanvas(700,600);
  //Length of game strip: 4,000 pixels
  //start @ x = 0
  //end @ x = 4000

  //Sizing is tmp for mechanics:      width height
  GROUND = createSprite(width/2, 550, 1400, 100);
  // GROUND.addImage(GroundImg);

  //BG = createSprite();

  PLAYER = createSprite(width/2, 475, 50, 50);
  // PLAYER.addImage(PlayerImg);
  PLAYER.setCollider("circle", 0,0,50);

  BOSS_CASTLE = createSprite(3500, 475, 400, 400);
  BOSS_CASTLE.setCollider();

  FireStatus = createSprite(125, 50, 200, 50);
  PlayerHealth = createSprite(125, 110, 200, 50);

  ENEMIES = new Group();
  FIRE = new Group();
  STRUCTURES = new Group();
  CLOUDS = new Group();

  EnemyHealth = new Group();

}

function draw() {
  background(100, 150, 200);
  textAlign(CENTER);
  PLAYER.velocity.y += GRAVITY;

  //Player GUI movement
  FireStatus.position.x = camera.position.x + (FireCounter - 100) - width/2 + 125;
  PlayerHealth.position.x = camera.position.x - width/2 + 125;

  FireStatus.width = FireCounter * 2;

  FireStatus.depth = 3;
  PlayerHealth.depth = 3;
  //PLAYER and CAMERA bounds
    //  Says that CAMERA will always follow PLAYER except out of bounds
  if(PLAYER.position.x >= 3850){
    camera.position.x = 3850;
  } else if(PLAYER.position.x <= 350){
    camera.position.x = 350;
  } else {
    camera.position.x = PLAYER.position.x;
  }

    //  bounding for PLAYER
  if(PLAYER.position.x < 50) {
    PLAYER.position.x = 50;
  } else if(PLAYER.position.x > 3850) {
    PLAYER.position.x = 3850;
  }

  if(PLAYER.position.y < 250) {
     PLAYER.position.y = 250;
  }

  /*

  End of PLAYER | CAMERA | GUI bounding

  */

  //Wrap ground

    //  My better-than-alex's attempt to get the ground to wrap with movement
  if(camera.position.x > GROUND.position.x + width / 4) {
    GROUND.position.x += GROUND.width / 6;
  } else if(camera.position.x < GROUND.position.x - width / 4) {
    GROUND.position.x -= GROUND.width / 6;
  }
  /*

  End of ground wrapping.

  */

  //Abilities

    //  Left | Right
  if(keyDown(65)) {
    PLAYER.position.x -= playerStep;
    PLAYER.mirrorX(1);
  } else if(keyDown(68)) {
    PLAYER.position.x += playerStep;
    PLAYER.mirrorX(-1);
  }

    //  Jump
  if(keyWentDown(87)) {
    PLAYER.velocity.y = JUMP;
  }

    //  Sprinting
  if(keyDown(16)) { //SHIFT keycode = 16
    playerStep = 9;
  } else {
    playerStep = 4;
  }

  if(FireCounter < 100) {
    FireCounter += .1;
  }

  //  Player spits fire
  if(keyWentDown(32) && FireCounter >= 10) {
      var fire = createSprite(PLAYER.position.x - 20 * PLAYER.mirrorX(), PLAYER.position.y);
      //fire.addImage(FireImg);
      fire.life = 40;
      fire.setSpeed(-(11 + playerStep) * PLAYER.mirrorX(), 0);
      fire.mirrorX(-1 * PLAYER.mirrorX());
      FIRE.add(fire);

      FireCounter -= 10;
  }

  //Prevents player from falling through ground (?)
  if(PLAYER.collide(GROUND)) {
    PLAYER.velocity.y = 0;
  }

  /*

  End of PLAYER code.

  */

  //Check values here
  console.log("FireStatus.position.x: " + FireStatus.position.x);

  //Environment sprites

    //  Create Enemies
  for(var i = ENEMIES.length; i < 2; i++) {
    var posXenemy = random(PLAYER.position.x - (width/2), PLAYER.position.x + (width/2));
    var posYenemy = 475;
    createEnemy(posXenemy, posYenemy);
  }

    //  Create EnemyHealth
  for(var i = 0; i < ENEMIES.length; i++) {
    if(PLAYER.position.x <= ENEMIES[i].position.x + 50 || PLAYER.position.x >= ENEMIES[i].position - 50) {
      var posX = ENEMIES[i].position.x;
      var posY = ENEMIES[i].position.y - 40;
      var w = 50;
      var h = 10;
      for(var j = EnemyHealth.length; j < 2; j++) {
        createEnemyHealth(posX, posY, w, h);
        if(PLAYER.position.x > ENEMIES[i].position.x + 50 || PLAYER.position.x < ENEMIES[i].position - 50) {
          EnemyHealth[i].remove();
        }
      }
    }
  }

    //  Remove Enemies
  for (var i = 0; i < ENEMIES.length; i++) {
    if(ENEMIES[i].position.x + (ENEMIES[i].width / 2) < PLAYER.position.x - (width / 2) || ENEMIES[i].position.x - (ENEMIES[i].width / 2) > PLAYER.position.x + (width / 2)) {
      ENEMIES[i].remove();
    }
  }

  var min = camera.position.x - width / 2 - 75;
  var max = camera.position.x + width / 2 + 75;

  //Clouds

    //  Create Clouds
  for(var i = CLOUDS.length; i < 21; i++) {

    var posY = random(height / 3, 0);

    if(i <= 10) {
      // generates an x position that is onscreen
      var posX = random(min, max);

    } else {
      // generates an x position to the next screen over, depending on which way the player is facing
      var posX = random(min - width * PLAYER.mirrorX(), max - width * PLAYER.mirrorX());
    }
    createCloud(posX, posY);
  }

    //  Remove Clouds
  for(var i = 0; i < CLOUDS.length; i++) {
    if(CLOUDS[i].position.x + (CLOUDS[i].width / 2) < min - width - (width * PLAYER.mirrorX()) || CLOUDS[i].position.x - (CLOUDS[i].width / 2) > max + width - (width * PLAYER.mirrorX())) {
      CLOUDS[i].remove();
    }
  }

  //Debug
  GROUND.debug = true;
  PLAYER.debug = true;
  BOSS_CASTLE.debug = true;

  drawSprites();
}

//Creates an enemy
function createEnemy(x, y) {
  var enemy = createSprite(x, y, 50, 50);
  //add img for enemy here (?)

  enemy.setSpeed(-1, 0);
  enemy.debug = true;
  enemy.setCollider("circle", 0,0,50);
  ENEMIES.add(enemy);

  return enemy;
}

function createEnemyHealth(x, y, w, h) {
  var newEnemyHealth = createSprite(x, y, w, h);

  newEnemyHealth.setSpeed(-1, 0);
  newEnemyHealth.debug = true;
  newEnemyHealth.setCollider("circle", 0, 0, 50);
  EnemyHealth.add(newEnemyHealth);

  return newEnemyHealth;
}

//Creates a cloud
function createCloud(x, y) {
  var newCloud = createSprite(x ,y, random(50, 75), random(16, 32));
      newCloud.depth = y / 100;
  // newCloud.setCollider("rectangle");
  CLOUDS.add(newCloud);

  return newCloud;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2014 by Animatron.
 * All rights are reserved.
 */

/* Variables we get from template:
   playerDomain — a URL to player domain host, e.g. player.animatron.com
   amazonDomain — a URL to snapshot storage host, e.g. http://snapshots.animatron.com/<snapshot-id>
   width — width of the animation
   height — height of the animation
   playerVersion — player version, default 'latest'
   filename — filename of snapshot, used as amazonDomain + filename
   autostart — (boolean) autostart of movie on player load
   loop — (boolean) loop animation instead of stoping at the end
   animation — JSON object of animatron movie (currently not used)
*/
(function($global, $window, $document) {
    var inIFrame = ($window.self !== $window.top);

    var autostart = $global['autostart'] || false,
        loop = $global['loop'] || false;

    var utils = {
        isInt: function(n) {
            n = Number(n);
            return !isNaN(n) && Math.floor(n) === n;
        },
        serializeToQueryString: function(obj) {
            var str = [];
            for(var p in obj) {
                if (obj.hasOwnProperty(p)) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
            }
            return str.join("&");
        },
        parseQueryString: function() {
            var queryString = location.search.substring(1);
            if (!queryString) {
                return {};
            }
            var queries = queryString.split("&"),
                params = {}, temp, i, l;
            for ( i = 0, l = queries.length; i < l; i++ ) {
                temp = queries[i].split('=');
                params[temp[0]] = temp[1];
            }
            return params;
        },
        getRequiredRect: function () {
            if (inIFrame) {
                return utils.getIframeSize();
            } else {
                return {w: width, h: height};
            }
        },
        getIframeSize: function () {
            var size = {w:0, h:0};
            if (typeof $window.innerWidth == 'number') {
                size.w = $window.innerWidth;
                size.h = $window.innerHeight;
            } else {
                size.w = $document.documentElement.clientWidth;
                size.h = $document.documentElement.clientHeight;
            }
            return size;
        },
        forcedJS: function (path, then) {
            var scriptElm = $document.createElement('script');
            scriptElm.type = 'text/javascript';
            scriptElm.async = 'async';
            scriptElm.src = path;
            scriptElm.onload = scriptElm.onreadystatechange = (function () {
                var success = false;
                return function () {
                    if (this.readyState === 'loading') {
                        return;
                    }
                    if (!success && (!this.readyState ||
                        (this.readyState === 'complete' || this.readyState === 'loaded')
                    )) {
                        success = true;
                        then();
                    } else if (!success && $window.console) {
                        console.error('Request failed: ' + this.readyState);
                    }
                };
            })();
            var headElm = $document.head || $document.getElementsByTagName('head')[0];
            headElm.appendChild(scriptElm);
        }
    };

    var TARGET_ID = 'target',
    WRAPPER_CLASS = 'anm-wrapper',
    PLAYER_VERSION_ID = playerVersion || 'latest';

    // options to apply just _after_ the snapshot was completely loaded are stored in the url (width and height in `params`)
    // initialization options are stored in `initOptions`
    var params = utils.parseQueryString(),
        initOptions = {},
        minified = params.nomin ? false : true;

    var rect = utils.getRequiredRect(),
        targetWidth, targetHeight;

    //floating-point w&h parameters mean percentage sizing
    if (params.w && !utils.isInt(params.w)) {
        targetWidth = params.w = Math.round(params.w * rect.w);
    } else {
        targetWidth = params.w = params.w || rect.w;
    }
    if (params.h && !utils.isInt(params.h)) {
        targetHeight = params.h = Math.round(params.h * rect.h);
    } else {
        targetHeight = params.h = params.h || rect.h;
    }

    if (autostart) initOptions.autoPlay = true;
    if (loop) initOptions.repeat = true;

    if (params.ver || params.version) { PLAYER_VERSION_ID = (params.ver || params.version); }
    if (params.stretch) initOptions.stretchToCanvas = true;

    var snapshotUrl = amazonDomain + '/' + filename + '?' +
        utils.serializeToQueryString(params);
    var thumbnailUrl = amazonDomain + '/' + filename.slice(0, filename.indexOf('.')) + '.jpg';

    initOptions.thumbnail = thumbnailUrl;

    var start = function () {
        try {
            if (!inIFrame) {
                $document.body.className ='no-iframe';
            } else {
                $document.body.style.overflow = 'hidden';
            }
            var target = $document.getElementById(TARGET_ID);
            target.style.width  = targetWidth + 'px';
            target.style.height = targetHeight + 'px';
            target.style.marginLeft = -Math.floor(targetWidth / 2) + 'px';
            target.style.marginTop  = -Math.floor(targetHeight / 2) + 'px';
            target.style.position = 'absolute';
            target.style.left = '50%';
            target.style.top = '50%';

            utils.forcedJS('//' + playerDomain + '/' + PLAYER_VERSION_ID + '/bundle/animatron' + (minified ? '.min' : '') + '.js',
                function () {
                    var player = anm.Player.forSnapshot(TARGET_ID, snapshotUrl, anm.importers.create('animatron'), $window.actions, initOptions);
                    if (anm.interop && anm.interop.playerjs) {
                        anm.interop.playerjs.setPlayer(player);
                    }
            });
        } catch (e) {
            if($window.console) console.error(e);
        }
    };

    $window.start = start;

})(this, window, document);
<commit_msg>[EDIT-18088] fixed. Tall project gets cut on publish (embed).<commit_after>/*
 * Copyright (c) 2011-2014 by Animatron.
 * All rights are reserved.
 */

/* Variables we get from template:
   playerDomain — a URL to player domain host, e.g. player.animatron.com
   amazonDomain — a URL to snapshot storage host, e.g. http://snapshots.animatron.com/<snapshot-id>
   width — width of the animation
   height — height of the animation
   playerVersion — player version, default 'latest'
   filename — filename of snapshot, used as amazonDomain + filename
   autostart — (boolean) autostart of movie on player load
   loop — (boolean) loop animation instead of stoping at the end
   animation — JSON object of animatron movie (currently not used)
*/
(function($global, $window, $document) {
    var inIFrame = ($window.self !== $window.top);

    var autostart = $global['autostart'] || false,
        loop = $global['loop'] || false;

    var utils = {
        isInt: function(n) {
            n = Number(n);
            return !isNaN(n) && Math.floor(n) === n;
        },
        serializeToQueryString: function(obj) {
            var str = [];
            for(var p in obj) {
                if (obj.hasOwnProperty(p)) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
            }
            return str.join("&");
        },
        parseQueryString: function() {
            var queryString = location.search.substring(1);
            if (!queryString) {
                return {};
            }
            var queries = queryString.split("&"),
                params = {}, temp, i, l;
            for ( i = 0, l = queries.length; i < l; i++ ) {
                temp = queries[i].split('=');
                params[temp[0]] = temp[1];
            }
            return params;
        },
        getRequiredRect: function () {
            if (inIFrame) {
                return utils.getIframeSize();
            } else {
                return {w: width, h: height};
            }
        },
        getIframeSize: function () {
            var size = {w:0, h:0};
            if (typeof $window.innerWidth == 'number') {
                size.w = $window.innerWidth;
                size.h = $window.innerHeight;
            } else {
                size.w = $document.documentElement.clientWidth;
                size.h = $document.documentElement.clientHeight;
            }
            return size;
        },
        forcedJS: function (path, then) {
            var scriptElm = $document.createElement('script');
            scriptElm.type = 'text/javascript';
            scriptElm.async = 'async';
            scriptElm.src = path;
            scriptElm.onload = scriptElm.onreadystatechange = (function () {
                var success = false;
                return function () {
                    if (this.readyState === 'loading') {
                        return;
                    }
                    if (!success && (!this.readyState ||
                        (this.readyState === 'complete' || this.readyState === 'loaded')
                    )) {
                        success = true;
                        then();
                    } else if (!success && $window.console) {
                        console.error('Request failed: ' + this.readyState);
                    }
                };
            })();
            var headElm = $document.head || $document.getElementsByTagName('head')[0];
            headElm.appendChild(scriptElm);
        }
    };

    var TARGET_ID = 'target',
    WRAPPER_CLASS = 'anm-wrapper',
    PLAYER_VERSION_ID = playerVersion || 'latest';

    // options to apply just _after_ the snapshot was completely loaded are stored in the url (width and height in `params`)
    // initialization options are stored in `initOptions`
    var params = utils.parseQueryString(),
        initOptions = {},
        minified = params.nomin ? false : true;

    var rect = utils.getRequiredRect(),
        targetWidth, targetHeight;

    //floating-point w&h parameters mean percentage sizing
    if (params.w && !utils.isInt(params.w)) {
        targetWidth = params.w = Math.round(params.w * rect.w);
    } else {
        targetWidth = params.w = params.w || rect.w;
    }
    if (params.h && !utils.isInt(params.h)) {
        targetHeight = params.h = Math.round(params.h * rect.h);
    } else {
        targetHeight = params.h = params.h || rect.h;
    }

    if (autostart) initOptions.autoPlay = true;
    if (loop) initOptions.repeat = true;

    if (params.ver || params.version) { PLAYER_VERSION_ID = (params.ver || params.version); }
    if (params.stretch) initOptions.stretchToCanvas = true;

    var snapshotUrl = amazonDomain + '/' + filename + '?' +
        utils.serializeToQueryString(params);
    var thumbnailUrl = amazonDomain + '/' + filename.slice(0, filename.indexOf('.')) + '.jpg';

    initOptions.thumbnail = thumbnailUrl;

    var start = function () {
        try {
            if (!inIFrame) {
                $document.body.className ='no-iframe';
            } else {
                $document.body.style.overflow = 'hidden';
            }
            var target = $document.getElementById(TARGET_ID);
            target.style.width  = targetWidth + 'px';
            target.style.height = targetHeight + 'px';
            target.style.marginLeft = -Math.floor(targetWidth / 2) + 'px';
            target.style.marginTop  = -Math.floor(window.innerHeight / 2) + 'px';
            target.style.position = 'absolute';
            target.style.left = '50%';
            target.style.top = '50%';

            utils.forcedJS('//' + playerDomain + '/' + PLAYER_VERSION_ID + '/bundle/animatron' + (minified ? '.min' : '') + '.js',
                function () {
                    var player = anm.Player.forSnapshot(TARGET_ID, snapshotUrl, anm.importers.create('animatron'), $window.actions, initOptions);
                    if (anm.interop && anm.interop.playerjs) {
                        anm.interop.playerjs.setPlayer(player);
                    }
            });
        } catch (e) {
            if($window.console) console.error(e);
        }
    };

    $window.start = start;

})(this, window, document);
<|endoftext|>