<commit_before>(function (global) {

  'use strict';

  var colors = require('colors'),
    DEFAULTS = {
      failedAsserts: true,
      failedSpec: true,
      failuresSummary: true,
      inColors: true,
      indent: '\t',
      namesInColors: false,
      passedSpec: true,
      pendingSpec: true,
      pendingSuite: true,
      specDuration: true,
      stacktrace: true,
      suiteDuration: false,
      summary: true,
      colors: {
        failed: 'red',
        passed: 'green',
        pending: 'yellow',
        suite: 'cyan',
        system: 'grey'
      },
      symbols: {
        failed: '✗  '.strikethrough,
        passed: '✓  '.strikethrough,
        pending: '~  '.strikethrough,
        suite: '» '.strikethrough
      }
    };

  function configOpts(opts) {
    opts = opts || {};

    opts.indent = 'indent' in opts ? opts.indent : DEFAULTS.indent;
    opts.failedAsserts = 'failedAsserts' in opts ?
      opts.failedAsserts : DEFAULTS.failedAsserts;
    opts.failedSpec = 'failedSpec' in opts ?
      opts.failedSpec : DEFAULTS.failedSpec;
    opts.failuresSummary = 'failuresSummary' in opts ?
      opts.failuresSummary : DEFAULTS.failuresSummary;
    opts.passedSpec = 'passedSpec' in opts ?
      opts.passedSpec : DEFAULTS.passedSpec;
    opts.pendingSpec = 'pendingSpec' in opts ?
      opts.pendingSpec : DEFAULTS.pendingSpec;
    opts.pendingSuite = 'pendingSuite' in opts ?
      opts.pendingSuite : DEFAULTS.pendingSuite;
    opts.specDuration = 'specDuration' in opts ?
      opts.specDuration : DEFAULTS.specDuration;
    opts.stacktrace = 'stacktrace' in opts ?
      opts.stacktrace : DEFAULTS.stacktrace;
    opts.suiteDuration = 'suiteDuration' in opts ?
      opts.suiteDuration : DEFAULTS.suiteDuration;
    opts.summary = 'summary' in opts ? opts.summary : DEFAULTS.summary;
    opts.inColors = 'inColors' in opts ? opts.inColors : DEFAULTS.inColors;
    opts.namesInColors = 'namesInColors' in opts ?
      opts.namesInColors : DEFAULTS.namesInColors;

    opts.symbols = {
      passed: opts.symbols && opts.symbols.passed !== undefined ?
        opts.symbols.passed.strikethrough : DEFAULTS.symbols.passed,
      failed: opts.symbols && opts.symbols.failed !== undefined ?
        opts.symbols.failed.strikethrough : DEFAULTS.symbols.failed,
      pending: opts.symbols && opts.symbols.pending !== undefined ?
        opts.symbols.pending.strikethrough : DEFAULTS.symbols.pending,
      suite: opts.symbols && opts.symbols.suite !== undefined ?
        opts.symbols.suite.strikethrough : DEFAULTS.symbols.suite
    };

    colors.setTheme({
      passed: opts.colors && opts.colors.passed ?
        opts.colors.passed : DEFAULTS.colors.passed,
      failed: opts.colors && opts.colors.failed ?
        opts.colors.failed : DEFAULTS.colors.failed,
      pending: opts.colors && opts.colors.pending ?
        opts.colors.pending : DEFAULTS.colors.pending,
      suite: opts.colors && opts.colors.suite ?
        opts.colors.suite : DEFAULTS.colors.suite,
      system: opts.colors && opts.colors.system ?
        opts.colors.system : DEFAULTS.colors.system
    });

    return opts;
  }

  var TerminalLogger = function (options) {
    this.options = configOpts(options);
    this.indentLevel = 0;
    this.lastNewLine = false;
    this.failedSpecs = [];
  };

  TerminalLogger.prototype = {
    start: function () {
      this.print('\n JASMINE STARTING: \n'.bold.inverse);
    },
    stop: function (errors, calc) {
      if (this.options.summary) this.summary(calc);
      if (this.options.failuresSummary &&
        (calc.failedSpecs > 0)) this.failuresSummary(calc);
    },
    failuresSummary: function () {
      this.resetIndent();
      this.newLine(true);
      this.print('**************************************************');
      this.print('*                   ' + ' Failures '.bold.inverse +
        '                   *');
      this.print('**************************************************');
      this.newLine();
      for (var i = 0; i < this.failedSpecs.length; i++) {
        this.failedSummary(this.failedSpecs[i], i + 1);
        this.newLine();
      }
    },
    failedSummary: function (spec, index) {
      this.print(index + ') ' + spec.fullName.bold);
      this.displayErrorMessages(spec, true);
    },
    displayErrorMessages: function (spec, isSummary) {
      this.increaseIndent();
      var assertions = spec.failedExpectations;
      for (var i = 0; i < assertions.length; i++) {
        if (!assertions[i].passed) {
          this.print('- '.failed + assertions[i].message.failed);
          if (this.options.stacktrace && isSummary) {
            this.print(this.filterStackTraces(assertions[i].stack)
              .failed);
          }
        }
      }
      this.decreaseIndent();
    },
    filterStackTraces: function (traces) {
      var lines = traces.split('\n');
      var filtered = [];
      for (var i = 1; i < lines.length; i++) {
        if (!/(jasmine[^\/]*\.js|Timer\.listOnTimeout)/.test(lines[i])) {
          filtered.push(lines[i]);
        }
      }
      return filtered.join('\n');
    },
    summary: function (calc) {
      var execution = 'Executed '.system + ('' + calc.executedSpecs)
        .strikethrough + ' out of '.system +
        ('' + calc.totalSpecs)
        .strikethrough +
        (calc.totalSpecs === 1 ? ' spec '.system : ' specs '.system) +
        'in '.system + calc.runTime.system,
        passed = 'PASSED   ' + calc.passedSpecs + ' (' +
        calc.formatProcentage(calc.passedSpecs, calc.totalSpecs) + ')',
        failed = 'FAILED   ' + calc.failedSpecs + ' (' +
        calc.formatProcentage(calc.failedSpecs, calc.totalSpecs) + ')',
        pending = 'SKIPPED  ' + calc.pendingSpecs + ' (' +
        calc.formatProcentage(calc.pendingSpecs, calc.totalSpecs) + ')';
      this.resetIndent();
      this.newLine(true);
      this.print('**************************************************');
      this.print('*                   ' + ' Summary '.bold.inverse +
        '                    *');
      this.print('**************************************************');
      this.newLine();
      this.print(execution.italic);
      this.newLine();
      this.increaseIndent();
      this.print(passed.passed);
      this.print(failed.failed);
      this.print(pending.pending);
      this.decreaseIndent();
      this.newLine();
    },
    startSuite: function (suite) {
      this.newLine();
      this.increaseIndent();
      this.print(this.options.symbols.suite.suite +
        this.getSuiteName(suite, 'suite'));
    },
    stopSuite: function (suite, calc) {
      if (calc.suites[suite.id].status === 'skip') {
        this.pendingSuite(suite, calc);
      } else if (this.options.suiteDuration) {
        this.suiteDetails(suite, calc);
      } else {
        this.decreaseIndent();
        this.newLine();
      }
      delete calc.suites[suite.id]; // prevent memory leak
    },
    pendingSuite: function (suite) {
      if (this.options.pendingSuite) {
        this.increaseIndent();
        this.print(this.options.symbols.pending.pending +
          this.getSuiteName(suite, 'pending'));
        this.decreaseIndent();
      }
    },
    suiteDetails: function (suite, calc) {
      this.print('  Finished '.system + this.getSuiteName(suite, 'suite') +
        ' in '.system + calc.suites[suite.id].duration.system);
      this.decreaseIndent();
      this.newLine();
    },
    startSpec: function () {
      this.increaseIndent();
    },
    stopSpec: function (spec, calc) {
      this[spec.status](spec, calc);
      this.decreaseIndent();
    },
    passed: function (spec, calc) {
      if (this.options.passedSpec) {
        var duration = this.options.specDuration ?
          ' (' + calc.specTime + ')' : '';
        this.print(this.options.symbols.passed.passed +
          this.getSpecName(spec, 'passed') + duration.system);
      }
    },
    failed: function (spec, calc) {
      this.failedSpecs.push(spec);
      if (this.options.failedSpec) {
        var duration = this.options.specDuration ?
          ' (' + calc.specTime + ')' : '';
        this.print(this.options.symbols.failed.failed +
          this.getSpecName(spec, 'failed') + duration.system);
        if (this.options.failedAsserts)
          this.displayErrorMessages(spec, false);
      }
    },
    pending: function (spec) {
      if (this.options.pendingSpec) {
        this.print(this.options.symbols.pending.pending +
          this.getSpecName(spec, 'pending'));
      }
    },
    getSuiteName: function (suite, color) {
      return this.options.namesInColors ?
        suite.description.bold[color] : suite.description.bold;
    },
    getSpecName: function (spec, color) {
      return this.options.namesInColors ?
        spec.description[color] : spec.description;
    },
    print: function (stuff) {
      if (!this.options.inColors) {
        stuff = ('' + stuff)
          .replace(/\x1B\[\d+m/g, '');
      }
      console.log(this.createIndent() + stuff);
      this.lastNewLine = false;
    },
    newLine: function (force) {
      if (!this.lastNewLine || force) {
        console.log('');
        this.lastNewLine = true;
      }
    },
    createIndent: function () {
      return (new Array(this.indentLevel)
          .join(this.options.indent))
        .toString();
    },
    increaseIndent: function () {
      this.indentLevel++;
    },
    decreaseIndent: function () {
      this.indentLevel--;
    },
    resetIndent: function () {
      this.indentLevel = 1;
    }
  };

  function expose() {
    if (typeof module !== 'undefined' && module.exports) {
      return exports;
    } else {
      global.reporterHelpers = global.reporterHelpers || {};
      return global.reporterHelpers;
    }
  }

  expose()
    .TerminalLogger = TerminalLogger;
})(this);
<commit_msg>Fix #5<commit_after>(function (global) {

  'use strict';

  var colors = require('colors'),
    DEFAULTS = {
      failedAsserts: true,
      failedSpec: true,
      failuresSummary: true,
      inColors: true,
      indent: '\t',
      namesInColors: false,
      passedSpec: true,
      pendingSpec: true,
      pendingSuite: true,
      specDuration: true,
      stacktrace: true,
      suiteDuration: false,
      summary: true,
      colors: {
        failed: 'red',
        passed: 'green',
        pending: 'yellow',
        suite: 'cyan',
        system: 'grey'
      },
      symbols: {
        failed: '✗  '.strikethrough,
        passed: '✓  '.strikethrough,
        pending: '~  '.strikethrough,
        suite: '» '.strikethrough
      }
    };

  function configOpts(opts) {
    opts = opts || {};

    opts.indent = 'indent' in opts ? opts.indent : DEFAULTS.indent;
    opts.failedAsserts = 'failedAsserts' in opts ?
      opts.failedAsserts : DEFAULTS.failedAsserts;
    opts.failedSpec = 'failedSpec' in opts ?
      opts.failedSpec : DEFAULTS.failedSpec;
    opts.failuresSummary = 'failuresSummary' in opts ?
      opts.failuresSummary : DEFAULTS.failuresSummary;
    opts.passedSpec = 'passedSpec' in opts ?
      opts.passedSpec : DEFAULTS.passedSpec;
    opts.pendingSpec = 'pendingSpec' in opts ?
      opts.pendingSpec : DEFAULTS.pendingSpec;
    opts.pendingSuite = 'pendingSuite' in opts ?
      opts.pendingSuite : DEFAULTS.pendingSuite;
    opts.specDuration = 'specDuration' in opts ?
      opts.specDuration : DEFAULTS.specDuration;
    opts.stacktrace = 'stacktrace' in opts ?
      opts.stacktrace : DEFAULTS.stacktrace;
    opts.suiteDuration = 'suiteDuration' in opts ?
      opts.suiteDuration : DEFAULTS.suiteDuration;
    opts.summary = 'summary' in opts ? opts.summary : DEFAULTS.summary;
    opts.inColors = 'inColors' in opts ? opts.inColors : DEFAULTS.inColors;
    opts.namesInColors = 'namesInColors' in opts ?
      opts.namesInColors : DEFAULTS.namesInColors;

    opts.symbols = {
      passed: opts.symbols && opts.symbols.passed !== undefined ?
        opts.symbols.passed.strikethrough : DEFAULTS.symbols.passed,
      failed: opts.symbols && opts.symbols.failed !== undefined ?
        opts.symbols.failed.strikethrough : DEFAULTS.symbols.failed,
      pending: opts.symbols && opts.symbols.pending !== undefined ?
        opts.symbols.pending.strikethrough : DEFAULTS.symbols.pending,
      suite: opts.symbols && opts.symbols.suite !== undefined ?
        opts.symbols.suite.strikethrough : DEFAULTS.symbols.suite
    };

    colors.setTheme({
      passed: opts.colors && opts.colors.passed ?
        opts.colors.passed : DEFAULTS.colors.passed,
      failed: opts.colors && opts.colors.failed ?
        opts.colors.failed : DEFAULTS.colors.failed,
      pending: opts.colors && opts.colors.pending ?
        opts.colors.pending : DEFAULTS.colors.pending,
      suite: opts.colors && opts.colors.suite ?
        opts.colors.suite : DEFAULTS.colors.suite,
      system: opts.colors && opts.colors.system ?
        opts.colors.system : DEFAULTS.colors.system
    });

    return opts;
  }

  var TerminalLogger = function (options) {
    this.options = configOpts(options);
    this.indentLevel = 0;
    this.lastNewLine = false;
    this.failedSpecs = [];
  };

  TerminalLogger.prototype = {
    start: function () {
      this.print('\n JASMINE STARTING: \n'.bold.inverse);
    },
    stop: function (errors, calc) {
      if (this.options.summary) this.summary(calc);
      if (this.options.failuresSummary &&
        (calc.failedSpecs > 0)) this.failuresSummary(calc);
    },
    failuresSummary: function () {
      this.resetIndent();
      this.newLine(true);
      this.print('**************************************************');
      this.print('*                   ' + ' Failures '.bold.inverse +
        '                   *');
      this.print('**************************************************');
      this.newLine();
      for (var i = 0; i < this.failedSpecs.length; i++) {
        this.failedSummary(this.failedSpecs[i], i + 1);
        this.newLine();
      }
    },
    failedSummary: function (spec, index) {
      this.print(index + ') ' + spec.fullName.bold);
      this.displayErrorMessages(spec, true);
    },
    displayErrorMessages: function (spec, isSummary) {
      this.increaseIndent();
      var assertions = spec.failedExpectations;
      for (var i = 0; i < assertions.length; i++) {
        if (!assertions[i].passed) {
          this.print('- '.failed + assertions[i].message.failed);
          if (this.options.stacktrace && isSummary && assertions[i].stack) {
            this.print(this.filterStackTraces(assertions[i].stack)
              .failed);
          }
        }
      }
      this.decreaseIndent();
    },
    filterStackTraces: function (traces) {
      var lines = traces.split('\n');
      var filtered = [];
      for (var i = 1; i < lines.length; i++) {
        if (!/(jasmine[^\/]*\.js|Timer\.listOnTimeout)/.test(lines[i])) {
          filtered.push(lines[i]);
        }
      }
      return filtered.join('\n');
    },
    summary: function (calc) {
      var execution = 'Executed '.system + ('' + calc.executedSpecs)
        .strikethrough + ' out of '.system +
        ('' + calc.totalSpecs)
        .strikethrough +
        (calc.totalSpecs === 1 ? ' spec '.system : ' specs '.system) +
        'in '.system + calc.runTime.system,
        passed = 'PASSED   ' + calc.passedSpecs + ' (' +
        calc.formatProcentage(calc.passedSpecs, calc.totalSpecs) + ')',
        failed = 'FAILED   ' + calc.failedSpecs + ' (' +
        calc.formatProcentage(calc.failedSpecs, calc.totalSpecs) + ')',
        pending = 'SKIPPED  ' + calc.pendingSpecs + ' (' +
        calc.formatProcentage(calc.pendingSpecs, calc.totalSpecs) + ')';
      this.resetIndent();
      this.newLine(true);
      this.print('**************************************************');
      this.print('*                   ' + ' Summary '.bold.inverse +
        '                    *');
      this.print('**************************************************');
      this.newLine();
      this.print(execution.italic);
      this.newLine();
      this.increaseIndent();
      this.print(passed.passed);
      this.print(failed.failed);
      this.print(pending.pending);
      this.decreaseIndent();
      this.newLine();
    },
    startSuite: function (suite) {
      this.newLine();
      this.increaseIndent();
      this.print(this.options.symbols.suite.suite +
        this.getSuiteName(suite, 'suite'));
    },
    stopSuite: function (suite, calc) {
      if (calc.suites[suite.id].status === 'skip') {
        this.pendingSuite(suite, calc);
      } else if (this.options.suiteDuration) {
        this.suiteDetails(suite, calc);
      } else {
        this.decreaseIndent();
        this.newLine();
      }
      delete calc.suites[suite.id]; // prevent memory leak
    },
    pendingSuite: function (suite) {
      if (this.options.pendingSuite) {
        this.increaseIndent();
        this.print(this.options.symbols.pending.pending +
          this.getSuiteName(suite, 'pending'));
        this.decreaseIndent();
      }
    },
    suiteDetails: function (suite, calc) {
      this.print('  Finished '.system + this.getSuiteName(suite, 'suite') +
        ' in '.system + calc.suites[suite.id].duration.system);
      this.decreaseIndent();
      this.newLine();
    },
    startSpec: function () {
      this.increaseIndent();
    },
    stopSpec: function (spec, calc) {
      this[spec.status](spec, calc);
      this.decreaseIndent();
    },
    passed: function (spec, calc) {
      if (this.options.passedSpec) {
        var duration = this.options.specDuration ?
          ' (' + calc.specTime + ')' : '';
        this.print(this.options.symbols.passed.passed +
          this.getSpecName(spec, 'passed') + duration.system);
      }
    },
    failed: function (spec, calc) {
      this.failedSpecs.push(spec);
      if (this.options.failedSpec) {
        var duration = this.options.specDuration ?
          ' (' + calc.specTime + ')' : '';
        this.print(this.options.symbols.failed.failed +
          this.getSpecName(spec, 'failed') + duration.system);
        if (this.options.failedAsserts)
          this.displayErrorMessages(spec, false);
      }
    },
    pending: function (spec) {
      if (this.options.pendingSpec) {
        this.print(this.options.symbols.pending.pending +
          this.getSpecName(spec, 'pending'));
      }
    },
    getSuiteName: function (suite, color) {
      return this.options.namesInColors ?
        suite.description.bold[color] : suite.description.bold;
    },
    getSpecName: function (spec, color) {
      return this.options.namesInColors ?
        spec.description[color] : spec.description;
    },
    print: function (stuff) {
      if (!this.options.inColors) {
        stuff = ('' + stuff)
          .replace(/\x1B\[\d+m/g, '');
      }
      console.log(this.createIndent() + stuff);
      this.lastNewLine = false;
    },
    newLine: function (force) {
      if (!this.lastNewLine || force) {
        console.log('');
        this.lastNewLine = true;
      }
    },
    createIndent: function () {
      return (new Array(this.indentLevel)
          .join(this.options.indent))
        .toString();
    },
    increaseIndent: function () {
      this.indentLevel++;
    },
    decreaseIndent: function () {
      this.indentLevel--;
    },
    resetIndent: function () {
      this.indentLevel = 1;
    }
  };

  function expose() {
    if (typeof module !== 'undefined' && module.exports) {
      return exports;
    } else {
      global.reporterHelpers = global.reporterHelpers || {};
      return global.reporterHelpers;
    }
  }

  expose()
    .TerminalLogger = TerminalLogger;
})(this);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Steven Soloff
 *
 * This is free software: you can redistribute it and/or modify it under the
 * terms of the MIT License (https://opensource.org/licenses/MIT).
 * This software comes with ABSOLUTELY NO WARRANTY.
 */

'use strict'

const security = require('../../common/support/security')
const webdriver = require('selenium-webdriver')

const By = webdriver.By
const Key = webdriver.Key
const promise = webdriver.promise
const until = webdriver.until

const ResultsTableColumns = {
  EXPRESSION_TEXT: 1,
  EXPRESSION_CANONICAL_TEXT: 2,
  EXPRESSION_RESULT_TEXT: 3,
  EXPRESSION_RESULT_VALUE: 4,
  ACTIONS: 5
}

const Locators = {
  allExpressionResultRows: () => By.css('#main-history-expressionResults tr'),

  dieRollResults: () => By.id('main-sim-dieRollResults'),

  errorMessage: () => By.id('main-eval-errorMessage'),

  evaluate: () => By.id('main-eval-evaluate'),

  expressionForm: () => By.id('main-eval-expressionForm'),

  expressionResultCell: (row, column) => {
    return By.css(`#main-history-expressionResults tr:nth-child(${row}) td:nth-child(${column})`)
  },

  expressionText: () => By.id('main-eval-expressionText'),

  help: () => By.id('main-eval-help'),

  reevaluateExpressionResult: () => By.name('reevaluate'),

  removeAllResults: () => By.id('main-history-removeAllResults'),

  removeExpressionResult: () => By.name('remove'),

  roundingMode: (roundingMode) => By.id(`main-eval-roundingMode${roundingMode}`),

  toggleHelp: () => By.id('main-eval-toggleHelp')
}

class HomePage {
  constructor (driver) {
    this.driver = driver
  }

  awaitUntil (promiseSupplier) {
    const untilPromiseIsResolved = new webdriver.Condition('until promise is resolved', () => {
      return promiseSupplier().catch(() => null)
    })
    return this._wait(untilPromiseIsResolved).catch(() => promiseSupplier())
  }

  clearExpressionText () {
    return this.driver.findElement(Locators.expressionText()).clear()
  }

  evaluate () {
    return this.driver.findElement(Locators.evaluate()).click()
  }

  getErrorMessage () {
    return this.driver.findElement(Locators.errorMessage()).getText()
  }

  getExpressionCanonicalTextAtRow (row) {
    return this.driver.findElement(Locators.expressionResultCell(row, ResultsTableColumns.EXPRESSION_CANONICAL_TEXT))
      .getText()
  }

  getExpressionResultCount () {
    return this.driver.findElements(Locators.allExpressionResultRows())
      .then((elements) => elements.length)
  }

  getExpressionResultTextAtRow (row) {
    return this.driver.findElement(Locators.expressionResultCell(row, ResultsTableColumns.EXPRESSION_RESULT_TEXT))
      .getText()
  }

  getExpressionResultValueAtRow (row) {
    return this.driver.findElement(Locators.expressionResultCell(row, ResultsTableColumns.EXPRESSION_RESULT_VALUE))
      .getText()
  }

  getExpressionTextAtRow (row) {
    return this.driver.findElement(Locators.expressionResultCell(row, ResultsTableColumns.EXPRESSION_TEXT))
      .getText()
  }

  getHelpLinkText () {
    return this.driver.findElement(Locators.toggleHelp()).getText()
  }

  isErrorMessageDisplayed () {
    return this.driver.findElement(Locators.errorMessage()).isDisplayed()
  }

  isHelpDisplayed () {
    return this.driver.findElement(Locators.help()).isDisplayed()
  }

  open () {
    return this.driver.get('http://localhost:3000/')
      .then(() => {
        // Wait for async load of all feature fragments to complete
        const timeoutInMilliseconds = 60000
        return promise.all([
          this._wait(until.elementLocated(Locators.expressionForm()), timeoutInMilliseconds),
          this._wait(until.elementLocated(Locators.removeAllResults()), timeoutInMilliseconds),
          this._wait(until.elementLocated(Locators.dieRollResults()), timeoutInMilliseconds)
        ])
      })
  }

  reevaluateResultAtRow (row) {
    return this._wait(until.elementsLocated(Locators.expressionResultCell(row, ResultsTableColumns.ACTIONS)))
      .then((elements) => elements[0].findElement(Locators.reevaluateExpressionResult()).click())
  }

  removeAllResults () {
    return this.driver.findElement(Locators.removeAllResults()).click()
  }

  removeResultAtRow (row) {
    return this._wait(until.elementsLocated(Locators.expressionResultCell(row, ResultsTableColumns.ACTIONS)))
      .then((elements) => elements[0].findElement(Locators.removeExpressionResult()).click())
  }

  setRandomNumberGenerator (randomNumberGeneratorName) {
    const randomNumberGenerator = {
      content: {
        name: randomNumberGeneratorName
      },
      signature: null
    }
    randomNumberGenerator.signature = security.createSignature(randomNumberGenerator.content)
    return this.driver.executeScript(
      'document.getElementById(\'main-eval-randomNumberGeneratorJson\').value = \'' +
      JSON.stringify(randomNumberGenerator) +
      '\';'
    )
  }

  setRoundingMode (roundingMode) {
    return this.driver.findElement(Locators.roundingMode(roundingMode)).click()
  }

  toggleHelp () {
    return this.driver.findElement(Locators.toggleHelp()).click()
  }

  typeEnter () {
    return this.typeExpressionText(Key.ENTER)
  }

  typeExpressionText (expressionText) {
    return this.driver.findElement(Locators.expressionText()).sendKeys(expressionText)
  }

  waitUntilResultRowCountIs (rowCount) {
    const locator = Locators.allExpressionResultRows()
    const untilResultRowCountIs = new webdriver.Condition(`until result row count is '${rowCount}'`, () =>
      this.driver.findElements(locator)
        .then((elements) => elements.length === rowCount ? elements : null)
    )
    return this._wait(untilResultRowCountIs)
  }

  _wait (condition, timeoutInMilliseconds = 5000) {
    return this.driver.wait(condition, timeoutInMilliseconds)
  }
}

module.exports = HomePage
<commit_msg>Remove acceptance test wait for HTML fragments to load<commit_after>/*
 * Copyright (c) 2016 Steven Soloff
 *
 * This is free software: you can redistribute it and/or modify it under the
 * terms of the MIT License (https://opensource.org/licenses/MIT).
 * This software comes with ABSOLUTELY NO WARRANTY.
 */

'use strict'

const security = require('../../common/support/security')
const webdriver = require('selenium-webdriver')

const By = webdriver.By
const Key = webdriver.Key
const until = webdriver.until

const ResultsTableColumns = {
  EXPRESSION_TEXT: 1,
  EXPRESSION_CANONICAL_TEXT: 2,
  EXPRESSION_RESULT_TEXT: 3,
  EXPRESSION_RESULT_VALUE: 4,
  ACTIONS: 5
}

const Locators = {
  allExpressionResultRows: () => By.css('#main-history-expressionResults tr'),

  errorMessage: () => By.id('main-eval-errorMessage'),

  evaluate: () => By.id('main-eval-evaluate'),

  expressionResultCell: (row, column) => {
    return By.css(`#main-history-expressionResults tr:nth-child(${row}) td:nth-child(${column})`)
  },

  expressionText: () => By.id('main-eval-expressionText'),

  help: () => By.id('main-eval-help'),

  reevaluateExpressionResult: () => By.name('reevaluate'),

  removeAllResults: () => By.id('main-history-removeAllResults'),

  removeExpressionResult: () => By.name('remove'),

  roundingMode: (roundingMode) => By.id(`main-eval-roundingMode${roundingMode}`),

  toggleHelp: () => By.id('main-eval-toggleHelp')
}

class HomePage {
  constructor (driver) {
    this.driver = driver
  }

  awaitUntil (promiseSupplier) {
    const untilPromiseIsResolved = new webdriver.Condition('until promise is resolved', () => {
      return promiseSupplier().catch(() => null)
    })
    return this._wait(untilPromiseIsResolved).catch(() => promiseSupplier())
  }

  clearExpressionText () {
    return this.driver.findElement(Locators.expressionText()).clear()
  }

  evaluate () {
    return this.driver.findElement(Locators.evaluate()).click()
  }

  getErrorMessage () {
    return this.driver.findElement(Locators.errorMessage()).getText()
  }

  getExpressionCanonicalTextAtRow (row) {
    return this.driver.findElement(Locators.expressionResultCell(row, ResultsTableColumns.EXPRESSION_CANONICAL_TEXT))
      .getText()
  }

  getExpressionResultCount () {
    return this.driver.findElements(Locators.allExpressionResultRows())
      .then((elements) => elements.length)
  }

  getExpressionResultTextAtRow (row) {
    return this.driver.findElement(Locators.expressionResultCell(row, ResultsTableColumns.EXPRESSION_RESULT_TEXT))
      .getText()
  }

  getExpressionResultValueAtRow (row) {
    return this.driver.findElement(Locators.expressionResultCell(row, ResultsTableColumns.EXPRESSION_RESULT_VALUE))
      .getText()
  }

  getExpressionTextAtRow (row) {
    return this.driver.findElement(Locators.expressionResultCell(row, ResultsTableColumns.EXPRESSION_TEXT))
      .getText()
  }

  getHelpLinkText () {
    return this.driver.findElement(Locators.toggleHelp()).getText()
  }

  isErrorMessageDisplayed () {
    return this.driver.findElement(Locators.errorMessage()).isDisplayed()
  }

  isHelpDisplayed () {
    return this.driver.findElement(Locators.help()).isDisplayed()
  }

  open () {
    return this.driver.get('http://localhost:3000/')
  }

  reevaluateResultAtRow (row) {
    return this._wait(until.elementsLocated(Locators.expressionResultCell(row, ResultsTableColumns.ACTIONS)))
      .then((elements) => elements[0].findElement(Locators.reevaluateExpressionResult()).click())
  }

  removeAllResults () {
    return this.driver.findElement(Locators.removeAllResults()).click()
  }

  removeResultAtRow (row) {
    return this._wait(until.elementsLocated(Locators.expressionResultCell(row, ResultsTableColumns.ACTIONS)))
      .then((elements) => elements[0].findElement(Locators.removeExpressionResult()).click())
  }

  setRandomNumberGenerator (randomNumberGeneratorName) {
    const randomNumberGenerator = {
      content: {
        name: randomNumberGeneratorName
      },
      signature: null
    }
    randomNumberGenerator.signature = security.createSignature(randomNumberGenerator.content)
    return this.driver.executeScript(
      'document.getElementById(\'main-eval-randomNumberGeneratorJson\').value = \'' +
      JSON.stringify(randomNumberGenerator) +
      '\';'
    )
  }

  setRoundingMode (roundingMode) {
    return this.driver.findElement(Locators.roundingMode(roundingMode)).click()
  }

  toggleHelp () {
    return this.driver.findElement(Locators.toggleHelp()).click()
  }

  typeEnter () {
    return this.typeExpressionText(Key.ENTER)
  }

  typeExpressionText (expressionText) {
    return this.driver.findElement(Locators.expressionText()).sendKeys(expressionText)
  }

  waitUntilResultRowCountIs (rowCount) {
    const locator = Locators.allExpressionResultRows()
    const untilResultRowCountIs = new webdriver.Condition(`until result row count is '${rowCount}'`, () =>
      this.driver.findElements(locator)
        .then((elements) => elements.length === rowCount ? elements : null)
    )
    return this._wait(untilResultRowCountIs)
  }

  _wait (condition, timeoutInMilliseconds = 5000) {
    return this.driver.wait(condition, timeoutInMilliseconds)
  }
}

module.exports = HomePage
<|endoftext|>


<commit_before>
'use strict';

const hogan = require('hogan.js'),
      fs = require('fs'),
      path = require('path'),
      util = require('util'),
      mime = require('mime');

const baseDir = path.join(__dirname, 'email_templates');
const templateDir = path.join(baseDir, 'partials');
const outputDir = path.join(baseDir, 'generated');
const imagesDir = path.join(__dirname, 'images', 'email_templates');
const dest_environment = "https://citizenship-appointment-beta.cfapps.io/";

const email_templates = [
	{
		"name": "invitation_template",
		"template_name": "invitation_template",
		"data": {
			angleIcon: convertImageToHostedSrc("angle_icon.png"),
			headerText: "Invitation to book your citizenship appointment",
			websiteLink: dest_environment
		}
	},
	{
		"name": "confirmation_template",
		"template_name": "confirmation_template",
		"data": {
			locationIcon: convertImageToHostedSrc("location_icon.png"),
			calendarIcon: convertImageToHostedSrc("calendar_icon.png"),
			websiteLink: dest_environment
		}
	},
	{
		"name": "reminder_template",
		"template_name": "invitation_template",
		"data": {
			angleIcon: convertImageToHostedSrc("angle_icon.png"),
			headerText: "Reminder to book your citizenship appointment",
			websiteLink: dest_environment
		}
	},
	{
		"name": "noshow_template",
		"template_name": "invitation_template",
		"data": {
			angleIcon: convertImageToHostedSrc("angle_icon.png"),
			headerText: "You have missed your appointment. Please book your next citizenship appointment",
			websiteLink: dest_environment
		}
	},
	{
		"name": "lastchance_template",
		"template_name": "lastchance_template",
		"data": {
			angleIcon: convertImageToHostedSrc("angle_icon.png"),
			websiteLink: dest_environment
		}
	}
];

generateTemplates();

function generateTemplates(){
	var mainTemplateData = getImagesForMainTemplate(),
		mainBodyTemplate = compileTemplate("main_body.mustache");

	email_templates.forEach(function(template) {
		var compiledTemplate = compileTemplate(template.template_name + ".mustache");
		var templateData = mergeObjects(mainTemplateData, template.data);

		var fullTemplate = mainBodyTemplate.render(templateData, {content: compiledTemplate});
			fs.writeFileSync(path.join(outputDir, template.name + ".html"), fullTemplate);
	});
};

function compileTemplate(templateName){
	return hogan.compile(fs.readFileSync(path.join(templateDir, templateName), 'utf8'));
}

function convertImageToBase64(fileName) {
	var filePath = path.join(imagesDir, fileName);
    var data = fs.readFileSync(filePath).toString("base64");
    return util.format("data:%s;base64,%s", mime.lookup(filePath), data);
}

function convertImageToHostedSrc(fileName){
	return dest_environment + "images/" + fileName;
}

function getImagesForMainTemplate(){
	return {
		headerLogo: convertImageToHostedSrc("aust-govt-black-on-transparent-247x60.png"),
		passportIcon: convertImageToHostedSrc("passport.png"),
		birthCertificateIcon: convertImageToHostedSrc("id-verified.png"),
		documentWithPhotoIcon: convertImageToHostedSrc("license.png"),
		residentialAddressIcon: convertImageToHostedSrc("exterior.png"),
		certificateIcon: convertImageToHostedSrc("certificate-2.png"),
		formIcon: convertImageToHostedSrc("file.png"),
		policeCheckIcon: convertImageToHostedSrc("badge.png"),
		smallCertificateIcon: convertImageToHostedSrc("certificate.png"),
		playIcon: convertImageToHostedSrc("play_icon.png"),
		pdfIcon: convertImageToHostedSrc("pdf_icon.png"),
		checkIcon: convertImageToHostedSrc("check_icon.png")
	};
}

function mergeObjects(target, source){
	var result = {};
    for(var prop in source){
        result[prop] = source[prop];
    }
    for(var prop in target){
        result[prop] = target[prop];
    }
    return result;
}<commit_msg>Make email generation script executable<commit_after>#!/usr/bin/env node

'use strict';

const hogan = require('hogan.js'),
      fs = require('fs'),
      path = require('path'),
      util = require('util'),
      mime = require('mime');

const baseDir = path.join(__dirname, 'email_templates');
const templateDir = path.join(baseDir, 'partials');
const outputDir = path.join(baseDir, 'generated');
const imagesDir = path.join(__dirname, 'images', 'email_templates');
const dest_environment = "https://citizenship-appointment-beta.cfapps.io/";

const email_templates = [
	{
		"name": "invitation_template",
		"template_name": "invitation_template",
		"data": {
			angleIcon: convertImageToHostedSrc("angle_icon.png"),
			headerText: "Invitation to book your citizenship appointment",
			websiteLink: dest_environment
		}
	},
	{
		"name": "confirmation_template",
		"template_name": "confirmation_template",
		"data": {
			locationIcon: convertImageToHostedSrc("location_icon.png"),
			calendarIcon: convertImageToHostedSrc("calendar_icon.png"),
			websiteLink: dest_environment
		}
	},
	{
		"name": "reminder_template",
		"template_name": "invitation_template",
		"data": {
			angleIcon: convertImageToHostedSrc("angle_icon.png"),
			headerText: "Reminder to book your citizenship appointment",
			websiteLink: dest_environment
		}
	},
	{
		"name": "noshow_template",
		"template_name": "invitation_template",
		"data": {
			angleIcon: convertImageToHostedSrc("angle_icon.png"),
			headerText: "You have missed your appointment. Please book your next citizenship appointment",
			websiteLink: dest_environment
		}
	},
	{
		"name": "lastchance_template",
		"template_name": "lastchance_template",
		"data": {
			angleIcon: convertImageToHostedSrc("angle_icon.png"),
			websiteLink: dest_environment
		}
	}
];

generateTemplates();

function generateTemplates(){
	var mainTemplateData = getImagesForMainTemplate(),
		mainBodyTemplate = compileTemplate("main_body.mustache");

	email_templates.forEach(function(template) {
		var compiledTemplate = compileTemplate(template.template_name + ".mustache");
		var templateData = mergeObjects(mainTemplateData, template.data);

		var fullTemplate = mainBodyTemplate.render(templateData, {content: compiledTemplate});
			fs.writeFileSync(path.join(outputDir, template.name + ".html"), fullTemplate);
	});
};

function compileTemplate(templateName){
	return hogan.compile(fs.readFileSync(path.join(templateDir, templateName), 'utf8'));
}

function convertImageToBase64(fileName) {
	var filePath = path.join(imagesDir, fileName);
    var data = fs.readFileSync(filePath).toString("base64");
    return util.format("data:%s;base64,%s", mime.lookup(filePath), data);
}

function convertImageToHostedSrc(fileName){
	return dest_environment + "images/" + fileName;
}

function getImagesForMainTemplate(){
	return {
		headerLogo: convertImageToHostedSrc("aust-govt-black-on-transparent-247x60.png"),
		passportIcon: convertImageToHostedSrc("passport.png"),
		birthCertificateIcon: convertImageToHostedSrc("id-verified.png"),
		documentWithPhotoIcon: convertImageToHostedSrc("license.png"),
		residentialAddressIcon: convertImageToHostedSrc("exterior.png"),
		certificateIcon: convertImageToHostedSrc("certificate-2.png"),
		formIcon: convertImageToHostedSrc("file.png"),
		policeCheckIcon: convertImageToHostedSrc("badge.png"),
		smallCertificateIcon: convertImageToHostedSrc("certificate.png"),
		playIcon: convertImageToHostedSrc("play_icon.png"),
		pdfIcon: convertImageToHostedSrc("pdf_icon.png"),
		checkIcon: convertImageToHostedSrc("check_icon.png")
	};
}

function mergeObjects(target, source){
	var result = {};
    for(var prop in source){
        result[prop] = source[prop];
    }
    for(var prop in target){
        result[prop] = target[prop];
    }
    return result;
}
<|endoftext|>


<commit_before>'use strict';
var path = require('path'),
    html = require('html-wiring'),
    shelljs = require('shelljs'),
    engine = require('ejs').render,
    _ = require('lodash');

const constants = require('./generator-constants'),
    CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR,
    LANGUAGES_MAIN_SRC_DIR = '../../languages/templates/' + constants.CLIENT_MAIN_SRC_DIR;

module.exports = {
    rewrite: rewrite,
    rewriteFile: rewriteFile,
    replaceContent: replaceContent,
    classify: classify,
    rewriteJSONFile: rewriteJSONFile,
    copyWebResource: copyWebResource,
    wordwrap: wordwrap
};

function rewriteFile(args, _this) {
    args.path = args.path || process.cwd();
    var fullPath = path.join(args.path, args.file);

    args.haystack = _this.fs.read(fullPath);
    var body = rewrite(args);
    _this.fs.write(fullPath, body);
}

function replaceContent(args, _this) {
    args.path = args.path || process.cwd();
    var fullPath = path.join(args.path, args.file);

    var re = args.regex ? new RegExp(args.pattern, 'g') : args.pattern;

    var body = _this.fs.read(fullPath);
    body = body.replace(re, args.content);
    _this.fs.write(fullPath, body);
}

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}

function rewrite(args) {
    // check if splicable is already in the body text
    var re = new RegExp(args.splicable.map(function (line) {
        return '\s*' + escapeRegExp(line);
    }).join('\n'));

    if (re.test(args.haystack)) {
        return args.haystack;
    }

    var lines = args.haystack.split('\n');

    var otherwiseLineIndex = -1;
    lines.forEach(function (line, i) {
        if (line.indexOf(args.needle) !== -1) {
            otherwiseLineIndex = i;
        }
    });

    var spaces = 0;
    while (lines[otherwiseLineIndex].charAt(spaces) === ' ') {
        spaces += 1;
    }

    var spaceStr = '';
    while ((spaces -= 1) >= 0) {
        spaceStr += ' ';
    }

    lines.splice(otherwiseLineIndex, 0, args.splicable.map(function (line) {
        return spaceStr + line;
    }).join('\n'));

    return lines.join('\n');
}

// _.classify uses _.titleize which lowercase the string,
// so if the user chooses a proper ClassName it will not rename properly
function classify(string) {
    string = string.replace(/[\W_](\w)/g, function (match) {
        return ' ' + match[1].toUpperCase();
    }).replace(/\s/g, '');
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function rewriteJSONFile(filePath, rewriteFile, _this) {
    var jsonObj = _this.fs.readJSON(filePath);
    rewriteFile(jsonObj, _this);
    _this.fs.writeJSON(filePath, jsonObj, null, 4);
}

function copyWebResource(source, dest, regex, type, _this, _opt, template) {

    _opt = _opt !== undefined ? _opt : {};
    if (_this.enableTranslation) {
        // uses template method instead of copy if template boolean is set as true
        template ? _this.template(source, dest, _this, _opt) : _this.copy(source, dest);
    } else {
        var body = stripContent(source, regex, _this, _opt);
        switch (type) {
        case 'html' :
            body = replacePlaceholders(body, _this);
            break;
        case 'js' :
            body = replaceTitle(body, _this, template);
            break;
        }
        _this.write(dest, body);
    }
}

function stripContent(source, regex, _this, _opt) {

    var body = html.readFileAsString(path.join(_this.sourceRoot(), source));
    //temp hack to fix error thrown by ejs during entity creation, this needs a permanent fix when we add more .ejs files
    _opt.filename = path.join(_this.sourceRoot(), CLIENT_MAIN_SRC_DIR + 'app/entities/ng_validators.ejs');
    body = engine(body, _this, _opt);
    body = body.replace(regex, '');

    return body;
}

function replaceTitle(body, _this, template) {
    var re = /pageTitle[\s]*:[\s]*[\'|\"]([a-zA-Z0-9\.\-\_]+)[\'|\"]/g;
    var match;

    while ((match = re.exec(body)) !== null) {
        // match is now the next match, in array form and our key is at index 1, index 1 is replace target.
        var key = match[1], target = key;
        var jsonData = geti18nJson(key, _this);
        var keyValue = jsonData !== undefined ? deepFind(jsonData, key) : undefined;

        body = body.replace(target, keyValue !== undefined ? keyValue : _this.baseName);
    }

    return body;
}

function replacePlaceholders(body, _this) {
    var re = /placeholder=[\'|\"]([\{]{2}[\'|\"]([a-zA-Z0-9\.\-\_]+)[\'|\"][\s][\|][\s](translate)[\}]{2})[\'|\"]/g;
    var match;

    while ((match = re.exec(body)) !== null) {
        // match is now the next match, in array form and our key is at index 2, index 1 is replace target.
        var key = match[2], target = match[1];
        var jsonData = geti18nJson(key, _this);
        var keyValue = jsonData !== undefined ? deepFind(jsonData, key, true) : undefined; // dirty fix to get placeholder as it is not in proper json format, name has a dot in it. Assuming that all placeholders are in similar format

        body = body.replace(target, keyValue !== undefined ? keyValue : '');
    }

    return body;
}

function geti18nJson(key, _this, template) {

    var i18nDirectory = LANGUAGES_MAIN_SRC_DIR + 'i18n/en/',
        name = _.kebabCase(key.split('.')[0]),
        filename = i18nDirectory + name + '.json',
        render = template;

    if (!shelljs.test('-f', path.join(_this.sourceRoot(), filename))) {
        filename = i18nDirectory + '_' + name + '.json';
        render = true;
    }
    try {
        var file = html.readFileAsString(path.join(_this.sourceRoot(), filename));

        file = render ? engine(file, _this, {}) : file;
        file = JSON.parse(file);
        return file;
    } catch (err) {
        _this.log(err);
        _this.log("Error in file: " + filename);
        // 'Error reading translation file!'
        return undefined;
    }
}

function deepFind(obj, path, placeholder) {
    var paths = path.split('.'), current = obj, i;
    if (placeholder) {// dirty fix for placeholders, the json files needs to be corrected
        paths[paths.length - 2] = paths[paths.length - 2] + '.' + paths[paths.length - 1];
        paths.pop();
    }
    for (i = 0; i < paths.length; ++i) {
        if (current[paths[i]] === undefined) {
            return undefined;
        } else {
            current = current[paths[i]];
        }
    }
    return current;
}

function wordwrap (text, width, separator, keepLF) {
    var wrappedText = '';
    var rows = text.split('\n');
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        if (keepLF === true && i !== 0) {
            wrappedText = wrappedText + '\\n';
        }
        wrappedText = wrappedText + separator + _.padEnd(row,width) + separator;
    }
    return wrappedText;
}
<commit_msg>fix eslint error<commit_after>'use strict';
var path = require('path'),
    html = require('html-wiring'),
    shelljs = require('shelljs'),
    engine = require('ejs').render,
    _ = require('lodash');

const constants = require('./generator-constants'),
    CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR,
    LANGUAGES_MAIN_SRC_DIR = '../../languages/templates/' + constants.CLIENT_MAIN_SRC_DIR;

module.exports = {
    rewrite: rewrite,
    rewriteFile: rewriteFile,
    replaceContent: replaceContent,
    classify: classify,
    rewriteJSONFile: rewriteJSONFile,
    copyWebResource: copyWebResource,
    wordwrap: wordwrap
};

function rewriteFile(args, _this) {
    args.path = args.path || process.cwd();
    var fullPath = path.join(args.path, args.file);

    args.haystack = _this.fs.read(fullPath);
    var body = rewrite(args);
    _this.fs.write(fullPath, body);
}

function replaceContent(args, _this) {
    args.path = args.path || process.cwd();
    var fullPath = path.join(args.path, args.file);

    var re = args.regex ? new RegExp(args.pattern, 'g') : args.pattern;

    var body = _this.fs.read(fullPath);
    body = body.replace(re, args.content);
    _this.fs.write(fullPath, body);
}

function escapeRegExp(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}

function rewrite(args) {
    // check if splicable is already in the body text
    var re = new RegExp(args.splicable.map(function (line) {
        return '\s*' + escapeRegExp(line);
    }).join('\n'));

    if (re.test(args.haystack)) {
        return args.haystack;
    }

    var lines = args.haystack.split('\n');

    var otherwiseLineIndex = -1;
    lines.forEach(function (line, i) {
        if (line.indexOf(args.needle) !== -1) {
            otherwiseLineIndex = i;
        }
    });

    var spaces = 0;
    while (lines[otherwiseLineIndex].charAt(spaces) === ' ') {
        spaces += 1;
    }

    var spaceStr = '';
    while ((spaces -= 1) >= 0) {
        spaceStr += ' ';
    }

    lines.splice(otherwiseLineIndex, 0, args.splicable.map(function (line) {
        return spaceStr + line;
    }).join('\n'));

    return lines.join('\n');
}

// _.classify uses _.titleize which lowercase the string,
// so if the user chooses a proper ClassName it will not rename properly
function classify(string) {
    string = string.replace(/[\W_](\w)/g, function (match) {
        return ' ' + match[1].toUpperCase();
    }).replace(/\s/g, '');
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function rewriteJSONFile(filePath, rewriteFile, _this) {
    var jsonObj = _this.fs.readJSON(filePath);
    rewriteFile(jsonObj, _this);
    _this.fs.writeJSON(filePath, jsonObj, null, 4);
}

function copyWebResource(source, dest, regex, type, _this, _opt, template) {

    _opt = _opt !== undefined ? _opt : {};
    if (_this.enableTranslation) {
        // uses template method instead of copy if template boolean is set as true
        template ? _this.template(source, dest, _this, _opt) : _this.copy(source, dest);
    } else {
        var body = stripContent(source, regex, _this, _opt);
        switch (type) {
        case 'html' :
            body = replacePlaceholders(body, _this);
            break;
        case 'js' :
            body = replaceTitle(body, _this, template);
            break;
        }
        _this.write(dest, body);
    }
}

function stripContent(source, regex, _this, _opt) {

    var body = html.readFileAsString(path.join(_this.sourceRoot(), source));
    //temp hack to fix error thrown by ejs during entity creation, this needs a permanent fix when we add more .ejs files
    _opt.filename = path.join(_this.sourceRoot(), CLIENT_MAIN_SRC_DIR + 'app/entities/ng_validators.ejs');
    body = engine(body, _this, _opt);
    body = body.replace(regex, '');

    return body;
}

function replaceTitle(body, _this, template) {
    var re = /pageTitle[\s]*:[\s]*[\'|\"]([a-zA-Z0-9\.\-\_]+)[\'|\"]/g;
    var match;

    while ((match = re.exec(body)) !== null) {
        // match is now the next match, in array form and our key is at index 1, index 1 is replace target.
        var key = match[1], target = key;
        var jsonData = geti18nJson(key, _this);
        var keyValue = jsonData !== undefined ? deepFind(jsonData, key) : undefined;

        body = body.replace(target, keyValue !== undefined ? keyValue : _this.baseName);
    }

    return body;
}

function replacePlaceholders(body, _this) {
    var re = /placeholder=[\'|\"]([\{]{2}[\'|\"]([a-zA-Z0-9\.\-\_]+)[\'|\"][\s][\|][\s](translate)[\}]{2})[\'|\"]/g;
    var match;

    while ((match = re.exec(body)) !== null) {
        // match is now the next match, in array form and our key is at index 2, index 1 is replace target.
        var key = match[2], target = match[1];
        var jsonData = geti18nJson(key, _this);
        var keyValue = jsonData !== undefined ? deepFind(jsonData, key, true) : undefined; // dirty fix to get placeholder as it is not in proper json format, name has a dot in it. Assuming that all placeholders are in similar format

        body = body.replace(target, keyValue !== undefined ? keyValue : '');
    }

    return body;
}

function geti18nJson(key, _this, template) {

    var i18nDirectory = LANGUAGES_MAIN_SRC_DIR + 'i18n/en/',
        name = _.kebabCase(key.split('.')[0]),
        filename = i18nDirectory + name + '.json',
        render = template;

    if (!shelljs.test('-f', path.join(_this.sourceRoot(), filename))) {
        filename = i18nDirectory + '_' + name + '.json';
        render = true;
    }
    try {
        var file = html.readFileAsString(path.join(_this.sourceRoot(), filename));

        file = render ? engine(file, _this, {}) : file;
        file = JSON.parse(file);
        return file;
    } catch (err) {
        _this.log(err);
        _this.log('Error in file: ' + filename);
        // 'Error reading translation file!'
        return undefined;
    }
}

function deepFind(obj, path, placeholder) {
    var paths = path.split('.'), current = obj, i;
    if (placeholder) {// dirty fix for placeholders, the json files needs to be corrected
        paths[paths.length - 2] = paths[paths.length - 2] + '.' + paths[paths.length - 1];
        paths.pop();
    }
    for (i = 0; i < paths.length; ++i) {
        if (current[paths[i]] === undefined) {
            return undefined;
        } else {
            current = current[paths[i]];
        }
    }
    return current;
}

function wordwrap (text, width, separator, keepLF) {
    var wrappedText = '';
    var rows = text.split('\n');
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        if (keepLF === true && i !== 0) {
            wrappedText = wrappedText + '\\n';
        }
        wrappedText = wrappedText + separator + _.padEnd(row,width) + separator;
    }
    return wrappedText;
}
<|endoftext|>


<commit_before>// npm install request js-beautify
var request = require('request');
var fs = require('fs');
var path = require('path');
var beautify = require('js-beautify').js_beautify;

function getFiles(instanceName) {
  var files = [
    '-persons.json',
    '-memberships.json',
    '-organizations.json',
    '-posts.json',
    '_locdata.json'
  ];

  files.forEach(function(file) {
    var filename = instanceName + file;
    var url = "http://static-beta.cargografias.org/datasets/" + filename;
    console.log("Getting:", url);
    request({
      url: url,
      gzip: true
    }, function(error, response, body) {
      if (error) {
        console.log("Error getting file", filename);
      } else if (response.statusCode != 200) {
        console.log("Error getting file", filename, response.statusCode, response.statusMessage);
      } else {
        var dest = path.normalize("static-public/datasets/" + filename);
        fs.writeFile(dest, beautify(body), function(err) {
          if (err) console.log("Error writing", dest, err);
          else console.log("Complete:", dest);
        });
      }
    })
  })
}

function runProgram(a, b, instanceName) {
  if (!instanceName) {
    console.log("Usage: node getInstanceData.js [instanceName]");
    return;
  }
  getFiles(instanceName);
}

runProgram.apply(this, process.argv);
<commit_msg>data y optras codsas<commit_after>// npm install request js-beautify
var request = require('request');
var fs = require('fs');
var path = require('path');
var beautify = require('js-beautify').js_beautify;

function getFiles(instanceName) {
  var files = [
    '-persons.json',
    '-memberships.json',
    '-organizations.json',
    '-posts.json',
    '_locdata.json'
  ];

  files.forEach(function(file) {
    var filename = instanceName + file;
    var url = "http://static.cargografias.org/datasets/" + filename;
    console.log("Getting:", url);
    request({
      url: url,
      gzip: true
    }, function(error, response, body) {
      if (error) {
        console.log("Error getting file", filename);
      } else if (response.statusCode != 200) {
        console.log("Error getting file", filename, response.statusCode, response.statusMessage);
      } else {
        var dest = path.normalize("static-public/datasets/" + filename);
        fs.writeFile(dest, beautify(body), function(err) {
          if (err) console.log("Error writing", dest, err);
          else console.log("Complete:", dest);
        });
      }
    })
  })
}

function runProgram(a, b, instanceName) {
  if (!instanceName) {
    console.log("Usage: node getInstanceData.js [instanceName]");
    return;
  }
  getFiles(instanceName);
}

runProgram.apply(this, process.argv);
<|endoftext|>


<commit_before>'use strict';

const eventTypes = require('./resources/trackables.json').eventTypes;
const rewardTypes = require('./resources/trackables.json').rewardTypes;

function trackablesFromParameters (paramString) {
  let items = paramString.split(' ');

  const trackables = {
    events: [],
    items: [],
  }

  if (items[0].toLowerCase() === 'all') {
    trackables.events = trackables.events.concat(eventTypes);
    trackables.items = trackables.items.concat(rewardTypes);
  } else {
    items = items.map(item => item.trim());
    items.forEach((item) => {
      if (item.toLowerCase() === 'items') {
        trackables.items = trackables.items.concat(rewardTypes);
      } else if (item.toLowerCase() === 'events') {
        trackables.events = trackables.events.concat(eventTypes);
      } else if (item.toLowerCase === 'fissures') {
        trackables.events = trackables.events.concat([ 'fissures.t1', 'fissures.t2', 'fissures.t3', 'fissures.t4' ]);
      } else if (item.toLowerCase === 'syndicates') {
        trackables.events = trackables.events.concat([ 'syndicate.arbiters', 'syndicate.suda', 'syndicate.loka', 'syndicate.perrin', 'syndicate.veil', 'syndicate.meridian' ]);
      } else if (item.toLowerCase === 'conclave') {
        trackables.events = trackables.events.concat([ 'conclave.weeklies', 'conclave.dailies' ]);
      } else if (item.toLowerCase === 'deals') {
        trackables.events = trackables.events.concat([ "deals.featured", "deals.popular"  ]);
      } else if (rewardTypes.includes(item.trim())) {
        trackables.items.push(item.trim());
      } else if (eventTypes.includes(item.trim())) {
        trackables.events.push(item.trim());
      }
    });
  }
  return trackables;
}

function getTrackInstructionEmbed(message, prefix, call) {
  const embed = {
    type: 'rich',
    color: 0x0000ff,
    fields: [
      {
        name: `${prefix}${call} <event(s)/item(s) to ${call === 'untrack' ? 'un' : ''}track>`,
        value: 'Track events/items to be alerted in this channel.',
        inline: true,
      },
      {
        name: 'Possible values:',
        value: '_ _',
        inline: false,
      },
      {
        name: '**Events:**',
        value: `${eventTypes.concat(['all', 'events', 'fissures', 'syndicates', 'conclave']).join('\n')}`,
        inline: true,
      },
      {
        name: '**Rewards:**',
        value: `${rewardTypes.join('\n')}\nall\nitems`,
        inline: true,
      },
    ],
  };

  switch (call) {
    case 'track':
      embed.fields[0].value = 'Track events/items to be alerted in this channel.'
      break;
    case 'untrack':
      embed.fields[0].value = 'Untrack events/items to be alerted in this channel.'
      break;
    case 'set ping':
      embed.fields[0].value = 'Set the text added before an event/item notification.'
      embed.fields.push({
        name: '**Ping:**',
        value: 'Whatever string you want to be added before a notification for this item or event. If you leave this blank, the ping for this item/event will be cleared',
        inline: true,
      });
      break;
  }
  return embed;
}

module.exports = { trackablesFromParameters, getTrackInstructionEmbed };
<commit_msg>fix formatting, clean up literals<commit_after>'use strict';

const eventTypes = require('./resources/trackables.json').eventTypes;
const rewardTypes = require('./resources/trackables.json').rewardTypes;

const fissures = ['fissures.t1', 'fissures.t2', 'fissures.t3', 'fissures.t4'];
const syndicates = ['syndicate.arbiters', 'syndicate.suda', 'syndicate.loka', 'syndicate.perrin', 'syndicate.veil', 'syndicate.meridian'];
const conclave = ['conclave.weeklies', 'conclave.dailies'];
const deals = ['deals.featured', 'deals.popular']

function trackablesFromParameters (paramString) {
  let items = paramString.split(' ');

  const trackables = {
    events: [],
    items: [],
  }

  if (items[0].toLowerCase() === 'all') {
    trackables.events = trackables.events.concat(eventTypes);
    trackables.items = trackables.items.concat(rewardTypes);
  } else {
    items = items.map(item => item.trim());
    items.forEach((item) => {
      const i = item.toLowerCase().trim();
      if (i === 'items') {
        trackables.items = trackables.items.concat(rewardTypes);
      } else if (i === 'events') {
        trackables.events = trackables.events.concat(eventTypes);
      } else if (i === 'fissures') {
        trackables.events = trackables.events.concat(fissures);
      } else if (i === 'syndicates') {
        trackables.events = trackables.events.concat(syndicates);
      } else if (i === 'conclave') {
        trackables.events = trackables.events.concat(conclave);
      } else if (i === 'deals') {
        trackables.events = trackables.events.concat(deals);
      } else if (rewardTypes.includes(item.trim())) {
        trackables.items.push(item.trim());
      } else if (eventTypes.includes(item.trim())) {
        trackables.events.push(item.trim());
      }
    });
  }
  return trackables;
}

function getTrackInstructionEmbed(message, prefix, call) {
  const embed = {
    type: 'rich',
    color: 0x0000ff,
    fields: [
      {
        name: `${prefix}${call} <event(s)/item(s) to ${call === 'untrack' ? 'un' : ''}track>`,
        value: 'Track events/items to be alerted in this channel.',
        inline: true,
      },
      {
        name: 'Possible values:',
        value: '_ _',
        inline: false,
      },
      {
        name: '**Events:**',
        value: `${eventTypes.concat(['all', 'events', 'fissures', 'syndicates', 'conclave']).join('\n')}`,
        inline: true,
      },
      {
        name: '**Rewards:**',
        value: `${rewardTypes.join('\n')}\nall\nitems`,
        inline: true,
      },
    ],
  };

  switch (call) {
    case 'track':
      embed.fields[0].value = 'Track events/items to be alerted in this channel.'
      break;
    case 'untrack':
      embed.fields[0].value = 'Untrack events/items to be alerted in this channel.'
      break;
    case 'set ping':
      embed.fields[0].value = 'Set the text added before an event/item notification.'
      embed.fields.push({
        name: '**Ping:**',
        value: 'Whatever string you want to be added before a notification for this item or event. If you leave this blank, the ping for this item/event will be cleared',
        inline: true,
      });
      break;
  }
  return embed;
}

module.exports = { trackablesFromParameters, getTrackInstructionEmbed };
<|endoftext|>


<commit_before>'use strict';

/* Controllers */
var flaskenbergControllers = angular.module('flaskenbergControllers', []);

flaskenbergControllers.controller('SurveyCtrl', ['$scope', 'User', 'Task', 'Question', 'Answer',
  function($scope, User, Task, Question, Answer) {

    //Get the next question
    User.next({userId: 1}, function(res){
      $scope.answer   = Answer.get({answerId: res.answer_id});
      $scope.task     = Task.get({taskId: res.task_id});
      $scope.question = Question.get({questionId: res.question_id});
    });

    //Submit
    $scope.submit = function(){
      Answer.save($scope.answer);
    };
  }]);<commit_msg>Moves onto the next question! but now throws at the end of the tasks assigned to the user<commit_after>'use strict';

/* Controllers */
var flaskenbergControllers = angular.module('flaskenbergControllers', []);

flaskenbergControllers.controller('SurveyCtrl', ['$scope', 'User', 'Task', 'Question', 'Answer',
  function($scope, User, Task, Question, Answer) {

    var init = function(){
      //Get the next question
      User.next({userId: 1}, function(res){
        $scope.answer   = Answer.get({answerId: res.answer_id});
        $scope.task     = Task.get({taskId: res.task_id});
        $scope.question = Question.get({questionId: res.question_id});
      });
    };

    //Submit
    $scope.submit = function(){
      Answer.save($scope.answer);
      init();
    };

    init();
  }]);<|endoftext|>


<commit_before>// バックで環境設定などのややこしい処理をします。
var sphero = require("sphero");
var events = {};
module.exports = {
  addEventListener: function(eventName, fn) {
    if (typeof events[eventName] === "undefined") {
      events[eventName] = [];
    }
    events[eventName].push(fn);
  },
  connect: function(port, callback) {
    var orb = sphero(port);
    orb.connect(function() {
      console.log("準備開始");
      orb.startCalibration(); // 位置関係の補正
      setTimeout(function() {
        console.log("準備終了");
        orb.finishCalibration();
        orb.detectCollisions(); // 衝突判定を有効化
        callback(orb);
      }, 10000);
    });
    orb.on("collision", function() {
      raiseEvent("collision");
    });
    return orb;
  },
  move: function(speed, deg, orb) {
    var _deg;
    if (typeof deg === "number") {
      _deg = deg;
    } else if (typeof deg === "string") {
      _deg = 0;
      switch (deg) {
        case "左":
          _deg = 270;
          break;
        case "後":
          _deg = 180;
          break;
        case "右":
          _deg = 90;
          break;
        case "前":
          _deg = 0;
          break;
      }
    }
    orb.roll(speed, _deg);
    setMoveLoop(orb, speed, _deg);
  },
  color: function(orb, color, time) {
    var _c;
    orb.getColor(function(err, data) {
      // なぜかdata.colorは、16進数だが文字列として帰ってくるので、parseInt。
      _c = parseInt(data.color);
      orb.color(color);
      if (typeof time !== "undefined") {
        setTimeout(function() {
          orb.color(_c);
        }, time * 1000);
      }
    });
  }
};

function raiseEvent(eventName) {
  if (typeof events[eventName] !== "undefined") {
    events[eventName].forEach(i => {
      i();
    });
  }
}

// (#15) orb.roll が、数秒後に止まらないようにする
function setMoveLoop(orb, speed, deg) {
  if (moveLoopId !== -1) {
    clearTimeout(moveLoopId);
  }
  var loop = function() {
    orb.roll(speed, deg);
    moveLoopId = setTimeout(loop, 1000);
  }
  moveLoopId = setTimeout(loop, 1000);
}
var moveLoopId = -1;
<commit_msg>move 関数をちょっといい感じに<commit_after>// バックで環境設定などのややこしい処理をします。
var sphero = require("sphero");
var events = {};
module.exports = {
  addEventListener: function(eventName, fn) {
    if (typeof events[eventName] === "undefined") {
      events[eventName] = [];
    }
    events[eventName].push(fn);
  },
  connect: function(port, callback) {
    var orb = sphero(port);
    orb.connect(function() {
      console.log("準備開始");
      orb.startCalibration(); // 位置関係の補正
      setTimeout(function() {
        console.log("準備終了");
        orb.finishCalibration();
        orb.detectCollisions(); // 衝突判定を有効化
        callback(orb);
      }, 10000);
    });
    orb.on("collision", function() {
      raiseEvent("collision");
    });
    return orb;
  },
  move: function(speed, deg, orb) {
    var _deg = 0;
    if (typeof deg === "number") {
      _deg = deg;
    } else if (typeof deg === "string") {
      switch (deg) {
        case "左":
          _deg = 270;
          break;
        case "後":
          _deg = 180;
          break;
        case "右":
          _deg = 90;
          break;
        case "前":
          _deg = 0;
          break;
      }
    }
    orb.roll(speed, _deg);
    setMoveLoop(orb, speed, _deg);
  },
  color: function(orb, color, time) {
    var _c;
    orb.getColor(function(err, data) {
      // なぜかdata.colorは、16進数だが文字列として帰ってくるので、parseInt。
      _c = parseInt(data.color);
      orb.color(color);
      if (typeof time !== "undefined") {
        setTimeout(function() {
          orb.color(_c);
        }, time * 1000);
      }
    });
  }
};

function raiseEvent(eventName) {
  if (typeof events[eventName] !== "undefined") {
    events[eventName].forEach(i => {
      i();
    });
  }
}

// (#15) orb.roll が、数秒後に止まらないようにする
function setMoveLoop(orb, speed, deg) {
  if (moveLoopId !== -1) {
    clearTimeout(moveLoopId);
  }
  var loop = function() {
    orb.roll(speed, deg);
    moveLoopId = setTimeout(loop, 1000);
  }
  moveLoopId = setTimeout(loop, 1000);
}
var moveLoopId = -1;
<|endoftext|>


<commit_before><commit_msg>Added a very simple peephole optimizer<commit_after><|endoftext|>


<commit_before>var hooks = {
  /***************** express *****************/
  beforeExpress: (port, abe) => {
    return port
  },
  afterExpress: (app, express, abe) => {
    return app
  },
  beforeRoute: (req, res, next, abe) => {
    return req
  },
  beforeAddRoute: (router, abe) => {
    return router
  },
  afterAddRoute: (router, abe) => {
    return router
  },

  /***************** preview *****************/
  beforePreview: (html, req, res, next, abe) => {
    return html
  },

  /***************** delete *****************/
  beforeDeleteFile: (filePath, abe) => {
    return filePath
  },
  afterDeleteFile: (path, json, abe) => {
    return path
  },

  /***************** reject *****************/
  beforeReject: (json, filePath, tplPath, abe) => {
    return json
  },
  afterReject: (result, abe) => {
    return result
  },

  /***************** publish *****************/
  beforePublish: (json, filePath, tplPath, abe) => {
    return json
  },
  afterPublish: (result, filePath, abe) => {
    return result
  },

  /***************** unpublish *****************/
  beforeUnpublish: (filePath, abe) => {
    return filePath
  },
  afterUnpublish: (path, postPath, json, abe) => {
    return path
  },

  /***************** create *****************/
  beforeCreate: (json, postUrl, template, abe) => {
    return json
  },
  afterCreate: (json, text, path, name, req, forceJson, abe) => {
    return json
  },

  /***************** duplicate *****************/
  beforeDuplicate: (oldFilePath, template, path, name, req, deleteFiles, abe) => {
    // if deleteFiles this is an update not a duplicate
    return oldFilePath
  },
  afterDuplicate: (json, oldFilePath, template, path, name, req, deleteFiles, abe) => {
    return json
  },

  /***************** update *****************/
  beforeUpdate: (json, oldFilePath, template, path, name, req, deleteFiles, abe) => {
    return json
  },

  /***************** save *****************/
  beforeFirstSave: (json, body, abe) => {
    return json
  },
  beforeSave: (obj, abe) => {
    return obj
  },
  afterSave: (obj, abe) => {
    return obj
  },
  beforeSaveImage: (folderWebPath, abe) => {
    return folderWebPath
  },
  afterSaveImage: (resp, abe) => {
    return resp
  },
  afterPageSaveCompile: (tmp, json, abe) => {
    return tmp
  },
  afterPageEditorCompile: (tmp, json, abe) => {
    return tmp
  },

  /***************** Manager *****************/
  beforeGetAllFilesDraft: (drafted, abe) => {
    return drafted
  },
  beforeGetAllFilesPublished: (published, abe) => {
    return published
  },
  afterGetAllFiles: (merged, abe) => {
    return merged
  },

  /***************** Editor *****************/
  beforeImport: (file, config, ctx, abe) => {
    return file
  },
  afterImport: (res, file, config, ctx, abe) => {
    return res
  },
  afterHandlebarsHelpers: (Handlebars, abe) => {
    return Handlebars
  },
  beforeEditorInput: (params, abe) => {
    return params
  },
  afterEditorInput: (htmlString, params, abe) => {
    return htmlString
  },

  beforeAbeAttributes: (str, json, abe) => {
    return str
  },
  afterAbeAttributes: (obj, str, json, abe) => {
    return obj
  },
  beforeEditorFormBlocks: (json, text, abe) => {
    return json
  },
  afterEditorFormBlocks: (blocks, json, text, abe) => {
    return blocks
  },
  beforeListPage: (file, index, text) => {
    return file
  },
  afterListPageDraft: (workflow, file, index, text) => {
    return workflow
  },
  afterListPage: (res, file, index, text) => {
    return res
  },
  afterVariables: (EditorVariables, abe) => {
    return EditorVariables
  },

  /***************** json *****************/
  beforeGetJson: (path, abe) => {
    return path
  },
  afterGetJson: (json, abe) => {
    return json
  },
  beforeUpdateJson: (jsonFilesArray, abe) => {
    return jsonFilesArray
  },

  /***************** text *****************/
  beforeGetTemplate: (file, abe) => {
    return file
  },
  afterGetTemplate: (text, abe) => {
    return text
  },

  /***************** Page *****************/
  afterAddSourcePage: (json, text, abe) => {
    return json
  },

  beforePageJson: (json, abe) => {
    return json
  }
}

export default hooks
<commit_msg>fix: signature of beforePublish hook was incorrect<commit_after>var hooks = {
  /***************** express *****************/
  beforeExpress: (port, abe) => {
    return port
  },
  afterExpress: (app, express, abe) => {
    return app
  },
  beforeRoute: (req, res, next, abe) => {
    return req
  },
  beforeAddRoute: (router, abe) => {
    return router
  },
  afterAddRoute: (router, abe) => {
    return router
  },

  /***************** preview *****************/
  beforePreview: (html, req, res, next, abe) => {
    return html
  },

  /***************** delete *****************/
  beforeDeleteFile: (filePath, abe) => {
    return filePath
  },
  afterDeleteFile: (path, json, abe) => {
    return path
  },

  /***************** reject *****************/
  beforeReject: (json, filePath, tplPath, abe) => {
    return json
  },
  afterReject: (result, abe) => {
    return result
  },

  /***************** publish *****************/
  beforePublish: (json, filePath, abe) => {
    return json
  },
  afterPublish: (result, filePath, abe) => {
    return result
  },

  /***************** unpublish *****************/
  beforeUnpublish: (filePath, abe) => {
    return filePath
  },
  afterUnpublish: (path, postPath, json, abe) => {
    return path
  },

  /***************** create *****************/
  beforeCreate: (json, postUrl, template, abe) => {
    return json
  },
  afterCreate: (json, text, path, name, req, forceJson, abe) => {
    return json
  },

  /***************** duplicate *****************/
  beforeDuplicate: (oldFilePath, template, path, name, req, deleteFiles, abe) => {
    // if deleteFiles this is an update not a duplicate
    return oldFilePath
  },
  afterDuplicate: (json, oldFilePath, template, path, name, req, deleteFiles, abe) => {
    return json
  },

  /***************** update *****************/
  beforeUpdate: (json, oldFilePath, template, path, name, req, deleteFiles, abe) => {
    return json
  },

  /***************** save *****************/
  beforeFirstSave: (json, body, abe) => {
    return json
  },
  beforeSave: (obj, abe) => {
    return obj
  },
  afterSave: (obj, abe) => {
    return obj
  },
  beforeSaveImage: (folderWebPath, abe) => {
    return folderWebPath
  },
  afterSaveImage: (resp, abe) => {
    return resp
  },
  afterPageSaveCompile: (tmp, json, abe) => {
    return tmp
  },
  afterPageEditorCompile: (tmp, json, abe) => {
    return tmp
  },

  /***************** Manager *****************/
  beforeGetAllFilesDraft: (drafted, abe) => {
    return drafted
  },
  beforeGetAllFilesPublished: (published, abe) => {
    return published
  },
  afterGetAllFiles: (merged, abe) => {
    return merged
  },

  /***************** Editor *****************/
  beforeImport: (file, config, ctx, abe) => {
    return file
  },
  afterImport: (res, file, config, ctx, abe) => {
    return res
  },
  afterHandlebarsHelpers: (Handlebars, abe) => {
    return Handlebars
  },
  beforeEditorInput: (params, abe) => {
    return params
  },
  afterEditorInput: (htmlString, params, abe) => {
    return htmlString
  },

  beforeAbeAttributes: (str, json, abe) => {
    return str
  },
  afterAbeAttributes: (obj, str, json, abe) => {
    return obj
  },
  beforeEditorFormBlocks: (json, text, abe) => {
    return json
  },
  afterEditorFormBlocks: (blocks, json, text, abe) => {
    return blocks
  },
  beforeListPage: (file, index, text) => {
    return file
  },
  afterListPageDraft: (workflow, file, index, text) => {
    return workflow
  },
  afterListPage: (res, file, index, text) => {
    return res
  },
  afterVariables: (EditorVariables, abe) => {
    return EditorVariables
  },

  /***************** json *****************/
  beforeGetJson: (path, abe) => {
    return path
  },
  afterGetJson: (json, abe) => {
    return json
  },
  beforeUpdateJson: (jsonFilesArray, abe) => {
    return jsonFilesArray
  },

  /***************** text *****************/
  beforeGetTemplate: (file, abe) => {
    return file
  },
  afterGetTemplate: (text, abe) => {
    return text
  },

  /***************** Page *****************/
  afterAddSourcePage: (json, text, abe) => {
    return json
  },

  beforePageJson: (json, abe) => {
    return json
  }
}

export default hooks
<|endoftext|>


<commit_before>(function(root, factory) {
    // Set up BaseView appropriately for the environment. Start with AMD.
    if (typeof define === 'function' && define.amd) {
        define(['underscore', 'jquery', 'backbone', 'exports'], function(_, $, Backbone, exports) {
            // Export global even in AMD case in case this script is loaded with
            // others that may still expect a global Backbone.
            root.BaseView = factory(root, exports, _, $, Backbone);
        });
        // Next for Node.js or CommonJS. jQuery may not be needed as a module.
    } else if (typeof exports !== 'undefined') {
        var _ = require('underscore'),
            $ = require('jquery'),
            Backbone = require('backbone');
        factory(root, exports, _, $, Backbone);
        // Finally, as a browser global.
    } else {
        root.BaseView = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$), root.Backbone);
    }
}(this, function(root, BaseView, _, $, Backbone) {

    var BaseView = Backbone.View.extend({

        constructor: function(options) {
            options || (options = {});
            _.extend(this, _.pick(options, viewOptions));
            this.children = options.children || {};
            this.collections = options.collections || {};
            this.models = options.models || {};
            this.setTemplate(this.template || '');
            Backbone.View.apply(this, arguments);
        },

        _ensureElement: function() {
            var el = this.el,
                mid = _.result(this, 'mid'),
                attributes = {};
            Backbone.View.prototype._ensureElement.apply(this, arguments);
            if (el) {
                return;
            }
            attributes['data-cid'] = this.cid;
            if (mid) {
                attributes['data-mid'] = mid;
                this.$el.addClass(this.toClassName(mid));
            }
            this.$el.attr(attributes);
        },

        toClassName: function(className) {
            return className.match(/-?[_a-zA-Z]+[_a-zA-Z0-9-]*/g, '').join('-').replace(/[\/\_]/g, '-').toLowerCase();
        },

        remove: function() {
            Backbone.View.prototype.remove.apply(this, arguments);
            this.invoke('remove');
        },

        compileTemplate: function(str) {
            return _.template(str)
        },

        renderTemplate: function() {
            var interpolated = this.ctemplate.apply(null, arguments);
            this.trigger('render:template', this, interpolated, arguments);
            return interpolated;
        },

        renderTemplateDefer: function() {
            _.defer.apply(null, [this.renderTemplate.bind(this)].concat(Array.prototype.slice.call(arguments)));
        },

        renderTemplateDebounce: function() {
            if (!this._renderTemplateDebounce) {
                this._renderTemplateDebounce = _.debounce(this.renderTemplate.bind(this));
            }
            this._renderTemplateDebounce.apply(this, arguments);
        },

        setTemplate: function(template) {
            this.ctemplate = this.compileTemplate(template);
            this.template = template;
        }

    });

    var array = [];
    var slice = array.slice;

    //List of view options to be merged as properties.
    var viewOptions = ['template', 'mid'];

    var childMethods = ['each', 'where', 'findWhere', 'invoke', 'pluck', 'size', 'keys', 'values', 'pairs', 'pick', 'omit', 'defaults', 'clone', 'tap', 'has', 'propertyOf', 'isEmpty'];
    _.each(childMethods, function(method) {
        if (!_[method]) {
            return;
        }
        BaseView.prototype[method] = function() {
            var args = slice.call(arguments);
            args.unshift(this.children);
            return _[method].apply(_, args);
        };
    });

    return BaseView;
}));
<commit_msg>fix callback arguments; pass parent and child<commit_after>(function(root, factory) {
    // Set up BaseView appropriately for the environment. Start with AMD.
    if (typeof define === 'function' && define.amd) {
        define(['underscore', 'jquery', 'backbone', 'exports'], function(_, $, Backbone, exports) {
            // Export global even in AMD case in case this script is loaded with
            // others that may still expect a global Backbone.
            root.BaseView = factory(root, exports, _, $, Backbone);
        });
        // Next for Node.js or CommonJS. jQuery may not be needed as a module.
    } else if (typeof exports !== 'undefined') {
        var _ = require('underscore'),
            $ = require('jquery'),
            Backbone = require('backbone');
        factory(root, exports, _, $, Backbone);
        // Finally, as a browser global.
    } else {
        root.BaseView = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$), root.Backbone);
    }
}(this, function(root, BaseView, _, $, Backbone) {

    var BaseView = Backbone.View.extend({

        constructor: function(options) {
            options || (options = {});
            _.extend(this, _.pick(options, viewOptions));
            this.children = options.children || {};
            this.collections = options.collections || {};
            this.models = options.models || {};
            this.setTemplate(this.template || '');
            Backbone.View.apply(this, arguments);
        },

        _ensureElement: function() {
            var el = this.el,
                mid = _.result(this, 'mid'),
                attributes = {};
            Backbone.View.prototype._ensureElement.apply(this, arguments);
            if (el) {
                return;
            }
            attributes['data-cid'] = this.cid;
            if (mid) {
                attributes['data-mid'] = mid;
                this.$el.addClass(this.toClassName(mid));
            }
            this.$el.attr(attributes);
        },

        toClassName: function(className) {
            return className.match(/-?[_a-zA-Z]+[_a-zA-Z0-9-]*/g, '').join('-').replace(/[\/\_]/g, '-').toLowerCase();
        },

        remove: function() {
            Backbone.View.prototype.remove.apply(this, arguments);
            this.invoke('remove');
        },

        compileTemplate: function(str) {
            return _.template(str)
        },

        renderTemplate: function() {
            var interpolated = this.ctemplate.apply(null, arguments);
            this.trigger('render:template', this, interpolated, arguments);
            return interpolated;
        },

        renderTemplateDefer: function() {
            _.defer.apply(null, [this.renderTemplate.bind(this)].concat(Array.prototype.slice.call(arguments)));
        },

        renderTemplateDebounce: function() {
            if (!this._renderTemplateDebounce) {
                this._renderTemplateDebounce = _.debounce(this.renderTemplate.bind(this));
            }
            this._renderTemplateDebounce.apply(this, arguments);
        },

        setTemplate: function(template) {
            this.ctemplate = this.compileTemplate(template);
            this.template = template;
        },

        traverse: function(callback, options) {
            options || (options = {});
            var view = options.view || this;
            view.each(function(child) {
                callback.call(this, view, child);
                this.traverse(callback, {view: child});
            }, this);
        }

    });

    var array = [];
    var slice = array.slice;

    //List of view options to be merged as properties.
    var viewOptions = ['template', 'mid'];

    var childMethods = ['each', 'where', 'findWhere', 'invoke', 'pluck', 'size', 'keys', 'values', 'pairs', 'pick', 'omit', 'defaults', 'clone', 'tap', 'has', 'propertyOf', 'isEmpty'];
    _.each(childMethods, function(method) {
        if (!_[method]) {
            return;
        }
        BaseView.prototype[method] = function() {
            var args = slice.call(arguments);
            args.unshift(this.children);
            return _[method].apply(_, args);
        };
    });

    return BaseView;
}));
<|endoftext|>


<commit_before>/* @flow */

import actionTypes from './actionTypes';
import type {
  FluxAction,
  FluxActionWithPreviousIntent,
  FluxActionForRemoval,
  FluxActionForDismissal,
} from './types';

type EnqueuedAction = FluxAction | Function;

export const connectionChange = (isConnected: boolean): FluxAction => ({
  type: actionTypes.CONNECTION_CHANGE,
  payload: isConnected,
});

export const fetchOfflineMode = (
  action: EnqueuedAction,
): FluxActionWithPreviousIntent => {
  if (typeof action === 'object') {
    return {
      type: actionTypes.FETCH_OFFLINE_MODE,
      payload: {
        prevAction: {
          type: action.type,
          payload: action.payload,
        },
      },
      meta: action.meta || {},
    };
  }
  // Thunk
  return {
    type: actionTypes.FETCH_OFFLINE_MODE,
    payload: {
      prevThunk: action,
    },
    meta: action.meta || {},
  };
};

export const removeActionFromQueue = (
  action: EnqueuedAction,
): FluxActionForRemoval => ({
  type: actionTypes.REMOVE_FROM_ACTION_QUEUE,
  payload: action,
});

export const dismissActionsFromQueue = (
  actionTrigger: string,
): FluxActionForDismissal => ({
  type: actionTypes.DISMISS_ACTIONS_FROM_QUEUE,
  payload: actionTrigger,
});
<commit_msg>Support unknown action types (#123)<commit_after>/* @flow */

import actionTypes from './actionTypes';
import type {
  FluxAction,
  FluxActionWithPreviousIntent,
  FluxActionForRemoval,
  FluxActionForDismissal,
} from './types';

type EnqueuedAction = FluxAction | Function;

export const connectionChange = (isConnected: boolean): FluxAction => ({
  type: actionTypes.CONNECTION_CHANGE,
  payload: isConnected,
});

export const fetchOfflineMode = (
  action: EnqueuedAction,
): FluxActionWithPreviousIntent => {
  const { meta = {}, ...actionRest } = action;
  if (typeof action === 'object') {
    return {
      type: actionTypes.FETCH_OFFLINE_MODE,
      payload: {
        prevAction: {
          ...actionRest,
        },
      },
      meta,
    };
  }
  // Thunk
  return {
    type: actionTypes.FETCH_OFFLINE_MODE,
    payload: {
      prevThunk: action,
    },
    meta,
  };
};

export const removeActionFromQueue = (
  action: EnqueuedAction,
): FluxActionForRemoval => ({
  type: actionTypes.REMOVE_FROM_ACTION_QUEUE,
  payload: action,
});

export const dismissActionsFromQueue = (
  actionTrigger: string,
): FluxActionForDismissal => ({
  type: actionTypes.DISMISS_ACTIONS_FROM_QUEUE,
  payload: actionTrigger,
});
<|endoftext|>


<commit_before>/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Control/ZoomBox.js
 * @requires OpenLayers/Control/DragPan.js
 * @requires OpenLayers/Handler/MouseWheel.js
 * @requires OpenLayers/Handler/Click.js
 */

/**
 * Class: OpenLayers.Control.Navigation
 * The navigation control handles map browsing with mouse events (dragging,
 *     double-clicking, and scrolling the wheel).  Create a new navigation
 *     control with the <OpenLayers.Control.Navigation> control.
 *
 *     Note that this control is added to the map by default (if no controls
 *     array is sent in the options object to the <OpenLayers.Map>
 *     constructor).
 *
 * Inherits:
 *  - <OpenLayers.Control>
 */
OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, {

    /**
     * Property: dragPan
     * {<OpenLayers.Control.DragPan>}
     */
    dragPan: null,

    /**
     * Property: zoomBox
     * {<OpenLayers.Control.ZoomBox>}
     */
    zoomBox: null,

    /**
     * Property: wheelHandler
     * {<OpenLayers.Handler.MouseWheel>}
     */
    wheelHandler: null,

    /**
     * Constructor: OpenLayers.Control.Navigation
     * Create a new navigation control
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *                    the control
     */
    initialize: function(options) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
    },

    /**
     * Method: activate
     */
    activate: function() {
        this.dragPan.activate();
        this.wheelHandler.activate();
        this.clickHandler.activate();
        this.zoomBox.activate();
        return OpenLayers.Control.prototype.activate.apply(this,arguments);
    },

    /**
     * Method: deactivate
     */
    deactivate: function() {
        this.zoomBox.deactivate();
        this.dragPan.deactivate();
        this.clickHandler.deactivate();
        this.wheelHandler.deactivate();
        return OpenLayers.Control.prototype.deactivate.apply(this,arguments);
    },

    /**
     * Method: draw
     */
    draw: function() {
        this.clickHandler = new OpenLayers.Handler.Click(this,
                                        { 'dblclick': this.defaultDblClick },
                                        {
                                          'double': true,
                                          'stopDouble': true
                                        });
        this.dragPan = new OpenLayers.Control.DragPan({map: this.map});
        this.zoomBox = new OpenLayers.Control.ZoomBox(
                    {map: this.map, keyMask: OpenLayers.Handler.MOD_SHIFT});
        this.dragPan.draw();
        this.zoomBox.draw();
        this.wheelHandler = new OpenLayers.Handler.MouseWheel(
                                    this, {"up"  : this.wheelUp,
                                           "down": this.wheelDown} );
        this.activate();
    },

    /**
     * Method: defaultDblClick
     *
     * Parameters:
     * evt - {Event}
     */
    defaultDblClick: function (evt) {
        var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
        this.map.setCenter(newCenter, this.map.zoom + 1);
    },

    /**
     * Method: wheelChange
     *
     * Parameters:
     * evt - {Event}
     */
    wheelChange: function(evt, deltaZ) {
        var newZoom = this.map.getZoom() + deltaZ;
        if (!this.map.isValidZoomLevel(newZoom)) {
            return;
        }
        var size    = this.map.getSize();
        var deltaX  = size.w/2 - evt.xy.x;
        var deltaY  = evt.xy.y - size.h/2;
        var newRes  = this.map.baseLayer.resolutions[newZoom];
        var zoomPoint = this.map.getLonLatFromPixel(evt.xy);
        var newCenter = new OpenLayers.LonLat(
                            zoomPoint.lon + deltaX * newRes,
                            zoomPoint.lat + deltaY * newRes );
        this.map.setCenter( newCenter, newZoom );
    },

    /**
     * Method: wheelUp
     * User spun scroll wheel up
     *
     * Parameters:
     * evt - {Event}
     */
    wheelUp: function(evt) {
        this.wheelChange(evt, 1);
    },

    /**
     * Method: wheelDown
     * User spun scroll wheel down
     *
     * Parameters:
     * evt - {Event}
     */
    wheelDown: function(evt) {
        this.wheelChange(evt, -1);
    },

    CLASS_NAME: "OpenLayers.Control.Navigation"
});
<commit_msg>Cleanup after the Navigation control (at least slightly more)<commit_after>/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Control/ZoomBox.js
 * @requires OpenLayers/Control/DragPan.js
 * @requires OpenLayers/Handler/MouseWheel.js
 * @requires OpenLayers/Handler/Click.js
 */

/**
 * Class: OpenLayers.Control.Navigation
 * The navigation control handles map browsing with mouse events (dragging,
 *     double-clicking, and scrolling the wheel).  Create a new navigation
 *     control with the <OpenLayers.Control.Navigation> control.
 *
 *     Note that this control is added to the map by default (if no controls
 *     array is sent in the options object to the <OpenLayers.Map>
 *     constructor).
 *
 * Inherits:
 *  - <OpenLayers.Control>
 */
OpenLayers.Control.Navigation = OpenLayers.Class(OpenLayers.Control, {

    /**
     * Property: dragPan
     * {<OpenLayers.Control.DragPan>}
     */
    dragPan: null,

    /**
     * Property: zoomBox
     * {<OpenLayers.Control.ZoomBox>}
     */
    zoomBox: null,

    /**
     * Property: wheelHandler
     * {<OpenLayers.Handler.MouseWheel>}
     */
    wheelHandler: null,

    /**
     * Constructor: OpenLayers.Control.Navigation
     * Create a new navigation control
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *                    the control
     */
    initialize: function(options) {
        OpenLayers.Control.prototype.initialize.apply(this, arguments);
    },

    /**
     * Method: destroy
     * The destroy method is used to perform any clean up before the control
     * is dereferenced.  Typically this is where event listeners are removed
     * to prevent memory leaks.
     */
    destroy: function() {
        OpenLayers.Control.prototype.destroy.apply(this,arguments);
        this.deactivate();
        this.dragPan.destroy();
        this.wheelHandler.destroy();
        this.clickHandler.destroy();
        this.zoomBox.destroy();
    },

    /**
     * Method: activate
     */
    activate: function() {
        this.dragPan.activate();
        this.wheelHandler.activate();
        this.clickHandler.activate();
        this.zoomBox.activate();
        return OpenLayers.Control.prototype.activate.apply(this,arguments);
    },

    /**
     * Method: deactivate
     */
    deactivate: function() {
        this.zoomBox.deactivate();
        this.dragPan.deactivate();
        this.clickHandler.deactivate();
        this.wheelHandler.deactivate();
        return OpenLayers.Control.prototype.deactivate.apply(this,arguments);
    },

    /**
     * Method: draw
     */
    draw: function() {
        this.clickHandler = new OpenLayers.Handler.Click(this,
                                        { 'dblclick': this.defaultDblClick },
                                        {
                                          'double': true,
                                          'stopDouble': true
                                        });
        this.dragPan = new OpenLayers.Control.DragPan({map: this.map});
        this.zoomBox = new OpenLayers.Control.ZoomBox(
                    {map: this.map, keyMask: OpenLayers.Handler.MOD_SHIFT});
        this.dragPan.draw();
        this.zoomBox.draw();
        this.wheelHandler = new OpenLayers.Handler.MouseWheel(
                                    this, {"up"  : this.wheelUp,
                                           "down": this.wheelDown} );
        this.activate();
    },

    /**
     * Method: defaultDblClick
     *
     * Parameters:
     * evt - {Event}
     */
    defaultDblClick: function (evt) {
        var newCenter = this.map.getLonLatFromViewPortPx( evt.xy );
        this.map.setCenter(newCenter, this.map.zoom + 1);
    },

    /**
     * Method: wheelChange
     *
     * Parameters:
     * evt - {Event}
     */
    wheelChange: function(evt, deltaZ) {
        var newZoom = this.map.getZoom() + deltaZ;
        if (!this.map.isValidZoomLevel(newZoom)) {
            return;
        }
        var size    = this.map.getSize();
        var deltaX  = size.w/2 - evt.xy.x;
        var deltaY  = evt.xy.y - size.h/2;
        var newRes  = this.map.baseLayer.resolutions[newZoom];
        var zoomPoint = this.map.getLonLatFromPixel(evt.xy);
        var newCenter = new OpenLayers.LonLat(
                            zoomPoint.lon + deltaX * newRes,
                            zoomPoint.lat + deltaY * newRes );
        this.map.setCenter( newCenter, newZoom );
    },

    /**
     * Method: wheelUp
     * User spun scroll wheel up
     *
     * Parameters:
     * evt - {Event}
     */
    wheelUp: function(evt) {
        this.wheelChange(evt, 1);
    },

    /**
     * Method: wheelDown
     * User spun scroll wheel down
     *
     * Parameters:
     * evt - {Event}
     */
    wheelDown: function(evt) {
        this.wheelChange(evt, -1);
    },

    CLASS_NAME: "OpenLayers.Control.Navigation"
});
<|endoftext|>