<commit_before>const { DEFAULT_EXT, DEFAULT_TABLE_NAME } = require('./constants');
const { resolveClientNameWithAliases } = require('../../lib/util/helpers');
const fs = require('fs');
const path = require('path');
const escalade = require('escalade/sync');
const tildify = require('tildify');
const color = require('colorette');
const argv = require('getopts')(process.argv.slice(2));

function mkConfigObj(opts) {
  if (!opts.client) {
    throw new Error(
      `No configuration file found and no commandline connection parameters passed`
    );
  }

  const envName = opts.env || process.env.NODE_ENV || 'development';
  const resolvedClientName = resolveClientNameWithAliases(opts.client);
  const useNullAsDefault = resolvedClientName === 'sqlite3';
  return {
    ext: DEFAULT_EXT,
    [envName]: {
      useNullAsDefault,
      client: opts.client,
      connection: opts.connection,
      migrations: {
        directory: opts.migrationsDirectory,
        tableName: opts.migrationsTableName || DEFAULT_TABLE_NAME,
      },
    },
  };
}

function resolveEnvironmentConfig(opts, allConfigs, configFilePath) {
  const environment = opts.env || process.env.NODE_ENV || 'development';
  const result = allConfigs[environment] || allConfigs;

  if (allConfigs[environment]) {
    console.log('Using environment:', color.magenta(environment));
  }

  if (!result) {
    console.log(color.red('Warning: unable to read knexfile config'));
    process.exit(1);
  }

  if (argv.debug !== undefined) {
    result.debug = argv.debug;
  }

  // It is safe to assume that unless explicitly specified, we would want
  // migrations, seeds etc. to be generated with same extension
  if (configFilePath) {
    result.ext = result.ext || path.extname(configFilePath).replace('.', '');
  }

  return result;
}

function exit(text) {
  if (text instanceof Error) {
    console.error(
      color.red(`${text.detail ? `${text.detail}\n` : ''}${text.stack}`)
    );
  } else {
    console.error(color.red(text));
  }
  process.exit(1);
}

function success(text) {
  console.log(text);
  process.exit(0);
}

function checkLocalModule(env) {
  if (!env.modulePath) {
    console.log(
      color.red('No local knex install found in:'),
      color.magenta(tildify(env.cwd))
    );
    exit('Try running: npm install knex');
  }
}

function getMigrationExtension(env, opts) {
  const config = resolveEnvironmentConfig(
    opts,
    env.configuration,
    env.configPath
  );

  let ext = DEFAULT_EXT;
  if (argv.x) {
    ext = argv.x;
  } else if (config.migrations && config.migrations.extension) {
    ext = config.migrations.extension;
  } else if (config.ext) {
    ext = config.ext;
  }
  return ext.toLowerCase();
}

function getSeedExtension(env, opts) {
  const config = resolveEnvironmentConfig(
    opts,
    env.configuration,
    env.configPath
  );

  let ext = DEFAULT_EXT;
  if (argv.x) {
    ext = argv.x;
  } else if (config.seeds && config.seeds.extension) {
    ext = config.seeds.extension;
  } else if (config.ext) {
    ext = config.ext;
  }
  return ext.toLowerCase();
}

function getStubPath(configKey, env, opts) {
  const config = resolveEnvironmentConfig(opts, env.configuration);
  const stubDirectory = config[configKey] && config[configKey].directory;

  const { stub } = argv;
  if (!stub) {
    return null;
  } else if (stub.includes('/')) {
    // relative path to stub
    return stub;
  }

  // using stub <name> must have config[configKey].directory defined
  if (!stubDirectory) {
    console.log(color.red('Failed to load stub'), color.magenta(stub));
    exit(`config.${configKey}.directory in knexfile must be defined`);
  }

  return path.join(stubDirectory, stub);
}

function findUpModulePath(cwd, packageName) {
  const modulePackagePath = escalade(cwd, (dir, names) => {
    if (names.includes('package.json')) {
      return 'package.json';
    }
    return false;
  });
  try {
    const modulePackage = require(modulePackagePath);
    if (modulePackage.name === packageName) {
      return path.join(
        path.dirname(modulePackagePath),
        modulePackage.main || 'index.js'
      );
    }
  } catch (e) {}
}

function findUpConfig(cwd, name, extensions) {
  return escalade(cwd, (dir, names) => {
    for (const ext of extensions) {
      const filename = `${name}.${ext}`;
      if (names.includes(filename)) {
        return filename;
      }
    }
    return false;
  });
}

module.exports = {
  mkConfigObj,
  resolveEnvironmentConfig,
  exit,
  success,
  checkLocalModule,
  getSeedExtension,
  getMigrationExtension,
  getStubPath,
  findUpModulePath,
  findUpConfig,
};
<commit_msg>log error message (#4534)<commit_after>const { DEFAULT_EXT, DEFAULT_TABLE_NAME } = require('./constants');
const { resolveClientNameWithAliases } = require('../../lib/util/helpers');
const fs = require('fs');
const path = require('path');
const escalade = require('escalade/sync');
const tildify = require('tildify');
const color = require('colorette');
const argv = require('getopts')(process.argv.slice(2));

function mkConfigObj(opts) {
  if (!opts.client) {
    throw new Error(
      `No configuration file found and no commandline connection parameters passed`
    );
  }

  const envName = opts.env || process.env.NODE_ENV || 'development';
  const resolvedClientName = resolveClientNameWithAliases(opts.client);
  const useNullAsDefault = resolvedClientName === 'sqlite3';
  return {
    ext: DEFAULT_EXT,
    [envName]: {
      useNullAsDefault,
      client: opts.client,
      connection: opts.connection,
      migrations: {
        directory: opts.migrationsDirectory,
        tableName: opts.migrationsTableName || DEFAULT_TABLE_NAME,
      },
    },
  };
}

function resolveEnvironmentConfig(opts, allConfigs, configFilePath) {
  const environment = opts.env || process.env.NODE_ENV || 'development';
  const result = allConfigs[environment] || allConfigs;

  if (allConfigs[environment]) {
    console.log('Using environment:', color.magenta(environment));
  }

  if (!result) {
    console.log(color.red('Warning: unable to read knexfile config'));
    process.exit(1);
  }

  if (argv.debug !== undefined) {
    result.debug = argv.debug;
  }

  // It is safe to assume that unless explicitly specified, we would want
  // migrations, seeds etc. to be generated with same extension
  if (configFilePath) {
    result.ext = result.ext || path.extname(configFilePath).replace('.', '');
  }

  return result;
}

function exit(text) {
  if (text instanceof Error) {
    if (text.message) {
      console.error(color.red(text.message));
    }
    console.error(
      color.red(`${text.detail ? `${text.detail}\n` : ''}${text.stack}`)
    );
  } else {
    console.error(color.red(text));
  }
  process.exit(1);
}

function success(text) {
  console.log(text);
  process.exit(0);
}

function checkLocalModule(env) {
  if (!env.modulePath) {
    console.log(
      color.red('No local knex install found in:'),
      color.magenta(tildify(env.cwd))
    );
    exit('Try running: npm install knex');
  }
}

function getMigrationExtension(env, opts) {
  const config = resolveEnvironmentConfig(
    opts,
    env.configuration,
    env.configPath
  );

  let ext = DEFAULT_EXT;
  if (argv.x) {
    ext = argv.x;
  } else if (config.migrations && config.migrations.extension) {
    ext = config.migrations.extension;
  } else if (config.ext) {
    ext = config.ext;
  }
  return ext.toLowerCase();
}

function getSeedExtension(env, opts) {
  const config = resolveEnvironmentConfig(
    opts,
    env.configuration,
    env.configPath
  );

  let ext = DEFAULT_EXT;
  if (argv.x) {
    ext = argv.x;
  } else if (config.seeds && config.seeds.extension) {
    ext = config.seeds.extension;
  } else if (config.ext) {
    ext = config.ext;
  }
  return ext.toLowerCase();
}

function getStubPath(configKey, env, opts) {
  const config = resolveEnvironmentConfig(opts, env.configuration);
  const stubDirectory = config[configKey] && config[configKey].directory;

  const { stub } = argv;
  if (!stub) {
    return null;
  } else if (stub.includes('/')) {
    // relative path to stub
    return stub;
  }

  // using stub <name> must have config[configKey].directory defined
  if (!stubDirectory) {
    console.log(color.red('Failed to load stub'), color.magenta(stub));
    exit(`config.${configKey}.directory in knexfile must be defined`);
  }

  return path.join(stubDirectory, stub);
}

function findUpModulePath(cwd, packageName) {
  const modulePackagePath = escalade(cwd, (dir, names) => {
    if (names.includes('package.json')) {
      return 'package.json';
    }
    return false;
  });
  try {
    const modulePackage = require(modulePackagePath);
    if (modulePackage.name === packageName) {
      return path.join(
        path.dirname(modulePackagePath),
        modulePackage.main || 'index.js'
      );
    }
  } catch (e) {}
}

function findUpConfig(cwd, name, extensions) {
  return escalade(cwd, (dir, names) => {
    for (const ext of extensions) {
      const filename = `${name}.${ext}`;
      if (names.includes(filename)) {
        return filename;
      }
    }
    return false;
  });
}

module.exports = {
  mkConfigObj,
  resolveEnvironmentConfig,
  exit,
  success,
  checkLocalModule,
  getSeedExtension,
  getMigrationExtension,
  getStubPath,
  findUpModulePath,
  findUpConfig,
};
<|endoftext|>


<commit_before>var http = require('http');
var url = require('url');
var config = require('../lib/config');
var util = require('../lib/util');

function parseHeaders(headers, rawHeaderNames) {
  if (!headers || typeof headers != 'string') {
    return {};
  }

  try {
    return util.lowerCaseify(JSON.parse(headers), rawHeaderNames);
  } catch(e) {}

  return util.parseHeaders(headers, rawHeaderNames);
}

module.exports = function(req, res) {
  var _url = req.body.url;

  if (_url && typeof _url == 'string') {
    _url = _url.replace(/#.*$/, '');
    var options = url.parse(util.setProtocol(_url));
    var headers = parseHeaders(req.body.headers);
    if (!headers['user-agent']) {
      headers['user-agent'] = 'whistle/' + config.version;
    }

    if (options.protocol == 'https:') {
      headers[config.HTTPS_FIELD] = 1;
      if (options.port == 443) {
        options.port = '';
      }
    } else if (options.port == 80) {
      options.port = '';
    }

    headers.host = options.hostname;
    if (options.port) {
      headers.host += ':' + options.port;
    }
    options.protocol = null;
    options.hostname = null;
    options.method = req.body.method;
    options.host = '127.0.0.1';
    options.port = config.port;
    options.headers = headers;
    if (headers['content-length'] != null) {
      req.body.body = util.toBuffer(req.body.body || '');
      headers['content-length'] = req.body.body.length;
    }

    headers[config.CLIENT_IP_HEAD] = util.getClientIp(req);

    http.request(options, function(res) {
      res.on('error', util.noop);
      util.drain(res);
    })
.on('error', util.noop)
.end(req.body.body);
  }

  res.json({ec: 0, em: 'success'});
};
<commit_msg>refactor: Keep the original header name<commit_after>var http = require('http');
var url = require('url');
var config = require('../lib/config');
var util = require('../lib/util');

function parseHeaders(headers, rawHeaderNames) {
  if (!headers || typeof headers != 'string') {
    return {};
  }

  try {
    return util.lowerCaseify(JSON.parse(headers), rawHeaderNames);
  } catch(e) {}

  return util.parseHeaders(headers, rawHeaderNames);
}

module.exports = function(req, res) {
  var _url = req.body.url;

  if (_url && typeof _url == 'string') {
    _url = _url.replace(/#.*$/, '');
    var options = url.parse(util.setProtocol(_url));
    var rawHeaderNames = {};
    var headers = parseHeaders(req.body.headers, rawHeaderNames);
    if (!headers['user-agent']) {
      headers['user-agent'] = 'whistle/' + config.version;
    }

    if (options.protocol == 'https:') {
      headers[config.HTTPS_FIELD] = 1;
      if (options.port == 443) {
        options.port = '';
      }
    } else if (options.port == 80) {
      options.port = '';
    }

    headers.host = options.hostname;
    if (options.port) {
      headers.host += ':' + options.port;
    }
    options.protocol = null;
    options.hostname = null;
    options.method = req.body.method;
    options.host = '127.0.0.1';
    options.port = config.port;
    if (headers['content-length'] != null) {
      req.body.body = util.toBuffer(req.body.body || '');
      headers['content-length'] = req.body.body.length;
    }

    headers[config.CLIENT_IP_HEAD] = util.getClientIp(req);
    options.headers = util.formatHeaders(headers, rawHeaderNames);
    http.request(options, function(res) {
      res.on('error', util.noop);
      util.drain(res);
    })
.on('error', util.noop)
.end(req.body.body);
  }

  res.json({ec: 0, em: 'success'});
};
<|endoftext|>


<commit_before><commit_msg>Remove now-unnecessary blockspace visibility check<commit_after><|endoftext|>


<commit_before>

function Calendar(element, options, eventSources) {
	var t = this;

	// exports
	t.options = options;
	t.render = render;
	t.destroy = destroy;
	t.refetchEvents = refetchEvents;
	t.reportEvents = reportEvents;
	t.reportEventChange = reportEventChange;
	t.rerenderEvents = rerenderEvents;
	t.changeView = changeView;
	t.select = select;
	t.unselect = unselect;
	t.prev = prev;
	t.next = next;
	t.prevYear = prevYear;
	t.nextYear = nextYear;
	t.today = today;
	t.gotoDate = gotoDate;
	t.incrementDate = incrementDate;
	t.formatDate = function(format, date) { return formatDate(format, date, options) };
	t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
	t.getDate = getDate;
	t.getView = getView;
	t.option = option;
	t.trigger = trigger;

	// imports
	EventManager.call(t, options, eventSources);
	var isFetchNeeded = t.isFetchNeeded;
	var fetchEvents = t.fetchEvents;

	// locals
	var _element = element[0];
	var header;
	var headerElement;
	var content;
	var tm; // for making theme classes
	var currentView;
	var viewInstances = {};
	var elementOuterWidth;
	var suggestedViewHeight;
	var absoluteViewElement;
	var resizeUID = 0;
	var ignoreWindowResize = 0;
	var date = new Date();
	var events = [];
	var _dragElement;

	/* Main Rendering
	-----------------------------------------------------------------------------*/

	setYMD(date, options.year, options.month, options.date);

	function render(inc) {
		if (!content) {
			initialRender();
		}else{
			calcSize();
			markSizesDirty();
			markEventsDirty();
			renderView(inc);
		}
	}

	function initialRender() {
		tm = options.theme ? 'ui' : 'fc';
		element.addClass('fc');
		if (options.isRTL) {
			element.addClass('fc-rtl');
		}
		if (options.theme) {
			element.addClass('ui-widget');
		}
		content = $("
")
			.prependTo(element);
		header = new Header(t, options);
		headerElement = header.render();
		if (headerElement) {
			element.prepend(headerElement);
		}
		changeView(options.defaultView);
		$(window).resize(windowResize);
		// needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
		if (!bodyVisible()) {
			lateRender();
		}
	}

	// called when we know the calendar couldn't be rendered when it was initialized,
	// but we think it's ready now
	function lateRender() {
		setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
			if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
				renderView();
			}
		},0);
	}

	function destroy() {
		$(window).unbind('resize', windowResize);
		header.destroy();
		content.remove();
		element.removeClass('fc fc-rtl ui-widget');
	}

	function elementVisible() {
		return _element.offsetWidth !== 0;
	}

	function bodyVisible() {
		return $('body')[0].offsetWidth !== 0;
	}

	/* View Rendering
	-----------------------------------------------------------------------------*/

	// TODO: improve view switching (still weird transition in IE, and FF has whiteout problem)

	function changeView(newViewName) {
		if (!currentView || newViewName != currentView.name) {
			ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached

			unselect();

			var oldView = currentView;
			var newViewElement;

			if (oldView) {
				(oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera)
				setMinHeight(content, content.height());
				oldView.element.hide();
			}else{
				setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated
			}
			content.css('overflow', 'hidden');

			currentView = viewInstances[newViewName];
			if (currentView) {
				currentView.element.show();
			}else{
				currentView = viewInstances[newViewName] = new fcViews[newViewName](
					newViewElement = absoluteViewElement =
						$("
")
							.appendTo(content),
					t // the calendar object
				);
			}

			if (oldView) {
				header.deactivateButton(oldView.name);
			}
			header.activateButton(newViewName);

			renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null

			content.css('overflow', '');
			if (oldView) {
				setMinHeight(content, 1);
			}

			if (!newViewElement) {
				(currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera)
			}

			ignoreWindowResize--;
		}
	}

	function renderView(inc) {
		if (elementVisible()) {
			ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached

			unselect();

			if (suggestedViewHeight === undefined) {
				calcSize();
			}

			var forceEventRender = false;
			if (!currentView.start || inc || date < currentView.start || date >= currentView.end) {
				// view must render an entire new date range (and refetch/render events)
				currentView.render(date, inc || 0); // responsible for clearing events
				setSize(true);
				forceEventRender = true;
			}
			else if (currentView.sizeDirty) {
				// view must resize (and rerender events)
				currentView.clearEvents();
				setSize();
				forceEventRender = true;
			}
			else if (currentView.eventsDirty) {
				currentView.clearEvents();
				forceEventRender = true;
			}
			currentView.sizeDirty = false;
			currentView.eventsDirty = false;
			updateEvents(forceEventRender);

			elementOuterWidth = element.outerWidth();

			header.updateTitle(currentView.title);
			var today = new Date();
			if (today >= currentView.start && today < currentView.end) {
				header.disableButton('today');
			}else{
				header.enableButton('today');
			}

			ignoreWindowResize--;
			currentView.trigger('viewDisplay', _element);
		}
	}

	/* Resizing
	-----------------------------------------------------------------------------*/

	function updateSize() {
		markSizesDirty();
		if (elementVisible()) {
			calcSize();
			setSize();
			unselect();
			currentView.clearEvents();
			currentView.renderEvents(events);
			currentView.sizeDirty = false;
		}
	}

	function markSizesDirty() {
		$.each(viewInstances, function(i, inst) {
			inst.sizeDirty = true;
		});
	}

	function calcSize() {
		if (options.contentHeight) {
			suggestedViewHeight = options.contentHeight;
		}
		else if (options.height) {
			suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
		}
		else {
			suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
		}
	}

	function setSize(dateChanged) { // todo: dateChanged?
		ignoreWindowResize++;
		currentView.setHeight(suggestedViewHeight, dateChanged);
		if (absoluteViewElement) {
			absoluteViewElement.css('position', 'relative');
			absoluteViewElement = null;
		}
		currentView.setWidth(content.width(), dateChanged);
		ignoreWindowResize--;
	}

	function windowResize() {
		if (!ignoreWindowResize) {
			if (currentView.start) { // view has already been rendered
				var uid = ++resizeUID;
				setTimeout(function() { // add a delay
					if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
						if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
							ignoreWindowResize++; // in case the windowResize callback changes the height
							updateSize();
							currentView.trigger('windowResize', _element);
							ignoreWindowResize--;
						}
					}
				}, 200);
			}else{
				// calendar must have been initialized in a 0x0 iframe that has just been resized
				lateRender();
			}
		}
	}

	/* Event Fetching/Rendering
	-----------------------------------------------------------------------------*/

	// fetches events if necessary, rerenders events if necessary (or if forced)
	function updateEvents(forceRender) {
		if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
			refetchEvents();
		}
		else if (forceRender) {
			rerenderEvents();
		}
	}

	function refetchEvents() {
		fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents
	}

	// called when event data arrives
	function reportEvents(_events) {
		events = _events;
		rerenderEvents();
	}

	// called when a single event's data has been changed
	function reportEventChange(eventID) {
		rerenderEvents(eventID);
	}

	// attempts to rerenderEvents
	function rerenderEvents(modifiedEventID) {
		markEventsDirty();
		if (elementVisible()) {
			currentView.clearEvents();
			currentView.renderEvents(events, modifiedEventID);
			currentView.eventsDirty = false;
		}
	}

	function markEventsDirty() {
		$.each(viewInstances, function(i, inst) {
			inst.eventsDirty = true;
		});
	}

	/* Selection
	-----------------------------------------------------------------------------*/

	function select(start, end, allDay) {
		currentView.select(start, end, allDay===undefined ? true : allDay);
	}

	function unselect() { // safe to be called before renderView
		if (currentView) {
			currentView.unselect();
		}
	}

	/* Date
	-----------------------------------------------------------------------------*/

	function prev() {
		renderView(-1);
	}

	function next() {
		renderView(1);
	}

	function prevYear() {
		addYears(date, -1);
		renderView();
	}

	function nextYear() {
		addYears(date, 1);
		renderView();
	}

	function today() {
		date = new Date();
		renderView();
	}

	function gotoDate(year, month, dateOfMonth) {
		if (year instanceof Date) {
			date = cloneDate(year); // provided 1 argument, a Date
		}else{
			setYMD(date, year, month, dateOfMonth);
		}
		renderView();
	}

	function incrementDate(years, months, days) {
		if (years !== undefined) {
			addYears(date, years);
		}
		if (months !== undefined) {
			addMonths(date, months);
		}
		if (days !== undefined) {
			addDays(date, days);
		}
		renderView();
	}

	function getDate() {
		return cloneDate(date);
	}

	/* Misc
	-----------------------------------------------------------------------------*/

	function getView() {
		return currentView;
	}

	function option(name, value) {
		if (value === undefined) {
			return options[name];
		}
		if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
			options[name] = value;
			updateSize();
		}
	}

	function trigger(name, thisObj) {
		if (options[name]) {
			return options[name].apply(
				thisObj || _element,
				Array.prototype.slice.call(arguments, 2)
			);
		}
	}

	/* External Dragging
	------------------------------------------------------------------------*/

	if (options.droppable) {
		$(document)
			.bind('dragstart', function(ev, ui) {
				var _e = ev.target;
				var e = $(_e);
				if (!e.parents('.fc').length) { // not already inside a calendar
					var accept = options.dropAccept;
					if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
						_dragElement = _e;
						currentView.dragStart(_dragElement, ev, ui);
					}
				}
			})
			.bind('dragstop', function(ev, ui) {
				if (_dragElement) {
					currentView.dragStop(_dragElement, ev, ui);
					_dragElement = null;
				}
			});
	}

}
<commit_msg>Adds afterEventChange callback which can be used to run custom code when an event is changed.<commit_after>

function Calendar(element, options, eventSources) {
	var t = this;

	// exports
	t.options = options;
	t.render = render;
	t.destroy = destroy;
	t.refetchEvents = refetchEvents;
	t.reportEvents = reportEvents;
	t.reportEventChange = reportEventChange;
	t.rerenderEvents = rerenderEvents;
	t.changeView = changeView;
	t.select = select;
	t.unselect = unselect;
	t.prev = prev;
	t.next = next;
	t.prevYear = prevYear;
	t.nextYear = nextYear;
	t.today = today;
	t.gotoDate = gotoDate;
	t.incrementDate = incrementDate;
	t.formatDate = function(format, date) { return formatDate(format, date, options) };
	t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
	t.getDate = getDate;
	t.getView = getView;
	t.option = option;
	t.trigger = trigger;

	// imports
	EventManager.call(t, options, eventSources);
	var isFetchNeeded = t.isFetchNeeded;
	var fetchEvents = t.fetchEvents;

	// locals
	var _element = element[0];
	var header;
	var headerElement;
	var content;
	var tm; // for making theme classes
	var currentView;
	var viewInstances = {};
	var elementOuterWidth;
	var suggestedViewHeight;
	var absoluteViewElement;
	var resizeUID = 0;
	var ignoreWindowResize = 0;
	var date = new Date();
	var events = [];
	var _dragElement;

	/* Main Rendering
	-----------------------------------------------------------------------------*/

	setYMD(date, options.year, options.month, options.date);

	function render(inc) {
		if (!content) {
			initialRender();
		}else{
			calcSize();
			markSizesDirty();
			markEventsDirty();
			renderView(inc);
		}
	}

	function initialRender() {
		tm = options.theme ? 'ui' : 'fc';
		element.addClass('fc');
		if (options.isRTL) {
			element.addClass('fc-rtl');
		}
		if (options.theme) {
			element.addClass('ui-widget');
		}
		content = $("
")
			.prependTo(element);
		header = new Header(t, options);
		headerElement = header.render();
		if (headerElement) {
			element.prepend(headerElement);
		}
		changeView(options.defaultView);
		$(window).resize(windowResize);
		// needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
		if (!bodyVisible()) {
			lateRender();
		}
	}

	// called when we know the calendar couldn't be rendered when it was initialized,
	// but we think it's ready now
	function lateRender() {
		setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
			if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
				renderView();
			}
		},0);
	}

	function destroy() {
		$(window).unbind('resize', windowResize);
		header.destroy();
		content.remove();
		element.removeClass('fc fc-rtl ui-widget');
	}

	function elementVisible() {
		return _element.offsetWidth !== 0;
	}

	function bodyVisible() {
		return $('body')[0].offsetWidth !== 0;
	}

	/* View Rendering
	-----------------------------------------------------------------------------*/

	// TODO: improve view switching (still weird transition in IE, and FF has whiteout problem)

	function changeView(newViewName) {
		if (!currentView || newViewName != currentView.name) {
			ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached

			unselect();

			var oldView = currentView;
			var newViewElement;

			if (oldView) {
				(oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera)
				setMinHeight(content, content.height());
				oldView.element.hide();
			}else{
				setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated
			}
			content.css('overflow', 'hidden');

			currentView = viewInstances[newViewName];
			if (currentView) {
				currentView.element.show();
			}else{
				currentView = viewInstances[newViewName] = new fcViews[newViewName](
					newViewElement = absoluteViewElement =
						$("
")
							.appendTo(content),
					t // the calendar object
				);
			}

			if (oldView) {
				header.deactivateButton(oldView.name);
			}
			header.activateButton(newViewName);

			renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null

			content.css('overflow', '');
			if (oldView) {
				setMinHeight(content, 1);
			}

			if (!newViewElement) {
				(currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera)
			}

			ignoreWindowResize--;
		}
	}

	function renderView(inc) {
		if (elementVisible()) {
			ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached

			unselect();

			if (suggestedViewHeight === undefined) {
				calcSize();
			}

			var forceEventRender = false;
			if (!currentView.start || inc || date < currentView.start || date >= currentView.end) {
				// view must render an entire new date range (and refetch/render events)
				currentView.render(date, inc || 0); // responsible for clearing events
				setSize(true);
				forceEventRender = true;
			}
			else if (currentView.sizeDirty) {
				// view must resize (and rerender events)
				currentView.clearEvents();
				setSize();
				forceEventRender = true;
			}
			else if (currentView.eventsDirty) {
				currentView.clearEvents();
				forceEventRender = true;
			}
			currentView.sizeDirty = false;
			currentView.eventsDirty = false;
			updateEvents(forceEventRender);

			elementOuterWidth = element.outerWidth();

			header.updateTitle(currentView.title);
			var today = new Date();
			if (today >= currentView.start && today < currentView.end) {
				header.disableButton('today');
			}else{
				header.enableButton('today');
			}

			ignoreWindowResize--;
			currentView.trigger('viewDisplay', _element);
		}
	}

	/* Resizing
	-----------------------------------------------------------------------------*/

	function updateSize() {
		markSizesDirty();
		if (elementVisible()) {
			calcSize();
			setSize();
			unselect();
			currentView.clearEvents();
			currentView.renderEvents(events);
			currentView.sizeDirty = false;
		}
	}

	function markSizesDirty() {
		$.each(viewInstances, function(i, inst) {
			inst.sizeDirty = true;
		});
	}

	function calcSize() {
		if (options.contentHeight) {
			suggestedViewHeight = options.contentHeight;
		}
		else if (options.height) {
			suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
		}
		else {
			suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
		}
	}

	function setSize(dateChanged) { // todo: dateChanged?
		ignoreWindowResize++;
		currentView.setHeight(suggestedViewHeight, dateChanged);
		if (absoluteViewElement) {
			absoluteViewElement.css('position', 'relative');
			absoluteViewElement = null;
		}
		currentView.setWidth(content.width(), dateChanged);
		ignoreWindowResize--;
	}

	function windowResize() {
		if (!ignoreWindowResize) {
			if (currentView.start) { // view has already been rendered
				var uid = ++resizeUID;
				setTimeout(function() { // add a delay
					if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
						if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
							ignoreWindowResize++; // in case the windowResize callback changes the height
							updateSize();
							currentView.trigger('windowResize', _element);
							ignoreWindowResize--;
						}
					}
				}, 200);
			}else{
				// calendar must have been initialized in a 0x0 iframe that has just been resized
				lateRender();
			}
		}
	}

	/* Event Fetching/Rendering
	-----------------------------------------------------------------------------*/

	// fetches events if necessary, rerenders events if necessary (or if forced)
	function updateEvents(forceRender) {
		if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
			refetchEvents();
		}
		else if (forceRender) {
			rerenderEvents();
		}
	}

	function refetchEvents() {
		fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents
	}

	// called when event data arrives
	function reportEvents(_events) {
		events = _events;
		rerenderEvents();
	}

	// called when a single event's data has been changed
	function reportEventChange(eventID) {
		rerenderEvents(eventID);
		trigger('afterEventChange', Calendar, eventID);
	}

	// attempts to rerenderEvents
	function rerenderEvents(modifiedEventID) {
		markEventsDirty();
		if (elementVisible()) {
			currentView.clearEvents();
			currentView.renderEvents(events, modifiedEventID);
			currentView.eventsDirty = false;
		}
	}

	function markEventsDirty() {
		$.each(viewInstances, function(i, inst) {
			inst.eventsDirty = true;
		});
	}

	/* Selection
	-----------------------------------------------------------------------------*/

	function select(start, end, allDay) {
		currentView.select(start, end, allDay===undefined ? true : allDay);
	}

	function unselect() { // safe to be called before renderView
		if (currentView) {
			currentView.unselect();
		}
	}

	/* Date
	-----------------------------------------------------------------------------*/

	function prev() {
		renderView(-1);
	}

	function next() {
		renderView(1);
	}

	function prevYear() {
		addYears(date, -1);
		renderView();
	}

	function nextYear() {
		addYears(date, 1);
		renderView();
	}

	function today() {
		date = new Date();
		renderView();
	}

	function gotoDate(year, month, dateOfMonth) {
		if (year instanceof Date) {
			date = cloneDate(year); // provided 1 argument, a Date
		}else{
			setYMD(date, year, month, dateOfMonth);
		}
		renderView();
	}

	function incrementDate(years, months, days) {
		if (years !== undefined) {
			addYears(date, years);
		}
		if (months !== undefined) {
			addMonths(date, months);
		}
		if (days !== undefined) {
			addDays(date, days);
		}
		renderView();
	}

	function getDate() {
		return cloneDate(date);
	}

	/* Misc
	-----------------------------------------------------------------------------*/

	function getView() {
		return currentView;
	}

	function option(name, value) {
		if (value === undefined) {
			return options[name];
		}
		if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
			options[name] = value;
			updateSize();
		}
	}

	function trigger(name, thisObj) {
		if (options[name]) {
			return options[name].apply(
				thisObj || _element,
				Array.prototype.slice.call(arguments, 2)
			);
		}
	}

	/* External Dragging
	------------------------------------------------------------------------*/

	if (options.droppable) {
		$(document)
			.bind('dragstart', function(ev, ui) {
				var _e = ev.target;
				var e = $(_e);
				if (!e.parents('.fc').length) { // not already inside a calendar
					var accept = options.dropAccept;
					if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
						_dragElement = _e;
						currentView.dragStart(_dragElement, ev, ui);
					}
				}
			})
			.bind('dragstop', function(ev, ui) {
				if (_dragElement) {
					currentView.dragStop(_dragElement, ev, ui);
					_dragElement = null;
				}
			});
	}

}
<|endoftext|>


<commit_before>/* Copyright 2015 Bloomberg Finance L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define(["widgets/js/manager", "d3", "./utils", "./ColorUtils", "./Axis"], function(WidgetManager, d3, utils, Col_Pic, Axis) {
    var AxisView = Axis[0];
    var ColorBar = AxisView.extend({
        render: function() {
            this.parent = this.options.parent;
            this.highlight = this.options.highlight;
            this.margin = this.parent.margin;
            this.vertical = this.model.get("orientation") == "vertical" ? true : false;
            this.height = this.parent.height - (this.margin.top + this.margin.bottom);
            this.width = this.parent.width - (this.margin.left + this.margin.right);
            this.unique_id = IPython.utils.uuid();

            // scale data for drawing the axis
            var scale = this.model.get("scale");
            var that = this;
            this.create_child_view(scale).then(function(view) {
                that.axis_scale = view;
                that.axis_scale.set_range();
                that.axis_scale.on("domain_changed", that.redraw_axisline, that);
                that.axis_scale.on("color_scale_range_changed", that.redraw_axis, that);
                if(that.axis_scale.model.type == "date_color_linear") {
                    that.axis_line_scale = d3.time.scale().nice();
                } else if(that.axis_scale.model.type == "ordinal") {
                    that.axis_line_scale = d3.scale.ordinal();
                    that.ordinal = true;
                } else {
                    that.axis_line_scale = d3.scale.linear();
                }

                that.tick_format = that.generate_tick_formatter();
                that.append_axis();
            });

            // attributes used in drawing the color bar
            this.x_offset = 100;
            this.y_offset = 40;
            this.bar_height = 20;
            this.side = this.model.get("side");
            // Formatting data particular to the axis
            this.el = d3.select(document.createElementNS(d3.ns.prefix.svg, "g"))
                .attr("class", "ColorBar")
                .attr("display", (this.model.get("visible") ? "inline" : "none"))
                .style("transform", this.get_topg_transform());

            this.label = this.model.get("label");
            this.ordinal = false;
            this.num_ticks = this.model.get("num_ticks");
            this.tick_values = this.model.get("tick_values");

            this.parent.on("margin_updated", this.parent_margin_updated, this);
            this.model.on("change:tick_format", this.tickformat_changed, this);
            this.model.on("change:visible", this.update_visibility, this);
            this.model.on("change:label", this.update_label, this);
        },
        append_axis: function() {
            // The label is allocated a space of 100px. If the label
            // occupies more than 100px then you are out of luck :)
            this.axis_line_scale.domain(this.axis_scale.scale.domain());
            this.set_scales_range();

            this.axis = d3.svg.axis()
                .scale(this.axis_line_scale)
                .orient(this.side)
                .tickFormat(this.tick_format);

            var that = this;
            if(this.label) {
                this.el.append("g")
                    .attr("transform", this.get_label_transform())
                    .attr("class", "axis")
                    .append("text")
                    .append("tspan")
                    .attr("id", "text_elem")
                    .attr("dy", "0.5ex")
                    .text(this.model.get("label"))
                    .attr("class", "axislabel")
                    .style("text-anchor", this.vertical ? "middle" : "end");
            }

            var colorBar = this.el.append("g")
                .attr({
                    "id"        : "colorBarG" + this.unique_id,
                    "transform" : this.get_colorbar_transform()
                });

            this.draw_color_bar();
            this.g_axisline = colorBar.append("g")
                .attr("class", "axis")
                .call(this.axis)
                .attr("transform", this.get_axisline_transform());
            this.set_tick_values();
        },
        draw_color_bar: function() {
            var colorBar = this.el.select("#colorBarG" + this.unique_id);
            var that = this;
            colorBar.selectAll(".g-rect")
                .remove();
            colorBar.selectAll(".g-defs")
                .remove();

            this.set_scales_range();
            this.colors = this.axis_scale.scale.range();
            var colorSpacing = 100 / (this.colors.length - 1);

            if(this.ordinal) {
                var bar_width = this.get_color_bar_width() / this.colors.length;
                var rects = colorBar.append("g")
                    .attr("class", "g-rect axis")
                    .style("transform", (this.vertical) ? "rotate(-90deg)" : "")
                    .selectAll("rect")
                    .data(this.colors);

                rects.enter()
                    .append("rect")
                    .attr("y", 0)
                    .attr("height", this.bar_height)
                    .attr("width", bar_width)
                    .style("fill",function(d) { return d; });

                if(this.vertical) {
                    rects.attr("x", function(d, i) { return i * bar_width - (that.height - 2 * that.x_offset)  ; });
                } else {
                    rects.attr("x", function(d, i) { return i * bar_width; });
                }
            }
            else {
                colorBar.append("g")
                    .attr("class", "g-defs")
                    .append("defs")
                    .append("linearGradient")
                    .attr({
                        id : "colorBarGradient" + this.unique_id,
                        x1 : "0%",
                        y1 : "0%",
                        x2 : "100%",
                        y2 : "0%"
                    })
                    .selectAll("stop")
                    .data(this.colors)
                    .enter()
                    .append("stop")
                    .attr({
                        "offset": function(d,i){return colorSpacing * (i) + "%"},
                        "stop-color":function(d,i){return that.colors[i]},
                        "stop-opacity":1
                    });

                colorBar.append("g")
                    .attr("class", "g-rect axis")
                    .style("transform", (this.vertical) ? "rotate(-90deg)" : "")
                    .append("rect")
                    .attr({
                        "width": this.get_color_bar_width(),
                        "height": this.bar_height,
                        x: (this.vertical) ? -(this.height - 2 * this.x_offset) : 0,
                        y: 0,
                        "stroke-width":1
                    })
                    .style("fill","url(#colorBarGradient" + this.unique_id + ")");
            }
        },
        get_topg_transform: function() {
            if(this.vertical){
                if(this.side == "right") {
                    return "translate(" + this.get_basic_transform() + "px, 0px)" + " translate(" + this.margin.right + "px, 0px)" +
                         " translate(" + (-this.bar_height) + "px, 0px) translate(-5em, 0px)";
                }
                    return "translate(" + this.get_basic_transform() + "px, 0px)" + " translate(" + -(this.margin.left) + "px, 0px)" +
                         " translate(" + (this.bar_height) + "px, 0px) translate(5em, 0px)";

            } else {
                return "translate(0px, " + this.get_basic_transform() + "px)" + "translate(0px, " + this.margin.bottom + "px)" +
                         " translate(0px, " + (-this.bar_height) + "px) translate(0px, -2em)";
            }
        },
        get_label_transform: function() {
            if(this.vertical) {
                return "translate(" + ((this.side == "right") ? (this.bar_height / 2) : (-this.bar_height / 2)) + ", " + (this.x_offset - 15) + ")";
            }
            return "translate(" + (this.x_offset - 5) + ", " + (this.bar_height / 2)+ ")";
        },
        get_axisline_transform: function() {
            if(this.vertical) {
                return "translate(" + ((this.side == "right") ? this.bar_height : -(this.bar_height)) + ", 0)";
            }
            return "translate(0, " + this.bar_height + ")";
        },
        get_colorbar_transform: function() {
            if(this.vertical) {
                return "translate(0, " + (this.x_offset) + ")";
            }
            return "translate(" + this.x_offset + ", 0)";
        },
        set_scales_range: function() {
            var range = (this.vertical) ? [this.height - 2 * this.x_offset, 0] : [0, this.width -  2 * this.x_offset];
            if(this.ordinal) {
                this.axis_line_scale.rangeRoundBands(range, 0.05);
            }
            else {
                if(this.axis_scale.divergent) {
                    this.axis_line_scale.range([range[0], (range[0] + range[1]) * 0.5, range[1]]);
                } else {
                    this.axis_line_scale.range(range);
                }
            }
        },
        get_color_bar_width: function() {
            return (this.vertical) ? (this.height - (2 * this.x_offset)) : (this.width - 2 * this.x_offset);
        },
        tickformat_changed: function() {
            this.tick_format = this.generate_tick_formatter();
            this.axis.tickFormat(this.tick_format);
            if(this.g_axisline) {
                this.g_axisline.call(this.axis);
            }
        },
        update_label: function(model, value) {
            this.label = value;
            this.el.select("#text_elem")
                .text(this.label);
        },
        rescale_axis: function() {
            // rescale the axis
            this.height = this.parent.height - (this.margin.top + this.margin.bottom);
            this.width = this.parent.width - (this.margin.left + this.margin.right);
            this.set_scales_range();
            // shifting the entire g of the color bar first.
            this.el.style("transform", this.get_topg_transform());
            var self = this;
            var bar_width = this.get_color_bar_width() / this.colors.length;
            if(this.ordinal) {
                var rectangles = this.el.select("#colorBarG" + this.unique_id)
                    .select(".g-rect")
                    .selectAll("rect")
                    .attr("width", bar_width);
                if(this.vertical)
                    rectangles.attr("x", function(d, i) { return (i * bar_width) - (self.height - 2 * self.x_offset)  ; });
                else
                    rectangles.attr("x", function(d, i) { return i * bar_width; });
            } else {
                this.el.select("#colorBarG" + this.unique_id)
                    .select(".g-rect")
                    .selectAll("rect")
                    .attr("width", this.get_color_bar_width())
                    .attr("x", (this.vertical) ? -(this.height - 2 * this.x_offset) : 0);
            }
            this.g_axisline.call(this.axis);
        },
        redraw_axisline: function() {
            this.axis_line_scale.domain(this.axis_scale.scale.domain());
            this.axis.scale(this.axis_line_scale);
            this.set_tick_values();
            this.g_axisline.call(this.axis);
        },
        redraw_axis: function() {
            this.draw_color_bar();
            this.redraw_axisline();
        },
        set_tick_values: function() {
            if (this.tick_values.length > 0) {
                this.axis.tickValues(this.tick_values);
            } else if (this.num_ticks != undefined) {
                    this.axis.tickValues(this.get_ticks())
            } else {
                this.axis.tickValues((this.axis_scale.model.type == "ordinal")
                                    ? this.axis_scale.scale.domain()
                                    : this.axis_scale.scale.ticks())
            }
            this.axis.tickFormat(this.tick_format);
            if(this.g_axisline) {
                this.g_axisline.call(this.axis);
            }
        },
    });
    WidgetManager.WidgetManager.register_widget_view("bqplot.ColorAxis", ColorBar);

});
<commit_msg>color axis bug fix<commit_after>/* Copyright 2015 Bloomberg Finance L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define(["widgets/js/manager", "d3", "./utils", "./ColorUtils", "./Axis"], function(WidgetManager, d3, utils, Col_Pic, Axis) {
    var AxisView = Axis[0];
    var ColorBar = AxisView.extend({
        render: function() {
            this.parent = this.options.parent;
            this.highlight = this.options.highlight;
            this.margin = this.parent.margin;
            this.vertical = this.model.get("orientation") == "vertical" ? true : false;
            this.height = this.parent.height - (this.margin.top + this.margin.bottom);
            this.width = this.parent.width - (this.margin.left + this.margin.right);
            this.unique_id = IPython.utils.uuid();

            // scale data for drawing the axis
            var scale = this.model.get("scale");
            var that = this;
            this.create_child_view(scale).then(function(view) {
                that.axis_scale = view;
                that.axis_scale.set_range();
                that.axis_scale.on("domain_changed", that.redraw_axisline, that);
                that.axis_scale.on("color_scale_range_changed", that.redraw_axis, that);
                if(that.axis_scale.model.type == "date_color_linear") {
                    that.axis_line_scale = d3.time.scale().nice();
                } else if(that.axis_scale.model.type == "ordinal") {
                    that.axis_line_scale = d3.scale.ordinal();
                    that.ordinal = true;
                } else {
                    that.axis_line_scale = d3.scale.linear();
                }

                that.tick_format = that.generate_tick_formatter();
                that.append_axis();
            });

            // attributes used in drawing the color bar
            this.x_offset = 100;
            this.y_offset = 40;
            this.bar_height = 20;
            this.side = this.model.get("side");
            // Formatting data particular to the axis
            this.el = d3.select(document.createElementNS(d3.ns.prefix.svg, "g"))
                .attr("class", "ColorBar")
                .attr("display", (this.model.get("visible") ? "inline" : "none"))
                .style("transform", this.get_topg_transform());

            this.label = this.model.get("label");
            this.ordinal = false;
            this.num_ticks = this.model.get("num_ticks");
            this.tick_values = this.model.get("tick_values");

            this.parent.on("margin_updated", this.parent_margin_updated, this);
            this.model.on("change:tick_format", this.tickformat_changed, this);
            this.model.on("change:visible", this.update_visibility, this);
            this.model.on("change:label", this.update_label, this);
            this.model.on_some_change(["side", "orientation"], function() { this.vertical = this.model.get("orientation") == "vertical" ? true : false;
                                                                            this.side = this.model.get("side");
                                                                            this.rescale_axis();
                                                                            this.redraw_axis();
                                                                          }, this);
        },
        append_axis: function() {
            // The label is allocated a space of 100px. If the label
            // occupies more than 100px then you are out of luck :)
            this.set_scales_range();
            var that = this;
            if(this.label) {
                this.el.append("g")
                    .attr("transform", this.get_label_transform())
                    .attr("class", "axis label_g")
                    .append("text")
                    .append("tspan")
                    .attr("id", "text_elem")
                    .attr("dy", "0.5ex")
                    .text(this.model.get("label"))
                    .attr("class", "axislabel")
                    .style("text-anchor", this.vertical ? "middle" : "end");
            }

            var colorBar = this.el.append("g").attr("id","colorBarG" + this.unique_id);

            this.draw_color_bar();
            this.axis_line_scale.domain(this.axis_scale.scale.domain());

            this.g_axisline = colorBar.append("g")
                .attr("class", "axis");

            this.axis = d3.svg.axis()
                .tickFormat(this.tick_format);
            this.redraw_axisline();
        },
        draw_color_bar: function() {
            var colorBar = this.el.select("#colorBarG" + this.unique_id);
            colorBar.attr("transform", this.get_colorbar_transform());

            var that = this;
            colorBar.selectAll(".g-rect")
                .remove();
            colorBar.selectAll(".g-defs")
                .remove();

            this.set_scales_range();
            this.colors = this.axis_scale.scale.range();
            var colorSpacing = 100 / (this.colors.length - 1);

            if(this.ordinal) {
                var bar_width = this.get_color_bar_width() / this.colors.length;
                var rects = colorBar.append("g")
                    .attr("class", "g-rect axis")
                    .style("transform", (this.vertical) ? "rotate(-90deg)" : "")
                    .selectAll("rect")
                    .data(this.colors);

                rects.enter()
                    .append("rect")
                    .attr("y", 0)
                    .attr("height", this.bar_height)
                    .attr("width", bar_width)
                    .style("fill",function(d) { return d; });

                if(this.vertical) {
                    rects.attr("x", function(d, i) { return i * bar_width - (that.height - 2 * that.x_offset)  ; });
                } else {
                    rects.attr("x", function(d, i) { return i * bar_width; });
                }
            }
            else {
                colorBar.append("g")
                    .attr("class", "g-defs")
                    .append("defs")
                    .append("linearGradient")
                    .attr({
                        id : "colorBarGradient" + this.unique_id,
                        x1 : "0%",
                        y1 : "0%",
                        x2 : "100%",
                        y2 : "0%"
                    })
                    .selectAll("stop")
                    .data(this.colors)
                    .enter()
                    .append("stop")
                    .attr({
                        "offset": function(d,i){return colorSpacing * (i) + "%"},
                        "stop-color":function(d,i){return that.colors[i]},
                        "stop-opacity":1
                    });

                colorBar.append("g")
                    .attr("class", "g-rect axis")
                    .style("transform", (this.vertical) ? "rotate(-90deg)" : "")
                    .append("rect")
                    .attr({
                        "width": this.get_color_bar_width(),
                        "height": this.bar_height,
                        x: (this.vertical) ? -(this.height - 2 * this.x_offset) : 0,
                        y: 0,
                        "stroke-width":1
                    })
                    .style("fill","url(#colorBarGradient" + this.unique_id + ")");
            }
        },
        get_topg_transform: function() {
            if(this.vertical){
                if(this.side == "right") {
                    return "translate(" + this.get_basic_transform() + "px, 0px)" + " translate(" + this.margin.right + "px, 0px)" +
                         " translate(" + (-this.bar_height) + "px, 0px) translate(-5em, 0px)";
                }
                    return "translate(" + this.get_basic_transform() + "px, 0px)" + " translate(" + -(this.margin.left) + "px, 0px)" +
                         " translate(" + (this.bar_height) + "px, 0px) translate(5em, 0px)";

            } else {
                return "translate(0px, " + this.get_basic_transform() + "px)" + "translate(0px, " + this.margin.bottom + "px)" +
                         " translate(0px, " + (-this.bar_height) + "px) translate(0px, -2em)";
            }
        },
        get_label_transform: function() {
            if(this.vertical) {
                return "translate(" + ((this.side == "right") ? (this.bar_height / 2) : (-this.bar_height / 2)) + ", " + (this.x_offset - 15) + ")";
            }
            return "translate(" + (this.x_offset - 5) + ", " + (this.bar_height / 2)+ ")";
        },
        get_axisline_transform: function() {
            if(this.vertical) {
                return "translate(" + ((this.side == "right") ? this.bar_height : -(this.bar_height)) + ", 0)";
            }
            return "translate(0, " + this.bar_height + ")";
        },
        get_colorbar_transform: function() {
            if(this.vertical) {
                return "translate(0, " + (this.x_offset) + ")";
            }
            return "translate(" + this.x_offset + ", 0)";
        },
        set_scales_range: function() {
            var range = (this.vertical) ? [this.height - 2 * this.x_offset, 0] : [0, this.width -  2 * this.x_offset];
            if(this.ordinal) {
                this.axis_line_scale.rangeRoundBands(range, 0.05);
            }
            else {
                if(this.axis_scale.divergent) {
                    this.axis_line_scale.range([range[0], (range[0] + range[1]) * 0.5, range[1]]);
                } else {
                    this.axis_line_scale.range(range);
                }
            }
        },
        get_color_bar_width: function() {
            return (this.vertical) ? (this.height - (2 * this.x_offset)) : (this.width - 2 * this.x_offset);
        },
        tickformat_changed: function() {
            this.tick_format = this.generate_tick_formatter();
            this.axis.tickFormat(this.tick_format);
            if(this.g_axisline) {
                this.g_axisline.call(this.axis);
            }
        },
        update_label: function(model, value) {
            this.label = value;
            this.el.select("#text_elem")
                .text(this.label);
        },
        rescale_axis: function() {
            // rescale the axis
            this.height = this.parent.height - (this.margin.top + this.margin.bottom);
            this.width = this.parent.width - (this.margin.left + this.margin.right);
            this.set_scales_range();
            // shifting the entire g of the color bar first.
            this.el.style("transform", this.get_topg_transform());
            var self = this;
            var bar_width = this.get_color_bar_width() / this.colors.length;
            if(this.ordinal) {
                var rectangles = this.el.select("#colorBarG" + this.unique_id)
                    .select(".g-rect")
                    .selectAll("rect")
                    .attr("width", bar_width);
                if(this.vertical)
                    rectangles.attr("x", function(d, i) { return (i * bar_width) - (self.height - 2 * self.x_offset)  ; });
                else
                    rectangles.attr("x", function(d, i) { return i * bar_width; });
            } else {
                this.el.select("#colorBarG" + this.unique_id)
                    .select(".g-rect")
                    .selectAll("rect")
                    .attr("width", this.get_color_bar_width())
                    .attr("x", (this.vertical) ? -(this.height - 2 * this.x_offset) : 0);
            }
            if(this.label) {
                this.el.select(".label_g")
                    .attr("transform", this.get_label_transform())
                    .select("#text_elem")
                    .text(this.model.get("label"))
                    .style("text-anchor", this.vertical ? "middle" : "end");
            }
            this.g_axisline.call(this.axis);
        },
        redraw_axisline: function() {
            this.axis_line_scale.domain(this.axis_scale.scale.domain());
            this.axis.orient(this.side)
                .scale(this.axis_line_scale);
            this.set_tick_values();
            this.g_axisline
                .attr("transform", this.get_axisline_transform())
                .call(this.axis);
        },
        redraw_axis: function() {
            this.draw_color_bar();
            this.redraw_axisline();
        },
        set_tick_values: function() {
            if (this.tick_values.length > 0) {
                this.axis.tickValues(this.tick_values);
            } else if (this.num_ticks != undefined) {
                    this.axis.tickValues(this.get_ticks())
            } else {
                this.axis.tickValues((this.axis_scale.model.type == "ordinal")
                                    ? this.axis_scale.scale.domain()
                                    : this.axis_scale.scale.ticks())
            }
            this.axis.tickFormat(this.tick_format);
            if(this.g_axisline) {
                this.g_axisline.call(this.axis);
            }
        },
    });
    WidgetManager.WidgetManager.register_widget_view("bqplot.ColorAxis", ColorBar);

});
<|endoftext|>


<commit_before>Template.participantsDefinition.events({
	"click .submitGameConfiguration": function() {
		var filterInt = function(value) {
			if (/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
				return Number(value);
			return NaN;
		};
		var currentGame = this._id;
		var isFilled = function(element) {
			if ($(element).val() === "") {
				return null;
			} else {
				return $(element).val();
			}
		};
		var homeTeamPlayers = [];
		var awayTeamPlayers = [];
		var homeTeamCoachs = [];
		var awayTeamCoachs = [];
		var homeTeam = {};
		var awayTeam = {};
		$('.player').each(function(index, element) {
			var player = {
				firstName: isFilled($(element).find('.firstName')),
				lastName: isFilled($(element).find('.lastName')),
				jersey: filterInt($(element).find('.jersey').val()),
				playerIndex: filterInt($(element).find('.playerIndex').val()),
				inPlay: false,
				stats: {
					points: {
						onePointIn: 0,
						totalPoints: 0,
						twoPointsIn: 0,
						threePointsIn: 0,
						onePointOut: 0,
						twoPointsOut: 0,
						threePointsOut: 0
					},
					evaluation: 0,
					assists: 0,
					rebounds: {
						offReb: 0,
						defReb: 0
					},
					turnovers: 0,
					fouls: {
						offFouls: 0,
						totalFouls: 0,
						provFouls: {
							offFouls: 0,
							defFouls: 0
						},
						foul: 0,
						foul1FT: 0,
						foul2FT: 0,
						foul3FT: 0,
						techFoul: 0,
						antiSportFoul: 0,
						disqualifyingFoul: 0
					},
					steals: 0,
					blocks: 0
				}
			};
			if (index < 12) {
				player.team = "homeTeam";
				homeTeamPlayers.push(player);
			} else {
				player.team = "awayTeam";
				awayTeamPlayers.push(player);
			}
		});
		$('.coach').each(function(index, element) {
			var coach = {
				firstName: isFilled($(element).find('.firstName')),
				lastName: isFilled($(element).find('.lastName')),
				coachIndex: filterInt($(element).find('.coachIndex').val()),
				team: $(element).find('.team').val()
			};
			if (index < 2) {
				homeTeamCoachs.push(coach);
			} else {
				awayTeamCoachs.push(coach);
			}
		});
		homeTeam.players = homeTeamPlayers;
		homeTeam.coachs = homeTeamCoachs;
		awayTeam.players = awayTeamPlayers;
		awayTeam.coachs = awayTeamCoachs;

		Meteor.call('participantsUpdate', currentGame, homeTeam, awayTeam, function(error, result) {
			if (error) {
				return throwError(error.message);
			}
			Router.go('gameStats', {
				_id: currentGame
			});
		});
	}
});
<commit_msg>Add gameTime property when a player is added<commit_after>Template.participantsDefinition.events({
	"click .submitGameConfiguration": function() {
		var filterInt = function(value) {
			if (/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
				return Number(value);
			return NaN;
		};
		var currentGame = this._id;
		var isFilled = function(element) {
			if ($(element).val() === "") {
				return null;
			} else {
				return $(element).val();
			}
		};
		var homeTeamPlayers = [];
		var awayTeamPlayers = [];
		var homeTeamCoachs = [];
		var awayTeamCoachs = [];
		var homeTeam = {};
		var awayTeam = {};
		$('.player').each(function(index, element) {
			var player = {
				firstName: isFilled($(element).find('.firstName')),
				lastName: isFilled($(element).find('.lastName')),
				jersey: filterInt($(element).find('.jersey').val()),
				playerIndex: filterInt($(element).find('.playerIndex').val()),
				inPlay: false,
				gameTime: [],
				stats: {
					points: {
						onePointIn: 0,
						totalPoints: 0,
						twoPointsIn: 0,
						threePointsIn: 0,
						onePointOut: 0,
						twoPointsOut: 0,
						threePointsOut: 0
					},
					evaluation: 0,
					assists: 0,
					rebounds: {
						offReb: 0,
						defReb: 0
					},
					turnovers: 0,
					fouls: {
						offFouls: 0,
						totalFouls: 0,
						provFouls: {
							offFouls: 0,
							defFouls: 0
						},
						foul: 0,
						foul1FT: 0,
						foul2FT: 0,
						foul3FT: 0,
						techFoul: 0,
						antiSportFoul: 0,
						disqualifyingFoul: 0
					},
					steals: 0,
					blocks: 0
				}
			};
			if (index < 12) {
				player.team = "homeTeam";
				homeTeamPlayers.push(player);
			} else {
				player.team = "awayTeam";
				awayTeamPlayers.push(player);
			}
		});
		$('.coach').each(function(index, element) {
			var coach = {
				firstName: isFilled($(element).find('.firstName')),
				lastName: isFilled($(element).find('.lastName')),
				coachIndex: filterInt($(element).find('.coachIndex').val()),
				team: $(element).find('.team').val()
			};
			if (index < 2) {
				homeTeamCoachs.push(coach);
			} else {
				awayTeamCoachs.push(coach);
			}
		});
		homeTeam.players = homeTeamPlayers;
		homeTeam.coachs = homeTeamCoachs;
		awayTeam.players = awayTeamPlayers;
		awayTeam.coachs = awayTeamCoachs;

		Meteor.call('participantsUpdate', currentGame, homeTeam, awayTeam, function(error, result) {
			if (error) {
				return throwError(error.message);
			}
			Router.go('gameStats', {
				_id: currentGame
			});
		});
	}
});
<|endoftext|>


<commit_before>var inherits = require('inherits');
var LiveShot = require('liveshot-core');
var CanvasView = require('./CanvasView');
var CardBuilder = require('liveshot-protocol').CardBuilder;

function CardView() {
    this.initialize();
}

module.exports = CardView;
inherits(CardView, CanvasView);

// --- External API ---
CardView.prototype.setCard = function (card, valid) {
    if (!valid) {
        card = CardBuilder.sanitizeCard(card);
    }

    this.card = card;

    this.setTarget(this.card.config.targetID);
    this.setGaugeSize(this.card.config.gaugeSize);
    this.setShots(this.card.result.shots);

    this.updateScale();
    this.draw();
};

// --- Internal API ---
CardView.prototype.initialize = function () {
    CanvasView.prototype.initialize.apply(this);

    this.card = CardBuilder.createBlankCard();
    this.shotRenderer = new LiveShot.ShotRenderer();
    this.triangleRenderer = new LiveShot.TriangleRenderer();
};

CardView.prototype.setTarget = function (targetID) {
    if (this.targetID == targetID) {
        return;
    }

    this.targetID = targetID;

    this.targetRenderer = LiveShot.targets.getRenderer(this.targetID);
    this.scaler = LiveShot.targets.getScaler(this.targetID);
};

CardView.prototype.setShots = function (shots) {
    if (this.shots == shots) {
        return;
    }

    this.shots = shots;

    this.scaler.setShots(shots);
    this.shotRenderer.setShots(shots);
};

CardView.prototype.setGaugeSize = function (gaugeSize) {
    if (this.gaugeSize == gaugeSize) {
        return;
    }

    this.gaugeSize = gaugeSize;
    this.shotRenderer.setStyle({gaugeSize:gaugeSize});
};

CardView.prototype.updateScale = function () {
    var scale = this.scaler.getScale();

    this.targetRenderer.setScale(scale);
    this.shotRenderer.setScale(scale);
};

CardView.prototype.render = function (ctx, rect) {
    this.renderTarget(ctx, rect);
};

CardView.prototype.renderTarget = function (ctx, rect) {
    if (this.targetRenderer == null) {
        return;
    }

    var targetRect = this.getTargetRect(rect);

    this.targetRenderer
        .setContext(ctx)
        .setRect(targetRect)
        .render();

    this.shotRenderer
        .setContext(ctx)
        .setRect(targetRect)
        .render();

    if (!this.card.result.marking) {
        this.triangleRenderer
            .setContext(ctx)
            .setRect(targetRect)
            .render();
    }
};

CardView.prototype.getTargetRect = function (rect) {
    return rect;
};
<commit_msg>Disabled test firing triangle<commit_after>var inherits = require('inherits');
var LiveShot = require('liveshot-core');
var CanvasView = require('./CanvasView');
var CardBuilder = require('liveshot-protocol').CardBuilder;

function CardView() {
    this.initialize();
}

module.exports = CardView;
inherits(CardView, CanvasView);

// --- External API ---
CardView.prototype.setCard = function (card, valid) {
    if (!valid) {
        card = CardBuilder.sanitizeCard(card);
    }

    this.card = card;

    this.setTarget(this.card.config.targetID);
    this.setGaugeSize(this.card.config.gaugeSize);
    this.setShots(this.card.result.shots);

    this.updateScale();
    this.draw();
};

// --- Internal API ---
CardView.prototype.initialize = function () {
    CanvasView.prototype.initialize.apply(this);

    this.card = CardBuilder.createBlankCard();
    this.shotRenderer = new LiveShot.ShotRenderer();
    this.triangleRenderer = new LiveShot.TriangleRenderer();
};

CardView.prototype.setTarget = function (targetID) {
    if (this.targetID == targetID) {
        return;
    }

    this.targetID = targetID;

    this.targetRenderer = LiveShot.targets.getRenderer(this.targetID);
    this.scaler = LiveShot.targets.getScaler(this.targetID);
};

CardView.prototype.setShots = function (shots) {
    if (this.shots == shots) {
        return;
    }

    this.shots = shots;

    this.scaler.setShots(shots);
    this.shotRenderer.setShots(shots);
};

CardView.prototype.setGaugeSize = function (gaugeSize) {
    if (this.gaugeSize == gaugeSize) {
        return;
    }

    this.gaugeSize = gaugeSize;
    this.shotRenderer.setStyle({gaugeSize:gaugeSize});
};

CardView.prototype.updateScale = function () {
    var scale = this.scaler.getScale();

    this.targetRenderer.setScale(scale);
    this.shotRenderer.setScale(scale);
};

CardView.prototype.render = function (ctx, rect) {
    this.renderTarget(ctx, rect);
};

CardView.prototype.renderTarget = function (ctx, rect) {
    if (this.targetRenderer == null) {
        return;
    }

    var targetRect = this.getTargetRect(rect);

    this.targetRenderer
        .setContext(ctx)
        .setRect(targetRect)
        .render();

    this.shotRenderer
        .setContext(ctx)
        .setRect(targetRect)
        .render();

    /*
    if (!this.card.result.marking) {
        this.triangleRenderer
            .setContext(ctx)
            .setRect(targetRect)
            .render();
    }
    */
};

CardView.prototype.getTargetRect = function (rect) {
    return rect;
};
<|endoftext|>


<commit_before>"use strict";
const bot = require('./index.js');
const fs = require('fs');
const chalk = require('chalk');
const cmdExC = chalk.bold.cyan;
const msgRecC = chalk.bold.blue;
let logs = [];
let updated = false;
let writing = false;

setInterval(function () {
    if (updated === true) {
        if (writing) return;
        writing = true;
        let data = logs.join(`,\n`);
        data += `,\n`;
        fs.appendFile('./logs.txt', data, (err) => {
            if (err) throw `[${new Date(Date.now())}]: Error writing to log: ${err}`;
            console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.green('Wrote to logs successfully'));
            logs = [];
            updated = false;
            writing = false;
        });
    }
}, 15000);

// leave now; even this one is bad by my standards
bot.on('messageCreate', (msg) => {
    let date = new Date(Date.now());
    if ((!bot.commandOptions.ignoreSelf || msg.author.id !== bot.user.id) && (!bot.commandOptions.ignoreBots || !msg.author.bot) && (msg.prefix = bot.checkPrefix(msg))) {
        let args = msg.content.replace(/<@!/g, "<@").substring(msg.prefix.length).split(" ");
        let label = args.shift();
        label = bot.commandAliases[label] || label;
        let command;
        if (msg.channel.guild && (command = bot.commands[label]) !== undefined || msg.channel.guild && ((command = bot.commands[label.toLowerCase()]) !== undefined && command.caseInsensitive)) { // Command executed in guild
            console.log(chalk.white(`[${date}]: `), cmdExC(`${command.label} executed in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username})`));
            logs.push(`[${date}]: ${command.label} executed in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username})`);
        } else if ((command = bot.commands[label]) !== undefined || ((command = bot.commands[label.toLowerCase()]) !== undefined && command.caseInsensitive)) { // Command executed in DM
            console.log(chalk.white(`[${date}]: `), cmdExC(`${command.label} executed in DM by ${msg.author.id} (${msg.author.username})`));
            logs.push(`[${date}]: ${command.label} executed in DM by ${msg.author.id} (${msg.author.username})`);
        } else if (msg.author.id !== bot.user.id && msg.channel.guild) { // Message recieved in guild starting with prefix
            console.log(chalk.white(`[${date}]: `), msgRecC(`msgRecC in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`));
            logs.push(`[${date}]: msgRecC in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`);
        } else if (msg.author.id !== bot.user.id) { // DM recieved starting with prefix
            console.log(chalk.white(`[${date}]: `), msgRecC(`msgRecC in DM by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`));
            logs.push(`[${date}]: msgRecC in DM by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`);
        }
    } else if (msg.author.id !== bot.user.id && msg.channel.guild) { // Message recieved in guild
        console.log(chalk.white(`[${date}]: `), msgRecC(`msgRecC in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`));
        logs.push(`[${date}]: msgRecC in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`);
    } else if (msg.author.id !== bot.user.id) { // DM recieved
        console.log(chalk.white(`[${date}]: `), msgRecC(`msgRecC in DM by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`));
        logs.push(`[${date}]: msgRecC in DM by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`);
    }
    updated = true;
});

bot.on('guildUnavailable', (g) => {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.yellow(`Guild unavailable: ${g.id} (${g.name})`));
    logs.push(`[${new Date(Date.now())}]: Guild unavailable: ${g.id} (${g.name})`);
    updated = true;
});

let errC = function (error) {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.red(`${error}`));
    logs.push(`[${new Date(Date.now())}]: (ERROR) ${error}`);
    updated = true;
}

let warnC = function (msg) {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.yellow(`${msg}`));
    logs.push(`[${new Date(Date.now())}]: (WARN) ${msg}`);
    updated = true;
}

let successC = function (res) {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.green(`${res}`));
    logs.push(`[${new Date(Date.now())}]: ${res}`);
    updated = true;
}

let botG = function (g) {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.magenta(`Guild created. ${g.name} | ${g.id}`));
    logs.push(`[${new Date(Date.now())}]: Guild created. ${g.name} | ${g.id}`);
    updated = true;
}

let botGD = function (g) {
    if (g) {
        console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.magenta(`Guild delete. ${g.name} | ${g.id}`));
        logs.push(`[${new Date(Date.now())}]: Guild delete. ${g.name} | ${g.id}`);
        updated = true;
    } else {
        console.log(chalk.white('Guild deleted.'));
        logs.push(`[${new Date(Date.now())}]: Guild delete.`);
        updated = true;
    }
}

module.exports.errC = errC;
module.exports.warnC = warnC;
module.exports.successC = successC;
module.exports.botG = botG;
module.exports.botGD = botGD;
<commit_msg>Apparently msg.command is a thing :eyes:<commit_after>"use strict";
const bot = require('./index.js');
const fs = require('fs');
const chalk = require('chalk');
const cmdExC = chalk.bold.cyan;
const msgRecC = chalk.bold.blue;
let logs = [];
let updated = false;
let writing = false;

setInterval(function () {
    if (updated === true) {
        if (writing) return;
        writing = true;
        let data = logs.join(`,\n`);
        data += `,\n`;
        fs.appendFile('./logs.txt', data, (err) => {
            if (err) throw `[${new Date(Date.now())}]: Error writing to log: ${err}`;
            console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.green('Wrote to logs successfully'));
            logs = [];
            updated = false;
            writing = false;
        });
    }
}, 15000);

bot.on('messageCreate', (msg) => {
    if (msg.author.id === bot.user.id) return;
    let date = new Date(Date.now());
    if (msg.command && msg.channel.guild) {
        console.log(chalk.white(`[${date}]: `), cmdExC(`${msg.command.label} executed in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username})`));
        logs.push(`[${date}]: ${msg.command.label} executed in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username})`);
    } else if (msg.command) {
        console.log(chalk.white(`[${date}]: `), cmdExC(`${msg.command.label} executed in DM by ${msg.author.id} (${msg.author.username})`));
        logs.push(`[${date}]: ${msg.command.label} executed in DM by ${msg.author.id} (${msg.author.username})`);
    } else if (msg.channel.guild) {
        console.log(chalk.white(`[${date}]: `), msgRecC(`msgRecC in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`));
        logs.push(`[${date}]: msgRecC in ${msg.channel.guild.id} (${msg.channel.guild.name}) by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`);
    } else {
        console.log(chalk.white(`[${date}]: `), msgRecC(`msgRecC in DM by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`));
        logs.push(`[${date}]: msgRecC in DM by ${msg.author.id} (${msg.author.username}): ${msg.cleanContent}`);
    }
    updated = true;
});

bot.on('guildUnavailable', (g) => {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.yellow(`Guild unavailable: ${g.id} (${g.name})`));
    logs.push(`[${new Date(Date.now())}]: Guild unavailable: ${g.id} (${g.name})`);
    updated = true;
});

let errC = function (error) {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.red(`${error}`));
    logs.push(`[${new Date(Date.now())}]: (ERROR) ${error}`);
    updated = true;
}

let warnC = function (msg) {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.yellow(`${msg}`));
    logs.push(`[${new Date(Date.now())}]: (WARN) ${msg}`);
    updated = true;
}

let successC = function (res) {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.green(`${res}`));
    logs.push(`[${new Date(Date.now())}]: ${res}`);
    updated = true;
}

let botG = function (g) {
    console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.magenta(`Guild created. ${g.name} | ${g.id}`));
    logs.push(`[${new Date(Date.now())}]: Guild created. ${g.name} | ${g.id}`);
    updated = true;
}

let botGD = function (g) {
    if (g) {
        console.log(chalk.white(`[${new Date(Date.now())}]: `), chalk.bold.magenta(`Guild delete. ${g.name} | ${g.id}`));
        logs.push(`[${new Date(Date.now())}]: Guild delete. ${g.name} | ${g.id}`);
        updated = true;
    } else {
        console.log(chalk.white('Guild deleted.'));
        logs.push(`[${new Date(Date.now())}]: Guild delete.`);
        updated = true;
    }
}

module.exports.errC = errC;
module.exports.warnC = warnC;
module.exports.successC = successC;
module.exports.botG = botG;
module.exports.botGD = botGD;
<|endoftext|>


<commit_before>"use strict";
// Log class

var config    = require('./config');
var plugins;
var connection;
var outbound;
var constants = require('./constants');
var util      = require('util');
var tty = require('tty')

var logger = exports;

logger.LOGDATA      = 9;
logger.LOGPROTOCOL  = 8;
logger.LOGDEBUG     = 7;
logger.LOGINFO      = 6;
logger.LOGNOTICE    = 5;
logger.LOGWARN      = 4;
logger.LOGERROR     = 3;
logger.LOGCRIT      = 2;
logger.LOGALERT     = 1;
logger.LOGEMERG     = 0;

logger.colors = { // Makes me cringe spelling it this way...
    "DATA" : "green",
    "PROTOCOL" : "green",
    "DEBUG" : "grey",
    "INFO" : "cyan",
    "info" : "cyan",
    "NOTICE" : "blue",
    "WARN" : "red",
    "ERROR" : "red",
    "CRIT" : "red",
    "ALERT" : "red",
    "EMERG" : "red"
};

var stdout_is_tty = tty.isatty(process.stdout.fd);

function colorize (color, str) {
    if (!util.inspect.colors || !util.inspect.colors[color]) return str;
    return '\u001b[' + util.inspect.colors[color][0] + 'm' + str +
              '\u001b[' + util.inspect.colors[color][1] + 'm';
}

var loglevel = logger.LOGWARN;

var deferred_logs = [];

logger.dump_logs = function (exit) {
    while (deferred_logs.length > 0) {
        var log_item = deferred_logs.shift();
        var color = logger.colors[log_item.level];
        if (color && stdout_is_tty) {
            console.log(colorize(color,log_item.data));
        }
        else {
            console.log(log_item.data);
        }
    }
    if (exit) {
        process.exit(1);
    }
}

logger.log = function (level, data) {
    if (level === 'PROTOCOL') {
        data = data.replace(/\n/g, '\\n\n');
    }
    data = data.replace(/\r/g, '\\r')
               .replace(/\n$/, '');
    // todo - just buffer these up (defer) until plugins are loaded
    if (plugins && plugins.plugin_list) {
        while (deferred_logs.length > 0) {
            var log_item = deferred_logs.shift();
            plugins.run_hooks('log', logger, log_item);
        }
        plugins.run_hooks('log', logger, {
            'level' : level,
            'data'  : data
        });
    }
    else {
        deferred_logs.push({
            'level' : level,
            'data'  : data
        });
    }
}

logger.log_respond = function (retval, msg, data) {
    // any other return code is irrelevant
    if (retval === constants.cont) {
        var color = logger.colors[data.level];
        if (color && stdout_is_tty) {
            return console.log(colorize(color,data.data));
        }
        else {
            return console.log(data.data);
        }
    }
};

logger._init_loglevel = function () {
    var self = this;
    var _loglevel = config.get('loglevel', 'value', function () {
        self._init_loglevel();
    });
    if (_loglevel) {
        var loglevel_num = parseInt(_loglevel);
        if (!loglevel_num || loglevel_num === NaN) {
            this.log('info', 'loglevel: ' + _loglevel.toUpperCase());
            loglevel = logger[_loglevel.toUpperCase()];
        }
        else {
            loglevel = loglevel_num;
        }
        if (!loglevel) {
            loglevel = logger.LOGWARN;
        }
    }
};

logger.would_log = function (level) {
    if (loglevel < level) return false;
    return true;
}

var original_console_log = console.log;

logger._init_timestamps = function () {
    var self = this;
    var _timestamps = config.get('log_timestamps', 'value', function () {
        self._init_timestamps();
    });
    if (_timestamps) {
        console.log = original_console_log.bind(console, new Date().toISOString());
    }
    else {
        console.log = original_console_log;
    }
}

logger._init_loglevel();
logger._init_timestamps();

var level, key;
for (key in logger) {
    if(logger.hasOwnProperty(key)) {
        if (key.match(/^LOG\w/)) {
            level = key.slice(3);
            logger[key.toLowerCase()] = (function(level, key) {
                return function() {
                    if (loglevel < logger[key])
                        return;
                    var levelstr = "[" + level + "]";
                    var str = "";
                    var uuidstr = "[-]";
                    var pluginstr = "[core]";
                    for (var i = 0; i < arguments.length; i++) {
                        var data = arguments[i];
                        if (typeof(data) === 'object') {
                            // if the object is a connection, we wish to add
                            // the connection id
                            if (data instanceof connection.Connection) {
                                uuidstr = "[" + data.uuid;
                                if (data.tran_count > 0) {
                                  uuidstr += "." + data.tran_count;
                                }
                                uuidstr += "]";
                            }
                            else if (data instanceof plugins.Plugin) {
                                pluginstr = "[" + data.name + "]";
                            }
                            else if (data instanceof outbound.HMailItem) {
                                pluginstr = "[outbound]";
                                if (data.todo && data.todo.uuid) {
                                    uuidstr = "[" + data.todo.uuid + "]";
                                }
                            }
                            else {
                                str += util.inspect(data);
                            }
                        }
                        else {
                            str += data;
                        }
                    }
                    logger.log(level, [levelstr, uuidstr, pluginstr, str].join(" "));
                }
            })(level, key);
        }
    }
}

// load these down here so it sees all the logger methods compiled above
plugins = require('./plugins');
connection = require('./connection');
outbound = require('./outbound');
<commit_msg>logger: added missing semicolons<commit_after>"use strict";
// Log class

var config    = require('./config');
var plugins;
var connection;
var outbound;
var constants = require('./constants');
var util      = require('util');
var tty       = require('tty');

var logger = exports;

logger.LOGDATA      = 9;
logger.LOGPROTOCOL  = 8;
logger.LOGDEBUG     = 7;
logger.LOGINFO      = 6;
logger.LOGNOTICE    = 5;
logger.LOGWARN      = 4;
logger.LOGERROR     = 3;
logger.LOGCRIT      = 2;
logger.LOGALERT     = 1;
logger.LOGEMERG     = 0;

logger.colors = { // Makes me cringe spelling it this way...
    "DATA" : "green",
    "PROTOCOL" : "green",
    "DEBUG" : "grey",
    "INFO" : "cyan",
    "info" : "cyan",
    "NOTICE" : "blue",
    "WARN" : "red",
    "ERROR" : "red",
    "CRIT" : "red",
    "ALERT" : "red",
    "EMERG" : "red",
};

var stdout_is_tty = tty.isatty(process.stdout.fd);

function colorize (color, str) {
    if (!util.inspect.colors || !util.inspect.colors[color]) return str;
    return '\u001b[' + util.inspect.colors[color][0] + 'm' + str +
              '\u001b[' + util.inspect.colors[color][1] + 'm';
}

var loglevel = logger.LOGWARN;

var deferred_logs = [];

logger.dump_logs = function (exit) {
    while (deferred_logs.length > 0) {
        var log_item = deferred_logs.shift();
        var color = logger.colors[log_item.level];
        if (color && stdout_is_tty) {
            console.log(colorize(color,log_item.data));
        }
        else {
            console.log(log_item.data);
        }
    }
    if (exit) {
        process.exit(1);
    }
};

logger.log = function (level, data) {
    if (level === 'PROTOCOL') {
        data = data.replace(/\n/g, '\\n\n');
    }
    data = data.replace(/\r/g, '\\r')
               .replace(/\n$/, '');
    // todo - just buffer these up (defer) until plugins are loaded
    if (plugins && plugins.plugin_list) {
        while (deferred_logs.length > 0) {
            var log_item = deferred_logs.shift();
            plugins.run_hooks('log', logger, log_item);
        }
        plugins.run_hooks('log', logger, {
            'level' : level,
            'data'  : data
        });
    }
    else {
        deferred_logs.push({
            'level' : level,
            'data'  : data
        });
    }
};

logger.log_respond = function (retval, msg, data) {
    // any other return code is irrelevant
    if (retval === constants.cont) {
        var color = logger.colors[data.level];
        if (color && stdout_is_tty) {
            return console.log(colorize(color,data.data));
        }
        else {
            return console.log(data.data);
        }
    }
};

logger._init_loglevel = function () {
    var self = this;
    var _loglevel = config.get('loglevel', 'value', function () {
        self._init_loglevel();
    });
    if (_loglevel) {
        var loglevel_num = parseInt(_loglevel);
        if (!loglevel_num || loglevel_num === NaN) {
            this.log('info', 'loglevel: ' + _loglevel.toUpperCase());
            loglevel = logger[_loglevel.toUpperCase()];
        }
        else {
            loglevel = loglevel_num;
        }
        if (!loglevel) {
            loglevel = logger.LOGWARN;
        }
    }
};

logger.would_log = function (level) {
    if (loglevel < level) return false;
    return true;
};

var original_console_log = console.log;

logger._init_timestamps = function () {
    var self = this;
    var _timestamps = config.get('log_timestamps', 'value', function () {
        self._init_timestamps();
    });
    if (_timestamps) {
        console.log = original_console_log.bind(console, new Date().toISOString());
    }
    else {
        console.log = original_console_log;
    }
};

logger._init_loglevel();
logger._init_timestamps();

var level, key;
for (key in logger) {
    if(!logger.hasOwnProperty(key)) { continue; }

    if (key.match(/^LOG\w/)) {
        level = key.slice(3);
        logger[key.toLowerCase()] = (function(level, key) {
            return function() {
                if (loglevel < logger[key]) { return; }
                var levelstr = "[" + level + "]";
                var str = "";
                var uuidstr = "[-]";
                var pluginstr = "[core]";
                for (var i = 0; i < arguments.length; i++) {
                    var data = arguments[i];
                    if (typeof(data) === 'object') {
                        // if the object is a connection, we wish to add
                        // the connection id
                        if (data instanceof connection.Connection) {
                            uuidstr = "[" + data.uuid;
                            if (data.tran_count > 0) {
                                uuidstr += "." + data.tran_count;
                            }
                            uuidstr += "]";
                        }
                        else if (data instanceof plugins.Plugin) {
                            pluginstr = "[" + data.name + "]";
                        }
                        else if (data instanceof outbound.HMailItem) {
                            pluginstr = "[outbound]";
                            if (data.todo && data.todo.uuid) {
                                uuidstr = "[" + data.todo.uuid + "]";
                            }
                        }
                        else {
                            str += util.inspect(data);
                        }
                    }
                    else {
                        str += data;
                    }
                }
                logger.log(level, [levelstr, uuidstr, pluginstr, str].join(" "));
            };
        })(level, key);
    }
}

// load these down here so it sees all the logger methods compiled above
plugins = require('./plugins');
connection = require('./connection');
outbound = require('./outbound');
<|endoftext|>


<commit_before>'use strict'

var pino = require('pino')
var maxInt = 2147483647

function pinoLogger (opts, stream) {
  if (opts && opts._writableState) {
    stream = opts
    opts = null
  }

  opts = opts || {}
  opts.serializers = opts.serializers || {}
  opts.serializers.req = opts.serializers.req || asReqValue
  opts.serializers.res = opts.serializers.res || pino.stdSerializers.res

  var logger = pino(opts, stream)

  loggingMiddleware.logger = logger

  var nextId = 0

  stream = logger.stream

  return loggingMiddleware

  function onResFinished (err) {
    this.removeListener('finish', onResFinished)
    this.removeListener('error', onResFinished)

    var end = process.hrtime(this.startTime)
    var log = this.log
    var responseTime = Math.round(end[0] * 1e3 + end[1] / 1e6)

    if (err) {
      log.error({
        res: this,
        err: err,
        responseTime: this.responseTime
      }, 'request errored')
      return
    }

    log.info({
      res: this,
      responseTime: responseTime
    }, 'request completed')
  }

  function loggingMiddleware (req, res, next) {
    var startTime = process.hrtime()
    req.id = ++nextId
    nextId = nextId % maxInt

    var child = logger.child({ req: req })

    req.log = child
    res.log = child
    res.startTime = startTime

    res.on('finish', onResFinished)
    res.on('error', onResFinished)

    if (next) {
      next()
    }
  }
}

function asReqValue (req) {
  return {
    id: req.id,
    method: req.method,
    url: req.url,
    headers: req.headers,
    remoteAddress: req.connection.remoteAddress,
    remotePort: req.connection.remotePort
  }
}

module.exports = pinoLogger
<commit_msg>switch to Date.now()<commit_after>'use strict'

var pino = require('pino')
var maxInt = 2147483647

function pinoLogger (opts, stream) {
  if (opts && opts._writableState) {
    stream = opts
    opts = null
  }

  opts = opts || {}
  opts.serializers = opts.serializers || {}
  opts.serializers.req = opts.serializers.req || asReqValue
  opts.serializers.res = opts.serializers.res || pino.stdSerializers.res

  var logger = pino(opts, stream)

  loggingMiddleware.logger = logger

  var nextId = 0

  stream = logger.stream

  return loggingMiddleware

  function onResFinished (err) {
    this.removeListener('finish', onResFinished)
    this.removeListener('error', onResFinished)

    var log = this.log
    var responseTime = Date.now() - this.startTime

    if (err) {
      log.error({
        res: this,
        err: err,
        responseTime: this.responseTime
      }, 'request errored')
      return
    }

    log.info({
      res: this,
      responseTime: responseTime
    }, 'request completed')
  }

  function loggingMiddleware (req, res, next) {
    var startTime = Date.now()
    req.id = ++nextId
    nextId = nextId % maxInt

    var child = logger.child({req: req})

    req.log = child
    res.log = child
    res.startTime = startTime

    res.on('finish', onResFinished)
    res.on('error', onResFinished)

    if (next) {
      next()
    }
  }
}

function asReqValue (req) {
  return {
    id: req.id,
    method: req.method,
    url: req.url,
    headers: req.headers,
    remoteAddress: req.connection.remoteAddress,
    remotePort: req.connection.remotePort
  }
}

module.exports = pinoLogger
<|endoftext|>