<commit_before>$(document).ready(function(){
$(function(){

$("#mainTable").tablesorter({

    // *** APPEARANCE ***
    // Add a theme - try 'blackice', 'blue', 'dark', 'default'
    //  'dropbox', 'green', 'grey' or 'ice'
    // to use 'bootstrap' or 'jui', you'll need to add the "uitheme"
    // widget and also set it to the same name
    // this option only adds a table class name "tablesorter-{theme}"
    theme: 'blackice',

    // fix the column widths
    widthFixed: false,

    // Show an indeterminate timer icon in the header when the table
    // is sorted or filtered
    showProcessing: false,

    // header layout template (HTML ok); {content} = innerHTML,
    // {icon} = <i/> (class from cssIcon)
    headerTemplate: '{content}{icon}',

    // return the modified template string
    onRenderTemplate: null, // function(index, template){ return template; },

    // called after each header cell is rendered, use index to target the column
    // customize header HTML
	onRenderHeader: function(index){
      // the TH content is wrapped with a div.tablesorter-header-inner by default, so just add the new class
      $(this).find('div').addClass('roundedCorners header' + index );
    },
    // *** FUNCTIONALITY ***
    // prevent text selection in header
    cancelSelection: true,

    // other options: "ddmmyyyy" & "yyyymmdd"
    dateFormat: "mmddyyyy",

    // The key used to select more than one column for multi-column
    // sorting.
    sortMultiSortKey: "shiftKey",

    // key used to remove sorting on a column
    sortResetKey: 'ctrlKey',

    // false for German "1.234.567,89" or French "1 234 567,89"
    usNumberFormat: true,

    // If true, parsing of all table cell data will be delayed
    // until the user initializes a sort
    delayInit: false,

    // if true, server-side sorting should be performed because
    // client-side sorting will be disabled, but the ui and events
    // will still be used.
    serverSideSorting: false,

    // *** SORT OPTIONS ***
    // These are detected by default,
    // but you can change or disable them
    // these can also be set using data-attributes or class names
    headers: {
        // set "sorter : false" (no quotes) to disable the column
        0: {
            sorter: "text"
        },
        1: {
            sorter: "text"
        },
        2: {
            sorter: "number"
        },
        3: {
            sorter: "number"
        },
		4: {
            sorter: "number"
        },
		5: {
            sorter: "number"
        },
		6: {
            sorter: "number"
        },
		7: {
            sorter: "number"
        },
		8: {
            sorter: "number"
        },
    },

    // ignore case while sorting
    ignoreCase: true,

    // forces the user to have this/these column(s) sorted first
    sortForce: null,

    // default sort that is added to the end of the users sort
    // selection.
    sortAppend: null,

    // starting sort direction "asc" or "desc"
    sortInitialOrder: "asc",

    // Replace equivalent character (accented characters) to allow
    // for alphanumeric sorting
    sortLocaleCompare: false,

    // third click on the header will reset column to default - unsorted
    sortReset: false,

    // restart sort to "sortInitialOrder" when clicking on previously
    // unsorted columns
    sortRestart: false,

    // sort empty cell to bottom, top, none, zero
    emptyTo: "bottom",

    // sort strings in numerical column as max, min, top, bottom, zero
    stringTo: "max",

    // use custom text sorter
    // function(a,b){ return a.sort(b); } // basic sort
    textSorter: null,

    // *** WIDGETS ***

    // apply widgets on tablesorter initialization
    initWidgets: true,

    // include zebra and any other widgets, options:
    // 'columns', 'filter', 'stickyHeaders' & 'resizable'
    // 'uitheme' is another widget, but requires loading
    // a different skin and a jQuery UI theme.
    widgets: ['zebra', 'columns','filter','scroller'],

    widgetOptions: {

        // zebra widget: adding zebra striping, using content and
        // default styles - the ui css removes the background
        // from default even and odd class names included for this
        // demo to allow switching themes
        // [ "even", "odd" ]
        zebra: [
            "ui-widget-content even",
            "ui-state-default odd"],

        // columns widget: change the default column class names
        // primary is the 1st column sorted, secondary is the 2nd, etc
        columns: [
            "primary",
            "secondary"],

        // columns widget: If true, the class names from the columns
        // option will also be added to the table tfoot.
        columns_tfoot: false,

        // columns widget: If true, the class names from the columns
        // option will also be added to the table thead.
        columns_thead: true,

        // filter widget: If there are child rows in the table (rows with
        // class name from "cssChildRow" option) and this option is true
        // and a match is found anywhere in the child row, then it will make
        // that row visible; default is false
        filter_childRows: false,

        // filter widget: If true, a filter will be added to the top of
        // each table column.
        filter_columnFilters: true,

        // filter widget: css class applied to the table row containing the
        // filters & the inputs within that row
        filter_cssFilter: "tablesorter-filter",

        // filter widget: Customize the filter widget by adding a select
        // dropdown with content, custom options or custom filter functions
        // see http://goo.gl/HQQLW for more details
        filter_functions: {
			 2 : {
          "< 10"      : function(e, n, f, i, $r, c, data) { return n < 10; },
          "10 - 100" : function(e, n, f, i, $r, c, data) { return n >= 10 && n <=100; },
          "100 - 1000"     : function(e, n, f, i, $r, c, data) { return n >= 100 && n <=1000; },
          "1000 - 10000"     : function(e, n, f, i, $r, c, data) { return n >= 1000 && n <=10000; },
		  "> 10000"     : function(e, n, f, i, $r, c, data) { return n > 10000; }
		},
		// Total (jQuery selector added v2.17.0)
			3 : function($cell, indx){
          return $.tablesorter.filterFormatter.uiRange( $cell, indx, {
            delayed : false,
            valueToHeader : false,
            // jQuery UI slider options
            values : [0, 10],
            min : 1,
            max : 10+
          });
        },

		},

        // filter widget: Set this option to true to hide the filter row
        // initially. The rows is revealed by hovering over the filter
        // row or giving any filter input/select focus.
        filter_hideFilters: false,

        // filter widget: Set this option to false to keep the searches
        // case sensitive
        filter_ignoreCase: true,

        // filter widget: jQuery selector string of an element used to
        // reset the filters.
        filter_reset: null,

        // Delay in milliseconds before the filter widget starts searching;
        // This option prevents searching for every character while typing
        // and should make searching large tables faster.
        filter_searchDelay: 300,

        // Set this option to true if filtering is performed on the server-side.
        filter_serversideFiltering: false,

        // filter widget: Set this option to true to use the filter to find
        // text from the start of the column. So typing in "a" will find
        // "albert" but not "frank", both have a's; default is false
        filter_startsWith: false,

        // filter widget: If true, ALL filter searches will only use parsed
        // data. To only use parsed data in specific columns, set this option
        // to false and add class name "filter-parsed" to the header
        filter_useParsedData: false,

        // Resizable widget: If this option is set to false, resized column
        // widths will not be saved. Previous saved values will be restored
        // on page reload
        resizable: true,

        // saveSort widget: If this option is set to false, new sorts will
        // not be saved. Any previous saved sort will be restored on page
        // reload.
        saveSort: true,

        // stickyHeaders widget: css class name applied to the sticky header
        stickyHeaders: "tablesorter-stickyHeader",

		scroller_height : 300,
		// scroll tbody to top after sorting
		scroller_upAfterSort: true,
		// pop table header into view while scrolling up the page
		scroller_jumpToHeader: true,
		// In tablesorter v2.19.0 the scroll bar width is auto-detected
		// add a value here to override the auto-detected setting
		scroller_barWidth : null
		// scroll_idPrefix was removed in v2.18.0
		// scroller_idPrefix : 's_'

    },

    // *** CALLBACKS ***
    // function called after tablesorter has completed initialization
    initialized: function (table) {},

    // *** CSS CLASS NAMES ***
    tableClass: 'tablesorter',
    cssAsc: "tablesorter-headerSortUp",
    cssDesc: "tablesorter-headerSortDown",
    cssHeader: "tablesorter-header",
    cssHeaderRow: "tablesorter-headerRow",
    cssIcon: "tablesorter-icon",
    cssChildRow: "tablesorter-childRow",
    cssInfoBlock: "tablesorter-infoOnly",
    cssProcessing: "tablesorter-processing",

    // *** SELECTORS ***
    // jQuery selectors used to find the header cells.
    selectorHeaders: '> thead th, > thead td',

    // jQuery selector of content within selectorHeaders
    // that is clickable to trigger a sort.
    selectorSort: "th, td",

    // rows with this class name will be removed automatically
    // before updating the table cache - used by "update",
    // "addRows" and "appendCache"
    selectorRemove: "tr.remove-me",

    // *** DEBUGING ***
    // send messages to console
    debug: false

}).tablesorterPager({

    // target the pager markup - see the HTML block below
    container: $(".pager"),

    // use this url format "http:/mydatabase.com?page={page}&size={size}"
    ajaxUrl: null,

    // process ajax so that the data object is returned along with the
    // total number of rows; example:
    // {
    //   "data" : [{ "ID": 1, "Name": "Foo", "Last": "Bar" }],
    //   "total_rows" : 100
    // }
    ajaxProcessing: function(ajax) {
        if (ajax && ajax.hasOwnProperty('data')) {
            // return [ "data", "total_rows" ];
            return [ajax.data, ajax.total_rows];
        }
    },

    // output string - default is '{page}/{totalPages}';
    // possible variables:
    // {page}, {totalPages}, {startRow}, {endRow} and {totalRows}
    output: '{startRow} to {endRow} ({totalRows})',

    // apply disabled classname to the pager arrows when the rows at
    // either extreme is visible - default is true
    updateArrows: true,

    // starting page of the pager (zero based index)
    page: 0,

    // Number of visible rows - default is 10
    size: 10,

    // if true, the table will remain the same height no matter how many
    // records are displayed. The space is made up by an empty
    // table row set to a height to compensate; default is false
    fixedHeight: false,

    // remove rows from the table to speed up the sort of large tables.
    // setting this to false, only hides the non-visible rows; needed
    // if you plan to add/remove rows with the pager enabled.
    removeRows: false,

    // css class names of pager arrows
    // next page arrow
    cssNext: '.next',
    // previous page arrow
    cssPrev: '.prev',
    // go to first page arrow
    cssFirst: '.first',
    // go to last page arrow
    cssLast: '.last',
    // select dropdown to allow choosing a page
    cssGoto: '.gotoPage',
    // location of where the "output" is displayed
    cssPageDisplay: '.pagedisplay',
    // dropdown that sets the "size" option
    cssPageSize: '.pagesize',
    // class added to arrows when at the extremes
    // (i.e. prev/first arrows are "disabled" when on the first page)
    // Note there is no period "." in front of this class name
    cssDisabled: 'disabled'

});

// Extend the themes to change any of the default class names ** NEW **
$.extend($.tablesorter.themes.jui, {
    // change default jQuery uitheme icons - find the full list of icons
    // here: http://jqueryui.com/themeroller/ (hover over them for their name)
    table: 'ui-widget ui-widget-content ui-corner-all', // table classes
    header: 'ui-widget-header ui-corner-all ui-state-default', // header classes
    icons: 'ui-icon', // icon class added to the <i> in the header
    sortNone: 'ui-icon-carat-2-n-s',
    sortAsc: 'ui-icon-carat-1-n',
    sortDesc: 'ui-icon-carat-1-s',
    active: 'ui-state-active', // applied when column is sorted
    hover: 'ui-state-hover', // hover class
    filterRow: '',
    even: 'ui-widget-content', // even row zebra striping
    odd: 'ui-state-default' // odd row zebra striping
});

});
});

<commit_msg>edit range<commit_after>$(document).ready(function(){
$(function(){

$("#mainTable").tablesorter({

    // *** APPEARANCE ***
    // Add a theme - try 'blackice', 'blue', 'dark', 'default'
    //  'dropbox', 'green', 'grey' or 'ice'
    // to use 'bootstrap' or 'jui', you'll need to add the "uitheme"
    // widget and also set it to the same name
    // this option only adds a table class name "tablesorter-{theme}"
    theme: 'blackice',

    // fix the column widths
    widthFixed: false,

    // Show an indeterminate timer icon in the header when the table
    // is sorted or filtered
    showProcessing: false,

    // header layout template (HTML ok); {content} = innerHTML,
    // {icon} = <i/> (class from cssIcon)
    headerTemplate: '{content}{icon}',

    // return the modified template string
    onRenderTemplate: null, // function(index, template){ return template; },

    // called after each header cell is rendered, use index to target the column
    // customize header HTML
	onRenderHeader: function(index){
      // the TH content is wrapped with a div.tablesorter-header-inner by default, so just add the new class
      $(this).find('div').addClass('roundedCorners header' + index );
    },
    // *** FUNCTIONALITY ***
    // prevent text selection in header
    cancelSelection: true,

    // other options: "ddmmyyyy" & "yyyymmdd"
    dateFormat: "mmddyyyy",

    // The key used to select more than one column for multi-column
    // sorting.
    sortMultiSortKey: "shiftKey",

    // key used to remove sorting on a column
    sortResetKey: 'ctrlKey',

    // false for German "1.234.567,89" or French "1 234 567,89"
    usNumberFormat: true,

    // If true, parsing of all table cell data will be delayed
    // until the user initializes a sort
    delayInit: false,

    // if true, server-side sorting should be performed because
    // client-side sorting will be disabled, but the ui and events
    // will still be used.
    serverSideSorting: false,

    // *** SORT OPTIONS ***
    // These are detected by default,
    // but you can change or disable them
    // these can also be set using data-attributes or class names
    headers: {
        // set "sorter : false" (no quotes) to disable the column
        0: {
            sorter: "text"
        },
        1: {
            sorter: "text"
        },
        2: {
            sorter: "number"
        },
        3: {
            sorter: "number"
        },
		4: {
            sorter: "number"
        },
		5: {
            sorter: "number"
        },
		6: {
            sorter: "number"
        },
		7: {
            sorter: "number"
        },
		8: {
            sorter: "number"
        },
    },

    // ignore case while sorting
    ignoreCase: true,

    // forces the user to have this/these column(s) sorted first
    sortForce: null,

    // default sort that is added to the end of the users sort
    // selection.
    sortAppend: null,

    // starting sort direction "asc" or "desc"
    sortInitialOrder: "asc",

    // Replace equivalent character (accented characters) to allow
    // for alphanumeric sorting
    sortLocaleCompare: false,

    // third click on the header will reset column to default - unsorted
    sortReset: false,

    // restart sort to "sortInitialOrder" when clicking on previously
    // unsorted columns
    sortRestart: false,

    // sort empty cell to bottom, top, none, zero
    emptyTo: "bottom",

    // sort strings in numerical column as max, min, top, bottom, zero
    stringTo: "max",

    // use custom text sorter
    // function(a,b){ return a.sort(b); } // basic sort
    textSorter: null,

    // *** WIDGETS ***

    // apply widgets on tablesorter initialization
    initWidgets: true,

    // include zebra and any other widgets, options:
    // 'columns', 'filter', 'stickyHeaders' & 'resizable'
    // 'uitheme' is another widget, but requires loading
    // a different skin and a jQuery UI theme.
    widgets: ['zebra', 'columns','filter','scroller'],

    widgetOptions: {

        // zebra widget: adding zebra striping, using content and
        // default styles - the ui css removes the background
        // from default even and odd class names included for this
        // demo to allow switching themes
        // [ "even", "odd" ]
        zebra: [
            "ui-widget-content even",
            "ui-state-default odd"],

        // columns widget: change the default column class names
        // primary is the 1st column sorted, secondary is the 2nd, etc
        columns: [
            "primary",
            "secondary"],

        // columns widget: If true, the class names from the columns
        // option will also be added to the table tfoot.
        columns_tfoot: false,

        // columns widget: If true, the class names from the columns
        // option will also be added to the table thead.
        columns_thead: true,

        // filter widget: If there are child rows in the table (rows with
        // class name from "cssChildRow" option) and this option is true
        // and a match is found anywhere in the child row, then it will make
        // that row visible; default is false
        filter_childRows: false,

        // filter widget: If true, a filter will be added to the top of
        // each table column.
        filter_columnFilters: true,

        // filter widget: css class applied to the table row containing the
        // filters & the inputs within that row
        filter_cssFilter: "tablesorter-filter",

        // filter widget: Customize the filter widget by adding a select
        // dropdown with content, custom options or custom filter functions
        // see http://goo.gl/HQQLW for more details
        filter_functions: {
			 2 : {
          "< 10"      : function(e, n, f, i, $r, c, data) { return n < 10; },
          "10 - 100" : function(e, n, f, i, $r, c, data) { return n >= 10 && n <=100; },
          "100 - 1000"     : function(e, n, f, i, $r, c, data) { return n >= 100 && n <=1000; },
          "1000 - 10000"     : function(e, n, f, i, $r, c, data) { return n >= 1000 && n <=10000; },
		  "> 10000"     : function(e, n, f, i, $r, c, data) { return n > 10000; }
		},
		// Total (jQuery selector added v2.17.0)
			3 : function($cell, indx){
          return $.tablesorter.filterFormatter.uiRange( $cell, indx, {
            delayed : false,
            valueToHeader : false,
            // jQuery UI slider options
            values : [0, 100],
            min : 1,
            max : 100
          });
        },

		},

        // filter widget: Set this option to true to hide the filter row
        // initially. The rows is revealed by hovering over the filter
        // row or giving any filter input/select focus.
        filter_hideFilters: false,

        // filter widget: Set this option to false to keep the searches
        // case sensitive
        filter_ignoreCase: true,

        // filter widget: jQuery selector string of an element used to
        // reset the filters.
        filter_reset: null,

        // Delay in milliseconds before the filter widget starts searching;
        // This option prevents searching for every character while typing
        // and should make searching large tables faster.
        filter_searchDelay: 300,

        // Set this option to true if filtering is performed on the server-side.
        filter_serversideFiltering: false,

        // filter widget: Set this option to true to use the filter to find
        // text from the start of the column. So typing in "a" will find
        // "albert" but not "frank", both have a's; default is false
        filter_startsWith: false,

        // filter widget: If true, ALL filter searches will only use parsed
        // data. To only use parsed data in specific columns, set this option
        // to false and add class name "filter-parsed" to the header
        filter_useParsedData: false,

        // Resizable widget: If this option is set to false, resized column
        // widths will not be saved. Previous saved values will be restored
        // on page reload
        resizable: true,

        // saveSort widget: If this option is set to false, new sorts will
        // not be saved. Any previous saved sort will be restored on page
        // reload.
        saveSort: true,

        // stickyHeaders widget: css class name applied to the sticky header
        stickyHeaders: "tablesorter-stickyHeader",

		scroller_height : 300,
		// scroll tbody to top after sorting
		scroller_upAfterSort: true,
		// pop table header into view while scrolling up the page
		scroller_jumpToHeader: true,
		// In tablesorter v2.19.0 the scroll bar width is auto-detected
		// add a value here to override the auto-detected setting
		scroller_barWidth : null
		// scroll_idPrefix was removed in v2.18.0
		// scroller_idPrefix : 's_'

    },

    // *** CALLBACKS ***
    // function called after tablesorter has completed initialization
    initialized: function (table) {},

    // *** CSS CLASS NAMES ***
    tableClass: 'tablesorter',
    cssAsc: "tablesorter-headerSortUp",
    cssDesc: "tablesorter-headerSortDown",
    cssHeader: "tablesorter-header",
    cssHeaderRow: "tablesorter-headerRow",
    cssIcon: "tablesorter-icon",
    cssChildRow: "tablesorter-childRow",
    cssInfoBlock: "tablesorter-infoOnly",
    cssProcessing: "tablesorter-processing",

    // *** SELECTORS ***
    // jQuery selectors used to find the header cells.
    selectorHeaders: '> thead th, > thead td',

    // jQuery selector of content within selectorHeaders
    // that is clickable to trigger a sort.
    selectorSort: "th, td",

    // rows with this class name will be removed automatically
    // before updating the table cache - used by "update",
    // "addRows" and "appendCache"
    selectorRemove: "tr.remove-me",

    // *** DEBUGING ***
    // send messages to console
    debug: false

}).tablesorterPager({

    // target the pager markup - see the HTML block below
    container: $(".pager"),

    // use this url format "http:/mydatabase.com?page={page}&size={size}"
    ajaxUrl: null,

    // process ajax so that the data object is returned along with the
    // total number of rows; example:
    // {
    //   "data" : [{ "ID": 1, "Name": "Foo", "Last": "Bar" }],
    //   "total_rows" : 100
    // }
    ajaxProcessing: function(ajax) {
        if (ajax && ajax.hasOwnProperty('data')) {
            // return [ "data", "total_rows" ];
            return [ajax.data, ajax.total_rows];
        }
    },

    // output string - default is '{page}/{totalPages}';
    // possible variables:
    // {page}, {totalPages}, {startRow}, {endRow} and {totalRows}
    output: '{startRow} to {endRow} ({totalRows})',

    // apply disabled classname to the pager arrows when the rows at
    // either extreme is visible - default is true
    updateArrows: true,

    // starting page of the pager (zero based index)
    page: 0,

    // Number of visible rows - default is 10
    size: 10,

    // if true, the table will remain the same height no matter how many
    // records are displayed. The space is made up by an empty
    // table row set to a height to compensate; default is false
    fixedHeight: false,

    // remove rows from the table to speed up the sort of large tables.
    // setting this to false, only hides the non-visible rows; needed
    // if you plan to add/remove rows with the pager enabled.
    removeRows: false,

    // css class names of pager arrows
    // next page arrow
    cssNext: '.next',
    // previous page arrow
    cssPrev: '.prev',
    // go to first page arrow
    cssFirst: '.first',
    // go to last page arrow
    cssLast: '.last',
    // select dropdown to allow choosing a page
    cssGoto: '.gotoPage',
    // location of where the "output" is displayed
    cssPageDisplay: '.pagedisplay',
    // dropdown that sets the "size" option
    cssPageSize: '.pagesize',
    // class added to arrows when at the extremes
    // (i.e. prev/first arrows are "disabled" when on the first page)
    // Note there is no period "." in front of this class name
    cssDisabled: 'disabled'

});

// Extend the themes to change any of the default class names ** NEW **
$.extend($.tablesorter.themes.jui, {
    // change default jQuery uitheme icons - find the full list of icons
    // here: http://jqueryui.com/themeroller/ (hover over them for their name)
    table: 'ui-widget ui-widget-content ui-corner-all', // table classes
    header: 'ui-widget-header ui-corner-all ui-state-default', // header classes
    icons: 'ui-icon', // icon class added to the <i> in the header
    sortNone: 'ui-icon-carat-2-n-s',
    sortAsc: 'ui-icon-carat-1-n',
    sortDesc: 'ui-icon-carat-1-s',
    active: 'ui-state-active', // applied when column is sorted
    hover: 'ui-state-hover', // hover class
    filterRow: '',
    even: 'ui-widget-content', // even row zebra striping
    odd: 'ui-state-default' // odd row zebra striping
});

});
});

<|endoftext|>


<commit_before>var Client = require('../rollbar');
var _ = require('../utility');
var API = require('../api');
var logger = require('./logger');
var globals = require('./globalSetup');

var transport = require('./transport');
var urllib = require('./url');

var transforms = require('./transforms');
var predicates = require('./predicates');
var errorParser = require('./errorParser');

function Rollbar(options, client) {
  this.options = _.extend(true, defaultOptions, options);
  var api = new API(this.options, transport, urllib);
  this.client = client || new Client(this.options, api, logger);
  addTransformsToNotifier(this.client.notifier);
  addPredicatesToQueue(this.client.queue);
  if (this.options.captureUncaught) {
    globals.captureUncaughtExceptions(window, this);
    globals.wrapGlobals(window, this);
  }
  if (this.options.captureUnhandledRejections) {
    globals.captureUnhandledRejections(window, this);
  }
}

Rollbar.prototype.global = function(options) {
  this.client.global(options);
  return this;
};

Rollbar.prototype.configure = function(options) {
  var oldOptions = this.options;
  this.options = _.extend(true, {}, oldOptions, options);
  this.client.configure(options);
  return this;
};

Rollbar.prototype.log = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.log(item);
  return {uuid: uuid};
};

Rollbar.prototype.debug = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.debug(item);
  return {uuid: uuid};
};

Rollbar.prototype.info = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.info(item);
  return {uuid: uuid};
};

Rollbar.prototype.warn = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.warn(item);
  return {uuid: uuid};
};

Rollbar.prototype.warning = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.warning(item);
  return {uuid: uuid};
};

Rollbar.prototype.error = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.error(item);
  return {uuid: uuid};
};

Rollbar.prototype.critical = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.critical(item);
  return {uuid: uuid};
};

Rollbar.prototype.handleUncaughtException = function(message, url, lineno, colno, error, context) {
  var item;
  var stackInfo = _.makeUnhandledStackInfo(
    message,
    url,
    lineno,
    colno,
    error,
    'onerror',
    'uncaught exception',
    errorParser
  );
  if (_.isError(error)) {
    item = this._createItem([message, error, context]);
    item._unhandledStackInfo = stackInfo;
  } else if (_.isError(url)) {
    item = this._createItem([message, url, context]);
    item._unhandledStackInfo = stackInfo;
  } else {
    item = this._createItem([message, context]);
    item.stackInfo = stackInfo;
  }
  item.level = this.options.uncaughtErrorLevel;
  item._isUncaught = true;
  this.client.log(item);
};

Rollbar.prototype.handleUnhandledRejection = function(reason, promise) {
  var message = 'unhandled rejection was null or undefined!';
  message = reason ? (reason.message || String(reason)) : message;
  var context = (reason && reason._rollbarContext) || promise._rollbarContext;

  var item;
  if (_.isError(reason)) {
    item = this._createItem([message, reason, context]);
  } else {
    item = this._createItem([message, context]);
    item.stackInfo = _.makeUnhandledStackInfo(
      message,
      '',
      0,
      0,
      null,
      'unhandledrejection',
      '',
      errorParser
    );
  }
  item.level = this.options.uncaughtErrorLevel;
  item._isUncaught = true;
  this.client.log(item);
};

Rollbar.prototype.wrap = function(f, context) {
  try {
    var ctxFn;
    if(_.isFunction(context)) {
      ctxFn = context;
    } else {
      ctxFn = function() { return context || {}; };
    }

    if (!_.isFunction(f)) {
      return f;
    }

    if (f._isWrap) {
      return f;
    }

    if (!f._wrapped) {
      f._wrapped = function () {
        try {
          return f.apply(this, arguments);
        } catch(exc) {
          var e = exc;
          if (_.isType(e, 'string')) {
            e = new String(e);
          }
          e._rollbarContext = ctxFn() || {};
          e._rollbarContext._wrappedSource = f.toString();

          window._rollbarWrappedError = e;
          throw e;
        }
      };

      f._wrapped._isWrap = true;

      for (var prop in f) {
        if (f.hasOwnProperty(prop)) {
          f._wrapped[prop] = f[prop];
        }
      }
    }

    return f._wrapped;
  } catch (e) {
    // Return the original function if the wrap fails.
    return f;
  }
};

/* Internal */

function addTransformsToNotifier(notifier) {
  notifier
    .addTransform(transforms.handleItemWithError)
    .addTransform(transforms.ensureItemHasSomethingToSay)
    .addTransform(transforms.addBaseInfo)
    .addTransform(transforms.addRequestInfo(window))
    .addTransform(transforms.addClientInfo(window))
    .addTransform(transforms.addPluginInfo(window))
    .addTransform(transforms.addBody)
    .addTransform(transforms.scrubPayload)
    .addTransform(transforms.userTransform)
    .addTransform(transforms.itemToPayload);
}

function addPredicatesToQueue(queue) {
  queue
    .addPredicate(predicates.checkIgnore)
    .addPredicate(predicates.userCheckIgnore)
    .addPredicate(predicates.urlIsWhitelisted)
    .addPredicate(predicates.messageIsIgnored);
}

Rollbar.prototype._createItem = function(args) {
  var message, err, custom, callback;
  var arg;
  var extraArgs = [];

  for (var i = 0, l = args.length; i < l; ++i) {
    arg = args[i];

    switch (_.typeName(arg)) {
      case 'undefined':
        break;
      case 'string':
        message ? extraArgs.push(arg) : message = arg;
        break;
      case 'function':
        callback = _.wrapRollbarFunction(logger, arg, this);
        break;
      case 'date':
        extraArgs.push(arg);
        break;
      case 'error':
      case 'domexception':
        err ? extraArgs.push(arg) : err = arg;
        break;
      case 'object':
      case 'array':
        if (arg instanceof Error || (typeof DOMException !== 'undefined' && arg instanceof DOMException)) {
          err ? extraArgs.push(arg) : err = arg;
          break;
        }
        custom ? extraArgs.push(arg) : custom = arg;
        break;
      default:
        if (arg instanceof Error || (typeof DOMException !== 'undefined' && arg instanceof DOMException)) {
          err ? extraArgs.push(arg) : err = arg;
          break;
        }
        extraArgs.push(arg);
    }
  }

  if (extraArgs.length > 0) {
    // if custom is an array this turns it into an object with integer keys
    custom = _.extend(true, {}, custom);
    custom.extraArgs = extraArgs;
  }

  var item = {
    message: message,
    err: err,
    custom: custom,
    timestamp: (new Date()).getTime(),
    callback: callback,
    uuid: _.uuid4()
  };
  item._originalArgs = args;
  return item;
};

/* global __NOTIFIER_VERSION__:false */
/* global __DEFAULT_BROWSER_SCRUB_FIELDS__:false */
/* global __DEFAULT_LOG_LEVEL__:false */
/* global __DEFAULT_REPORT_LEVEL__:false */
/* global __DEFAULT_UNCAUGHT_ERROR_LEVEL:false */
/* global __DEFAULT_ENDPOINT__:false */

var defaultOptions = {
  version: __NOTIFIER_VERSION__,
  scrubFields: __DEFAULT_BROWSER_SCRUB_FIELDS__,
  logLevel: __DEFAULT_LOG_LEVEL__,
  reportLevel: __DEFAULT_REPORT_LEVEL__,
  uncaughtErrorLevel: __DEFAULT_UNCAUGHT_ERROR_LEVEL,
  endpoint: __DEFAULT_ENDPOINT__
};

module.exports = Rollbar;
<commit_msg>fix TypeError: Cannot read property '_rollbarContext' of undefined<commit_after>var Client = require('../rollbar');
var _ = require('../utility');
var API = require('../api');
var logger = require('./logger');
var globals = require('./globalSetup');

var transport = require('./transport');
var urllib = require('./url');

var transforms = require('./transforms');
var predicates = require('./predicates');
var errorParser = require('./errorParser');

function Rollbar(options, client) {
  this.options = _.extend(true, defaultOptions, options);
  var api = new API(this.options, transport, urllib);
  this.client = client || new Client(this.options, api, logger);
  addTransformsToNotifier(this.client.notifier);
  addPredicatesToQueue(this.client.queue);
  if (this.options.captureUncaught) {
    globals.captureUncaughtExceptions(window, this);
    globals.wrapGlobals(window, this);
  }
  if (this.options.captureUnhandledRejections) {
    globals.captureUnhandledRejections(window, this);
  }
}

Rollbar.prototype.global = function(options) {
  this.client.global(options);
  return this;
};

Rollbar.prototype.configure = function(options) {
  var oldOptions = this.options;
  this.options = _.extend(true, {}, oldOptions, options);
  this.client.configure(options);
  return this;
};

Rollbar.prototype.log = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.log(item);
  return {uuid: uuid};
};

Rollbar.prototype.debug = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.debug(item);
  return {uuid: uuid};
};

Rollbar.prototype.info = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.info(item);
  return {uuid: uuid};
};

Rollbar.prototype.warn = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.warn(item);
  return {uuid: uuid};
};

Rollbar.prototype.warning = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.warning(item);
  return {uuid: uuid};
};

Rollbar.prototype.error = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.error(item);
  return {uuid: uuid};
};

Rollbar.prototype.critical = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.critical(item);
  return {uuid: uuid};
};

Rollbar.prototype.handleUncaughtException = function(message, url, lineno, colno, error, context) {
  var item;
  var stackInfo = _.makeUnhandledStackInfo(
    message,
    url,
    lineno,
    colno,
    error,
    'onerror',
    'uncaught exception',
    errorParser
  );
  if (_.isError(error)) {
    item = this._createItem([message, error, context]);
    item._unhandledStackInfo = stackInfo;
  } else if (_.isError(url)) {
    item = this._createItem([message, url, context]);
    item._unhandledStackInfo = stackInfo;
  } else {
    item = this._createItem([message, context]);
    item.stackInfo = stackInfo;
  }
  item.level = this.options.uncaughtErrorLevel;
  item._isUncaught = true;
  this.client.log(item);
};

Rollbar.prototype.handleUnhandledRejection = function(reason, promise) {
  var message = 'unhandled rejection was null or undefined!';
  message = reason ? (reason.message || String(reason)) : message;
  var context = (reason && reason._rollbarContext) || (promise && promise._rollbarContext);

  var item;
  if (_.isError(reason)) {
    item = this._createItem([message, reason, context]);
  } else {
    item = this._createItem([message, context]);
    item.stackInfo = _.makeUnhandledStackInfo(
      message,
      '',
      0,
      0,
      null,
      'unhandledrejection',
      '',
      errorParser
    );
  }
  item.level = this.options.uncaughtErrorLevel;
  item._isUncaught = true;
  this.client.log(item);
};

Rollbar.prototype.wrap = function(f, context) {
  try {
    var ctxFn;
    if(_.isFunction(context)) {
      ctxFn = context;
    } else {
      ctxFn = function() { return context || {}; };
    }

    if (!_.isFunction(f)) {
      return f;
    }

    if (f._isWrap) {
      return f;
    }

    if (!f._wrapped) {
      f._wrapped = function () {
        try {
          return f.apply(this, arguments);
        } catch(exc) {
          var e = exc;
          if (_.isType(e, 'string')) {
            e = new String(e);
          }
          e._rollbarContext = ctxFn() || {};
          e._rollbarContext._wrappedSource = f.toString();

          window._rollbarWrappedError = e;
          throw e;
        }
      };

      f._wrapped._isWrap = true;

      for (var prop in f) {
        if (f.hasOwnProperty(prop)) {
          f._wrapped[prop] = f[prop];
        }
      }
    }

    return f._wrapped;
  } catch (e) {
    // Return the original function if the wrap fails.
    return f;
  }
};

/* Internal */

function addTransformsToNotifier(notifier) {
  notifier
    .addTransform(transforms.handleItemWithError)
    .addTransform(transforms.ensureItemHasSomethingToSay)
    .addTransform(transforms.addBaseInfo)
    .addTransform(transforms.addRequestInfo(window))
    .addTransform(transforms.addClientInfo(window))
    .addTransform(transforms.addPluginInfo(window))
    .addTransform(transforms.addBody)
    .addTransform(transforms.scrubPayload)
    .addTransform(transforms.userTransform)
    .addTransform(transforms.itemToPayload);
}

function addPredicatesToQueue(queue) {
  queue
    .addPredicate(predicates.checkIgnore)
    .addPredicate(predicates.userCheckIgnore)
    .addPredicate(predicates.urlIsWhitelisted)
    .addPredicate(predicates.messageIsIgnored);
}

Rollbar.prototype._createItem = function(args) {
  var message, err, custom, callback;
  var arg;
  var extraArgs = [];

  for (var i = 0, l = args.length; i < l; ++i) {
    arg = args[i];

    switch (_.typeName(arg)) {
      case 'undefined':
        break;
      case 'string':
        message ? extraArgs.push(arg) : message = arg;
        break;
      case 'function':
        callback = _.wrapRollbarFunction(logger, arg, this);
        break;
      case 'date':
        extraArgs.push(arg);
        break;
      case 'error':
      case 'domexception':
        err ? extraArgs.push(arg) : err = arg;
        break;
      case 'object':
      case 'array':
        if (arg instanceof Error || (typeof DOMException !== 'undefined' && arg instanceof DOMException)) {
          err ? extraArgs.push(arg) : err = arg;
          break;
        }
        custom ? extraArgs.push(arg) : custom = arg;
        break;
      default:
        if (arg instanceof Error || (typeof DOMException !== 'undefined' && arg instanceof DOMException)) {
          err ? extraArgs.push(arg) : err = arg;
          break;
        }
        extraArgs.push(arg);
    }
  }

  if (extraArgs.length > 0) {
    // if custom is an array this turns it into an object with integer keys
    custom = _.extend(true, {}, custom);
    custom.extraArgs = extraArgs;
  }

  var item = {
    message: message,
    err: err,
    custom: custom,
    timestamp: (new Date()).getTime(),
    callback: callback,
    uuid: _.uuid4()
  };
  item._originalArgs = args;
  return item;
};

/* global __NOTIFIER_VERSION__:false */
/* global __DEFAULT_BROWSER_SCRUB_FIELDS__:false */
/* global __DEFAULT_LOG_LEVEL__:false */
/* global __DEFAULT_REPORT_LEVEL__:false */
/* global __DEFAULT_UNCAUGHT_ERROR_LEVEL:false */
/* global __DEFAULT_ENDPOINT__:false */

var defaultOptions = {
  version: __NOTIFIER_VERSION__,
  scrubFields: __DEFAULT_BROWSER_SCRUB_FIELDS__,
  logLevel: __DEFAULT_LOG_LEVEL__,
  reportLevel: __DEFAULT_REPORT_LEVEL__,
  uncaughtErrorLevel: __DEFAULT_UNCAUGHT_ERROR_LEVEL,
  endpoint: __DEFAULT_ENDPOINT__
};

module.exports = Rollbar;
<|endoftext|>


<commit_before>// # Quintus platformer example
//
// [Run the example](../quintus/examples/platformer/index.html)
// WARNING: this game must be run from a non-file:// url
// as it loads a level json file.
//
// This is the example from the website homepage, it consists
// a simple, non-animated platformer with some enemies and a
// target for the player.

window.addEventListener("load",function() {

// Set up an instance of the Quintus engine  and include
// the Sprites, Scenes, Input and 2D module. The 2D module
// includes the `TileLayer` class as well as the `2d` componet.
var Q = window.Q = Quintus()
        .include("Sprites, Scenes, Input, 2D, Anim, Touch, UI")
        // Maximize this game to whatever the size of the browser is
        .setup({ maximize: true })
        // And turn on default input controls and touch input (for UI)
        .controls().touch()

// ## Player Sprite
// The very basic player sprite, this is just a normal sprite
// using the player sprite sheet with default controls added to it.
Q.Sprite.extend("Player",{

  // the init constructor is called on creation
  init: function(p) {

    // You can call the parent's constructor with this._super(..)
    this._super(p, {
      sheet: "player",  // Setting a sprite sheet sets sprite width and height
      x: 410,           // You can also set additional properties that can
      y: 90             // be overridden on object creation
    });

    // Add in pre-made components to get up and running quickly
    // The `2d` component adds in default 2d collision detection
    // and kinetics (velocity, gravity)
    // The `platformerControls` makes the player controllable by the
    // default input actions (left, right to move,  up or action to jump)
    // It also checks to make sure the player is on a horizontal surface before
    // letting them jump.
    this.add('2d, platformerControls');

    // Write event handlers to respond hook into behaviors.
    // hit.sprite is called everytime the player collides with a sprite
    this.on("hit.sprite",function(collision) {

      // Check the collision, if it's the Tower, you win!
      if(collision.obj.isA("Tower")) {
        Q.stageScene("endGame",1, { label: "You Won!" });
        this.destroy();
      }
    });

  }

});

// ## Tower Sprite
// Sprites can be simple, the Tower sprite just sets a custom sprite sheet
Q.Sprite.extend("Tower", {
  init: function(p) {
    this._super(p, { sheet: 'tower' });
  }
});

// ## Enemy Sprite
// Create the Enemy class to add in some baddies
Q.Sprite.extend("Enemy",{
  init: function(p) {
    this._super(p, { sheet: 'enemy', vx: 100 });

    // Enemies use the Bounce AI to change direction
    // whenver they run into something.
    this.add('2d, aiBounce');

    // Listen for a sprite collision, if it's the player,
    // end the game unless the enemy is hit on top
    this.on("bump.left,bump.right,bump.bottom",function(collision) {
      if(collision.obj.isA("Player")) {
        Q.stageScene("endGame",1, { label: "You Died" });
        collision.obj.destroy();
      }
    });

    // If the enemy gets hit on the top, destroy it
    // and give the user a "hop"
    this.on("bump.top",function(collision) {
      if(collision.obj.isA("Player")) {
        this.destroy();
        collision.obj.p.vy = -300;
      }
    });
  }
});

//enemy that goes up and down
Q.Sprite.extend("VerticalEnemy", {
    init: function(p) {
      this._super(p, { sheet: 'enemy', vx: 100 });

      // Enemies use the Bounce AI to change direction
      // whenver they run into something.
      this.add('2d, aiBounce');

      // Listen for a sprite collision, if it's the player,
      // end the game unless the enemy is hit on top
      this.on("bump.left,bump.right,bump.bottom",function(collision) {
        if(collision.obj.isA("Player")) {
          Q.stageScene("endGame",1, { label: "You Died" });
          collision.obj.destroy();
        }
      });

      // If the enemy gets hit on the top, destroy it
      // and give the user a "hop"
      this.on("bump.top",function(collision) {
        if(collision.obj.isA("Player")) {
          this.destroy();
          collision.obj.p.vy = -300;
        }
      });
    },
    step: function(dt) {
        if(this.p.y - this.p.initialY >= this.p.rangeY && this.p.vy > 0) {
            this.p.vy = -this.p.vy;
        }
        else if(-this.p.y + this.p.initialY >= this.p.rangeY && this.p.vy < 0) {
            this.p.vy = -this.p.vy;
        }
    }
});

// ## Level1 scene
// Create a new scene called level 1
Q.scene("level1",function(stage) {

  // Add in a repeater for a little parallax action
  stage.insert(new Q.Repeater({ asset: "background-wall.png", speedX: 0.5, speedY: 0.5 }));

  // Add in a tile layer, and make it the collision layer
  stage.collisionLayer(new Q.TileLayer({
                             dataAsset: 'level.json',
                             sheet:     'tiles' }));

  // Create the player and add them to the stage
  var player = stage.insert(new Q.Player());

  // Give the stage a moveable viewport and tell it
  // to follow the player.
  stage.add("viewport").follow(player);

  // Add in a couple of enemies
  stage.insert(new Q.Enemy({ x: 700, y: 0 }));
  stage.insert(new Q.Enemy({ x: 800, y: 0 }));
  stage.insert(new Q.VerticalEnemy({x: 800, y: 120, rangeY: 70, asset: "fly.png" }));
  stage.insert(new Q.VerticalEnemy({x: 800, y: 120, rangeY: 70, asset: "fly.png" }));

  // Finally add in the tower goal
  stage.insert(new Q.Tower({ x: 180, y: 50 }));
});

// To display a game over / game won popup box,
// create a endGame scene that takes in a `label` option
// to control the displayed message.
Q.scene('endGame',function(stage) {
  var container = stage.insert(new Q.UI.Container({
    x: Q.width/2, y: Q.height/2, fill: "rgba(0,0,0,0.5)"
  }));

  var button = container.insert(new Q.UI.Button({ x: 0, y: 0, fill: "#CCCCCC",
                                                  label: "Play Again" }))
  var label = container.insert(new Q.UI.Text({x:10, y: -10 - button.p.h,
                                                   label: stage.options.label }));
  // When the button is clicked, clear all the stages
  // and restart the game.
  button.on("click",function() {
    Q.clearStages();
    Q.stageScene('level1');
  });

  // Expand the container to visibily fit it's contents
  // (with a padding of 20 pixels)
  container.fit(20);
});

// ## Asset Loading and Game Launch
// Q.load can be called at any time to load additional assets
// assets that are already loaded will be skipped
// The callback will be triggered when everything is loaded
Q.load("sprites.png, sprites.json, level.json, fly.png, tiles.png, background-wall.png", function() {
  // Sprites sheets can be created manually
  Q.sheet("tiles","tiles.png", { tilew: 32, tileh: 32 });

  // Or from a .json asset that defines sprite locations
  Q.compileSheets("sprites.png","sprites.json");

  // Finally, call stageScene to run the game
  Q.stageScene("level1");
});

// ## Possible Experimentations:
//
// The are lots of things to try out here.
//
// 1. Modify level.json to change the level around and add in some more enemies.
// 2. Add in a second level by creating a level2.json and a level2 scene that gets
//    loaded after level 1 is complete.
// 3. Add in a title screen
// 4. Add in a hud and points for jumping on enemies.
// 5. Add in a `Repeater` behind the TileLayer to create a paralax scrolling effect.

});
<commit_msg>maybe?<commit_after>// # Quintus platformer example
//
// [Run the example](../quintus/examples/platformer/index.html)
// WARNING: this game must be run from a non-file:// url
// as it loads a level json file.
//
// This is the example from the website homepage, it consists
// a simple, non-animated platformer with some enemies and a
// target for the player.

window.addEventListener("load",function() {

// Set up an instance of the Quintus engine  and include
// the Sprites, Scenes, Input and 2D module. The 2D module
// includes the `TileLayer` class as well as the `2d` componet.
var Q = window.Q = Quintus()
        .include("Sprites, Scenes, Input, 2D, Anim, Touch, UI")
        // Maximize this game to whatever the size of the browser is
        .setup({ maximize: true })
        // And turn on default input controls and touch input (for UI)
        .controls().touch()

// ## Player Sprite
// The very basic player sprite, this is just a normal sprite
// using the player sprite sheet with default controls added to it.
Q.Sprite.extend("Player",{

  // the init constructor is called on creation
  init: function(p) {

    // You can call the parent's constructor with this._super(..)
    this._super(p, {
      sheet: "player",  // Setting a sprite sheet sets sprite width and height
      x: 410,           // You can also set additional properties that can
      y: 90             // be overridden on object creation
    });

    // Add in pre-made components to get up and running quickly
    // The `2d` component adds in default 2d collision detection
    // and kinetics (velocity, gravity)
    // The `platformerControls` makes the player controllable by the
    // default input actions (left, right to move,  up or action to jump)
    // It also checks to make sure the player is on a horizontal surface before
    // letting them jump.
    this.add('2d, platformerControls');

    // Write event handlers to respond hook into behaviors.
    // hit.sprite is called everytime the player collides with a sprite
    this.on("hit.sprite",function(collision) {

      // Check the collision, if it's the Tower, you win!
      if(collision.obj.isA("Tower")) {
        Q.stageScene("endGame",1, { label: "You Won!" });
        this.destroy();
      }
    });

  }

});

// ## Tower Sprite
// Sprites can be simple, the Tower sprite just sets a custom sprite sheet
Q.Sprite.extend("Tower", {
  init: function(p) {
    this._super(p, { sheet: 'tower' });
  }
});

// ## Enemy Sprite
// Create the Enemy class to add in some baddies
Q.Sprite.extend("Enemy",{
  init: function(p) {
    this._super(p, { sheet: 'enemy', vx: 100 });

    // Enemies use the Bounce AI to change direction
    // whenver they run into something.
    this.add('2d, aiBounce');

    // Listen for a sprite collision, if it's the player,
    // end the game unless the enemy is hit on top
    this.on("bump.left,bump.right,bump.bottom",function(collision) {
      if(collision.obj.isA("Player")) {
        Q.stageScene("endGame",1, { label: "You Died" });
        collision.obj.destroy();
      }
    });

    // If the enemy gets hit on the top, destroy it
    // and give the user a "hop"
    this.on("bump.top",function(collision) {
      if(collision.obj.isA("Player")) {
        this.destroy();
        collision.obj.p.vy = -300;
      }
    });
  }
});

//enemy that goes up and down
Q.Sprite.extend("VerticalEnemy", {
    init: function(p) {
        this._super(p, { sheet: 'enemy', vy: -100, rangeY: 200, gravity: 0  });
        this.add("2d, aiBounce");
        this.p.initialY = this.p.y;

        // Listen for a sprite collision, if it's the player,
        // end the game unless the enemy is hit on top
        this.on("bump.left,bump.right,bump.bottom",function(collision) {
          if(collision.obj.isA("Player")) {
            Q.stageScene("endGame",1, { label: "You Died" });
            collision.obj.destroy();
          }
        });

        // If the enemy gets hit on the top, destroy it
        // and give the user a "hop"
        this.on("bump.top",function(collision) {
          if(collision.obj.isA("Player")) {
            this.destroy();
            collision.obj.p.vy = -300;
          }
        });
    },
    step: function(dt) {
        if(this.p.y - this.p.initialY >= this.p.rangeY && this.p.vy > 0) {
            this.p.vy = -this.p.vy;
        }
        else if(-this.p.y + this.p.initialY >= this.p.rangeY && this.p.vy < 0) {
            this.p.vy = -this.p.vy;
        }
    }
});

// ## Level1 scene
// Create a new scene called level 1
Q.scene("level1",function(stage) {

  // Add in a repeater for a little parallax action
  stage.insert(new Q.Repeater({ asset: "background-wall.png", speedX: 0.5, speedY: 0.5 }));

  // Add in a tile layer, and make it the collision layer
  stage.collisionLayer(new Q.TileLayer({
                             dataAsset: 'level.json',
                             sheet:     'tiles' }));

  // Create the player and add them to the stage
  var player = stage.insert(new Q.Player());

  // Give the stage a moveable viewport and tell it
  // to follow the player.
  stage.add("viewport").follow(player);

  // Add in a couple of enemies
  stage.insert(new Q.Enemy({ x: 700, y: 0 }));
  stage.insert(new Q.Enemy({ x: 800, y: 0 }));
  stage.insert(new Q.VerticalEnemy({x: 800, y: 120, rangeY: 70, asset: "fly.png" }));
  stage.insert(new Q.VerticalEnemy({x: 800, y: 120, rangeY: 70, asset: "fly.png" }));

  // Finally add in the tower goal
  stage.insert(new Q.Tower({ x: 180, y: 50 }));
});

// To display a game over / game won popup box,
// create a endGame scene that takes in a `label` option
// to control the displayed message.
Q.scene('endGame',function(stage) {
  var container = stage.insert(new Q.UI.Container({
    x: Q.width/2, y: Q.height/2, fill: "rgba(0,0,0,0.5)"
  }));

  var button = container.insert(new Q.UI.Button({ x: 0, y: 0, fill: "#CCCCCC",
                                                  label: "Play Again" }))
  var label = container.insert(new Q.UI.Text({x:10, y: -10 - button.p.h,
                                                   label: stage.options.label }));
  // When the button is clicked, clear all the stages
  // and restart the game.
  button.on("click",function() {
    Q.clearStages();
    Q.stageScene('level1');
  });

  // Expand the container to visibily fit it's contents
  // (with a padding of 20 pixels)
  container.fit(20);
});

// ## Asset Loading and Game Launch
// Q.load can be called at any time to load additional assets
// assets that are already loaded will be skipped
// The callback will be triggered when everything is loaded
Q.load("sprites.png, sprites.json, level.json, fly.png, tiles.png, background-wall.png", function() {
  // Sprites sheets can be created manually
  Q.sheet("tiles","tiles.png", { tilew: 32, tileh: 32 });

  // Or from a .json asset that defines sprite locations
  Q.compileSheets("sprites.png","sprites.json");

  // Finally, call stageScene to run the game
  Q.stageScene("level1");
});

// ## Possible Experimentations:
//
// The are lots of things to try out here.
//
// 1. Modify level.json to change the level around and add in some more enemies.
// 2. Add in a second level by creating a level2.json and a level2 scene that gets
//    loaded after level 1 is complete.
// 3. Add in a title screen
// 4. Add in a hud and points for jumping on enemies.
// 5. Add in a `Repeater` behind the TileLayer to create a paralax scrolling effect.

});
<|endoftext|>


<commit_before>Cut.addTexture({
  name : "base",
  imagePath : "assets/base.png",
  imageRatio : 4,
  ratio : 16,
  filter : function(cut) {
    cut.y = 1 - (cut.y + cut.height);
    return cut;
  },
  cutouts : [
    { name : "drone", x : 0, y : 0, width : 1, height : 1 }
  ]
}); <commit_msg>added moar drone images<commit_after>Cut.addTexture({
  name : "base",
  imagePath : "assets/base.png",
  imageRatio : 4,
  ratio : 16,
  filter : function(cut) {
    cut.y = 1 - (cut.y + cut.height);
    return cut;
  },
  cutouts : [
    { name : "drone", x : 0, y : 0, width : 1, height : 1 },
    { name : "drone2", x : 1, y : 0, width : 1, height : 1 },
    { name : "drone3", x : 2, y : 0, width : 1, height : 1 },
    { name : "drone4", x : 3, y : 0, width : 1, height : 1 }
  ]
}); <|endoftext|>


<commit_before>var DB_VERSION = 2;
var DB_NAME = "gih-reservations";

// Returns a promise which resolves with a database object if it is  opened
// successfully or rejects with an error message if it didn't.
var openDatabase = function() {
  return new Promise(function (resolve, reject) {
    // Make sure IndexedDB is supported before attempting to use it
    if (!this.indexedDB) {
      reject("IndexedDB not supported");
    }
    var request = this.indexedDB.open(DB_NAME, DB_VERSION);
    request.onerror = function(event) {
      reject("Database error: " + event.target.error);
    };

    request.onupgradeneeded = function(event) {
      var db = event.target.result;
      var upgradeTransaction = event.target.transaction;
      var reservationsStore;
      if (!db.objectStoreNames.contains("reservations")) {
        reservationsStore = db.createObjectStore("reservations",
          { keyPath: "id" }
        );
      } else {
        reservationsStore = upgradeTransaction.objectStore('reservations');
      }

      if (!reservationsStore.indexNames.contains("idx_status")) {
        reservationsStore.createIndex("idx_status", "status", { unique: false });
      }
    };

    request.onsuccess = function(event) {
      resolve(event.target.result);
    };
  });
};

// Returns a promise which resolves with an object store object
var openObjectStore = function(db, storeName, transactionMode) {
  return new Promise(function (resolve, reject) {
    var objectStore = db
      .transaction(storeName, transactionMode)
      .objectStore(storeName);
    resolve(objectStore);
  });
};

var addToObjectStore = function(storeName, object) {
  return new Promise(function(resolve, reject) {
    openDatabase().then(function(db) {
      return openObjectStore(db, storeName, 'readwrite');
    }).then(function(objectStore) {
        objectStore.add(object).onsuccess = resolve;
    }).catch(function(errorMessage) {
      reject(errorMessage);
    });
  });
};

var updateInObjectStore = function(storeName, id, object) {
  return new Promise(function(resolve, reject) {
    openDatabase().then(function(db) {
      return openObjectStore(db, storeName, 'readwrite');
    }).then(function(objectStore) {
      objectStore.openCursor().onsuccess = function(event) {
        var cursor = event.target.result;
        if (!cursor) {
          reject('Reservation not found in object store');
        }
        if (cursor.value.id === id) {
          cursor.update(object).onsuccess = resolve;
          return;
        }
        cursor.continue();
      };
    }).catch(function(errorMessage) {
      reject(errorMessage);
    });
  });
};

var getReservations = function(successCallback) {
  openDatabase().then(function(db) {
    return openObjectStore(db, 'reservations');
  }).then(function(objectStore) {
    var reservations = [];
    objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;
      if (cursor) {
        reservations.push(cursor.value);
        cursor.continue();
      } else {
        if (reservations.length > 0) {
          successCallback(reservations);
        } else {
          getReservationsFromServer(function(reservations) {
            openDatabase().then(function(db) {
              return openObjectStore(db, 'reservations', 'readwrite');
            }).then(function(objectStore) {
              for (var i = 0; i < reservations.length; i++) {
                objectStore.add(reservations[i]);
              }
              successCallback(reservations);
            });
          });
        }
      }
    };
  }).catch(function(errorMessage) {
    getReservationsFromServer('/reservations.json', successCallback);
  });
};

var getReservationsFromServer = function(successCallback) {
  $.getJSON('/reservations.json', successCallback);
};
<commit_msg>Changed reservations store to access IndexedDB through window, and not this. This will be changed in chapter 7<commit_after>var DB_VERSION = 2;
var DB_NAME = "gih-reservations";

// Returns a promise which resolves with a database object if it is  opened
// successfully or rejects with an error message if it didn't.
var openDatabase = function() {
  return new Promise(function (resolve, reject) {
    // Make sure IndexedDB is supported before attempting to use it
    if (!window.indexedDB) {
      reject("IndexedDB not supported");
    }
    var request = window.indexedDB.open(DB_NAME, DB_VERSION);
    request.onerror = function(event) {
      reject("Database error: " + event.target.error);
    };

    request.onupgradeneeded = function(event) {
      var db = event.target.result;
      var upgradeTransaction = event.target.transaction;
      var reservationsStore;
      if (!db.objectStoreNames.contains("reservations")) {
        reservationsStore = db.createObjectStore("reservations",
          { keyPath: "id" }
        );
      } else {
        reservationsStore = upgradeTransaction.objectStore('reservations');
      }

      if (!reservationsStore.indexNames.contains("idx_status")) {
        reservationsStore.createIndex("idx_status", "status", { unique: false });
      }
    };

    request.onsuccess = function(event) {
      resolve(event.target.result);
    };
  });
};

// Returns a promise which resolves with an object store object
var openObjectStore = function(db, storeName, transactionMode) {
  return new Promise(function (resolve, reject) {
    var objectStore = db
      .transaction(storeName, transactionMode)
      .objectStore(storeName);
    resolve(objectStore);
  });
};

var addToObjectStore = function(storeName, object) {
  return new Promise(function(resolve, reject) {
    openDatabase().then(function(db) {
      return openObjectStore(db, storeName, 'readwrite');
    }).then(function(objectStore) {
        objectStore.add(object).onsuccess = resolve;
    }).catch(function(errorMessage) {
      reject(errorMessage);
    });
  });
};

var updateInObjectStore = function(storeName, id, object) {
  return new Promise(function(resolve, reject) {
    openDatabase().then(function(db) {
      return openObjectStore(db, storeName, 'readwrite');
    }).then(function(objectStore) {
      objectStore.openCursor().onsuccess = function(event) {
        var cursor = event.target.result;
        if (!cursor) {
          reject('Reservation not found in object store');
        }
        if (cursor.value.id === id) {
          cursor.update(object).onsuccess = resolve;
          return;
        }
        cursor.continue();
      };
    }).catch(function(errorMessage) {
      reject(errorMessage);
    });
  });
};

var getReservations = function(successCallback) {
  openDatabase().then(function(db) {
    return openObjectStore(db, 'reservations');
  }).then(function(objectStore) {
    var reservations = [];
    objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;
      if (cursor) {
        reservations.push(cursor.value);
        cursor.continue();
      } else {
        if (reservations.length > 0) {
          successCallback(reservations);
        } else {
          getReservationsFromServer(function(reservations) {
            openDatabase().then(function(db) {
              return openObjectStore(db, 'reservations', 'readwrite');
            }).then(function(objectStore) {
              for (var i = 0; i < reservations.length; i++) {
                objectStore.add(reservations[i]);
              }
              successCallback(reservations);
            });
          });
        }
      }
    };
  }).catch(function(errorMessage) {
    getReservationsFromServer('/reservations.json', successCallback);
  });
};

var getReservationsFromServer = function(successCallback) {
  $.getJSON('/reservations.json', successCallback);
};
<|endoftext|>


<commit_before>const {readFileSync} = require("fs")
const {request} = require("https")

let mods = ["model", "transform", "state", "view",
            "keymap", "inputrules", "history", "collab", "commands", "gapcursor",
            "schema-basic", "schema-list",
            "menu", "example-setup", "markdown", "dropcursor", "test-builder", "changeset"]

Promise.all(mods.map(mod => {
  let local
  try { local = require.resolve(`prosemirror-${mod}/CHANGELOG.md`) }
  catch(_) {}
  if (local) return Promise.resolve({mod, log: readFileSync(local, "utf8")})

  return new Promise((resolve, reject) => {
    let req = request({
      hostname: "raw.githubusercontent.com",
      path: `/ProseMirror/prosemirror-${mod}/master/CHANGELOG.md`,
      method: "GET",
      headers: {Accept: "text/plain"}
    }, response => {
      if (response.statusCode >= 300) return reject("Failed " + response.statusText)
      let buf = ""
      response.on("data", b => buf += b)
      response.on("end", () => resolve({mod, log: buf}))
      response.on("error", reject)
    })
    req.on("error", reject)
    req.end()
  })
})).then(logs => {
  let entries = []
  let release = /(?:^|\n)## ([\d\.]+) \(([\d-]+)\)\n([^]*?)(?=\n## )/g
  for (let {mod, log} of logs) {
    for (let m; m = release.exec(log);) {
      let [_, version, date, body] = m
      entries.push({date, content: `## [prosemirror-${mod}](../ref/#${mod}) ${version} (${date})\n${body}`})
    }
  }
  console.log(entries.sort((a, b) => (a.date == b.date ? 0 : a.date < b.date ? 1 : -1)).map(e => e.content).join("\n"))
})
<commit_msg>Remove trailing whitespace<commit_after>const {readFileSync} = require("fs")
const {request} = require("https")

let mods = ["model", "transform", "state", "view",
            "keymap", "inputrules", "history", "collab", "commands", "gapcursor",
            "schema-basic", "schema-list",
            "menu", "example-setup", "markdown", "dropcursor", "test-builder", "changeset"]

Promise.all(mods.map(mod => {
  let local
  try { local = require.resolve(`prosemirror-${mod}/CHANGELOG.md`) }
  catch(_) {}
  if (local) return Promise.resolve({mod, log: readFileSync(local, "utf8")})

  return new Promise((resolve, reject) => {
    let req = request({
      hostname: "raw.githubusercontent.com",
      path: `/ProseMirror/prosemirror-${mod}/master/CHANGELOG.md`,
      method: "GET",
      headers: {Accept: "text/plain"}
    }, response => {
      if (response.statusCode >= 300) return reject("Failed " + response.statusText)
      let buf = ""
      response.on("data", b => buf += b)
      response.on("end", () => resolve({mod, log: buf}))
      response.on("error", reject)
    })
    req.on("error", reject)
    req.end()
  })
})).then(logs => {
  let entries = []
  let release = /(?:^|\n)## ([\d\.]+) \(([\d-]+)\)\n([^]*?)(?=\n## )/g
  for (let {mod, log} of logs) {
    for (let m; m = release.exec(log);) {
      let [_, version, date, body] = m
      entries.push({date, content: `## [prosemirror-${mod}](../ref/#${mod}) ${version} (${date})\n${body}`})
    }
  }
  console.log(entries.sort((a, b) => (a.date == b.date ? 0 : a.date < b.date ? 1 : -1)).map(e => e.content).join("\n"))
})
<|endoftext|>


<commit_before>
define(function(require) {
    var Crafty = require('crafty');
    var Vec2d = Crafty.math.Vector2D;
    var pi = 3.14159;

    var dashdecel = 3.0;
    var maxdashspeed = 40.0;
    var mindashspeed = 30.0;
    var enddashspeed = 1.0;

    var turnTowards = function(from, to) {
        var c1 = to - from;
        var c2 = to + 2*pi - from;
        var c3 = to - 2*pi - from;
        var shortest;
        if(Math.abs(c1) <= Math.abs(c2)) {
            if(Math.abs(c1) <= Math.abs(c3)) {
                shortest = c1;
            } else {
                shortest = c3;
            }
        } else {
            if(Math.abs(c2) <= Math.abs(c3)) {
                shortest = c2;
            } else {
                shortest = c3;
            }
        }
        return shortest?shortest<0?-1:1:0;
    };

    var constrainAngle = function(angle) {
        if(angle < -pi) {
            angle += 2 * pi;
        } else if(angle > pi) {
            angle -= 2 * pi;
        }
        return angle;
    };

    Crafty.c("PlayerControl", {
        _moving: true,
        _speed: 0,
        _maxspeed: 8,
        _acceleration: 0.3,
        _turnrate: 0.4,
        _hitmaxspeed: false,

        _dashing: false,
        _targetangle: 0,
        _moveangle: 0,

        _mousedown: function(e) {
            if(e.mouseButton == 0) {
                //LMB
                var position = new Vec2d(this.x, this.y);
                var target = new Vec2d(e.realX, e.realY);
                var rel = target.subtract(position);
                this._targetangle = Math.atan2(rel.y, rel.x);

                if(!this._dashing && this._speed >= 0) {
                    this._dashing = true;
                    //Dash to mouse pointer; I derived this equation for speed
                    this._speed = Math.sqrt(2 * dashdecel * rel.magnitude());
                    this._speed = Math.min(this._speed, maxdashspeed);
                    this._speed = Math.max(this._speed, mindashspeed);
                    this._moveangle = this._targetangle;
                    this.trigger('StartDash');
                }
            } else if(e.mouseButton == 2 && this._canBomb()) {
                //RMB, bomb - pass control to entityDestroyer
               this._speed = 0;
               this._moving = false;
               this._dashing = false;
               this.visible = false;
               this.trigger('StopDash');
               this.trigger('StartBomb');
               this.bind('EndBomb', function() {
                   this.visible = true;
                   this._moving = true;
               });
            }
        },

        _mousemove: function(e) {
            var position = new Vec2d(this.x, this.y);
            var target = new Vec2d(e.realX, e.realY);
            var rel = target.subtract(position);
            this._targetangle = Math.atan2(rel.y, rel.x);
        },

        _enterframe: function() {
            if(this._moving) {
                if(!this._dashing) {
                    if(this._speed < this._maxspeed) {
                        this._speed += this._acceleration;
                        this._hitmaxspeed = false;
                    } else {
                        this._speed = this._maxspeed;
                        if(!this._hitmaxspeed) {
                            this._hitmaxspeed = true;
                            this.trigger('HitMaxSpeed');
                        }
                    }
                } else {
                    if(this._speed > enddashspeed) {
                        this._speed -= dashdecel;
                    } else {
                        this._dashing = false;
                        this.trigger('StopDash');
                    }
                }
            }

            if(this._speed > 0) {
                //Don't change direction while dashing
                if(!this._dashing) {
                    var turnDir = turnTowards(this._moveangle, this._targetangle);
                    this._moveangle += turnDir * Math.min(Math.abs(this._moveangle - this._targetangle),
                            this._turnrate);
                    this._moveangle = constrainAngle(this._moveangle);

                    this.rotation = this._moveangle * 360.0/(2*pi) + 90;
                }

                var position = new Vec2d(this.x, this.y);
                var movement = new Vec2d(this._speed * Math.cos(this._moveangle),
                                this._speed * Math.sin(this._moveangle));
                this.x += movement.x;
                this.y += movement.y;
                this.trigger('Moved', {x: this.x - movement.x, y: this.y - movement.y});
            }
        },

        init: function() {
            this.requires('Mouse');

            Crafty.addEvent(this, Crafty.stage.elem, "mousemove", this._mousemove);
            Crafty.addEvent(this, Crafty.stage.elem, "mouseup", this._mouseup);
            Crafty.addEvent(this, Crafty.stage.elem, "mousedown", this._mousedown);

            this.bind("EnterFrame", this._enterframe);
        },

        playercontrol: function(maxspeed, acceleration, turnrate) {
            this._maxspeed = maxspeed;
            this._acceleration = acceleration;
            this._turnrate = turnrate;
            return this;
        },

        maxspeed: function(maxspeed) {
            this._maxspeed = maxspeed;
        },

        acceleration: function(acceleration) {
            this._acceleration = acceleration;
        },

        turnrate: function(turnrate) {
            this._turnrate = turnrate;
        }
    })
});
<commit_msg>Stop on cursor<commit_after>
define(function(require) {
    var Crafty = require('crafty');
    var Vec2d = Crafty.math.Vector2D;
    var pi = 3.14159;

    var dashdecel = 3.0;
    var maxdashspeed = 40.0;
    var mindashspeed = 30.0;
    var enddashspeed = 1.0;

    var turnTowards = function(from, to) {
        var c1 = to - from;
        var c2 = to + 2*pi - from;
        var c3 = to - 2*pi - from;
        var shortest;
        if(Math.abs(c1) <= Math.abs(c2)) {
            if(Math.abs(c1) <= Math.abs(c3)) {
                shortest = c1;
            } else {
                shortest = c3;
            }
        } else {
            if(Math.abs(c2) <= Math.abs(c3)) {
                shortest = c2;
            } else {
                shortest = c3;
            }
        }
        return shortest?shortest<0?-1:1:0;
    };

    var constrainAngle = function(angle) {
        if(angle < -pi) {
            angle += 2 * pi;
        } else if(angle > pi) {
            angle -= 2 * pi;
        }
        return angle;
    };

    Crafty.c("PlayerControl", {
        _moving: true,
        _speed: 0,
        _maxspeed: 8,
        _acceleration: 0.3,
        _turnrate: 0.4,
        _hitmaxspeed: false,

        _dashing: false,
        _target: new Vec2d(0,0),
        _targetangle: 0,
        _moveangle: 0,

        _mousedown: function(e) {
            if(e.mouseButton == 0) {
                //LMB
                var position = new Vec2d(this.x, this.y);
                var target = new Vec2d(e.realX, e.realY);
                var rel = target.subtract(position);
                this._targetangle = Math.atan2(rel.y, rel.x);

                if(!this._dashing && this._speed >= 0) {
                    this._dashing = true;
                    //Dash to mouse pointer; I derived this equation for speed
                    this._speed = Math.sqrt(2 * dashdecel * rel.magnitude());
                    this._speed = Math.min(this._speed, maxdashspeed);
                    this._speed = Math.max(this._speed, mindashspeed);
                    this._moveangle = this._targetangle;
                    this.trigger('StartDash');
                }
            } else if(e.mouseButton == 2 && this._canBomb()) {
                //RMB, bomb - pass control to entityDestroyer
               this._speed = 0;
               this._moving = false;
               this._dashing = false;
               this.visible = false;
               this.trigger('StopDash');
               this.trigger('StartBomb');
               this.bind('EndBomb', function() {
                   this.visible = true;
                   this._moving = true;
               });
            }
        },

        _mousemove: function(e) {
            this._target = new Vec2d(e.realX, e.realY);
        },

        _enterframe: function() {
            if(this._moving) {
                if(!this._dashing) {
                    if(this._speed < this._maxspeed) {
                        this._speed += this._acceleration;
                        this._hitmaxspeed = false;
                    } else {
                        this._speed = this._maxspeed;
                        if(!this._hitmaxspeed) {
                            this._hitmaxspeed = true;
                            this.trigger('HitMaxSpeed');
                        }
                    }
                } else {
                    if(this._speed > enddashspeed) {
                        this._speed -= dashdecel;
                    } else {
                        this._dashing = false;
                        this.trigger('StopDash');
                    }
                }
            }

            if(this._speed > 0) {
                var position = new Vec2d(this.x, this.y);
                var rel = this._target.clone().subtract(position);
                //Don't change direction while dashing
                if(!this._dashing) {
                    var targetangle = Math.atan2(rel.y, rel.x);
                    var turnDir = turnTowards(this._moveangle, targetangle);
                    this._moveangle += turnDir * Math.min(Math.abs(this._moveangle - targetangle),
                            this._turnrate);
                    this._moveangle = constrainAngle(this._moveangle);

                    this.rotation = this._moveangle * 360.0/(2*pi) + 90;
                }

                //If we're very close to the mouse, just don't move
                if(this._dashing || Math.abs(rel.x) > 4 || Math.abs(rel.y) > 4) {
                    var movement = new Vec2d(this._speed * Math.cos(this._moveangle),
                                    this._speed * Math.sin(this._moveangle));
                    this.x += movement.x;
                    this.y += movement.y;
                    this.trigger('Moved', {x: this.x - movement.x, y: this.y - movement.y});
                }
            }
        },

        init: function() {
            this.requires('Mouse');

            Crafty.addEvent(this, Crafty.stage.elem, "mousemove", this._mousemove);
            Crafty.addEvent(this, Crafty.stage.elem, "mouseup", this._mouseup);
            Crafty.addEvent(this, Crafty.stage.elem, "mousedown", this._mousedown);

            this.bind("EnterFrame", this._enterframe);
        },

        playercontrol: function(maxspeed, acceleration, turnrate) {
            this._maxspeed = maxspeed;
            this._acceleration = acceleration;
            this._turnrate = turnrate;
            return this;
        },

        maxspeed: function(maxspeed) {
            this._maxspeed = maxspeed;
        },

        acceleration: function(acceleration) {
            this._acceleration = acceleration;
        },

        turnrate: function(turnrate) {
            this._turnrate = turnrate;
        }
    })
});
<|endoftext|>


<commit_before>var port = process.env.PORT || process.env.EM_PORT || 5000;

module.exports = {
  "swagger": "2.0",
  "info": {
    "description": "Documentation for Event Mapping Server App.",
    "version": "0.0.1",
    "title": "EventMapping API",
    "contact": {
      "email": "sinem93@gmail.com"
    },
    "license": {
      "name": "MIT",
      "url": "https://github.com/swagger-api/swagger-ui/blob/master/LICENSE"
    }
  },
  "host": process.env.EM_DOMAIN + ":" + port,
  "basePath": "/",
  "produces": ["application/json"],
  "consumes": ["application/json"],
  "schemes": [
    "http"
  ],
  "definitions": {
    "EventRequestModel": {
      "type": "object",
      "properties": {
        "since": {
          "type": "string"
        },
        "until": {
          "type": "string"
        }
      }
    },
    "EventResponseModel": {
      "type": "object",
      "properties": {
        "api": {
          "type": "string"
        },
        "data" : {
          "schema": {
            "$ref": "#/definitions/EventArrayModel"
          }
        }
      }
    },
    "EventArrayModel": {
      "type": "array",
      "items": {
        "schema": {
          "$ref": "#/definitions/EventModel"
        }
      }
    },
    "EventModel": {
      "type": "object",
      "properties" : {
        "api": {
          "description": "API from which event data is taken from",
          "type": "string"
        },
        "name": {
          "description": "name of the event",
          "type": "string"
        },
        "description": {
          "description": "description of the event",
          "type": "string"
        },
        "venue_name": {
          "description": "name of the venue the event is hosted in",
          "type": "string"
        },
        "lat": {
          "description": "latitude of the event",
          "type": "number"
        },
        "lng": {
          "description": "longitude of the event",
          "type": "number"
        },
        "category": {
          "type": "string"
        },
        "photo": {
        },
        "start_time": {
          "type": "string"
        },
        "end_time": {
          "type": "string"
        },
        "attending_count": {
          "type": "number"
        },
        "maybe_count": {
          "type": "number"
        },
        "interested_count": {
          "type": "number"
        },
        "waitlist_count": {
          "type": "number"
        },
        "link": {
          "description": "Url of a location where more info about the event can be found",
          "type": "string"
        }
      }
    }
  },
  "paths": {
    "/density": {
      "post": {
        "tags": ["Get Density"],
        "descriptions": "Returns the density of people in Istanbul for the past 15 mins",
        "notes": "Notes",
        "summary": "summary",
        "responses": {
          "200": {
            "description": "Successfully got density",
            "schema": {
              "type":  "array",
              "items": {
                "type": "array",
                "items": {
                  "type": "number"
                }
              }
            }
          }
        }
      }
      },
    "/weather/current": {
      "post": {
        "tags": ["Get Current Weather"],
        "descriptions": "Returns the current weather for the coordinates if given, or for pre-determined coordinates in Istanbul",
        "parameters": [
          {
            "name": "body",
            "in": "body",
            "description": "Coordinates for which the weather data is requested",
            "required": false,
            "schema": {
              "type": "object",
              "properties": {
                  "coords": {
                    "type": "string"
                  }
              }
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully got the weather data",
            "schema": {
              "type": "object",
              "properties": {
                "api": {
                  "type": "string"
                },
                "data": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "latitude": {
                        "type": "number"
                      },
                      "longitude": {
                        "type": "number"
                      },
                      "apparentTemperature": {
                        "type": "number"
                      },
                      "windSpeed": {
                        "type": "number"
                      },
                      "precipProbability": {
                        "type": "number"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/meetup": {
      "post": {
        "tags": ["Get Meetup Events"],
        "descriptions": "Returns events from Meetup. If no time interval is specified, events in the coming week are returned",
        "parameters" : [
          {
            "name": "body",
            "in": "body",
            "description": "Defines the time interval",
            "required": false,
            "schema": {
              "$ref": "#/definitions/EventRequestModel"
            }
        }
      ],
      "responses": {
        "200": {
          "description": "Successfully got events",
          "schema": {
            "$ref": "#/definitions/EventResponseModel"
          }
        }
      }
      }
    },
    "/eventful": {
      "post": {
        "tags": ["Get Eventful Events"],
        "descriptions": "Returns events from Eventful. If no time interval is specified, events in the coming week are returned",
        "parameters" : [
          {
            "name": "body",
            "in": "body",
            "description": "Defines the time interval",
            "required": false,
            "schema": {
              "$ref": "#/definitions/EventRequestModel"
            }
        }
      ],
      "responses": {
        "200": {
          "description": "Successfully got events",
          "schema": {
            "$ref": "#/definitions/EventResponseModel"
          }
        }
      }
      }
    },
    "/facebook/" : {
      "post": {
        "tags": ["Get Facebook Events"],
        "descriptions": "Returns events from Facebook. If no time interval is specified, events in the coming week are returned",
        "parameters" : [
          {
            "name": "body",
            "in": "body",
            "description": "Defines the time interval",
            "required": false,
            "schema": {
              "$ref": "#/definitions/EventRequestModel"
            }
        }
        ],
        "responses": {
          "200": {
            "description": "Successfully got events",
            "schema": {
              "$ref": "#/definitions/EventResponseModel"
            }
          }
        }
      }
    },
    "/events" : {
      "post": {
        "tags" : ["Get Events"],
        "descriptions": "Returns events from Facebook, Eventful, Meetup API's in the specified time interval. If no time interval is specified, events in the coming week are returned",
        "parameters": [
          {
            "name": "body",
            "in": "body",
            "description": "Defines the time interval",
            "required": false,
            "schema": {
                "$ref": "#/definitions/EventRequestModel"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully got events",
            "schema": {
              "$ref": "#/definitions/EventResponseModel"
            }
          }
        }
      }
    }
  }
}
<commit_msg>port made compatible with heroku (3)<commit_after>var host = process.env.EM_DOMAIN;

if (!process.env.PORT) {
  var port = process.env.EM_PORT || 5000;
  host += ":" + port;
}
module.exports = {
  "swagger": "2.0",
  "info": {
    "description": "Documentation for Event Mapping Server App.",
    "version": "0.0.1",
    "title": "EventMapping API",
    "contact": {
      "email": "sinem93@gmail.com"
    },
    "license": {
      "name": "MIT",
      "url": "https://github.com/swagger-api/swagger-ui/blob/master/LICENSE"
    }
  },
  "host": host,
  "basePath": "/",
  "produces": ["application/json"],
  "consumes": ["application/json"],
  "schemes": [
    "http"
  ],
  "definitions": {
    "EventRequestModel": {
      "type": "object",
      "properties": {
        "since": {
          "type": "string"
        },
        "until": {
          "type": "string"
        }
      }
    },
    "EventResponseModel": {
      "type": "object",
      "properties": {
        "api": {
          "type": "string"
        },
        "data" : {
          "schema": {
            "$ref": "#/definitions/EventArrayModel"
          }
        }
      }
    },
    "EventArrayModel": {
      "type": "array",
      "items": {
        "schema": {
          "$ref": "#/definitions/EventModel"
        }
      }
    },
    "EventModel": {
      "type": "object",
      "properties" : {
        "api": {
          "description": "API from which event data is taken from",
          "type": "string"
        },
        "name": {
          "description": "name of the event",
          "type": "string"
        },
        "description": {
          "description": "description of the event",
          "type": "string"
        },
        "venue_name": {
          "description": "name of the venue the event is hosted in",
          "type": "string"
        },
        "lat": {
          "description": "latitude of the event",
          "type": "number"
        },
        "lng": {
          "description": "longitude of the event",
          "type": "number"
        },
        "category": {
          "type": "string"
        },
        "photo": {
        },
        "start_time": {
          "type": "string"
        },
        "end_time": {
          "type": "string"
        },
        "attending_count": {
          "type": "number"
        },
        "maybe_count": {
          "type": "number"
        },
        "interested_count": {
          "type": "number"
        },
        "waitlist_count": {
          "type": "number"
        },
        "link": {
          "description": "Url of a location where more info about the event can be found",
          "type": "string"
        }
      }
    }
  },
  "paths": {
    "/density": {
      "post": {
        "tags": ["Get Density"],
        "descriptions": "Returns the density of people in Istanbul for the past 15 mins",
        "notes": "Notes",
        "summary": "summary",
        "responses": {
          "200": {
            "description": "Successfully got density",
            "schema": {
              "type":  "array",
              "items": {
                "type": "array",
                "items": {
                  "type": "number"
                }
              }
            }
          }
        }
      }
      },
    "/weather/current": {
      "post": {
        "tags": ["Get Current Weather"],
        "descriptions": "Returns the current weather for the coordinates if given, or for pre-determined coordinates in Istanbul",
        "parameters": [
          {
            "name": "body",
            "in": "body",
            "description": "Coordinates for which the weather data is requested",
            "required": false,
            "schema": {
              "type": "object",
              "properties": {
                  "coords": {
                    "type": "string"
                  }
              }
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully got the weather data",
            "schema": {
              "type": "object",
              "properties": {
                "api": {
                  "type": "string"
                },
                "data": {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "properties": {
                      "latitude": {
                        "type": "number"
                      },
                      "longitude": {
                        "type": "number"
                      },
                      "apparentTemperature": {
                        "type": "number"
                      },
                      "windSpeed": {
                        "type": "number"
                      },
                      "precipProbability": {
                        "type": "number"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/meetup": {
      "post": {
        "tags": ["Get Meetup Events"],
        "descriptions": "Returns events from Meetup. If no time interval is specified, events in the coming week are returned",
        "parameters" : [
          {
            "name": "body",
            "in": "body",
            "description": "Defines the time interval",
            "required": false,
            "schema": {
              "$ref": "#/definitions/EventRequestModel"
            }
        }
      ],
      "responses": {
        "200": {
          "description": "Successfully got events",
          "schema": {
            "$ref": "#/definitions/EventResponseModel"
          }
        }
      }
      }
    },
    "/eventful": {
      "post": {
        "tags": ["Get Eventful Events"],
        "descriptions": "Returns events from Eventful. If no time interval is specified, events in the coming week are returned",
        "parameters" : [
          {
            "name": "body",
            "in": "body",
            "description": "Defines the time interval",
            "required": false,
            "schema": {
              "$ref": "#/definitions/EventRequestModel"
            }
        }
      ],
      "responses": {
        "200": {
          "description": "Successfully got events",
          "schema": {
            "$ref": "#/definitions/EventResponseModel"
          }
        }
      }
      }
    },
    "/facebook/" : {
      "post": {
        "tags": ["Get Facebook Events"],
        "descriptions": "Returns events from Facebook. If no time interval is specified, events in the coming week are returned",
        "parameters" : [
          {
            "name": "body",
            "in": "body",
            "description": "Defines the time interval",
            "required": false,
            "schema": {
              "$ref": "#/definitions/EventRequestModel"
            }
        }
        ],
        "responses": {
          "200": {
            "description": "Successfully got events",
            "schema": {
              "$ref": "#/definitions/EventResponseModel"
            }
          }
        }
      }
    },
    "/events" : {
      "post": {
        "tags" : ["Get Events"],
        "descriptions": "Returns events from Facebook, Eventful, Meetup API's in the specified time interval. If no time interval is specified, events in the coming week are returned",
        "parameters": [
          {
            "name": "body",
            "in": "body",
            "description": "Defines the time interval",
            "required": false,
            "schema": {
                "$ref": "#/definitions/EventRequestModel"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Successfully got events",
            "schema": {
              "$ref": "#/definitions/EventResponseModel"
            }
          }
        }
      }
    }
  }
}
<|endoftext|>