<commit_before>var
  regexLib = require('../regexlib')
  utils = require('../utils'),
  config = require('../config')
  ;

/**
 * Pads number with zeros until it's length is the same as given length.
 *
 * @param {Number} number Number to pad.
 * @param {Number} length Max string length with.
 * @return {String}     Returns a string padded with proper amount of '0'.
 */
function padNumber(number, length)
{
  var result = number.toString();

  while (result.length < length)
    result = '0' + result;

  return result;
};

/**
 * Wraps each line of the string into  tag with given style applied to it.
 *
 * @param {String} str   Input string.
 * @param {String} css   Style name to apply to the string.
 * @return {String}      Returns input string with each line surrounded by  tag.
 */
function wrapLinesWithCode(str, css)
{
  if (str == null || str.length == 0 || str == '\n')
    return str;

  str = str.replace(/</g, '<');

  // Replace two or more sequential spaces with   leaving last space untouched.
  str = str.replace(/ {2,}/g, function(m)
  {
    var spaces = '';

    for (var i = 0, l = m.length; i < l - 1; i++)
      spaces += config.space;

    return spaces + ' ';
  });

  // Split each line and apply ... to them so that
  // leading spaces aren't included.
  if (css != null)
    str = utils.eachLine(str, function(line)
    {
      if (line.length == 0)
        return '';

      var spaces = '';

      line = line.replace(/^( | )+/, function(s)
      {
        spaces = s;
        return '';
      });

      if (line.length == 0)
        return spaces;

      return spaces + '' + line + '';
    });

  return str;
}

/**
 * Turns all URLs in the code into  tags.
 * @param {String} code Input code.
 * @return {String} Returns code with  tags.
 */
function processUrls(code)
{
  var gt = /(.*)((>|<).*)/;

  return code.replace(regexLib.url, function(m)
  {
    var suffix = '',
      match = null
      ;

    // We include < and > in the URL for the common cases like <http://google.com>
    // The problem is that they get transformed into <http://google.com>
    // Where as > easily looks like part of the URL string.

    if (match = gt.exec(m))
    {
      m = match[1];
      suffix = match[2];
    }

    return '' + m + '' + suffix;
  });
}

function Renderer(code, matches, opts)
{
  var _this = this;

  _this.opts = opts;
  _this.code = code;
  _this.matches = matches;
  _this.lines = code.split(/\r?\n/);
};

Renderer.prototype = {
  /**
   * Creates an array containing integer line numbers starting from the 'first-line' param.
   * @return {Array} Returns array of integers.
   */
  figureOutLineNumbers: function(code)
  {
    var lineNumbers = [],
        lines = this.lines,
        firstLine = parseInt(this.opts.firstLine || 0),
        i,
        l
        ;

    for (i = 0, l = lines.length; i < l; i++)
      lineNumbers.push(i + firstLine);

    return lineNumbers;
  },

  /**
   * Determines if specified line number is in the highlighted list.
   */
  isLineHighlighted: function(lineNumber)
  {
    var linesToHighlight = this.opts.highlight || [];

    if (typeof(linesToHighlight.push) !== 'function')
      linesToHighlight = [linesToHighlight];

    return linesToHighlight.indexOf(lineNumber.toString()) !== -1;
  },

  /**
   * Generates HTML markup for a single line of code while determining alternating line style.
   * @param {Integer} lineNumber  Line number.
   * @param {String} code Line  HTML markup.
   * @return {String}       Returns HTML markup.
   */
  wrapLine: function(lineIndex, lineNumber, lineHtml)
  {
    var classes = [
      'line',
      'number' + lineNumber,
      'index' + lineIndex,
      'alt' + (lineNumber % 2 == 0 ? 1 : 2).toString()
    ];

    if (this.isLineHighlighted(lineNumber))
      classes.push('highlighted');

    if (lineNumber == 0)
      classes.push('break');

    return '
' + lineHtml + '
';
  },

  /**
   * Generates HTML markup for line number column.
   * @param {String} code     Complete code HTML markup.
   * @param {Array} lineNumbers Calculated line numbers.
   * @return {String}       Returns HTML markup.
   */
  renderLineNumbers: function(code, lineNumbers)
  {
    var html = '',
        count = utils.splitLines(code).length,
        firstLine = parseInt(this.opts.firstLine),
        pad = this.opts.padLineNumbers,
        lineNumber,
        i
        ;

    if (pad == true)
      pad = (firstLine + count - 1).toString().length;
    else if (isNaN(pad) == true)
      pad = 0;

    for (i = 0; i < count; i++)
    {
      lineNumber = lineNumbers ? lineNumbers[i] : firstLine + i;
      code = lineNumber == 0 ? config.space : padNumber(lineNumber, pad);
      html += this.wrapLine(i, lineNumber, code);
    }

    return html;
  },

  /**
   * Splits block of text into individual DIV lines.
   * @param {String} code     Code to highlight.
   * @param {Array} lineNumbers Calculated line numbers.
   * @return {String}       Returns highlighted code in HTML form.
   */
  getCodeLinesHtml: function(html, lineNumbers)
  {
    // html = utils.trim(html);

    var _this = this,
        lines = utils.splitLines(html),
        padLength = _this.opts.padLineNumbers,
        firstLine = parseInt(_this.opts.firstLine),
        brushName = _this.opts.brush,
        html = ''
        ;

    for (var i = 0, l = lines.length; i < l; i++)
    {
      var line = lines[i],
          indent = /^( |\s)+/.exec(line),
          spaces = null,
          lineNumber = lineNumbers ? lineNumbers[i] : firstLine + i;
          ;

      if (indent != null)
      {
        spaces = indent[0].toString();
        line = line.substr(spaces.length);
        spaces = spaces.replace(' ', config.space);
      }

      line = utils.trim(line);

      if (line.length == 0)
        line = config.space;

      html += _this.wrapLine(
        i,
        lineNumber,
        (spaces != null ? '' + spaces + '' : '') + line
      );
    }

    return html;
  },

  /**
   * Returns HTML for the table title or empty string if title is null.
   */
  getTitleHtml: function(title)
  {
    return title ? '
' + title + '
' : '';
  },

  /**
   * Finds all matches in the source code.
   * @param {String} code   Source code to process matches in.
   * @param {Array} matches Discovered regex matches.
   * @return {String} Returns formatted HTML with processed mathes.
   */
  getMatchesHtml: function(code, matches)
  {
    function getBrushNameCss(match)
    {
      var result = match ? (match.brushName || brushName) : brushName;
      return result ? result + ' ' : '';
    };

    var pos = 0,
        result = '',
        brushName = this.opts.brush || '',
        match,
        matchBrushName,
        i,
        l
        ;

    // Finally, go through the final list of matches and pull the all
    // together adding everything in between that isn't a match.
    for (i = 0, l = matches.length; i < l; i++)
    {
      match = matches[i];

      if (match === null || match.length === 0)
        continue;

      matchBrushName = getBrushNameCss(match);

      result += wrapLinesWithCode(code.substr(pos, match.index - pos), matchBrushName + 'plain')
          + wrapLinesWithCode(match.value, matchBrushName + match.css)
          ;

      pos = match.index + match.length + (match.offset || 0);
    }

    // don't forget to add whatever's remaining in the string
    result += wrapLinesWithCode(code.substr(pos), getBrushNameCss() + 'plain');

    return result;
  },

  /**
   * Generates HTML markup for the whole syntax highlighter.
   * @param {String} code Source code.
   * @return {String} Returns HTML markup.
   */
  getHtml: function()
  {
    var _this = this,
        opts = _this.opts,
        code = _this.code,
        matches = _this.matches,
        classes = ['syntaxhighlighter'],
        lineNumbers,
        html
        ;

    if (opts.collapse === true)
      classes.push('collapsed');

    if ((gutter = opts.gutter) === false)
      classes.push('nogutter');

    // add custom user style name
    classes.push(opts.className);

    // add brush alias to the class name for custom CSS
    classes.push(opts.brush);

    if (gutter)
      lineNumbers = _this.figureOutLineNumbers(code);

    // processes found matches into the html
    html = _this.getMatchesHtml(code, matches);

    // finally, split all lines so that they wrap well
    html = _this.getCodeLinesHtml(html, lineNumbers);

    // finally, process the links
    if (opts.autoLinks)
      html = processUrls(html);

    if (typeof(navigator) != 'undefined' && navigator.userAgent && navigator.userAgent.match(/MSIE/))
      classes.push('ie');

    html =
      '
'
        // + (opts.toolbar ? sh.toolbar.getHtml(_this) : '')
        + '
'
          + _this.getTitleHtml(opts.title)
          + '
'
            + '
'
              + (gutter ? '' + _this.renderLineNumbers(code) + '	' : '')
              + ''
                + '
'
                  + html
                + '
'
              + '	'
            + '
'
          + '
'
        + '
'
      + '
'
      ;

    return html;
  },

  render: function()
  {
    return this.getHtml();
  }
};

module.exports = {
  Renderer: Renderer
};
<commit_msg>Cleans up renderer.<commit_after>var
  utils = require('../utils')
  ;

/**
 * Pads number with zeros until it's length is the same as given length.
 *
 * @param {Number} number Number to pad.
 * @param {Number} length Max string length with.
 * @return {String}     Returns a string padded with proper amount of '0'.
 */
function padNumber(number, length)
{
  var result = number.toString();

  while (result.length < length)
    result = '0' + result;

  return result;
};

function Renderer(code, matches, opts)
{
  var _this = this;

  _this.opts = opts;
  _this.code = code;
  _this.matches = matches;
  _this.lines = code.split(/\r?\n/);
};

Renderer.prototype = {
  /**
   * Wraps each line of the string into  tag with given style applied to it.
   *
   * @param {String} str   Input string.
   * @param {String} css   Style name to apply to the string.
   * @return {String}      Returns input string with each line surrounded by  tag.
   */
  wrapLinesWithCode: function(str, css)
  {
    if (str == null || str.length == 0 || str == '\n')
      return str;

    var _this = this;

    str = str.replace(/</g, '<');

    // Replace two or more sequential spaces with   leaving last space untouched.
    str = str.replace(/ {2,}/g, function(m)
    {
      var spaces = '';

      for (var i = 0, l = m.length; i < l - 1; i++)
        spaces += _this.opts.space;

      return spaces + ' ';
    });

    // Split each line and apply ... to them so that
    // leading spaces aren't included.
    if (css != null)
      str = utils.eachLine(str, function(line)
      {
        if (line.length == 0)
          return '';

        var spaces = '';

        line = line.replace(/^( | )+/, function(s)
        {
          spaces = s;
          return '';
        });

        if (line.length == 0)
          return spaces;

        return spaces + '' + line + '';
      });

    return str;
  },

  /**
   * Turns all URLs in the code into  tags.
   * @param {String} code Input code.
   * @return {String} Returns code with  tags.
   */
  processUrls: function(code)
  {
    var gt = /(.*)((>|<).*)/,
        url = /\w+:\/\/[\w-.\/?%&=:@;#]*/g
        ;

    return code.replace(url, function(m)
    {
      var suffix = '',
          match = null
          ;

      // We include < and > in the URL for the common cases like <http://google.com>
      // The problem is that they get transformed into <http://google.com>
      // Where as > easily looks like part of the URL string.

      if (match = gt.exec(m))
      {
        m = match[1];
        suffix = match[2];
      }

      return '' + m + '' + suffix;
    });
  },

  /**
   * Creates an array containing integer line numbers starting from the 'first-line' param.
   * @return {Array} Returns array of integers.
   */
  figureOutLineNumbers: function(code)
  {
    var lineNumbers = [],
        lines = this.lines,
        firstLine = parseInt(this.opts.firstLine || 0),
        i,
        l
        ;

    for (i = 0, l = lines.length; i < l; i++)
      lineNumbers.push(i + firstLine);

    return lineNumbers;
  },

  /**
   * Determines if specified line number is in the highlighted list.
   */
  isLineHighlighted: function(lineNumber)
  {
    var linesToHighlight = this.opts.highlight || [];

    if (typeof(linesToHighlight.push) !== 'function')
      linesToHighlight = [linesToHighlight];

    return linesToHighlight.indexOf(lineNumber.toString()) !== -1;
  },

  /**
   * Generates HTML markup for a single line of code while determining alternating line style.
   * @param {Integer} lineNumber  Line number.
   * @param {String} code Line  HTML markup.
   * @return {String}       Returns HTML markup.
   */
  wrapLine: function(lineIndex, lineNumber, lineHtml)
  {
    var classes = [
      'line',
      'number' + lineNumber,
      'index' + lineIndex,
      'alt' + (lineNumber % 2 == 0 ? 1 : 2).toString()
    ];

    if (this.isLineHighlighted(lineNumber))
      classes.push('highlighted');

    if (lineNumber == 0)
      classes.push('break');

    return '
' + lineHtml + '
';
  },

  /**
   * Generates HTML markup for line number column.
   * @param {String} code     Complete code HTML markup.
   * @param {Array} lineNumbers Calculated line numbers.
   * @return {String}       Returns HTML markup.
   */
  renderLineNumbers: function(code, lineNumbers)
  {
    var _this = this,
        opts = _this.opts,
        html = '',
        count = utils.splitLines(code).length,
        firstLine = parseInt(opts.firstLine),
        pad = opts.padLineNumbers,
        lineNumber,
        i
        ;

    if (pad == true)
      pad = (firstLine + count - 1).toString().length;
    else if (isNaN(pad) == true)
      pad = 0;

    for (i = 0; i < count; i++)
    {
      lineNumber = lineNumbers ? lineNumbers[i] : firstLine + i;
      code = lineNumber == 0 ? opts.space : padNumber(lineNumber, pad);
      html += _this.wrapLine(i, lineNumber, code);
    }

    return html;
  },

  /**
   * Splits block of text into individual DIV lines.
   * @param {String} code     Code to highlight.
   * @param {Array} lineNumbers Calculated line numbers.
   * @return {String}       Returns highlighted code in HTML form.
   */
  getCodeLinesHtml: function(html, lineNumbers)
  {
    // html = utils.trim(html);

    var _this = this,
        opts = _this.opts,
        lines = utils.splitLines(html),
        padLength = opts.padLineNumbers,
        firstLine = parseInt(opts.firstLine),
        brushName = opts.brush,
        html = ''
        ;

    for (var i = 0, l = lines.length; i < l; i++)
    {
      var line = lines[i],
          indent = /^( |\s)+/.exec(line),
          spaces = null,
          lineNumber = lineNumbers ? lineNumbers[i] : firstLine + i;
          ;

      if (indent != null)
      {
        spaces = indent[0].toString();
        line = line.substr(spaces.length);
        spaces = spaces.replace(' ', opts.space);
      }

      line = utils.trim(line);

      if (line.length == 0)
        line = opts.space;

      html += _this.wrapLine(
        i,
        lineNumber,
        (spaces != null ? '' + spaces + '' : '') + line
      );
    }

    return html;
  },

  /**
   * Returns HTML for the table title or empty string if title is null.
   */
  getTitleHtml: function(title)
  {
    return title ? '
' + title + '
' : '';
  },

  /**
   * Finds all matches in the source code.
   * @param {String} code   Source code to process matches in.
   * @param {Array} matches Discovered regex matches.
   * @return {String} Returns formatted HTML with processed mathes.
   */
  getMatchesHtml: function(code, matches)
  {
    function getBrushNameCss(match)
    {
      var result = match ? (match.brushName || brushName) : brushName;
      return result ? result + ' ' : '';
    };

    var _this = this,
        pos = 0,
        result = '',
        brushName = _this.opts.brush || '',
        match,
        matchBrushName,
        i,
        l
        ;

    // Finally, go through the final list of matches and pull the all
    // together adding everything in between that isn't a match.
    for (i = 0, l = matches.length; i < l; i++)
    {
      match = matches[i];

      if (match === null || match.length === 0)
        continue;

      matchBrushName = getBrushNameCss(match);

      result += _this.wrapLinesWithCode(code.substr(pos, match.index - pos), matchBrushName + 'plain')
          + _this.wrapLinesWithCode(match.value, matchBrushName + match.css)
          ;

      pos = match.index + match.length + (match.offset || 0);
    }

    // don't forget to add whatever's remaining in the string
    result += _this.wrapLinesWithCode(code.substr(pos), getBrushNameCss() + 'plain');

    return result;
  },

  /**
   * Generates HTML markup for the whole syntax highlighter.
   * @param {String} code Source code.
   * @return {String} Returns HTML markup.
   */
  getHtml: function()
  {
    var _this = this,
        opts = _this.opts,
        code = _this.code,
        matches = _this.matches,
        classes = ['syntaxhighlighter'],
        lineNumbers,
        html
        ;

    if (opts.collapse === true)
      classes.push('collapsed');

    if ((gutter = opts.gutter) === false)
      classes.push('nogutter');

    // add custom user style name
    classes.push(opts.className);

    // add brush alias to the class name for custom CSS
    classes.push(opts.brush);

    if (gutter)
      lineNumbers = _this.figureOutLineNumbers(code);

    // processes found matches into the html
    html = _this.getMatchesHtml(code, matches);

    // finally, split all lines so that they wrap well
    html = _this.getCodeLinesHtml(html, lineNumbers);

    // finally, process the links
    if (opts.autoLinks)
      html = _this.processUrls(html);

    if (typeof(navigator) != 'undefined' && navigator.userAgent && navigator.userAgent.match(/MSIE/))
      classes.push('ie');

    html =
      '
'
        // + (opts.toolbar ? sh.toolbar.getHtml(_this) : '')
        + '
'
          + _this.getTitleHtml(opts.title)
          + '
'
            + '
'
              + (gutter ? '' + _this.renderLineNumbers(code) + '	' : '')
              + ''
                + '
'
                  + html
                + '
'
              + '	'
            + '
'
          + '
'
        + '
'
      + '
'
      ;

    return html;
  },

  render: function()
  {
    return this.getHtml();
  }
};

module.exports = {
  Renderer: Renderer
};
<|endoftext|>


<commit_before>'use strict';

const MongoClient = require('./mongo-client'),
  Observable = require('rx').Observable;

const CARD_COLLECTION = 'cards';

module.exports = {
  bulkFind: cardNames => {
    return MongoClient.connect().flatMap(bulkFind(cardNames));
  },
  get: (cardName, set) => {
    return MongoClient.connect().flatMap(find(cardName, set));
  }
};

function find(cardName, set) {
  return db => {
    let criteria = { name: cardName };
    if (set) {
      criteria['printings'] = { $elemMatch: { $eq: set } }
    }
    let query = db.collection(CARD_COLLECTION).find(criteria);
    return Observable.fromNodeCallback(query.next, query)();
  };
}

function bulkFind(cardNames) {
  return db => {
    let criteria = { name: { $in: cardNames } };
    let query = db.collection(CARD_COLLECTION).find(criteria);
    return Observable.fromNodeCallback(query.toArray, query)();
  };
}
<commit_msg>Omit mongo stuff from endpoint data<commit_after>'use strict';

const MongoClient = require('./mongo-client'),
  Observable = require('rx').Observable;

const CARD_COLLECTION = 'cards';

module.exports = {
  bulkFind: cardNames => {
    return MongoClient.connect().flatMap(bulkFind(cardNames));
  },
  get: (cardName, set) => {
    return MongoClient.connect().flatMap(find(cardName, set));
  }
};

function find(cardName, set) {
  return db => {
    let fields = { _id: 0 };
    let criteria = { name: cardName };
    if (set) {
      criteria['printings'] = { $elemMatch: { $eq: set } }
    }
    let query = db.collection(CARD_COLLECTION).find(criteria, fields);
    return Observable.fromNodeCallback(query.next, query)();
  };
}

function bulkFind(cardNames) {
  return db => {
    let criteria = { name: { $in: cardNames } };
    let query = db.collection(CARD_COLLECTION).find(criteria);
    return Observable.fromNodeCallback(query.toArray, query)();
  };
}
<|endoftext|>


<commit_before>let Loader             = require('taskcluster-lib-loader');
let Docs               = require('taskcluster-lib-docs');
let Validate           = require('taskcluster-lib-validate');
let Monitor            = require('taskcluster-lib-monitor');
let App                = require('taskcluster-lib-app');
let Config             = require('typed-env-config');
let data               = require('./data');
let containers         = require('./containers');
let v1                 = require('./v1');
let path               = require('path');
let debug              = require('debug')('server');
let Promise            = require('promise');
let AWS                = require('aws-sdk');
let exchanges          = require('./exchanges');
let ScopeResolver      = require('./scoperesolver');
let signaturevalidator = require('./signaturevalidator');
let taskcluster        = require('taskcluster-client');
let url                = require('url');
let SentryManager      = require('./sentrymanager');
let Statsum            = require('statsum');
let _                  = require('lodash');

// Create component loader
let load = Loader({
  cfg: {
    requires: ['profile'],
    setup: ({profile}) => Config({profile}),
  },

  sentryManager: {
    requires: ['cfg'],
    setup: ({cfg}) => new SentryManager(cfg.app.sentry),
  },

  monitor: {
    requires: ['cfg', 'sentryManager', 'profile', 'process'],
    setup: ({cfg, sentryManager, profile, process}) => {
      return Monitor({
        project: 'taskcluster-auth',
        process,
        mock: profile === 'test',
        aws: {credentials: _.pick(cfg.aws, ['accessKeyId', 'secretAccessKey']), region: cfg.aws.region},
        logName: cfg.app.auditLog, // Audit logs will be noop if this is null
        statsumToken: async (project) => {
          return {
            project,
            token:    Statsum.createToken(project, cfg.app.statsum.secret, '25h'),
            baseUrl:  cfg.app.statsum.baseUrl,
            expires:  taskcluster.fromNowJSON('24 hours'),
          };

        },
        sentryDSN: async (project) => {
          let key = await this.sentryManager.projectDSN(project);
          return {
            project,
            dsn: _.pick(key.dsn, ['secret', 'public']),
            expires: key.expires.toJSON(),
          };
        },
      });
    },
  },

  resolver: {
    requires: ['cfg'],
    setup: ({cfg}) => new ScopeResolver({
      maxLastUsedDelay: cfg.app.maxLastUsedDelay,
    }),
  },

  Client: {
    requires: ['cfg', 'monitor'],
    setup: ({cfg, monitor}) =>
      data.Client.setup({
        table:        cfg.app.clientTableName,
        credentials:  cfg.azure || {},
        signingKey:   cfg.app.tableSigningKey,
        cryptoKey:    cfg.app.tableCryptoKey,
        monitor:      monitor.prefix('table.clients'),
      }),
  },

  Role: {
    requires: ['cfg', 'monitor'],
    setup: ({cfg, monitor}) =>
      data.Role.setup({
        table:        cfg.app.rolesTableName,
        credentials:  cfg.azure || {},
        signingKey:   cfg.app.tableSigningKey,
        monitor:      monitor.prefix('table.roles'),
      }),
  },

  Roles: {
    requires: ['cfg'],
    setup: async ({cfg}) => {
      let Roles = new containers.Roles({
        credentials:  cfg.azure || {},
        containerName: cfg.app.rolesContainerName,
      });
      await Roles.setup();
      return Roles;
    },
  },

  validator: {
    requires: ['cfg'],
    setup: ({cfg}) => Validate({
      prefix:  'auth/v1/',
      aws:      cfg.aws,
      bucket:   cfg.app.buckets.schemas,
    }),
  },

  docs: {
    requires: ['cfg', 'validator'],
    setup: ({cfg, validator}) => Docs.documenter({
      aws: cfg.aws,
      tier: 'platform',
      schemas: validator.schemas,
      bucket: cfg.app.buckets.docs,
      references: [
        {
          name: 'api',
          reference: v1.reference({baseUrl: cfg.server.publicUrl + '/v1'}),
        }, {
          name: 'events',
          reference: exchanges.reference({
            exchangePrefix:   cfg.app.exchangePrefix,
            credentials:      cfg.pulse,
          }),
        },
      ],
    }),
  },

  publisher: {
    requires: ['cfg', 'validator', 'monitor'],
    setup: ({cfg, validator, monitor}) =>
      exchanges.setup({
        credentials:      cfg.pulse,
        exchangePrefix:   cfg.app.exchangePrefix,
        validator:        validator,
        referencePrefix:  'auth/v1/exchanges.json',
        publish:          cfg.app.publishMetaData,
        aws:              cfg.aws,
        referenceBucket:  cfg.app.buckets.references,
        monitor:          monitor.prefix('publisher'),
      }),
  },

  api: {
    requires: [
      'cfg', 'Client', 'Roles', 'validator', 'publisher', 'resolver',
      'sentryManager', 'monitor',
    ],
    setup: async ({
      cfg, Client, Roles, validator, publisher, resolver, sentryManager, monitor,
    }) => {
      // Set up the Azure tables
      await Client.ensureTable();

      // set up the root access token if necessary
      if (cfg.app.rootAccessToken) {
        await Client.ensureRootClient(cfg.app.rootAccessToken);
      }

      // Load everything for resolver
      await resolver.setup({
        Client, Roles,
        exchangeReference: exchanges.reference({
          credentials:      cfg.pulse,
          exchangePrefix:   cfg.app.exchangePrefix,
        }),
        connection: new taskcluster.PulseConnection(cfg.pulse),
      });

      let signatureValidator = signaturevalidator.createSignatureValidator({
        expandScopes: (scopes) => resolver.resolve(scopes),
        clientLoader: (clientId) => resolver.loadClient(clientId),
        monitor,
      });

      return v1.setup({
        context: {
          Client, Roles,
          publisher,
          resolver,
          sts:                new AWS.STS(cfg.aws),
          azureAccounts:      cfg.app.azureAccounts,
          signatureValidator,
          sentryManager,
          statsum:            cfg.app.statsum,
          webhooktunnel:      cfg.app.webhooktunnel,
          monitor,
        },
        validator,
        signatureValidator,
        publish:            cfg.app.publishMetaData,
        baseUrl:            cfg.server.publicUrl + '/v1',
        referencePrefix:    'auth/v1/api.json',
        aws:                cfg.aws,
        referenceBucket:    cfg.app.buckets.references,
        monitor:            monitor.prefix('api'),
      });
    },
  },

  server: {
    requires: ['cfg', 'api', 'docs'],
    setup: async ({cfg, api, docs}) => {
      // Create app
      let serverApp = App(cfg.server);

      serverApp.use('/v1', api);

      serverApp.get('/', (req, res) => {
        res.redirect(302, url.format({
          protocol:       'https',
          host:           'login.taskcluster.net',
          query: {
            target:       req.query.target,
            description:  req.query.description,
          },
        }));
      });

      // Create server
      return serverApp.createServer();
    },
  },

  'expire-sentry': {
    requires: ['cfg', 'sentryManager'],
    setup: async ({cfg, sentryManager}) => {
      let now = taskcluster.fromNow(cfg.app.sentryExpirationDelay);
      if (isNaN(now)) {
        console.log('FATAL: sentryExpirationDelay is not valid!');
        process.exit(1);
      }
      await sentryManager.purgeExpiredKeys(now);
    },
  },

  'purge-expired-clients': {
    requires: ['cfg', 'Client'],
    setup: async ({cfg, Client}) => {
      now = taskcluster.fromNow(cfg.app.clientExpirationDelay);
      if (isNaN(now)) {
        console.log('FATAL: clientExpirationDelay is not valid!');
        process.exit(1);
      }
      await Client.purgeExpired(now);
    },
  },

  rolesToBlob: {
    requires: ['cfg', 'Role', 'Roles'],
    setup: async ({cfg, Role, Roles}) => {
      let blob = [];
      await Role.scan({}, {
        handler: r => {
          console.log(`read ${r.roleId}`);
          blob.push({
            roleId: r.roleId,
            scopes: r.scopes,
            description: r.description,
            lastModified: r.details.lastModified,
            created: r.details.created,
          });
        },
      });

      console.log('writing to blob');
      await Roles.modify(roles => {
        // clear and replace
        roles.splice(0);
        blob.forEach(r => roles.push(r));
      });
      console.log('wrote blob');
    },
  },

  dumpBlob: {
    requires: ['cfg', 'Roles'],
    setup: async ({cfg, Roles}) => {
      let roles = await Roles.get();
      console.log(JSON.stringify(roles, null, 2));
    },
  },
}, ['profile', 'process']);

// If this file is executed launch component from first argument
if (!module.parent) {
  load(process.argv[2], {
    process: process.argv[2],
    profile: process.env.NODE_ENV,
  }).catch(err => {
    console.log(err.stack);
    process.exit(1);
  });
}

// Export load for tests
module.exports = load;
<commit_msg>remove unnecessary and incorrect `this`<commit_after>let Loader             = require('taskcluster-lib-loader');
let Docs               = require('taskcluster-lib-docs');
let Validate           = require('taskcluster-lib-validate');
let Monitor            = require('taskcluster-lib-monitor');
let App                = require('taskcluster-lib-app');
let Config             = require('typed-env-config');
let data               = require('./data');
let containers         = require('./containers');
let v1                 = require('./v1');
let path               = require('path');
let debug              = require('debug')('server');
let Promise            = require('promise');
let AWS                = require('aws-sdk');
let exchanges          = require('./exchanges');
let ScopeResolver      = require('./scoperesolver');
let signaturevalidator = require('./signaturevalidator');
let taskcluster        = require('taskcluster-client');
let url                = require('url');
let SentryManager      = require('./sentrymanager');
let Statsum            = require('statsum');
let _                  = require('lodash');

// Create component loader
let load = Loader({
  cfg: {
    requires: ['profile'],
    setup: ({profile}) => Config({profile}),
  },

  sentryManager: {
    requires: ['cfg'],
    setup: ({cfg}) => new SentryManager(cfg.app.sentry),
  },

  monitor: {
    requires: ['cfg', 'sentryManager', 'profile', 'process'],
    setup: ({cfg, sentryManager, profile, process}) => {
      return Monitor({
        project: 'taskcluster-auth',
        process,
        mock: profile === 'test',
        aws: {credentials: _.pick(cfg.aws, ['accessKeyId', 'secretAccessKey']), region: cfg.aws.region},
        logName: cfg.app.auditLog, // Audit logs will be noop if this is null
        statsumToken: async (project) => {
          return {
            project,
            token:    Statsum.createToken(project, cfg.app.statsum.secret, '25h'),
            baseUrl:  cfg.app.statsum.baseUrl,
            expires:  taskcluster.fromNowJSON('24 hours'),
          };

        },
        sentryDSN: async (project) => {
          let key = await sentryManager.projectDSN(project);
          return {
            project,
            dsn: _.pick(key.dsn, ['secret', 'public']),
            expires: key.expires.toJSON(),
          };
        },
      });
    },
  },

  resolver: {
    requires: ['cfg'],
    setup: ({cfg}) => new ScopeResolver({
      maxLastUsedDelay: cfg.app.maxLastUsedDelay,
    }),
  },

  Client: {
    requires: ['cfg', 'monitor'],
    setup: ({cfg, monitor}) =>
      data.Client.setup({
        table:        cfg.app.clientTableName,
        credentials:  cfg.azure || {},
        signingKey:   cfg.app.tableSigningKey,
        cryptoKey:    cfg.app.tableCryptoKey,
        monitor:      monitor.prefix('table.clients'),
      }),
  },

  Role: {
    requires: ['cfg', 'monitor'],
    setup: ({cfg, monitor}) =>
      data.Role.setup({
        table:        cfg.app.rolesTableName,
        credentials:  cfg.azure || {},
        signingKey:   cfg.app.tableSigningKey,
        monitor:      monitor.prefix('table.roles'),
      }),
  },

  Roles: {
    requires: ['cfg'],
    setup: async ({cfg}) => {
      let Roles = new containers.Roles({
        credentials:  cfg.azure || {},
        containerName: cfg.app.rolesContainerName,
      });
      await Roles.setup();
      return Roles;
    },
  },

  validator: {
    requires: ['cfg'],
    setup: ({cfg}) => Validate({
      prefix:  'auth/v1/',
      aws:      cfg.aws,
      bucket:   cfg.app.buckets.schemas,
    }),
  },

  docs: {
    requires: ['cfg', 'validator'],
    setup: ({cfg, validator}) => Docs.documenter({
      aws: cfg.aws,
      tier: 'platform',
      schemas: validator.schemas,
      bucket: cfg.app.buckets.docs,
      references: [
        {
          name: 'api',
          reference: v1.reference({baseUrl: cfg.server.publicUrl + '/v1'}),
        }, {
          name: 'events',
          reference: exchanges.reference({
            exchangePrefix:   cfg.app.exchangePrefix,
            credentials:      cfg.pulse,
          }),
        },
      ],
    }),
  },

  publisher: {
    requires: ['cfg', 'validator', 'monitor'],
    setup: ({cfg, validator, monitor}) =>
      exchanges.setup({
        credentials:      cfg.pulse,
        exchangePrefix:   cfg.app.exchangePrefix,
        validator:        validator,
        referencePrefix:  'auth/v1/exchanges.json',
        publish:          cfg.app.publishMetaData,
        aws:              cfg.aws,
        referenceBucket:  cfg.app.buckets.references,
        monitor:          monitor.prefix('publisher'),
      }),
  },

  api: {
    requires: [
      'cfg', 'Client', 'Roles', 'validator', 'publisher', 'resolver',
      'sentryManager', 'monitor',
    ],
    setup: async ({
      cfg, Client, Roles, validator, publisher, resolver, sentryManager, monitor,
    }) => {
      // Set up the Azure tables
      await Client.ensureTable();

      // set up the root access token if necessary
      if (cfg.app.rootAccessToken) {
        await Client.ensureRootClient(cfg.app.rootAccessToken);
      }

      // Load everything for resolver
      await resolver.setup({
        Client, Roles,
        exchangeReference: exchanges.reference({
          credentials:      cfg.pulse,
          exchangePrefix:   cfg.app.exchangePrefix,
        }),
        connection: new taskcluster.PulseConnection(cfg.pulse),
      });

      let signatureValidator = signaturevalidator.createSignatureValidator({
        expandScopes: (scopes) => resolver.resolve(scopes),
        clientLoader: (clientId) => resolver.loadClient(clientId),
        monitor,
      });

      return v1.setup({
        context: {
          Client, Roles,
          publisher,
          resolver,
          sts:                new AWS.STS(cfg.aws),
          azureAccounts:      cfg.app.azureAccounts,
          signatureValidator,
          sentryManager,
          statsum:            cfg.app.statsum,
          webhooktunnel:      cfg.app.webhooktunnel,
          monitor,
        },
        validator,
        signatureValidator,
        publish:            cfg.app.publishMetaData,
        baseUrl:            cfg.server.publicUrl + '/v1',
        referencePrefix:    'auth/v1/api.json',
        aws:                cfg.aws,
        referenceBucket:    cfg.app.buckets.references,
        monitor:            monitor.prefix('api'),
      });
    },
  },

  server: {
    requires: ['cfg', 'api', 'docs'],
    setup: async ({cfg, api, docs}) => {
      // Create app
      let serverApp = App(cfg.server);

      serverApp.use('/v1', api);

      serverApp.get('/', (req, res) => {
        res.redirect(302, url.format({
          protocol:       'https',
          host:           'login.taskcluster.net',
          query: {
            target:       req.query.target,
            description:  req.query.description,
          },
        }));
      });

      // Create server
      return serverApp.createServer();
    },
  },

  'expire-sentry': {
    requires: ['cfg', 'sentryManager'],
    setup: async ({cfg, sentryManager}) => {
      let now = taskcluster.fromNow(cfg.app.sentryExpirationDelay);
      if (isNaN(now)) {
        console.log('FATAL: sentryExpirationDelay is not valid!');
        process.exit(1);
      }
      await sentryManager.purgeExpiredKeys(now);
    },
  },

  'purge-expired-clients': {
    requires: ['cfg', 'Client'],
    setup: async ({cfg, Client}) => {
      now = taskcluster.fromNow(cfg.app.clientExpirationDelay);
      if (isNaN(now)) {
        console.log('FATAL: clientExpirationDelay is not valid!');
        process.exit(1);
      }
      await Client.purgeExpired(now);
    },
  },

  rolesToBlob: {
    requires: ['cfg', 'Role', 'Roles'],
    setup: async ({cfg, Role, Roles}) => {
      let blob = [];
      await Role.scan({}, {
        handler: r => {
          console.log(`read ${r.roleId}`);
          blob.push({
            roleId: r.roleId,
            scopes: r.scopes,
            description: r.description,
            lastModified: r.details.lastModified,
            created: r.details.created,
          });
        },
      });

      console.log('writing to blob');
      await Roles.modify(roles => {
        // clear and replace
        roles.splice(0);
        blob.forEach(r => roles.push(r));
      });
      console.log('wrote blob');
    },
  },

  dumpBlob: {
    requires: ['cfg', 'Roles'],
    setup: async ({cfg, Roles}) => {
      let roles = await Roles.get();
      console.log(JSON.stringify(roles, null, 2));
    },
  },
}, ['profile', 'process']);

// If this file is executed launch component from first argument
if (!module.parent) {
  load(process.argv[2], {
    process: process.argv[2],
    profile: process.env.NODE_ENV,
  }).catch(err => {
    console.log(err.stack);
    process.exit(1);
  });
}

// Export load for tests
module.exports = load;
<|endoftext|>


<commit_before>define([
    'streamhub-gallery/horizontal-list-view',
    'text!streamhub-gallery/css/gallery-view.css',
    'hgn!streamhub-gallery/templates/gallery-view',
    'hgn!streamhub-gallery/css/theme.css',
    'streamhub-sdk/util'
], function (HorizontalListView, GalleryViewCss, GalleryViewTemplate, ThemeCssTemplate, util) {

    var STYLE_EL,
        GALLERY_THEME_STYLE_EL = $('');

    var GALLERY_CSS = {
        contentBefore: {
            transforms: {
                translateX: '-9999px',
                scale: 0.45
            }
        },
        contentAfter: {
            transforms: {
                translateX: '9999px',
                scale: 0.45
            }
        }
    };
    GALLERY_CSS.contentBefore1 = { opacity: 0.7 };
    GALLERY_CSS.contentBefore2 = { opacity: 0.3 };
    GALLERY_CSS.contentBefore3 = { opacity: 0.1 };
    GALLERY_CSS.contentAfter1 = { opacity: 0.7 };
    GALLERY_CSS.contentAfter2 = { opacity: 0.3 };
    GALLERY_CSS.contentAfter3 = { opacity: 0.1 };

    var GalleryView = function (opts) {
        opts = opts || {};
        opts.modal = opts.modal || true;
        opts.aspectRatio = opts.aspectRatio || 16/9;

        this._activeContentView = null;
        this._newContentCount = 0;
        HorizontalListView.call(this, opts);

        this._id = this.galleryListViewClassName + '-' + new Date().getTime();

        if (!STYLE_EL) {
            STYLE_EL = $('').text(GalleryViewCss).prependTo('head');
        }
    };
    util.inherits(GalleryView, HorizontalListView);

    GalleryView.prototype.template = GalleryViewTemplate;
    GalleryView.prototype.galleryListViewClassName = 'streamhub-gallery-view';

    GalleryView.prototype.setElement = function (el) {
        var galleryViewEl = $(this.template());
        this.el = galleryViewEl.filter('.'+this.galleryListViewClassName);
        HorizontalListView.prototype.setElement.call(this, this.el);
        galleryViewEl.appendTo(el);

        var self = this;
        this.$el.on('focusContent.hub', function (e) {
            var contentEl = $(e.target).hasClass('content') ? e.target : $(e.target).closest('article.content')[0];
            if ($(contentEl).parent().hasClass('content-before') || $(contentEl).parent().hasClass('content-after')) {
                e.stopImmediatePropagation();
            }
        });

        this.$el.on('click', '.content-before, .content-after', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var targetContentView;
            for (var i=0; i < self.contentViews.length; i++) {
                var contentEl = $(e.target).hasClass('content') ? e.target : $(e.target).closest('article.content')[0];
                if (self.contentViews[i].el === contentEl) {
                    targetContentView = self.contentViews[i];
                    break;
                }
            }
            self.jump(targetContentView);
        });

        $('.streamhub-gallery-view-prev > .streamhub-gallery-view-page-button').on('click', function (e) {
            e.preventDefault();
            self.prev();
        });

        $('.streamhub-gallery-view-next > .streamhub-gallery-view-page-button').on('click', function (e) {
            e.preventDefault();
            self.next();
        });

        $('.streamhub-gallery-view-notification').on('click', function (e) {
            e.preventDefault();
            // Jump to head when the notification is clicked
            self.jump(self.contentViews[0]);
            self._hideNewNotification();
        });

        this.$el.on('imageLoaded.hub', function (e) {
            self._adjustContentSize();
        });
    };

    GalleryView.prototype.add = function (content) {
        var contentView = HorizontalListView.prototype.add.call(this, content);
        // If there is new content and we're not focused at the head, show notification
        if (this.contentViews.indexOf(this._activeContentView) == 0) {
            return;
        }
        this._newContentCount++;
        this._showNewNotification();
        return contentView;
    };

    GalleryView.prototype._showNewNotification = function () {
        var notificationEl = $('.streamhub-gallery-view-notification');
        notificationEl.find('.streamhub-gallery-view-notification-count').html(this._newContentCount);
        notificationEl.fadeIn();
    };

    GalleryView.prototype._hideNewNotification = function () {
        var notificationEl = $('.streamhub-gallery-view-notification');
        this._newContentCount = 0;
        notificationEl.fadeOut();
    };

    GalleryView.prototype._insert = function (contentView) {
        var self = this,
            newContentViewIndex,
            $previousEl;

        newContentViewIndex = this.contentViews.indexOf(contentView);

        var $containerEl = $('

');
        contentView.$el.wrap($containerEl);
        var $wrappedEl = contentView.$el.parent();

        if (newContentViewIndex === 0) {
            // Beginning!
            $wrappedEl.prependTo(this.el);
        } else {
            // Find it's previous contentView and insert new contentView after
            $previousEl = this.contentViews[newContentViewIndex - 1].$el;
            $wrappedEl.insertAfter($previousEl.parent('.'+this.contentContainerClassName));
        }

        this.focus();
    };

    GalleryView.prototype.jump = function (contentView) {
        var contentViewIndex = this.contentViews.indexOf(contentView);
        if (contentViewIndex == 0) {
            newContentCount = 0;
        }
        this.$el.removeClass('animate');
        var originalActiveContentView = this._activeContentView;
        // Apply transforms exclusive of translations to calculate spacing
        var newTransforms = $.extend(true, {}, this.focus({
            translate: false,
            contentView: contentView
        }));
        // Revert to original state of spacing
        this.focus({
            contentView: originalActiveContentView
        });
        // Apply calculated transforms to original state
        var self = this;
        setTimeout(function () {
            self.$el.addClass('animate');
            self.focus({
                translate: newTransforms,
                contentView: contentView
            });
        },1);
    };

    GalleryView.prototype.next = function () {
        var activeIndex = this.contentViews.indexOf(this._activeContentView);
        var targetContentView = this.contentViews[Math.min(activeIndex+1, this.contentViews.length-1)];
        this.jump(targetContentView);
    };

    GalleryView.prototype.prev = function () {
        var activeIndex = this.contentViews.indexOf(this._activeContentView);
        var targetContentView = this.contentViews[activeIndex-1 || 0];
        this.jump(targetContentView);
    };

    GalleryView.prototype.focus = function (opts) {
        if (! this._activeContentView) {
            this._activeContentView = this.contentViews[0];
        }

        opts = opts || {};

        var contentContainerEls = this.$el.find('.content-container');
        contentContainerEls.removeClass('content-active')
            .removeClass('content-before-3')
            .removeClass('content-before-2')
            .removeClass('content-before-1')
            .removeClass('content-after-3')
            .removeClass('content-after-2')
            .removeClass('content-after-1')
            .removeClass('content-before')
            .removeClass('content-after')
            .removeAttr('style');

        this._activeContentView = opts.contentView ? opts.contentView : this._activeContentView;
        var activeIndex = this.contentViews.indexOf(this._activeContentView);

        var targetContentEl = this.contentViews[activeIndex].$el;
        var targetContainerEl = targetContentEl.parent();
        targetContainerEl.addClass('content-active');
        targetContainerEl.prevAll().addClass('content-before');
        targetContainerEl.nextAll().addClass('content-after');
        var before1 = targetContainerEl.prev().addClass('content-before-1');
        var before2 = before1.prev().addClass('content-before-2');
        var before3 = before2.prev().addClass('content-before-3');
        var after1 = targetContainerEl.next().addClass('content-after-1');
        var after2 = after1.next().addClass('content-after-2');
        var after3 = after2.next().addClass('content-after-3');

        return this._adjustContentSize(opts);
    };

    GalleryView.prototype._getContentSize = function () {
        var containerWidth = this.$el.width();
        var contentHeight = this.$el.height();
        var contentWidth = Math.min(contentHeight * this._aspectRatio, containerWidth);

        if (contentWidth/containerWidth <= 0.9) {
            contentHeight = contentHeight * 0.95;
            contentWidth = contentHeight * this._aspectRatio;
        } else if (contentWidth/containerWidth <= 0.95) {
            contentHeight = contentHeight * 0.8;
            contentWidth = contentHeight * this._aspectRatio;
        } else {
            contentHeight = contentHeight * 0.5;
            contentWidth = contentHeight * this._aspectRatio;
        }

        return { width: contentWidth, height: contentHeight };
    };

    GalleryView.prototype._adjustContentSize = function (opts) {
        var styleEl = $('style.'+this._id);
        if (styleEl) {
            styleEl.remove();
        }

        styleEl = $('');
        var styles = '';
        var contentSize = this._getContentSize();
        styles = '.'+this.horizontalListViewClassName + ' .'+this.contentContainerClassName + ' { width: ' + contentSize.width + 'px; height: ' + contentSize.height + 'px; margin-left: '+ contentSize.width/-2 + 'px; margin-top: '+ contentSize.height/-2+ 'px; }';
        styleEl.html(styles);
        $('head').append(styleEl);

        // Make content with tiled attachments square except when there's a
        // video attachment
        var contentWithImageEls = this.$el.find('.content-with-image');
        for (var i=0; i < contentWithImageEls.length; i++) {
            var contentEl = contentWithImageEls.eq(i).closest('.content-container');
            if (contentEl.find('.content-attachment-video').length) {
                contentEl.find('.content, .content-attachment').css({
                    'padding-bottom': 1/this._aspectRatio * 100 + '%',
                });
            } else {
                contentEl.css({
                    'width': contentSize.height + 'px',
                    'height': contentSize.height + 'px',
                    'margin-left': contentSize.height/-2 + 'px',
                    'margin-top': contentSize.height/-2 + 'px'
                });
            }
        }

        return this._adjustContentSpacing(opts);
    };

    GalleryView.prototype._adjustContentSpacing = function (opts) {
        return this._slideshowSpacing(opts);
    };

    GalleryView.prototype._slideshowSpacing = function (opts) {
        opts = opts || {};
        var visibleAdjacentContent = 3;

        if (opts.translate) {
            GALLERY_CSS = opts.translate;
            this._updateStyleEl(opts.translate);
            return;
        }

        var adjacentContentEls = this.$el.find('.content-before, .content-after, .content-active');
        if (!adjacentContentEls.length) {
            return;
        }

        var beforeTranslateX = 0;
        var afterTranslateX = 0;
        for (var i=0; i < visibleAdjacentContent; i++) {
            var adjacentIndex = i+1;

            // Before
            var contentBefore = adjacentContentEls.filter('.content-before-'+adjacentIndex);
            var contentBeforeWidth;
            if (contentBefore.length) {
                GALLERY_CSS['contentBefore'+adjacentIndex].transforms = $.extend({}, GALLERY_CSS.contentBefore.transforms);
                contentBeforeWidth = contentBefore[0].getBoundingClientRect().width;
                var previousEl = contentBefore.next();
                var previousWidth = previousEl[0].getBoundingClientRect().width;
                beforeTranslateX = beforeTranslateX - previousWidth - (contentBeforeWidth - previousWidth)/2;
                GALLERY_CSS['contentBefore'+adjacentIndex].transforms.translateX = beforeTranslateX+'px';
            }

            // After
            var contentAfter = adjacentContentEls.filter('.content-after-'+adjacentIndex);
            var contentAfterWidth;
            if (contentAfter.length) {
                GALLERY_CSS['contentAfter'+adjacentIndex].transforms = $.extend({}, GALLERY_CSS.contentAfter.transforms);
                contentAfterWidth = contentAfter[0].getBoundingClientRect().width;
                var previousEl = contentAfter.prev();
                var previousWidth = previousEl[0].getBoundingClientRect().width;
                afterTranslateX = afterTranslateX + previousWidth + (contentAfterWidth - previousWidth)/2
                GALLERY_CSS['contentAfter'+adjacentIndex].transforms.translateX = afterTranslateX+'px';
            }
        }

        this._updateStyleEl(opts.translate);

        return GALLERY_CSS;
    };

    GalleryView.prototype._updateStyleEl = function (translate) {
        translate = translate === undefined ? true : translate;
        for (var style in GALLERY_CSS) {
            var transform = '';
            for (var t in GALLERY_CSS[style].transforms) {
                if (translate || style == 'contentBefore' || style == 'contentAfter' || (!translate && t.indexOf('translate') == -1)) {
                    transform = transform + t + '(' + GALLERY_CSS[style].transforms[t]  + ') ';
                }
            }
            GALLERY_CSS[style].transform = transform;
        }
        var styleInnerHtml = ThemeCssTemplate(GALLERY_CSS);
        var matches = styleInnerHtml.match(new RegExp("(\A|\})\s*(?![^ ~>|]*\.*\{)", 'g'));
        for (var i=0; i < matches.length; i++) {
            var idx = styleInnerHtml.indexOf(matches[i]);
            styleInnerHtml = styleInnerHtml.slice(0, idx) +
                this._id + styleInnerHtml.slice(idx);
        }

        GALLERY_THEME_STYLE_EL.remove();
        GALLERY_THEME_STYLE_EL = $('').text(styleInnerHtml).appendTo('head');
    };

    return GalleryView;
});
<commit_msg>Rename #_adjustContentSpacing to #_relayout<commit_after>define([
    'streamhub-gallery/horizontal-list-view',
    'text!streamhub-gallery/css/gallery-view.css',
    'hgn!streamhub-gallery/templates/gallery-view',
    'hgn!streamhub-gallery/css/theme.css',
    'streamhub-sdk/util'
], function (HorizontalListView, GalleryViewCss, GalleryViewTemplate, ThemeCssTemplate, util) {

    var STYLE_EL,
        GALLERY_THEME_STYLE_EL = $('');

    var GALLERY_CSS = {
        contentBefore: {
            transforms: {
                translateX: '-9999px',
                scale: 0.45
            }
        },
        contentAfter: {
            transforms: {
                translateX: '9999px',
                scale: 0.45
            }
        }
    };
    GALLERY_CSS.contentBefore1 = { opacity: 0.7 };
    GALLERY_CSS.contentBefore2 = { opacity: 0.3 };
    GALLERY_CSS.contentBefore3 = { opacity: 0.1 };
    GALLERY_CSS.contentAfter1 = { opacity: 0.7 };
    GALLERY_CSS.contentAfter2 = { opacity: 0.3 };
    GALLERY_CSS.contentAfter3 = { opacity: 0.1 };

    var GalleryView = function (opts) {
        opts = opts || {};
        opts.modal = opts.modal || true;
        opts.aspectRatio = opts.aspectRatio || 16/9;

        this._activeContentView = null;
        this._newContentCount = 0;
        HorizontalListView.call(this, opts);

        this._id = this.galleryListViewClassName + '-' + new Date().getTime();

        if (!STYLE_EL) {
            STYLE_EL = $('').text(GalleryViewCss).prependTo('head');
        }
    };
    util.inherits(GalleryView, HorizontalListView);

    GalleryView.prototype.template = GalleryViewTemplate;
    GalleryView.prototype.galleryListViewClassName = 'streamhub-gallery-view';

    GalleryView.prototype.setElement = function (el) {
        var galleryViewEl = $(this.template());
        this.el = galleryViewEl.filter('.'+this.galleryListViewClassName);
        HorizontalListView.prototype.setElement.call(this, this.el);
        galleryViewEl.appendTo(el);

        var self = this;
        this.$el.on('focusContent.hub', function (e) {
            var contentEl = $(e.target).hasClass('content') ? e.target : $(e.target).closest('article.content')[0];
            if ($(contentEl).parent().hasClass('content-before') || $(contentEl).parent().hasClass('content-after')) {
                e.stopImmediatePropagation();
            }
        });

        this.$el.on('click', '.content-before, .content-after', function (e) {
            e.preventDefault();
            e.stopPropagation();

            var targetContentView;
            for (var i=0; i < self.contentViews.length; i++) {
                var contentEl = $(e.target).hasClass('content') ? e.target : $(e.target).closest('article.content')[0];
                if (self.contentViews[i].el === contentEl) {
                    targetContentView = self.contentViews[i];
                    break;
                }
            }
            self.jump(targetContentView);
        });

        $('.streamhub-gallery-view-prev > .streamhub-gallery-view-page-button').on('click', function (e) {
            e.preventDefault();
            self.prev();
        });

        $('.streamhub-gallery-view-next > .streamhub-gallery-view-page-button').on('click', function (e) {
            e.preventDefault();
            self.next();
        });

        $('.streamhub-gallery-view-notification').on('click', function (e) {
            e.preventDefault();
            // Jump to head when the notification is clicked
            self.jump(self.contentViews[0]);
            self._hideNewNotification();
        });

        this.$el.on('imageLoaded.hub', function (e) {
            self._adjustContentSize();
        });
    };

    GalleryView.prototype.add = function (content) {
        var contentView = HorizontalListView.prototype.add.call(this, content);
        // If there is new content and we're not focused at the head, show notification
        if (this.contentViews.indexOf(this._activeContentView) == 0) {
            return;
        }
        this._newContentCount++;
        this._showNewNotification();
        return contentView;
    };

    GalleryView.prototype._showNewNotification = function () {
        var notificationEl = $('.streamhub-gallery-view-notification');
        notificationEl.find('.streamhub-gallery-view-notification-count').html(this._newContentCount);
        notificationEl.fadeIn();
    };

    GalleryView.prototype._hideNewNotification = function () {
        var notificationEl = $('.streamhub-gallery-view-notification');
        this._newContentCount = 0;
        notificationEl.fadeOut();
    };

    GalleryView.prototype._insert = function (contentView) {
        var self = this,
            newContentViewIndex,
            $previousEl;

        newContentViewIndex = this.contentViews.indexOf(contentView);

        var $containerEl = $('

');
        contentView.$el.wrap($containerEl);
        var $wrappedEl = contentView.$el.parent();

        if (newContentViewIndex === 0) {
            // Beginning!
            $wrappedEl.prependTo(this.el);
        } else {
            // Find it's previous contentView and insert new contentView after
            $previousEl = this.contentViews[newContentViewIndex - 1].$el;
            $wrappedEl.insertAfter($previousEl.parent('.'+this.contentContainerClassName));
        }

        this.focus();
    };

    GalleryView.prototype.jump = function (contentView) {
        var contentViewIndex = this.contentViews.indexOf(contentView);
        if (contentViewIndex == 0) {
            newContentCount = 0;
        }
        this.$el.removeClass('animate');
        var originalActiveContentView = this._activeContentView;
        // Apply transforms exclusive of translations to calculate spacing
        var newTransforms = $.extend(true, {}, this.focus({
            translate: false,
            contentView: contentView
        }));
        // Revert to original state of spacing
        this.focus({
            contentView: originalActiveContentView
        });
        // Apply calculated transforms to original state
        var self = this;
        setTimeout(function () {
            self.$el.addClass('animate');
            self.focus({
                translate: newTransforms,
                contentView: contentView
            });
        },1);
    };

    GalleryView.prototype.next = function () {
        var activeIndex = this.contentViews.indexOf(this._activeContentView);
        var targetContentView = this.contentViews[Math.min(activeIndex+1, this.contentViews.length-1)];
        this.jump(targetContentView);
    };

    GalleryView.prototype.prev = function () {
        var activeIndex = this.contentViews.indexOf(this._activeContentView);
        var targetContentView = this.contentViews[activeIndex-1 || 0];
        this.jump(targetContentView);
    };

    GalleryView.prototype.focus = function (opts) {
        if (! this._activeContentView) {
            this._activeContentView = this.contentViews[0];
        }

        opts = opts || {};

        var contentContainerEls = this.$el.find('.content-container');
        contentContainerEls.removeClass('content-active')
            .removeClass('content-before-3')
            .removeClass('content-before-2')
            .removeClass('content-before-1')
            .removeClass('content-after-3')
            .removeClass('content-after-2')
            .removeClass('content-after-1')
            .removeClass('content-before')
            .removeClass('content-after')
            .removeAttr('style');

        this._activeContentView = opts.contentView ? opts.contentView : this._activeContentView;
        var activeIndex = this.contentViews.indexOf(this._activeContentView);

        var targetContentEl = this.contentViews[activeIndex].$el;
        var targetContainerEl = targetContentEl.parent();
        targetContainerEl.addClass('content-active');
        targetContainerEl.prevAll().addClass('content-before');
        targetContainerEl.nextAll().addClass('content-after');
        var before1 = targetContainerEl.prev().addClass('content-before-1');
        var before2 = before1.prev().addClass('content-before-2');
        var before3 = before2.prev().addClass('content-before-3');
        var after1 = targetContainerEl.next().addClass('content-after-1');
        var after2 = after1.next().addClass('content-after-2');
        var after3 = after2.next().addClass('content-after-3');

        return this._adjustContentSize(opts);
    };

    GalleryView.prototype._getContentSize = function () {
        var containerWidth = this.$el.width();
        var contentHeight = this.$el.height();
        var contentWidth = Math.min(contentHeight * this._aspectRatio, containerWidth);

        if (contentWidth/containerWidth <= 0.9) {
            contentHeight = contentHeight * 0.95;
            contentWidth = contentHeight * this._aspectRatio;
        } else if (contentWidth/containerWidth <= 0.95) {
            contentHeight = contentHeight * 0.8;
            contentWidth = contentHeight * this._aspectRatio;
        } else {
            contentHeight = contentHeight * 0.5;
            contentWidth = contentHeight * this._aspectRatio;
        }

        return { width: contentWidth, height: contentHeight };
    };

    GalleryView.prototype._adjustContentSize = function (opts) {
        var styleEl = $('style.'+this._id);
        if (styleEl) {
            styleEl.remove();
        }

        styleEl = $('');
        var styles = '';
        var contentSize = this._getContentSize();
        styles = '.'+this.horizontalListViewClassName + ' .'+this.contentContainerClassName + ' { width: ' + contentSize.width + 'px; height: ' + contentSize.height + 'px; margin-left: '+ contentSize.width/-2 + 'px; margin-top: '+ contentSize.height/-2+ 'px; }';
        styleEl.html(styles);
        $('head').append(styleEl);

        // Make content with tiled attachments square except when there's a
        // video attachment
        var contentWithImageEls = this.$el.find('.content-with-image');
        for (var i=0; i < contentWithImageEls.length; i++) {
            var contentEl = contentWithImageEls.eq(i).closest('.content-container');
            if (contentEl.find('.content-attachment-video').length) {
                contentEl.find('.content, .content-attachment').css({
                    'padding-bottom': 1/this._aspectRatio * 100 + '%',
                });
            } else {
                contentEl.css({
                    'width': contentSize.height + 'px',
                    'height': contentSize.height + 'px',
                    'margin-left': contentSize.height/-2 + 'px',
                    'margin-top': contentSize.height/-2 + 'px'
                });
            }
        }

        return this._relayout(opts);
    };

    GalleryView.prototype._relayout = function (opts) {
        return this._slideshowSpacing(opts);
    };

    GalleryView.prototype._slideshowSpacing = function (opts) {
        opts = opts || {};
        var visibleAdjacentContent = 3;

        if (opts.translate) {
            GALLERY_CSS = opts.translate;
            this._updateStyleEl(opts.translate);
            return;
        }

        var adjacentContentEls = this.$el.find('.content-before, .content-after, .content-active');
        if (!adjacentContentEls.length) {
            return;
        }

        var beforeTranslateX = 0;
        var afterTranslateX = 0;
        for (var i=0; i < visibleAdjacentContent; i++) {
            var adjacentIndex = i+1;

            // Before
            var contentBefore = adjacentContentEls.filter('.content-before-'+adjacentIndex);
            var contentBeforeWidth;
            if (contentBefore.length) {
                GALLERY_CSS['contentBefore'+adjacentIndex].transforms = $.extend({}, GALLERY_CSS.contentBefore.transforms);
                contentBeforeWidth = contentBefore[0].getBoundingClientRect().width;
                var previousEl = contentBefore.next();
                var previousWidth = previousEl[0].getBoundingClientRect().width;
                beforeTranslateX = beforeTranslateX - previousWidth - (contentBeforeWidth - previousWidth)/2;
                GALLERY_CSS['contentBefore'+adjacentIndex].transforms.translateX = beforeTranslateX+'px';
            }

            // After
            var contentAfter = adjacentContentEls.filter('.content-after-'+adjacentIndex);
            var contentAfterWidth;
            if (contentAfter.length) {
                GALLERY_CSS['contentAfter'+adjacentIndex].transforms = $.extend({}, GALLERY_CSS.contentAfter.transforms);
                contentAfterWidth = contentAfter[0].getBoundingClientRect().width;
                var previousEl = contentAfter.prev();
                var previousWidth = previousEl[0].getBoundingClientRect().width;
                afterTranslateX = afterTranslateX + previousWidth + (contentAfterWidth - previousWidth)/2
                GALLERY_CSS['contentAfter'+adjacentIndex].transforms.translateX = afterTranslateX+'px';
            }
        }

        this._updateStyleEl(opts.translate);

        return GALLERY_CSS;
    };

    GalleryView.prototype._updateStyleEl = function (translate) {
        translate = translate === undefined ? true : translate;
        for (var style in GALLERY_CSS) {
            var transform = '';
            for (var t in GALLERY_CSS[style].transforms) {
                if (translate || style == 'contentBefore' || style == 'contentAfter' || (!translate && t.indexOf('translate') == -1)) {
                    transform = transform + t + '(' + GALLERY_CSS[style].transforms[t]  + ') ';
                }
            }
            GALLERY_CSS[style].transform = transform;
        }
        var styleInnerHtml = ThemeCssTemplate(GALLERY_CSS);
        var matches = styleInnerHtml.match(new RegExp("(\A|\})\s*(?![^ ~>|]*\.*\{)", 'g'));
        for (var i=0; i < matches.length; i++) {
            var idx = styleInnerHtml.indexOf(matches[i]);
            styleInnerHtml = styleInnerHtml.slice(0, idx) +
                this._id + styleInnerHtml.slice(idx);
        }

        GALLERY_THEME_STYLE_EL.remove();
        GALLERY_THEME_STYLE_EL = $('').text(styleInnerHtml).appendTo('head');
    };

    return GalleryView;
});
<|endoftext|>


<commit_before>'use strict';

import { isFulfilled, isRejected, isSettled, isPending, isNever } from './inspect';
import { Future, resolve, reject, never, all, race, iterablePromise, taskQueue } from './Promise';

import _delay from './delay';
import _timeout from './timeout';

import Any from './Any';
import Merge from './Merge';
import Settle from './Settle';
import { resultsArray } from './iterable';

import _runPromise from './runPromise';
import _runNode from './node';
import _runCoroutine from './coroutine.js';

// -------------------------------------------------------------
// ## Core promise methods
// -------------------------------------------------------------

export {
    resolve, reject, never, all, race,
    isFulfilled, isRejected, isSettled, isPending, isNever
};

// -------------------------------------------------------------
// ## Coroutine
// -------------------------------------------------------------

// coroutine :: Generator e a -> (...args -> Promise e a)
// Make a coroutine from a promise-yielding generator
export function coroutine(generator) {
    return function (...args) {
        return runGenerator(generator, this, args);
    };
}

function runGenerator(generator, thisArg, args) {
    var iterator = generator.apply(thisArg, args);
    return _runCoroutine(resolve, iterator, new Future());
}

// -------------------------------------------------------------
// ## Node-style async
// -------------------------------------------------------------

// type NodeApi e a = ...args -> Nodeback e a -> ()
// type Nodeback e a = e -> a -> ()

// fromNode :: NodeApi e a -> (...args -> Promise e a)
// Turn a Node API into a promise-returning function
export function fromNode(f) {
    return function (...args) {
        return runNodeResolver(f, this, args, new Future());
    };
}

// fromNode :: NodeApi e a -> ...args -> Promise e a
// Run a Node API, returning a promise for the outcome
export function runNode(f, ...args) {
    return runNodeResolver(f, this, args, new Future());
}

function runNodeResolver(f, thisArg, args, p) {
    checkFunction(f);

    try {
        _runNode(f, thisArg, args, p);
    } catch (e) {
        p._reject(e);
    }
    return p;
}

// -------------------------------------------------------------
// ## Make a promise
// -------------------------------------------------------------

// type Resolve a = a -> ()
// type Reject e = e -> ()
// type Producer e a = (...args -> Resolve a -> Reject e -> ())
// runPromise :: Producer e a -> ...args -> Promise e a
export function runPromise(f, ...args) {
    return runResolver(f, this, args, new Future());
}

function runResolver(f, thisArg, args, p) {
    checkFunction(f);

    try {
        _runPromise(f, thisArg, args, p);
    } catch (e) {
        p._reject(e);
    }
    return p;
}

// -------------------------------------------------------------
// ## Time
// -------------------------------------------------------------

// delay :: number -> Promise e a -> Promise e a
export function delay(ms, x) {
    let p = resolve(x);
    return ms <= 0 || isRejected(p) || isNever(p) ? p : _delay(ms, p, new Future());
}

// timeout :: number -> Promise e a -> Promise (e|TimeoutError) a
export function timeout(ms, x) {
    var p = resolve(x);
    return isSettled(p) ? p : _timeout(ms, p, new Future());
}

// -------------------------------------------------------------
// ## Iterables
// -------------------------------------------------------------

// any :: Iterable (Promise e a) -> Promise e a
export function any(promises) {
    return iterablePromise(new Any(), promises);
}

// settle :: Iterable (Promise e a) -> Promise e [Promise e a]
export function settle(promises) {
    let handler = new Settle(resolve, resultsArray(promises));
    return iterablePromise(handler, promises);
}

// -------------------------------------------------------------
// ## Lifting
// -------------------------------------------------------------

// merge :: (...a -> b) -> ...Promise e a -> Promise e b
export function merge(f, ...args) {
    return runMerge(f, this, args);
}

function runMerge(f, thisArg, args) {
    let handler = new Merge(new MergeHandler(f, thisArg), resultsArray(args));
    return iterablePromise(handler, args);
}

class MergeHandler {
    constructor(f, c) {
        this.f = f;
        this.c = c;
        this.promise = void 0;
        this.args = void 0;
    }

    merge(promise, args) {
        this.promise = promise;
        this.args = args;
        taskQueue.add(this);
    }

    run() {
        try {
            this.promise._resolve(this.f.apply(this.c, this.args));
        } catch (e) {
            this.promise._reject(e);
        }
    }
}

function checkFunction(f) {
    if (typeof f !== 'function') {
        throw new TypeError('must provide a resolver function');
    }
}

// -------------------------------------------------------------
// ## ES6 Promise polyfill
// -------------------------------------------------------------

const NOARGS = [];

// type Resolve a = a -> ()
// type Reject e = e -> ()
// Promise :: (Resolve a -> Reject e) -> Promise e a
class CreedPromise extends Future {
    constructor(f) {
        super();
        runResolver(f, void 0, NOARGS, this);
    }
}

CreedPromise.resolve = resolve;
CreedPromise.reject = reject;
CreedPromise.all = all;
CreedPromise.race = race;

export function shim() {
    let orig = typeof Promise === 'function' && Promise;

    if (typeof self !== 'undefined') {
        self.Promise = CreedPromise;
    } else if (typeof global !== 'undefined') {
        global.Promise = CreedPromise;
    }

    return orig;
}

export { CreedPromise as Promise };

if (typeof Promise !== 'function') {
    shim();
}

<commit_msg>Use asterisk for variadic params<commit_after>'use strict';

import { isFulfilled, isRejected, isSettled, isPending, isNever } from './inspect';
import { Future, resolve, reject, never, all, race, iterablePromise, taskQueue } from './Promise';

import _delay from './delay';
import _timeout from './timeout';

import Any from './Any';
import Merge from './Merge';
import Settle from './Settle';
import { resultsArray } from './iterable';

import _runPromise from './runPromise';
import _runNode from './node';
import _runCoroutine from './coroutine.js';

// -------------------------------------------------------------
// ## Core promise methods
// -------------------------------------------------------------

export {
    resolve, reject, never, all, race,
    isFulfilled, isRejected, isSettled, isPending, isNever
};

// -------------------------------------------------------------
// ## Coroutine
// -------------------------------------------------------------

// coroutine :: Generator e a -> (...* -> Promise e a)
// Make a coroutine from a promise-yielding generator
export function coroutine(generator) {
    return function (...args) {
        return runGenerator(generator, this, args);
    };
}

function runGenerator(generator, thisArg, args) {
    var iterator = generator.apply(thisArg, args);
    return _runCoroutine(resolve, iterator, new Future());
}

// -------------------------------------------------------------
// ## Node-style async
// -------------------------------------------------------------

// type NodeApi e a = ...* -> Nodeback e a -> ()
// type Nodeback e a = e -> a -> ()

// fromNode :: NodeApi e a -> (...args -> Promise e a)
// Turn a Node API into a promise-returning function
export function fromNode(f) {
    return function (...args) {
        return runNodeResolver(f, this, args, new Future());
    };
}

// fromNode :: NodeApi e a -> ...* -> Promise e a
// Run a Node API, returning a promise for the outcome
export function runNode(f, ...args) {
    return runNodeResolver(f, this, args, new Future());
}

function runNodeResolver(f, thisArg, args, p) {
    checkFunction(f);

    try {
        _runNode(f, thisArg, args, p);
    } catch (e) {
        p._reject(e);
    }
    return p;
}

// -------------------------------------------------------------
// ## Make a promise
// -------------------------------------------------------------

// type Resolve a = a -> ()
// type Reject e = e -> ()
// type Producer e a = (...* -> Resolve a -> Reject e -> ())
// runPromise :: Producer e a -> ...* -> Promise e a
export function runPromise(f, ...args) {
    return runResolver(f, this, args, new Future());
}

function runResolver(f, thisArg, args, p) {
    checkFunction(f);

    try {
        _runPromise(f, thisArg, args, p);
    } catch (e) {
        p._reject(e);
    }
    return p;
}

// -------------------------------------------------------------
// ## Time
// -------------------------------------------------------------

// delay :: number -> Promise e a -> Promise e a
export function delay(ms, x) {
    let p = resolve(x);
    return ms <= 0 || isRejected(p) || isNever(p) ? p : _delay(ms, p, new Future());
}

// timeout :: number -> Promise e a -> Promise (e|TimeoutError) a
export function timeout(ms, x) {
    var p = resolve(x);
    return isSettled(p) ? p : _timeout(ms, p, new Future());
}

// -------------------------------------------------------------
// ## Iterables
// -------------------------------------------------------------

// any :: Iterable (Promise e a) -> Promise e a
export function any(promises) {
    return iterablePromise(new Any(), promises);
}

// settle :: Iterable (Promise e a) -> Promise e [Promise e a]
export function settle(promises) {
    let handler = new Settle(resolve, resultsArray(promises));
    return iterablePromise(handler, promises);
}

// -------------------------------------------------------------
// ## Lifting
// -------------------------------------------------------------

// merge :: (...* -> b) -> ...Promise e a -> Promise e b
export function merge(f, ...args) {
    return runMerge(f, this, args);
}

function runMerge(f, thisArg, args) {
    let handler = new Merge(new MergeHandler(f, thisArg), resultsArray(args));
    return iterablePromise(handler, args);
}

class MergeHandler {
    constructor(f, c) {
        this.f = f;
        this.c = c;
        this.promise = void 0;
        this.args = void 0;
    }

    merge(promise, args) {
        this.promise = promise;
        this.args = args;
        taskQueue.add(this);
    }

    run() {
        try {
            this.promise._resolve(this.f.apply(this.c, this.args));
        } catch (e) {
            this.promise._reject(e);
        }
    }
}

function checkFunction(f) {
    if (typeof f !== 'function') {
        throw new TypeError('must provide a resolver function');
    }
}

// -------------------------------------------------------------
// ## ES6 Promise polyfill
// -------------------------------------------------------------

const NOARGS = [];

// type Resolve a = a -> ()
// type Reject e = e -> ()
// Promise :: (Resolve a -> Reject e) -> Promise e a
class CreedPromise extends Future {
    constructor(f) {
        super();
        runResolver(f, void 0, NOARGS, this);
    }
}

CreedPromise.resolve = resolve;
CreedPromise.reject = reject;
CreedPromise.all = all;
CreedPromise.race = race;

export function shim() {
    let orig = typeof Promise === 'function' && Promise;

    if (typeof self !== 'undefined') {
        self.Promise = CreedPromise;
    } else if (typeof global !== 'undefined') {
        global.Promise = CreedPromise;
    }

    return orig;
}

export { CreedPromise as Promise };

if (typeof Promise !== 'function') {
    shim();
}

<|endoftext|>


<commit_before>/*
 * Main Loop
 *
 * the main loop of the ai
 *
 */

// prototypes
require('prototype.memory');
require('prototype.creep');
require('prototype.source');
require('prototype.mineral');
require('prototype.room');
require('prototype.structureContainer');
require('prototype.structureStorage');
require('prototype.roomPosition');

// global methods
global.C            = require('constants');
global.cli          = require('cli');

// load the queue systems
var Stats           = require('stats');
var Queue           = require('queue');
var Mil             = require('mil');
var Manage          = require('manage');

module.exports.loop = function () {
    Game.Stats          = new Stats;
    Game.Manage         = new Manage;
    Game.Queue          = new Queue;
    Game.Mil            = new Mil;

    Game.Queue.run();
    Game.Manage.run();
    Game.Stats.run();
}
<commit_msg>updated main<commit_after>/*
 * Main Loop
 *
 * the main loop of the ai
 *
 */

// prototypes
require('prototype.memory');
require('prototype.creep');
require('prototype.source');
require('prototype.mineral');
require('prototype.room');
require('prototype.structureContainer');
require('prototype.structureStorage');
require('prototype.roomPosition');

// global methods
global.C            = require('constants');
global.cli          = require('cli');

// load the queue systems
var Stats           = require('stats');
var Queue           = require('queue');
var Manage          = require('manage');
var Mil             = require('mil');
var Flags           = require('flags');

module.exports.loop = function () {
    Game.Stats          = new Stats;
    Game.Queue          = new Queue;
    Game.Manage         = new Manage;
    Game.Mil            = new Mil;
    Game.Flags          = new Flags;

    Game.Queue.run();
    Game.Manage.run();
    Game.Stats.run();
}
<|endoftext|>


<commit_before>var uuid = require('node-uuid');
var Promise = require('bluebird');

var route = function(db) {
  _getApplication = Promise.promisify(db.getApplication).bind(db);
  _updateApplication = Promise.promisify(db.updateApplication).bind(db);

  return function updateApplication(req, res) {
    var appId = req.param('id');
    var urlSlug = req.param('urlSlug');
    var contents = req.param('contents');

    if (!appId || !urlSlug || !contents) {
      res.status(400).send({ error: 'must provide appId, urlSlug, contents' });
      return;
    }

    var isNew = false;
    var params = {
      id: uuid.v4(),
      applicationId: appId,
      contents: contents,
      urlSlug: urlSlug,
      createdAt: new Date().getTime()
    };

    _getApplication(appId)
    .then(function(data) {
      // App is being created, createdAt is now
      if (!data) {
        isNew = true;
      // App already exists, keep the immutable properties
      } else {
        params.id = data.id;
        params.createdAt = data.createdAt;
      }

      return _updateApplication(appId, params)
      .then(function(data) {
        var statusCode = (isNew) ? 201 : 200;
        res.status(statusCode).send(params);
      });
    })
    .catch(function(err) {
      res.status(500).send({ error: err.toString() });
      console.error(err.stack);
    });
  };
}

module.exports = route;
<commit_msg>Removing content as a required parameter for an application<commit_after>var uuid = require('node-uuid');
var Promise = require('bluebird');

var route = function(db) {
  _getApplication = Promise.promisify(db.getApplication).bind(db);
  _updateApplication = Promise.promisify(db.updateApplication).bind(db);

  return function updateApplication(req, res) {
    var appId = req.param('id');
    var urlSlug = req.param('urlSlug');

    if (!appId || !urlSlug) {
      res.status(400).send({ error: 'must provide appId, urlSlug' });
      return;
    }

    var isNew = false;
    var params = {
      id: uuid.v4(),
      applicationId: appId,
      urlSlug: urlSlug,
      createdAt: new Date().getTime()
    };

    _getApplication(appId)
    .then(function(data) {
      // App is being created, createdAt is now
      if (!data) {
        isNew = true;
      // App already exists, keep the immutable properties
      } else {
        params.id = data.id;
        params.createdAt = data.createdAt;
      }

      return _updateApplication(appId, params)
      .then(function(data) {
        var statusCode = (isNew) ? 201 : 200;
        res.status(statusCode).send(params);
      });
    })
    .catch(function(err) {
      res.status(500).send({ error: err.toString() });
      console.error(err.stack);
    });
  };
}

module.exports = route;
<|endoftext|>


<commit_before>/**
 * @file Main for client
 * @author treelite(c.xinle@gmail.com)
 */

define(function (require) {

    var initialData;

    var DEFALUT_CORE = 'memory';

    /**
     * 存储能力检测
     *
     * @inner
     * @param {string} name 存储方式
     * @return {boolean}
     */
    function check(name) {
        try {
            var storage = window[name];
            var key = 'foo';
            var value = 'bar';

            storage.setItem(key, value);
            var support = value === storage.getItem(key);
            storage.removeItem(key);

            return support;
        }
        catch (e) {
            return false;
        }
    }

    /**
     * 存储内核
     *
     * @type {Object}
     */
    var cores = {
        memory: require('./memoryStorage'),
        local: check('localStorage') ? window.localStorage : null,
        session: check('sessionStorage') ? window.sessionStorage : null
    };

    /**
     * 获取存储对象
     *
     * @public
     * @param {string} type 存储类型
     * @return {Object}
     */
    function Storage(type) {
        type = type || DEFALUT_CORE;
        var core = cores[type];

        if (core) {
            var Storage = require('./Storage');
            return new Storage(location.hostname, core, initialData);
        }
        return core;
    }

    /**
     * 填充初始化数据
     *
     * @public
     * @param {Object} app server
     */
    Storage.fill = function (app) {
        initialData = app.getSyncData('session');
    };

    return Storage;

});
<commit_msg>Rename file -> sync<commit_after>/**
 * @file Main for client
 * @author treelite(c.xinle@gmail.com)
 */

define(function (require) {

    var initialData;

    var DEFALUT_CORE = 'memory';

    /**
     * 存储对象缓存
     *
     * @type {Array}
     */
    var storages = [];

    /**
     * 存储能力检测
     *
     * @inner
     * @param {string} name 存储方式
     * @return {boolean}
     */
    function check(name) {
        try {
            var storage = window[name];
            var key = 'foo';
            var value = 'bar';

            storage.setItem(key, value);
            var support = value === storage.getItem(key);
            storage.removeItem(key);

            return support;
        }
        catch (e) {
            return false;
        }
    }

    /**
     * 存储内核
     *
     * @type {Object}
     */
    var cores = {
        memory: require('./memoryStorage'),
        local: check('localStorage') ? window.localStorage : null,
        session: check('sessionStorage') ? window.sessionStorage : null
    };

    /**
     * 获取存储对象
     *
     * @public
     * @param {string} type 存储类型
     * @return {Object}
     */
    function Storage(type) {
        type = type || DEFALUT_CORE;
        var core = cores[type];

        if (core) {
            var Storage = require('./Storage');
            var storage = new Storage(location.hostname, core, initialData);
            storages.push(storage);
            return storage;
        }
        return core;
    }

    /**
     * 同步初始化数据
     *
     * @public
     * @param {Object} app server
     */
    Storage.sync = function (app) {
        var data = initialData = app.getSyncData('session');

        storages.forEach(function (storage) {
            Object.keys(data).forEach(function (key) {
                storage.setItem(key, data[key]);
            });
        });
    };

    return Storage;

});
<|endoftext|>


<commit_before>var exec = require( 'child_process' ).exec;
var path = require( 'path' );
var pretty = require( 'pretty-time' );
var nodeProcess = require( './process' );

module.exports = {
  _execute: function ( program, cmds ) {
    var cmdManager = require( '../index' ).create();

    var opts = program.opts;

    cmdManager.on( 'command:start', function ( e, args ) {
      program.subtle( 'starting command', args.cmd );
    } );

    cmdManager.on( 'command:error', function ( e, args ) {
      program.subtle( 'command error', args, 'duration: ', pretty( args.duration, 's' ) );
    } );

    cmdManager.on( 'command:exit', function ( e, args ) {
      program.subtle( 'command', args.cmd, 'exited with code', args.exitCode + ', took: ', pretty( args.duration ) );
      if ( opts.sortOutput ) {
        args.stdout && console.log( args.stdout );
        args.stderr && console.error( args.stderr );
      }
      if ( args.exitCode !== 0 && opts.bail ) {
        program.warn( 'command', args.cmd, 'failed. Stopping all' );
        cmdManager.stopAll();
        process.exit( 1 ); // eslint-disable-line
      }

    } );

    cmdManager.on( 'command:killed', function ( e, args ) {
      program.subtle( 'command killed:', args.cmd, 'pid:', args.pid );
    } );

    var d = require( 'domain' ).create();

    d.on( 'error', function () {
      cmdManager.stopAll();
    } );

    var p = cmdManager.runCmds( cmds, {
      stdio: opts.sortOutput ? 'pipe' : 'inherit'
    } );

    p.then( function ( args ) {
      var results = [ ];

      args.forEach( function ( result ) {
        if ( result.exitCode !== 0 ) {
          results.push( {
            cmd: result.cmd, exitCode: result.exitCode
          } );
        }
      } );

      if ( results.length > 0 ) {
        program.error( 'Some commands failed', results );
        process.exit( 1 ); // eslint-disable-line
      }
    } );

    var lines = [
      'Commands execution started',
      '',
      '    To kill commands from the shell In case I become a zombie, execute:',
      '',
      '    ' + cmdManager.getKillCommand(),
      '',
      ''
    ];

    program.subtle( lines.join( '\n' ) );

    nodeProcess.on( 'SIGINT', function ( code ) {
      program.subtle( 'killing all processes' );
      cmdManager.stopAll();
      nodeProcess.exit( code );
    } );
  },
  run: function ( program ) {

    var cmds = program.opts._;

    var addNPMBinToPath = function ( cb ) {
      exec( 'npm bin', function ( error, stdout, stderr ) {
        if ( error ) {
          program.error( 'received error', error );
          stderr && program.error( stderr );
          return;
        }

        process.env.PATH += '' + path.delimiter + stdout.trim();

        cb && cb();
      } );
    };

    if ( cmds.length === 0 ) {
      program.error( 'please provide some commands to execute' );
      program.showHelp();
      return;
    }
    var me = this;
    addNPMBinToPath( function () {
      me._execute( program, cmds );
    } );
  }
};
<commit_msg>FEAT: Add color to processes using stdin pipe instead of inherit stdio<commit_after>var exec = require( 'child_process' ).exec;
var path = require( 'path' );
var pretty = require( 'pretty-time' );
var nodeProcess = require( './process' );

module.exports = {
  _execute: function ( program, cmds ) {
    var cmdManager = require( '../index' ).create();

    var opts = program.opts;

    cmdManager.on( 'command:start', function ( e, args ) {
      program.subtle( 'starting command', args.cmd );
    } );

    cmdManager.on( 'command:error', function ( e, args ) {
      program.subtle( 'command error', args, 'duration: ', pretty( args.duration, 's' ) );
    } );

    cmdManager.on( 'command:exit', function ( e, args ) {
      program.subtle( 'command', args.cmd, 'exited with code', args.exitCode + ', took: ', pretty( args.duration ) );
      if ( opts.sortOutput ) {
        args.stdout && console.log( args.stdout );
        args.stderr && console.error( args.stderr );
      }
      if ( args.exitCode !== 0 && opts.bail ) {
        program.warn( 'command', args.cmd, 'failed. Stopping all' );
        cmdManager.stopAll();
        process.exit( 1 ); // eslint-disable-line
      }

    } );

    cmdManager.on( 'command:killed', function ( e, args ) {
      program.subtle( 'command killed:', args.cmd, 'pid:', args.pid );
    } );

    var d = require( 'domain' ).create();

    d.on( 'error', function () {
      cmdManager.stopAll();
    } );

    var p = cmdManager.runCmds( cmds, {
      stdio: opts.sortOutput ? 'pipe' : 'inherit'
    } );

    p.then( function ( args ) {
      var results = [ ];

      args.forEach( function ( result ) {
        if ( result.exitCode !== 0 ) {
          results.push( {
            cmd: result.cmd, exitCode: result.exitCode
          } );
        }
      } );

      if ( results.length > 0 ) {
        program.error( 'Some commands failed', results );
        process.exit( 1 ); // eslint-disable-line
      }
    } );

    var lines = [
      'Commands execution started',
      '',
      '    To kill commands from the shell In case I become a zombie, execute:',
      '',
      '    ' + cmdManager.getKillCommand(),
      '',
      ''
    ];

    program.subtle( lines.join( '\n' ) );

    nodeProcess.on( 'SIGINT', function ( code ) {
      program.subtle( 'killing all processes' );
      cmdManager.stopAll();
      nodeProcess.exit( code );
    } );
  },
  run: function ( program ) {

    var cmds = program.opts._;

    var addNPMBinToPath = function ( cb ) {
      exec( 'npm bin', function ( error, stdout, stderr ) {
        if ( error ) {
          program.error( 'received error', error );
          stderr && program.error( stderr );
          return;
        }

        if ( typeof process.env.FORCE_COLOR === 'undefined' ) {
          process.env.FORCE_COLOR = 'true';
        }

        process.env.PATH += '' + path.delimiter + stdout.trim();

        cb && cb();
      } );
    };

    if ( cmds.length === 0 ) {
      program.error( 'please provide some commands to execute' );
      program.showHelp();
      return;
    }
    var me = this;
    addNPMBinToPath( function () {
      me._execute( program, cmds );
    } );
  }
};
<|endoftext|>


<commit_before>import Vue from 'vue'
import Router from 'vue-router'
import {
  domain,
  fromNow,
  dataMatchFormatter,
  formatTimestamp
} from './filters'
import App from './components/App.vue'
import Home from './components/Home.vue'
import Task from './components/Task.vue'
import TaskIndex from './components/TaskIndex.vue'
import TaskNew from './components/TaskNew.vue'
import TaskShow from './components/TaskShow.vue'
import Log from './components/Log.vue'
import Monitor from './components/Monitor.vue'
import Alert from './components/Alert.vue'

// require external css
require('assets/css/pure-min.css')
require('assets/css/baby-blue.css')
require('assets/css/grids-responsive-min.css')

// require external js

// install router
Vue.use(Router)

// register filters globally
Vue.filter('fromNow', fromNow)
Vue.filter('domain', domain)
Vue.filter('dataMatchFormatter', dataMatchFormatter)
Vue.filter('formatTimestamp', formatTimestamp)

// routing
var router = new Router()

router.map({
  '/': {
    component: Home
  },
  '/task': {
    component: Task,
    subRoutes: {
      '/index': {
        component: TaskIndex
      },
      '/new': {
        component: TaskNew
      },
      '/:id': {
        component: TaskShow
      }
    }
  },
  '/log': {
    component: Log
  },
  '/monitor': {
    component: Monitor
  },
  '/alert': {
    component: Alert
  }
})

router.beforeEach(() => {
  window.scrollTo(0, 0)
})

router.redirect({
  '*': '/'
})

router.start(App, '#app')
<commit_msg>add TaskEdit to main.js<commit_after>import Vue from 'vue'
import Router from 'vue-router'
import {
  domain,
  fromNow,
  dataMatchFormatter,
  formatTimestamp
} from './filters'
import App from './components/App.vue'
import Home from './components/Home.vue'
import Task from './components/Task.vue'
import TaskIndex from './components/TaskIndex.vue'
import TaskNew from './components/TaskNew.vue'
import TaskShow from './components/TaskShow.vue'
import TaskEdit from './components/TaskEdit.vue'
import Log from './components/Log.vue'
import Monitor from './components/Monitor.vue'
import Alert from './components/Alert.vue'

// require external css
require('assets/css/pure-min.css')
require('assets/css/baby-blue.css')
require('assets/css/grids-responsive-min.css')

// require external js

// install router
Vue.use(Router)

// register filters globally
Vue.filter('fromNow', fromNow)
Vue.filter('domain', domain)
Vue.filter('dataMatchFormatter', dataMatchFormatter)
Vue.filter('formatTimestamp', formatTimestamp)

// routing
var router = new Router()

router.map({
  '/': {
    component: Home
  },
  '/task': {
    component: Task,
    subRoutes: {
      '/index': {
        component: TaskIndex
      },
      '/new': {
        component: TaskNew
      },
      '/:id': {
        component: TaskShow
      },
      '/:id/edit': {
        component: TaskEdit
      }
    }
  },
  '/log': {
    component: Log
  },
  '/monitor': {
    component: Monitor
  },
  '/alert': {
    component: Alert
  }
})

router.beforeEach(() => {
  window.scrollTo(0, 0)
})

router.redirect({
  '*': '/'
})

router.start(App, '#app')
<|endoftext|>