<commit_before>'use strict';

var $interpolateMinErr = minErr('$interpolate');

/**
 * @ngdoc provider
 * @name $interpolateProvider
 * @function
 *
 * @description
 *
 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
 *
 * @example
<example module="customInterpolationApp">
<file name="index.html">

    //demo.label//

</file>
<file name="protractor.js" type="protractor">
  it('should interpolate binding with custom symbols', function() {
    expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  });
</file>
</example>
 */
function $InterpolateProvider() {
  var startSymbol = '{{';
  var endSymbol = '}}';

  /**
   * @ngdoc method
   * @name $interpolateProvider#startSymbol
   * @description
   * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
   *
   * @param {string=} value new value to set the starting symbol to.
   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
   */
  this.startSymbol = function(value){
    if (value) {
      startSymbol = value;
      return this;
    } else {
      return startSymbol;
    }
  };

  /**
   * @ngdoc method
   * @name $interpolateProvider#endSymbol
   * @description
   * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
   *
   * @param {string=} value new value to set the ending symbol to.
   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
   */
  this.endSymbol = function(value){
    if (value) {
      endSymbol = value;
      return this;
    } else {
      return endSymbol;
    }
  };

  this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
    var startSymbolLength = startSymbol.length,
        endSymbolLength = endSymbol.length;

    /**
     * @ngdoc service
     * @name $interpolate
     * @function
     *
     * @requires $parse
     * @requires $sce
     *
     * @description
     *
     * Compiles a string with markup into an interpolation function. This service is used by the
     * HTML {@link ng.$compile $compile} service for data binding. See
     * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
     * interpolation markup.
     *
     *
       ```js
         var $interpolate = ...; // injected
         var exp = $interpolate('Hello {{name | uppercase}}!');
         expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
       ```
     *
     *
     * @param {string} text The text with markup to interpolate.
     * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
     *    embedded expression in order to return an interpolation function. Strings with no
     *    embedded expression will return null for the interpolation function.
     * @param {string=} trustedContext when provided, the returned function passes the interpolated
     *    result through {@link ng.$sce#methods_getTrusted $sce.getTrusted(interpolatedResult,
     *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that
     *    provides Strict Contextual Escaping for details.
     * @returns {function(context)} an interpolation function which is used to compute the
     *    interpolated string. The function has these parameters:
     *
     *    * `context`: an object against which any expressions embedded in the strings are evaluated
     *      against.
     *
     */
    function $interpolate(text, mustHaveExpression, trustedContext) {
      var startIndex,
          endIndex,
          index = 0,
          parts = [],
          length = text.length,
          hasInterpolation = false,
          fn,
          exp,
          concat = [];

      while(index < length) {
        if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
             ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
          (index != startIndex) && parts.push(text.substring(index, startIndex));
          parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
          fn.exp = exp;
          index = endIndex + endSymbolLength;
          hasInterpolation = true;
        } else {
          // we did not find anything, so we have to add the remainder to the parts array
          (index != length) && parts.push(text.substring(index));
          index = length;
        }
      }

      if (!(length = parts.length)) {
        // we added, nothing, must have been an empty string.
        parts.push('');
        length = 1;
      }

      // Concatenating expressions makes it hard to reason about whether some combination of
      // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a
      // single expression be used for iframe[src], object[src], etc., we ensure that the value
      // that's used is assigned or constructed by some JS code somewhere that is more testable or
      // make it obvious that you bound the value to some user controlled value.  This helps reduce
      // the load when auditing for XSS issues.
      if (trustedContext && parts.length > 1) {
          throw $interpolateMinErr('noconcat',
              "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
              "interpolations that concatenate multiple expressions when a trusted value is " +
              "required.  See http://docs.angularjs.org/api/ng.$sce", text);
      }

      if (!mustHaveExpression  || hasInterpolation) {
        concat.length = length;
        fn = function(context) {
          try {
            for(var i = 0, ii = length, part; i<ii; i++) {
              if (typeof (part = parts[i]) == 'function') {
                part = part(context);
                if (trustedContext) {
                  part = $sce.getTrusted(trustedContext, part);
                } else {
                  part = $sce.valueOf(part);
                }
                if (part === null || isUndefined(part)) {
                  part = '';
                } else if (typeof part != 'string') {
                  part = toJson(part);
                }
              }
              concat[i] = part;
            }
            return concat.join('');
          }
          catch(err) {
            var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
                err.toString());
            $exceptionHandler(newErr);
          }
        };
        fn.exp = text;
        fn.parts = parts;
        return fn;
      }
    }

    /**
     * @ngdoc method
     * @name $interpolate#startSymbol
     * @description
     * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
     *
     * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
     * the symbol.
     *
     * @returns {string} start symbol.
     */
    $interpolate.startSymbol = function() {
      return startSymbol;
    };

    /**
     * @ngdoc method
     * @name $interpolate#endSymbol
     * @description
     * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
     *
     * Use {@link ng.$interpolateProvider#methods_endSymbol $interpolateProvider#endSymbol} to change
     * the symbol.
     *
     * @returns {string} start symbol.
     */
    $interpolate.endSymbol = function() {
      return endSymbol;
    };

    return $interpolate;
  }];
}

<commit_msg>docs($interpolate): correct small typo<commit_after>'use strict';

var $interpolateMinErr = minErr('$interpolate');

/**
 * @ngdoc provider
 * @name $interpolateProvider
 * @function
 *
 * @description
 *
 * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
 *
 * @example
<example module="customInterpolationApp">
<file name="index.html">

    //demo.label//

</file>
<file name="protractor.js" type="protractor">
  it('should interpolate binding with custom symbols', function() {
    expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  });
</file>
</example>
 */
function $InterpolateProvider() {
  var startSymbol = '{{';
  var endSymbol = '}}';

  /**
   * @ngdoc method
   * @name $interpolateProvider#startSymbol
   * @description
   * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
   *
   * @param {string=} value new value to set the starting symbol to.
   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
   */
  this.startSymbol = function(value){
    if (value) {
      startSymbol = value;
      return this;
    } else {
      return startSymbol;
    }
  };

  /**
   * @ngdoc method
   * @name $interpolateProvider#endSymbol
   * @description
   * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
   *
   * @param {string=} value new value to set the ending symbol to.
   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
   */
  this.endSymbol = function(value){
    if (value) {
      endSymbol = value;
      return this;
    } else {
      return endSymbol;
    }
  };

  this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
    var startSymbolLength = startSymbol.length,
        endSymbolLength = endSymbol.length;

    /**
     * @ngdoc service
     * @name $interpolate
     * @function
     *
     * @requires $parse
     * @requires $sce
     *
     * @description
     *
     * Compiles a string with markup into an interpolation function. This service is used by the
     * HTML {@link ng.$compile $compile} service for data binding. See
     * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
     * interpolation markup.
     *
     *
       ```js
         var $interpolate = ...; // injected
         var exp = $interpolate('Hello {{name | uppercase}}!');
         expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
       ```
     *
     *
     * @param {string} text The text with markup to interpolate.
     * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
     *    embedded expression in order to return an interpolation function. Strings with no
     *    embedded expression will return null for the interpolation function.
     * @param {string=} trustedContext when provided, the returned function passes the interpolated
     *    result through {@link ng.$sce#methods_getTrusted $sce.getTrusted(interpolatedResult,
     *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that
     *    provides Strict Contextual Escaping for details.
     * @returns {function(context)} an interpolation function which is used to compute the
     *    interpolated string. The function has these parameters:
     *
     *    * `context`: an object against which any expressions embedded in the strings are evaluated
     *      against.
     *
     */
    function $interpolate(text, mustHaveExpression, trustedContext) {
      var startIndex,
          endIndex,
          index = 0,
          parts = [],
          length = text.length,
          hasInterpolation = false,
          fn,
          exp,
          concat = [];

      while(index < length) {
        if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
             ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
          (index != startIndex) && parts.push(text.substring(index, startIndex));
          parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
          fn.exp = exp;
          index = endIndex + endSymbolLength;
          hasInterpolation = true;
        } else {
          // we did not find anything, so we have to add the remainder to the parts array
          (index != length) && parts.push(text.substring(index));
          index = length;
        }
      }

      if (!(length = parts.length)) {
        // we added, nothing, must have been an empty string.
        parts.push('');
        length = 1;
      }

      // Concatenating expressions makes it hard to reason about whether some combination of
      // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a
      // single expression be used for iframe[src], object[src], etc., we ensure that the value
      // that's used is assigned or constructed by some JS code somewhere that is more testable or
      // make it obvious that you bound the value to some user controlled value.  This helps reduce
      // the load when auditing for XSS issues.
      if (trustedContext && parts.length > 1) {
          throw $interpolateMinErr('noconcat',
              "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
              "interpolations that concatenate multiple expressions when a trusted value is " +
              "required.  See http://docs.angularjs.org/api/ng.$sce", text);
      }

      if (!mustHaveExpression  || hasInterpolation) {
        concat.length = length;
        fn = function(context) {
          try {
            for(var i = 0, ii = length, part; i<ii; i++) {
              if (typeof (part = parts[i]) == 'function') {
                part = part(context);
                if (trustedContext) {
                  part = $sce.getTrusted(trustedContext, part);
                } else {
                  part = $sce.valueOf(part);
                }
                if (part === null || isUndefined(part)) {
                  part = '';
                } else if (typeof part != 'string') {
                  part = toJson(part);
                }
              }
              concat[i] = part;
            }
            return concat.join('');
          }
          catch(err) {
            var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
                err.toString());
            $exceptionHandler(newErr);
          }
        };
        fn.exp = text;
        fn.parts = parts;
        return fn;
      }
    }

    /**
     * @ngdoc method
     * @name $interpolate#startSymbol
     * @description
     * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
     *
     * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
     * the symbol.
     *
     * @returns {string} start symbol.
     */
    $interpolate.startSymbol = function() {
      return startSymbol;
    };

    /**
     * @ngdoc method
     * @name $interpolate#endSymbol
     * @description
     * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
     *
     * Use {@link ng.$interpolateProvider#methods_endSymbol $interpolateProvider#endSymbol} to change
     * the symbol.
     *
     * @returns {string} end symbol.
     */
    $interpolate.endSymbol = function() {
      return endSymbol;
    };

    return $interpolate;
  }];
}

<|endoftext|>


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

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

define({
    // Relative to the samples folder
    "WEB_PLATFORM_DOCS_LICENSE" : "http://creativecommons.org/licenses/by/3.0/deed.fa"
});<commit_msg>Updat for add Getting Start for Farsi | Persian | فارسی Language<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

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

define({
    // Relative to the samples folder
    "GETTING_STARTED"           : "fa-ir/Getting Started",
    "ADOBE_THIRD_PARTY"         : "http://www.adobe.com/go/thirdparty/",
    "WEB_PLATFORM_DOCS_LICENSE" : "http://creativecommons.org/licenses/by/3.0/deed.fa"
});<|endoftext|>


<commit_before>/* global mathjs */

const allowedOps = [
    '+', '-', '*', '/',
    '==', '!=', '>', '<', '>=', '<=',
    'and', 'or', 'xor',
    '^',
    'sqrt', 'log10',
    'ceil', 'floor', 'round',
    'abs',
    'sin', 'cos', 'tan',
    'asin', 'acos', 'atan',
    'sinh', 'cosh', 'tanh',
    'atan2'
];

export default class ToolCreateModalController {
    constructor(
        $scope, $state, uuid4, toolService
    ) {
        'ngInject';
        this.$scope = $scope;
        this.$state = $state;
        this.uuid4 = uuid4;
        this.toolService = toolService;
    }

    $onInit() {
        this.toolBuffer = {
            title: '',
            description: '',
            visibility: 'PRIVATE'
        };
        this.isProcessing = false;
        this.definitionExpression = '';
    }

    toolIsPublic() {
        return this.toolBuffer.visibility === 'PUBLIC';
    }

    createTool() {
        this.currentError = '';
        this.isProcessing = true;
        this.commonSymbols = [];
        let expressionTree = null;
        try {
            expressionTree = mathjs.parse(this.definitionExpression);
            this.toolBuffer.definition = this.transformNode(expressionTree);
            this.toolService.createTool(this.toolBuffer).then(tool => {
                this.dismiss();
                this.$state.go('lab.run', { toolid: tool.id });
            });
        } catch (e) {
            this.currentError = 'The tool definition is not valid';
            this.isProcessing = false;
        }
    }

    onVisibilityChange(value) {
        const vis = value ? 'PUBLIC' : 'PRIVATE';
        this.toolBuffer.visibility = vis;
    }

    closeWithData(data) {
        this.close({ $value: data });
    }

    getSymbolId(symbol) {
        const s = this.commonSymbols[symbol];
        if (s) {
            return s.id;
        }
        let id = this.uuid4.generate();
        this.commonSymbols[symbol] = { id };
        return id;
    }

    transformNode(node, value) {
        let builtNode = {
            metadata: {}
        };

        if (node.op && allowedOps.indexOf(node.op) >= 0) {
            // Op node
            builtNode.id = this.uuid4.generate();
            builtNode.apply = node.op;
            builtNode.metadata.label = node.fn;
            builtNode.args = node.args.map(n => this.transformNode(n));
        } else if (node.fn && node.fn.name && allowedOps.indexOf(node.fn.name) >= 0) {
            // Function node; handle nearly the same as op node, for now
            builtNode.id = this.uuid4.generate();
            builtNode.apply = node.fn.name;
            builtNode.metadata.label = node.fn.name;
            builtNode.args = node.args.map(n => this.transformNode(n));
        } else if (node.name) {
            // Symbol node
            if (node.object && node.value) {
                // Symbol with a default (constant)
                return this.transformNode(node.object, node.value.value);
            }
            // Symbol without a default yet (constant or not)
            let isConst = node.name.startsWith('_');
            if (isConst) {
                // Constant symbols without a default yet
                builtNode.type = 'const';
                builtNode.metadata.label = node.name.substring(1);
                if (value) {
                    builtNode.constant = parseFloat(value);
                }
            } else {
                // Raster symbolds
                builtNode.type = 'src';
                builtNode.metadata.label = node.name;
            }
            builtNode.id = this.getSymbolId(builtNode.metadata.label);
        } else if (node.value) {
            builtNode.id = this.uuid4.generate();
            builtNode.type = 'const';
            builtNode.constant = node.value;
            builtNode.metadata.label = node.value;
        } else if (node.content) {
            return this.transformNode(node.content);
        }

        return builtNode;
    }

    isValid() {
        this.currentParsingError = '';
        const parensBalanced = this.validateParenDepth();
        if (!parensBalanced) {
            this.currentParsingError = 'The parentheses in this expression are not balanced';
        }
        return this.toolBuffer.title && this.definitionExpression && parensBalanced;
    }

    validateParenDepth() {
        const expressionArray = this.definitionExpression.split('');
        const result = expressionArray.reduce((acc, c) => {
            if (acc.continue) {
                let d = acc.depth;
                if (c === '(') {
                    d += 1;
                } else if (c === ')') {
                    d -= 1;
                }
                return { depth: d, continue: d >= 0};
            }
            return acc;
        }, { depth: 0, continue: true });
        return result.continue && result.depth === 0;
    }

}
<commit_msg>Add parsing of `classify` function in mamlscript (#2474)<commit_after>/* global mathjs */

const allowedOps = [
    '+', '-', '*', '/',
    '==', '!=', '>', '<', '>=', '<=',
    'and', 'or', 'xor',
    '^',
    'sqrt', 'log10',
    'ceil', 'floor', 'round',
    'abs',
    'sin', 'cos', 'tan',
    'asin', 'acos', 'atan',
    'sinh', 'cosh', 'tanh',
    'atan2'
];

export default class ToolCreateModalController {
    constructor(
        $scope, $state, uuid4, toolService
    ) {
        'ngInject';
        this.$scope = $scope;
        this.$state = $state;
        this.uuid4 = uuid4;
        this.toolService = toolService;
    }

    $onInit() {
        this.toolBuffer = {
            title: '',
            description: '',
            visibility: 'PRIVATE'
        };
        this.isProcessing = false;
        this.definitionExpression = '';
    }

    toolIsPublic() {
        return this.toolBuffer.visibility === 'PUBLIC';
    }

    createTool() {
        this.currentError = '';
        this.isProcessing = true;
        this.commonSymbols = [];
        let expressionTree = null;
        try {
            expressionTree = mathjs.parse(this.definitionExpression);
            this.toolBuffer.definition = this.expressionTreeToMAML(expressionTree);
            this.toolService.createTool(this.toolBuffer).then(tool => {
                this.dismiss();
                this.$state.go('lab.run', { toolid: tool.id });
            });
        } catch (e) {
            this.currentError = 'The tool definition is not valid';
            this.isProcessing = false;
        }
    }

    onVisibilityChange(value) {
        const vis = value ? 'PUBLIC' : 'PRIVATE';
        this.toolBuffer.visibility = vis;
    }

    closeWithData(data) {
        this.close({ $value: data });
    }

    getSymbolId(symbol) {
        const s = this.commonSymbols[symbol];
        if (s) {
            return s.id;
        }
        let id = this.uuid4.generate();
        this.commonSymbols[symbol] = { id };
        return id;
    }

    expressionTreeToMAML(tree, value, allowCollapse = true) {
        let mamlNode = {
            id: this.uuid4.generate(),
            metadata: {}
        };

        switch (tree.type) {
        case 'AssignmentNode':
            return this.expressionTreeToMAML(tree.object, tree.value.value);
        case 'ConstantNode':
            Object.assign(mamlNode, {
                type: 'const',
                constant: tree.value,
                metadata: {
                    label: tree.value
                }
            });
            break;
        case 'OperatorNode':
            if (allowedOps.indexOf(tree.op) >= 0) {
                mamlNode.apply = tree.op;
                mamlNode.metadata.label = tree.fn;
                mamlNode.metadata.collapsable = allowCollapse;
                break;
            }
            return false;
        case 'FunctionNode':
            mamlNode.apply = tree.fn.name;
            mamlNode.metadata.label = tree.fn.name;
            if (mamlNode.apply === 'classify') {
                const classifications = tree.args[1];
                tree.args = [ tree.args[0] ];
                mamlNode.classMap = {
                    classifications: this.objectNodeToClassifications(classifications)
                };
            }
            break;
        case 'ParenthesisNode':
            return this.expressionTreeToMAML(tree.content, null, false);
        case 'SymbolNode':
            if (tree.name.startsWith('_')) {
                mamlNode.type = 'const';
                mamlNode.metadata.label = tree.name.substring(1);
                if (value) {
                    mamlNode.constant = parseFloat(value);
                }
            } else {
                mamlNode.type = 'src';
                mamlNode.metadata.label = tree.name;
            }
            mamlNode.id = this.getSymbolId(mamlNode.metadata.label);
            break;
        default:
            return false;
        }

        if (tree.args && tree.args.length) {
            mamlNode.args = tree.args.map(a => this.expressionTreeToMAML(a));
        }

        if (tree.type === 'OperatorNode' && tree.args) {
            mamlNode.args.forEach((c, i) => {
                if (c.apply && c.apply === mamlNode.apply && c.metadata.collapsable) {
                    mamlNode.args = [
                        ...mamlNode.args.slice(0, i),
                        ...c.args,
                        ...mamlNode.args.slice(i + 1, mamlNode.args.length)
                    ];
                }
            });
        }
        return mamlNode;
    }

    objectNodeToClassifications(node) {
        return Object.keys(node.properties).reduce((acc, p) => {
            acc[`${parseFloat(p)}`] = parseInt(node.properties[p].value, 10);
            return acc;
        }, {});
    }

    isValid() {
        this.currentParsingError = '';
        const parensBalanced = this.validateParenDepth();
        const bracesBalanced = this.validateBraceDepth();
        if (!parensBalanced) {
            this.currentParsingError = 'The parentheses in this expression are not balanced';
        } else if (!bracesBalanced) {
            this.currentParsingError = 'The braces in this expression are not balanced';
        }
        return this.toolBuffer.title && this.definitionExpression && parensBalanced;
    }

    validateParenDepth() {
        const expressionArray = this.definitionExpression.split('');
        const result = expressionArray.reduce((acc, c) => {
            if (acc.continue) {
                let d = acc.depth;
                if (c === '(') {
                    d += 1;
                } else if (c === ')') {
                    d -= 1;
                }
                return { depth: d, continue: d >= 0};
            }
            return acc;
        }, { depth: 0, continue: true });
        return result.continue && result.depth === 0;
    }

    validateBraceDepth() {
        const expressionArray = this.definitionExpression.split('');
        const result = expressionArray.reduce((acc, c) => {
            if (acc.continue) {
                let d = acc.depth;
                if (c === '{') {
                    d += 1;
                } else if (c === '}') {
                    d -= 1;
                }
                return { depth: d, continue: d >= 0};
            }
            return acc;
        }, { depth: 0, continue: true });
        return result.continue && result.depth === 0;
    }

}
<|endoftext|>


<commit_before>import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import { getColorPalette } from 'utils/data';
import { format } from 'd3-format';

// get list data
const getData = state => state.data;
const getSettings = state => state.settings;
const getCurrentLocation = state => state.currentLabel;
const getIndicator = state => state.indicator || null;
const getWhitelist = state => state.countryWhitelist;
const getColors = state => state.colors;
const getSentences = state => state.config && state.config.sentences;

// get lists selected
export const parseData = createSelector(
  [getData, getSettings, getWhitelist, getColors],
  (data, settings, whitelist, colors) => {
    if (isEmpty(data)) return null;
    const { totalArea, totalExtent, extent } = data;
    const colorRange = getColorPalette(colors.ramp, 2);
    const parsedData = [
      {
        label: 'Intact Forest',
        value: extent,
        color: colorRange[0],
        percentage: extent / totalArea * 100
      },
      {
        label: 'Other Tree Cover',
        value: totalExtent - extent,
        color: colorRange[1],
        percentage: (totalExtent - extent) / totalArea * 100
      },
      {
        label: 'Non-Forest',
        value: totalArea - totalExtent,
        color: colors.nonForest,
        percentage: (totalArea - totalExtent) / totalArea * 100
      }
    ];
    return parsedData;
  }
);

export const getSentence = createSelector(
  [parseData, getSettings, getCurrentLocation, getIndicator, getSentences],
  (parsedData, settings, currentLabel, indicator, sentences) => {
    if (!parsedData) return null;
    const {
      initial,
      withIndicator,
      globalInitial,
      globalWithIndicator
    } = sentences;
    const totalExtent = parsedData
      .filter(d => d.label !== 'Non-Forest')
      .map(d => d.value)
      .reduce((sum, d) => sum + d);
    const intactData = parsedData.find(d => d.label === 'Intact Forest').value;
    const intactPercentage = intactData && intactData / totalExtent * 100;
    let indicatorLabel = indicator && indicator.label;
    switch (indicator && indicator.value) {
      case 'ifl_2013__mining':
        indicatorLabel = 'Mining concessions';
        break;
      case 'ifl_2013__wdpa':
        indicatorLabel = 'Protected areas';
        break;
      default:
        indicatorLabel = 'Intact forest';
    }
    const params = {
      location: currentLabel || 'global',
      indicator: indicatorLabel,
      percentage:
        intactPercentage < 0.1
          ? '<0.1%'
          : `${format('.2r')(intactPercentage)}%`,
      intact: 'intact forest'
    };

    let sentence =
      indicator && indicator.value === 'ifl_2013' ? initial : withIndicator;

    if (!currentLabel) {
      sentence =
        indicator && indicator.value === 'ifl_2013'
          ? globalInitial
          : globalWithIndicator;
    }
    return {
      sentence,
      params
    };
  }
);
<commit_msg>Removes unused whitelist<commit_after>import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import { getColorPalette } from 'utils/data';
import { format } from 'd3-format';

// get list data
const getData = state => state.data;
const getSettings = state => state.settings;
const getCurrentLocation = state => state.currentLabel;
const getIndicator = state => state.indicator || null;
const getWhitelist = state => state.countryWhitelist;
const getColors = state => state.colors;
const getSentences = state => state.config && state.config.sentences;

// get lists selected
export const parseData = createSelector(
  [getData, getSettings, getColors],
  (data, settings, colors) => {
    if (isEmpty(data)) return null;
    const { totalArea, totalExtent, extent } = data;
    const colorRange = getColorPalette(colors.ramp, 2);
    const parsedData = [
      {
        label: 'Intact Forest',
        value: extent,
        color: colorRange[0],
        percentage: extent / totalArea * 100
      },
      {
        label: 'Other Tree Cover',
        value: totalExtent - extent,
        color: colorRange[1],
        percentage: (totalExtent - extent) / totalArea * 100
      },
      {
        label: 'Non-Forest',
        value: totalArea - totalExtent,
        color: colors.nonForest,
        percentage: (totalArea - totalExtent) / totalArea * 100
      }
    ];
    return parsedData;
  }
);

export const getSentence = createSelector(
  [parseData, getSettings, getCurrentLocation, getIndicator, getSentences],
  (parsedData, settings, currentLabel, indicator, sentences) => {
    if (!parsedData) return null;
    const {
      initial,
      withIndicator,
      globalInitial,
      globalWithIndicator
    } = sentences;
    const totalExtent = parsedData
      .filter(d => d.label !== 'Non-Forest')
      .map(d => d.value)
      .reduce((sum, d) => sum + d);
    const intactData = parsedData.find(d => d.label === 'Intact Forest').value;
    const intactPercentage = intactData && intactData / totalExtent * 100;
    let indicatorLabel = indicator && indicator.label;
    switch (indicator && indicator.value) {
      case 'ifl_2013__mining':
        indicatorLabel = 'Mining concessions';
        break;
      case 'ifl_2013__wdpa':
        indicatorLabel = 'Protected areas';
        break;
      default:
        indicatorLabel = 'Intact forest';
    }
    const params = {
      location: currentLabel || 'global',
      indicator: indicatorLabel,
      percentage:
        intactPercentage < 0.1
          ? '<0.1%'
          : `${format('.2r')(intactPercentage)}%`,
      intact: 'intact forest'
    };

    let sentence =
      indicator && indicator.value === 'ifl_2013' ? initial : withIndicator;

    if (!currentLabel) {
      sentence =
        indicator && indicator.value === 'ifl_2013'
          ? globalInitial
          : globalWithIndicator;
    }
    return {
      sentence,
      params
    };
  }
);
<|endoftext|>


<commit_before>module.exports = function(grunt) {

    'use strict';

    var path = require('path');

    grunt.initConfig({

        /**
         * Pull in the package.json file so we can read its metadata.
         */
        pkg: grunt.file.readJSON('package.json'),

        /**
         * Bower: https://github.com/yatskevich/grunt-bower-task
         *
         * Install Bower packages and migrate static assets.
         */
        bower: {
            install: {
                options: {
                    targetDir: './src/vendor/',
                    install: true,
                    verbose: true,
                    cleanBowerDir: true,
                    cleanTargetDir: true,
                    layout: function(type, component) {
                        if (type === 'img') {
                            return path.join('../static/img');
                        } else if (type === 'fonts') {
                            return path.join('../static/fonts');
                        } else {
                            return path.join(component);
                        }
                    }
                }
            }
        },

        /**
         * Concat: https://github.com/gruntjs/grunt-contrib-concat
         *
         * Concatenate cf-* LESS files prior to compiling them.
         */
        concat: {
            'cf-less': {
                src: [
                    'src/vendor/cf-*/*.less'
                ],
                dest: 'src/vendor/cf-concat/cf.less'
            }
        },

        /**
         * LESS: https://github.com/gruntjs/grunt-contrib-less
         *
         * Compile LESS files to CSS.
         */
        less: {
            main: {
                options: {
                    paths: grunt.file.expand('src/vendor/**/')
                },
                files: {
                    'src/static/css/main.css': ['src/static/css/main.less']
                }
            }
        },

        /**
         * Autoprefixer: https://github.com/nDmitry/grunt-autoprefixer
         *
         * Parse CSS and add vendor-prefixed CSS properties using the Can I Use database.
         */
        autoprefixer: {
            options: {
                // Options we might want to enable in the future.
                diff: false,
                map: false
            },
            multiple_files: {
                // Prefix all CSS files found in `src/static/css` and overwrite.
                expand: true,
                src: 'src/static/css/*.css'
            }
        },

        /**
         * Uglify: https://github.com/gruntjs/grunt-contrib-uglify
         *
         * Minify JS files.
         * Make sure to add any other JS libraries/files you'll be using.
         * You can exclude files with the ! pattern.
         */
        uglify: {
            options: {
                sourceMap: true,
                sourceMapUrl: '/static/js/main.min.js',
                beautify: false,
                drop_console: true
            },
            bodyScripts: {
                src: [
                    'src/vendor/jquery/jquery.js',
                    'src/vendor/jquery.easing/jquery.easing.js',
                    'src/static/js/jquery-hashchange.js',
                    'src/vendor/typeahead.js/typeahead.bundle.js',
                    'src/vendor/cf-*/*.js',
                    'src/static/js/jquery.custom-input.js',
                    'src/static/js/jquery.custom-select.js',
                    'src/static/js/custom-select.js',
                    'src/static/js/query.js',
                    'src/static/js/app.js'
                ],
                dest: 'src/static/js/main.min.js'
            }
        },

        /**
         * CSS Min: https://github.com/gruntjs/grunt-contrib-cssmin
         *
         * Minify CSS and optionally rewrite asset paths.
         */
        cssmin: {
            combine: {
                options: {
                    //root: '/src/'
                },
                files: {
                    'src/static/css/main.min.css': ['src/static/css/main.css'],
                    'src/static/css/fonts.min.css': ['src/static/css/fonts.css'],
                }
            }
        },

        /**
         * Clean: https://github.com/gruntjs/grunt-contrib-clean
         *
         * Clear files and folders.
         */
        clean: {
            bowerDir: ['bower_components'],
            dist: ['dist/**/*', '!dist/.git/']
        },

        /**
         * Copy: https://github.com/gruntjs/grunt-contrib-copy
         *
         * Copy files and folders.
         */
        copy: {
            dist: {
                files: [{
                    expand: true,
                    cwd: 'src/',
                    src: [
                        "*.xml",
                        'index.html',
                        'static-test.html',
                        // Only include minified assets in css/ and js/
                        'static/css/*.min.css',
                        'static/js/html5shiv-printshiv.js',
                        'static/js/*.min.js',
                        'static/js/*.min.js.map',
                        'static/fonts/**',
                        'static/img/**'
                    ],
                    dest: 'dist/'
                }]
            },
            vendor: {
                files: [{
                    expand: true,
                    cwd: 'src/',
                    src: [
                        // Only include vendor files that we use independently
                        'vendor/html5shiv/html5shiv-printshiv.min.js',
                        'vendor/box-sizing-polyfill/boxsizing.htc'
                    ],
                    // Place them in static/
                    dest: 'dist/static/'
                }]
            }
        },

        /**
         * grunt-gh-pages: https://github.com/tschaub/grunt-gh-pages
         *
         * Use Grunt to push to your gh-pages branch hosted on GitHub or any other branch anywhere else
         */
        'gh-pages': {
            options: {
                base: 'dist'
            },
            src: ['**']
        },

        /**
         * JSHint: https://github.com/gruntjs/grunt-contrib-jshint
         *
         * Validate files with JSHint.
         * Below are options that conform to idiomatic.js standards.
         * Feel free to add/remove your favorites: http://www.jshint.com/docs/#options
         */
        jshint: {
            options: {
                camelcase: false,
                curly: true,
                forin: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                quotmark: true,
                sub: true,
                boss: true,
                strict: true,
                evil: true,
                eqnull: true,
                browser: true,
                plusplus: false,
                globals: {
                    jQuery: true,
                    $: true,
                    module: true,
                    require: true,
                    define: true,
                    console: true,
                    EventEmitter: true
                }
            },
            all: ['src/static/js/main.min.js']
        },

        /**
         * Watch: https://github.com/gruntjs/grunt-contrib-connect
         *
         * Start a static web server.
         */
        connect: {
            server: {
                options: {
                    base: 'dist'
                },
            },
        },

        /**
         * Watch: https://github.com/gruntjs/grunt-contrib-watch
         *
         * Run predefined tasks whenever watched file patterns are added, changed or deleted.
         * Add files to monitor below.
         */
        watch: {
            src: {
                options: {
                    livereload: true
                },
                files: [
                    'Gruntfile.js',
                    'src/index.html',
                    'src/static/css/*.less',
                    'src/static/js/query_variables.js',
                    'src/static/js/expandable.js',
                    'src/static/js/app.js',
                    'src/static/js/querry.js'
                ],
                tasks: ['default', 'dist']
            }
        }
    });

    /**
     * The above tasks are loaded here.
     */
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.loadNpmTasks('grunt-bower-task');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-gh-pages');
    grunt.loadNpmTasks('grunt-shell');

    /**
     * Create custom task aliases and combinations
     */
    grunt.registerTask('vendor', ['clean:bowerDir', 'bower:install', 'concat:cf-less']);
    grunt.registerTask('default', ['less', 'autoprefixer', 'cssmin', 'uglify']);
    grunt.registerTask('dist', ['clean:dist', 'copy:dist', 'copy:vendor']);

    /**
     * Start a connect server and watch for changes
     */
    grunt.registerTask('serve', [
        'dist',
        'connect',
        'watch'
    ]);

};<commit_msg>watch watches renamed query.js<commit_after>module.exports = function(grunt) {

    'use strict';

    var path = require('path');

    grunt.initConfig({

        /**
         * Pull in the package.json file so we can read its metadata.
         */
        pkg: grunt.file.readJSON('package.json'),

        /**
         * Bower: https://github.com/yatskevich/grunt-bower-task
         *
         * Install Bower packages and migrate static assets.
         */
        bower: {
            install: {
                options: {
                    targetDir: './src/vendor/',
                    install: true,
                    verbose: true,
                    cleanBowerDir: true,
                    cleanTargetDir: true,
                    layout: function(type, component) {
                        if (type === 'img') {
                            return path.join('../static/img');
                        } else if (type === 'fonts') {
                            return path.join('../static/fonts');
                        } else {
                            return path.join(component);
                        }
                    }
                }
            }
        },

        /**
         * Concat: https://github.com/gruntjs/grunt-contrib-concat
         *
         * Concatenate cf-* LESS files prior to compiling them.
         */
        concat: {
            'cf-less': {
                src: [
                    'src/vendor/cf-*/*.less'
                ],
                dest: 'src/vendor/cf-concat/cf.less'
            }
        },

        /**
         * LESS: https://github.com/gruntjs/grunt-contrib-less
         *
         * Compile LESS files to CSS.
         */
        less: {
            main: {
                options: {
                    paths: grunt.file.expand('src/vendor/**/')
                },
                files: {
                    'src/static/css/main.css': ['src/static/css/main.less']
                }
            }
        },

        /**
         * Autoprefixer: https://github.com/nDmitry/grunt-autoprefixer
         *
         * Parse CSS and add vendor-prefixed CSS properties using the Can I Use database.
         */
        autoprefixer: {
            options: {
                // Options we might want to enable in the future.
                diff: false,
                map: false
            },
            multiple_files: {
                // Prefix all CSS files found in `src/static/css` and overwrite.
                expand: true,
                src: 'src/static/css/*.css'
            }
        },

        /**
         * Uglify: https://github.com/gruntjs/grunt-contrib-uglify
         *
         * Minify JS files.
         * Make sure to add any other JS libraries/files you'll be using.
         * You can exclude files with the ! pattern.
         */
        uglify: {
            options: {
                sourceMap: true,
                sourceMapUrl: '/static/js/main.min.js',
                beautify: false,
                drop_console: true
            },
            bodyScripts: {
                src: [
                    'src/vendor/jquery/jquery.js',
                    'src/vendor/jquery.easing/jquery.easing.js',
                    'src/static/js/jquery-hashchange.js',
                    'src/vendor/typeahead.js/typeahead.bundle.js',
                    'src/vendor/cf-*/*.js',
                    'src/static/js/jquery.custom-input.js',
                    'src/static/js/jquery.custom-select.js',
                    'src/static/js/custom-select.js',
                    'src/static/js/query.js',
                    'src/static/js/app.js'
                ],
                dest: 'src/static/js/main.min.js'
            }
        },

        /**
         * CSS Min: https://github.com/gruntjs/grunt-contrib-cssmin
         *
         * Minify CSS and optionally rewrite asset paths.
         */
        cssmin: {
            combine: {
                options: {
                    //root: '/src/'
                },
                files: {
                    'src/static/css/main.min.css': ['src/static/css/main.css'],
                    'src/static/css/fonts.min.css': ['src/static/css/fonts.css'],
                }
            }
        },

        /**
         * Clean: https://github.com/gruntjs/grunt-contrib-clean
         *
         * Clear files and folders.
         */
        clean: {
            bowerDir: ['bower_components'],
            dist: ['dist/**/*', '!dist/.git/']
        },

        /**
         * Copy: https://github.com/gruntjs/grunt-contrib-copy
         *
         * Copy files and folders.
         */
        copy: {
            dist: {
                files: [{
                    expand: true,
                    cwd: 'src/',
                    src: [
                        "*.xml",
                        'index.html',
                        'static-test.html',
                        // Only include minified assets in css/ and js/
                        'static/css/*.min.css',
                        'static/js/html5shiv-printshiv.js',
                        'static/js/*.min.js',
                        'static/js/*.min.js.map',
                        'static/fonts/**',
                        'static/img/**'
                    ],
                    dest: 'dist/'
                }]
            },
            vendor: {
                files: [{
                    expand: true,
                    cwd: 'src/',
                    src: [
                        // Only include vendor files that we use independently
                        'vendor/html5shiv/html5shiv-printshiv.min.js',
                        'vendor/box-sizing-polyfill/boxsizing.htc'
                    ],
                    // Place them in static/
                    dest: 'dist/static/'
                }]
            }
        },

        /**
         * grunt-gh-pages: https://github.com/tschaub/grunt-gh-pages
         *
         * Use Grunt to push to your gh-pages branch hosted on GitHub or any other branch anywhere else
         */
        'gh-pages': {
            options: {
                base: 'dist'
            },
            src: ['**']
        },

        /**
         * JSHint: https://github.com/gruntjs/grunt-contrib-jshint
         *
         * Validate files with JSHint.
         * Below are options that conform to idiomatic.js standards.
         * Feel free to add/remove your favorites: http://www.jshint.com/docs/#options
         */
        jshint: {
            options: {
                camelcase: false,
                curly: true,
                forin: true,
                immed: true,
                latedef: true,
                newcap: true,
                noarg: true,
                quotmark: true,
                sub: true,
                boss: true,
                strict: true,
                evil: true,
                eqnull: true,
                browser: true,
                plusplus: false,
                globals: {
                    jQuery: true,
                    $: true,
                    module: true,
                    require: true,
                    define: true,
                    console: true,
                    EventEmitter: true
                }
            },
            all: ['src/static/js/main.min.js']
        },

        /**
         * Watch: https://github.com/gruntjs/grunt-contrib-connect
         *
         * Start a static web server.
         */
        connect: {
            server: {
                options: {
                    base: 'dist'
                },
            },
        },

        /**
         * Watch: https://github.com/gruntjs/grunt-contrib-watch
         *
         * Run predefined tasks whenever watched file patterns are added, changed or deleted.
         * Add files to monitor below.
         */
        watch: {
            src: {
                options: {
                    livereload: true
                },
                files: [
                    'Gruntfile.js',
                    'src/index.html',
                    'src/static/css/*.less',
                    'src/static/js/query_variables.js',
                    'src/static/js/expandable.js',
                    'src/static/js/app.js',
                    'src/static/js/query.js'
                ],
                tasks: ['default', 'dist']
            }
        }
    });

    /**
     * The above tasks are loaded here.
     */
    grunt.loadNpmTasks('grunt-autoprefixer');
    grunt.loadNpmTasks('grunt-bower-task');
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-copy');
    grunt.loadNpmTasks('grunt-contrib-cssmin');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-less');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-gh-pages');
    grunt.loadNpmTasks('grunt-shell');

    /**
     * Create custom task aliases and combinations
     */
    grunt.registerTask('vendor', ['clean:bowerDir', 'bower:install', 'concat:cf-less']);
    grunt.registerTask('default', ['less', 'autoprefixer', 'cssmin', 'uglify']);
    grunt.registerTask('dist', ['clean:dist', 'copy:dist', 'copy:vendor']);

    /**
     * Start a connect server and watch for changes
     */
    grunt.registerTask('serve', [
        'dist',
        'connect',
        'watch'
    ]);

};<|endoftext|>


<commit_before>#!/usr/bin/env node

var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
var formatter = require('bible-reference-formatter/es6/tr');

bcv.set_options({
  'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

var references = [];

function extract_references (data) {
  var res = bcv.parse(data).parsed_entities();
  res.forEach(function(match) {
    var ref = {};
    ref.original = data.slice(match.indices[0], match.indices[1]);
    ref.osis = match.osis;
    ref.seq = bcv.translations.default.order[match.start.b] * 1000000 + match.start.c * 1000 + match.start.v;
    ref.reformat = formatter('yc-long', match.osis);
    references.push(ref);
  });
}

function output_references () {
  var output = JSON.stringify(references, null, '  ');
  process.stdout.write(output);
}

rl.on('line', extract_references);
rl.on('close', output_references);
<commit_msg>Pass along pre-parsed BCV items to make life easier in Lua<commit_after>#!/usr/bin/env node

var readline = require('readline');
var bcv_parser = require('bible-passage-reference-parser/js/tr_bcv_parser').bcv_parser;
var bcv = new bcv_parser();
var formatter = require('bible-reference-formatter/es6/tr');

bcv.set_options({
  'sequence_combination_strategy': 'separate'
});
bcv.include_apocrypha(true);

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

var references = [];

function extract_references (data) {
  var res = bcv.parse(data).parsed_entities();
  res.forEach(function(match) {
    var ref = {};
    ref.original = data.slice(match.indices[0], match.indices[1]);
    ref.osis = match.osis;
    ref.b = formatter('yc-long', match.start.b);
    ref.c = match.start.c;
    ref.v = match.start.v;
    ref.seq = bcv.translations["default"].order[match.start.b] * 1000000 + match.start.c * 1000 + match.start.v;
    ref.reformat = formatter('yc-long', match.osis);
    references.push(ref);
  });
}

function output_references () {
  var output = JSON.stringify(references, null, '  ');
  process.stdout.write(output);
}

rl.on('line', extract_references);
rl.on('close', output_references);
<|endoftext|>


<commit_before>#!/usr/bin/env node
// Usage:  ghw <input> <output dir>
// where <input> is either a file or a dir.
var VERSION = '0.0.3'

var fs = require('fs');
var marked = require('marked');
var mu = require('mu2');

if(require.main == module) {
    var program = require('commander');

    program.
        version(VERSION).
        option('-t --template <template>', 'base template (Moustache)').
        option('-i --input <input>', 'input (file/directory)').
        option('-o --output <output>', 'output directory').
        parse(process.argv);

    function quit(msg) {
        console.log(msg);
        process.exit();
    }

    if (!program.template) quit('Missing template');
    if (!program.input) quit('Missing input');
    if (!program.output) quit('Missing output');

    console.log('ghw ' + VERSION);

    transform(program.input, transformers(), function(f, d) {
        var stream = mu.compileAndRender(program.template, {data: d});
        var target = program.output + f.substring(f.lastIndexOf('/'), f.length).substring(0, f.indexOf('.')) + 'html';
        var writeStream = fs.createWriteStream(target);

        stream.pipe(writeStream);
        stream.on('end', function() {
            console.log('Wrote ' + target);
        });
    });
}
else {
    exports.VERSION = VERSION;
    exports.transform = transform;
    exports.transformers = transformers();
}

function transform(f, transformers, done) {
    fs.readFile(f, 'utf-8', function(err, data) {
        if (err) throw err;

        var tokens = marked.lexer(data).map(function(t) {
            if(t.type == 'text') {
                var text = t.text;

                for(var k in transformers) {
                    text = transformers[k](text);
                }

                return {
                    type: 'text',
                    text: text
                };
            }
            return t;
        });
        tokens.links = [];

        done(f, marked.parser(tokens));
    });
}

function transformers() {
    return {
        pipe_link: function(t) {
            return t.replace(
                /\[([^\|]+)\|([^\]]+)\]/,
                '$1'
            );
        },
        bracket_link: function(t) {
            return t.replace(
                /\[\[([^\]]+)\]\]/,
                '$1'
            );
        }
    };
}

<commit_msg>Make the tool accept directory input<commit_after>#!/usr/bin/env node
// Usage:  ghw <input> <output dir>
// where <input> is either a file or a dir.
var VERSION = '0.0.3'

var path = require('path');
var fs = require('fs');
var marked = require('marked');
var mu = require('mu2');

if(require.main == module) {
    var program = require('commander');

    program.
        version(VERSION).
        option('-t --template <template>', 'base template (Moustache)').
        option('-i --input <input>', 'input (file/directory)').
        option('-o --output <output>', 'output directory').
        parse(process.argv);

    function quit(msg) {
        console.log(msg);
        process.exit();
    }

    if (!program.template) quit('Missing template');
    if (!program.input) quit('Missing input');
    if (!program.output) quit('Missing output');

    console.log('ghw ' + VERSION);

    fs.stat(program.input, function(err, stats) {
        if (err) throw err;

        if(stats.isFile()) {
            transform(program.input, transformers(), proc);
        }
        if(stats.isDirectory()) {
            fs.readdir(program.input, function(err, files) {
                if (err) throw err;

                files.forEach(function (file) {
                    var p = path.join(program.input, file);

                    fs.stat(p, function(err, stats) {
                        if(stats.isFile()) {
                            transform(p, transformers(), proc);
                        }
                    });
                });
            });
        }
    });

    function proc(f, d) {
        var stream = mu.compileAndRender(program.template, {data: d});
        var target = path.join(program.output, path.basename(f, '.md') + '.html');
        var writeStream = fs.createWriteStream(target);

        stream.pipe(writeStream);
        stream.on('end', function() {
            console.log('Wrote ' + target);
        });
    }
}
else {
    exports.VERSION = VERSION;
    exports.transform = transform;
    exports.transformers = transformers();
}

function transform(f, transformers, done) {
    fs.readFile(f, 'utf-8', function(err, data) {
        if (err) throw err;

        var tokens = marked.lexer(data).map(function(t) {
            if(t.type == 'text') {
                var text = t.text;

                for(var k in transformers) {
                    text = transformers[k](text);
                }

                return {
                    type: 'text',
                    text: text
                };
            }
            return t;
        });
        tokens.links = [];

        done(f, marked.parser(tokens));
    });
}

function transformers() {
    return {
        pipe_link: function(t) {
            return t.replace(
                /\[([^\|]+)\|([^\]]+)\]/,
                '$1'
            );
        },
        bracket_link: function(t) {
            return t.replace(
                /\[\[([^\]]+)\]\]/,
                '$1'
            );
        }
    };
}

<|endoftext|>


<commit_before>(function() {

   var ChildProcess = require('child_process');

   /**
    * Git handling for node. All public functions can be chained and all `then` handlers are optional.
    *
    * @param {String} baseDir
    * @constructor
    */
   function Git(baseDir) {
      this._baseDir = baseDir;
      this._runCache = [];
   }

   /**
    * Initalize a git repo
    *
    * @param {Function} [then]
    */
   Git.prototype.init = function(then) {
      return this._run('git init', function(err) {
         then && then(err);
      });
   };

   /**
    * Clone a git repo
    *
    * @param {String} repoPath
    * @param {String} localPath
    * @param {Function} [then]
    */
   Git.prototype.clone = function(repoPath, localPath, then ) {
      return this._run('git clone ' + repoPath + ' ' + localPath, function(err) {
         then && then(err);
      });
   };

   /**
    * Internally uses pull and tags to get the list of tags then checks out the latest tag.
    *
    * @param {Function} [then]
    */
   Git.prototype.checkoutLatestTag = function(then) {
      var git = this;
      return this.pull().tags(function(err, tags) {
         git.checkout(tags.latest, then);
      });
   };

   /**
    * Adds one or more files to source control
    *
    * @param {String|String[]} files
    * @param {Function} [then]
    */
   Git.prototype.add = function(files, then) {
      return this._run('git add "' + [].concat(files).join('" "') + '"', function(err, data) {
         then && then(err);
      });
   };

   /**
    * Commits changes in the current working directory - when specific file paths are supplied, only changes on those
    * files will be committed.
    *
    * @param {String} message
    * @param {String|String[]} [files]
    * @param {Function} [then]
    */
   Git.prototype.commit = function(message, files, then) {
      var git = this;
      if(!then && typeof files === "function") {
         then = files;
         files = [];
      }

      files = files ? ' "' + [].concat(files).join('" "') + '"' : '';

      return this._run('git commit -m "' + message.replace(/"/g, '\\"') + '"' + files, function(err, data) {
         then && then(err, !err && git._parseCommit(data));
      });
   };

   /**
    * Pull the updated contents of the current repo
    * @param {String} [remote]
    * @param {String} [branch]
    * @param {Function} [then]
    */
   Git.prototype.pull = function(remote, branch, then) {
      var command = "git pull";
      if (typeof remote === 'string' && typeof branch === 'string') {
         command += ' "' + remote + '" "' + branch + '"';
      }
      if (typeof arguments[arguments.length - 1] === 'function') {
         then = arguments[arguments.length - 1];
      }

      return this._run(command, function(err, data) {
         then && then(err, !err && this._parsePull(data));
      });
   };

   /**
    * Fetch the updated contents of the current repo.
    *
    * @example
    *   .fetch('upstream', 'master') // fetches from master on remote named upstream
    *   .fetch(function () {}) // runs fetch against default remote and branch and calls function
    *
    * @param {String} [remote]
    * @param {String} [branch]
    * @param {Function} [then]
    */
   Git.prototype.fetch = function(remote, branch, then) {
      var command = "git fetch";
      if (typeof remote === 'string' && typeof branch === 'string') {
         command += ' "' + remote + '" "' + branch + '"';
      }
      if (typeof arguments[arguments.length - 1] === 'function') {
         then = arguments[arguments.length - 1];
      }

      return this._run(command, function(err, data) {
         then && then(err, !err && this._parsePush(data));
      });
   };

   /**
    * List all tags
    *
    * @param {Function} [then]
    */
   Git.prototype.tags = function(then) {
      return this._run('git tag -l', function(err, data) {
         then && then(err, !err && this._parseListTags(data));
      });
   };

   /**
    * Check out a tag or revision
    *
    * @param {String} what
    * @param {Function} [then]
    */
   Git.prototype.checkout = function(what, then) {
      return this._run('git checkout "' + what + '"', function(err, data) {
         then && then(err, !err && this._parseCheckout(data));
      });
   };

   /**
    * Add a submodule
    *
    * @param {String} repo
    * @param {String} path
    * @param {Function} [then]
    */
   Git.prototype.submoduleAdd = function(repo, path, then) {
      return this._run('git submodule add "' + repo + '" "' + path + '"', function(err) {
         then && then(err);
      });
   };

   /**
    * List remote
    *
    * @param {String} [args]
    * @param {Function} [then]
    */
   Git.prototype.listRemote = function(args, then) {
      if (!then && typeof args === "function") {
         then = args;
         args = '';
      }
      return this._run('git ls-remote ' + args, function(err, data) {
         then && then(err, data);
      });
   };

   /**
    * Adds a remote to the list of remotes.
    *
    * @param {String} remoteName Name of the repository - eg "upstream"
    * @param {String} remoteRepo Fully qualified SSH or HTTP(S) path to the remote repo
    * @param {Function} [then]
    * @returns {*}
    */
   Git.prototype.addRemote = function(remoteName, remoteRepo, then) {
      return this._run('git remote add "' + remoteName + '" "' + remoteRepo + '"', function (err) {
         then && then(err);
      });
   };

   /**
    * Removes an entry from the list of remotes.
    *
    * @param {String} remoteName Name of the repository - eg "upstream"
    * @param {Function} [then]
    * @returns {*}
    */
   Git.prototype.removeRemote = function(remoteName, then) {
      return this._run('git remote remove "' + remoteName + '"', function (err) {
         then && then(err);
      });
   };

   /**
    * Pushes the current committed changes to a remote, optionally specify the names of the remote and branch to use
    * when pushing.
    *
    * @param {String} [remote]
    * @param {String} [branch]
    * @param {Function} [then]
    */
   Git.prototype.push = function(remote, branch, then) {
      var command = "git push";
      if (typeof remote === 'string' && typeof branch === 'string') {
         command += ' "' + remote + '" "' + branch + '"';
      }
      if (typeof arguments[arguments.length - 1] === 'function') {
         then = arguments[arguments.length - 1];
      }

      return this._run(command, function(err, data) {
         then && then(err, !err && this._parsePush(data));
      });
   };

   /**
    * Removes the named files from source control.
    *
    * @param {String|String[]} files
    * @param {Function} [then]
    */
   Git.prototype.rm = function(files, then) {
      return this._rm(files, '-f', then);
   };

   /**
    * Removes the named files from source control but keeps them on disk rather than deleting them entirely. To
    * completely remove the files, use `rm`.
    *
    * @param {String|String[]} files
    * @param {Function} [then]
    */
   Git.prototype.rmKeepLocal = function(files, then) {
      return this._rm(files, '--cached', then);
   };

   Git.prototype._rm = function(files, options, then) {
      return this._run('git rm ' + options + ' "' + [].concat(files).join('" "') + '"', function(err) {
         then && then(err);
      });
   };

   Git.prototype._parsePull = function(pull) {
      var changes = {
         files: [],
         insertions: {},
         deletions: {},
         summary: {
            changes: 0,
            insertions: 0,
            deletions: 0
         }
      };

      var fileUpdateRegex = /^\s*(.+)\s\|\s(\d+)\s([\+]+)/;
      for(var lines = pull.split('\n'), i = 0, l = lines.length; i < l; i++) {
         var update = fileUpdateRegex.exec(lines[i]);

         // search for update statement for each file
         if(update) {
            changes.files.push(update[1]);

            var insertions = update[3].length;
            if(insertions) {
               changes.insertions[update[1]] = insertions;
            }
            if(update[2] > insertions) {
               changes.deletions[update[1]] = update[2] - insertions;
            }
         }

         // summary appears after updates
         else if(changes.files.length && (update = /(\d+)\D+(\d+)\D+(\d+)/.exec(lines[i]))) {
            changes.summary.changes = +update[1];
            changes.summary.insertions = +update[2];
            changes.summary.deletions = +update[3];
         }
      }

      return changes;
   };

   Git.prototype._parseListTags = function(tags) {
      var tagList = tags.split('\n').sort(function(tagA, tagB) {
         var partsA = tagA.split('.');
         var partsB = tagB.split('.');

         for(var i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) {
            var diff = partsA[i] - partsB[i];
            if(diff) {
               return diff > 0 ? 1 : -1;
            }
         }

         return 0;
      });

      return {
         latest: tagList.length && tagList[tagList.length - 1],
         all: tagList
      };
   };

   Git.prototype._parseCommit = function(commit) {
      var lines = commit.trim().split('\n');
      var branch = /\[([^\s]+) ([^\]]+)/.exec(lines.shift());
      var summary = /(\d+)[^,]*(?:,\s*(\d+)[^,]*)?(?:,\s*(\d+))?/g.exec(lines.shift()) || [];

      return {
         branch: branch[1],
         commit: branch[2],
         summary: {
            changes: (typeof summary[1] !== 'undefined') ? summary[1] : 0,
            insertions: (typeof summary[2] !== 'undefined') ? summary[2] : 0,
            deletions: (typeof summary[3] !== 'undefined') ? summary[3] : 0
         }
      };
   };

   Git.prototype._parseCheckout = function(checkout) {
      // TODO
   };

   Git.prototype._parseFetch = function(fetch) {
      return data;
   };

   Git.prototype._run = function(command, then) {
      this._runCache.push([command, then]);
      this._schedule();

      return this;
   };

   Git.prototype._schedule = function() {
      if(!this._childProcess && this._runCache.length) {
         var task = this._runCache.shift();
         var command = task[0];
         var then = task[1];

         this._childProcess = ChildProcess.exec(
             command,
             {cwd: this._baseDir},
             function(err, stdout, stderr) {
                delete this._childProcess;

                if(err) {
                   console.error(stderr);
                   this._runCache = [];
                   then.call(this, err, null);
                }
                else {
                   then.call(this, null, stdout);
                }

                process.nextTick(this._schedule.bind(this));
             }.bind(this));
      }
   };

   module.exports = function(baseDir) {
      return new Git(baseDir || process.cwd());
   };

}());
<commit_msg>Added diff function<commit_after>(function() {

   var ChildProcess = require('child_process');

   /**
    * Git handling for node. All public functions can be chained and all `then` handlers are optional.
    *
    * @param {String} baseDir
    * @constructor
    */
   function Git(baseDir) {
      this._baseDir = baseDir;
      this._runCache = [];
   }

   /**
    * Initalize a git repo
    *
    * @param {Function} [then]
    */
   Git.prototype.init = function(then) {
      return this._run('git init', function(err) {
         then && then(err);
      });
   };

   /**
    * Clone a git repo
    *
    * @param {String} repoPath
    * @param {String} localPath
    * @param {Function} [then]
    */
   Git.prototype.clone = function(repoPath, localPath, then ) {
      return this._run('git clone ' + repoPath + ' ' + localPath, function(err) {
         then && then(err);
      });
   };

   /**
    * Internally uses pull and tags to get the list of tags then checks out the latest tag.
    *
    * @param {Function} [then]
    */
   Git.prototype.checkoutLatestTag = function(then) {
      var git = this;
      return this.pull().tags(function(err, tags) {
         git.checkout(tags.latest, then);
      });
   };

   /**
    * Adds one or more files to source control
    *
    * @param {String|String[]} files
    * @param {Function} [then]
    */
   Git.prototype.add = function(files, then) {
      return this._run('git add "' + [].concat(files).join('" "') + '"', function(err, data) {
         then && then(err);
      });
   };

   /**
    * Commits changes in the current working directory - when specific file paths are supplied, only changes on those
    * files will be committed.
    *
    * @param {String} message
    * @param {String|String[]} [files]
    * @param {Function} [then]
    */
   Git.prototype.commit = function(message, files, then) {
      var git = this;
      if(!then && typeof files === "function") {
         then = files;
         files = [];
      }

      files = files ? ' "' + [].concat(files).join('" "') + '"' : '';

      return this._run('git commit -m "' + message.replace(/"/g, '\\"') + '"' + files, function(err, data) {
         then && then(err, !err && git._parseCommit(data));
      });
   };

   /**
    * Pull the updated contents of the current repo
    * @param {String} [remote]
    * @param {String} [branch]
    * @param {Function} [then]
    */
   Git.prototype.pull = function(remote, branch, then) {
      var command = "git pull";
      if (typeof remote === 'string' && typeof branch === 'string') {
         command += ' "' + remote + '" "' + branch + '"';
      }
      if (typeof arguments[arguments.length - 1] === 'function') {
         then = arguments[arguments.length - 1];
      }

      return this._run(command, function(err, data) {
         then && then(err, !err && this._parsePull(data));
      });
   };

   /**
    * Fetch the updated contents of the current repo.
    *
    * @example
    *   .fetch('upstream', 'master') // fetches from master on remote named upstream
    *   .fetch(function () {}) // runs fetch against default remote and branch and calls function
    *
    * @param {String} [remote]
    * @param {String} [branch]
    * @param {Function} [then]
    */
   Git.prototype.fetch = function(remote, branch, then) {
      var command = "git fetch";
      if (typeof remote === 'string' && typeof branch === 'string') {
         command += ' "' + remote + '" "' + branch + '"';
      }
      if (typeof arguments[arguments.length - 1] === 'function') {
         then = arguments[arguments.length - 1];
      }

      return this._run(command, function(err, data) {
         then && then(err, !err && this._parsePush(data));
      });
   };

   /**
    * List all tags
    *
    * @param {Function} [then]
    */
   Git.prototype.tags = function(then) {
      return this._run('git tag -l', function(err, data) {
         then && then(err, !err && this._parseListTags(data));
      });
   };

   /**
    * Check out a tag or revision
    *
    * @param {String} what
    * @param {Function} [then]
    */
   Git.prototype.checkout = function(what, then) {
      return this._run('git checkout "' + what + '"', function(err, data) {
         then && then(err, !err && this._parseCheckout(data));
      });
   };

   /**
    * Add a submodule
    *
    * @param {String} repo
    * @param {String} path
    * @param {Function} [then]
    */
   Git.prototype.submoduleAdd = function(repo, path, then) {
      return this._run('git submodule add "' + repo + '" "' + path + '"', function(err) {
         then && then(err);
      });
   };

   /**
    * List remote
    *
    * @param {String} [args]
    * @param {Function} [then]
    */
   Git.prototype.listRemote = function(args, then) {
      if (!then && typeof args === "function") {
         then = args;
         args = '';
      }
      return this._run('git ls-remote ' + args, function(err, data) {
         then && then(err, data);
      });
   };

   /**
    * Adds a remote to the list of remotes.
    *
    * @param {String} remoteName Name of the repository - eg "upstream"
    * @param {String} remoteRepo Fully qualified SSH or HTTP(S) path to the remote repo
    * @param {Function} [then]
    * @returns {*}
    */
   Git.prototype.addRemote = function(remoteName, remoteRepo, then) {
      return this._run('git remote add "' + remoteName + '" "' + remoteRepo + '"', function (err) {
         then && then(err);
      });
   };

   /**
    * Removes an entry from the list of remotes.
    *
    * @param {String} remoteName Name of the repository - eg "upstream"
    * @param {Function} [then]
    * @returns {*}
    */
   Git.prototype.removeRemote = function(remoteName, then) {
      return this._run('git remote remove "' + remoteName + '"', function (err) {
         then && then(err);
      });
   };

   /**
    * Pushes the current committed changes to a remote, optionally specify the names of the remote and branch to use
    * when pushing.
    *
    * @param {String} [remote]
    * @param {String} [branch]
    * @param {Function} [then]
    */
   Git.prototype.push = function(remote, branch, then) {
      var command = "git push";
      if (typeof remote === 'string' && typeof branch === 'string') {
         command += ' "' + remote + '" "' + branch + '"';
      }
      if (typeof arguments[arguments.length - 1] === 'function') {
         then = arguments[arguments.length - 1];
      }

      return this._run(command, function(err, data) {
         then && then(err, !err && this._parsePush(data));
      });
   };

   /**
    * Removes the named files from source control.
    *
    * @param {String|String[]} files
    * @param {Function} [then]
    */
   Git.prototype.rm = function(files, then) {
      return this._rm(files, '-f', then);
   };

   /**
    * Removes the named files from source control but keeps them on disk rather than deleting them entirely. To
    * completely remove the files, use `rm`.
    *
    * @param {String|String[]} files
    * @param {Function} [then]
    */
   Git.prototype.rmKeepLocal = function(files, then) {
      return this._rm(files, '--cached', then);
   };

   /**
    * Return repository changes.
    *
    * @param {String} [options]
    * @param {Function} [then]
    */
   Git.prototype.diff = function(options, then) {
      var command = 'git diff';
      if (typeof options === 'string' && typeof then === 'function') {
         command += ' ' + options;
      }
      if (typeof arguments[arguments.length - 1] === 'function') {
         then = arguments[arguments.length - 1];
      }

      return this._run(command, function(err, data) {
         then && then(err, data);
      });
   };

   Git.prototype._rm = function(files, options, then) {
      return this._run('git rm ' + options + ' "' + [].concat(files).join('" "') + '"', function(err) {
         then && then(err);
      });
   };

   Git.prototype._parsePull = function(pull) {
      var changes = {
         files: [],
         insertions: {},
         deletions: {},
         summary: {
            changes: 0,
            insertions: 0,
            deletions: 0
         }
      };

      var fileUpdateRegex = /^\s*(.+)\s\|\s(\d+)\s([\+]+)/;
      for(var lines = pull.split('\n'), i = 0, l = lines.length; i < l; i++) {
         var update = fileUpdateRegex.exec(lines[i]);

         // search for update statement for each file
         if(update) {
            changes.files.push(update[1]);

            var insertions = update[3].length;
            if(insertions) {
               changes.insertions[update[1]] = insertions;
            }
            if(update[2] > insertions) {
               changes.deletions[update[1]] = update[2] - insertions;
            }
         }

         // summary appears after updates
         else if(changes.files.length && (update = /(\d+)\D+(\d+)\D+(\d+)/.exec(lines[i]))) {
            changes.summary.changes = +update[1];
            changes.summary.insertions = +update[2];
            changes.summary.deletions = +update[3];
         }
      }

      return changes;
   };

   Git.prototype._parseListTags = function(tags) {
      var tagList = tags.split('\n').sort(function(tagA, tagB) {
         var partsA = tagA.split('.');
         var partsB = tagB.split('.');

         for(var i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) {
            var diff = partsA[i] - partsB[i];
            if(diff) {
               return diff > 0 ? 1 : -1;
            }
         }

         return 0;
      });

      return {
         latest: tagList.length && tagList[tagList.length - 1],
         all: tagList
      };
   };

   Git.prototype._parseCommit = function(commit) {
      var lines = commit.trim().split('\n');
      var branch = /\[([^\s]+) ([^\]]+)/.exec(lines.shift());
      var summary = /(\d+)[^,]*(?:,\s*(\d+)[^,]*)?(?:,\s*(\d+))?/g.exec(lines.shift()) || [];

      return {
         branch: branch[1],
         commit: branch[2],
         summary: {
            changes: (typeof summary[1] !== 'undefined') ? summary[1] : 0,
            insertions: (typeof summary[2] !== 'undefined') ? summary[2] : 0,
            deletions: (typeof summary[3] !== 'undefined') ? summary[3] : 0
         }
      };
   };

   Git.prototype._parseCheckout = function(checkout) {
      // TODO
   };

   Git.prototype._parseFetch = function(fetch) {
      return data;
   };

   Git.prototype._run = function(command, then) {
      this._runCache.push([command, then]);
      this._schedule();

      return this;
   };

   Git.prototype._schedule = function() {
      if(!this._childProcess && this._runCache.length) {
         var task = this._runCache.shift();
         var command = task[0];
         var then = task[1];

         this._childProcess = ChildProcess.exec(
             command,
             {cwd: this._baseDir},
             function(err, stdout, stderr) {
                delete this._childProcess;

                if(err) {
                   console.error(stderr);
                   this._runCache = [];
                   then.call(this, err, null);
                }
                else {
                   then.call(this, null, stdout);
                }

                process.nextTick(this._schedule.bind(this));
             }.bind(this));
      }
   };

   module.exports = function(baseDir) {
      return new Git(baseDir || process.cwd());
   };

}());
<|endoftext|>


<commit_before>#!/usr/bin/env node

var format = require('..')
  , indent = 2
  , argv = process.argv;

var indentIdx = argv.indexOf('--indent') || argv.indexOf('-i');
if (~indentIdx) {
  indent = argv[indentIdx + 1];
}

process.stdin.pipe(format(parseInt(indent, 10))).pipe(process.stdout);
<commit_msg>fixing -i flag<commit_after>#!/usr/bin/env node

var format = require('..')
  , argv = process.argv;

var indent = (function() {
  var indentIdx = argv.indexOf('--indent');
  indentIdx = ~indentIdx ? indentIdx : argv.indexOf('-i');
  return ~indentIdx ? argv[indentIdx + 1] : 2;
})();

process.stdin.pipe(format(parseInt(indent, 10))).pipe(process.stdout);
<|endoftext|>


<commit_before>module.exports = Renderer;

var EntityManager = require('tiny-ecs').EntityManager;
var Vec2          = require('tiny-ecs').Vec2;
var Style         = require('../../lib/renderer/Style.js');
var Canvas        = require('../../lib/renderer/Canvas.js');
var Position      = require('../components/Position.js');
var Spatial       = require('../components/Spatial.js');
var LevelObject   = require('../components/LevelObject.js');
var ColorSpirit   = require('../components/ColorSpirit.js');
var Avatar        = require('../components/Avatar.js');
var Text          = require('../components/Text.js');

/**
 * @constructor
 * @param {EntityManager} entities
 * @param {Canvas} screen
 */
function Renderer(screen, entities, maps)
{
  this.screen     = screen;
  this.entities   = entities;
  this.maps       = maps;
  global.renderer = this;
}

var COLOR_FILTER = [Position, Spatial, ColorSpirit];
var LEVEL_FILTER = [Position, LevelObject];

var TEXT_FILTER = [Position, Text];

// All avatars have to have a color spirit
var AVATAR_FILTER = [Position, Spatial, Avatar, ColorSpirit];

/**
 * @param {Number} dt
 * @param {Number} time
 */
Renderer.prototype.update = function(dt, time)
{
  this.screen.save();
  this.screen.fill('#202020');
  this.cameraTransform();
  this.drawBg();
  this.drawWalls();
  this.drawGems(dt, time);
  this.drawLevelObjects();
  this.drawAvatars();
  // this.drawTexts();
  this.screen.restore();
};

var borderStyle = new Style();
borderStyle.color = '#333';
var bV = new Vec2();
Renderer.prototype.drawBg = function()
{
  var player = this.entities.queryTag('player')[0];
  var pad = 30;
  bV.assign(this.maps.size);
  bV.x += pad*2;
  bV.y += pad*2;
  this.screen.save();
  this.screen.save();
  this.screen.translate(-pad, -pad);
  this.screen.drawRectangle(bV, borderStyle);
  this.screen.restore();
  this.screen.drawRectangle(this.maps.size, player.colorSpirit.style);
  this.screen.restore();
};

var ct = new Vec2();
Renderer.prototype.cameraTransform = function()
{
  var player = this.entities.queryTag('player')[0];

  // cacl zoom
  var zoom = this.zoom || 1;
  var per = player.newtonian.velocity.magnitude() / player.newtonian.maxSpeed;

  // do zoom
  var p = 0.992;
  var newZoom = 2 - 1 * per;
  zoom = zoom * p + (1-p) * newZoom;
  this.screen.scale(zoom, zoom);
  this.zoom = zoom;

  // Translate to account for player
  ct.assign(this.screen.getSize()).smult(0.5 * (1/zoom));
  this.screen.vtranslate(ct);
  ct.assign(player.position.location).smult(-1);
  this.screen.vtranslate(ct);

};

Renderer.prototype.drawTexts = function()
{
  var entities = this.entities.queryComponents(TEXT_FILTER);

  for (var n = 0; n < entities.length; n++) {
    this.drawText(entities[n]);
  }
};

Renderer.prototype.drawWalls = function()
{
  var entities = this.entities.queryTag('wall');
  for (var n = 0; n < entities.length; n++) {
    this.drawWall(entities[n]);
  }
};

Renderer.prototype.drawWall = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawHwRect(entity.spatial.hwidth, entity.colorSpirit.style)
    .restore();
};

Renderer.prototype.drawGems = function(dt, time)
{
  var entities = this.entities.queryTag('gem');
  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];
    this.drawGem(entity, dt, time);
  }
};

Renderer.prototype.drawGem = function(entity, dt, time)
{
  var wiggle = Math.sin(5*time/1000) * 2 + 2;
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawCircle(entity.spatial.hwidth.x + wiggle, entity.colorSpirit.style)
    .restore();
};

Renderer.prototype.drawAvatars = function()
{
  var entities = this.entities.queryComponents(AVATAR_FILTER);

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];
    this.drawAvatar(entity);
  }
};

var vh = new Vec2();
var playerStyle = new Style();
playerStyle.color = '#fff';
var shipsize = 15;
//playerStyle.fillStyle = '#EEE';
Renderer.prototype.drawAvatar = function(entity)
{
  var h = Vec2.aquire();
  var pos = Vec2.aquire();

  h.assign(entity.spatial.hwidth);
  h.y *= 0.5;
  pos.set(entity.spatial.hwidth.x/2.2, 0);

  this.screen
    .save()
    .vtranslate(entity.position.location)
    .rotate(entity.position.rotation)
    //.drawHwRect(entity.spatial.hwidth, playerStyle)
    .drawShape(
      // [170, 80,
      // 130, 100, 130, 150, 230, 150,
      // 250, 180, 320, 180, 340, 150,
      // 420, 150, 420, 120, 390, 100,
      // 430, 40, 370, 30, 340, 50,
      // 320, 5, 250, 20, 250, 50,
      // 200, 5, 150, 20, 170, 80]
      [ {x:-shipsize, y:shipsize}, {x:shipsize,y:0}, {x:-shipsize,y:-shipsize}]
      , playerStyle)

    //.vtranslate(pos)
    //.drawHwRect(h, playerStyle)
    .restore();

  Vec2.release(h);
  Vec2.release(pos);
};

Renderer.prototype.drawLevelObjects = function()
{
  var entities = this.entities.queryComponents(LEVEL_FILTER);
  var screen = this.screen;

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];

    if (entity.levelObject.type === LevelObject.types.PLAYER_START)
      this.drawStart(entity);

    if (entity.levelObject.type === LevelObject.types.LEVEL_FINISH)
      this.drawStart(entity);
  }
};

var textStyle = new Style();
textStyle.color = '#fff';
Renderer.prototype.drawText = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawText(entity.text.value, textStyle)
    .restore();
}

var startSize = new Vec2(25, 25);
var startStyle = new Style()
startStyle.stroke = '#333';
startStyle.strokeWidth = 5;
Renderer.prototype.drawStart = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    //.drawHwRect(startSize, startStyle)
    .drawCircle(50, startStyle)
    .restore();
};

<commit_msg>REnder pipe djust<commit_after>module.exports = Renderer;

var EntityManager = require('tiny-ecs').EntityManager;
var Vec2          = require('tiny-ecs').Vec2;
var Style         = require('../../lib/renderer/Style.js');
var Canvas        = require('../../lib/renderer/Canvas.js');
var Position      = require('../components/Position.js');
var Spatial       = require('../components/Spatial.js');
var LevelObject   = require('../components/LevelObject.js');
var ColorSpirit   = require('../components/ColorSpirit.js');
var Color         = require('../../lib/renderer/Color.js');
var Avatar        = require('../components/Avatar.js');
var Text          = require('../components/Text.js');

/**
 * @constructor
 * @param {EntityManager} entities
 * @param {Canvas} screen
 */
function Renderer(screen, entities, maps)
{
  this.screen     = screen;
  this.entities   = entities;
  this.maps       = maps;
  global.renderer = this;
}

var COLOR_FILTER = [Position, Spatial, ColorSpirit];
var LEVEL_FILTER = [Position, LevelObject];

var TEXT_FILTER = [Position, Text];

// All avatars have to have a color spirit
var AVATAR_FILTER = [Position, Spatial, Avatar, ColorSpirit];

/**
 * @param {Number} dt
 * @param {Number} time
 */
Renderer.prototype.update = function(dt, time)
{
  this.screen.save();
  this.screen.fill('#202020');
  this.cameraTransform();
  this.drawBg();
  this.drawWalls();
  this.drawGems(dt, time);
  this.drawLevelObjects();
  this.drawAvatars();
  // this.drawTexts();
  this.screen.restore();
};

var borderStyle = new Style();
borderStyle.color = '#333';
var bV = new Vec2();
Renderer.prototype.drawBg = function()
{
  var player = this.entities.queryTag('player')[0];
  var pad = 30;
  bV.assign(this.maps.size);
  bV.x += pad*2;
  bV.y += pad*2;
  this.screen.save();
  this.screen.save();
  this.screen.translate(-pad, -pad);
  this.screen.drawRectangle(bV, borderStyle);
  this.screen.restore();
  this.screen.drawRectangle(this.maps.size, player.colorSpirit.style);
  this.screen.restore();
};

var ct = new Vec2();
Renderer.prototype.cameraTransform = function()
{
  var player = this.entities.queryTag('player')[0];

  // cacl zoom
  var zoom = this.zoom || 1;
  var per = player.newtonian.velocity.magnitude() / player.newtonian.maxSpeed;

  // do zoom
  var p = 0.992;
  var newZoom = 2 - 1 * per;
  zoom = zoom * p + (1-p) * newZoom;
  this.screen.scale(zoom, zoom);
  this.zoom = zoom;

  // Translate to account for player
  ct.assign(this.screen.getSize()).smult(0.5 * (1/zoom));
  this.screen.vtranslate(ct);
  ct.assign(player.position.location).smult(-1);
  this.screen.vtranslate(ct);

};

Renderer.prototype.drawTexts = function()
{
  var entities = this.entities.queryComponents(TEXT_FILTER);

  for (var n = 0; n < entities.length; n++) {
    this.drawText(entities[n]);
  }
};

Renderer.prototype.drawWalls = function()
{
  var entities = this.entities.queryTag('wall');
  var pColor = this.entities.queryTag('player')[0].colorSpirit.toColor();

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];
    var wColor = entity.colorSpirit.toColor();
    if (Color.equals(pColor, wColor))
      this.drawWall(entities[n]);
  }

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];
    var wColor = entity.colorSpirit.toColor();
    if (!Color.equals(pColor, wColor))
      this.drawWall(entities[n]);
  }
};

Renderer.prototype.drawWall = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawHwRect(entity.spatial.hwidth, entity.colorSpirit.style)
    .restore();
};

Renderer.prototype.drawGems = function(dt, time)
{
  var entities = this.entities.queryTag('gem');
  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];
    this.drawGem(entity, dt, time);
  }
};

Renderer.prototype.drawGem = function(entity, dt, time)
{
  var wiggle = Math.sin(5*time/1000) * 2 + 2;
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawCircle(entity.spatial.hwidth.x + wiggle, entity.colorSpirit.style)
    .restore();
};

Renderer.prototype.drawAvatars = function()
{
  var entities = this.entities.queryComponents(AVATAR_FILTER);

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];
    this.drawAvatar(entity);
  }
};

var vh = new Vec2();
var playerStyle = new Style();
playerStyle.color = '#fff';
var shipsize = 15;
//playerStyle.fillStyle = '#EEE';
Renderer.prototype.drawAvatar = function(entity)
{
  var h = Vec2.aquire();
  var pos = Vec2.aquire();

  h.assign(entity.spatial.hwidth);
  h.y *= 0.5;
  pos.set(entity.spatial.hwidth.x/2.2, 0);

  this.screen
    .save()
    .vtranslate(entity.position.location)
    .rotate(entity.position.rotation)
    //.drawHwRect(entity.spatial.hwidth, playerStyle)
    .drawShape(
      // [170, 80,
      // 130, 100, 130, 150, 230, 150,
      // 250, 180, 320, 180, 340, 150,
      // 420, 150, 420, 120, 390, 100,
      // 430, 40, 370, 30, 340, 50,
      // 320, 5, 250, 20, 250, 50,
      // 200, 5, 150, 20, 170, 80]
      [ {x:-shipsize, y:shipsize}, {x:shipsize,y:0}, {x:-shipsize,y:-shipsize}]
      , playerStyle)

    //.vtranslate(pos)
    //.drawHwRect(h, playerStyle)
    .restore();

  Vec2.release(h);
  Vec2.release(pos);
};

Renderer.prototype.drawLevelObjects = function()
{
  var entities = this.entities.queryComponents(LEVEL_FILTER);
  var screen = this.screen;

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];

    if (entity.levelObject.type === LevelObject.types.PLAYER_START)
      this.drawStart(entity);

    if (entity.levelObject.type === LevelObject.types.LEVEL_FINISH)
      this.drawStart(entity);
  }
};

var textStyle = new Style();
textStyle.color = '#fff';
Renderer.prototype.drawText = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawText(entity.text.value, textStyle)
    .restore();
}

var startSize = new Vec2(25, 25);
var startStyle = new Style()
startStyle.stroke = '#333';
startStyle.strokeWidth = 5;
Renderer.prototype.drawStart = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    //.drawHwRect(startSize, startStyle)
    .drawCircle(50, startStyle)
    .restore();
};

<|endoftext|>