<commit_before>if (typeof(require) !== 'undefined') { var tree = require('less/tree') }

tree.Rule = function Rule(name, value) {
    this.name = name;
    this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]);

    if (name.charAt(0) === '@') {
        this.variable = true;
    } else { this.variable = false }
};
tree.Rule.prototype.toCSS = function (env) {
    if (this.variable) { return "" }
    else {
        return this.name + ": " +
              (this.value.toCSS ? this.value.toCSS(env) : this.value) + ";";
    }
};

tree.Rule.prototype.eval = function (context) {
    return new(tree.Rule)(this.name, this.value.eval(context));
};

tree.Value = function Value(value) {
    this.value = value;
    this.is = 'value';
};
tree.Value.prototype = {
    eval: function (env) {
        if (this.value.length === 1) {
            return this.value[0].eval ? this.value[0].eval(env)
                                      : this.value[0];
        } else {
            return this;
        }
    },
    toCSS: function (env) {
        return this.value.map(function (e) {
            return e.toCSS ? e.toCSS(env) : e;
        }).join(', ');
    }
};

tree.Shorthand = function Shorthand(a, b) {
    this.a = a;
    this.b = b;
};

tree.Shorthand.prototype = {
    toCSS: function (env) {
        return this.a.toCSS(env) + "/" + this.b.toCSS(env);
    }
};
<commit_msg>evaluate Values of length > 1 properly<commit_after>if (typeof(require) !== 'undefined') { var tree = require('less/tree') }

tree.Rule = function Rule(name, value) {
    this.name = name;
    this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]);

    if (name.charAt(0) === '@') {
        this.variable = true;
    } else { this.variable = false }
};
tree.Rule.prototype.toCSS = function (env) {
    if (this.variable) { return "" }
    else {
        return this.name + ": " +
              (this.value.toCSS ? this.value.toCSS(env) : this.value) + ";";
    }
};

tree.Rule.prototype.eval = function (context) {
    return new(tree.Rule)(this.name, this.value.eval(context));
};

tree.Value = function Value(value) {
    this.value = value;
    this.is = 'value';
};
tree.Value.prototype = {
    eval: function (env) {
        if (this.value.length === 1) {
            return this.value[0].eval ? this.value[0].eval(env)
                                      : this.value[0];
        } else {
            return new(tree.Value)(this.value.map(function (v) {
                return v.eval(env);
            }));
        }
    },
    toCSS: function (env) {
        return this.value.map(function (e) {
            return e.toCSS ? e.toCSS(env) : e;
        }).join(', ');
    }
};

tree.Shorthand = function Shorthand(a, b) {
    this.a = a;
    this.b = b;
};

tree.Shorthand.prototype = {
    toCSS: function (env) {
        return this.a.toCSS(env) + "/" + this.b.toCSS(env);
    }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import axios from 'axios';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recentCampers: [],
      allTimeCampers: [],
      currentView: 'recentCampers'
    };
  }
  componentWillMount() {
    axios.all([this.fetchRecentCampers(), this.fetchAllTimCampers()])
      .then(axios.spread(function(recentCampers, allTimeCampers) {
        this.setState({ recentCampers, allTimeCampers });
      }));
  }

  fetchRecentCampers() {
    return axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent');
  }
  fetchAllTimCampers() {
    return axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/alltime');
  }
  changeView(currentView) {
    this.setState({ currentView });
  }

  render() {
    return (

{`Viewing Top ${this.state.currentView}`}

        <button onClick={() => this.changeView('recentCampers')} className="btn btn-primary">Recent</button>
        <button onClick={() => this.changeView('allTimeCampers')} className="btn btn-primary">All Time</button>

    );
  }
}
<commit_msg>Fixed anon function to ES6 fat arrow function<commit_after>import React, { Component } from 'react';
import axios from 'axios';

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recentCampers: [],
      allTimeCampers: [],
      currentView: 'recentCampers'
    };
  }
  componentWillMount() {
    axios.all([this.fetchRecentCampers(), this.fetchAllTimCampers()])
      .then(axios.spread((recentCampers, allTimeCampers) => {
        this.setState({ recentCampers, allTimeCampers });
      }));
  }

  fetchRecentCampers() {
    return axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent');
  }
  fetchAllTimCampers() {
    return axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/alltime');
  }
  changeView(currentView) {
    this.setState({ currentView  });
  }

  render() {
    return (

{`Viewing Top ${this.state.currentView}`}

        <button onClick={() => this.changeView('recentCampers')} className="btn btn-primary">Recent</button>
        <button onClick={() => this.changeView('allTimeCampers')} className="btn btn-primary">All Time</button>

    );
  }
}
<|endoftext|>


<commit_before>/**
 * Exports array that contains questions for prompting.
 * The array with questions is an array of Inquirer prompt objects - https://github.com/SBoudrias/Inquirer.js#prompts-type
 *
 * @example
 * export default [{
 *   type: 'input',
 *   name: 'inputName',
 *   message: 'Message for the input'
 * }];
 */

export default [{
  type: 'input',
  name: 'app:name',
  message: 'Application name',
  default: 'sails-rest-api'
}];
<commit_msg>changed default app name<commit_after>/**
 * Exports array that contains questions for prompting.
 * The array with questions is an array of Inquirer prompt objects - https://github.com/SBoudrias/Inquirer.js#prompts-type
 *
 * @example
 * export default [{
 *   type: 'input',
 *   name: 'inputName',
 *   message: 'Message for the input'
 * }];
 */

export default [{
  type: 'input',
  name: 'app:name',
  message: 'Application name',
  default: 'my-trails-app'
}];
<|endoftext|>


<commit_before>const jsonValidator = require('json-dup-key-validator');

const { mergeChildConfig } = require('../../../config');
const { migrateAndValidate } = require('../../../config/migrate-validate');
const { decryptConfig } = require('../../../config/decrypt');
const presets = require('../../../config/presets');

// Check for config in `renovate.json`
async function mergeRenovateConfig(config) {
  let returnConfig = { ...config };
  // istanbul ignore if
  if (config.mirrorMode) {
    logger.info('Repository is in mirror mode');
    const renovateJson = JSON.parse(
      await platform.getFile(
        'renovate.json',
        config.repoIsOnboarded ? 'renovate-config' : 'renovate/configure'
      )
    );
    logger.debug({ renovateJson }, 'mirrorMode config');
    const migratedConfig = migrateAndValidate(config, renovateJson);
    const resolvedConfig = await presets.resolveConfigPresets(migratedConfig);
    returnConfig = mergeChildConfig(returnConfig, resolvedConfig);
    returnConfig.renovateJsonPresent = true;
    return returnConfig;
  }
  const fileList = await platform.getFileList();
  let configFile;
  if (fileList.includes('renovate.json')) {
    configFile = 'renovate.json';
  } else if (fileList.includes('.renovaterc')) {
    configFile = '.renovaterc';
  } else if (fileList.includes('.renovaterc.json')) {
    configFile = '.renovaterc.json';
  } else if (fileList.includes('package.json')) {
    try {
      const pJson = JSON.parse(await platform.getFile('package.json'));
      if (pJson.renovate) {
        logger.info('Using package.json for global renovate config');
        configFile = 'package.json';
      }
    } catch (err) {
      // Do nothing
    }
  }
  if (!configFile) {
    logger.debug('No renovate config file found');
    return returnConfig;
  }
  logger.debug(`Found ${configFile} config file`);
  let renovateJson;
  if (configFile === 'package.json') {
    // We already know it parses
    renovateJson = JSON.parse(await platform.getFile('package.json')).renovate;
    logger.info({ config: renovateJson }, 'package.json>renovate config');
  } else {
    const renovateConfig = await platform.getFile(configFile);
    let allowDuplicateKeys = true;
    let jsonValidationError = jsonValidator.validate(
      renovateConfig,
      allowDuplicateKeys
    );
    if (jsonValidationError) {
      const error = new Error('config-validation');
      error.configFile = configFile;
      error.validationError = 'Invalid JSON (parsing failed)';
      error.validationMessage = jsonValidationError;
      throw error;
    }
    allowDuplicateKeys = false;
    jsonValidationError = jsonValidator.validate(
      renovateConfig,
      allowDuplicateKeys
    );
    if (jsonValidationError) {
      const error = new Error('config-validation');
      error.configFile = configFile;
      error.validationError = 'Duplicate keys in JSON';
      error.validationMessage = JSON.stringify(jsonValidationError);
      throw error;
    }
    renovateJson = JSON.parse(renovateConfig);
    logger.info({ config: renovateJson }, 'renovate.json config');
  }
  const migratedConfig = migrateAndValidate(config, renovateJson);
  if (migratedConfig.errors.length) {
    const error = new Error('config-validation');
    error.configFile = configFile;
    error.validationError =
      'The renovate configuration file contains some invalid settings';
    error.validationMessage = migratedConfig.errors
      .map(e => e.message)
      .join(', ');
    throw error;
  }
  delete migratedConfig.errors;
  delete migratedConfig.warnings;
  logger.debug({ config: migratedConfig }, 'renovate.json migrated config');
  const decryptedConfig = decryptConfig(migratedConfig, config.privateKey);
  const resolvedConfig = await presets.resolveConfigPresets(decryptedConfig);
  logger.trace({ config: resolvedConfig }, 'renovate.json resolved config');
  returnConfig = mergeChildConfig(returnConfig, resolvedConfig);
  returnConfig.renovateJsonPresent = true;
  return returnConfig;
}

module.exports = {
  mergeRenovateConfig,
};
<commit_msg>fix: perform additional decrypt after preset resolve<commit_after>const jsonValidator = require('json-dup-key-validator');

const { mergeChildConfig } = require('../../../config');
const { migrateAndValidate } = require('../../../config/migrate-validate');
const { decryptConfig } = require('../../../config/decrypt');
const presets = require('../../../config/presets');

// Check for config in `renovate.json`
async function mergeRenovateConfig(config) {
  let returnConfig = { ...config };
  // istanbul ignore if
  if (config.mirrorMode) {
    logger.info('Repository is in mirror mode');
    const renovateJson = JSON.parse(
      await platform.getFile(
        'renovate.json',
        config.repoIsOnboarded ? 'renovate-config' : 'renovate/configure'
      )
    );
    logger.debug({ renovateJson }, 'mirrorMode config');
    const migratedConfig = migrateAndValidate(config, renovateJson);
    const resolvedConfig = await presets.resolveConfigPresets(migratedConfig);
    returnConfig = mergeChildConfig(returnConfig, resolvedConfig);
    returnConfig.renovateJsonPresent = true;
    return returnConfig;
  }
  const fileList = await platform.getFileList();
  let configFile;
  if (fileList.includes('renovate.json')) {
    configFile = 'renovate.json';
  } else if (fileList.includes('.renovaterc')) {
    configFile = '.renovaterc';
  } else if (fileList.includes('.renovaterc.json')) {
    configFile = '.renovaterc.json';
  } else if (fileList.includes('package.json')) {
    try {
      const pJson = JSON.parse(await platform.getFile('package.json'));
      if (pJson.renovate) {
        logger.info('Using package.json for global renovate config');
        configFile = 'package.json';
      }
    } catch (err) {
      // Do nothing
    }
  }
  if (!configFile) {
    logger.debug('No renovate config file found');
    return returnConfig;
  }
  logger.debug(`Found ${configFile} config file`);
  let renovateJson;
  if (configFile === 'package.json') {
    // We already know it parses
    renovateJson = JSON.parse(await platform.getFile('package.json')).renovate;
    logger.info({ config: renovateJson }, 'package.json>renovate config');
  } else {
    const renovateConfig = await platform.getFile(configFile);
    let allowDuplicateKeys = true;
    let jsonValidationError = jsonValidator.validate(
      renovateConfig,
      allowDuplicateKeys
    );
    if (jsonValidationError) {
      const error = new Error('config-validation');
      error.configFile = configFile;
      error.validationError = 'Invalid JSON (parsing failed)';
      error.validationMessage = jsonValidationError;
      throw error;
    }
    allowDuplicateKeys = false;
    jsonValidationError = jsonValidator.validate(
      renovateConfig,
      allowDuplicateKeys
    );
    if (jsonValidationError) {
      const error = new Error('config-validation');
      error.configFile = configFile;
      error.validationError = 'Duplicate keys in JSON';
      error.validationMessage = JSON.stringify(jsonValidationError);
      throw error;
    }
    renovateJson = JSON.parse(renovateConfig);
    logger.info({ config: renovateJson }, 'renovate.json config');
  }
  const migratedConfig = migrateAndValidate(config, renovateJson);
  if (migratedConfig.errors.length) {
    const error = new Error('config-validation');
    error.configFile = configFile;
    error.validationError =
      'The renovate configuration file contains some invalid settings';
    error.validationMessage = migratedConfig.errors
      .map(e => e.message)
      .join(', ');
    throw error;
  }
  delete migratedConfig.errors;
  delete migratedConfig.warnings;
  logger.debug({ config: migratedConfig }, 'renovate.json migrated config');
  // Decrypt before resolving in case we need npm authentication for any presets
  const decryptedConfig = decryptConfig(migratedConfig, config.privateKey);
  // Decrypt after resolving in case the preset contains npm authentication instead
  const resolvedConfig = decryptConfig(
    await presets.resolveConfigPresets(decryptedConfig),
    config.privateKey
  );
  logger.trace({ config: resolvedConfig }, 'renovate.json resolved config');
  returnConfig = mergeChildConfig(returnConfig, resolvedConfig);
  returnConfig.renovateJsonPresent = true;
  return returnConfig;
}

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


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50, forin: true */
/*global $, define, brackets */

/**
 * A Jasmine reporter that summarizes test results data:
 *  - summarizes the results for each top-level suite (instead of flattening out all suites)
 *  - counts the number of passed/failed specs instead of counting each expect()
 *  - tracks performance data for tests that want to log it
 * and rebroadcasts the summarized results to the reporter view, as well as serializing the data
 * to JSON.
 */

define(function (require, exports, module) {
    "use strict";

    var UrlParams = require("utils/UrlParams").UrlParams,
        SpecRunnerUtils = require("spec/SpecRunnerUtils"),
        Global = require("utils/Global"),
        BuildInfoUtils = require("utils/BuildInfoUtils");

    var activeReporter;

    /**
     * @constructor
     * Creates a UnitTestReporter object. This has a number public properties:
     *
     * suites - an object with entries for each top-level suite; each value is an object containing:
     *    name - the full name of the suite
     *    specCount - number of specs in the suite and its descendants
     *    passedCount - number of passed specs in the suite and its descendants
     *    failedCount - number of failed specs in the suite and its descendants
     *    specs - an array of results for each spec; each result is an object containing:
     *        name - the full name of the spec
     *        passed - true if the spec passed, false otherwise
     *        messages - if defined, an array of message objects for the failed spec
     *        perf - if defined, the performance record for the spec
     *
     * passed - true if all specs passed, false otherwise
     * sortedNames - a sorted list of suite names (including all the keys in the suites object except All).
     * activeSuite - the suite currently selected in the URL params, or null if all are being run
     * activeSpecCount - the number of specs that will actually be run given the current filter
     * activeSpecCompleteCount - the number of specs that have been run so far
     * totalSpecCount - the total number of specs (ignoring filter)
     * totalPassedCount - the total number of specs passed across all suites
     * totalFailedCount - the total number of specs failed across all suites
     *
     * runInfo - an object containing info about the current run:
     *     app - name of the app
     *     version - version number
     *     branch - branch the current build is running on
     *     sha - sha of the current build
     *     platform - platform of the current run
     *     startTime - time the run was started
     *     endTime - time the run finished
     *
     * @param {!Object} env The Jasmine environment we're running in.
     * @param {Function} filter The filter being used to determine whether a given spec is run or not.
     * @param {string} activeSuite The suite currently selected in the URL params, or null if all are being run.
     */
    function UnitTestReporter(env, filter, activeSuite) {
        var self = this;

        this.activeSuite = activeSuite;

        this.runInfo = {
            app: brackets.metadata.name,
            version: brackets.metadata.version,
            platform: brackets.platform
        };
        BuildInfoUtils.getBracketsSHA().done(function (branch, sha) {
            self.runInfo.branch = branch;
            self.runInfo.sha = sha;
        });

        // _topLevelFilter is applied first - selects Performance vs. Unit test suites
        this._topLevelFilter = filter;

        // Jasmine's runner uses the specFilter to choose which tests to run.
        // If you selected an option other than "All" this will be a subset of all tests loaded.
        env.specFilter = this._createSpecFilter(this.activeSuite);

        this.suites = {};
        this.passed = false;

        this.totalSpecCount = 0;
        this.totalPassedCount = 0;
        this.totalFailedCount = 0;
        env.currentRunner().topLevelSuites().forEach(function (suite) {
            var specCount = self._countSpecs(suite, filter);
            self.suites[suite.getFullName()] = {
                id: suite.id,
                name: suite.getFullName(),
                specCount: specCount,
                passedCount: 0,
                failedCount: 0,
                specs: []
            };
            self.totalSpecCount += specCount;
        });

        this.sortedNames = Object.keys(this.suites).sort(function (a, b) {
            a = a.toLowerCase();
            b = b.toLowerCase();
            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            }
            return 0;
        });

        this.activeSpecCount = 0;
        this.activeSpecCompleteCount = 0;

        env.currentRunner().specs().forEach(function (spec, index) {
            if (env.specFilter(spec)) {
                self.activeSpecCount++;
            }
        });
    }

    /**
     * @private
     * Filters specs by full name. Applies _topLevelFilter first before checking
     * for a matching starting substring.
     */
    UnitTestReporter.prototype._createSpecFilter = function (filterString) {
        var self = this,
            filter = filterString ? filterString.toLowerCase() : undefined;

        return function (spec) {
            // filterString is undefined when no top-level suite is active (e.g. "All", "HTMLUtils", etc.)
            // When undefined, all specs fail this filter and no tests are ran. This is by design.
            // This setup allows the SpecRunner to load initially without automatically running all tests.
            if (filter === undefined) {
                return false;
            }

            if (!self._topLevelFilter(spec)) {
                return false;
            }

            if (filter === "all") {
                return true;
            }

            if (filter === spec.getFullName().toLowerCase()) {
                return true;
            }

            // spec.getFullName() concatenates the names of all containing describe()s. We want to filter
            // on just the outermost suite's name (i.e., the item that was selected in the spec list UI)
            // to avoid ambiguity when suite names share the same prefix.
            var topLevelSuite = spec.suite;
            while (topLevelSuite.parentSuite) {
                topLevelSuite = topLevelSuite.parentSuite;
            }

            return filter === topLevelSuite.description.toLowerCase();
        };
    };

    /**
     * @private
     *
     * @param {!jasmine.Suite} suite
     * @param {Function} filter
     * @return {Number} count The number of specs in the given suite (and its descendants) that match the filter.
     */
    UnitTestReporter.prototype._countSpecs = function (suite, filter) {
        var count = 0,
            self = this;

        // count specs attached directly to this suite
        suite.specs().forEach(function (spec) {
            if (!filter || filter(spec)) {
                count++;
            }
        });

        // recursively count child suites
        suite.suites().forEach(function (child) {
            count += self._countSpecs(child, filter);
        });

        return count;
    };

    /**
     * Returns the name of the top-level suite containing the given spec.
     * @param {!jasmine.Spec} spec
     * @return {string} the top level suite name
     */
    UnitTestReporter.prototype.getTopLevelSuiteName = function (spec) {
        var topLevelSuite = spec.suite;

        while (topLevelSuite.parentSuite) {
            topLevelSuite = topLevelSuite.parentSuite;
        }

        return topLevelSuite.getFullName();
    };

    /**
     * @private
     * Adds the passed/failed counts and failure messages for the given spec to the data for its top level suite,
     * and updates the total counts on the All record.
     * @param {!jasmine.Spec} spec The spec to record
     * @param {Object} results Jasmine result object for that spec
     * @return {Object} the spec data for the given spec, listing whether it passed and any
     * messages/perf data
     */
    UnitTestReporter.prototype._addSpecResults = function (spec, results, perfRecord) {
        var suiteData = this.suites[this.getTopLevelSuiteName(spec)],
            specData = {
                name: spec.getFullName(),
                description: spec.description,
                passed: results.passed()
            };

        this.activeSpecCompleteCount++;

        if (specData.passed) {
            suiteData.passedCount++;
            this.totalPassedCount++;
        } else {
            suiteData.failedCount++;
            this.totalFailedCount++;
        }

        results.getItems().forEach(function (item) {
            var message = SpecRunnerUtils.getResultMessage(item);
            if (message) {
                specData.messages = specData.messages || [];
                specData.messages.push(message);
            }
        });

        if (perfRecord && perfRecord.length) {
            specData.perf = perfRecord;
        }

        suiteData.specs.push(specData);
        return specData;
    };

    /**
     * Returns a JSON string containing all our public data. See the constructor
     * docs for a list.
     * @return {string} the JSON string
     */
    UnitTestReporter.prototype.toJSON = function () {
        var data = {}, prop;
        for (prop in this) {
            if (this.hasOwnProperty(prop) && prop.charAt(0) !== "_") {
                data[prop] = this[prop];
            }
        }
        return JSON.stringify(data, null, "    ");
    };

    // Handlers for Jasmine callback functions

    UnitTestReporter.prototype.reportRunnerStarting = function (runner) {
        activeReporter = this;
        this.runInfo.startTime = new Date().toString();
        $(this).triggerHandler("runnerStart", [this]);
    };

    UnitTestReporter.prototype.reportRunnerResults = function (runner) {
        this.passed = runner.results().passed();
        this.runInfo.endTime = new Date().toString();
        $(this).triggerHandler("runnerEnd", [this]);
        activeReporter = null;
    };

    UnitTestReporter.prototype.reportSuiteResults = function (suite) {
        if (suite.parentSuite === null) {
            $(this).triggerHandler("suiteEnd", [this, this.suites[suite.getFullName()]]);
        }
    };

    /**
     * @private
     * @param {!Object} spec the Jasmine spec to find the category for
     * @return {string} the category for the given spec, or null if it has no category
     */
    UnitTestReporter.prototype._getCategory = function (spec) {
        if (spec.category) {
            return spec.category;
        } else {
            var suite = spec.suite;
            while (suite) {
                if (suite.category) {
                    return suite.category;
                }
                suite = suite.parentSuite;
            }
        }
        return null;
    };

    UnitTestReporter.prototype.reportSpecStarting = function (spec) {
        if (this._getCategory(spec) === "performance") {
            this._currentPerfRecord = [];
        }
        $(this).triggerHandler("specStart", [this, spec.getFullName()]);
    };

    UnitTestReporter.prototype.reportSpecResults = function (spec) {
        if (!spec.results().skipped) {
            var specData = this._addSpecResults(spec, spec.results(), this._currentPerfRecord);
            $(this).triggerHandler("specEnd", [this, specData, this.suites[this.getTopLevelSuiteName(spec)]]);
        }
        this._currentPerfRecord = null;
    };

    // Performance tracking

    UnitTestReporter.prototype._getTestWindowPerf = function () {
        return SpecRunnerUtils.getTestWindow().brackets.test.PerfUtils;
    };

    UnitTestReporter.prototype._logTestWindowMeasurement = function (measureInfo) {
        var value,
            printName = measureInfo.measure.name || measureInfo.name,
            record = {},
            self = this;

        if (measureInfo.measure instanceof RegExp) {
            value = this._currentPerfUtils.searchData(measureInfo.measure);
        } else {
            value = this._currentPerfUtils.getData(measureInfo.measure.id);
        }

        if (value === undefined) {
            value = "(None)";
        }

        if (measureInfo.measure.name && measureInfo.name) {
            printName = measureInfo.measure.name + " - " + measureInfo.name;
        }

        if (measureInfo.operation === "sum") {
            if (Array.isArray(value)) {
                value = value.reduce(function (a, b) { return a + b; });
            }

            printName = "Sum of all " + printName;
        }

        record.name = printName;
        record.value = value;

        if (measureInfo.children) {
            record.children = [];
            measureInfo.children.forEach(function (child) {
                record.children.push(self._logTestWindowMeasurement(child));
            });
        }

        return record;
    };

    /**
     * Records a performance measurement from the test window for the current running spec.
     * @param {!(PerfMeasurement|string)} measure A PerfMeasurement or string key to query PerfUtils for metrics.
     * @param {string} name An optional name or description to print with the measurement name
     * @param {string} operation An optional operation to perform on the measurement data. Currently supports sum.
     */
    UnitTestReporter.prototype.logTestWindow = function (measures, name, operation) {
        var self = this;

        if (!this._currentPerfRecord) {
            return;
        }

        this._currentPerfUtils = this._getTestWindowPerf();

        if (!Array.isArray(measures)) {
            measures = [{measure: measures, name: name, operation: operation}];
        }

        measures.forEach(function (measure) {
            self._currentPerfRecord.push(self._logTestWindowMeasurement(measure));
        });

        this._currentPerfUtils = null;
    };

    /**
     * Clears the current set of performance measurements.
     */
    UnitTestReporter.prototype.clearTestWindow = function () {
        this._getTestWindowPerf().clear();
    };

    /**
     * @return The active unit test reporter, or null if no unit test is running.
     */
    function getActiveReporter() {
        return activeReporter;
    }

    // Exports

    exports.UnitTestReporter = UnitTestReporter;
    exports.getActiveReporter = getActiveReporter;
});<commit_msg>code review comments<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50, forin: true */
/*global $, define, brackets */

/**
 * A Jasmine reporter that summarizes test results data:
 *  - summarizes the results for each top-level suite (instead of flattening out all suites)
 *  - counts the number of passed/failed specs instead of counting each expect()
 *  - tracks performance data for tests that want to log it
 * and rebroadcasts the summarized results to the reporter view, as well as serializing the data
 * to JSON.
 */

define(function (require, exports, module) {
    "use strict";

    var SpecRunnerUtils = require("spec/SpecRunnerUtils"),
        Global = require("utils/Global"),
        BuildInfoUtils = require("utils/BuildInfoUtils");

    var activeReporter;

    /**
     * @constructor
     * Creates a UnitTestReporter object. This has a number public properties:
     *
     * suites - an object with entries for each top-level suite; each value is an object containing:
     *    name - the full name of the suite
     *    specCount - number of specs in the suite and its descendants
     *    passedCount - number of passed specs in the suite and its descendants
     *    failedCount - number of failed specs in the suite and its descendants
     *    specs - an array of results for each spec; each result is an object containing:
     *        name - the full name of the spec
     *        passed - true if the spec passed, false otherwise
     *        messages - if defined, an array of message objects for the failed spec
     *        perf - if defined, the performance record for the spec
     *
     * passed - true if all specs passed, false otherwise
     * sortedNames - a sorted list of suite names (including all the keys in the suites object except All).
     * activeSuite - the suite currently selected in the URL params, "all" if all are being run, and null if no tests are being run.
     * activeSpecCount - the number of specs that will actually be run given the current filter
     * activeSpecCompleteCount - the number of specs that have been run so far
     * totalSpecCount - the total number of specs (ignoring filter)
     * totalPassedCount - the total number of specs passed across all suites
     * totalFailedCount - the total number of specs failed across all suites
     *
     * runInfo - an object containing info about the current run:
     *     app - name of the app
     *     version - version number
     *     branch - branch the current build is running on
     *     sha - sha of the current build
     *     platform - platform of the current run
     *     startTime - time the run was started
     *     endTime - time the run finished
     *
     * @param {!Object} env The Jasmine environment we're running in.
     * @param {Function} filter The filter being used to determine whether a given spec is run or not.
     * @param {string} activeSuite The suite currently selected in the URL params, or null if all are being run.
     */
    function UnitTestReporter(env, filter, activeSuite) {
        var self = this;

        this.activeSuite = activeSuite;

        this.runInfo = {
            app: brackets.metadata.name,
            version: brackets.metadata.version,
            platform: brackets.platform
        };
        BuildInfoUtils.getBracketsSHA().done(function (branch, sha) {
            self.runInfo.branch = branch;
            self.runInfo.sha = sha;
        });

        // _topLevelFilter is applied first - selects Performance vs. Unit test suites
        this._topLevelFilter = filter;

        // Jasmine's runner uses the specFilter to choose which tests to run.
        // If you selected an option other than "All" this will be a subset of all tests loaded.
        env.specFilter = this._createSpecFilter(this.activeSuite);

        this.suites = {};
        this.passed = false;

        this.totalSpecCount = 0;
        this.totalPassedCount = 0;
        this.totalFailedCount = 0;
        env.currentRunner().topLevelSuites().forEach(function (suite) {
            var specCount = self._countSpecs(suite, filter);
            self.suites[suite.getFullName()] = {
                id: suite.id,
                name: suite.getFullName(),
                specCount: specCount,
                passedCount: 0,
                failedCount: 0,
                specs: []
            };
            self.totalSpecCount += specCount;
        });

        this.sortedNames = Object.keys(this.suites).sort(function (a, b) {
            a = a.toLowerCase();
            b = b.toLowerCase();
            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            }
            return 0;
        });

        this.activeSpecCount = 0;
        this.activeSpecCompleteCount = 0;

        env.currentRunner().specs().forEach(function (spec, index) {
            if (env.specFilter(spec)) {
                self.activeSpecCount++;
            }
        });
    }

    /**
     * @private
     * Filters specs by full name. Applies _topLevelFilter first before checking
     * for a matching starting substring.
     */
    UnitTestReporter.prototype._createSpecFilter = function (filterString) {
        var self = this,
            filter = filterString ? filterString.toLowerCase() : undefined;

        return function (spec) {
            // filterString is undefined when no top-level suite is active (e.g. "All", "HTMLUtils", etc.)
            // When undefined, all specs fail this filter and no tests are ran. This is by design.
            // This setup allows the SpecRunner to load initially without automatically running all tests.
            if (filter === undefined) {
                return false;
            }

            if (!self._topLevelFilter(spec)) {
                return false;
            }

            if (filter === "all") {
                return true;
            }

            if (filter === spec.getFullName().toLowerCase()) {
                return true;
            }

            // spec.getFullName() concatenates the names of all containing describe()s. We want to filter
            // on just the outermost suite's name (i.e., the item that was selected in the spec list UI)
            // to avoid ambiguity when suite names share the same prefix.
            var topLevelSuite = spec.suite;
            while (topLevelSuite.parentSuite) {
                topLevelSuite = topLevelSuite.parentSuite;
            }

            return filter === topLevelSuite.description.toLowerCase();
        };
    };

    /**
     * @private
     *
     * @param {!jasmine.Suite} suite
     * @param {Function} filter
     * @return {Number} count The number of specs in the given suite (and its descendants) that match the filter.
     */
    UnitTestReporter.prototype._countSpecs = function (suite, filter) {
        var count = 0,
            self = this;

        // count specs attached directly to this suite
        suite.specs().forEach(function (spec) {
            if (!filter || filter(spec)) {
                count++;
            }
        });

        // recursively count child suites
        suite.suites().forEach(function (child) {
            count += self._countSpecs(child, filter);
        });

        return count;
    };

    /**
     * Returns the name of the top-level suite containing the given spec.
     * @param {!jasmine.Spec} spec
     * @return {string} the top level suite name
     */
    UnitTestReporter.prototype.getTopLevelSuiteName = function (spec) {
        var topLevelSuite = spec.suite;

        while (topLevelSuite.parentSuite) {
            topLevelSuite = topLevelSuite.parentSuite;
        }

        return topLevelSuite.getFullName();
    };

    /**
     * @private
     * Adds the passed/failed counts and failure messages for the given spec to the data for its top level suite,
     * and updates the total counts on the All record.
     * @param {!jasmine.Spec} spec The spec to record
     * @param {Object} results Jasmine result object for that spec
     * @return {Object} the spec data for the given spec, listing whether it passed and any
     * messages/perf data
     */
    UnitTestReporter.prototype._addSpecResults = function (spec, results, perfRecord) {
        var suiteData = this.suites[this.getTopLevelSuiteName(spec)],
            specData = {
                name: spec.getFullName(),
                description: spec.description,
                passed: results.passed()
            };

        this.activeSpecCompleteCount++;

        if (specData.passed) {
            suiteData.passedCount++;
            this.totalPassedCount++;
        } else {
            suiteData.failedCount++;
            this.totalFailedCount++;
        }

        results.getItems().forEach(function (item) {
            var message = SpecRunnerUtils.getResultMessage(item);
            if (message) {
                specData.messages = specData.messages || [];
                specData.messages.push(message);
            }
        });

        if (perfRecord && perfRecord.length) {
            specData.perf = perfRecord;
        }

        suiteData.specs.push(specData);
        return specData;
    };

    /**
     * Returns a JSON string containing all our public data. See the constructor
     * docs for a list.
     * @return {string} the JSON string
     */
    UnitTestReporter.prototype.toJSON = function () {
        var data = {}, prop;
        for (prop in this) {
            if (this.hasOwnProperty(prop) && prop.charAt(0) !== "_") {
                data[prop] = this[prop];
            }
        }
        return JSON.stringify(data, null, "    ");
    };

    // Handlers for Jasmine callback functions

    UnitTestReporter.prototype.reportRunnerStarting = function (runner) {
        activeReporter = this;
        this.runInfo.startTime = new Date().toString();
        $(this).triggerHandler("runnerStart", [this]);
    };

    UnitTestReporter.prototype.reportRunnerResults = function (runner) {
        this.passed = runner.results().passed();
        this.runInfo.endTime = new Date().toString();
        $(this).triggerHandler("runnerEnd", [this]);
        activeReporter = null;
    };

    UnitTestReporter.prototype.reportSuiteResults = function (suite) {
        if (suite.parentSuite === null) {
            $(this).triggerHandler("suiteEnd", [this, this.suites[suite.getFullName()]]);
        }
    };

    /**
     * @private
     * @param {!Object} spec the Jasmine spec to find the category for
     * @return {string} the category for the given spec, or null if it has no category
     */
    UnitTestReporter.prototype._getCategory = function (spec) {
        if (spec.category) {
            return spec.category;
        } else {
            var suite = spec.suite;
            while (suite) {
                if (suite.category) {
                    return suite.category;
                }
                suite = suite.parentSuite;
            }
        }
        return null;
    };

    UnitTestReporter.prototype.reportSpecStarting = function (spec) {
        if (this._getCategory(spec) === "performance") {
            this._currentPerfRecord = [];
        }
        $(this).triggerHandler("specStart", [this, spec.getFullName()]);
    };

    UnitTestReporter.prototype.reportSpecResults = function (spec) {
        if (!spec.results().skipped) {
            var specData = this._addSpecResults(spec, spec.results(), this._currentPerfRecord);
            $(this).triggerHandler("specEnd", [this, specData, this.suites[this.getTopLevelSuiteName(spec)]]);
        }
        this._currentPerfRecord = null;
    };

    // Performance tracking

    UnitTestReporter.prototype._getTestWindowPerf = function () {
        return SpecRunnerUtils.getTestWindow().brackets.test.PerfUtils;
    };

    UnitTestReporter.prototype._logTestWindowMeasurement = function (measureInfo) {
        var value,
            printName = measureInfo.measure.name || measureInfo.name,
            record = {},
            self = this;

        if (measureInfo.measure instanceof RegExp) {
            value = this._currentPerfUtils.searchData(measureInfo.measure);
        } else {
            value = this._currentPerfUtils.getData(measureInfo.measure.id);
        }

        if (value === undefined) {
            value = "(None)";
        }

        if (measureInfo.measure.name && measureInfo.name) {
            printName = measureInfo.measure.name + " - " + measureInfo.name;
        }

        if (measureInfo.operation === "sum") {
            if (Array.isArray(value)) {
                value = value.reduce(function (a, b) { return a + b; });
            }

            printName = "Sum of all " + printName;
        }

        record.name = printName;
        record.value = value;

        if (measureInfo.children) {
            record.children = [];
            measureInfo.children.forEach(function (child) {
                record.children.push(self._logTestWindowMeasurement(child));
            });
        }

        return record;
    };

    /**
     * Records a performance measurement from the test window for the current running spec.
     * @param {!(PerfMeasurement|string)} measure A PerfMeasurement or string key to query PerfUtils for metrics.
     * @param {string} name An optional name or description to print with the measurement name
     * @param {string} operation An optional operation to perform on the measurement data. Currently supports sum.
     */
    UnitTestReporter.prototype.logTestWindow = function (measures, name, operation) {
        var self = this;

        if (!this._currentPerfRecord) {
            return;
        }

        this._currentPerfUtils = this._getTestWindowPerf();

        if (!Array.isArray(measures)) {
            measures = [{measure: measures, name: name, operation: operation}];
        }

        measures.forEach(function (measure) {
            self._currentPerfRecord.push(self._logTestWindowMeasurement(measure));
        });

        this._currentPerfUtils = null;
    };

    /**
     * Clears the current set of performance measurements.
     */
    UnitTestReporter.prototype.clearTestWindow = function () {
        this._getTestWindowPerf().clear();
    };

    /**
     * @return The active unit test reporter, or null if no unit test is running.
     */
    function getActiveReporter() {
        return activeReporter;
    }

    // Exports

    exports.UnitTestReporter = UnitTestReporter;
    exports.getActiveReporter = getActiveReporter;
});<|endoftext|>


<commit_before><commit_msg>offset -> htmlOffset<commit_after><|endoftext|>


<commit_before>import {autobind} from 'core-decorators';

import AsyncQueue from '../lib/async-queue';

class Task {
  constructor(name, error) {
    this.name = name;
    this.error = error;
    this.started = false;
    this.finished = false;
  }

  @autobind
  run() {
    this.started = true;
    this.finished = false;
    return new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    });
  }

  @autobind
  finish() {
    this.finished = true;
    if (this.error) {
      this.reject(new Error(this.name));
    } else {
      this.resolve(this.name);
    }
  }
}

describe.only('AsyncQueue', function() {
  it('runs items in parallel up to the set max', async function() {
    const queue = new AsyncQueue({parallelism: 3});

    const tasks = [
      new Task('task 1'),
      new Task('task 2', true),
      new Task('task 3'),
      new Task('task 4'),
      new Task('task 5'),
    ];
    const results = [false, false, false, false, false];
    const errors = [false, false, false, false, false];

    const p0 = queue.push(() => tasks[0].run());
    const p1 = queue.push(() => tasks[1].run());
    const p2 = queue.push(() => tasks[2].run());
    const p3 = queue.push(() => tasks[3].run());
    const p4 = queue.push(() => tasks[4].run());

    p0.then(value => { results[0] = value; }).catch(err => { errors[0] = err; });
    p1.then(value => { results[1] = value; }).catch(err => { errors[1] = err; });
    p2.then(value => { results[2] = value; }).catch(err => { errors[2] = err; });
    p3.then(value => { results[3] = value; }).catch(err => { errors[3] = err; });
    p4.then(value => { results[4] = value; }).catch(err => { errors[4] = err; });

    assert.isTrue(tasks[0].started);
    assert.isTrue(tasks[1].started);
    assert.isTrue(tasks[2].started);
    assert.isFalse(tasks[3].started);
    assert.isFalse(tasks[4].started);

    assert.isFalse(results[0]);

    tasks[0].finish();
    assert.isTrue(tasks[0].finished);
    await assert.async.equal(results[0], 'task 1');
    assert.isFalse(tasks[1].finished);
    assert.isFalse(results[1]);

    assert.isTrue(tasks[3].started);
    assert.isFalse(tasks[4].started);

    tasks[1].finish();
    assert.isTrue(tasks[1].finished);
    assert.isFalse(tasks[2].finished);
    await assert.async.equal(errors[1].message, 'task 2');

    assert.isTrue(tasks[4].started);
  });

  it('runs non-parallelizable tasks serially', async function() {
    const queue = new AsyncQueue({parallelism: 3});

    const tasks = [
      new Task('task 1'),
      new Task('task 2'),
      new Task('task 3'),
      new Task('task 4'),
      new Task('task 5'),
      new Task('task 6'),
    ];

    const p0 = queue.push(() => tasks[0].run());
    const p1 = queue.push(() => tasks[1].run());
    const p2 = queue.push(() => tasks[2].run(), {parallel: false});
    const p3 = queue.push(() => tasks[3].run(), {parallel: false});
    queue.push(() => tasks[4].run());
    queue.push(() => tasks[5].run());

    assert.isTrue(tasks[0].started);
    assert.isTrue(tasks[1].started);
    assert.isFalse(tasks[2].started); // not parallelizable!!
    assert.isFalse(tasks[3].started);
    assert.isFalse(tasks[4].started);
    assert.isFalse(tasks[5].started);

    tasks[0].finish();
    await p0;
    assert.isFalse(tasks[2].started); // still can't be started
    assert.isFalse(tasks[3].started);

    tasks[1].finish();
    await p1;
    await assert.async.isTrue(tasks[2].started);
    assert.isFalse(tasks[3].started); // still can't be started

    tasks[2].finish();
    await p2;
    await assert.async.isTrue(tasks[3].started);
    assert.isFalse(tasks[4].started); // 3 is non-parallelizable so 4 can't start

    tasks[3].finish();
    await p3;
    await assert.async.isTrue(tasks[4].started); // both can start since they are parallelizable
    assert.isTrue(tasks[5].started);
  });
});
<commit_msg>:fire: .only<commit_after>import {autobind} from 'core-decorators';

import AsyncQueue from '../lib/async-queue';

class Task {
  constructor(name, error) {
    this.name = name;
    this.error = error;
    this.started = false;
    this.finished = false;
  }

  @autobind
  run() {
    this.started = true;
    this.finished = false;
    return new Promise((resolve, reject) => {
      this.resolve = resolve;
      this.reject = reject;
    });
  }

  @autobind
  finish() {
    this.finished = true;
    if (this.error) {
      this.reject(new Error(this.name));
    } else {
      this.resolve(this.name);
    }
  }
}

describe('AsyncQueue', function() {
  it('runs items in parallel up to the set max', async function() {
    const queue = new AsyncQueue({parallelism: 3});

    const tasks = [
      new Task('task 1'),
      new Task('task 2', true),
      new Task('task 3'),
      new Task('task 4'),
      new Task('task 5'),
    ];
    const results = [false, false, false, false, false];
    const errors = [false, false, false, false, false];

    const p0 = queue.push(() => tasks[0].run());
    const p1 = queue.push(() => tasks[1].run());
    const p2 = queue.push(() => tasks[2].run());
    const p3 = queue.push(() => tasks[3].run());
    const p4 = queue.push(() => tasks[4].run());

    p0.then(value => { results[0] = value; }).catch(err => { errors[0] = err; });
    p1.then(value => { results[1] = value; }).catch(err => { errors[1] = err; });
    p2.then(value => { results[2] = value; }).catch(err => { errors[2] = err; });
    p3.then(value => { results[3] = value; }).catch(err => { errors[3] = err; });
    p4.then(value => { results[4] = value; }).catch(err => { errors[4] = err; });

    assert.isTrue(tasks[0].started);
    assert.isTrue(tasks[1].started);
    assert.isTrue(tasks[2].started);
    assert.isFalse(tasks[3].started);
    assert.isFalse(tasks[4].started);

    assert.isFalse(results[0]);

    tasks[0].finish();
    assert.isTrue(tasks[0].finished);
    await assert.async.equal(results[0], 'task 1');
    assert.isFalse(tasks[1].finished);
    assert.isFalse(results[1]);

    assert.isTrue(tasks[3].started);
    assert.isFalse(tasks[4].started);

    tasks[1].finish();
    assert.isTrue(tasks[1].finished);
    assert.isFalse(tasks[2].finished);
    await assert.async.equal(errors[1].message, 'task 2');

    assert.isTrue(tasks[4].started);
  });

  it('runs non-parallelizable tasks serially', async function() {
    const queue = new AsyncQueue({parallelism: 3});

    const tasks = [
      new Task('task 1'),
      new Task('task 2'),
      new Task('task 3'),
      new Task('task 4'),
      new Task('task 5'),
      new Task('task 6'),
    ];

    const p0 = queue.push(() => tasks[0].run());
    const p1 = queue.push(() => tasks[1].run());
    const p2 = queue.push(() => tasks[2].run(), {parallel: false});
    const p3 = queue.push(() => tasks[3].run(), {parallel: false});
    queue.push(() => tasks[4].run());
    queue.push(() => tasks[5].run());

    assert.isTrue(tasks[0].started);
    assert.isTrue(tasks[1].started);
    assert.isFalse(tasks[2].started); // not parallelizable!!
    assert.isFalse(tasks[3].started);
    assert.isFalse(tasks[4].started);
    assert.isFalse(tasks[5].started);

    tasks[0].finish();
    await p0;
    assert.isFalse(tasks[2].started); // still can't be started
    assert.isFalse(tasks[3].started);

    tasks[1].finish();
    await p1;
    await assert.async.isTrue(tasks[2].started);
    assert.isFalse(tasks[3].started); // still can't be started

    tasks[2].finish();
    await p2;
    await assert.async.isTrue(tasks[3].started);
    assert.isFalse(tasks[4].started); // 3 is non-parallelizable so 4 can't start

    tasks[3].finish();
    await p3;
    await assert.async.isTrue(tasks[4].started); // both can start since they are parallelizable
    assert.isTrue(tasks[5].started);
  });
});
<|endoftext|>


<commit_before>(function($){var el;var settings={};var methods={init:function(options){el=this;settings={token:false,query_param:'query'};if(options){$.extend(settings,options);}
if(!settings.token||settings.query_param==''){return this;}
$.getJSON('http://tapirgo.com/api/1/search.json?token='+570e9e6314ad6644b943ab78+'&query='+paramValue(settings.query_param)+'&callback=?',function(data){if(settings['complete']){settings.complete()}
$.each(data,function(key,val){el.append('

'+val.title+'

'+val.summary+'

');});});return this;}};function paramValue(query_param){var results=new RegExp('[\\?&]'+query_param+'=([^&#]*)').exec(window.location.href);return results?results[1]:false;}
$.fn.tapir=function(method){if(methods[method]){return methods[method].apply(this,Array.prototype.slice.call(arguments,1));}else if(typeof method==='object'||!method){return methods.init.apply(this,arguments);}else{$.error('Method '+method+' does not exist on jQuery.tapir');}};})(jQuery);
<commit_msg>Update jquery-tapir.min.js<commit_after>(function($){var el;var settings={};var methods={init:function(options){el=this;settings={token:false,query_param:'query'};if(options){$.extend(settings,options);}
if(!settings.token||settings.query_param==''){return this;}
$.getJSON('http://tapirgo.com/api/1/search.json?token='+'570e9e6314ad6644b943ab78'+'&query='+paramValue(settings.query_param)+'&callback=?',function(data){if(settings['complete']){settings.complete()}
$.each(data,function(key,val){el.append('

'+val.title+'

'+val.summary+'

');});});return this;}};function paramValue(query_param){var results=new RegExp('[\\?&]'+query_param+'=([^&#]*)').exec(window.location.href);return results?results[1]:false;}
$.fn.tapir=function(method){if(methods[method]){return methods[method].apply(this,Array.prototype.slice.call(arguments,1));}else if(typeof method==='object'||!method){return methods.init.apply(this,arguments);}else{$.error('Method '+method+' does not exist on jQuery.tapir');}};})(jQuery);
<|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiFinalChoiceDialogCtrl', function (
        $scope,
        $location,
        $routeParams,
        $route,
        rgiNotifier,
        ngDialog,
        rgiAnswerSrvc,
        rgiAnswerMethodSrvc,
        rgiIdentitySrvc,
        rgiQuestionSetSrvc
    ) {
        var assessment_ID = $routeParams.answer_ID.substring(0, $routeParams.answer_ID.length - 4),
            _ = $scope.$parent.$parent.$parent._;

        $scope.current_user = rgiIdentitySrvc.currentUser;
        $scope.question_criteria = $scope.$parent.question.question_criteria;
        $scope.answer = $scope.$parent.$parent.answer;
        $scope.requestProcessing = false;

        rgiAnswerSrvc.query({assessment_ID: assessment_ID}, function (answers) {
            rgiQuestionSetSrvc.setAnswers(answers);
        });

        $scope.final_choice_set = [
            {
                text: 'Agree with researcher score',
                score: $scope.answer.researcher_score,
                justification: $scope.answer.researcher_justification,
                comment: '',
                value: 'researcher',
                role: 'researcher'
            },
            {
                text: 'Other score',
                score: 0,
                justification: '',
                comment: '',
                value: 'other',
                role: $scope.current_user.role
            }
        ];

        if ($scope.answer.reviewer_score) {
            $scope.final_choice_set.push({
                text: 'Agree with reviewer score',
                score: $scope.answer.reviewer_score,
                justification: $scope.answer.reviewer_justification,
                comment: '',
                value: 'reviewer',
                role: 'reviewer'
            });
        }

        $scope.externalChoiceSubmit = function () {
            $scope.requestProcessing = true;
            var
                new_answer_data = $scope.answer,
                final_choice = $scope.final_choice;

            new_answer_data.external_answer.push({
                comment: final_choice.comment,
                author: $scope.current_user._id
            });

            if (final_choice.justification) {
                _.last(new_answer_data.external_answer).justification = final_choice.justification;
            }

            if (final_choice.score) {
                _.last(new_answer_data.external_answer).score = final_choice.score;
            }

            rgiAnswerMethodSrvc.updateAnswer(new_answer_data)
                .then(function () {
                    rgiNotifier.notify('Input added');
                    $route.reload();
                    ngDialog.close();
                }, function (reason) {
                    rgiNotifier.error(reason);
                }).finally(function() {
                    $scope.requestProcessing = false;
                });
        };

        $scope.finalChoiceSubmit = function () {
            var new_answer_data = $scope.$parent.answer,
                final_choice = $scope.final_choice;
            if (!final_choice) {
                rgiNotifier.error("You must select an action!");
            } else if (!final_choice.score) {
                rgiNotifier.error("You must select a score!");
            } else if (!final_choice.justification) {
                rgiNotifier.error("You must provide a justification!");
            } else {
                new_answer_data.status = 'final';
                new_answer_data.final_score = final_choice.score;
                new_answer_data.final_role = final_choice.role;
                new_answer_data.final_justification = final_choice.justification;

                rgiAnswerMethodSrvc.updateAnswer(new_answer_data)
                    .then(function () {
                        var root_url = $scope.current_user.isSupervisor() ? '/admin/assessments-admin' : '/assessments';

                        if (rgiQuestionSetSrvc.isAnyQuestionRemaining(new_answer_data)) {
                            $location.path(root_url + '/answer/' + new_answer_data.assessment_ID + "-" + rgiQuestionSetSrvc.getNextQuestionId(new_answer_data));
                        } else {
                            $location.path(root_url + '/' + new_answer_data.assessment_ID);
                        }
                        rgiNotifier.notify('Answer finalized');
                        ngDialog.close();
                    }, function (reason) {
                        rgiNotifier.error(reason);
                    });
            }

            $scope.closeDialog = function () {
                ngDialog.close();
            };
        };
    });<commit_msg>reorder the final score options<commit_after>'use strict';

angular.module('app')
    .controller('rgiFinalChoiceDialogCtrl', function (
        $scope,
        $location,
        $routeParams,
        $route,
        rgiNotifier,
        ngDialog,
        rgiAnswerSrvc,
        rgiAnswerMethodSrvc,
        rgiIdentitySrvc,
        rgiQuestionSetSrvc
    ) {
        var assessment_ID = $routeParams.answer_ID.substring(0, $routeParams.answer_ID.length - 4),
            _ = $scope.$parent.$parent.$parent._;

        $scope.current_user = rgiIdentitySrvc.currentUser;
        $scope.question_criteria = $scope.$parent.question.question_criteria;
        $scope.answer = $scope.$parent.$parent.answer;
        $scope.requestProcessing = false;

        rgiAnswerSrvc.query({assessment_ID: assessment_ID}, function (answers) {
            rgiQuestionSetSrvc.setAnswers(answers);
        });

        var getFinalScoreOption = function(text, score, justification, value, role) {
            return {
                text: text,
                score: score,
                justification: justification,
                comment: '',
                value: value,
                role: role
            };
        };

        $scope.final_choice_set = [getFinalScoreOption('Agree with researcher score', $scope.answer.researcher_score,
            $scope.answer.researcher_justification, 'researcher', 'researcher')];

        if ($scope.answer.reviewer_score) {
            $scope.final_choice_set.push(getFinalScoreOption('Agree with reviewer score', $scope.answer.reviewer_score,
                $scope.answer.reviewer_justification, 'reviewer', 'reviewer'));
        }

        $scope.final_choice_set.push(getFinalScoreOption('Other score', 0, '', 'other', $scope.current_user.role));

        $scope.externalChoiceSubmit = function () {
            $scope.requestProcessing = true;
            var
                new_answer_data = $scope.answer,
                final_choice = $scope.final_choice;

            new_answer_data.external_answer.push({
                comment: final_choice.comment,
                author: $scope.current_user._id
            });

            if (final_choice.justification) {
                _.last(new_answer_data.external_answer).justification = final_choice.justification;
            }

            if (final_choice.score) {
                _.last(new_answer_data.external_answer).score = final_choice.score;
            }

            rgiAnswerMethodSrvc.updateAnswer(new_answer_data)
                .then(function () {
                    rgiNotifier.notify('Input added');
                    $route.reload();
                    ngDialog.close();
                }, function (reason) {
                    rgiNotifier.error(reason);
                }).finally(function() {
                    $scope.requestProcessing = false;
                });
        };

        $scope.finalChoiceSubmit = function () {
            var new_answer_data = $scope.$parent.answer,
                final_choice = $scope.final_choice;
            if (!final_choice) {
                rgiNotifier.error("You must select an action!");
            } else if (!final_choice.score) {
                rgiNotifier.error("You must select a score!");
            } else if (!final_choice.justification) {
                rgiNotifier.error("You must provide a justification!");
            } else {
                new_answer_data.status = 'final';
                new_answer_data.final_score = final_choice.score;
                new_answer_data.final_role = final_choice.role;
                new_answer_data.final_justification = final_choice.justification;

                rgiAnswerMethodSrvc.updateAnswer(new_answer_data)
                    .then(function () {
                        var root_url = $scope.current_user.isSupervisor() ? '/admin/assessments-admin' : '/assessments';

                        if (rgiQuestionSetSrvc.isAnyQuestionRemaining(new_answer_data)) {
                            $location.path(root_url + '/answer/' + new_answer_data.assessment_ID + "-" + rgiQuestionSetSrvc.getNextQuestionId(new_answer_data));
                        } else {
                            $location.path(root_url + '/' + new_answer_data.assessment_ID);
                        }
                        rgiNotifier.notify('Answer finalized');
                        ngDialog.close();
                    }, function (reason) {
                        rgiNotifier.error(reason);
                    });
            }

            $scope.closeDialog = function () {
                ngDialog.close();
            };
        };
    });<|endoftext|>


<commit_before>(function($){
   $.fn.dateRange = function(options)
   {
      if (options && options.command == 'entered') {
        this.get(0).dateRange.entered();
        return this;
      }
      var defaults = {selected: null, startWith: null, minimumDate: null, maximumDate: null};
      var opts = $.extend({}, defaults, options);
      var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
      var abbreviations = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
      var daySelector = 'td:not(.m):not(:empty)';
      return this.each(function()
      {
         if (this.dateRange) { return false; }

         var $input = $(this);
         var $container, selecting, selected;
         var self =
         {
            initialize: function()
            {
               $container = self.initializeContainer().hide();
               $prev = $container.delegate('td.prev', 'click', self.loadPrevious);
               $next = $container.delegate('td.next', 'click', self.loadNext);
               var now = new Date();
               now.setDate(1);
               var prev = new Date(now.getFullYear(), now.getMonth()-1, 1);
               $container.append(self.buildMonth(prev));
               $container.append(self.buildMonth(now));
               self.fixNav();

               $input.click(function()
               {
                  self.show();
                  return false;
               }).keydown(function(e)
               {
                 if (e.keyCode == 13) { self.entered(); }
               });

               $(document).keydown(function(e)
               {
                  if (e.keyCode == 27) { self.hide(); }
               }).click(self.hide);

               $container.delegate(daySelector, 'click', self.clicked);
               $container.click(function(){return false;});

               if (opts.startWith != null)
               {
                  selected = opts.startWith;
                  self.rangeSelected();
               }
            },
            entered: function()
            {
              var values = $input.val().split('-');
              if (values.length != 2) { return false; }

              var from = self.parseDate(values[0].replace(/^\s*/, '').replace(/\s*$/, ''));
              var to = self.parseDate(values[1].replace(/^\s*/, '').replace(/\s*$/, ''));
              if (from == null || to == null) { return false; }

              selected = [from, to];
              self.rangeSelected();
              return false;
            },
            parseDate: function(value)
            {
              return new Date(value);
            },
            show: function()
            {
               selecting = new Array();
               $container.show();
            },
            hide: function()
            {
               $container.hide();
            },
            clicked: function()
            {
               var $td = $(this).addClass('selected');
               var date = $td.closest('table').data('date');
               selecting.push(new Date(date.getFullYear(), date.getMonth(), $td.text()));
               if (selecting.length == 2)
               {
                  selected = selecting;
                  self.rangeSelected();
               }
            },
            rangeSelected: function()
            {
               if (selected[0] > selected[1])
               {
                  var x = selected[0];
                  selected[0] = selected[1];
                  selected[1] = x;
               }
               $input.val(self.format(selected[0]) + ' - ' + self.format(selected[1]));
               self.highlight($container.find('table:first'));
               self.highlight($container.find('table:last'));
               self.hide();
               if (opts.selected != null) { opts.selected(selected); }
            },
            highlight: function($table)
            {
               if (selected == null || selected.length != 2) { return; }

               $table.find('td.highlight').removeClass('highlight');
               var startDate = $table.data('date');
               var endDate = new Date(startDate.getFullYear(), startDate.getMonth()+1, 0);
               if (startDate > selected[1] || endDate < selected[0]) { return; }

               var $tds = $table.find(daySelector);
               var start = selected[0].getMonth() < startDate.getMonth() || selected[0].getFullYear() < startDate.getFullYear() ? 0 : selected[0].getDate()-1;
               var end = selected[1].getMonth() > endDate.getMonth() || selected[1].getFullYear() > endDate.getFullYear() ? $tds.length : selected[1].getDate();
               for(var i = start; i < end; ++i)
               {
                  $tds.get(i).className = 'highlight';
               }
            },
            loadPrevious: function()
            {
               $container.children('table:eq(1)').remove();
               var $remaining = $container.children('table')
               var date = $remaining.data('date');
               $remaining.before(self.buildMonth(new Date(date.getFullYear(), date.getMonth()-1, 1)));
               self.fixNav();
            },
            loadNext: function()
            {
               $container.children('table:eq(0)').remove();
               var $remaining = $container.children('table')
               var date = $remaining.data('date');
               $remaining.after(self.buildMonth(new Date(date.getFullYear(), date.getMonth()+1, 1)));
               self.fixNav();
            },
            initializeContainer: function()
            {
               $input.wrap($('<div>').addClass('calendarWrap'));
               var $container = $('<div>').addClass('calendar').insertAfter($input);
               return $container;
            },
            buildMonth: function(date)
            {
               var first = new Date(date.getFullYear(), date.getMonth(), 1);
               var last = new Date(date.getFullYear(), date.getMonth()+1, 0);
               var firstDay = first.getDay();
               var totalDays = last.getDate();
               var weeks = Math.ceil((totalDays + firstDay) / 7);
               var table = document.createElement('table');

               for (var i = 0, count = 1; i < weeks; ++i)
               {
                  var row = table.insertRow(-1);
                  for(var j = 0; j < 7; ++j, ++count)
                  {
                     var cell = row.insertCell(-1);
                     if (count > firstDay && count <= totalDays+firstDay)
                     {
                        cell.innerHTML = count - firstDay;
                     }
                  }
               }
               self.insertHeader(date, table);
               var $table = $(table).data('date', date);
               self.highlight($table);

               if (opts.minimumDate && opts.minimumDate >= first) { self.prev().hide() } else { self.prev().show(); }
               if (opts.maximumDate && opts.maximumDate <= last) { self.next().hide() } else { self.next().show(); }

               return $table;
            },
            format: function(date)
            {
               return abbreviations[date.getMonth()] + ' ' + date.getDate() + ' ' + date.getFullYear();
            },
            insertHeader: function(date, table)
            {
              var header = table.insertRow(0);
              var cell = header.insertCell(-1);
              cell.className = 'm nav';

              cell = header.insertCell(1);
              cell.innerHTML = months[date.getMonth()] + ' ' + date.getFullYear();
              cell.className = 'm'; //very stupid IE (all versions) fix
              cell.colSpan = 5;

              cell = header.insertCell(2);
              cell.className = 'm nav';
            },
            prev: function()
            {
              return $container.find('div.prev');
            },
            next: function()
            {
              return $container.find('div.next');
            },
            fixNav: function()
            {
              var $first = $container.find('table:first tr:first');
              $first.find('td:first').addClass('prev nav').html('‹')
              $first.find('td:last').removeClass('next nav').html('');

              var $second = $container.find('table:last tr:first');
              $second.find('td:first').removeClass('prev nav').html('')
              $second.find('td:last').addClass('next nav').html('›');
            }
         };
         this.dateRange = self;
         self.initialize();
      });
   }
})(jQuery);
<commit_msg>entered called with from/to<commit_after>(function($){
   $.fn.dateRange = function(options)
   {
      if (options && options.command == 'entered') {
        this.get(0).dateRange.set(options.from, options.to).entered();
        return this;
      }
      var defaults = {selected: null, startWith: null, minimumDate: null, maximumDate: null};
      var opts = $.extend({}, defaults, options);
      var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
      var abbreviations = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
      var daySelector = 'td:not(.m):not(:empty)';
      return this.each(function()
      {
         if (this.dateRange) { return false; }

         var $input = $(this);
         var $container, selecting, selected;
         var self =
         {
            initialize: function()
            {
               $container = self.initializeContainer().hide();
               $prev = $container.delegate('td.prev', 'click', self.loadPrevious);
               $next = $container.delegate('td.next', 'click', self.loadNext);
               var now = new Date();
               now.setDate(1);
               var prev = new Date(now.getFullYear(), now.getMonth()-1, 1);
               $container.append(self.buildMonth(prev));
               $container.append(self.buildMonth(now));
               self.fixNav();

               $input.click(function()
               {
                  self.show();
                  return false;
               }).keydown(function(e)
               {
                 if (e.keyCode == 13) { self.entered(); }
               });

               $(document).keydown(function(e)
               {
                  if (e.keyCode == 27) { self.hide(); }
               }).click(self.hide);

               $container.delegate(daySelector, 'click', self.clicked);
               $container.click(function(){return false;});

               if (opts.startWith != null)
               {
                  selected = opts.startWith;
                  self.rangeSelected();
               }
            },
            set: function(from, to) {
              $input.val(self.format(from) + ' - ' + self.format(to));
              return this;
            },
            entered: function()
            {
              var values = $input.val().split('-');
              if (values.length != 2) { return false; }

              var from = self.parseDate(values[0].replace(/^\s*/, '').replace(/\s*$/, ''));
              var to = self.parseDate(values[1].replace(/^\s*/, '').replace(/\s*$/, ''));
              if (from == null || to == null) { return false; }

              selected = [from, to];
              self.rangeSelected();
              return false;
            },
            parseDate: function(value)
            {
              return new Date(value);
            },
            show: function()
            {
               selecting = new Array();
               $container.show();
            },
            hide: function()
            {
               $container.hide();
            },
            clicked: function()
            {
               var $td = $(this).addClass('selected');
               var date = $td.closest('table').data('date');
               selecting.push(new Date(date.getFullYear(), date.getMonth(), $td.text()));
               if (selecting.length == 2)
               {
                  selected = selecting;
                  self.rangeSelected();
               }
            },
            rangeSelected: function()
            {
               if (selected[0] > selected[1])
               {
                  var x = selected[0];
                  selected[0] = selected[1];
                  selected[1] = x;
               }
               $input.val(self.format(selected[0]) + ' - ' + self.format(selected[1]));
               self.highlight($container.find('table:first'));
               self.highlight($container.find('table:last'));
               self.hide();
               if (opts.selected != null) { opts.selected(selected); }
            },
            highlight: function($table)
            {
               if (selected == null || selected.length != 2) { return; }

               $table.find('td.highlight').removeClass('highlight');
               var startDate = $table.data('date');
               var endDate = new Date(startDate.getFullYear(), startDate.getMonth()+1, 0);
               if (startDate > selected[1] || endDate < selected[0]) { return; }

               var $tds = $table.find(daySelector);
               var start = selected[0].getMonth() < startDate.getMonth() || selected[0].getFullYear() < startDate.getFullYear() ? 0 : selected[0].getDate()-1;
               var end = selected[1].getMonth() > endDate.getMonth() || selected[1].getFullYear() > endDate.getFullYear() ? $tds.length : selected[1].getDate();
               for(var i = start; i < end; ++i)
               {
                  $tds.get(i).className = 'highlight';
               }
            },
            loadPrevious: function()
            {
               $container.children('table:eq(1)').remove();
               var $remaining = $container.children('table')
               var date = $remaining.data('date');
               $remaining.before(self.buildMonth(new Date(date.getFullYear(), date.getMonth()-1, 1)));
               self.fixNav();
            },
            loadNext: function()
            {
               $container.children('table:eq(0)').remove();
               var $remaining = $container.children('table')
               var date = $remaining.data('date');
               $remaining.after(self.buildMonth(new Date(date.getFullYear(), date.getMonth()+1, 1)));
               self.fixNav();
            },
            initializeContainer: function()
            {
               $input.wrap($('<div>').addClass('calendarWrap'));
               var $container = $('<div>').addClass('calendar').insertAfter($input);
               return $container;
            },
            buildMonth: function(date)
            {
               var first = new Date(date.getFullYear(), date.getMonth(), 1);
               var last = new Date(date.getFullYear(), date.getMonth()+1, 0);
               var firstDay = first.getDay();
               var totalDays = last.getDate();
               var weeks = Math.ceil((totalDays + firstDay) / 7);
               var table = document.createElement('table');

               for (var i = 0, count = 1; i < weeks; ++i)
               {
                  var row = table.insertRow(-1);
                  for(var j = 0; j < 7; ++j, ++count)
                  {
                     var cell = row.insertCell(-1);
                     if (count > firstDay && count <= totalDays+firstDay)
                     {
                        cell.innerHTML = count - firstDay;
                     }
                  }
               }
               self.insertHeader(date, table);
               var $table = $(table).data('date', date);
               self.highlight($table);

               if (opts.minimumDate && opts.minimumDate >= first) { self.prev().hide() } else { self.prev().show(); }
               if (opts.maximumDate && opts.maximumDate <= last) { self.next().hide() } else { self.next().show(); }

               return $table;
            },
            format: function(date)
            {
               return abbreviations[date.getMonth()] + ' ' + date.getDate() + ' ' + date.getFullYear();
            },
            insertHeader: function(date, table)
            {
              var header = table.insertRow(0);
              var cell = header.insertCell(-1);
              cell.className = 'm nav';

              cell = header.insertCell(1);
              cell.innerHTML = months[date.getMonth()] + ' ' + date.getFullYear();
              cell.className = 'm'; //very stupid IE (all versions) fix
              cell.colSpan = 5;

              cell = header.insertCell(2);
              cell.className = 'm nav';
            },
            prev: function()
            {
              return $container.find('div.prev');
            },
            next: function()
            {
              return $container.find('div.next');
            },
            fixNav: function()
            {
              var $first = $container.find('table:first tr:first');
              $first.find('td:first').addClass('prev nav').html('‹')
              $first.find('td:last').removeClass('next nav').html('');

              var $second = $container.find('table:last tr:first');
              $second.find('td:first').removeClass('prev nav').html('')
              $second.find('td:last').addClass('next nav').html('›');
            }
         };
         this.dateRange = self;
         self.initialize();
      });
   }
})(jQuery);
<|endoftext|>


<commit_before>/*
 * @author JasonRammoray
 * @email jason.rammoray@gmail.com
 */

(function() {
  'use strict';

  var WebPage = require('webpage');

  var args = require('system').args;

  var fs = require('fs');

  /*
   * args in this case consists of two arguments:
   * [0] - path to phantom job (this file)
   * [1] - job parameters serialized as json
   */

  try {
    var jobParams = JSON.parse(args[1]);
  } catch( error ) {
    console.log('Params passed to phantom job can not be parsed as json. Exiting...');

    phantom.exit();
  }

  var websitePages = jobParams.pages;

  var pageLoadingTimeout = jobParams.pageLoadingTimeout;

  var utils = {
    log: {
      /**
       * Returns reference to log object.
       */

      get: (function() {
        var log = [];

        return function() {
          return log;
        };
      })(),

      /**
       * Adds message to the log object and logs it to the console.
       * @param {*} message - message data
       */

      add: function(message) {
        this.get().push(message);

        console.log(message);
      },

      /**
       * Erases the log.
       */

      reset: function() {
        this.get().splice(0)
      },

      /**
       * Saves log only if path to the log file can be converted to boolean true.
       */

      save: function(logFile) {
        if( !!logFile ) {
          fs.write(jobParams.output.dir + '/' + jobParams.output.logFile, this.get().join('\n'), {
            mode: 'w',

            charset: 'utf-8'
          });
        } else {
          console.log('Skipping saving a log file. Check log file name.');
        }
      }
    }
  };

  /**
   * Loads pages and stores their html snapshots.
   * Algorithm:
   * a) check if there is still pages to process;
   * b) if there is no one, then exit;
   * c) fetch page from list and load it in headless browser;
   * d) if there is no pending http requests, then store page snapshot in a file and load next page (go to step a);
   * e) otherwise wait pageLoadingTimeout ms and repeat step d.
   * @param {Array} websitePages - pages list, that should be processed
   */

  function loadPages(websitePages) {
    if( !websitePages.length ) {
      utils.log.add('Job for building html snapshots is done. Exiting...');

      utils.log.save(jobParams.output.logFile);

      phantom.exit();
    }

    var websitePage = websitePages.shift();

    var pageObj = WebPage.create();

    var websitePageUrl = jobParams.baseUrl + websitePage.path;

    var websitePageOutputFile = jobParams.output.dir +

        '/' +

      websitePage.file +

      (!!jobParams.output.snapshotFileExt ? '.' + jobParams.output.snapshotFileExt : '');

    pageObj.onLoadFinished = function() {
      var pageHtml = jobParams.pageDocType;

      /**
       * Checks if page is loaded.
       * If so, then stores it's content to a file and the proceeds to the next page,
       * otherwise sets timeout for checking page loading status.
       */

      var loadPageHtml = function pageLoader() {
        utils.log.add('Checking if page "' + websitePageUrl + '" is loaded.');

        var documentHtml = pageObj.evaluate(function() {
          // Keep in mind, that angular might not be loaded at the moment

          try {
            var http = angular.injector(['ng']).get('$http');

            return http.pendingRequests.length ? false : document.documentElement.innerHTML;
          } catch( err ) {
            return false;
          }
        });

        if( !!documentHtml ) {
          pageHtml += documentHtml;

          utils.log.add('Page "' + websitePageUrl + '" is loaded, writing output to file: ' + websitePageOutputFile);

          fs.write(websitePageOutputFile, pageHtml, {
            mode: 'w',

            charset: 'utf-8'
          });

          utils.log.add('Proceeding to the remaining pages...');

          loadPages(websitePages);
        } else {
          utils.log.add('Page ' + websitePageUrl + ' is not yet loaded. Wait for ' + pageLoadingTimeout + ' ms.');

          /*
           * Note: at the moment there is no threshold for checks.
           * Phantom js will continuously try to check page loading status
           * after each pageLoadingTimeout ms. You have to kill phantom js
           * explicitly if you want to stop process or wait for 5 minutes
           * before process will be killed by timeout.
           */

          setTimeout(pageLoader, pageLoadingTimeout);
        }
      };

      loadPageHtml();
    };

    utils.log.add('Opening page: "' + websitePageUrl + '"');

    pageObj.open(websitePageUrl);
  }

  loadPages(websitePages);
})();<commit_msg>Fix for method for checking page loading status in the default phantom.js job<commit_after>/*
 * @author JasonRammoray
 * @email jason.rammoray@gmail.com
 */

(function() {
  'use strict';

  var WebPage = require('webpage');

  var args = require('system').args;

  var fs = require('fs');

  /*
   * args in this case consists of two arguments:
   * [0] - path to phantom job (this file)
   * [1] - job parameters serialized as json
   */

  try {
    var jobParams = JSON.parse(args[1]);
  } catch( error ) {
    console.log('Params passed to phantom job can not be parsed as json. Exiting...');

    phantom.exit();
  }

  var websitePages = jobParams.pages;

  var pageLoadingTimeout = jobParams.pageLoadingTimeout;

  var utils = {
    log: {
      /**
       * Returns reference to log object.
       */

      get: (function() {
        var log = [];

        return function() {
          return log;
        };
      })(),

      /**
       * Adds message to the log object and logs it to the console.
       * @param {*} message - message data
       */

      add: function(message) {
        this.get().push(message);

        console.log(message);
      },

      /**
       * Erases the log.
       */

      reset: function() {
        this.get().splice(0)
      },

      /**
       * Saves log only if path to the log file can be converted to boolean true.
       */

      save: function(logFile) {
        if( !!logFile ) {
          fs.write(jobParams.output.dir + '/' + jobParams.output.logFile, this.get().join('\n'), {
            mode: 'w',

            charset: 'utf-8'
          });
        } else {
          console.log('Skipping saving a log file. Check log file name.');
        }
      }
    }
  };

  /**
   * Loads pages and stores their html snapshots.
   * Algorithm:
   * a) check if there is still pages to process;
   * b) if there is no one, then exit;
   * c) fetch page from list and load it in headless browser;
   * d) if there is no pending http requests, then store page snapshot in a file and load next page (go to step a);
   * e) otherwise wait pageLoadingTimeout ms and repeat step d.
   * @param {Array} websitePages - pages list, that should be processed
   */

  function loadPages(websitePages) {
    if( !websitePages.length ) {
      utils.log.add('Job for building html snapshots is done. Exiting...');

      utils.log.save(jobParams.output.logFile);

      phantom.exit();
    }

    var websitePage = websitePages.shift();

    var pageObj = WebPage.create();

    var websitePageUrl = jobParams.baseUrl + websitePage.path;

    var websitePageOutputFile = jobParams.output.dir +

        '/' +

      websitePage.file +

      (!!jobParams.output.snapshotFileExt ? '.' + jobParams.output.snapshotFileExt : '');

    pageObj.onLoadFinished = function() {
      var pageHtml = jobParams.pageDocType;

      /**
       * Checks if page is loaded.
       * If so, then stores it's content to a file and the proceeds to the next page,
       * otherwise sets timeout for checking page loading status.
       */

      var loadPageHtml = function pageLoader() {
        utils.log.add('Checking if page "' + websitePageUrl + '" is loaded.');

        var documentHtml = pageObj.evaluate(function() {
          /*
           * Keep in mind, that angular might either not be loaded at the moment or
           * it's api might be changed dramatically in the future.
           * Note: check for page loading status works only if you have automatically
           * bootstrapped application on the page (either via ng-app, or data-ng-app,
           * or x-ng-app, or ng_app).
           * Hence wrap code block with try / catch
           */

          try {
            var appDomElement = document.querySelector('[ng-app], [data-ng-app], [x-ng-app], [ng_app]');

            var http = angular.element(appDomElement).injector().get('$http');

            return http.pendingRequests.length ? false : document.documentElement.innerHTML;
          } catch( err ) {
            return false;
          }
        });

        if( !!documentHtml ) {
          pageHtml += documentHtml;

          utils.log.add('Page "' + websitePageUrl + '" is loaded, writing output to file: ' + websitePageOutputFile);

          fs.write(websitePageOutputFile, pageHtml, {
            mode: 'w',

            charset: 'utf-8'
          });

          utils.log.add('Proceeding to the remaining pages...');

          loadPages(websitePages);
        } else {
          utils.log.add('Page ' + websitePageUrl + ' is not yet loaded. Wait for ' + pageLoadingTimeout + ' ms.');

          /*
           * Note: at the moment there is no threshold for checks.
           * Phantom js will continuously try to check page loading status
           * after each pageLoadingTimeout ms. You have to kill phantom js
           * explicitly if you want to stop process or wait for 5 minutes
           * before process will be killed by timeout.
           */

          setTimeout(pageLoader, pageLoadingTimeout);
        }
      };

      loadPageHtml();
    };

    utils.log.add('Opening page: "' + websitePageUrl + '"');

    pageObj.open(websitePageUrl);
  }

  loadPages(websitePages);
})();<|endoftext|>


<commit_before>define([
  'angular',
  'lodash',
],
function (angular, _) {
  'use strict';

  var module = angular.module('grafana.controllers');

  module.controller('PrometheusQueryCtrl', function($scope) {

    $scope.init = function() {
      var target = $scope.target;

      target.expr = target.expr || '';
      target.intervalFactor = target.intervalFactor || 2;

      $scope.metric = '';
      $scope.resolutions = _.map([1,2,3,4,5,10], function(f) {
        return {factor: f, label: '1/' + f};
      });

      $scope.$on('typeahead-updated', function() {
        $scope.$apply($scope.inputMetric);
        $scope.refreshMetricData();
      });
    };

    $scope.refreshMetricData = function() {
      if (!_.isEqual($scope.oldTarget, $scope.target)) {
        $scope.oldTarget = angular.copy($scope.target);
        $scope.get_data();
      }
    };

    $scope.inputMetric = function() {
      $scope.target.expr += $scope.target.metric;
      $scope.metric = '';
    };

    $scope.suggestMetrics = function(query, callback) {
      $scope.datasource
        .performSuggestQuery(query)
        .then(callback);
    };

    $scope.linkToPrometheus = function() {
      var range = Math.ceil(($scope.range.to.valueOf() - $scope.range.from.valueOf()) / 1000);
      var endTime = $scope.range.to.utc().format('YYYY-MM-DD HH:MM');
      var expr = {
        expr: $scope.target.expr,
        range_input: range + 's',
        end_input: endTime,
        step_input: '',
        stacked: $scope.panel.stack,
        tab: 0
      };
      var hash = encodeURIComponent(JSON.stringify([expr]));
      return $scope.datasource.directUrl + '/graph#' + hash;
    };

    $scope.init();
  });

});
<commit_msg>fix Prometheus link, expand template variable in expression<commit_after>define([
  'angular',
  'lodash',
],
function (angular, _) {
  'use strict';

  var module = angular.module('grafana.controllers');

  module.controller('PrometheusQueryCtrl', function($scope, templateSrv) {

    $scope.init = function() {
      var target = $scope.target;

      target.expr = target.expr || '';
      target.intervalFactor = target.intervalFactor || 2;

      $scope.metric = '';
      $scope.resolutions = _.map([1,2,3,4,5,10], function(f) {
        return {factor: f, label: '1/' + f};
      });

      $scope.$on('typeahead-updated', function() {
        $scope.$apply($scope.inputMetric);
        $scope.refreshMetricData();
      });
    };

    $scope.refreshMetricData = function() {
      if (!_.isEqual($scope.oldTarget, $scope.target)) {
        $scope.oldTarget = angular.copy($scope.target);
        $scope.get_data();
      }
    };

    $scope.inputMetric = function() {
      $scope.target.expr += $scope.target.metric;
      $scope.metric = '';
    };

    $scope.suggestMetrics = function(query, callback) {
      $scope.datasource
        .performSuggestQuery(query)
        .then(callback);
    };

    $scope.linkToPrometheus = function() {
      var range = Math.ceil(($scope.range.to.valueOf() - $scope.range.from.valueOf()) / 1000);
      var endTime = $scope.range.to.utc().format('YYYY-MM-DD HH:MM');
      var expr = {
        expr: templateSrv.replace($scope.target.expr, $scope.panel.scopedVars),
        range_input: range + 's',
        end_input: endTime,
        step_input: '',
        stacked: $scope.panel.stack,
        tab: 0
      };
      var hash = encodeURIComponent(JSON.stringify([expr]));
      return $scope.datasource.directUrl + '/graph#' + hash;
    };

    $scope.init();
  });

});
<|endoftext|>