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

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

var transforms = require('./transforms');
var sharedTransforms = require('../transforms');
var predicates = require('./predicates');
var sharedPredicates = require('../predicates');
var errorParser = require('./errorParser');
var Instrumenter = require('./telemetry');

function Rollbar(options, client) {
  this.options = _.handleOptions(defaultOptions, options);
  var api = new API(this.options, transport, urllib);
  this.client = client || new Client(this.options, api, logger, 'browser');

  var gWindow = ((typeof window != 'undefined') && window) || ((typeof self != 'undefined') && self);
  var gDocument = (typeof document != 'undefined') && document;
  addTransformsToNotifier(this.client.notifier);
  addPredicatesToQueue(this.client.queue);
  if (this.options.captureUncaught || this.options.handleUncaughtExceptions) {
    globals.captureUncaughtExceptions(gWindow, this);
    globals.wrapGlobals(gWindow, this);
  }
  if (this.options.captureUnhandledRejections || this.options.handleUnhandledRejections) {
    globals.captureUnhandledRejections(gWindow, this);
  }

  this.instrumenter = new Instrumenter(this.options, this.client.telemeter, this, gWindow, gDocument);
  this.instrumenter.instrument();
}

var _instance = null;
Rollbar.init = function(options, client) {
  if (_instance) {
    return _instance.global(options).configure(options);
  }
  _instance = new Rollbar(options, client);
  return _instance;
};

function handleUninitialized(maybeCallback) {
  var message = 'Rollbar is not initialized';
  logger.error(message);
  if (maybeCallback) {
    maybeCallback(new Error(message));
  }
}

Rollbar.prototype.global = function(options) {
  this.client.global(options);
  return this;
};
Rollbar.global = function(options) {
  if (_instance) {
    return _instance.global(options);
  } else {
    handleUninitialized();
  }
};

Rollbar.prototype.configure = function(options, payloadData) {
  var oldOptions = this.options;
  var payload = {};
  if (payloadData) {
    payload = {payload: payloadData};
  }
  this.options = _.handleOptions(oldOptions, options, payload);
  this.client.configure(this.options, payloadData);
  this.instrumenter.configure(this.options);
  return this;
};
Rollbar.configure = function(options, payloadData) {
  if (_instance) {
    return _instance.configure(options, payloadData);
  } else {
    handleUninitialized();
  }
};

Rollbar.prototype.lastError = function() {
  return this.client.lastError;
};
Rollbar.lastError = function() {
  if (_instance) {
    return _instance.lastError();
  } else {
    handleUninitialized();
  }
};

Rollbar.prototype.log = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.log(item);
  return {uuid: uuid};
};
Rollbar.log = function() {
  if (_instance) {
    return _instance.log.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.debug = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.debug(item);
  return {uuid: uuid};
};
Rollbar.debug = function() {
  if (_instance) {
    return _instance.debug.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.info = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.info(item);
  return {uuid: uuid};
};
Rollbar.info = function() {
  if (_instance) {
    return _instance.info.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.warn = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.warn(item);
  return {uuid: uuid};
};
Rollbar.warn = function() {
  if (_instance) {
    return _instance.warn.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.warning = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.warning(item);
  return {uuid: uuid};
};
Rollbar.warning = function() {
  if (_instance) {
    return _instance.warning.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.error = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.error(item);
  return {uuid: uuid};
};
Rollbar.error = function() {
  if (_instance) {
    return _instance.error.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.critical = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.critical(item);
  return {uuid: uuid};
};
Rollbar.critical = function() {
  if (_instance) {
    return _instance.critical.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

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

Rollbar.prototype.handleUnhandledRejection = function(reason, promise) {
  var message = 'unhandled rejection was null or undefined!';
  if (reason) {
    if (reason.message) {
      message = reason.message;
    } else {
      var reasonResult = _.stringify(reason);
      if (reasonResult.value) {
        message = reasonResult.value;
      }
    }
  }
  var context = (reason && reason._rollbarContext) || (promise && promise._rollbarContext);

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

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

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

    if (f._isWrap) {
      return f;
    }

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

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

      f._rollbar_wrapped._isWrap = true;

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

    return f._rollbar_wrapped;
  } catch (e) {
    // Return the original function if the wrap fails.
    return f;
  }
};
Rollbar.wrap = function(f, context) {
  if (_instance) {
    return _instance.wrap(f, context);
  } else {
    handleUninitialized();
  }
};

Rollbar.prototype.captureEvent = function(metadata, level) {
  return this.client.captureEvent(metadata, level);
};
Rollbar.captureEvent = function(metadata, level) {
  if (_instance) {
    return _instance.captureEvent(metadata, level);
  } else {
    handleUninitialized();
  }
};

// The following two methods are used internally and are not meant for public use
Rollbar.prototype.captureDomContentLoaded = function(e, ts) {
  if (!ts) {
    ts = new Date();
  }
  return this.client.captureDomContentLoaded(ts);
};

Rollbar.prototype.captureLoad = function(e, ts) {
  if (!ts) {
    ts = new Date();
  }
  return this.client.captureLoad(ts);
};

/* Internal */

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

function addPredicatesToQueue(queue) {
  queue
    .addPredicate(sharedPredicates.checkLevel)
    .addPredicate(predicates.checkIgnore)
    .addPredicate(sharedPredicates.userCheckIgnore(logger))
    .addPredicate(sharedPredicates.urlIsNotBlacklisted(logger))
    .addPredicate(sharedPredicates.urlIsWhitelisted(logger))
    .addPredicate(sharedPredicates.messageIsIgnored(logger));
}

Rollbar.prototype._createItem = function(args) {
  return _.createItem(args, logger, this);
};

function _getFirstFunction(args) {
  for (var i = 0, len = args.length; i < len; ++i) {
    if (_.isFunction(args[i])) {
      return args[i];
    }
  }
  return undefined;
}

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

var defaultOptions = {
  version: __NOTIFIER_VERSION__,
  scrubFields: __DEFAULT_BROWSER_SCRUB_FIELDS__,
  logLevel: __DEFAULT_LOG_LEVEL__,
  reportLevel: __DEFAULT_REPORT_LEVEL__,
  uncaughtErrorLevel: __DEFAULT_UNCAUGHT_ERROR_LEVEL,
  endpoint: __DEFAULT_ENDPOINT__,
  verbose: false,
  enabled: true,
  sendConfig: false,
  includeItemsInTelemetry: true,
  captureIp: true
};

module.exports = Rollbar;
<commit_msg>Support web workers by passing gWindow instead of window<commit_after>var Client = require('../rollbar');
var _ = require('../utility');
var API = require('../api');
var logger = require('./logger');
var globals = require('./globalSetup');

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

var transforms = require('./transforms');
var sharedTransforms = require('../transforms');
var predicates = require('./predicates');
var sharedPredicates = require('../predicates');
var errorParser = require('./errorParser');
var Instrumenter = require('./telemetry');

function Rollbar(options, client) {
  this.options = _.handleOptions(defaultOptions, options);
  var api = new API(this.options, transport, urllib);
  this.client = client || new Client(this.options, api, logger, 'browser');

  var gWindow = ((typeof window != 'undefined') && window) || ((typeof self != 'undefined') && self);
  var gDocument = (typeof document != 'undefined') && document;
  addTransformsToNotifier(this.client.notifier, gWindow);
  addPredicatesToQueue(this.client.queue);
  if (this.options.captureUncaught || this.options.handleUncaughtExceptions) {
    globals.captureUncaughtExceptions(gWindow, this);
    globals.wrapGlobals(gWindow, this);
  }
  if (this.options.captureUnhandledRejections || this.options.handleUnhandledRejections) {
    globals.captureUnhandledRejections(gWindow, this);
  }

  this.instrumenter = new Instrumenter(this.options, this.client.telemeter, this, gWindow, gDocument);
  this.instrumenter.instrument();
}

var _instance = null;
Rollbar.init = function(options, client) {
  if (_instance) {
    return _instance.global(options).configure(options);
  }
  _instance = new Rollbar(options, client);
  return _instance;
};

function handleUninitialized(maybeCallback) {
  var message = 'Rollbar is not initialized';
  logger.error(message);
  if (maybeCallback) {
    maybeCallback(new Error(message));
  }
}

Rollbar.prototype.global = function(options) {
  this.client.global(options);
  return this;
};
Rollbar.global = function(options) {
  if (_instance) {
    return _instance.global(options);
  } else {
    handleUninitialized();
  }
};

Rollbar.prototype.configure = function(options, payloadData) {
  var oldOptions = this.options;
  var payload = {};
  if (payloadData) {
    payload = {payload: payloadData};
  }
  this.options = _.handleOptions(oldOptions, options, payload);
  this.client.configure(this.options, payloadData);
  this.instrumenter.configure(this.options);
  return this;
};
Rollbar.configure = function(options, payloadData) {
  if (_instance) {
    return _instance.configure(options, payloadData);
  } else {
    handleUninitialized();
  }
};

Rollbar.prototype.lastError = function() {
  return this.client.lastError;
};
Rollbar.lastError = function() {
  if (_instance) {
    return _instance.lastError();
  } else {
    handleUninitialized();
  }
};

Rollbar.prototype.log = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.log(item);
  return {uuid: uuid};
};
Rollbar.log = function() {
  if (_instance) {
    return _instance.log.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.debug = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.debug(item);
  return {uuid: uuid};
};
Rollbar.debug = function() {
  if (_instance) {
    return _instance.debug.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.info = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.info(item);
  return {uuid: uuid};
};
Rollbar.info = function() {
  if (_instance) {
    return _instance.info.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.warn = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.warn(item);
  return {uuid: uuid};
};
Rollbar.warn = function() {
  if (_instance) {
    return _instance.warn.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.warning = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.warning(item);
  return {uuid: uuid};
};
Rollbar.warning = function() {
  if (_instance) {
    return _instance.warning.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.error = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.error(item);
  return {uuid: uuid};
};
Rollbar.error = function() {
  if (_instance) {
    return _instance.error.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

Rollbar.prototype.critical = function() {
  var item = this._createItem(arguments);
  var uuid = item.uuid;
  this.client.critical(item);
  return {uuid: uuid};
};
Rollbar.critical = function() {
  if (_instance) {
    return _instance.critical.apply(_instance, arguments);
  } else {
    var maybeCallback = _getFirstFunction(arguments);
    handleUninitialized(maybeCallback);
  }
};

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

Rollbar.prototype.handleUnhandledRejection = function(reason, promise) {
  var message = 'unhandled rejection was null or undefined!';
  if (reason) {
    if (reason.message) {
      message = reason.message;
    } else {
      var reasonResult = _.stringify(reason);
      if (reasonResult.value) {
        message = reasonResult.value;
      }
    }
  }
  var context = (reason && reason._rollbarContext) || (promise && promise._rollbarContext);

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

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

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

    if (f._isWrap) {
      return f;
    }

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

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

      f._rollbar_wrapped._isWrap = true;

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

    return f._rollbar_wrapped;
  } catch (e) {
    // Return the original function if the wrap fails.
    return f;
  }
};
Rollbar.wrap = function(f, context) {
  if (_instance) {
    return _instance.wrap(f, context);
  } else {
    handleUninitialized();
  }
};

Rollbar.prototype.captureEvent = function(metadata, level) {
  return this.client.captureEvent(metadata, level);
};
Rollbar.captureEvent = function(metadata, level) {
  if (_instance) {
    return _instance.captureEvent(metadata, level);
  } else {
    handleUninitialized();
  }
};

// The following two methods are used internally and are not meant for public use
Rollbar.prototype.captureDomContentLoaded = function(e, ts) {
  if (!ts) {
    ts = new Date();
  }
  return this.client.captureDomContentLoaded(ts);
};

Rollbar.prototype.captureLoad = function(e, ts) {
  if (!ts) {
    ts = new Date();
  }
  return this.client.captureLoad(ts);
};

/* Internal */

function addTransformsToNotifier(notifier, gWindow) {
  notifier
    .addTransform(transforms.handleItemWithError)
    .addTransform(transforms.ensureItemHasSomethingToSay)
    .addTransform(transforms.addBaseInfo)
    .addTransform(transforms.addRequestInfo(gWindow))
    .addTransform(transforms.addClientInfo(gWindow))
    .addTransform(transforms.addPluginInfo(gWindow))
    .addTransform(transforms.addBody)
    .addTransform(sharedTransforms.addMessageWithError)
    .addTransform(sharedTransforms.addTelemetryData)
    .addTransform(sharedTransforms.addConfigToPayload)
    .addTransform(transforms.scrubPayload)
    .addTransform(sharedTransforms.userTransform(logger))
    .addTransform(sharedTransforms.itemToPayload);
}

function addPredicatesToQueue(queue) {
  queue
    .addPredicate(sharedPredicates.checkLevel)
    .addPredicate(predicates.checkIgnore)
    .addPredicate(sharedPredicates.userCheckIgnore(logger))
    .addPredicate(sharedPredicates.urlIsNotBlacklisted(logger))
    .addPredicate(sharedPredicates.urlIsWhitelisted(logger))
    .addPredicate(sharedPredicates.messageIsIgnored(logger));
}

Rollbar.prototype._createItem = function(args) {
  return _.createItem(args, logger, this);
};

function _getFirstFunction(args) {
  for (var i = 0, len = args.length; i < len; ++i) {
    if (_.isFunction(args[i])) {
      return args[i];
    }
  }
  return undefined;
}

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

var defaultOptions = {
  version: __NOTIFIER_VERSION__,
  scrubFields: __DEFAULT_BROWSER_SCRUB_FIELDS__,
  logLevel: __DEFAULT_LOG_LEVEL__,
  reportLevel: __DEFAULT_REPORT_LEVEL__,
  uncaughtErrorLevel: __DEFAULT_UNCAUGHT_ERROR_LEVEL,
  endpoint: __DEFAULT_ENDPOINT__,
  verbose: false,
  enabled: true,
  sendConfig: false,
  includeItemsInTelemetry: true,
  captureIp: true
};

module.exports = Rollbar;
<|endoftext|>


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

    angular
    .module('wfm.popup', [])
    .component('wfmPopup', {
        transclude: true,
        templateUrl: 'directives/popup-menu/popup.tpl.html',
        controller: PopupComponentController,
        bindings: {
            show: '='
        },
    });
    PopupComponentController.inject = [];
    function PopupComponentController() {
        var ctrl = this;

        console.log(ctrl.show);

    }
})();
<commit_msg>clean<commit_after>(function () {
    'use strict';

    angular
    .module('wfm.popup', [])
    .component('wfmPopup', {
        transclude: true,
        templateUrl: 'directives/popup-menu/popup.tpl.html',
        controller: PopupComponentController,
        bindings: {
            show: '='
        },
    });
    PopupComponentController.inject = [];
    function PopupComponentController() {
        var ctrl = this;
    }
})();
<|endoftext|>


<commit_before>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE

import fs from 'fs';
import requestf from 'request';
import lodash from 'lodash';

import Loggers from './Loggers';

const logger = Loggers.create(__filename);

export function requestJson(options) { // TODO deprecated
   return json(options);
}

export function json(options) {
   options = processOptions(options);
   options.json = true;
   logger.debug('requestJson', options);
   return request(options);
}

export function request(options) {
   options = processOptions(options);
   logger.debug('request', options);
   return new Promise((resolve, reject) => {
      requestf(options, (err, response, content) => {
         logger.debug('response', options.url || options, err || response.statusCode);
         if (err) {
            reject(err);
         } else if (response.statusCode !== 200) {
            reject({statusCode: response.statusCode});
         } else {
            resolve(content);
         }
      });
   });
}

export function response(options) {
   options = processOptions(options);
   logger.debug('request', options);
   return new Promise((resolve, reject) => {
      requestf(options, (err, response, content) => {
         logger.debug('response', options, err || response.statusCode);
         if (err) {
            reject(err);
         } else if (response.statusCode === 200) {
            resolve([response, content]);
         } else {
            resolve([response]);
         }
      });
   });
}

export function head(options) {
   options = processOptions(options);
   options.method = 'HEAD';
   logger.debug('head', options);
   return new Promise((resolve, reject) => {
      request(options, (err, response) => {
         logger.debug('response', options.url, err || response.statusCode);
         if (err) {
            reject(err);
         } else {
            resolve(response);
         }
      });
   });
}

function processOptions(options) {
   if (typeof options === 'string') {
      return {url: options};
   } else if (typeof options === 'object') {
      assert(options.url, 'url');
      if (options.lastModified) {
         options.headers = {'If-Modified-Since': options.lastModified};
      }
      return options;
   } else {
      throw 'Invalid request options type: ' + (typeof options);
   }
}
<commit_msg>Requests json<commit_after>// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE

import fs from 'fs';
import requestf from 'request';
import lodash from 'lodash';

import Loggers from './Loggers';

const logger = Loggers.create(__filename);

export function requestJson(options) { // TODO deprecated
   return json(options);
}

export function json(options) {
   options = processOptions(options);
   options.json = true;
   logger.debug('json', options.url);
   return request(options);
}

export function request(options) {
   options = processOptions(options);
   logger.vdebug('request', options);
   return new Promise((resolve, reject) => {
      requestf(options, (err, response, content) => {
         logger.debug('response', options.url || options, err || response.statusCode);
         if (err) {
            reject(err);
         } else if (response.statusCode !== 200) {
            reject({statusCode: response.statusCode});
         } else {
            resolve(content);
         }
      });
   });
}

export function response(options) {
   options = processOptions(options);
   logger.debug('request', options);
   return new Promise((resolve, reject) => {
      requestf(options, (err, response, content) => {
         logger.debug('response', options, err || response.statusCode);
         if (err) {
            reject(err);
         } else if (response.statusCode === 200) {
            resolve([response, content]);
         } else {
            resolve([response]);
         }
      });
   });
}

export function head(options) {
   options = processOptions(options);
   options.method = 'HEAD';
   logger.debug('head', options);
   return new Promise((resolve, reject) => {
      request(options, (err, response) => {
         logger.debug('response', options.url, err || response.statusCode);
         if (err) {
            reject(err);
         } else {
            resolve(response);
         }
      });
   });
}

function processOptions(options) {
   if (typeof options === 'string') {
      return {url: options};
   } else if (typeof options === 'object') {
      assert(options.url, 'url');
      if (options.lastModified) {
         options.headers = {'If-Modified-Since': options.lastModified};
      }
      return options;
   } else {
      throw 'Invalid request options type: ' + (typeof options);
   }
}
<|endoftext|>


<commit_before>/* This file is written by a person who doesn't like JavaScript and codes in python.
 * Deal with it.
 *
 * Author: Tomas Tomecek <ttomecek@redhat.com>
 */

// global variables, hold current state
var chart = null;
var previous_values = null;
var chart_data = null;
var constants = {
  datetime_format: '%Y-%m-%d %H:%M',
  day_format: '%Y-%m-%d',
};

function get_default_line_config() {
  return $().c3ChartDefaults().getDefaultLineConfig();
}

function get_default_bar_config() {
  return $().c3ChartDefaults().getDefaultBarConfig();
}

function get_default_area_config() {
  return $().c3ChartDefaults().getDefaultAreaConfig();
}

// initialize empty chart from patternfly
function init_chart(chart_config) {
  chart_config.bindto = '#chart';
  chart_config.size = {
    height: 480,
  };
  chart_config.legend = {
    show: true,
  };
  return chart_config;
}

// TODO: get rid of reload functions, one function should load and reload
// class with "classmethods" to create charts
var charting = {
  reload_control: function(data) {
    chart_data.json = data.data;
    chart_data.unload = chart.columns;
    chart.load(chart_data);
  },

  control: function(data) {
    var chart_defaults = init_chart(get_default_line_config());
    chart_data = {
      json: data["data"],
      keys: {
        value: ["date", "days"],
        x: 'date',
      },
      xFormat: constants.datetime_format,
      type: 'scatter',
      onclick: on_point_click,
    };

    var ch = {
      data: chart_data,
      legend: {
        show: true
      },
      axis: {
        x: {
          type: 'timeseries',
          tick: {
            // fit: true,
            format: constants.day_format,
            label: "Date"
          }
        },
        y: {
          label: 'Days',
        }
      },
      tooltip: {
        contents: get_tooltip
      },
      point: {
        r: point_size,
        focus: {
          expand: {
            enabled: false
          }
        }
      }
    };
    $.extend(true, chart_defaults, ch);
    chart = c3.generate(chart_defaults);
  },

  reload_cumulative_flow: function(data) {
    chart_data.json = data.data;
    chart_data.keys.value = data.order;
    chart_data.groups = data.order
    chart_data.unload = previous_values;
    chart.load(chart_data);
    previous_values = data.order;
  },

  cumulative_flow: function(data) {
    var chart_defaults = init_chart(get_default_area_config());
    previous_values = data.order;
    chart_data = {
      json: data["data"],
      keys: {
        value: data["order"],
        x: 'date',
      },
      xFormat: constants.datetime_format,
      type: 'area',  // area, area-spline, area-step
      groups: [data.order],
      order: null
    };

    var ch = {
      data: chart_data,
      axis: {
        x: {
          type: 'timeseries',
          label: 'Date',
          tick: {
            format: constants.day_format
          }
        },
        y: {
          label: '# cards',
        }
      },
      legend: {
        show: true
      },
      line: {
        connectNull: true
      }
    };
    $.extend(true, ch, chart_defaults);
    chart = c3.generate(ch);
  },

  reload_burndown: function(data) {
    chart_data["json"] = data["data"];
    chart_data["unload"] = chart.columns;
    chart.load(chart_data);
  },
  burndown: function (data) {
    var chart_defaults = init_chart(get_default_line_config());
    chart_data = {
      json: data["data"],
      keys: {
        value: ["done", "not_done", "date", "ideal"]
      },
      x: 'date',
      xFormat: constants.datetime_format,
      types: {
        "done": "bar",
        "not_done": "line",
        "ideal": "line",
      }
    };
    var ch = {
      data: chart_data,
      axis: {
        x: {
          type: 'timeseries',
          label: 'Date',
          tick: {
            format: constants.day_format
          }
        },
        y: {
          label: 'Story points',
        }
      },
      tooltip: {
        contents: get_burndown_tooltip
      },
      line: {
        connectNull: true
      }
    }
    $.extend(true, ch, chart_defaults)

    chart = c3.generate(ch);
  },

  reload_velocity: function(data) {
    chart_data["json"] = data["data"];
    chart_data["unload"] = chart.columns;
    chart.load(chart_data);
  },
  velocity: function(data) {
    var bar_chart_defaults = init_chart(get_default_bar_config());
    var line_chart_defaults = init_chart(get_default_line_config());
    chart_data = {
      json: data["data"],
      keys: {
        value: ["done", "committed", "average"],
        x: "name",
      },
      types: {
        "done": "bar",
        "committed": "bar",
        "average": "area",
      }
    };

    var ch = {
      data: chart_data,
      bar: {
        width: {
            ratio: 0.5
        }
      },
      axis: {
        x: {
          label: "Sprint",
          type: "category"
        },
        y: {
          label: "Story points"
        }
      },
    };
    $.extend(true, ch, line_chart_defaults, bar_chart_defaults);
    chart = c3.generate(ch);
  },

  reload_list_history: function(data) {
    chart_data["json"] = data["data"];
    chart.load(chart_data);
  },
  list_history: function(data) {
    var chart_defaults = init_chart(get_default_line_config());
    chart_data = {
      json: data.data,
      keys: {
        value: ["cards", "story_points", "date"],
        x: 'date',
      },
      xFormat: constants.datetime_format,
      type: "line"
    };
    var ch = {
      data: chart_data,
      axis: {
        x: {
          type: 'timeseries',
          label: 'Time',
          tick: {
            format: constants.day_format
          }
        },
        y: {
          label: 'Count',
        }
      }
    };
    $.extend(true, ch, chart_defaults);
    chart = c3.generate(ch);
  }
};

function load_chart(callback) {
  $("#errors").hide()
  $.post(
    GLOBAL.chart_data_url,
    $('#chart-settings').serialize(),
    function(data) {
      if ("error" in data) {
        $("#errors").show()
        $("#error-content").html(data.error);
      } else {
        callback(data);
      }
    },
    'json' // I expect a JSON response
  );
}

var controller = {
  chart: function(){
    // load chart data
    load_chart(function(data) {
      charting[GLOBAL.chart_name](data);
    });

    // get chart data on form submit
    $('input#submit-button').click(function() {
      load_chart(function(data) {
        charting["reload_" + GLOBAL.chart_name](data);
      });
    });
  },
  index: function(){},
  chart_without_form: function() {
    $.get(
      GLOBAL.chart_data_url,
      function(data) {
        charting[GLOBAL.chart_name](data);
      },
      'json' // I expect a JSON response
    );
  }
};

// DOM is ready, let's start the show
$(function() {
  controller[GLOBAL.view]();

  $('.datepicker').datepicker({
    format: 'yyyy-mm-dd'
  });
  $('.timepicker').datetimepicker({
    format: 'LT',
  });
  // focus event is still on when you're changing options, let's hook with change event
  $("div.state-workflow div.state-workflow-column select").change(on_focus_states);
});

// handler for growing state machine
function on_focus_states(data) {
  var t = $(this); // select
  var parent_div = t.parent("div"); // div.state-workflow-column
  var root_div = parent_div.parent("div.state-workflow");

  // selectedIndex is better than .filter(":selected")
  if (root_div.children("div.state-workflow-column").last().children("select")[0].selectedIndex > 0) {
    var new_div = root_div
        .children("div.state-workflow-column")
        .last()
        .clone()
        .appendTo(root_div)
    var new_select = new_div
        .children("select")
        .val("")
        .attr("id", function(i, oldVal) {
            return oldVal.replace(/\d+/, function(m) {
                return (+m + 1);  // +m means it's converted to `int(m) + 1`
            });
        })
        .attr("name", function(i, oldVal) {
            return oldVal.replace(/\d+/, function(m) {
                return (+m + 1);
            });
        })
    new_select
        .on("change", on_focus_states);
    // set # of forms, needed by django formsets
    parent_div.siblings("input[id$='-TOTAL_FORMS']")
        .val(root_div.find("div.state-workflow-column").length);
  }
}

function get_tooltip(d, defaultTitleFormat, defaultValueFormat, color) {
  var card = this.config.data_json[d[0].source_index];
  var titleFormat = this.config.tooltip_format_title || defaultTitleFormat;
  var title = titleFormat ? titleFormat(d[0].x) : d[0].x;

  var valueFormat = this.config.tooltip_format_value || defaultValueFormat;
  var value = valueFormat(d[0].value, d[0].ratio, d[0].id, d[0].index, d);

  var tooltip = $("div#custom-chart-tooltip").html();

  tooltip = tooltip.replace("TITLE", "#" + card.trello_card_short_id + " " + card.name);
  tooltip = tooltip.replace("DATE", title);
  tooltip = tooltip.replace("DAYS", value);
  return tooltip;
}

function on_point_click(d, element) {
  var card_id = this.internal.config.data_json[d.source_index].id;
  window.open('/card/' + card_id + '/', '_blank');
}

function point_size(d) {
  var sizes={0:2, 1:3, 2:4, 3:5, 5:6, 8:8, 13:13};
  var point_size = this.data_json[d.source_index].size;
  for (var s in sizes) {
    if (s >= point_size) {
      return sizes[s];
    }
  }
}

function get_burndown_tooltip(d, defaultTitleFormat, defaultValueFormat, color) {
  var data = this.config.data_json[d[0].source_index];
  var template_b="

";
  var template_e="

";
  var cards = "";
  data.done_cards.forEach(function(card) {
    cards += "
" + card.name + "
";
  });
  var response = template_b + cards +
    "
Done	" + data.done + "
" +
    "
Not done	" + data.not_done + "
" +
    template_e;
  return response;
}
<commit_msg>control,point size: sensible sizes, default for upper bound<commit_after>/* This file is written by a person who doesn't like JavaScript and codes in python.
 * Deal with it.
 *
 * Author: Tomas Tomecek <ttomecek@redhat.com>
 */

// global variables, hold current state
var chart = null;
var previous_values = null;
var chart_data = null;
var constants = {
  datetime_format: '%Y-%m-%d %H:%M',
  day_format: '%Y-%m-%d',
};

function get_default_line_config() {
  return $().c3ChartDefaults().getDefaultLineConfig();
}

function get_default_bar_config() {
  return $().c3ChartDefaults().getDefaultBarConfig();
}

function get_default_area_config() {
  return $().c3ChartDefaults().getDefaultAreaConfig();
}

// initialize empty chart from patternfly
function init_chart(chart_config) {
  chart_config.bindto = '#chart';
  chart_config.size = {
    height: 480,
  };
  chart_config.legend = {
    show: true,
  };
  return chart_config;
}

// TODO: get rid of reload functions, one function should load and reload
// class with "classmethods" to create charts
var charting = {
  reload_control: function(data) {
    chart_data.json = data.data;
    chart_data.unload = chart.columns;
    chart.load(chart_data);
  },

  control: function(data) {
    var chart_defaults = init_chart(get_default_line_config());
    chart_data = {
      json: data["data"],
      keys: {
        value: ["date", "days"],
        x: 'date',
      },
      xFormat: constants.datetime_format,
      type: 'scatter',
      onclick: on_point_click,
    };

    var ch = {
      data: chart_data,
      legend: {
        show: true
      },
      axis: {
        x: {
          type: 'timeseries',
          tick: {
            // fit: true,
            format: constants.day_format,
            label: "Date"
          }
        },
        y: {
          label: 'Days',
        }
      },
      tooltip: {
        contents: get_tooltip
      },
      point: {
        r: point_size,
        focus: {
          expand: {
            enabled: false
          }
        }
      }
    };
    $.extend(true, chart_defaults, ch);
    chart = c3.generate(chart_defaults);
  },

  reload_cumulative_flow: function(data) {
    chart_data.json = data.data;
    chart_data.keys.value = data.order;
    chart_data.groups = data.order
    chart_data.unload = previous_values;
    chart.load(chart_data);
    previous_values = data.order;
  },

  cumulative_flow: function(data) {
    var chart_defaults = init_chart(get_default_area_config());
    previous_values = data.order;
    chart_data = {
      json: data["data"],
      keys: {
        value: data["order"],
        x: 'date',
      },
      xFormat: constants.datetime_format,
      type: 'area',  // area, area-spline, area-step
      groups: [data.order],
      order: null
    };

    var ch = {
      data: chart_data,
      axis: {
        x: {
          type: 'timeseries',
          label: 'Date',
          tick: {
            format: constants.day_format
          }
        },
        y: {
          label: '# cards',
        }
      },
      legend: {
        show: true
      },
      line: {
        connectNull: true
      }
    };
    $.extend(true, ch, chart_defaults);
    chart = c3.generate(ch);
  },

  reload_burndown: function(data) {
    chart_data["json"] = data["data"];
    chart_data["unload"] = chart.columns;
    chart.load(chart_data);
  },
  burndown: function (data) {
    var chart_defaults = init_chart(get_default_line_config());
    chart_data = {
      json: data["data"],
      keys: {
        value: ["done", "not_done", "date", "ideal"]
      },
      x: 'date',
      xFormat: constants.datetime_format,
      types: {
        "done": "bar",
        "not_done": "line",
        "ideal": "line",
      }
    };
    var ch = {
      data: chart_data,
      axis: {
        x: {
          type: 'timeseries',
          label: 'Date',
          tick: {
            format: constants.day_format
          }
        },
        y: {
          label: 'Story points',
        }
      },
      tooltip: {
        contents: get_burndown_tooltip
      },
      line: {
        connectNull: true
      }
    }
    $.extend(true, ch, chart_defaults)

    chart = c3.generate(ch);
  },

  reload_velocity: function(data) {
    chart_data["json"] = data["data"];
    chart_data["unload"] = chart.columns;
    chart.load(chart_data);
  },
  velocity: function(data) {
    var bar_chart_defaults = init_chart(get_default_bar_config());
    var line_chart_defaults = init_chart(get_default_line_config());
    chart_data = {
      json: data["data"],
      keys: {
        value: ["done", "committed", "average"],
        x: "name",
      },
      types: {
        "done": "bar",
        "committed": "bar",
        "average": "area",
      }
    };

    var ch = {
      data: chart_data,
      bar: {
        width: {
            ratio: 0.5
        }
      },
      axis: {
        x: {
          label: "Sprint",
          type: "category"
        },
        y: {
          label: "Story points"
        }
      },
    };
    $.extend(true, ch, line_chart_defaults, bar_chart_defaults);
    chart = c3.generate(ch);
  },

  reload_list_history: function(data) {
    chart_data["json"] = data["data"];
    chart.load(chart_data);
  },
  list_history: function(data) {
    var chart_defaults = init_chart(get_default_line_config());
    chart_data = {
      json: data.data,
      keys: {
        value: ["cards", "story_points", "date"],
        x: 'date',
      },
      xFormat: constants.datetime_format,
      type: "line"
    };
    var ch = {
      data: chart_data,
      axis: {
        x: {
          type: 'timeseries',
          label: 'Time',
          tick: {
            format: constants.day_format
          }
        },
        y: {
          label: 'Count',
        }
      }
    };
    $.extend(true, ch, chart_defaults);
    chart = c3.generate(ch);
  }
};

function load_chart(callback) {
  $("#errors").hide()
  $.post(
    GLOBAL.chart_data_url,
    $('#chart-settings').serialize(),
    function(data) {
      if ("error" in data) {
        $("#errors").show()
        $("#error-content").html(data.error);
      } else {
        callback(data);
      }
    },
    'json' // I expect a JSON response
  );
}

var controller = {
  chart: function(){
    // load chart data
    load_chart(function(data) {
      charting[GLOBAL.chart_name](data);
    });

    // get chart data on form submit
    $('input#submit-button').click(function() {
      load_chart(function(data) {
        charting["reload_" + GLOBAL.chart_name](data);
      });
    });
  },
  index: function(){},
  chart_without_form: function() {
    $.get(
      GLOBAL.chart_data_url,
      function(data) {
        charting[GLOBAL.chart_name](data);
      },
      'json' // I expect a JSON response
    );
  }
};

// DOM is ready, let's start the show
$(function() {
  controller[GLOBAL.view]();

  $('.datepicker').datepicker({
    format: 'yyyy-mm-dd'
  });
  $('.timepicker').datetimepicker({
    format: 'LT',
  });
  // focus event is still on when you're changing options, let's hook with change event
  $("div.state-workflow div.state-workflow-column select").change(on_focus_states);
});

// handler for growing state machine
function on_focus_states(data) {
  var t = $(this); // select
  var parent_div = t.parent("div"); // div.state-workflow-column
  var root_div = parent_div.parent("div.state-workflow");

  // selectedIndex is better than .filter(":selected")
  if (root_div.children("div.state-workflow-column").last().children("select")[0].selectedIndex > 0) {
    var new_div = root_div
        .children("div.state-workflow-column")
        .last()
        .clone()
        .appendTo(root_div)
    var new_select = new_div
        .children("select")
        .val("")
        .attr("id", function(i, oldVal) {
            return oldVal.replace(/\d+/, function(m) {
                return (+m + 1);  // +m means it's converted to `int(m) + 1`
            });
        })
        .attr("name", function(i, oldVal) {
            return oldVal.replace(/\d+/, function(m) {
                return (+m + 1);
            });
        })
    new_select
        .on("change", on_focus_states);
    // set # of forms, needed by django formsets
    parent_div.siblings("input[id$='-TOTAL_FORMS']")
        .val(root_div.find("div.state-workflow-column").length);
  }
}

function get_tooltip(d, defaultTitleFormat, defaultValueFormat, color) {
  var card = this.config.data_json[d[0].source_index];
  var titleFormat = this.config.tooltip_format_title || defaultTitleFormat;
  var title = titleFormat ? titleFormat(d[0].x) : d[0].x;

  var valueFormat = this.config.tooltip_format_value || defaultValueFormat;
  var value = valueFormat(d[0].value, d[0].ratio, d[0].id, d[0].index, d);

  var tooltip = $("div#custom-chart-tooltip").html();

  tooltip = tooltip.replace("TITLE", "#" + card.trello_card_short_id + " " + card.name);
  tooltip = tooltip.replace("DATE", title);
  tooltip = tooltip.replace("DAYS", value);
  return tooltip;
}

function on_point_click(d, element) {
  var card_id = this.internal.config.data_json[d.source_index].id;
  window.open('/card/' + card_id + '/', '_blank');
}

function point_size(d) {
  var sizes={0:2, 1:3, 2:4, 3:5, 5:6, 8:8, 13:11};
  var point_size = this.data_json[d.source_index].size;
  for (var s in sizes) {
    if (s >= point_size) {
      return sizes[s];
    }
  }
  return 15;
}

function get_burndown_tooltip(d, defaultTitleFormat, defaultValueFormat, color) {
  var data = this.config.data_json[d[0].source_index];
  var template_b="

";
  var template_e="

";
  var cards = "";
  data.done_cards.forEach(function(card) {
    cards += "
" + card.name + "
";
  });
  var response = template_b + cards +
    "
Done	" + data.done + "
" +
    "
Not done	" + data.not_done + "
" +
    template_e;
  return response;
}
<|endoftext|>


<commit_before>FlowRouter.route('/', {
    name: "home",
    action: function(path, params) {
        if (params.type) {
            Session.set('type',  params.type);
            Session.set('genre',  "");
        }
        if (params.genre) {
            Session.set('genre', params.genre);
        }
    }
});

Template.mmenu.rendered = function() {
    // initialize mobile-menu
    $('#mmenu').mmenu({
        classes: "mm-white",
        header: false,
        counters: true,
        onClick: {
            blockUI: false,
            close: true,
            preventDefault: false,
            setSelected: true,
        },
        offCanvas: {
            position: "left",
            zposition: "front"
        }
    });
};

Template.mmenu.helpers({
    items: function() {
        // get all records, group by type
        var groups = _.groupBy(Movies.find({}, {
            fields: {type: true, genre: true}
        }).fetch(), function(r) {
            return r.type;
        });
        // reduce
        var result = [];
        _.map(_.keys(groups), function(key) {
            var r = _.reduce(groups[key], function(r1, r2) {
                return {
                    type: r1.type,
                    genre: _.union(r1.genre, r2.genre)
                };
            });
            if (r.type.length > 0) {
                r.genres = _.map(r.genre.sort(), function(t){
                    return {
                        type: r.type,
                        genre: t
                    };
                });
                result.push(r);
            }
        });
        return result;
    }
});
<commit_msg>use Template.onRendered rather than deprecated Template.rendered<commit_after>FlowRouter.route('/', {
    name: "home",
    action: function(path, params) {
        if (params.type) {
            Session.set('type',  params.type);
            Session.set('genre',  "");
        }
        if (params.genre) {
            Session.set('genre', params.genre);
        }
    }
});

Template.mmenu.onRendered(function() {
    // initialize mobile-menu
    $('#mmenu').mmenu({
        classes: "mm-white",
        header: false,
        counters: true,
        onClick: {
            blockUI: false,
            close: true,
            preventDefault: false,
            setSelected: true,
        },
        offCanvas: {
            position: "left",
            zposition: "front"
        }
    });
});

Template.mmenu.helpers({
    items: function() {
        // get all records, group by type
        var groups = _.groupBy(Movies.find({}, {
            fields: {type: true, genre: true}
        }).fetch(), function(r) {
            return r.type;
        });
        // reduce
        var result = [];
        _.map(_.keys(groups), function(key) {
            var r = _.reduce(groups[key], function(r1, r2) {
                return {
                    type: r1.type,
                    genre: _.union(r1.genre, r2.genre)
                };
            });
            if (r.type.length > 0) {
                r.genres = _.map(r.genre.sort(), function(t){
                    return {
                        type: r.type,
                        genre: t
                    };
                });
                result.push(r);
            }
        });
        return result;
    }
});
<|endoftext|>


<commit_before>// Node.JS standard modules

var crypto = require('crypto'),
    fs = require('fs');

// 3rd-party modules

var Q = require('q'),
    mmm = require('mmmagic'),
    magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE);

// custom modules

// this module

/**
 * represents an individual file in the CDN, with required actions
 * @constructor
 */
var File = function(options) {
  var self = this,
      dfrd = Q.defer(),
      promises = [];

  this.localPath = options.localPath || '';
  this.path = options.path || '';
  this.mime = '';
  this.md5 = '';
  this.size = options.size;
  this.action = options.action || ''; // 'PUT' or 'DELETE'
  this.headers = null; // only those missing from destination
  this.promise = dfrd.promise;
  this.isDirty = options.isDirty || false;

  if (options.headers) {
    this.headers = JSON.parse(JSON.stringify(options.headers));
  } else {
    this.headers = {};
  }

  if (options.mime) {
    this.mime = options.mime;
  } else if (this.localPath) {
    promises.push(this.detectMIME());
  }

  if (options.md5) {
    this.md5 = options.md5;
  } else if (this.localPath) {
    promises.push(this.calculateMD5());
  }

  Q.all(promises).then(function() {
    process.nextTick(function() {
      dfrd.resolve(self);
    });
  });

  return this;
};

File.prototype.toString = function() {
  var string = '',
      mime = this.mime;

  mime = mime.replace('application', 'app.');
  mime = mime.replace('javascript', 'js.');
  if (this.action === 'PUT') {
    string += '+';
  } else if (this.action === 'DELETE') {
    string += '-';
  } else if (Object.keys(this.headers).length) {
    string += '*';
  }
  string += this.path + ': ';
  string += '#' + this.md5.substr(0, 6) + ' ';
  string += this.size + ' ';
  string += mime;
  return string;
};

File.prototype.setMIME = function(mime) {
  var parts,
      ext;
  if (mime.indexOf('text/') === 0) {
    parts = this.path.split('.');
    ext = parts[parts.length - 1];
    switch (ext) {
      case 'css':
        this.mime = 'text/css';
        break;
      case 'html':
        this.mime = 'text/html';
        break;
      case 'js':
        this.mime = 'application/javascript';
        break;
      case 'xml':
        this.mime = 'application/xml';
        break;
      default:
        this.mime = mime;
    }
  } else {
    this.mime = mime;
  }
};

File.prototype.detectMIME = function() {
  var self = this,
      dfrd = Q.defer();

  Q.ninvoke(magic, 'detectFile', this.localPath)
  .then(function(result) {
    self.setMIME(result);
    dfrd.resolve();
  }).fail(function(err) {
    dfrd.reject(err);
  }).done();
  return dfrd.promise;
};

File.prototype.calculateMD5 = function() {
  var self = this,
      dfrd = Q.defer(),
      md5 = crypto.createHash('md5'),
      rs;

  rs = fs.createReadStream(this.localPath);
  rs.on('error', function(err) {
    dfrd.reject(err);
  });
  rs.on('data', function(data) {
    md5.update(data);
  });
  rs.once('end', function() {
    self.md5 = md5.digest('hex');
    dfrd.resolve();
  });
  return dfrd.promise;
};

// exports

module.exports = File;
<commit_msg>add File.prototype.clone() for convenience<commit_after>// Node.JS standard modules

var crypto = require('crypto'),
    fs = require('fs');

// 3rd-party modules

var Q = require('q'),
    mmm = require('mmmagic'),
    magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE);

// custom modules

// this module

/**
 * represents an individual file in the CDN, with required actions
 * @constructor
 */
var File = function(options) {
  var self = this,
      dfrd = Q.defer(),
      promises = [];

  this.localPath = options.localPath || '';
  this.path = options.path || '';
  this.mime = '';
  this.md5 = '';
  this.size = options.size;
  this.action = options.action || ''; // 'PUT' or 'DELETE'
  this.headers = null; // only those missing from destination
  this.promise = dfrd.promise;
  this.isDirty = options.isDirty || false;

  if (options.headers) {
    this.headers = JSON.parse(JSON.stringify(options.headers));
  } else {
    this.headers = {};
  }

  if (options.mime) {
    this.mime = options.mime;
  } else if (this.localPath) {
    promises.push(this.detectMIME());
  }

  if (options.md5) {
    this.md5 = options.md5;
  } else if (this.localPath) {
    promises.push(this.calculateMD5());
  }

  Q.all(promises).then(function() {
    process.nextTick(function() {
      dfrd.resolve(self);
    });
  });

  return this;
};

File.prototype.clone = function() {
  return new File(this);
};

File.prototype.toString = function() {
  var string = '',
      mime = this.mime;

  mime = mime.replace('application', 'app.');
  mime = mime.replace('javascript', 'js.');
  if (this.action === 'PUT') {
    string += '+';
  } else if (this.action === 'DELETE') {
    string += '-';
  } else if (Object.keys(this.headers).length) {
    string += '*';
  }
  string += this.path + ': ';
  string += '#' + this.md5.substr(0, 6) + ' ';
  string += this.size + ' ';
  string += mime;
  return string;
};

File.prototype.setMIME = function(mime) {
  var parts,
      ext;
  if (mime.indexOf('text/') === 0) {
    parts = this.path.split('.');
    ext = parts[parts.length - 1];
    switch (ext) {
      case 'css':
        this.mime = 'text/css';
        break;
      case 'html':
        this.mime = 'text/html';
        break;
      case 'js':
        this.mime = 'application/javascript';
        break;
      case 'xml':
        this.mime = 'application/xml';
        break;
      default:
        this.mime = mime;
    }
  } else {
    this.mime = mime;
  }
};

File.prototype.detectMIME = function() {
  var self = this,
      dfrd = Q.defer();

  Q.ninvoke(magic, 'detectFile', this.localPath)
  .then(function(result) {
    self.setMIME(result);
    dfrd.resolve();
  }).fail(function(err) {
    dfrd.reject(err);
  }).done();
  return dfrd.promise;
};

File.prototype.calculateMD5 = function() {
  var self = this,
      dfrd = Q.defer(),
      md5 = crypto.createHash('md5'),
      rs;

  rs = fs.createReadStream(this.localPath);
  rs.on('error', function(err) {
    dfrd.reject(err);
  });
  rs.on('data', function(data) {
    md5.update(data);
  });
  rs.once('end', function() {
    self.md5 = md5.digest('hex');
    dfrd.resolve();
  });
  return dfrd.promise;
};

// exports

module.exports = File;
<|endoftext|>


<commit_before>import m from 'mithril';
import _ from 'underscore';
import h from '../h';
import userVM from '../vms/user-vm';

const postsPreview = {
    controller(args) {
        const togglePreview = () => {
                args.showPreview(false);
            },
            sendNotification = (e) => {
                e.preventDefault();

                const notificationData = {
                    title: args.title(),
                    comment_html: args.comment_html(),
                    reward_id: args.reward_id >= 1 ? args.reward_id : null,
                    recipients: args.reward_id >= 1 ? 'reward' : args.reward_id == '-1' ? 'public' : 'backers'
                };

                return m.request({
                    method: 'POST',
                    url: `/projects/${args.project_id}/posts.json`,
                    data: {
                        project_post: notificationData,
                        project: args.project_id
                    },
                    config: h.setCsrfToken
                }).then(() => {
                    args.showSuccess(true);
                    args.comment_html('');
                    args.title('');
                    togglePreview();
                    m.redraw();
                }).catch((err) => {
                    args.errors('Erro ao enviar mensagem.'),
                    args.showError(true);
                    m.redraw();
                });
            };
        return {
            sendNotification: sendNotification,
            togglePreview
        };
    },
    view(ctrl, args) {
        const comment_html = args.comment_html(),
            title = args.title(),
            recipientsText = args.reward_id > 1 ?
            m('.fontsize-small.u-marginbottom-30', [
                'A novidade acima será enviada por email para os ',
                m('span.fontweight-semibold',
                    args.rewardText
                ),
                ' e ficará ',
                m('span.fontweight-semibold',
                'visível na plataforma somente para esses apoiadores.'
                )
            ]) :
            args.reward_id == '-1' ?
            m('.fontsize-small.u-marginbottom-30', [
                'A novidade acima será  ',
                m('span.fontweight-semibold',
                    'enviada por email para todos'
                ),
                ' os apoiadores e ficará ',
                m('span.fontweight-semibold',
                    'visível publicamente '
                ),
                'na plataforma.'
            ]) :
            m('.fontsize-small.u-marginbottom-30', [
                m('span', ' A novidade acima será  '),
                m('span.fontweight-semibold', 'enviada por email para todos os apoiadores'),
                m('span', ' e ficará '),
                m('span.fontweight-semibold' , 'visível somente para esses na plataforma.')
            ]);

        return m('div', [

            m('.dashboard-header.u-text-center',
                m('.w-container',
                    m('.w-row', [
                        m('.w-col.w-col-3'),
                        m('.w-col.w-col-6',
                            m('.fontsize-larger.fontweight-semibold.lineheight-tight',
                                'Revise sua novidade antes de enviar!'
                            )
                        ),
                        m('.w-col.w-col-3')
                    ])
                )
            ),
            m('.section', [
                m('.w-container',
                    m('.card.u-marginbottom-60.u-radius.w-row', [
                        m('.w-col.w-col-1'),
                        m('.u-marginbottom-30.u-margintop-30.w-col.w-col-10.w-hidden-small.w-hidden-tiny', [
                            m('.fontcolor-secondary.fontsize-small.u-text-center',
                                '16/01/2017'
                            ),
                            m('.fontsize-larger.fontweight-semibold.u-marginbottom-30.u-text-center',
                                title
                            ),
                            m('.fontsize-base', m.trust(comment_html))
                        ]),
                        m('.w-col.w-col-1')
                    ])
                ),
                m('.w-row', [
                    m('.w-col.w-col-3'),
                    m('.w-col.w-col-6',
                        recipientsText
                    ),
                    m('.w-col.w-col-3')
                ]),
                m('.u-marginbottom-20.w-row', [
                    m('.w-col.w-col-3'),
                    m('._w-sub-col.w-col.w-col-4',
                        m('button.btn.btn-large', {
                            onclick: ctrl.sendNotification
                        }, [
                            m('span.fa.fa-paper-plane',
                                ''
                            ),
                            ' ',
                            m.trust(' '),
                            'Enviar'
                        ])
                    ),
                    m('.w-col.w-col-2',
                        m('button.btn.btn-large.btn-terciary', {
                                onclick: ctrl.togglePreview
                            },
                            'Editar'
                        )
                    ),
                    m('.w-col.w-col-3')
                ])
            ])
        ]);
    }
};

export default postsPreview;
<commit_msg>Adds scroll top behaviour on post edit click [#139341989]<commit_after>import m from 'mithril';
import _ from 'underscore';
import h from '../h';
import userVM from '../vms/user-vm';

const postsPreview = {
    controller(args) {
        const togglePreview = () => {
                h.scrollTop();
                args.showPreview(false);
            },
            sendNotification = (e) => {
                e.preventDefault();

                const notificationData = {
                    title: args.title(),
                    comment_html: args.comment_html(),
                    reward_id: args.reward_id >= 1 ? args.reward_id : null,
                    recipients: args.reward_id >= 1 ? 'reward' : args.reward_id == '-1' ? 'public' : 'backers'
                };

                return m.request({
                    method: 'POST',
                    url: `/projects/${args.project_id}/posts.json`,
                    data: {
                        project_post: notificationData,
                        project: args.project_id
                    },
                    config: h.setCsrfToken
                }).then(() => {
                    args.showSuccess(true);
                    args.comment_html('');
                    args.title('');
                    togglePreview();
                    m.redraw();
                }).catch((err) => {
                    args.errors('Erro ao enviar mensagem.'),
                    args.showError(true);
                    m.redraw();
                });
            };
        return {
            sendNotification: sendNotification,
            togglePreview
        };
    },
    view(ctrl, args) {
        const comment_html = args.comment_html(),
            title = args.title(),
            recipientsText = args.reward_id > 1 ?
            m('.fontsize-small.u-marginbottom-30', [
                'A novidade acima será enviada por email para os ',
                m('span.fontweight-semibold',
                    args.rewardText
                ),
                ' e ficará ',
                m('span.fontweight-semibold',
                'visível na plataforma somente para esses apoiadores.'
                )
            ]) :
            args.reward_id == '-1' ?
            m('.fontsize-small.u-marginbottom-30', [
                'A novidade acima será  ',
                m('span.fontweight-semibold',
                    'enviada por email para todos'
                ),
                ' os apoiadores e ficará ',
                m('span.fontweight-semibold',
                    'visível publicamente '
                ),
                'na plataforma.'
            ]) :
            m('.fontsize-small.u-marginbottom-30', [
                m('span', ' A novidade acima será  '),
                m('span.fontweight-semibold', 'enviada por email para todos os apoiadores'),
                m('span', ' e ficará '),
                m('span.fontweight-semibold' , 'visível somente para esses na plataforma.')
            ]);

        return m('div', [

            m('.dashboard-header.u-text-center',
                m('.w-container',
                    m('.w-row', [
                        m('.w-col.w-col-3'),
                        m('.w-col.w-col-6',
                            m('.fontsize-larger.fontweight-semibold.lineheight-tight',
                                'Revise sua novidade antes de enviar!'
                            )
                        ),
                        m('.w-col.w-col-3')
                    ])
                )
            ),
            m('.section', [
                m('.w-container',
                    m('.card.u-marginbottom-60.u-radius.w-row', [
                        m('.w-col.w-col-1'),
                        m('.u-marginbottom-30.u-margintop-30.w-col.w-col-10.w-hidden-small.w-hidden-tiny', [
                            m('.fontcolor-secondary.fontsize-small.u-text-center',
                                '16/01/2017'
                            ),
                            m('.fontsize-larger.fontweight-semibold.u-marginbottom-30.u-text-center',
                                title
                            ),
                            m('.fontsize-base', m.trust(comment_html))
                        ]),
                        m('.w-col.w-col-1')
                    ])
                ),
                m('.w-row', [
                    m('.w-col.w-col-3'),
                    m('.w-col.w-col-6',
                        recipientsText
                    ),
                    m('.w-col.w-col-3')
                ]),
                m('.u-marginbottom-20.w-row', [
                    m('.w-col.w-col-3'),
                    m('._w-sub-col.w-col.w-col-4',
                        m('button.btn.btn-large', {
                            onclick: ctrl.sendNotification
                        }, [
                            m('span.fa.fa-paper-plane',
                                ''
                            ),
                            ' ',
                            m.trust(' '),
                            'Enviar'
                        ])
                    ),
                    m('.w-col.w-col-2',
                        m('button.btn.btn-large.btn-terciary', {
                                onclick: ctrl.togglePreview
                            },
                            'Editar'
                        )
                    ),
                    m('.w-col.w-col-3')
                ])
            ])
        ]);
    }
};

export default postsPreview;
<|endoftext|>


<commit_before>var debug = require('debug')('transmogrifier.js');
var leftPad = require('left-pad');

var SerialCoder = function SerialCoder(schema) {
  if (!(this instanceof SerialCoder)) {
    debug('Class not called with new. Instantiate automatically.');
    return new SerialCoder();
  }
  debug('Instantiated new SerialCoder class.');

  if (typeof schema !== 'object') {
    debug('Schema argument not object. Actual: %s.', typeof schema);
    throw new TypeError('Schema argument is required and must be an object.');
  }

  if (Object.keys(schema).length === 0) {
    debug('Invalid schema. Must have at least one property.');
    throw new Error('Invlid schema object. Must have at least one property.');
  }

  this._schema = schema;

  this._values = {};
  this._primaryBytes = 0;
  for (var property in schema) {
    this._values[property] = undefined;
    if (!('bytes' in schema[property])) {
      schema[property].bytes = 1;
    }
    this._primaryBytes += schema[property].bytes;
  }

  var saltLength = this._primaryBytes + 1;
  var salt = Math.floor(Math.random() * (Math.pow(2, saltLength) - 1));
  this.salt = this._salt = leftPad(salt.toString(2), saltLength, 0);
  this._totalBits = this._primaryBytes * 8 + this.salt.length;

  Object.defineProperties(this, {
    'salt': {
      get: function() {
        debug('Get the value of the salt.');
        return this._salt;
      },
      set: function(value) {
        debug('Set the value of the salt to %s.', value);
        var max = Math.pow(2, saltLength) - 1;
        switch (typeof value) {
          case 'number':
            if (value < 0 || value > max) {
              throw new RangeError('Value must be between 0 and ' + max + '.');
            }
            break;
          case 'string':
            if (value.match(/[^0-1]/g)) {
              throw new TypeError('Salt string must be a binary string.');
            }
            if (value.length !== this._salt.length) {
              throw new RangeError('Salt string must be ' +
                this._salt.length + ' chracters.');
            }
            value = parseInt(value, 2);
            break;
          case 'function':
            if (value === Math.random) {
              value = Math.floor(Math.random() * max);
              break;
            }
          default:
            throw new TypeError(
              'Salt must be either a number or binary string.');
        }
        this._salt = leftPad(value.toString(2), saltLength, 0);
        return this._salt;
      }
    }
  });

  return this;
};

SerialCoder.prototype.get = function(property) {
  if (property === undefined) {
    debug('Return all properties as an object.');
    return this._values;
  }

  debug('Get value of property %s.', property);
  if (!(property in this._schema)) {
    debug('Property %s not defined. Unable to get value', property);
    throw new ReferenceError('Property ' + property + ' not defined.');
  }

  return this._values[property];
};

var setPropertyValue = function(property, value) {
  if (!(property in this._schema)) {
    debug('Property %s not defined. Unable to set value', property);
    throw new ReferenceError('Property ' + property + ' not defined.');
  }

  if (typeof value !== 'number') {
    debug('Property value not a number. Actual %s.', typeof value);
    throw new TypeError('Value must be a number.');
  }

  var maxValue = Math.pow(2, this._schema[property]) - 1;

  if (value < 0 || value > maxValue) {
    debug('Value outside valid range. Range 0 - %d. Value %d.',
      maxValue, value);
    throw new RangeError('Value outside range. Range 0 - ' +
      maxValue + '. Value ' + value + '.');
  }

  this._values[property] = value;
  return this._values[property];
};

var deserialize = function(value) {
  debug('Decode string into properties.');

  if (typeof value !== 'string') {
    debug('Parameter must be a string. Passed in %s.', typeof value);
    throw new TypeError('First parameter must be a string.');
  }

  if (value.match(/[^0-1]/g)) {
    debug('SerialNumber string was not a binary string.');
    throw new TypeError('Parameter must be a binary string.');
  }

  if (value.length !== this._totalBits) {
    debug('Invalid string length.');
    throw new RangeError('Invalid string length. Expected %d.',
      this._totalBits);
  }

  var globalInvert = parseInt(value.charAt(this._totalBits - 1));
  var chunks = value.substr(0, this._totalBits - 1).match(/.{1,9}/g);
  chunks = chunks.map(function(chunk) {
    var localInvert = parseInt(chunk.charAt(0));
    var byte = chunk.substr(1);
    if (localInvert !== globalInvert) {
      byte = byte.split('').map(function(bit) {
        return parseInt(bit) ? 0 : 1;
      }).join('');
    }
    return byte;
  });

  for (var property in this._schema) {
    var propertyBytes = chunks.splice(0, this._schema[property].bytes);
    setPropertyValue.call(this, property,
      parseInt(propertyBytes.join(''), 2));
  }

  return this;
};

SerialCoder.prototype.set = function(property, value) {
  switch (arguments.length) {
    case 1:
      switch (typeof property) {
        case 'object':
          debug('Set values of properties using an object. %o', property);
          var response = {};
          for (var prop in property) {
            response[prop] = setPropertyValue.call(this, prop, property[prop]);
          }
          return response;
        case 'string':
          if (value.match(/[^0-1]/g)) {
            throw new TypeError(
              'Single argument string must be a binary string.');
          }
          debug('deserialize an encoded string.');
          deserialize(property);
          return this._values;
        default:
          throw new TypeError('When supplying one argument,' +
            ' it must be either a string or object.');
      }
    case 2:
      debug('Set value of property %s to %s.', property, value);
      return setPropertyValue.call(this, property, value);
    default:
      throw new Error('Set method must take either one or two arguments.');
  }
};

var normalizeChunks = function(chunks, globalInvert, salt) {
  var saltIndex = 0;
  return chunks.map(function(chunk) {
    var localInvert = parseInt(salt.charAt(saltIndex));
    if (localInvert !== globalInvert) {
      chunk = chunk.split('').map(function(bit) {
        return parseInt(bit) ? 0 : 1;
      }).join('');
    }
    saltIndex++;
    return localInvert + chunk;
  });
};

SerialCoder.prototype.toString = function() {
  debug('Return string value of serial.');

  var undefinedProperties = [];
  for (var property in this._schema) {
    if (this._values[property] === undefined) {
      undefinedProperties.push(property);
    }
  }
  if (undefinedProperties.length) {
    debug('There are some undefined properties. Cannot proceed.');
    throw new Error('All properties must be defined.' +
      ' The following properties are undefined: ' +
      undefinedProperties.join(', ') + '.');
  }

  var globalInvert = parseInt(this._salt.charAt(this._salt.length - 1));
  var salt = this._salt.substring(0, this._salt.length - 1);

  var serial = '';

  for (property in this._schema) {
    var bytes = this._schema[property].bytes;
    var bin = leftPad(this._values[property].toString(2), 8 * bytes, 0);
    var chunks = bin.match(/.{1,8}/g);
    serial += normalizeChunks(chunks, globalInvert, salt).join('');
  }

  return serial + globalInvert;
};

module.exports = SerialCoder;
<commit_msg>fix issue with context<commit_after>var debug = require('debug')('transmogrifier.js');
var leftPad = require('left-pad');

var SerialCoder = function SerialCoder(schema) {
  if (!(this instanceof SerialCoder)) {
    debug('Class not called with new. Instantiate automatically.');
    return new SerialCoder();
  }
  debug('Instantiated new SerialCoder class.');

  if (typeof schema !== 'object') {
    debug('Schema argument not object. Actual: %s.', typeof schema);
    throw new TypeError('Schema argument is required and must be an object.');
  }

  if (Object.keys(schema).length === 0) {
    debug('Invalid schema. Must have at least one property.');
    throw new Error('Invlid schema object. Must have at least one property.');
  }

  this._schema = schema;

  this._values = {};
  this._primaryBytes = 0;
  for (var property in schema) {
    this._values[property] = undefined;
    if (!('bytes' in schema[property])) {
      schema[property].bytes = 1;
    }
    this._primaryBytes += schema[property].bytes;
  }

  var saltLength = this._primaryBytes + 1;
  var salt = Math.floor(Math.random() * (Math.pow(2, saltLength) - 1));
  this.salt = this._salt = leftPad(salt.toString(2), saltLength, 0);
  this._totalBits = this._primaryBytes * 8 + this.salt.length;

  Object.defineProperties(this, {
    'salt': {
      get: function() {
        debug('Get the value of the salt.');
        return this._salt;
      },
      set: function(value) {
        debug('Set the value of the salt to %s.', value);
        var max = Math.pow(2, saltLength) - 1;
        switch (typeof value) {
          case 'number':
            if (value < 0 || value > max) {
              throw new RangeError('Value must be between 0 and ' + max + '.');
            }
            break;
          case 'string':
            if (value.match(/[^0-1]/g)) {
              throw new TypeError('Salt string must be a binary string.');
            }
            if (value.length !== this._salt.length) {
              throw new RangeError('Salt string must be ' +
                this._salt.length + ' chracters.');
            }
            value = parseInt(value, 2);
            break;
          case 'function':
            if (value === Math.random) {
              value = Math.floor(Math.random() * max);
              break;
            }
          default:
            throw new TypeError(
              'Salt must be either a number or binary string.');
        }
        this._salt = leftPad(value.toString(2), saltLength, 0);
        return this._salt;
      }
    }
  });

  return this;
};

SerialCoder.prototype.get = function(property) {
  if (property === undefined) {
    debug('Return all properties as an object.');
    return this._values;
  }

  debug('Get value of property %s.', property);
  if (!(property in this._schema)) {
    debug('Property %s not defined. Unable to get value', property);
    throw new ReferenceError('Property ' + property + ' not defined.');
  }

  return this._values[property];
};

var setPropertyValue = function(property, value) {
  if (!(property in this._schema)) {
    debug('Property %s not defined. Unable to set value', property);
    throw new ReferenceError('Property ' + property + ' not defined.');
  }

  if (typeof value !== 'number') {
    debug('Property value not a number. Actual %s.', typeof value);
    throw new TypeError('Value must be a number.');
  }

  var maxValue = Math.pow(2, this._schema[property]) - 1;

  if (value < 0 || value > maxValue) {
    debug('Value outside valid range. Range 0 - %d. Value %d.',
      maxValue, value);
    throw new RangeError('Value outside range. Range 0 - ' +
      maxValue + '. Value ' + value + '.');
  }

  this._values[property] = value;
  return this._values[property];
};

var deserialize = function(value) {
  debug('Decode string into properties.');

  if (typeof value !== 'string') {
    debug('Parameter must be a string. Passed in %s.', typeof value);
    throw new TypeError('First parameter must be a string.');
  }

  if (value.match(/[^0-1]/g)) {
    debug('SerialNumber string was not a binary string.');
    throw new TypeError('Parameter must be a binary string.');
  }

  if (value.length !== this._totalBits) {
    debug('Invalid string length.');
    throw new RangeError('Invalid string length. Expected ' +
       this._totalBits + '.');
  }

  var globalInvert = parseInt(value.charAt(this._totalBits - 1));
  var chunks = value.substr(0, this._totalBits - 1).match(/.{1,9}/g);
  chunks = chunks.map(function(chunk) {
    var localInvert = parseInt(chunk.charAt(0));
    var byte = chunk.substr(1);
    if (localInvert !== globalInvert) {
      byte = byte.split('').map(function(bit) {
        return parseInt(bit) ? 0 : 1;
      }).join('');
    }
    return byte;
  });

  for (var property in this._schema) {
    var propertyBytes = chunks.splice(0, this._schema[property].bytes);
    setPropertyValue.call(this, property,
      parseInt(propertyBytes.join(''), 2));
  }

  return this;
};

SerialCoder.prototype.set = function(property, value) {
  switch (arguments.length) {
    case 1:
      switch (typeof property) {
        case 'object':
          debug('Set values of properties using an object. %o', property);
          var response = {};
          for (var prop in property) {
            response[prop] = setPropertyValue.call(this, prop, property[prop]);
          }
          return response;
        case 'string':
          if (property.match(/[^0-1]/g)) {
            throw new TypeError(
              'Single argument string must be a binary string.');
          }
          debug('deserialize an encoded string.');
          deserialize.call(this, property);
          return this._values;
        default:
          throw new TypeError('When supplying one argument,' +
            ' it must be either a string or object.');
      }
    case 2:
      debug('Set value of property %s to %s.', property, value);
      return setPropertyValue.call(this, property, value);
    default:
      throw new Error('Set method must take either one or two arguments.');
  }
};

var normalizeChunks = function(chunks, globalInvert, salt) {
  var saltIndex = 0;
  return chunks.map(function(chunk) {
    var localInvert = parseInt(salt.charAt(saltIndex));
    if (localInvert !== globalInvert) {
      chunk = chunk.split('').map(function(bit) {
        return parseInt(bit) ? 0 : 1;
      }).join('');
    }
    saltIndex++;
    return localInvert + chunk;
  });
};

SerialCoder.prototype.toString = function() {
  debug('Return string value of serial.');

  var undefinedProperties = [];
  for (var property in this._schema) {
    if (this._values[property] === undefined) {
      undefinedProperties.push(property);
    }
  }
  if (undefinedProperties.length) {
    debug('There are some undefined properties. Cannot proceed.');
    throw new Error('All properties must be defined.' +
      ' The following properties are undefined: ' +
      undefinedProperties.join(', ') + '.');
  }

  var globalInvert = parseInt(this._salt.charAt(this._salt.length - 1));
  var salt = this._salt.substring(0, this._salt.length - 1);

  var serial = '';

  for (property in this._schema) {
    var bytes = this._schema[property].bytes;
    var bin = leftPad(this._values[property].toString(2), 8 * bytes, 0);
    var chunks = bin.match(/.{1,8}/g);
    serial += normalizeChunks(chunks, globalInvert, salt).join('');
  }

  return serial + globalInvert;
};

module.exports = SerialCoder;
<|endoftext|>


<commit_before>module.exports = {
  main: [{
    type: "list",
    name: "type",
    message: "请选择需要更改的配置项: ",
    choices: [{
      value: "account",
      name: '配置豆瓣电台账户密码 / Update douban.fm account'
    }, {
      value: 'download',
      name: '更新下载文件夹路径 / Update download directory path'
    }, {
      value: 'http_proxy',
      name: '设置HTTP代理 / Set http proxy'
    }, {
      value: 'id3',
      name: '更新本地曲库歌曲ID3 / Update ID3 for local songs'
    }, {
      value: 'help',
      name: '查看帮助文档 / Help'
    }, {
      value: 'quit',
      name: '退出配置向导 / Quit'
    }]
  }],
  account: [{
    type: "input",
    name: "email",
    message: "豆瓣账户 (Email 地址)",
    validate: function(value) {
      var EmailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      var pass = value.match(EmailRegex);
      if (pass) {
        return true;
      } else {
        return "请输入有效的 Email 地址";
      }
    }
  }, {
    type: "password",
    name: "password",
    message: "豆瓣密码 (不会保留密码) ",
    validate: function(value) {
      if (value && value.length > 0) return true;
      return "请输入有效密码";
    }
  }],
  download: {
    main: function(dir) {
      return [{
        type: "confirm",
        name: "useWorkingPath",
        message: "将下载目录设置为当前目录 " + dir + "?",
        default: true
      }]
    },
    setting: [{
      type: "input",
      name: "download",
      message: "请输入一个有效的绝对路径作为新的曲库目录"
    }]
  },
  http_proxy: {
    main: function(http_proxy) {
      return [{
        type: "confirm",
        name: "useDefaultProxy",
        message: (http_proxy ? "设置HTTP代理为 " + http_proxy : "直接连接") + "?",
        default: true
      }];
    },
    setting: [{
      type: "input",
      name: "http_proxy",
      message: "HTTP代理格式为 (http://IP_ADDRESS:PORT)"
    }]
  },
};<commit_msg>Rewrite lib menu with ES6<commit_after>export default {
  main: [{
    type: 'list',
    name: 'type',
    message: '请选择需要更改的配置项: ',
    choices: [{
      value: 'account',
      name: '配置豆瓣电台账户密码 / Update douban.fm account'
    }, {
      value: 'download',
      name: '更新下载文件夹路径 / Update download directory path'
    }, {
      value: 'http_proxy',
      name: '设置HTTP代理 / Set http proxy'
    }, {
      value: 'id3',
      name: '更新本地曲库歌曲ID3 / Update ID3 for local songs'
    }, {
      value: 'help',
      name: '查看帮助文档 / Help'
    }, {
      value: 'quit',
      name: '退出配置向导 / Quit'
    }]
  }],
  'account': [{
    type: 'input',
    name: 'email',
    message: '豆瓣账户 (Email 地址)',
    validate: function(value) {
      var EmailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

      return value.match(EmailRegex) ? true : '请输入有效的 Email 地址'
    }
  }, {
    type: 'password',
    name: 'password',
    message: '豆瓣密码 (不会保留密码)',
    validate: function(value) {
      if (value && value.length > 0)
        return true

      return '请输入有效密码'
    }
  }],
  download: {
    main: function(dir) {
      return [{
        type: 'confirm',
        name: 'useWorkingPath',
        message: `将下载目录设置为当前目录 ${ dir }?`,
        default: true,
      }]
    },
    setting: [{
      type: 'input',
      name: 'download',
      message: '请输入一个有效的绝对路径作为新的曲库目录'
    }]
  },
  http_proxy: {
    main: function(http_proxy) {
      return [{
        type: 'confirm',
        name: 'useDefaultProxy',
        message: (http_proxy ? `设置HTTP代理为 ${ http_proxy }` : '直接连接') + '?',
        default: true
      }];
    },
    setting: [{
      type: 'input',
      name: 'http_proxy',
      message: 'HTTP代理格式为 (http://IP_ADDRESS:PORT)'
    }]
  },
}
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.csv2json = csv2json;
exports.json2csv = json2csv;

var _babyparse = require('babyparse');

var _babyparse2 = _interopRequireDefault(_babyparse);

var _flat = require('flat');

var _flat2 = _interopRequireDefault(_flat);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function csv2json(csv) {
  var opts = arguments.length <= 1 || arguments[1] === undefined ? { header: true, skipEmptyLines: true, dynamicTyping: true } : arguments[1];

  var results = _babyparse2.default.parse(csv, opts);
  return (0, _lodash2.default)(results.data).map(_flat.unflatten).value();
}

function json2csv(json) {
  var opts = arguments.length <= 1 || arguments[1] === undefined ? { delimiter: ';' } : arguments[1];

  var data = (0, _lodash2.default)(json).castArray().map(_flat2.default).value();

  var fields = (0, _lodash2.default)(data).map(_lodash2.default.keys).flatten().uniq().value();

  return _babyparse2.default.unparse({ fields: fields, data: data }, opts);
}<commit_msg>Build files<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.csv2json = csv2json;
exports.json2csv = json2csv;

exports.default = function (req, res, next) {
  res.csv = expressDecorator;
  next();
};

var _babyparse = require('babyparse');

var _babyparse2 = _interopRequireDefault(_babyparse);

var _flat = require('flat');

var _flat2 = _interopRequireDefault(_flat);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function csv2json(csv) {
  var opts = arguments.length <= 1 || arguments[1] === undefined ? { header: true, skipEmptyLines: true, dynamicTyping: true } : arguments[1];

  var results = _babyparse2.default.parse(csv, opts);
  return (0, _lodash2.default)(results.data).map(_flat.unflatten).value();
}

function json2csv(json) {
  var opts = arguments.length <= 1 || arguments[1] === undefined ? { delimiter: ';' } : arguments[1];

  var data = (0, _lodash2.default)(json).castArray().map(_flat2.default).value();

  var fields = (0, _lodash2.default)(data).map(_lodash2.default.keys).flatten().uniq().value();

  return _babyparse2.default.unparse({ fields: fields, data: data }, opts);
}

function expressDecorator(rawData) {
  var filename = arguments.length <= 1 || arguments[1] === undefined ? 'res.csv' : arguments[1];
  var opts = arguments[2];

  this.set('Content-Type', 'text/csv; charset=utf-8');
  this.set('Content-Disposition', 'attachment; filename=' + filename);
  this.status(200); // Fix for Chrome (CSV download fail if status is not 200)

  var data = (0, _lodash2.default)(rawData).castArray().map(function (item) {
    return item.toJSON ? item.toJSON() : item;
  }).value();

  var csv = json2csv(data, opts);
  this.send(csv);
}<|endoftext|>