<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";

      return message;
    }

    expect(getMessage()).toBe('Outer');
    expect(overrideMessage()).toBe('Inner');
    expect(message).toBe('Outer');
  });

  it("should have lexical scoping", function() {
    var variable = "top-level";

    function parentfunction() {
      var variable = "local";

      function childfunction() {
        return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe('local');
  });

  it("should use lexical scoping to synthesise functions", function() {

    function makeIncreaseByFunction(increaseByAmount) {
      return function(numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function() {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe('first');

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];

      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe('first,second,third');
  });

  it("should pass functions as values", function() {
    var appendRules = function(name) {
      return name + " rules!";
    };

    var appendDoubleRules = function(name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe('John rules!');

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe('Mary totally rules!');

  });

  it("should use function body as a string", function() {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(3);

    var multiply = function(a, b) {
      // An internal comment
      return a * b;
    };

    expect(multiply.toString()).toBe('function(a, b) {\n\t// An internal comment\n\treturn a * b;\n};');
  });
});
<commit_msg>Removed semicolon<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";

      return message;
    }

    expect(getMessage()).toBe('Outer');
    expect(overrideMessage()).toBe('Inner');
    expect(message).toBe('Outer');
  });

  it("should have lexical scoping", function() {
    var variable = "top-level";

    function parentfunction() {
      var variable = "local";

      function childfunction() {
        return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe('local');
  });

  it("should use lexical scoping to synthesise functions", function() {

    function makeIncreaseByFunction(increaseByAmount) {
      return function(numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function() {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe('first');

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];

      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe('first,second,third');
  });

  it("should pass functions as values", function() {
    var appendRules = function(name) {
      return name + " rules!";
    };

    var appendDoubleRules = function(name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe('John rules!');

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe('Mary totally rules!');

  });

  it("should use function body as a string", function() {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(3);

    var multiply = function(a, b) {
      // An internal comment
      return a * b;
    };

    expect(multiply.toString()).toBe('function(a, b) {\n\t // An internal comment\n\t return a * b;\n}');
  });
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var Promise = require('bluebird');
var chalk = require('chalk');
var apps = require('../../db/apps');
var parse = require('../../parse');
var log = require("../../logger");
var maxManifestResults = require('config').results.maxManifest;

module.exports = {
    init: init,
    find: find
}

function init(env) {
    return apps
        .init("manifest")
        .then(function (ret) {
            env.apps = ret
            return env
        })
}

function find(env, query, options) {
    // If query is not specified, return everything in scope
    if (!query) {
        return Promise.resolve(options.scope);
    }
    var manifestQuery = parse(query);
    // array to collect results
    var results = []
    var count = 0;
    var found = 0;
    // Iterate over ids in the scope
    for (var i = 0; i < options.scope.length; i++) {
        var id = options.scope[i];
        var app = env.apps.get(id, {manifest: true})

        if (app.manifest === undefined || app.manifest === null) {
            return;
        }

        var matcher = _lookup_matcher(manifestQuery)

        // apply the matcher to 'app' to see if it maches
        var matched = matcher(manifestQuery, app)

        // if so
        if (matched) {
            // add to the results array
            results.push(id)
            found++;
        }

        log.info('%d: %s %s', count, chalk.grey(id),
            matched ? chalk.green('yes') : chalk.red('no'))
        count++;

        if (found == maxManifestResults) {
            // the maximum number of UI results have been reached.
            break;
        }
    }

    return Promise.resolve(results);
}

// analyze the pattern of the given query and lookup a matcher to process the query
function _lookup_matcher(q) {
    if (q.children === undefined && q.count === 1) {
        return _find_by_a_single_tag
    }
    else if (q.children === undefined && q.count > 1) {
        return _find_by_siblings
    }
    else if (q.children.length === 1) {
        return _find_by_a_single_tag_with_n_children_of_one_tag
    }
    else if (q.children.length > 1) {
        return _find_by_a_single_tag_with_n_children_of_multiple_tags
    }
    else {
        log.error('Unrecognized query.');
        return function () {
            return false
        }
    }

}

function _find_by_a_single_tag(q, app) {
    var $ = app.manifest
    var selector = _get_element_name(q)

    // find a custom tag like: <com.whatsapp.*/>
    if (selector.indexOf('*') != -1) {
        return _.filter($('*'), function (val) {
            var allAttributesFound = true;
            if (q.attribs.length > 0) {
                allAttributesFound = _.forEach(otherAttributes, function (attribute) {
                    if (val.attribs[attribute.name] != attribute.value) return false;
                })
                return _.startsWith(val.name, selector.split('*')[0]) && allAttributesFound == true
            }
            return _.startsWith(val.name, selector.split('*')[0])
        });
    }
    if ('attributes' in q) {
        selector += _getAttributeSelectors(q.attributes)
    }
    if ('min' in q) {
        $(selector).length > q.min;
    } else if ('max' in q) {
        $(selector).length < q.count;
    } else if ('exactly' in q) {
        $(selector).length == q.exactly;
    }
    return $(selector).length >= q.count
}

function _find_by_a_single_tag_with_n_children_of_one_tag(q, app) {
    var $ = app.manifest || app
    var selector = _get_element_name(q)
    var childName = _get_child_name(q.children[0])
    var childCount = q.children[0].count
    var result
    if (typeof $ === 'function') {
        // Find each selector that is nth in relation to its sibling selector with the same element name.
        result = (childName === '*') ? $(selector + ' > ' + childName) :
            $(selector + ' > ' + childName + ':nth-of-type(' + childCount + ')')
        return result.length == 1;
    }
    else {
        result = $.children(childName);
    }
    if ('children' in q.children[0] && result.length >= childCount) {
        return _find_by_a_single_tag_with_n_children_of_one_tag(q.children[0], result)
    }
    return result.length >= childCount
}

function _find_by_siblings(q, app) {
    var $ = app.manifest
    var selector = _get_element_name(q)
    var result = $(selector + ':nth-of-type(' + q.count + ')')
    return result.length > 0
}

function _find_by_a_single_tag_with_n_children_of_multiple_tags(q, app) {
    // Find the children of the single tag and count their children
    // as siblings of each other.
    // Example: $('manifest').children('activity ~ uses-permission')
    var $ = app.manifest;
    var selector = _get_element_name(q);
    var childrenNames = new Array();
    _.forEach(q.children, function (child) {
        var fullChildName = _get_child_name(child) + " ";
        childrenNames.push(_.repeat(fullChildName + " ~ ", child.count));
    });
    // Join the array and remove the last four characters for " ~ "
    var querySiblings = childrenNames.join('').slice(0, -4);
    return $(selector).children(querySiblings).length >= 1
}

function _get_element_name(element) {
    var selector = element.name
    if (selector == '_') {
        selector = '*'
    }
    selector = _escapeSpecialCharacters(selector)
    if ('attributes' in element) {
        var actualAttributes = _filterExtraAttributes(element.attributes)
        selector += _getAttributeSelectors(actualAttributes)
    }
    return selector
}

function _getAttributeSelectors(attributes) {
    var attributesSelector = ''
    _.forEach(attributes, function (attrib) {
        var idx = attrib['value'].indexOf('*');
        // Attribute value equals to a value
        if (idx == -1) {
            var attribText = '[' + _escapeSpecialCharacters(attrib.name) +
                '="' + _escapeSpecialCharacters(attrib.value) + '"]';
            attributesSelector += attribText
        }
        // Attribute value starts with a value
        else if (idx == attrib['value'].length - 1) {
            var attribText = '[' + _escapeSpecialCharacters(attrib.name)
                + '^="' + _escapeSpecialCharacters(attrib.value.split('*')[0]) + '"]';
            attributesSelector += attribText
        }
        // Attribute value ends with a value
        else if (idx == 0) {
            var attribText = '[' + _escapeSpecialCharacters(attrib.name) +
                '$="' + _escapeSpecialCharacters(attrib.value.split('*')[1]) + '"]';
            attributesSelector += attribText
        }
    })
    return attributesSelector;
}

function _filterExtraAttributes(attributes) {
    return _.filter(attributes, function (attrib) {
        return attrib.name != '__name'
    })
}

function _get_child_name(child) {
    var childName = child.name
    if (childName == '_') {
        childName = '*'
    }
    if ('attributes' in child) {
        var actualAttributes = _filterExtraAttributes(child.attributes)
        childName += _getAttributeSelectors(actualAttributes)
    }
    if (childName != '*') {
        childName = _escapeSpecialCharacters(childName)
    }
    return childName;

}
/**
 * Escape names that use any of JQuery meta-characters as a literal part of a name.
 * @param str a String that may use any of the meta-characters
 * @returns {String} The escaped string with with two backslashes replacing the
 * JQuery's special meta-characters
 * @private
 */
function _escapeSpecialCharacters(str) {
    return str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
}
<commit_msg>fix escaping special characters<commit_after>var _ = require('lodash');
var Promise = require('bluebird');
var chalk = require('chalk');
var apps = require('../../db/apps');
var parse = require('../../parse');
var log = require("../../logger");
var maxManifestResults = require('config').results.maxManifest;

module.exports = {
    init: init,
    find: find
}

function init(env) {
    return apps
        .init("manifest")
        .then(function (ret) {
            env.apps = ret
            return env
        })
}

function find(env, query, options) {
    // If query is not specified, return everything in scope
    if (!query) {
        return Promise.resolve(options.scope);
    }
    var manifestQuery = parse(query);
    // array to collect results
    var results = []
    var count = 0;
    var found = 0;
    // Iterate over ids in the scope
    for (var i = 0; i < options.scope.length; i++) {
        var id = options.scope[i];
        var app = env.apps.get(id, {manifest: true})

        if (app.manifest === undefined || app.manifest === null) {
            return;
        }

        var matcher = _lookup_matcher(manifestQuery)

        // apply the matcher to 'app' to see if it maches
        var matched = matcher(manifestQuery, app)

        // if so
        if (matched) {
            // add to the results array
            results.push(id)
            found++;
        }

        log.info('%d: %s %s', count, chalk.grey(id),
            matched ? chalk.green('yes') : chalk.red('no'))
        count++;

        if (found == maxManifestResults) {
            // the maximum number of UI results have been reached.
            break;
        }
    }

    return Promise.resolve(results);
}

// analyze the pattern of the given query and lookup a matcher to process the query
function _lookup_matcher(q) {
    if (q.children === undefined && q.count === 1) {
        return _find_by_a_single_tag
    }
    else if (q.children === undefined && q.count > 1) {
        return _find_by_siblings
    }
    else if (q.children.length === 1) {
        return _find_by_a_single_tag_with_n_children_of_one_tag
    }
    else if (q.children.length > 1) {
        return _find_by_a_single_tag_with_n_children_of_multiple_tags
    }
    else {
        log.error('Unrecognized query.');
        return function () {
            return false
        }
    }

}

function _find_by_a_single_tag(q, app) {
    var $ = app.manifest
    var selector = _get_element_name(q)

    // find a custom tag like: <com.whatsapp.*/>
    if (selector.indexOf('*') != -1) {
        return _.filter($('*'), function (val) {
            var allAttributesFound = true;
            if (q.attribs.length > 0) {
                allAttributesFound = _.forEach(otherAttributes, function (attribute) {
                    if (val.attribs[attribute.name] != attribute.value) return false;
                })
                return _.startsWith(val.name, selector.split('*')[0]) && allAttributesFound == true
            }
            return _.startsWith(val.name, selector.split('*')[0])
        });
    }
    if ('min' in q) {
        $(selector).length > q.min;
    } else if ('max' in q) {
        $(selector).length < q.count;
    } else if ('exactly' in q) {
        $(selector).length == q.exactly;
    }
    return $(selector).length >= q.count
}

function _find_by_a_single_tag_with_n_children_of_one_tag(q, app) {
    var $ = app.manifest || app
    var selector = _get_element_name(q)
    var childName = _get_child_name(q.children[0])
    var childCount = q.children[0].count
    var result
    if (typeof $ === 'function') {
        // Find each selector that is nth in relation to its sibling selector with the same element name.
        result = (childName === '*') ? $(selector + ' > ' + childName) :
            $(selector + ' > ' + childName + ':nth-of-type(' + childCount + ')')
        return result.length == 1;
    }
    else {
        result = $.children(childName);
    }
    if ('children' in q.children[0] && result.length >= childCount) {
        return _find_by_a_single_tag_with_n_children_of_one_tag(q.children[0], result)
    }
    return result.length >= childCount
}

function _find_by_siblings(q, app) {
    var $ = app.manifest
    var selector = _get_element_name(q)
    var result = $(selector + ':nth-of-type(' + q.count + ')')
    return result.length > 0
}

function _find_by_a_single_tag_with_n_children_of_multiple_tags(q, app) {
    var $ = app.manifest;
    var selector = _get_element_name(q);
    var childrenNames = new Array();
    _.forEach(q.children, function (child) {
        var fullChildName = _get_child_name(child);
        for (var i = 0; i < child.count; i++) {
            childrenNames.push(fullChildName);
        }
    });
    var allChildrenFound = _.every(childrenNames, function (child) {
        return $(selector + " > " + child).length > 0;
    });
    return allChildrenFound === true;
}

function _get_element_name(element) {
    var selector = element.name
    if (selector == '_') {
        selector = '*'
    }
    if ('attributes' in element) {
        var actualAttributes = _filterExtraAttributes(element.attributes)
        selector += _getAttributeSelectors(actualAttributes)
    }
    selector = _escapeSpecialCharacters(selector)
    return selector
}

function _getAttributeSelectors(attributes) {
    var attributesSelector = ''
    _.forEach(attributes, function (attrib) {
        var idx = attrib['value'].indexOf('*');
        // Attribute value equals to a value
        if (idx == -1) {
            var attribText = '[' + (attrib.name) +
                '="' + (attrib.value) + '"]';
            attributesSelector += attribText
        }
        // Attribute value starts with a value
        else if (idx == attrib['value'].length - 1) {
            var attribText = '[' + (attrib.name)
                + '^="' + (attrib.value.split('*')[0]) + '"]';
            attributesSelector += attribText
        }
        // Attribute value ends with a value
        else if (idx == 0) {
            var attribText = '[' + (attrib.name) +
                '$="' + (attrib.value.split('*')[1]) + '"]';
            attributesSelector += attribText
        }
    })
    return attributesSelector;
}

function _filterExtraAttributes(attributes) {
    return _.filter(attributes, function (attrib) {
        return attrib.name != '__name'
    })
}

function _get_child_name(child) {
    var childName = child.name
    if (childName == '_') {
        childName = '*'
    }
    if ('attributes' in child) {
        var actualAttributes = _filterExtraAttributes(child.attributes)
        childName += _getAttributeSelectors(actualAttributes)
    }
    if (childName != '*') {
        childName = _escapeSpecialCharacters(childName)
    }
    return childName;

}

/**
 * Escape names that use any of JQuery meta-characters as a literal part of a name.
 * @param str a String that may use any of the meta-characters
 * @returns {String} The escaped string with two backslashes replacing the
 * JQuery's special meta-characters
 * @private
 */
function _escapeSpecialCharacters(str) {
    var r = str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\$1');
    return r.replace(':', '\\:');
}
<|endoftext|>


<commit_before>var twitter = require('./twitter')
var getSentiment = require('./getSentiments')
var keyword = 'hillary clinton'

module.exports = function (tweets) {
    return Promise.all(tweets.map(function (tweet) {
      return getSentiment(tweet)
    }))
  .then(function (sentimentObjects) {
    return sentimentObjects.filter(function (sentimentObject) {
      return ((sentimentObject.result.score > 0.3) || (sentimentObject.result.score < -0.3))
    }).map(function (sentimentObject) {
        console.log(`Tweet: ${sentimentObject.text} | Confidence: ${sentimentObject.result.score} | Sentiment: ${sentimentObject.result.sentiment}`)
        return sentimentObject.result.sentiment
    })
  })
  .then(function (sentiments) {
      console.log('Done!')
      return sentiments
  })
  .catch(function (err) {
    console.log(err)
  })
}
<commit_msg>Removed old 'twitter' module reference<commit_after>var getSentiment = require('./getSentiments')

module.exports = function (tweets) {
    return Promise.all(tweets.map(function (tweet) {
      return getSentiment(tweet)
    }))
  .then(function (sentimentObjects) {
    return sentimentObjects.filter(function (sentimentObject) {
      return ((sentimentObject.result.score > 0.3) || (sentimentObject.result.score < -0.3))
    }).map(function (sentimentObject) {
        console.log(`Tweet: ${sentimentObject.text} | Confidence: ${sentimentObject.result.score} | Sentiment: ${sentimentObject.result.sentiment}`)
        return sentimentObject.result.sentiment
    })
  })
  .then(function (sentiments) {
      console.log('Done!')
      return sentiments
  })
  .catch(function (err) {
    console.log(err)
  })
}
<|endoftext|>


<commit_before>/*global _*/

var ArgumentInvalidException = require('./custom_exception').ArgumentInvalidException;
var ArgumentNullException = require('./custom_exception').ArgumentNullException;
//Singleton container for all the binders.
var binders = {};

/**
 * Function use to register a binder.
 * @param {object} binder - The binder to register.
 */
function registerBinder(binder){
  if(_.isNull(binder) || !_.isObject(binder)){
    throw new ArgumentInvalidException("Binder to register should be an object and not null", binder);
  }
  if(!_.isString(binder.name)){
    throw new ArgumentInvalidException('binder name should be a string.',binder.name);
  }
  if(!_.isFunction(binder.fn)){
    throw new ArgumentInvalidException('binder value should be a function', binder.fn);
  }
  binders[binder.name] =  binder;
}
/**
 * Function used to call a registered binder.
 * @param {object} binderConf -  The configuration of the binder to call.
 * @param {object} value - The value to bind.
 * @returns {object} - The binder function call result.
 */
function callBinder(binderConf, value){
  if(_.isNull(binderConf) || !_.isObject(binderConf)){
    throw new ArgumentInvalidException("Binder to register should be an object and not null", binderConf);
  }
  if(!_.isString(binderConf.name)){
    throw new ArgumentInvalidException('binder name should be a string.',binderConf.name);
  }
  /*
  if(!_.isNull(binderConf.options) &&!_.isObject(binderConf.options)){
    throw new ArgumentInvalidException('binder value should be a function', binderConf.options);
  }*/
  var binder = binders[binderConf.name];
  if(_.isNull(binder)){
    throw new ArgumentNullException("The binder you are trying to call is not registered, call the registerBinder function", name);
  }
  if(!_.isFunction(binder.fn)){
    throw new ArgumentInvalidException('binder fn should be a function', binder.fn);
  }
  return binder.fn(value, binder.options);
}

/**
 * Helper to deal with the view binders.
 * The input parsed value from the form can be transform.
 * The process is html ->parse ->binder(parse)-> {}.
 * @type {{registerBinder: *, callBinder: *}}
 */

/**
 * @module focus/helpers/binderHelper
 */
module.exports = {
  registerBinder: registerBinder,
  callBinder: callBinder
}<commit_msg>#68 #60[helper][binder] Move js doc comment in order to have the module take into account .<commit_after>/*global _*/
/**
* @module focus/helpers/binderHelper
*/

var ArgumentInvalidException = require('./custom_exception').ArgumentInvalidException;
var ArgumentNullException = require('./custom_exception').ArgumentNullException;
//Singleton container for all the binders.
var binders = {};

/**
 * Function use to register a binder.
 * @param {object} binder - The binder to register.
 */
function registerBinder(binder){
  if(_.isNull(binder) || !_.isObject(binder)){
    throw new ArgumentInvalidException("Binder to register should be an object and not null", binder);
  }
  if(!_.isString(binder.name)){
    throw new ArgumentInvalidException('binder name should be a string.',binder.name);
  }
  if(!_.isFunction(binder.fn)){
    throw new ArgumentInvalidException('binder value should be a function', binder.fn);
  }
  binders[binder.name] =  binder;
}
/**
 * Function used to call a registered binder.
 * @param {object} binderConf -  The configuration of the binder to call.
 * @param {object} value - The value to bind.
 * @returns {object} - The binder function call result.
 */
function callBinder(binderConf, value){
  if(_.isNull(binderConf) || !_.isObject(binderConf)){
    throw new ArgumentInvalidException("Binder to register should be an object and not null", binderConf);
  }
  if(!_.isString(binderConf.name)){
    throw new ArgumentInvalidException('binder name should be a string.',binderConf.name);
  }
  /*
  if(!_.isNull(binderConf.options) &&!_.isObject(binderConf.options)){
    throw new ArgumentInvalidException('binder value should be a function', binderConf.options);
  }*/
  var binder = binders[binderConf.name];
  if(_.isNull(binder)){
    throw new ArgumentNullException("The binder you are trying to call is not registered, call the registerBinder function", name);
  }
  if(!_.isFunction(binder.fn)){
    throw new ArgumentInvalidException('binder fn should be a function', binder.fn);
  }
  return binder.fn(value, binder.options);
}

/**
 * Helper to deal with the view binders.
 * The input parsed value from the form can be transform.
 * The process is html ->parse ->binder(parse)-> {}.
 * @type {{registerBinder: *, callBinder: *}}
 */

module.exports = {
  registerBinder: registerBinder,
  callBinder: callBinder
}
<|endoftext|>


<commit_before>var reqwest = require('reqwest');

// Performs an https request
//
// o.path - the url path
// o.method - GET, PUT, POST, DELETE
// o.data - form data
// o.decodeResponse - function that decodes a successful response
// o.contentType - override content type
// o.callback - an optional callback
module.exports = function(o) {
  var url = 'https://' + this.truevault.getOption('host') + o.path;
  var headers = {
    'Authorization' : this.truevault.getOption('auth')
  };
  var options = {
    url: url,
    method: o.method,
    headers: headers,
    data: o.data,
    contentType: o.contentType || 'application/x-www-form-urlencoded'
  };

  var request = reqwest(options);

  request.then(function(response) {
    if (o.decodeResponse && response.response) {
      return o.decodeResponse(response.response);
    } else {
      return response;
    }
  });

  //TODO: handle error

  if (o.callback) {
    request.then(function success(result) {
      return o.callback(null, result);
    }, function error(e) {
      return o.callback(e);
    });
  }

  return request;
};

<commit_msg>WIP: standardize the way we handle errors<commit_after>var reqwest = require('reqwest');
var error_map = require('../error');
var Q = require('q');

// Performs an https request
//
// o.path - the url path
// o.method - GET, PUT, POST, DELETE
// o.data - form data
// o.decodeResponse - function that decodes a successful response
// o.contentType - override content type
// o.callback - an optional callback
module.exports = function(o) {
  var url = 'https://' + this.truevault.getOption('host') + o.path;
  var headers = {
    'Authorization' : this.truevault.getOption('auth')
  };
  var options = {
    url: url,
    method: o.method,
    headers: headers,
    data: o.data,
    contentType: o.contentType || 'application/x-www-form-urlencoded'
  };

  var deferred = Q.defer();

  function handleResponse(response) {
    if (o.decodeResponse && response.response) {
      deferred.resolve(o.decodeResponse(response.response));
    } else {
      deferred.resolve(response);
    }
  }

  options.success = handleResponse;
  options.error = function(err) {
    console.log(err);
  }

  var request = reqwest(options);

  // request.then(function(response) {
  //   if (o.decodeResponse && response.response) {
  //     return o.decodeResponse(response.response);
  //   } else {
  //     return response;
  //   }
  // }).catch(function(response) {
  //   return createError(response.status, response.responseText);
  // });

  //TODO: handle error

  var promise = deferred.promise;
  if (o.callback) {
    promise.then(function success(result) {
      return o.callback(null, result);
    }, function error(e) {
      return o.callback(e);
    });
  }

  return promise;
};

function createError(statusCode, msg) {
  var errorClass = error_map[statusCode];
  if(!errorClass) {
    return new error_map['default'](msg);
  } else {
    return new errorClass(msg);
  }
}

<|endoftext|>


<commit_before>'use strict'

var afterAll = require('after-all')
var stackman = require('stackman')({ filter: '/node_modules/opbeat/' })
var Transaction = require('./transaction')
var parsers = require('../parsers')
var request = require('../request')

var MAX_QUEUE_SIZE = Infinity
var MAX_SEND_DELAY = 60000

var Instrumentation = module.exports = function (client) {
  if (!(this instanceof Instrumentation)) return new Instrumentation(client)
  this._client = client
  this._queue = []
}

Instrumentation.prototype.add = function (transaction) {
  if (this._client.active && this._client._ff_instrument) {
    this._client.logger.trace('[%s] pushing transaction to queue', transaction._uuid)
    this._queue.push(transaction)
  } else {
    this._client.logger.trace('[%s] ignoring transaction', transaction._uuid)
  }
  if (this._queue.length >= MAX_QUEUE_SIZE) this._send()
  else if (this._queue.length && !this._timeout) this._queueSend()
}

Instrumentation.prototype.startTransaction = function (name, type, result) {
  return new Transaction(this._client, name, type, result)
}

Instrumentation.prototype._send = function () {
  this._client.logger.trace('flushing transaction queue')
  clearTimeout(this._timeout)
  this._timeout = null
  this._flush(function (result) {
    request.transactions(this._client, result) // TODO: Maybe add callback and re-queue stuff incase of a transmission error?
  }.bind(this))
}

Instrumentation.prototype._queueSend = function () {
  this._client.logger.trace('setting timer to flush transaction queue')
  this._timeout = setTimeout(this._send.bind(this), MAX_SEND_DELAY)
  this._timeout.unref()
}

Instrumentation.prototype._flush = function (cb) {
  var transactions = groupTransactions(this._queue)
  var traces = [].concat.apply([], this._queue.map(function (trans) {
    return trans.traces
  }))
  var groups = groupTraces(traces)
  var raw = rawTransactions(this._queue)
  this._queue = []

  addStackTracesToTraceGroups(groups, traces, function () {
    cb({
      transactions: transactions,
      traces: {
        groups: groups,
        raw: raw
      }
    })
  })
}

function groupTransactions (transactions) {
  var groups = groupByMinute(transactions, transactionGroupingKey)

  return Object.keys(groups).map(function (key) {
    var trans = groups[key][0]
    var durations = groups[key].map(function (trans) {
      return trans.duration()
    })
    return {
      transaction: trans.name,
      result: trans.result,
      kind: trans.type,
      timestamp: groupingTs(trans._start).toISOString(),
      durations: durations
    }
  })
}

function rawTransactions (transactions) {
  return transactions.map(function (trans) {
    return [trans.duration()].concat(rawTraces(trans.traces))
  })
}

function rawTraces (traces) {
  return traces.map(function (trace) {
    return [trace._groupIndex, trace.startTime(), trace.duration()]
  })
}

function addStackTracesToTraceGroups (groups, traces, cb) {
  var processed = []
  var next = afterAll(cb)
  traces.forEach(function (trace) {
    var index = trace._groupIndex
    if (~processed.indexOf(index)) return
    processed.push(index)
    var done = next()
    traceFrames(trace, function (frames) {
      groups[index].extra._frames = frames
      done()
    })
  })
}

function groupTraces (traces) {
  var groups = groupByMinute(traces, traceGroupingKey)

  return Object.keys(groups).map(function (key, index) {
    var trace = groups[key][0]
    groups[key].forEach(function (trace) {
      trace._groupIndex = index
    })
    return {
      transaction: trace.transaction.name,
      signature: trace.signature,
      kind: trace.type,
      timestamp: groupingTs(trace._start).toISOString(),
      parents: trace.ancestors(),
      extra: trace.extra || {}
    }
  })
}

function traceFrames (trace, cb) {
  if (trace._stackObj.frames) return process.nextTick(cb.bind(null, trace._stackObj.frames))
  stackman(trace._stackObj.err, function (stack) {
    var frames = stack.frames.map(parsers.parseCallsite)
    trace._stackObj.frames = frames
    cb(frames)
  })
}

function groupByMinute (arr, grouper) {
  var groups = {}

  arr.forEach(function (obj) {
    var key = grouper(obj)
    if (key in groups) groups[key].push(obj)
    else groups[key] = [obj]
  })

  return groups
}

function groupingTs (ts) {
  return new Date(ts.getFullYear(), ts.getMonth(), ts.getDate(), ts.getHours(), ts.getMinutes())
}

function transactionGroupingKey (trans) {
  return groupingTs(trans._start).getTime() + '|' + trans.name + '|' + trans.result + '|' + trans.type
}

function traceGroupingKey (trace) {
  var ancestors = trace.ancestors().map(function (trace) { return trace.signature }).join('|')
  return groupingTs(trace._start).getTime() + '|' + trace.transaction.name + '|' + ancestors + '|' + trace.signature
}
<commit_msg>Remove TODO<commit_after>'use strict'

var afterAll = require('after-all')
var stackman = require('stackman')({ filter: '/node_modules/opbeat/' })
var Transaction = require('./transaction')
var parsers = require('../parsers')
var request = require('../request')

var MAX_QUEUE_SIZE = Infinity
var MAX_SEND_DELAY = 60000

var Instrumentation = module.exports = function (client) {
  if (!(this instanceof Instrumentation)) return new Instrumentation(client)
  this._client = client
  this._queue = []
}

Instrumentation.prototype.add = function (transaction) {
  if (this._client.active && this._client._ff_instrument) {
    this._client.logger.trace('[%s] pushing transaction to queue', transaction._uuid)
    this._queue.push(transaction)
  } else {
    this._client.logger.trace('[%s] ignoring transaction', transaction._uuid)
  }
  if (this._queue.length >= MAX_QUEUE_SIZE) this._send()
  else if (this._queue.length && !this._timeout) this._queueSend()
}

Instrumentation.prototype.startTransaction = function (name, type, result) {
  return new Transaction(this._client, name, type, result)
}

Instrumentation.prototype._send = function () {
  this._client.logger.trace('flushing transaction queue')
  clearTimeout(this._timeout)
  this._timeout = null
  this._flush(function (result) {
    request.transactions(this._client, result)
  }.bind(this))
}

Instrumentation.prototype._queueSend = function () {
  this._client.logger.trace('setting timer to flush transaction queue')
  this._timeout = setTimeout(this._send.bind(this), MAX_SEND_DELAY)
  this._timeout.unref()
}

Instrumentation.prototype._flush = function (cb) {
  var transactions = groupTransactions(this._queue)
  var traces = [].concat.apply([], this._queue.map(function (trans) {
    return trans.traces
  }))
  var groups = groupTraces(traces)
  var raw = rawTransactions(this._queue)
  this._queue = []

  addStackTracesToTraceGroups(groups, traces, function () {
    cb({
      transactions: transactions,
      traces: {
        groups: groups,
        raw: raw
      }
    })
  })
}

function groupTransactions (transactions) {
  var groups = groupByMinute(transactions, transactionGroupingKey)

  return Object.keys(groups).map(function (key) {
    var trans = groups[key][0]
    var durations = groups[key].map(function (trans) {
      return trans.duration()
    })
    return {
      transaction: trans.name,
      result: trans.result,
      kind: trans.type,
      timestamp: groupingTs(trans._start).toISOString(),
      durations: durations
    }
  })
}

function rawTransactions (transactions) {
  return transactions.map(function (trans) {
    return [trans.duration()].concat(rawTraces(trans.traces))
  })
}

function rawTraces (traces) {
  return traces.map(function (trace) {
    return [trace._groupIndex, trace.startTime(), trace.duration()]
  })
}

function addStackTracesToTraceGroups (groups, traces, cb) {
  var processed = []
  var next = afterAll(cb)
  traces.forEach(function (trace) {
    var index = trace._groupIndex
    if (~processed.indexOf(index)) return
    processed.push(index)
    var done = next()
    traceFrames(trace, function (frames) {
      groups[index].extra._frames = frames
      done()
    })
  })
}

function groupTraces (traces) {
  var groups = groupByMinute(traces, traceGroupingKey)

  return Object.keys(groups).map(function (key, index) {
    var trace = groups[key][0]
    groups[key].forEach(function (trace) {
      trace._groupIndex = index
    })
    return {
      transaction: trace.transaction.name,
      signature: trace.signature,
      kind: trace.type,
      timestamp: groupingTs(trace._start).toISOString(),
      parents: trace.ancestors(),
      extra: trace.extra || {}
    }
  })
}

function traceFrames (trace, cb) {
  if (trace._stackObj.frames) return process.nextTick(cb.bind(null, trace._stackObj.frames))
  stackman(trace._stackObj.err, function (stack) {
    var frames = stack.frames.map(parsers.parseCallsite)
    trace._stackObj.frames = frames
    cb(frames)
  })
}

function groupByMinute (arr, grouper) {
  var groups = {}

  arr.forEach(function (obj) {
    var key = grouper(obj)
    if (key in groups) groups[key].push(obj)
    else groups[key] = [obj]
  })

  return groups
}

function groupingTs (ts) {
  return new Date(ts.getFullYear(), ts.getMonth(), ts.getDate(), ts.getHours(), ts.getMinutes())
}

function transactionGroupingKey (trans) {
  return groupingTs(trans._start).getTime() + '|' + trans.name + '|' + trans.result + '|' + trans.type
}

function traceGroupingKey (trace) {
  var ancestors = trace.ancestors().map(function (trace) { return trace.signature }).join('|')
  return groupingTs(trace._start).getTime() + '|' + trace.transaction.name + '|' + ancestors + '|' + trace.signature
}
<|endoftext|>


<commit_before>(function() {
  //
  // Imports
  //
  var util;
  try {
    util = require('util')
  } catch(e) {
    util = require('sys')
  }

  var jasmineNode = {};
  //
  // Helpers
  //
  function noop() {}

  jasmineNode.TerminalReporter = function(config) {
    this.print_ = config.print || function (str) { process.stdout.write(util.format(str)); };
    this.color_ = config.color ? this.ANSIColors : this.NoColors;

    this.started_ = false;
    this.finished_ = false;

    this.callback_ = config.onComplete || false

    this.suites_ = [];
    this.specResults_ = {};
    this.failures_ = [];
    this.includeStackTrace_ = config.includeStackTrace === false ? false : true;
    this.stackFilter_ = config.stackFilter || function(t) { return t; };
  }

  jasmineNode.TerminalReporter.prototype = {
    reportRunnerStarting: function(runner) {
      this.started_ = true;
      this.startedAt = new Date();
      var suites = runner.topLevelSuites();
      for (var i = 0; i < suites.length; i++) {
        var suite = suites[i];
        this.suites_.push(this.summarize_(suite));
      }
    },

    ANSIColors: {
        pass:    function() { return '\033[32m'; }, // Green
        fail:    function() { return '\033[31m'; }, // Red
        specTiming:  function()  { return '\033[34m'; }, // Blue
        suiteTiming:  function() { return '\033[33m'; }, // Yelow
        ignore:  function() { return '\033[37m'; }, // Light Gray
        neutral: function() { return '\033[0m';  }  // Normal
    },

    NoColors: {
        pass:    function() { return ''; },
        fail:    function() { return ''; },
        specTiming:  function() { return ''; },
        suiteTiming: function() { return ''; },
        ignore:  function() { return ''; },
        neutral: function() { return ''; }
    },

    summarize_: function(suiteOrSpec) {
      var isSuite = suiteOrSpec instanceof jasmine.Suite;

      // We could use a separate object for suite and spec
      var summary = {
        id: suiteOrSpec.id,
        name: suiteOrSpec.description,
        type: isSuite? 'suite' : 'spec',
        suiteNestingLevel: 0,
        children: []
      };

      if (isSuite) {
        var calculateNestingLevel = function(examinedSuite) {
          var nestingLevel = 0;
          while (examinedSuite.parentSuite !== null) {
            nestingLevel += 1;
            examinedSuite = examinedSuite.parentSuite;
          }
          return nestingLevel;
        };

        summary.suiteNestingLevel = calculateNestingLevel(suiteOrSpec);

        var children = suiteOrSpec.children();
        for (var i = 0; i < children.length; i++) {
          summary.children.push(this.summarize_(children[i]));
        }
      }

      return summary;
    },

    // This is heavily influenced by Jasmine's Html/Trivial Reporter
    reportRunnerResults: function(runner) {
      this.reportFailures_();

      var results = runner.results();
      var resultColor = (results.failedCount > 0) ? this.color_.fail() : this.color_.pass();

      var specs = runner.specs();
      var specCount = specs.length;

      var message = "\n\nFinished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + " seconds";
      this.printLine_(message);

      // This is what jasmine-html.js has
      //message = "" + specCount + " spec" + ( specCount === 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount === 1) ? "" : "s");

      this.printLine_(this.stringWithColor_(this.printRunnerResults_(runner), resultColor));

      this.finished_ = true;
      if(this.callback_) { this.callback_(runner); }
    },

    reportFailures_: function() {
      if (this.failures_.length === 0) {
        return;
      }

      var indent = '  ', failure;
      this.printLine_('\n');

      this.print_('Failures:');

      for (var i = 0; i < this.failures_.length; i++) {
        failure = this.failures_[i];
        this.printLine_('\n');
        this.printLine_('  ' + (i + 1) + ') ' + failure.spec);
        this.printLine_('   Message:');
        this.printLine_('     ' + this.stringWithColor_(failure.message, this.color_.fail()));
        if (this.includeStackTrace_) {
            this.printLine_('   Stacktrace:');
            this.print_('     ' + this.stackFilter_(failure.stackTrace));
        }
      }
    },

    reportSuiteResults: function(suite) {
      // Not used in this context
    },

    reportSpecResults: function(spec) {
      var result = spec.results();
      var msg = '';
      if (result.skipped) {
        msg = this.stringWithColor_('-', this.color_.ignore());
      } else if (result.passed()) {
        msg = this.stringWithColor_('.', this.color_.pass());
      } else {
        msg = this.stringWithColor_('F', this.color_.fail());
        this.addFailureToFailures_(spec);
      }
      this.spec_results += msg;
      this.print_(msg);
    },

    addFailureToFailures_: function(spec) {
      var result = spec.results();
      var failureItem = null;

      var items_length = result.items_.length;
      for (var i = 0; i < items_length; i++) {
        if (result.items_[i].passed_ === false) {
          failureItem = result.items_[i];

          var failure = {
            spec: spec.suite.getFullName() + " " + spec.description,
            message: failureItem.message,
            stackTrace: failureItem.trace.stack
          }

          this.failures_.push(failure);
        }
      }
    },

    printRunnerResults_: function(runner){
      var results = runner.results();
      var specs = runner.specs();
      var msg = '';
      var skippedCount = 0;
      specs.forEach(function(spec) {
        if (spec.results().skipped) {
          skippedCount++;
        }
      });
      var passedCount = specs.length - skippedCount;
      msg += passedCount + ' test' + ((passedCount === 1) ? '' : 's') + ', ';
      msg += results.totalCount + ' assertion' + ((results.totalCount === 1) ? '' : 's') + ', ';
      msg += results.failedCount + ' failure' + ((results.failedCount === 1) ? '' : 's') + ', ';
      msg += skippedCount + ' skipped' + '\n';
      return msg;
    },

      // Helper Methods //
    stringWithColor_: function(stringValue, color) {
      return (color || this.color_.neutral()) + stringValue + this.color_.neutral();
    },

    printLine_: function(stringValue) {
      this.print_(stringValue);
      this.print_('\n');
    }
  };

  // ***************************************************************
  // TerminalVerboseReporter uses the TerminalReporter's constructor
  // ***************************************************************
  jasmineNode.TerminalVerboseReporter = function(config) {
    jasmineNode.TerminalReporter.call(this, config);
    // The extra field in this object
    this.indent_ = 0;
    this.specTimes_ = {};
    this.suiteTimes_ = {};
    this.suiteResults_ = {};
  }

  jasmineNode.TerminalVerboseReporter.prototype = {

    reportSpecStarting: function(spec) {
        this.specTimes_[spec.id] = new Date().getTime();
        var suite = spec.suite;
        while (suite) {
            if (!this.suiteTimes_[suite.id]) {
                this.suiteTimes_[suite.id] = new Date().getTime();
            }
            suite = suite.parentSuite;
        }
    },

    reportSpecResults: function(spec) {
      var elapsed = new Date().getTime() - this.specTimes_[spec.id];

      if (spec.results().failedCount > 0) {
        this.addFailureToFailures_(spec);
      }

      this.specResults_[spec.id] = {
        messages: spec.results().getItems(),
        result: spec.results().failedCount > 0 ? 'failed' : 'passed',
        runtime: elapsed
      };
    },

    reportSuiteResults: function(suite) {
        var startTime = this.suiteTimes_[suite.id];
        if (startTime) {
            var elapsed = new Date().getTime() - startTime;
            this.suiteResults_[suite.id] = {
                runtime: elapsed
            };
        }
    },

    reportRunnerResults: function(runner) {
      var messages = new Array();
      this.buildMessagesFromResults_(messages, this.suites_);

      var messages_length = messages.length;
      for (var i = 0; i < messages_length-1; i++) {
        this.printLine_(messages[i]);
      }

      this.print_(messages[messages_length-1]);

      // Call the parent object's method
      jasmineNode.TerminalReporter.prototype.reportRunnerResults.call(this, runner);
    },

    buildMessagesFromResults_: function(messages, results, depth) {
      var element, specResult, specIndentSpaces, msg = '';
      depth = (depth === undefined) ? 0 : depth;

      var results_length = results.length;
      for (var i = 0; i < results_length; i++) {
        element = results[i];

        if (element.type === 'spec') {
          specResult = this.specResults_[element.id.toString()];

          if (specResult.result === 'passed') {
            msg = this.stringWithColor_(this.indentMessage_(element.name, depth), this.color_.pass());
          } else {
            msg = this.stringWithColor_(this.indentMessage_(element.name, depth), this.color_.fail());
          }
          msg += this.stringWithColor_(" - " + specResult.runtime + " ms",
                                       this.color_.specTiming());

          messages.push(msg);
        } else {
          messages.push('');
          msg = this.indentMessage_(element.name, depth)
          if (element.id != null) {
              suiteResult = this.suiteResults_[element.id.toString()];
              if (suiteResult) {
                  msg += this.stringWithColor_(" - " + suiteResult.runtime + " ms", this.color_.suiteTiming());
              }
          }
          messages.push(msg);
        }

        this.buildMessagesFromResults_(messages, element.children, depth + 2);
      }
    },

    indentMessage_: function(message, indentCount) {
      var _indent = '';
      for (var i = 0; i < indentCount; i++) {
        _indent += '  ';
      }
      return (_indent + message);
    }
  };

  // Inherit from TerminalReporter
  jasmineNode.TerminalVerboseReporter.prototype.__proto__ = jasmineNode.TerminalReporter.prototype;

  //
  // Exports
  //
  exports.jasmineNode = jasmineNode;
})();
<commit_msg>reuse Date.getTime() for suites and specs that start together<commit_after>(function() {
  //
  // Imports
  //
  var util;
  try {
    util = require('util')
  } catch(e) {
    util = require('sys')
  }

  var jasmineNode = {};
  //
  // Helpers
  //
  function noop() {}

  jasmineNode.TerminalReporter = function(config) {
    this.print_ = config.print || function (str) { process.stdout.write(util.format(str)); };
    this.color_ = config.color ? this.ANSIColors : this.NoColors;

    this.started_ = false;
    this.finished_ = false;

    this.callback_ = config.onComplete || false

    this.suites_ = [];
    this.specResults_ = {};
    this.failures_ = [];
    this.includeStackTrace_ = config.includeStackTrace === false ? false : true;
    this.stackFilter_ = config.stackFilter || function(t) { return t; };
  }

  jasmineNode.TerminalReporter.prototype = {
    reportRunnerStarting: function(runner) {
      this.started_ = true;
      this.startedAt = new Date();
      var suites = runner.topLevelSuites();
      for (var i = 0; i < suites.length; i++) {
        var suite = suites[i];
        this.suites_.push(this.summarize_(suite));
      }
    },

    ANSIColors: {
        pass:    function() { return '\033[32m'; }, // Green
        fail:    function() { return '\033[31m'; }, // Red
        specTiming:  function()  { return '\033[34m'; }, // Blue
        suiteTiming:  function() { return '\033[33m'; }, // Yelow
        ignore:  function() { return '\033[37m'; }, // Light Gray
        neutral: function() { return '\033[0m';  }  // Normal
    },

    NoColors: {
        pass:    function() { return ''; },
        fail:    function() { return ''; },
        specTiming:  function() { return ''; },
        suiteTiming: function() { return ''; },
        ignore:  function() { return ''; },
        neutral: function() { return ''; }
    },

    summarize_: function(suiteOrSpec) {
      var isSuite = suiteOrSpec instanceof jasmine.Suite;

      // We could use a separate object for suite and spec
      var summary = {
        id: suiteOrSpec.id,
        name: suiteOrSpec.description,
        type: isSuite? 'suite' : 'spec',
        suiteNestingLevel: 0,
        children: []
      };

      if (isSuite) {
        var calculateNestingLevel = function(examinedSuite) {
          var nestingLevel = 0;
          while (examinedSuite.parentSuite !== null) {
            nestingLevel += 1;
            examinedSuite = examinedSuite.parentSuite;
          }
          return nestingLevel;
        };

        summary.suiteNestingLevel = calculateNestingLevel(suiteOrSpec);

        var children = suiteOrSpec.children();
        for (var i = 0; i < children.length; i++) {
          summary.children.push(this.summarize_(children[i]));
        }
      }

      return summary;
    },

    // This is heavily influenced by Jasmine's Html/Trivial Reporter
    reportRunnerResults: function(runner) {
      this.reportFailures_();

      var results = runner.results();
      var resultColor = (results.failedCount > 0) ? this.color_.fail() : this.color_.pass();

      var specs = runner.specs();
      var specCount = specs.length;

      var message = "\n\nFinished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + " seconds";
      this.printLine_(message);

      // This is what jasmine-html.js has
      //message = "" + specCount + " spec" + ( specCount === 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount === 1) ? "" : "s");

      this.printLine_(this.stringWithColor_(this.printRunnerResults_(runner), resultColor));

      this.finished_ = true;
      if(this.callback_) { this.callback_(runner); }
    },

    reportFailures_: function() {
      if (this.failures_.length === 0) {
        return;
      }

      var indent = '  ', failure;
      this.printLine_('\n');

      this.print_('Failures:');

      for (var i = 0; i < this.failures_.length; i++) {
        failure = this.failures_[i];
        this.printLine_('\n');
        this.printLine_('  ' + (i + 1) + ') ' + failure.spec);
        this.printLine_('   Message:');
        this.printLine_('     ' + this.stringWithColor_(failure.message, this.color_.fail()));
        if (this.includeStackTrace_) {
            this.printLine_('   Stacktrace:');
            this.print_('     ' + this.stackFilter_(failure.stackTrace));
        }
      }
    },

    reportSuiteResults: function(suite) {
      // Not used in this context
    },

    reportSpecResults: function(spec) {
      var result = spec.results();
      var msg = '';
      if (result.skipped) {
        msg = this.stringWithColor_('-', this.color_.ignore());
      } else if (result.passed()) {
        msg = this.stringWithColor_('.', this.color_.pass());
      } else {
        msg = this.stringWithColor_('F', this.color_.fail());
        this.addFailureToFailures_(spec);
      }
      this.spec_results += msg;
      this.print_(msg);
    },

    addFailureToFailures_: function(spec) {
      var result = spec.results();
      var failureItem = null;

      var items_length = result.items_.length;
      for (var i = 0; i < items_length; i++) {
        if (result.items_[i].passed_ === false) {
          failureItem = result.items_[i];

          var failure = {
            spec: spec.suite.getFullName() + " " + spec.description,
            message: failureItem.message,
            stackTrace: failureItem.trace.stack
          }

          this.failures_.push(failure);
        }
      }
    },

    printRunnerResults_: function(runner){
      var results = runner.results();
      var specs = runner.specs();
      var msg = '';
      var skippedCount = 0;
      specs.forEach(function(spec) {
        if (spec.results().skipped) {
          skippedCount++;
        }
      });
      var passedCount = specs.length - skippedCount;
      msg += passedCount + ' test' + ((passedCount === 1) ? '' : 's') + ', ';
      msg += results.totalCount + ' assertion' + ((results.totalCount === 1) ? '' : 's') + ', ';
      msg += results.failedCount + ' failure' + ((results.failedCount === 1) ? '' : 's') + ', ';
      msg += skippedCount + ' skipped' + '\n';
      return msg;
    },

      // Helper Methods //
    stringWithColor_: function(stringValue, color) {
      return (color || this.color_.neutral()) + stringValue + this.color_.neutral();
    },

    printLine_: function(stringValue) {
      this.print_(stringValue);
      this.print_('\n');
    }
  };

  // ***************************************************************
  // TerminalVerboseReporter uses the TerminalReporter's constructor
  // ***************************************************************
  jasmineNode.TerminalVerboseReporter = function(config) {
    jasmineNode.TerminalReporter.call(this, config);
    // The extra field in this object
    this.indent_ = 0;
    this.specTimes_ = {};
    this.suiteTimes_ = {};
    this.suiteResults_ = {};
  }

  jasmineNode.TerminalVerboseReporter.prototype = {

    reportSpecStarting: function(spec) {
        now = new Date().getTime();
        this.specTimes_[spec.id] = now;
        var suite = spec.suite;
        while (suite) {
            if (!this.suiteTimes_[suite.id]) {
                this.suiteTimes_[suite.id] = now;
            }
            suite = suite.parentSuite;
        }
    },

    reportSpecResults: function(spec) {
      var elapsed = new Date().getTime() - this.specTimes_[spec.id];

      if (spec.results().failedCount > 0) {
        this.addFailureToFailures_(spec);
      }

      this.specResults_[spec.id] = {
        messages: spec.results().getItems(),
        result: spec.results().failedCount > 0 ? 'failed' : 'passed',
        runtime: elapsed
      };
    },

    reportSuiteResults: function(suite) {
        var startTime = this.suiteTimes_[suite.id];
        if (startTime) {
            var elapsed = new Date().getTime() - startTime;
            this.suiteResults_[suite.id] = {
                runtime: elapsed
            };
        }
    },

    reportRunnerResults: function(runner) {
      var messages = new Array();
      this.buildMessagesFromResults_(messages, this.suites_);

      var messages_length = messages.length;
      for (var i = 0; i < messages_length-1; i++) {
        this.printLine_(messages[i]);
      }

      this.print_(messages[messages_length-1]);

      // Call the parent object's method
      jasmineNode.TerminalReporter.prototype.reportRunnerResults.call(this, runner);
    },

    buildMessagesFromResults_: function(messages, results, depth) {
      var element, specResult, specIndentSpaces, msg = '';
      depth = (depth === undefined) ? 0 : depth;

      var results_length = results.length;
      for (var i = 0; i < results_length; i++) {
        element = results[i];

        if (element.type === 'spec') {
          specResult = this.specResults_[element.id.toString()];

          if (specResult.result === 'passed') {
            msg = this.stringWithColor_(this.indentMessage_(element.name, depth), this.color_.pass());
          } else {
            msg = this.stringWithColor_(this.indentMessage_(element.name, depth), this.color_.fail());
          }
          msg += this.stringWithColor_(" - " + specResult.runtime + " ms",
                                       this.color_.specTiming());

          messages.push(msg);
        } else {
          messages.push('');
          msg = this.indentMessage_(element.name, depth)
          if (element.id != null) {
              suiteResult = this.suiteResults_[element.id.toString()];
              if (suiteResult) {
                  msg += this.stringWithColor_(" - " + suiteResult.runtime + " ms", this.color_.suiteTiming());
              }
          }
          messages.push(msg);
        }

        this.buildMessagesFromResults_(messages, element.children, depth + 2);
      }
    },

    indentMessage_: function(message, indentCount) {
      var _indent = '';
      for (var i = 0; i < indentCount; i++) {
        _indent += '  ';
      }
      return (_indent + message);
    }
  };

  // Inherit from TerminalReporter
  jasmineNode.TerminalVerboseReporter.prototype.__proto__ = jasmineNode.TerminalReporter.prototype;

  //
  // Exports
  //
  exports.jasmineNode = jasmineNode;
})();
<|endoftext|>


<commit_before>import Vue from 'vue'
import VueTippy from './vue-tippy-2.1.3/dist/vue-tippy.min'
import store from './store'
import * as action_types from './store/action-types'
import * as mutation_types from './store/mutation-types'
import directions_point from './api/directions-point'
import VueAutosize from 'vue-autosize';
import VuejsDialog from 'vuejs-dialog';
import VueCollapse from 'vue2-collapse'
import 'vuejs-dialog/dist/vuejs-dialog.min.css';
import ReplaceAppendModal from './ui-cards/ReplaceAppendModal';
import RmisLocation from './ui-cards/RmisLocation'
import Fragment from 'vue-fragment'
import './styles.scss';

const VueInputMask = require('vue-inputmask').default;

Vue.use(VuejsDialog, {
    okText: 'Подтвердить',
    cancelText: 'Отмена',
    animation: 'fade'
});
Vue.use(VueAutosize)
Vue.use(VueTippy)
Vue.use(VueInputMask)
Vue.use(VueCollapse)
Vue.use(Tippy)
Vue.use(Fragment.Plugin)

const promiseFinally = require('promise.prototype.finally');
Vue.dialog.registerComponent('replace-append-modal', ReplaceAppendModal);
promiseFinally.shim();

new Vue({
  el: '#app',
  store,
  components: {
    'JournalGetMaterialModal': () => import('@/modals/JournalGetMaterialModal'),
    'StatisticsTicketsPrintModal': () => import('@/modals/StatisticsTicketsPrintModal'),
    'StatisticsResearchesPrintModal': () => import('@/modals/StatisticsResearchesPrintModal'),
    'DepartmentsForm': () => import('@/forms/DepartmentsForm'),
    'LaboratoryTune': () => import('@/forms/LaboratoryTune'),
    'Directions': () => import('@/pages/Directions'),
    'Cases': () => import('@/pages/Cases'),
    'ConstructParaclinic': () => import('@/construct/ConstructParaclinic'),
    'ConstructTemplates': () => import('@/construct/ConstructTemplates'),
    'ConstructBacteria': () => import('@/construct/ConstructBacteria'),
    'ResultsParaclinic': () => import('@/pages/ResultsParaclinic'),
    'StatisticsTickets': () => import('@/pages/StatisticsTickets'),
    'DirectionVisit': () => import('@/pages/DirectionVisit'),
    'PlanOperations': () => import('@/pages/PlanOperations'),
    'ResultsDepartment': () => import('@/pages/ResultsDepartment'),
    'ResultsReport': () => import('@/pages/ResultsReport'),
    // 'RmqManagement': () => import('@/ui-cards/RmqManagement'),
    'DirectionSteps': () => import('@/ui-cards/DirectionSteps'),
    'Favorites': () => import('@/ui-cards/Favorites'),
    'OperationPlans': () => import('@/ui-cards/OperationPlans'),
    'CardReader': () => import('@/ui-cards/CardReader'),
    'RmisConfirm': () => import('@/pages/RmisConfirm'),
    'Profiles': () => import('@/pages/Profiles'),
    'EmployeeJobs': () => import('@/pages/EmployeeJobs'),
    'Stationar': () => import('@/pages/Stationar'),
    // RmisLocation,
  },
  data: {
    timeouts: {},
  },
  computed: {
    inLoading() {
      return this.$store.getters.inLoading
    },
    loadingLabel() {
      return this.$store.getters.loadingLabel
    }
  },
  watch: {
    inLoading(n, o) {
      if (n && !o) {
        sl()
      }
      if (!n && o) {
        hl()
      }
    }
  },
  created() {
    this.$store.watch((state) => (state.departments.all), () => {
      let diff = this.$store.getters.diff_departments
      this.$store.dispatch(action_types.UPDATE_DEPARTMENTS, {type_update: 'update', to_update: diff}).then((ok) => {
        if (Array.isArray(ok) && ok.length > 0) {
          for (let r of ok) {
            this.$store.commit(mutation_types.SET_UPDATED_DEPARTMENT, {pk: r.pk, value: true})
            if (this.timeouts.hasOwnProperty(r.pk) && this.timeouts[r.pk] !== null) {
              clearTimeout(this.timeouts[r.pk])
              this.timeouts[r.pk] = null
            }
            this.timeouts[r.pk] = (function (vm, r) {
              return setTimeout(() => {
                this.$store.commit(mutation_types.SET_UPDATED_DEPARTMENT, {pk: r.pk, value: false})
                this.timeouts[r.pk] = null
              }, 2000)
            })(vm, r)
          }
        }
      })
    }, {deep: true})

    this.$store.dispatch(action_types.INC_LOADING)
    this.$store.dispatch(action_types.GET_ALL_DEPARTMENTS).then(() => {
      this.$store.dispatch(action_types.DEC_LOADING)
    })

    this.$store.dispatch(action_types.INC_LOADING)
    this.$store.dispatch(action_types.GET_BASES).then(() => {
      this.$store.dispatch(action_types.DEC_LOADING)
    })

    this.$store.dispatch(action_types.INC_LOADING)
    this.$store.dispatch(action_types.GET_USER_DATA).then(() => {
      this.$store.dispatch(action_types.DEC_LOADING)
    })

    function printForm(tpl, pks) {
      if (!pks || pks.length === 0) {
        return;
      }
      window.open(tpl.replace('{pks}', JSON.stringify(pks)), '_blank')
    }

    const hosp = window.location.href.includes('/stationar') ? 1 : 0;

    this.$root.$on('print:directions', (pks) => printForm('/directions/pdf?napr_id={pks}', pks))
    this.$root.$on('print:hosp', (pks) => printForm('/barcodes/hosp?napr_id={pks}', pks))
    this.$root.$on('print:directions:contract', (pks) => printForm('/directions/pdf?napr_id={pks}&contract=1', pks))

    this.$root.$on('print:barcodes', (pks) => printForm('/barcodes/tubes?napr_id={pks}', pks))
    this.$root.$on('print:barcodes:iss', (pks) => printForm('/barcodes/tubes?iss_ids={pks}', pks))

    this.$root.$on('print:results', (pks) => printForm(`/results/preview?pk={pks}&hosp=${hosp}`, pks))
    this.$root.$on('print:directions_list', (pks) => printForm('/statistic/xls?pk={pks}&type=directions_list', pks))

    this.$root.$on('generate-directions', ({
                                             type, card_pk, fin_source_pk, diagnos, base,
                                             researches, operator, ofname, history_num, comments,
                                             counts, for_rmis, rmis_data, callback, vich_code, count,
                                             discount, need_contract,
                                             parent_iss=null, kk='', localizations={}, service_locations={},
                                             direction_purpose='NONE', directions_count=1, external_organization='NONE',
                                             parent_slave_hosp=null,
                                           }) => {
      if (card_pk === -1) {
        errmessage('Не выбрана карта')
        return
      }
      if (fin_source_pk === -1) {
        errmessage('Не выбран источник финансирования')
        return
      }
      if (Object.keys(researches).length === 0) {
        errmessage('Не выбраны исследования')
        return
      }
      if (operator && ofname < 0) {
        errmessage('Не выбрано, от чьего имени выписываются направления')
        return
      }
      this.$store.dispatch(action_types.INC_LOADING)
      directions_point.sendDirections({
        card_pk, diagnos, fin_source: fin_source_pk, history_num,
        ofname_pk: ofname, researches, comments, for_rmis,
        rmis_data, vich_code, count, discount, parent_iss, counts, localizations, service_locations,
        direction_purpose, directions_count, external_organization, parent_slave_hosp,
      }).then(data => {
        this.$store.dispatch(action_types.DEC_LOADING)

        if (data.ok) {
          if (type === 'direction') {
            if (need_contract) {
              this.$root.$emit('print:directions:contract', data.directions)
            } else {
              this.$root.$emit('print:directions', data.directions)
            }
          }
          if (type === 'barcode') {
            this.$root.$emit('print:barcodes', data.directions)
          }
          if (type === 'just-save' || type === 'barcode') {
            okmessage('Направления созданы', 'Номера: ' + data.directions.join(', '))
          }
          this.$root.$emit('researches-picker:clear_all'+kk)
          this.$root.$emit('researches-picker:directions_created'+kk)
        } else {
          errmessage('Направления не созданы', data.message)
        }
        if (callback)
          callback()
      })
    })
  }
});
<commit_msg>Cleanup<commit_after>import Vue from 'vue'
import VueTippy from './vue-tippy-2.1.3/dist/vue-tippy.min'
import store from './store'
import * as action_types from './store/action-types'
import * as mutation_types from './store/mutation-types'
import directions_point from './api/directions-point'
import VueAutosize from 'vue-autosize';
import VuejsDialog from 'vuejs-dialog';
import VueCollapse from 'vue2-collapse'
import 'vuejs-dialog/dist/vuejs-dialog.min.css';
import ReplaceAppendModal from './ui-cards/ReplaceAppendModal';
import Fragment from 'vue-fragment'
import './styles.scss';

const VueInputMask = require('vue-inputmask').default;

Vue.use(VuejsDialog, {
    okText: 'Подтвердить',
    cancelText: 'Отмена',
    animation: 'fade'
});
Vue.use(VueAutosize)
Vue.use(VueTippy)
Vue.use(VueInputMask)
Vue.use(VueCollapse)
Vue.use(Tippy)
Vue.use(Fragment.Plugin)

const promiseFinally = require('promise.prototype.finally');
Vue.dialog.registerComponent('replace-append-modal', ReplaceAppendModal);
promiseFinally.shim();

new Vue({
  el: '#app',
  store,
  components: {
    'JournalGetMaterialModal': () => import('@/modals/JournalGetMaterialModal'),
    'StatisticsTicketsPrintModal': () => import('@/modals/StatisticsTicketsPrintModal'),
    'StatisticsResearchesPrintModal': () => import('@/modals/StatisticsResearchesPrintModal'),
    'DepartmentsForm': () => import('@/forms/DepartmentsForm'),
    'LaboratoryTune': () => import('@/forms/LaboratoryTune'),
    'Directions': () => import('@/pages/Directions'),
    'Cases': () => import('@/pages/Cases'),
    'ConstructParaclinic': () => import('@/construct/ConstructParaclinic'),
    'ConstructTemplates': () => import('@/construct/ConstructTemplates'),
    'ConstructBacteria': () => import('@/construct/ConstructBacteria'),
    'ResultsParaclinic': () => import('@/pages/ResultsParaclinic'),
    'StatisticsTickets': () => import('@/pages/StatisticsTickets'),
    'DirectionVisit': () => import('@/pages/DirectionVisit'),
    'PlanOperations': () => import('@/pages/PlanOperations'),
    'ResultsDepartment': () => import('@/pages/ResultsDepartment'),
    'ResultsReport': () => import('@/pages/ResultsReport'),
    'DirectionSteps': () => import('@/ui-cards/DirectionSteps'),
    'Favorites': () => import('@/ui-cards/Favorites'),
    'OperationPlans': () => import('@/ui-cards/OperationPlans'),
    'CardReader': () => import('@/ui-cards/CardReader'),
    'RmisConfirm': () => import('@/pages/RmisConfirm'),
    'Profiles': () => import('@/pages/Profiles'),
    'EmployeeJobs': () => import('@/pages/EmployeeJobs'),
    'Stationar': () => import('@/pages/Stationar'),
  },
  data: {
    timeouts: {},
  },
  computed: {
    inLoading() {
      return this.$store.getters.inLoading
    },
    loadingLabel() {
      return this.$store.getters.loadingLabel
    }
  },
  watch: {
    inLoading(n, o) {
      if (n && !o) {
        sl()
      }
      if (!n && o) {
        hl()
      }
    }
  },
  created() {
    this.$store.watch((state) => (state.departments.all), () => {
      let diff = this.$store.getters.diff_departments
      this.$store.dispatch(action_types.UPDATE_DEPARTMENTS, {type_update: 'update', to_update: diff}).then((ok) => {
        if (Array.isArray(ok) && ok.length > 0) {
          for (let r of ok) {
            this.$store.commit(mutation_types.SET_UPDATED_DEPARTMENT, {pk: r.pk, value: true})
            if (this.timeouts.hasOwnProperty(r.pk) && this.timeouts[r.pk] !== null) {
              clearTimeout(this.timeouts[r.pk])
              this.timeouts[r.pk] = null
            }
            this.timeouts[r.pk] = (function (vm, r) {
              return setTimeout(() => {
                this.$store.commit(mutation_types.SET_UPDATED_DEPARTMENT, {pk: r.pk, value: false})
                this.timeouts[r.pk] = null
              }, 2000)
            })(vm, r)
          }
        }
      })
    }, {deep: true})

    this.$store.dispatch(action_types.INC_LOADING)
    this.$store.dispatch(action_types.GET_ALL_DEPARTMENTS).then(() => {
      this.$store.dispatch(action_types.DEC_LOADING)
    })

    this.$store.dispatch(action_types.INC_LOADING)
    this.$store.dispatch(action_types.GET_BASES).then(() => {
      this.$store.dispatch(action_types.DEC_LOADING)
    })

    this.$store.dispatch(action_types.INC_LOADING)
    this.$store.dispatch(action_types.GET_USER_DATA).then(() => {
      this.$store.dispatch(action_types.DEC_LOADING)
    })

    function printForm(tpl, pks) {
      if (!pks || pks.length === 0) {
        return;
      }
      window.open(tpl.replace('{pks}', JSON.stringify(pks)), '_blank')
    }

    const hosp = window.location.href.includes('/stationar') ? 1 : 0;

    this.$root.$on('print:directions', (pks) => printForm('/directions/pdf?napr_id={pks}', pks))
    this.$root.$on('print:hosp', (pks) => printForm('/barcodes/hosp?napr_id={pks}', pks))
    this.$root.$on('print:directions:contract', (pks) => printForm('/directions/pdf?napr_id={pks}&contract=1', pks))

    this.$root.$on('print:barcodes', (pks) => printForm('/barcodes/tubes?napr_id={pks}', pks))
    this.$root.$on('print:barcodes:iss', (pks) => printForm('/barcodes/tubes?iss_ids={pks}', pks))

    this.$root.$on('print:results', (pks) => printForm(`/results/preview?pk={pks}&hosp=${hosp}`, pks))
    this.$root.$on('print:directions_list', (pks) => printForm('/statistic/xls?pk={pks}&type=directions_list', pks))

    this.$root.$on('generate-directions', ({
                                             type, card_pk, fin_source_pk, diagnos, base,
                                             researches, operator, ofname, history_num, comments,
                                             counts, for_rmis, rmis_data, callback, vich_code, count,
                                             discount, need_contract,
                                             parent_iss=null, kk='', localizations={}, service_locations={},
                                             direction_purpose='NONE', directions_count=1, external_organization='NONE',
                                             parent_slave_hosp=null,
                                           }) => {
      if (card_pk === -1) {
        errmessage('Не выбрана карта')
        return
      }
      if (fin_source_pk === -1) {
        errmessage('Не выбран источник финансирования')
        return
      }
      if (Object.keys(researches).length === 0) {
        errmessage('Не выбраны исследования')
        return
      }
      if (operator && ofname < 0) {
        errmessage('Не выбрано, от чьего имени выписываются направления')
        return
      }
      this.$store.dispatch(action_types.INC_LOADING)
      directions_point.sendDirections({
        card_pk, diagnos, fin_source: fin_source_pk, history_num,
        ofname_pk: ofname, researches, comments, for_rmis,
        rmis_data, vich_code, count, discount, parent_iss, counts, localizations, service_locations,
        direction_purpose, directions_count, external_organization, parent_slave_hosp,
      }).then(data => {
        this.$store.dispatch(action_types.DEC_LOADING)

        if (data.ok) {
          if (type === 'direction') {
            if (need_contract) {
              this.$root.$emit('print:directions:contract', data.directions)
            } else {
              this.$root.$emit('print:directions', data.directions)
            }
          }
          if (type === 'barcode') {
            this.$root.$emit('print:barcodes', data.directions)
          }
          if (type === 'just-save' || type === 'barcode') {
            okmessage('Направления созданы', 'Номера: ' + data.directions.join(', '))
          }
          this.$root.$emit('researches-picker:clear_all'+kk)
          this.$root.$emit('researches-picker:directions_created'+kk)
        } else {
          errmessage('Направления не созданы', data.message)
        }
        if (callback)
          callback()
      })
    })
  }
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {

var oop = require("pilot/oop");
var lang = require("pilot/lang");
var DocCommentHighlightRules = require("ace/mode/doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;

var JavaHighlightRules = function() {

    var docComment = new DocCommentHighlightRules();

    // taken from http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
    var keywords = lang.arrayToMap(
	("abstract|continue|for|new|switch|" +
	"assert|default|goto|package|synchronized" +
	"boolean|do|if|private|this" +
	"break|double|implements|protected|throw" +
	"byte|else|import|public|throws" +
	"case|enum|instanceof|return|transient" +
	"catch|extends|int|short|try" +
	"char|final|interface|static|void" +
	"class|finally|long|strictfp|volatile|" +
	"const|float|native|super|while").split("|")
    );

    var buildinConstants = lang.arrayToMap(
        ("null|Infinity|NaN|undefined").split("|")
    );

    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [
	        {
	            token : "comment",
	            regex : "\\/\\/.*$"
	        },
	        docComment.getStartRule("doc-start"),
            {
                token : "comment", // multi line comment
                regex : "\\/\\*",
                next : "comment"
            }, {
	            token : "comment", // multi line comment
	            regex : "\\/\\*\\*",
	            next : "comment"
	        }, {
	            token : "string.regexp",
	            regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
	        }, {
	            token : "string", // single line
	            regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
	        }, {
	            token : "string", // single line
	            regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
	        }, {
	            token : "constant.numeric", // hex
	            regex : "0[xX][0-9a-fA-F]+\\b"
	        }, {
	            token : "constant.numeric", // float
	            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
	        }, {
	            token : "constant.language.boolean",
	            regex : "(?:true|false)\\b"
	        }, {
	            token : function(value) {
	                if (value == "this")
	                    return "variable.language";
	                else if (keywords.hasOwnProperty(value))
	                    return "keyword";
	                else if (buildinConstants.hasOwnProperty(value))
	                    return "constant.language";
	                else
	                    return "identifier";
	            },
	            // TODO: Unicode escape sequences
	            // TODO: Unicode identifiers
	            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
	        }, {
	            token : "keyword.operator",
	            regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
	        }, {
	            token : "lparen",
	            regex : "[[({]"
	        }, {
	            token : "rparen",
	            regex : "[\\])}]"
	        }, {
	            token : "text",
	            regex : "\\s+"
	        }
        ],
        "comment" : [
	        {
	            token : "comment", // closing comment
	            regex : ".*?\\*\\/",
	            next : "start"
	        }, {
	            token : "comment", // comment spanning whole line
	            regex : ".+"
	        }
        ],
        "qqstring" : [
            {
	            token : "string",
	            regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
	            next : "start"
	        }, {
	            token : "string",
	            regex : '.+'
	        }
        ],
        "qstring" : [
	        {
	            token : "string",
	            regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
	            next : "start"
	        }, {
	            token : "string",
	            regex : '.+'
	        }
        ]
    };

    this.addRules(docComment.getRules(), "doc-");
    this.$rules["doc-start"][0].next = "start";
};

oop.inherits(JavaHighlightRules, TextHighlightRules);

exports.JavaHighlightRules = JavaHighlightRules;
});
<commit_msg>fix missing java keywords separators<commit_after>define(function(require, exports, module) {

var oop = require("pilot/oop");
var lang = require("pilot/lang");
var DocCommentHighlightRules = require("ace/mode/doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;

var JavaHighlightRules = function() {

    var docComment = new DocCommentHighlightRules();

    // taken from http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
    var keywords = lang.arrayToMap(
	("abstract|continue|for|new|switch|" +
	"assert|default|goto|package|synchronized|" +
	"boolean|do|if|private|this|" +
	"break|double|implements|protected|throw|" +
	"byte|else|import|public|throws|" +
	"case|enum|instanceof|return|transient|" +
	"catch|extends|int|short|try|" +
	"char|final|interface|static|void|" +
	"class|finally|long|strictfp|volatile|" +
	"const|float|native|super|while").split("|")
    );

    var buildinConstants = lang.arrayToMap(
        ("null|Infinity|NaN|undefined").split("|")
    );

    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [
	        {
	            token : "comment",
	            regex : "\\/\\/.*$"
	        },
	        docComment.getStartRule("doc-start"),
            {
                token : "comment", // multi line comment
                regex : "\\/\\*",
                next : "comment"
            }, {
	            token : "comment", // multi line comment
	            regex : "\\/\\*\\*",
	            next : "comment"
	        }, {
	            token : "string.regexp",
	            regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
	        }, {
	            token : "string", // single line
	            regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
	        }, {
	            token : "string", // single line
	            regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
	        }, {
	            token : "constant.numeric", // hex
	            regex : "0[xX][0-9a-fA-F]+\\b"
	        }, {
	            token : "constant.numeric", // float
	            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
	        }, {
	            token : "constant.language.boolean",
	            regex : "(?:true|false)\\b"
	        }, {
	            token : function(value) {
	                if (value == "this")
	                    return "variable.language";
	                else if (keywords.hasOwnProperty(value))
	                    return "keyword";
	                else if (buildinConstants.hasOwnProperty(value))
	                    return "constant.language";
	                else
	                    return "identifier";
	            },
	            // TODO: Unicode escape sequences
	            // TODO: Unicode identifiers
	            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
	        }, {
	            token : "keyword.operator",
	            regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
	        }, {
	            token : "lparen",
	            regex : "[[({]"
	        }, {
	            token : "rparen",
	            regex : "[\\])}]"
	        }, {
	            token : "text",
	            regex : "\\s+"
	        }
        ],
        "comment" : [
	        {
	            token : "comment", // closing comment
	            regex : ".*?\\*\\/",
	            next : "start"
	        }, {
	            token : "comment", // comment spanning whole line
	            regex : ".+"
	        }
        ],
        "qqstring" : [
            {
	            token : "string",
	            regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
	            next : "start"
	        }, {
	            token : "string",
	            regex : '.+'
	        }
        ],
        "qstring" : [
	        {
	            token : "string",
	            regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
	            next : "start"
	        }, {
	            token : "string",
	            regex : '.+'
	        }
        ]
    };

    this.addRules(docComment.getRules(), "doc-");
    this.$rules["doc-start"][0].next = "start";
};

oop.inherits(JavaHighlightRules, TextHighlightRules);

exports.JavaHighlightRules = JavaHighlightRules;
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var debug = require('debug')('4front:apphost:app-loader');
var helper = require('../helper');

require('simple-errors');

exports = module.exports = function(options) {
  options = _.defaults(options || {}, {});

  helper.ensureRequiredOptions(options, 'findAppFn', 'virtualHostDomain');

  return function(req, res, next) {
    debug("virtualAppLoader middleware");

    if (_.isEmpty(req.hostname))
      return next(Error.http(404, "Missing Host header"));

    var appName;
    var virtualHost = req.hostname.toLowerCase();
    debug('virtualHost=%s', virtualHost);

    determineVirtualEnv(req);

    debug('virtualEnv=%s', req.ext.virtualEnv);

    // If the virtualHost does not contain the virtualHostDomain, then it must be a custom domain.
    if (req.ext.virtualHost.indexOf(options.virtualHostDomain) === -1) {
      debug("find app by custom domain %s", virtualHost);
      options.findAppFn({domain: req.ext.virtualHost}, findAppCallback);
    }
    else {
      // The app name is assumed to be the first part of the vhost, i.e. appname.virtualhost.com.
      var appName = req.ext.virtualHost.split('.')[0];
      debug("find app by name %s", appName);
      options.findAppFn({name: appName}, findAppCallback);
    }

    function findAppCallback(err, virtualApp) {
      if (err)
        return next(err);

      if (!virtualApp) {
        debug("virtual app %s not found", appName);
        return next(Error.http(404, 'Virtual application ' + appName + ' not found'));
      }

      // If this app requires SSL and this request is not secure, then
      if (virtualApp.requireSsl === true) {
        debug("app must be requested via SSL");
        if (req.secure !== true) {
          return res.redirect('https://' + req.hostname + req.url);
        }
      }

      // Store the app in the req object for subsequent middleware
      req.ext.virtualApp = virtualApp;

      // If this app belongs to an org, store the orgId on the extended request.
      if (virtualApp.orgId) {
        debug('orgId=%s', virtualApp.orgId);
        req.ext.orgId = virtualApp.orgId;
      }

      // Set a custom virtual-app-id header
      res.set('virtual-app-id', virtualApp.appId);

      debug("current virtual application is " + virtualApp.appId);
      next();
    }
  };

  // Look for an environment indicator in the hostname which looks like appname--dev.virtualhost.com.
  // A double hyphen is valid and highly unlikely to conflict with an actual app name.
  // If none found, then assume 'prod'
  function determineVirtualEnv(req) {
    var match = req.hostname.match(/--([a-z]+)\./i);
    if (match && match.length === 2) {
      req.ext.virtualEnv = match[1];
      req.ext.virtualHost = req.hostname.toLowerCase().replace('--' + req.ext.virtualEnv, '');
      return;
    }

    // If no virtualEnv found in the hostname, default to 'prod'
    req.ext.virtualEnv = 'prod';
    req.ext.virtualHost = req.hostname.toLowerCase();
  }
};
<commit_msg>Use app.settings.virtualAppRegistry in app-loader<commit_after>var _ = require('lodash');
var debug = require('debug')('4front:apphost:app-loader');
var helper = require('../helper');

require('simple-errors');

exports = module.exports = function(options) {
  options = _.defaults(options || {}, {});

  return function(req, res, next) {
    debug("virtualAppLoader middleware");

    if (_.isEmpty(req.hostname))
      return next(Error.http(404, "Missing Host header"));

    var appName;
    var virtualHost = req.hostname.toLowerCase();
    debug('virtualHost=%s', virtualHost);

    determineVirtualEnv(req);

    debug('virtualEnv=%s', req.ext.virtualEnv);

    // If the virtualHost does not contain the virtualHostDomain, then it must be a custom domain.
    if (req.ext.virtualHost.indexOf(req.app.settings.virtualHost) === -1) {
      debug("find app by custom domain %s", virtualHost);
      req.app.settings.virtualAppRegistry.findByDomain(req.ext.virtualHost, findAppCallback);
    }
    else {
      // The app name is assumed to be the first part of the vhost, i.e. appname.virtualhost.com.
      var appName = req.ext.virtualHost.split('.')[0];
      debug("find app by name %s", appName);
      req.app.settings.virtualAppRegistry.findByName(appName, findAppCallback);
    }

    function findAppCallback(err, virtualApp) {
      if (err)
        return next(err);

      if (!virtualApp) {
        debug("virtual app %s not found", appName);
        return next(Error.http(404, 'Virtual application ' + appName + ' not found'));
      }

      // If this app requires SSL and this request is not secure, then
      if (virtualApp.requireSsl === true) {
        debug("app must be requested via SSL");
        if (req.secure !== true) {
          return res.redirect('https://' + req.hostname + req.url);
        }
      }

      // Store the app in the req object for subsequent middleware
      req.ext.virtualApp = virtualApp;

      // If this app belongs to an org, store the orgId on the extended request.
      if (virtualApp.orgId) {
        debug('orgId=%s', virtualApp.orgId);
        req.ext.orgId = virtualApp.orgId;
      }

      // Set a custom virtual-app-id header
      res.set('virtual-app-id', virtualApp.appId);

      debug("current virtual application is " + virtualApp.appId);
      next();
    }
  };

  // Look for an environment indicator in the hostname which looks like appname--dev.virtualhost.com.
  // A double hyphen is valid and highly unlikely to conflict with an actual app name.
  // If none found, then assume 'prod'
  function determineVirtualEnv(req) {
    var match = req.hostname.match(/--([a-z]+)\./i);
    if (match && match.length === 2) {
      req.ext.virtualEnv = match[1];
      req.ext.virtualHost = req.hostname.toLowerCase().replace('--' + req.ext.virtualEnv, '');
      return;
    }

    // If no virtualEnv found in the hostname, default to 'prod'
    req.ext.virtualEnv = 'prod';
    req.ext.virtualHost = req.hostname.toLowerCase();
  }
};
<|endoftext|>


<commit_before>/**
 * @file Render html
 * @author treelite(c.xinle@gmail.com)
 */

var extend = require('saber-lang').extend;
var config = require('../config');
var INDEX_FILE = 'index.html';

/**
 * 模版编译
 *
 * @inner
 * @param {Object=} options 配置项
 * @param {string=} options.indexFile 首页模版
 * @return {Function}
 */
function compile(options) {
    options = options || {};
    var fs = require('fs');
    var content = fs.readFileSync(options.indexFile || INDEX_FILE, 'utf8');
    // 插入同步数据的注入点
    content = content.replace('', '\n');

    var etpl = require('etpl');
    etpl = new etpl.Engine({defaultFilter: 'raw'});
    return etpl.compile(content);
}

/**
 * 生成页面渲染中间件
 *
 * @public
 * @param {Object} options 配置参数
 * @return {Function}
 */
module.exports = function (options) {
    var render = compile();
    return function (req, res, next) {
        if (res.hasOwnProperty('html')) {
            var data = extend({}, res.templateData, {content: res.html});
            // 传输需要同步的数据
            data.rebas = JSON.stringify(
                // 合并全局的待同步数据
                extend(
                    {},
                    config.syncData,
                    res.syncData,
                    {
                        model: res.data,
                        templateData: options.templateData || {}
                    }
                )
            );
            // 附加全局的模版数据
            data = extend({}, options.templateData, data);
            // 渲染HTML页面
            return res.send(render(data));
        }
        next();
    };
};
<commit_msg>Fix missing params<commit_after>/**
 * @file Render html
 * @author treelite(c.xinle@gmail.com)
 */

var extend = require('saber-lang').extend;
var config = require('../config');
var INDEX_FILE = 'index.html';

/**
 * 模版编译
 *
 * @inner
 * @param {Object=} options 配置项
 * @param {string=} options.indexFile 首页模版
 * @return {Function}
 */
function compile(options) {
    options = options || {};
    var fs = require('fs');
    var content = fs.readFileSync(options.indexFile || INDEX_FILE, 'utf8');
    // 插入同步数据的注入点
    content = content.replace('', '\n');

    var etpl = require('etpl');
    etpl = new etpl.Engine({defaultFilter: 'raw'});
    return etpl.compile(content);
}

/**
 * 生成页面渲染中间件
 *
 * @public
 * @param {Object} options 配置参数
 * @return {Function}
 */
module.exports = function (options) {
    var render = compile(options);
    return function (req, res, next) {
        if (res.hasOwnProperty('html')) {
            var data = extend({}, res.templateData, {content: res.html});
            // 传输需要同步的数据
            data.rebas = JSON.stringify(
                // 合并全局的待同步数据
                extend(
                    {},
                    config.syncData,
                    res.syncData,
                    {
                        model: res.data,
                        templateData: options.templateData || {}
                    }
                )
            );
            // 附加全局的模版数据
            data = extend({}, options.templateData, data);
            // 渲染HTML页面
            return res.send(render(data));
        }
        next();
    };
};
<|endoftext|>


<commit_before>define(function () {

    'use strict';

    return function (sneech) {
        sneech.star = true;
        return sneech;
    };

});<commit_msg>Update starOnMachine.js<commit_after>define(function () {

    'use strict';

    return function (sneetch) {
        sneetch.star = true;
        return sneetch;
    };

});
<|endoftext|>