<commit_before>'use strict';

if (!Error.captureStackTrace) throw new Error('Error.captureStackTrace does not exist!');

var util = require('./util');
var BE = require('./base_error');
var v = require('./validator').v;
var check = require('./validator').check;

var BaseError = BE.BaseError;

var Errors = {
    template: null,
};
exports = module.exports = Errors;

exports.setErrorStackSeparator = function(separator) {
    BE.ERROR_STACK_SEPARATOR = separator;
};
exports.setErrorStackSeparator('\n==== Pre-Error-Stack ====\n');

exports.setMessageConnector = function(connector) {
    BE.MESSAGE_CONNECTOR = connector;
};
exports.setMessageConnector(' && ');

/**
 * define a subclass of BaseError
 */
exports.defineError = function(definition, name) {
    if (!Errors.template) throw new Error('The error template should be defined firstly!');

    var E = function() {
        BaseError.apply(this, arguments);
    };
    util.inherits(E, BaseError);

    util.each(Errors.template, function(opts, key) {
        var value = definition[key];
        if (value !== undefined) {
            E.prototype[key] = value;
        } else {
            if (opts.required === true) {
                throw new Error('The key "' + key + '" is required, while definition = ' + JSON.stringify(definition));
            } else {
                value = opts.default;
            }
        }
    });

    E.prototype.name = name;

    Errors[name] = E;

    return E;
};

/**
 * To determine whether it is your custom error.
 *
 * if the error is an instance of the native Error, return `false`.
 *
 * @param  {*}  error
 * @return {Boolean}
 * @method isCustomError(err)
 */
exports.isCustomError = function(err) {
    return err instanceof BaseError;
};
// alias for isCustomError
exports.isError = Errors.isCustomError;

exports.setTemplate = function(template) {
    if (util.isObject(template) === false) {
        throw new Error('template should be an Object!');
    }

    var t = {};
    util.each(template, function(params, key) {
        if (util.isString(params)) {
            t[key] = {
                message: params,
                required: true,
            };
        } else if (util.isObject(params)) {
            t[key] = check(params, v.definition());
        } else {
            throw new Error('The value of template item should be an object or a string. Actual key=' + key + ' value=' + JSON.stringify(params));
        }
    });
    Errors.template = t;
};

/**
 * Assigns own enumerable properties of meta to the err.meta.
 *
 * If the err.meta is undefined before assigning, it will be assigned a new object,
 * and then the own enumerable properties of second parameter will be assigned to err.meta.
 * If the err.meta is not undefined, it should be a plain object.
 *
 * the properties of meta will overwrite the properties of err.meta, if they have same name.
 *
 * @side_effect  err, err.meta
 * @param  {Error}  err  the instance of Error class or Error subclass
 * @param  {Object} meta
 * @method addMeta
 */
exports.addMeta = function(err, meta) {
    if (!err.meta) err.meta = {};
    util.extend(err.meta, meta);
};

/**
 * initialize module
 *
 * @param  {Object} params
 * @param  {Object} params.template  a template for all error sub-classes
 * @param  {Array<Object>} params.definitions the definitions of error sub-classes
 * @param  {Boolean} [params.lazy=false]  if true, params.template and params.definitions could be optional.
 *                                        Otherwise, template and definitions are required.
 * @return {Null}
 * @method init(params)
 */
exports.init = function(params) {
    params = util.defaults({}, params, {
        lazy: false,
    });
    if (params.lazy) return undefined;

    Errors.setTemplate(params.template);
    util.each(params.definitions, Errors.defineError);
};
<commit_msg>update more specific code comments<commit_after>'use strict';

if (!Error.captureStackTrace) throw new Error('Error.captureStackTrace does not exist!');

var util = require('./util');
var BE = require('./base_error');
var v = require('./validator').v;
var check = require('./validator').check;

var BaseError = BE.BaseError;

var Errors = {
    template: null,
};
exports = module.exports = Errors;

/**
 * set the separator for multi error stacks.
 *
 * Default to "\n==== Pre-Error-Stack ====\n"
 *
 * @param  {String} separator
 * @method setErrorStackSeparator(separator)
 */
exports.setErrorStackSeparator = function(separator) {
    BE.ERROR_STACK_SEPARATOR = separator;
};
exports.setErrorStackSeparator('\n==== Pre-Error-Stack ====\n');

/**
 * set the connector for multi error messages. Default to " && "
 *
 * @param  {String} connector
 * @return {Undefined}
 * @method setMessageConnector(connector)
 */
exports.setMessageConnector = function(connector) {
    BE.MESSAGE_CONNECTOR = connector;
};
exports.setMessageConnector(' && ');

/**
 * define a subclass of BaseError
 *
 * @param  {Object} definition
 * @param  {String} name  the name of Error Class
 * @return {Function}  Error Class
 * @method defineError(definition, name)
 */
exports.defineError = function(definition, name) {
    if (!Errors.template) throw new Error('The error template should be defined firstly!');

    var E = function() {
        BaseError.apply(this, arguments);
    };
    util.inherits(E, BaseError);

    util.each(Errors.template, function(opts, key) {
        var value = definition[key];
        if (value !== undefined) {
            E.prototype[key] = value;
        } else {
            if (opts.required === true) {
                throw new Error('The key "' + key + '" is required, while definition = ' + JSON.stringify(definition));
            } else {
                value = opts.default;
            }
        }
    });

    E.prototype.name = name;

    Errors[name] = E;

    return E;
};

/**
 * To determine whether it is your custom error.
 *
 * if the error is an instance of the native Error, return `false`.
 *
 * @param  {*}  error
 * @return {Boolean}
 * @method isCustomError(err)
 */
exports.isCustomError = function(err) {
    return err instanceof BaseError;
};
/**
 * alias for isCustomError
 */
exports.isError = Errors.isCustomError;

/**
 * @param  {Object} template
 * @return {Undefined}
 * @method setTemplate(template)
 */
exports.setTemplate = function(template) {
    if (util.isObject(template) === false) {
        throw new Error('template should be an Object!');
    }

    var t = {};
    util.each(template, function(params, key) {
        if (util.isString(params)) {
            t[key] = {
                message: params,
                required: true,
            };
        } else if (util.isObject(params)) {
            t[key] = check(params, v.definition());
        } else {
            throw new Error('The value of template item should be an object or a string. Actual key=' + key + ' value=' + JSON.stringify(params));
        }
    });
    Errors.template = t;
};

/**
 * Assigns own enumerable properties of meta to the err.meta.
 *
 * If the err.meta is undefined before assigning, it will be assigned a new object,
 * and then the own enumerable properties of second parameter will be assigned to err.meta.
 * If the err.meta is not undefined, it should be a plain object.
 *
 * the properties of meta will overwrite the properties of err.meta, if they have same name.
 *
 * @side_effect  err, err.meta
 * @param  {Error}  err  the instance of Error class or Error subclass
 * @param  {Object} meta
 * @return {Undefined}
 * @method addMeta
 */
exports.addMeta = function(err, meta) {
    if (!err.meta) err.meta = {};
    util.extend(err.meta, meta);
};

/**
 * initialize module
 *
 * @param  {Object} params
 * @param  {Object} params.template  a template for all error sub-classes
 * @param  {Array<Object>} params.definitions the definitions of error sub-classes
 * @param  {Boolean} [params.lazy=false]  if true, params.template and params.definitions could be optional.
 *                                        Otherwise, template and definitions are required.
 * @return {Undefined}
 * @method init(params)
 */
exports.init = function(params) {
    params = util.defaults({}, params, {
        lazy: false,
    });
    if (params.lazy) return undefined;

    Errors.setTemplate(params.template);
    util.each(params.definitions, Errors.defineError);
};
<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React from 'react'
import {defineMessages, FormattedMessage, injectIntl} from 'react-intl'
import withStyles from 'isomorphic-style-loader/lib/withStyles'
import s from './Header.scss'
import {connect} from 'react-redux'
import Link from '../Link'
import Navigation from '../Navigation'
// import LanguageSwitcher from '../LanguageSwitcher'
import {FaAngleDown} from 'react-icons/lib/fa'
import UserInfo from '../UserInfo'

const messages = defineMessages({
  brand: {
    id: 'header.brand',
    defaultMessage: 'Rate Issues',
    description: 'Brand name displayed in header'
  }
})

const onUserClick = () => { console.log('testss') }

function Header ({displayName, picture}) {
  const renderUser = (onClick = null) => {
    if (picture) {
      return (

          <UserInfo picture={ picture }
            displayName={ displayName } >
          </UserInfo>
          <FaAngleDown color={ 'white' }
            onClick={ onClick }
            />

      )
    }
  }
  return (

          <Link
            className={ s.brand }
            to="/"
            >

              <FormattedMessage { ...messages.brand } />

          </Link>

            { /* <LanguageSwitcher />*/ }
            <Navigation className={ s.nav } />
            { renderUser(onUserClick) }

  )
}

export default connect(state => ({
  displayName: state.user.displayName,
  picture: state.user.picture
}))(withStyles(s)(injectIntl(withStyles(s)(Header))))
<commit_msg>format to lint<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React from 'react'
import {defineMessages, FormattedMessage, injectIntl} from 'react-intl'
import withStyles from 'isomorphic-style-loader/lib/withStyles'
import s from './Header.scss'
import {connect} from 'react-redux'
import Link from '../Link'
import Navigation from '../Navigation'
// import LanguageSwitcher from '../LanguageSwitcher'
import {FaAngleDown} from 'react-icons/lib/fa'
import UserInfo from '../UserInfo'

const messages = defineMessages({
  brand: {
    id: 'header.brand',
    defaultMessage: 'Rate Issues',
    description: 'Brand name displayed in header'
  }
})

const onUserClick = () => { console.log('testss') }

function Header ({displayName, picture}) {
  const renderUser = (onClick = null) => {
    if (picture) {
      return (

          <UserInfo picture={ picture }
            displayName={ displayName }
            >
          </UserInfo>
          <FaAngleDown color={ 'white' }
            onClick={ onClick }
            />

      )
    }
  }
  return (

          <Link
            className={ s.brand }
            to="/"
            >

              <FormattedMessage { ...messages.brand } />

          </Link>

            { /* <LanguageSwitcher />*/ }
            <Navigation className={ s.nav } />
            { renderUser(onUserClick) }

  )
}

export default connect(state => ({
  displayName: state.user.displayName,
  picture: state.user.picture
}))(withStyles(s)(injectIntl(withStyles(s)(Header))))
<|endoftext|>


<commit_before>app.controller('cartCtrl',function($scope, $http,$location,$rootScope) {
	console.log("cartCtrl");
	$scope.hello="hello";
	$scope.order =[{num:"1"},{num:"1"},{num:"1"},{num:"1"}];
	console.log("order~~~~~~~~~~~~~~",$scope.order);
	console.log("$rootScope.product",$rootScope.products);
if($rootScope.products==""){$rootScope.products = "no products"}
	var cart =[];
	$scope.addToCart=function(_id,color,sum){
				var data = $.param({
					item_id : _id,
					color : color,
					sum : sum
				});
				var config = {
					headers : {
						'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
					}
				}
				$http.post('/addToCart', data, config)
				.success(function (data, status, headers, config) {
					console.log("Succeed post addToCart");
					cart.push (data);
					console.log("addToCart ", data);
				})
				.error(function (data, status, header, config) {
					console.log("Error: "+ data);
					$scope.ResponseDetails = "addToCart " + data +
						"
status: " + status +
						"
headers: " + header +
						"
config: " + config;
				});
		};

});
<commit_msg>all list in the add to cart controller<commit_after>app.controller('cartCtrl',function($scope, $http,$location,$rootScope) {
	console.log("cartCtrl");
	$scope.hello=JSON.parse(localStorage.getItem('myList'));
	$scope.order =[{num:"1"},{num:"1"},{num:"1"},{num:"1"}];
	console.log("order~~~~~~~~~~~~~~",$scope.hello);
	console.log("$rootScope.product",$rootScope.products);
if($rootScope.products==""){$rootScope.products = "no products"}
	var cart =[];
	$scope.addToCart=function(_id,color,sum){
				var data = $.param({
					item_id : _id,
					color : color,
					sum : sum
				});
				var config = {
					headers : {
						'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
					}
				}
				$http.post('/addToCart', data, config)
				.success(function (data, status, headers, config) {
					console.log("Succeed post addToCart");
					cart.push (data);
					console.log("addToCart ", data);
				})
				.error(function (data, status, header, config) {
					console.log("Error: "+ data);
					$scope.ResponseDetails = "addToCart " + data +
						"
status: " + status +
						"
headers: " + header +
						"
config: " + config;
				});
		};

});
<|endoftext|>


<commit_before>/*
 * templateSpec.js
 *
 * Distributed under terms of the MIT license.
 */
/* global describe, it, expect */

var requirejs = require("requirejs");

requirejs.config({
    baseUrl: __dirname + "/../src/",
    nodeRequire: require
});

describe("Setup", function() {

    it("require", function() {
        expect(require).not.toBe(null);
        var css = requirejs("css_parser");
        expect(css).not.toBe(null);
        expect(requirejs("vue")).not.toBe(null);
    });

});

describe("Parser Templates", function() {
    var parser = requirejs("template_parser");

    it("Simple br", function() {
        var template = "<templete>" +
            "
</template>";

        var result = parser.extractTemplate(template);

        expect(result).toMatch("
");
    });

    it("Multiline", function() {
        var template = "<template>\n" +
            "  <input/>   Test\n" +
            "  </template>";
        var result = parser.extractTemplate(template);
        var expected =
            "'' + \n" +
            "' <input/> Test' + \n" +
            "' ' + ''";
        expect(result.length).toBe(expected.length);
        expect(true).toBe(result === expected);
    });

});
/* vim: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab : */
<commit_msg>:white_check_mark: Include more unit test to validate template parse with nested template tags<commit_after>/*
 * templateSpec.js
 *
 * Distributed under terms of the MIT license.
 */
/* global describe, it, expect */

var requirejs = require("requirejs");

requirejs.config({
    baseUrl: __dirname + "/../src/",
    nodeRequire: require
});

describe("Setup", function() {

    it("require", function() {
        expect(require).not.toBe(null);
        var css = requirejs("css_parser");
        expect(css).not.toBe(null);
        expect(requirejs("vue")).not.toBe(null);
    });

});

describe("Parser Templates", function() {
    var parser = requirejs("template_parser");

    it("Simple br", function() {
        var template = "<templete>" +
            "
</template>";

        var result = parser.extractTemplate(template);

        expect(result).toMatch("
");
    });

    it("Multiline", function() {
        var template = "<template>\n" +
            "  <input/>   Test\n" +
            "  </template>";
        var result = parser.extractTemplate(template);
        var expected =
            "'' + \n" +
            "' <input/> Test' + \n" +
            "' ' + ''";
        expect(result.length).toBe(expected.length);
        expect(true).toBe(result === expected);
    });

    it("Multi tamplate tags", function () {
        var template = "<template><template></template></template>" ;
        var result = parser.extractTemplate(template);
        var expected = "'<template></template>' + ''";

        expect(result).toEqual(expected);

    });

});
/* vim: set tabstop=4 softtabstop=4 shiftwidth=4 expandtab : */
<|endoftext|>


<commit_before>"use strict";

define(['jquery',
        'logManager'], function ( _jquery,
                                  logManager) {

    var WidgetBase;

    WidgetBase = function (options) {
        //this.logger --- logger instance for the Widget
        var loggerName = "WidgetBase",
            msg = "";

        if (options && options[WidgetBase.OPTIONS.LOGGER_INSTANCE_NAME]) {
            loggerName = options[WidgetBase.OPTIONS.LOGGER_INSTANCE_NAME];
        }

        this.logger = logManager.create(loggerName);

        //this.$el --- jQuery reference to the DOM container of Widget
        if (options && options[WidgetBase.OPTIONS.CONTAINER_ELEMENT]) {
            this.$el = $(options[WidgetBase.OPTIONS.CONTAINER_ELEMENT]);
            if (this.$el.length === 0) {
                msg = "Widget's container element can not be found";
                this.logger.error(msg);
                throw (msg);
            }
        } else {
            msg = "Widget's container element is not specified in constructor's 'options' parameter";
            this.logger.error(msg);
            throw (msg);
        }

        //by default Widget is in EDIT mode
        this._isReadOnly = false;
    };

    WidgetBase.OPTIONS = { "CONTAINER_ELEMENT" : "containerElement",
        "LOGGER_INSTANCE_NAME": "LOGGER_INSTANCE_NAME" };

    WidgetBase.READ_ONLY_CLASS = 'read-only';

    /************ SET READ-ONLY MODE *************/
    WidgetBase.prototype.setReadOnly = function (isReadOnly) {
        if (this._isReadOnly !== isReadOnly) {
            this._isReadOnly = isReadOnly;
            this.logger.debug("ReadOnly mode changed to '" + isReadOnly + "'");
            this.onReadOnlyChanged(this._isReadOnly);
        }
    };

    WidgetBase.prototype.getReadOnly = function () {
        return this._isReadOnly;
    };

    /* METHOD CALLED WHEN THE WIDGET'S READ-ONLY PROPERTY CHANGES */
    WidgetBase.prototype.onReadOnlyChanged = function (isReadOnly) {
        if (isReadOnly === true) {
            this.$el.addClass(READ_ONLY_CLASS);
        } else {
            this.$el.removeClass(READ_ONLY_CLASS);
        }
    };
    /***** END OF --- SET READ-ONLY MODE *********/

    /************** WIDGET-BASE INTERFACE *******************/

    /* METHOD CALLED WHEN THE WIDGET HAS TO CLEAR ITSELF */
    WidgetBase.prototype.clear = function () {
    };

    /* METHOD CALLED BEFORE IT WILL BE REMOVED FROM SCREEN */
    /* DO THE NECESSARY CLEANUP */
    WidgetBase.prototype.destroy = function () {
        this.clear();
    };

    /* METHOD CALLED WHEN THE PARENT CONTAINER SIZE HAS CHANGED AND WIDGET SHOULD RESIZE ITSELF ACCORDINGLY */
    WidgetBase.prototype.parentContainerSizeChanged = function (newWidth, newHeight) {
    };

    return WidgetBase;
});<commit_msg>rename getReadOnly to isReadOnly<commit_after>"use strict";

define(['jquery',
        'logManager'], function ( _jquery,
                                  logManager) {

    var WidgetBase;

    WidgetBase = function (options) {
        //this.logger --- logger instance for the Widget
        var loggerName = "WidgetBase",
            msg = "";

        if (options && options[WidgetBase.OPTIONS.LOGGER_INSTANCE_NAME]) {
            loggerName = options[WidgetBase.OPTIONS.LOGGER_INSTANCE_NAME];
        }

        this.logger = logManager.create(loggerName);

        //this.$el --- jQuery reference to the DOM container of Widget
        if (options && options[WidgetBase.OPTIONS.CONTAINER_ELEMENT]) {
            this.$el = $(options[WidgetBase.OPTIONS.CONTAINER_ELEMENT]);
            if (this.$el.length === 0) {
                msg = "Widget's container element can not be found";
                this.logger.error(msg);
                throw (msg);
            }
        } else {
            msg = "Widget's container element is not specified in constructor's 'options' parameter";
            this.logger.error(msg);
            throw (msg);
        }

        //by default Widget is in EDIT mode
        this._isReadOnly = false;
    };

    WidgetBase.OPTIONS = { "CONTAINER_ELEMENT" : "containerElement",
        "LOGGER_INSTANCE_NAME": "LOGGER_INSTANCE_NAME" };

    WidgetBase.READ_ONLY_CLASS = 'read-only';

    /************ SET READ-ONLY MODE *************/
    WidgetBase.prototype.setReadOnly = function (isReadOnly) {
        if (this._isReadOnly !== isReadOnly) {
            this._isReadOnly = isReadOnly;
            this.logger.debug("ReadOnly mode changed to '" + isReadOnly + "'");
            this.onReadOnlyChanged(this._isReadOnly);
        }
    };

    WidgetBase.prototype.isReadOnly = function () {
        return this._isReadOnly;
    };

    /* METHOD CALLED WHEN THE WIDGET'S READ-ONLY PROPERTY CHANGES */
    WidgetBase.prototype.onReadOnlyChanged = function (isReadOnly) {
        if (isReadOnly === true) {
            this.$el.addClass(READ_ONLY_CLASS);
        } else {
            this.$el.removeClass(READ_ONLY_CLASS);
        }
    };
    /***** END OF --- SET READ-ONLY MODE *********/

    /************** WIDGET-BASE INTERFACE *******************/

    /* METHOD CALLED WHEN THE WIDGET HAS TO CLEAR ITSELF */
    WidgetBase.prototype.clear = function () {
    };

    /* METHOD CALLED BEFORE IT WILL BE REMOVED FROM SCREEN */
    /* DO THE NECESSARY CLEANUP */
    WidgetBase.prototype.destroy = function () {
        this.clear();
    };

    /* METHOD CALLED WHEN THE PARENT CONTAINER SIZE HAS CHANGED AND WIDGET SHOULD RESIZE ITSELF ACCORDINGLY */
    WidgetBase.prototype.parentContainerSizeChanged = function (newWidth, newHeight) {
    };

    return WidgetBase;
});<|endoftext|>


<commit_before>// Require filesystem API (used to save data to file later on)
const fs = require('fs');
// ipc is used to open and communicate with the data viewer and other additional windows.
const ipc = require('electron').ipcRenderer;
const user = require('os').userInfo();
// Define some elements.
var pg = {
    team: document.getElementById('team'),
    match: document.getElementById('match'),
    submit: document.getElementById('submit'),
    reset: document.getElementById('reset'),
    view: document.getElementById('view'),
    position: document.getElementById('start-position'),
    red: document.getElementById('red'),
    blue: document.getElementById('blue'),
    color: document.getElementById('team-color')
};

var game = {
    parked: document.getElementById('parked'),
};

// Get date for file naming.
var d = new Date();
var home = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var desktopPath = home + (fs.existsSync(home + '/Desktop') ? '/Desktop' : '');
var path = desktopPath + '/scoutdata_' + user.username + '_' + ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'][d.getMonth()] + '_' + d.getDate() + '_' + d.getFullYear() + '.json';

localStorage.desktopPath = desktopPath;

// Generate an array of all data inputs in document.
// These will be used to generate an object.
// Inputs named .special are exempt. These can be used for things like path selection.
var tags = document.querySelectorAll('input:not(.special), select:not(.special), textarea');
// Create empty object.
var inputs = {};
// Make each element be the value to a key named after its ID.
for (tag of tags.values()) inputs[tag.id] = tag;
// Add the + and - buttons to a number specific input box
for (input in inputs) {
    if (inputs[input].type === 'number' && !inputs[input].classList.contains('large')) {
        var increase = document.createElement('button');
        increase.textContent = '+';
        increase.className = 'increase';
        var decrease = document.createElement('button');
        decrease.textContent = '-';
        decrease.className = 'decrease';
        inputs[input].insertAdjacentElement('beforebegin', decrease);
        inputs[input].insertAdjacentElement('afterend', increase);
    }
}

// Submit match data.
pg.submit.onclick = function() {
    if (
        // If the user has entered a team number and match number
        pg.team.value &&
        pg.match.value &&
        pg.color.value &&
        pg.position.value !== 'Position'
    ) {
        // Store current match, which will later be incremented by 1
        var currentMatch = parseInt(pg.match.value);
        // Make empty match object
        var match = {};
        // Go through each input in the data object and fill in the data from it
        for (input in inputs) {
            // Input the values from each input into the data object.
            // Need to get different data depending on the type of the input.
            switch (inputs[input].type) {
                case 'checkbox':
                    // Set this data point to a boolean of whether or not the checkbox is checked
                    match[input] = inputs[input].checked;
                    break;
                case 'number':
                    // Make this data point be the parsed integer value of that input
                    match[input] = parseInt(inputs[input].value);
                    break;
                default:
                    // Just use the raw string data
                    match[input] = inputs[input].value;
                    break;
            }
        }

        // Save the current match and position. The match will later be increased by one.
        write(match);
        resetInputs();
        pg.match.value = currentMatch + 1;
    } else {
        window.alert('You must enter a team number, color, position, and match!');
    }
};

function write(match) {
    var data = (fs.existsSync(path) && fs.statSync(path).size > 0) ? JSON.parse(fs.readFileSync(path)) : [];
    for (var i = 0; i < data.length; i++) {
        if (data[i].match === match.match && data[i].team === match.team) {
            if (confirm('Do you want to replace the previous data for this match?')) {
                data.splice(i--, 1);
            }
        }
    }
    data.push(match);
    // Write data to file.
    // Very occasionally, this will return JSON that uses WYSIWYG-style quotes (“”), rather
    // than JSON-standard, side-ambiguous, utf-8 quotes (""). This breaks JSON parsing later on.
    // Since it's as yet unclear why that issue occurs, just replace via regex for now.
    fs.writeFileSync(path, JSON.stringify(data).replace(/[“”]/, '"'));
}

// Reset all fields.
function resetInputs() {
    // For each input, reset to default value.
    for (input in inputs) {
        // Check if the element's class contains keep
        if (inputs[input].classList && inputs[input].classList.contains('keep')) continue;
        // Reset to different values depending on what type of input it is
        if (inputs[input].type === 'number' && !inputs[input].classList.contains('large')) inputs[input].value = 0; // If it's a small number box
        else if (inputs[input].type === 'checkbox') inputs[input].checked = false; // Checkbox
        else if (inputs[input].tagName === 'SELECT') inputs[input].value = 'None'; // Selector
        else inputs[input].value = '';
    }
    pg.team.focus();
    console.log('Reset inputs.');
}

pg.red.onclick = function() {
  if (this.style.background === '') {
    this.style.background = 'rgb(209, 39, 39)';
    pg.blue.style.background = '';
    pg.color.value = 'Red';
  } else {
    this.style.background = '';
    pg.color.value = '';
  }
}

pg.blue.onclick = function() {
  if (this.style.background === '') {
    this.style.background = '#1d7ac8';
    pg.red.style.background = '';
    pg.color.value = 'Blue';
  } else {
    this.style.background = '';
    pg.color.value = '';
  }
}

// When reset button is clicked, trigger reset
pg.reset.onclick = function() {
    if (window.confirm('Really reset inputs?')) resetInputs();
};

// When 'View Data' button is clicked
pg.view.onclick = function() {
    // Store the path to the data document
    localStorage.path = path;
    // Tell main.js to open rendered data window
    ipc.send('renderData');
};

// When user clicks on the screen, check if they clicked on an increase/decrease button
onclick = function(e) {
    // If click was on a decrease button, decrease the value of the adjacent input (but only if it's over 0)
    if (e.target.className === 'decrease' && e.target.nextElementSibling.value > 0) e.target.nextElementSibling.value = parseInt(e.target.nextElementSibling.value) - 1;
    // If click was on an increase button, increase the value of the adjacent input. If the button correlates to a rocket input, only increase if it is under the max
    // if (e.target.className === 'increase') e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1;
    if (e.target.className === 'increase') {
        if (e.target.previousElementSibling.hasAttribute('max')) {
            if (e.target.previousElementSibling.value < e.target.previousElementSibling.attributes.max.value) e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1;
        }
        else e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1;
    }
};
<commit_msg>stop data from submitting without position<commit_after>// Require filesystem API (used to save data to file later on)
const fs = require('fs');
// ipc is used to open and communicate with the data viewer and other additional windows.
const ipc = require('electron').ipcRenderer;
const user = require('os').userInfo();
// Define some elements.
var pg = {
    team: document.getElementById('team'),
    match: document.getElementById('match'),
    submit: document.getElementById('submit'),
    reset: document.getElementById('reset'),
    view: document.getElementById('view'),
    position: document.getElementById('start-position'),
    red: document.getElementById('red'),
    blue: document.getElementById('blue'),
    color: document.getElementById('team-color')
};

var game = {
    parked: document.getElementById('parked'),
};

// Get date for file naming.
var d = new Date();
var home = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
var desktopPath = home + (fs.existsSync(home + '/Desktop') ? '/Desktop' : '');
var path = desktopPath + '/scoutdata_' + user.username + '_' + ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'][d.getMonth()] + '_' + d.getDate() + '_' + d.getFullYear() + '.json';

localStorage.desktopPath = desktopPath;

// Generate an array of all data inputs in document.
// These will be used to generate an object.
// Inputs named .special are exempt. These can be used for things like path selection.
var tags = document.querySelectorAll('input:not(.special), select:not(.special), textarea');
// Create empty object.
var inputs = {};
// Make each element be the value to a key named after its ID.
for (tag of tags.values()) inputs[tag.id] = tag;
// Add the + and - buttons to a number specific input box
for (input in inputs) {
    if (inputs[input].type === 'number' && !inputs[input].classList.contains('large')) {
        var increase = document.createElement('button');
        increase.textContent = '+';
        increase.className = 'increase';
        var decrease = document.createElement('button');
        decrease.textContent = '-';
        decrease.className = 'decrease';
        inputs[input].insertAdjacentElement('beforebegin', decrease);
        inputs[input].insertAdjacentElement('afterend', increase);
    }
}

// Submit match data.
pg.submit.onclick = function() {
    if (
        // If the user has entered a team number and match number
        pg.team.value &&
        pg.match.value &&
        pg.color.value &&
        pg.position.value !== ''
    ) {
        // Store current match, which will later be incremented by 1
        var currentMatch = parseInt(pg.match.value);
        // Make empty match object
        var match = {};
        // Go through each input in the data object and fill in the data from it
        for (input in inputs) {
            // Input the values from each input into the data object.
            // Need to get different data depending on the type of the input.
            switch (inputs[input].type) {
                case 'checkbox':
                    // Set this data point to a boolean of whether or not the checkbox is checked
                    match[input] = inputs[input].checked;
                    break;
                case 'number':
                    // Make this data point be the parsed integer value of that input
                    match[input] = parseInt(inputs[input].value);
                    break;
                default:
                    // Just use the raw string data
                    match[input] = inputs[input].value;
                    break;
            }
        }

        // Save the current match and position. The match will later be increased by one.
        write(match);
        resetInputs();
        pg.match.value = currentMatch + 1;
    } else {
        window.alert('You must enter a team number, color, position, and match!');
    }
};

function write(match) {
    var data = (fs.existsSync(path) && fs.statSync(path).size > 0) ? JSON.parse(fs.readFileSync(path)) : [];
    for (var i = 0; i < data.length; i++) {
        if (data[i].match === match.match && data[i].team === match.team) {
            if (confirm('Do you want to replace the previous data for this match?')) {
                data.splice(i--, 1);
            }
        }
    }
    data.push(match);
    // Write data to file.
    // Very occasionally, this will return JSON that uses WYSIWYG-style quotes (“”), rather
    // than JSON-standard, side-ambiguous, utf-8 quotes (""). This breaks JSON parsing later on.
    // Since it's as yet unclear why that issue occurs, just replace via regex for now.
    fs.writeFileSync(path, JSON.stringify(data).replace(/[“”]/, '"'));
}

// Reset all fields.
function resetInputs() {
    // For each input, reset to default value.
    for (input in inputs) {
        // Check if the element's class contains keep
        if (inputs[input].classList && inputs[input].classList.contains('keep')) continue;
        // Reset to different values depending on what type of input it is
        if (inputs[input].type === 'number' && !inputs[input].classList.contains('large')) inputs[input].value = 0; // If it's a small number box
        else if (inputs[input].type === 'checkbox') inputs[input].checked = false; // Checkbox
        else if (inputs[input].tagName === 'SELECT') inputs[input].value = 'None'; // Selector
        else inputs[input].value = '';
    }
    pg.team.focus();
    console.log('Reset inputs.');
}

pg.red.onclick = function() {
  if (this.style.background === '') {
    this.style.background = 'rgb(209, 39, 39)';
    pg.blue.style.background = '';
    pg.color.value = 'Red';
  } else {
    this.style.background = '';
    pg.color.value = '';
  }
}

pg.blue.onclick = function() {
  if (this.style.background === '') {
    this.style.background = '#1d7ac8';
    pg.red.style.background = '';
    pg.color.value = 'Blue';
  } else {
    this.style.background = '';
    pg.color.value = '';
  }
}

// When reset button is clicked, trigger reset
pg.reset.onclick = function() {
    if (window.confirm('Really reset inputs?')) resetInputs();
};

// When 'View Data' button is clicked
pg.view.onclick = function() {
    // Store the path to the data document
    localStorage.path = path;
    // Tell main.js to open rendered data window
    ipc.send('renderData');
};

// When user clicks on the screen, check if they clicked on an increase/decrease button
onclick = function(e) {
    // If click was on a decrease button, decrease the value of the adjacent input (but only if it's over 0)
    if (e.target.className === 'decrease' && e.target.nextElementSibling.value > 0) e.target.nextElementSibling.value = parseInt(e.target.nextElementSibling.value) - 1;
    // If click was on an increase button, increase the value of the adjacent input. If the button correlates to a rocket input, only increase if it is under the max
    // if (e.target.className === 'increase') e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1;
    if (e.target.className === 'increase') {
        if (e.target.previousElementSibling.hasAttribute('max')) {
            if (e.target.previousElementSibling.value < e.target.previousElementSibling.attributes.max.value) e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1;
        }
        else e.target.previousElementSibling.value = parseInt(e.target.previousElementSibling.value) + 1;
    }
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    jsdoc = require('gulp-jsdoc'),
    docsSrcDir = './assets/js/**/*.js',
    docsDestDir = './docs/js',
    jsDocTask;

jsDocTask = function() {
  return gulp.src(docsSrcDir)
    .pipe(
      jsdoc(docsDestDir,
        {
          path: './node_modules/jaguarjs-jsdoc',
          applicationName: 'Dough JavaScript',
          cleverLinks: true,
          copyright: 'Copyright Money Advice Service ©',
          linenums: true,
          collapseSymbols: false
        },
        {
          plugins: ['plugins/markdown'],
        }
      )
    );
};

gulp.task('jsdoc', jsDocTask);

gulp.task('watch', function() {
  jsDocTask();
  gulp.watch(docsSrcDir, ['jsdoc']);
});
<commit_msg>Make jsdoc the default task<commit_after>var gulp = require('gulp'),
    jsdoc = require('gulp-jsdoc'),
    docsSrcDir = './assets/js/**/*.js',
    docsDestDir = './docs/js',
    jsDocTask;

jsDocTask = function() {
  return gulp.src(docsSrcDir)
    .pipe(
      jsdoc(docsDestDir,
        {
          path: './node_modules/jaguarjs-jsdoc',
          applicationName: 'Dough JavaScript',
          cleverLinks: true,
          copyright: 'Copyright Money Advice Service ©',
          linenums: true,
          collapseSymbols: false
        },
        {
          plugins: ['plugins/markdown'],
        }
      )
    );
};

gulp.task('default', ['jsdoc']);
gulp.task('jsdoc', jsDocTask);
gulp.task('watch', function() {
  jsDocTask();
  gulp.watch(docsSrcDir, ['jsdoc']);
});
<|endoftext|>


<commit_before>"use strict";

define(["common/js/InputValidator", "artifact/js/CardType", "model/js/Action", "controller/js/HumanAgentStrategy"],
   function(InputValidator, CardType, Action, HumanAgentStrategy)
   {
      function TravelTask(store)
      {
         InputValidator.validateNotNull("store", store);

         this.store = function()
         {
            return store;
         };
      }

      TravelTask.prototype.doIt = function(callback)
      {
         InputValidator.validateNotNull("callback", callback);

         var store = this.store();

         if (store.getState().activeLocationId === undefined)
         {
            // Pick a location from the staging area.
            var environment = store.getState().environment;
            var locations = environment.stagingArea(CardType.LOCATION).toJS();

            // Ask the first HumanAgent, if any, or the first agent.
            var agents = environment.agentQueue();
            var agent;

            for (var i = 0; i < agents.length; i++)
            {
               var myAgent = agents[i];

               // FIXME: don't rely on controller.
               if (myAgent._strategy() === HumanAgentStrategy)
               {
                  agent = myAgent;
                  break;
               }
            }

            if (agent === undefined && agents.length > 0)
            {
               agent = agents[0];
            }

            var queueCallback = this.finish.bind(this);
            var locationCallback = function(location)
            {
               queueCallback(location, callback);
            };

            agent.chooseLocation(locations, locationCallback);
         }
         else
         {
            callback();
         }
      };

      TravelTask.prototype.finish = function(location, callback)
      {
         var store = this.store();
         store.dispatch(Action.setActiveLocation(location));
         store.dispatch(Action.setUserMessage("Travel to " + location.card().name));

         callback();
      };

      return TravelTask;
   });
<commit_msg>Fixed a bug where no available locations caused an exception.<commit_after>"use strict";

define(["common/js/InputValidator", "artifact/js/CardType", "model/js/Action", "controller/js/HumanAgentStrategy"],
   function(InputValidator, CardType, Action, HumanAgentStrategy)
   {
      function TravelTask(store)
      {
         InputValidator.validateNotNull("store", store);

         this.store = function()
         {
            return store;
         };
      }

      TravelTask.prototype.doIt = function(callback)
      {
         InputValidator.validateNotNull("callback", callback);

         var store = this.store();

         if (store.getState().activeLocationId === undefined)
         {
            // Pick a location from the staging area.
            var environment = store.getState().environment;
            var locations = environment.stagingArea(CardType.LOCATION).toJS();

            if (locations.length > 0)
            {
               // Ask the first HumanAgent, if any, or the first agent.
               var agents = environment.agentQueue();
               var agent;

               for (var i = 0; i < agents.length; i++)
               {
                  var myAgent = agents[i];

                  // FIXME: don't rely on controller.
                  if (myAgent._strategy() === HumanAgentStrategy)
                  {
                     agent = myAgent;
                     break;
                  }
               }

               if (agent === undefined && agents.length > 0)
               {
                  agent = agents[0];
               }

               var queueCallback = this.finish.bind(this);
               var locationCallback = function(location)
               {
                  queueCallback(location, callback);
               };

               agent.chooseLocation(locations, locationCallback);
            }
            else
            {
               callback();
            }
         }
         else
         {
            callback();
         }
      };

      TravelTask.prototype.finish = function(location, callback)
      {
         var store = this.store();
         store.dispatch(Action.setActiveLocation(location));
         store.dispatch(Action.setUserMessage("Travel to " + location.card().name));

         callback();
      };

      return TravelTask;
   });
<|endoftext|>


<commit_before> getStatsFeed = function(name) {
	$('#stats').html('
Stats
');
	$('#errors').text('');
	var query = 'query.php?name=' + name + '&type=statsfeed';
	var jqxhr = $.getJSON(query, function(data) {
		$.each(data, function(key, val) {
			$('#stats').append('
'+key+': '+val+'
');
		});
		calcPerkLevels(data);
	}).error(function(jqXHR, textStatus, errorThrown) {
		console.log("hi");
		$('#errors').text(jqXHR.responseText);
//		console.log("error " + textStatus);
//		console.log("incoming Text " + jqXHR.responseText);
	});

	return false;
}

getAchievements = function(name) {
        $('#achievments').html('
Stats
');
        $('#errors').text('');
        var query = 'query.php?name=' + name + '&type=achievements';
        var jqxhr = $.getJSON(query, function(data) {
                $.each(data, function(key, val) {
                        $('#achievements').append('
'+key+': '+val+'
');
                });
                calcPerkLevels(data);
        }).error(function(jqXHR, textStatus, errorThrown) {
                console.log("hi");
                $('#errors').text(jqXHR.responseText);
//              console.log("error " + textStatus);
//              console.log("incoming Text " + jqXHR.responseText);
        });

        return false;
}
<commit_msg>fixed issue in getAchievements<commit_after> getStatsFeed = function(name) {
	$('#stats').html('
Stats
');
	$('#errors').text('');
	var query = 'query.php?name=' + name + '&type=statsfeed';
	var jqxhr = $.getJSON(query, function(data) {
		$.each(data, function(key, val) {
			$('#stats').append('
'+key+': '+val+'
');
		});
		calcPerkLevels(data);
	}).error(function(jqXHR, textStatus, errorThrown) {
		console.log("hi");
		$('#errors').text(jqXHR.responseText);
//		console.log("error " + textStatus);
//		console.log("incoming Text " + jqXHR.responseText);
	});

	return false;
}

getAchievements = function(name) {
        $('#achievments').html('
Stats
');
        $('#errors').text('');
        var query = 'query.php?name=' + name + '&type=achievements';
        var jqxhr = $.getJSON(query, function(data) {
                $.each(data, function(key, val) {
                        $('#achievements').append('
'+key+': '+val+'
');
                });
        }).error(function(jqXHR, textStatus, errorThrown) {
                console.log("hi");
                $('#errors').text(jqXHR.responseText);
//              console.log("error " + textStatus);
//              console.log("incoming Text " + jqXHR.responseText);
        });

        return false;
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible <commit_msg>Who you calling a fool?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible d<|endoftext|>


<commit_before>var EXFAT = module.exports
<commit_msg>Update lib/exfat: Add constants & ExFAT.test()<commit_after>var FSError = require( './error' )
var ExFAT = module.exports

ExFAT.FIRST_DATA_CLUSTER = 2
ExFAT.LAST_DATA_CLUSTER = 0xFFFFFFF6

ExFAT.CLUSTER_FREE = 0x00000000 // free cluster
ExFAT.CLUSTER_BAD  = 0xFFFFFFF7 // cluster contains bad sector
ExFAT.CLUSTER_END  = 0xFFFFFFFF // final cluster of file or directory

ExFAT.STATE_MOUNTED = 2

ExFAT.ENAME_MAX = 15

ExFAT.ATTR_RO     = 0x01
ExFAT.ATTR_HIDDEN = 0x02
ExFAT.ATTR_SYSTEM = 0x04
ExFAT.ATTR_VOLUME = 0x08
ExFAT.ATTR_DIR    = 0x10
ExFAT.ATTR_ARCH   = 0x20

ExFAT.FLAG_ALWAYS     = ( 1 << 0 )
ExFAT.FLAG_CONTIGUOUS = ( 1 << 1 )

ExFAT.Entry = require( './entry' )
ExFAT.Node = require( './node' )
ExFAT.Volume = require( './volume' )

/**
 * Determine whether a boot sector
 * indicates an ExFAT formatted volume
 * @param  {Buffer} block
 * @return {Boolean}
 */
ExFAT.test = function( block ) {

  var vbr = new ExFAT.Volume.BootRecord

  try {
    vbr.parse( block )
  } catch( err ) {
    return new FSError(
      FSError.EIO,
      'Failed to parse boot sector'
    )
  }

  if( vbr.oemName !== 'EXFAT   ' )
    return new FSError(
      FSError.EIO,
      'No exFAT file system found'
    )

  if( vbr.sectorBits < 9 )
    return new FSError(
      FSError.EIO,
      'Sector size too small: 2^' + vbr.sectorBits + ' bits'
    )

  if( vbr.sectorBits + vbr.spcBits > 25 )
    return new FSError(
      FSError.EIO,
      'Cluster size too big: 2^' + ( vbr.sectorBits + vbr.spcBits ) + ' bits'
    )

  if( vbr.version.major !== 1 || vbr.version.minor !== 0 )
    return new FSError(
      FSError.EIO,
      'Unsupported exFAT version: ' + vbr.version.major + '.' + vbr.version.minor
    )

  if( vbr.fatCount !== 1 )
    return new FSError(
      FSError.EIO,
      'Unsupported FAT count: ' + vbr.fatCount
    )

  // TODO: in volume.mount()
  // - Verify checksum
  // - FS larger than underlying device (?)
  // - Upcase table not found
  // - Cluster bitmap not found

}
<|endoftext|>


<commit_before>import React from 'react'
import { IndexLink, Link } from 'react-router'
import classes from './Header.scss'

export const Header = () => (

React Redux Master of the Universe

    <IndexLink to='/' activeClassName={classes.activeRoute}>
      Home
    </IndexLink>
    {' · '}
    <Link to='/counter' activeClassName={classes.activeRoute}>
      Counter
    </Link>

)

export default Header
<commit_msg>first commit in first testbranch<commit_after>import React from 'react'
import { IndexLink, Link } from 'react-router'
import classes from './Header.scss'

export const Header = () => (

React Redux Master of the Universe in the first testbranch

    <IndexLink to='/' activeClassName={classes.activeRoute}>
      Home
    </IndexLink>
    {' · '}
    <Link to='/counter' activeClassName={classes.activeRoute}>
      Counter
    </Link>

)

export default Header
<|endoftext|>


<commit_before>/**
 * Handlebars Helpers Tests: Math Helpers
 * http://github.com/assemble/handlebars-helpers
 * Copyright (c) 2013 Jon Schlinkert, Brian Woodward, contributors
 * Licensed under the MIT License (MIT).
 */

// node_modules
require('should');
var Handlebars = require('handlebars');

// Local helpers
require('../../lib/helpers/helpers-math').register(Handlebars, {});

var context = {
  value: 5
};

describe('add', function() {
  describe('{{add value 5}}', function() {
    it('should return the sum of two numbers.', function() {
      var source = '{{add value 5}}';
      var template = Handlebars.compile(source);
      template(context).should.equal('10');
    });
  });
});

describe('subtract', function() {
  describe('{{subtract value 5}}', function() {
    it('should return the difference of two numbers.', function() {
      var source = '{{subtract value 5}}';
      var template = Handlebars.compile(source);
      template(context).should.equal('0');
    });
  });
});

describe('divide', function() {
  describe('{{divide value 5}}', function() {
    it('should return the division of two numbers.', function() {
      var source = '{{divide value 5}}';
      var template = Handlebars.compile(source);
      template(context).should.equal('1');
    });
  });
});

describe('multiply', function() {
  describe('{{multiply value 5}}', function() {
    it('should return the multiplication of two numbers.', function() {
      var source = '{{multiply value 5}}';
      var template = Handlebars.compile(source);
      template(context).should.equal('25');
    });
  });
});

describe('floor', function() {
  describe('{{floor 5}}', function() {
    it('should return the value rounded down to the nearest integer.', function() {
      var source = '{{floor value}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: 5.6
      }).should.equal('5');
    });
  });
});

describe('ceil', function() {
  describe('{{ceil 5}}', function() {
    it('should return the value rounded up to the nearest integer.', function() {
      var source = '{{ceil value}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: 5.6
      }).should.equal('6');
    });
  });
});

describe('round', function() {
  describe('{{round 5}}', function() {
    it('should return the value rounded to the nearest integer.', function() {
      var source = '{{round value}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: 5.69
      }).should.equal('6');
    });
  });
});

describe('sum', function() {
  describe('{{sum value 67 80}}', function() {
    it('should return the sum of multiple numbers.', function() {
      var source = '{{sum value 67 80}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: 20
      }).should.equal('167');
    });
  });
});

describe('sum', function() {
  describe('{{sum 1 2 3}}', function() {
    it('should return the sum of multiple numbers.', function() {
      var source = '{{sum 1 2 3}}';
      var template = Handlebars.compile(source);
      template().should.equal('6');
    });
  });
});

describe('sum', function() {
  describe('{{sum value}}', function() {
    it('should return the total sum of array.', function() {
      var source = '{{sum value}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: [1, 2, 3]
      }).should.equal('6');
    });
  });
});

describe('sum', function() {
  describe('{{sum value 5}}', function() {
    it('should return the total sum of array and numbers.', function() {
      var source = '{{sum value 5}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: [1, 2, 3]
      }).should.equal('11');
    });
  });
});
<commit_msg>Add test for maths with string<commit_after>/**
 * Handlebars Helpers Tests: Math Helpers
 * http://github.com/assemble/handlebars-helpers
 * Copyright (c) 2013 Jon Schlinkert, Brian Woodward, contributors
 * Licensed under the MIT License (MIT).
 */

// node_modules
require('should');
var Handlebars = require('handlebars');

// Local helpers
require('../../lib/helpers/helpers-math').register(Handlebars, {});

var context = {
  value: 5
};

describe('add', function() {
  describe('{{add value 5}}', function() {
    it('should return the sum of two numbers.', function() {
      var source = '{{add value 5}}';
      var template = Handlebars.compile(source);
      template(context).should.equal('10');
    });
  });
});

describe('subtract', function() {
  describe('{{subtract value 5}}', function() {
    it('should return the difference of two numbers.', function() {
      var source = '{{subtract value 5}}';
      var template = Handlebars.compile(source);
      template(context).should.equal('0');
    });
  });
});

describe('divide', function() {
  describe('{{divide value 5}}', function() {
    it('should return the division of two numbers.', function() {
      var source = '{{divide value 5}}';
      var template = Handlebars.compile(source);
      template(context).should.equal('1');
    });
  });
});

describe('multiply', function() {
  describe('{{multiply value 5}}', function() {
    it('should return the multiplication of two numbers.', function() {
      var source = '{{multiply value 5}}';
      var template = Handlebars.compile(source);
      template(context).should.equal('25');
    });
  });
});

describe('floor', function() {
  describe('{{floor 5}}', function() {
    it('should return the value rounded down to the nearest integer.', function() {
      var source = '{{floor value}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: 5.6
      }).should.equal('5');
    });
  });
});

describe('ceil', function() {
  describe('{{ceil 5}}', function() {
    it('should return the value rounded up to the nearest integer.', function() {
      var source = '{{ceil value}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: 5.6
      }).should.equal('6');
    });
  });
});

describe('round', function() {
  describe('{{round 5}}', function() {
    it('should return the value rounded to the nearest integer.', function() {
      var source = '{{round value}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: 5.69
      }).should.equal('6');
    });
  });
});

describe('sum', function() {
  describe('{{sum value 67 80}}', function() {
    it('should return the sum of multiple numbers.', function() {
      var source = '{{sum value 67 80}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: 20
      }).should.equal('167');
    });
  });
});

describe('sum', function() {
  describe('{{sum "value" 10}}', function() {
    it('should return the sum of multiple numbers.', function() {
      var source = '{{sum value 10}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: "20"
      }).should.equal('30');
    });
  });
});

describe('sum', function() {
  describe('{{sum 1 2 3}}', function() {
    it('should return the sum of multiple numbers.', function() {
      var source = '{{sum 1 2 3}}';
      var template = Handlebars.compile(source);
      template().should.equal('6');
    });
  });
});

describe('sum', function() {
  describe('{{sum value}}', function() {
    it('should return the total sum of array.', function() {
      var source = '{{sum value}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: [1, 2, 3]
      }).should.equal('6');
    });
  });
});

describe('sum', function() {
  describe('{{sum value 5}}', function() {
    it('should return the total sum of array and numbers.', function() {
      var source = '{{sum value 5}}';
      var template = Handlebars.compile(source);
      template(context = {
        value: [1, 2, 3]
      }).should.equal('11');
    });
  });
});
<|endoftext|>


<commit_before>export const closeMicrocart =  {
  methods: {
    closeMicrocart () {
      this.$store.dispatch('ui/Microcart')
    }
  }
}<commit_msg>linting fixes<commit_after>export const closeMicrocart = {
  methods: {
    closeMicrocart () {
      this.$store.dispatch('ui/Microcart')
    }
  }
}
<|endoftext|>


<commit_before>const path = require('path')
const gulp = require('gulp')
const newer = require('gulp-newer')
const babel = require('gulp-babel')
const watch = require('gulp-watch')
const gutil = require('gulp-util')
const filter = require('gulp-filter')
const plumber = require('gulp-plumber')
const through = require('through2')
const chalk = require('chalk')
const childProcess = require('child_process')

const scripts = ['./packages/@sanity/*/src/**/*.js', './packages/sanity-plugin-*/src/**/*.js']
const assets = ['./packages/@sanity/*/src/**/*', './packages/sanity-plugin-*/src/**/*']
const srcOpts = {base: 'packages'}

let srcEx
let srcRootEx
let libFragment

if (path.win32 === path) {
  srcEx = /(@sanity\\[^\\]+)\\src\\/
  srcRootEx = /(sanity-plugin-[^\\]+)\\src\\/
  libFragment = '$1\\lib\\'
} else {
  srcEx = new RegExp('(@sanity/[^/]+)/src/')
  srcRootEx = /(sanity-plugin-[^/]+)\/src\//
  libFragment = '$1/lib/'
}

const mapToDest = orgPath => {
  const outPath = orgPath
    .replace(srcEx, libFragment)
    .replace(srcRootEx, libFragment)

  return outPath
}

const dest = 'packages'

gulp.task('default', ['build'])

gulp.task('build', () => {
  const assetFilter = filter(['**/*.js'], {restore: true})

  return gulp.src(assets, srcOpts)
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(newer({map: mapToDest}))
    .pipe(assetFilter)
    .pipe(through.obj((file, enc, callback) => {
      gutil.log('Compiling', `'${chalk.cyan(file.path)}'...`)
      callback(null, file)
    }))
    .pipe(babel())
    .pipe(assetFilter.restore)
    .pipe(through.obj((file, enc, callback) => {
      file._path = file.path
      file.path = mapToDest(file.path)
      callback(null, file)
    }))
    .pipe(gulp.dest(dest))
})

gulp.task('watch-js', () => {
  return gulp.src(scripts, srcOpts)
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(through.obj((file, enc, callback) => {
      file._path = file.path
      file.path = mapToDest(file.path)
      callback(null, file)
    }))
    .pipe(newer(dest))
    .pipe(through.obj((file, enc, callback) => {
      gutil.log('Compiling', `'${chalk.cyan(file._path)}'...`)
      callback(null, file)
    }))
    .pipe(babel())
    .pipe(gulp.dest(dest))
})

gulp.task('watch-assets', () => {
  return gulp.src(assets, srcOpts)
    .pipe(filter(['**/*.*', '!**/*.js']))
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(through.obj((file, enc, callback) => {
      file._path = file.path
      file.path = mapToDest(file.path)
      callback(null, file)
    }))
    .pipe(newer(dest))
    .pipe(through.obj((file, enc, callback) => {
      gutil.log('Copying', `'${chalk.cyan(file._path)}'...`)
      callback(null, file)
    }))
    .pipe(gulp.dest(dest))
})

gulp.task('watch', ['watch-js', 'watch-assets'], callback => {
  watch(scripts, {debounceDelay: 200}, () => {
    gulp.start('watch-js')
  })

  watch(assets, {debounceDelay: 200}, () => {
    gulp.start('watch-assets')
  })
})

gulp.task('dev', ['watch-js', 'watch-assets'], cb => {
  watch(scripts, {debounceDelay: 200}, () => {
    gulp.start('watch-js')
  })

  watch(assets, {debounceDelay: 200}, () => {
    gulp.start('watch-assets')
  })

  const projectPath = path.join(__dirname, 'packages', 'test-studio')
  const npmPath = path.join(projectPath, 'node_modules', '.bin')
  const proc = childProcess.spawn('sanity', ['start', '--host', '0.0.0.0'], {
    cwd: projectPath,
    env: Object.assign({}, process.env, {
      PATH: [npmPath].concat(process.env.PATH.split(path.delimiter)).join(path.delimiter)
    })
  })

  proc.stdout.pipe(process.stdout)
  proc.stderr.pipe(process.stderr)
})
gulp.task('example', ['watch-js', 'watch-assets'], cb => {
  watch(scripts, {debounceDelay: 200}, () => {
    gulp.start('watch-js')
  })

  watch(assets, {debounceDelay: 200}, () => {
    gulp.start('watch-assets')
  })

  const projectPath = path.join(__dirname, 'packages', 'example-studio')
  const npmPath = path.join(projectPath, 'node_modules', '.bin')
  const proc = childProcess.spawn('sanity', ['start', '--host', '0.0.0.0'], {
    cwd: projectPath,
    env: Object.assign({}, process.env, {
      PATH: [npmPath].concat(process.env.PATH.split(path.delimiter)).join(path.delimiter)
    })
  })

  proc.stdout.pipe(process.stdout)
  proc.stderr.pipe(process.stderr)
})

gulp.task('storybook', ['watch-js', 'watch-assets'], () => {
  watch(scripts, {debounceDelay: 200}, () => {
    gulp.start('watch-js')
  })

  watch(assets, {debounceDelay: 200}, () => {
    gulp.start('watch-assets')
  })

  const projectPath = path.join(__dirname, 'packages', 'storybook')
  const npmPath = path.join(projectPath, 'node_modules', '.bin')
  const proc = childProcess.spawn('npm', ['start'], {
    cwd: projectPath,
    env: Object.assign({}, process.env, {
      PATH: [npmPath].concat(process.env.PATH.split(path.delimiter)).join(path.delimiter)
    })
  })

  proc.stdout.pipe(process.stdout)
  proc.stderr.pipe(process.stderr)
})
<commit_msg>[infrastructure] Fix spawning gulptasks on windows (#143)<commit_after>const path = require('path')
const gulp = require('gulp')
const newer = require('gulp-newer')
const babel = require('gulp-babel')
const watch = require('gulp-watch')
const gutil = require('gulp-util')
const filter = require('gulp-filter')
const plumber = require('gulp-plumber')
const through = require('through2')
const chalk = require('chalk')
const childProcess = require('child_process')

const isWindows = /^win/.test(process.platform)
const scripts = ['./packages/@sanity/*/src/**/*.js', './packages/sanity-plugin-*/src/**/*.js']
const assets = ['./packages/@sanity/*/src/**/*', './packages/sanity-plugin-*/src/**/*']
const srcOpts = {base: 'packages'}

const getProjectEnv = projectPath => {
  const npmPath = path.join(projectPath, 'node_modules', '.bin')
  /* eslint-disable no-process-env */
  const paths = [npmPath].concat(process.env.PATH.split(path.delimiter)).filter(Boolean)
  return Object.assign({}, process.env, {
    PATH: paths.join(path.delimiter)
  })
  /* eslint-enable no-process-env */
}

let srcEx
let srcRootEx
let libFragment

if (path.win32 === path) {
  srcEx = /(@sanity\\[^\\]+)\\src\\/
  srcRootEx = /(sanity-plugin-[^\\]+)\\src\\/
  libFragment = '$1\\lib\\'
} else {
  srcEx = new RegExp('(@sanity/[^/]+)/src/')
  srcRootEx = /(sanity-plugin-[^/]+)\/src\//
  libFragment = '$1/lib/'
}

const mapToDest = orgPath => {
  const outPath = orgPath
    .replace(srcEx, libFragment)
    .replace(srcRootEx, libFragment)

  return outPath
}

const dest = 'packages'

gulp.task('default', ['build'])

gulp.task('build', () => {
  const assetFilter = filter(['**/*.js'], {restore: true})

  return gulp.src(assets, srcOpts)
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(newer({map: mapToDest}))
    .pipe(assetFilter)
    .pipe(through.obj((file, enc, callback) => {
      gutil.log('Compiling', `'${chalk.cyan(file.path)}'...`)
      callback(null, file)
    }))
    .pipe(babel())
    .pipe(assetFilter.restore)
    .pipe(through.obj((file, enc, callback) => {
      file._path = file.path
      file.path = mapToDest(file.path)
      callback(null, file)
    }))
    .pipe(gulp.dest(dest))
})

gulp.task('watch-js', () => {
  return gulp.src(scripts, srcOpts)
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(through.obj((file, enc, callback) => {
      file._path = file.path
      file.path = mapToDest(file.path)
      callback(null, file)
    }))
    .pipe(newer(dest))
    .pipe(through.obj((file, enc, callback) => {
      gutil.log('Compiling', `'${chalk.cyan(file._path)}'...`)
      callback(null, file)
    }))
    .pipe(babel())
    .pipe(gulp.dest(dest))
})

gulp.task('watch-assets', () => {
  return gulp.src(assets, srcOpts)
    .pipe(filter(['**/*.*', '!**/*.js']))
    .pipe(plumber({errorHandler: err => gutil.log(err.stack)}))
    .pipe(through.obj((file, enc, callback) => {
      file._path = file.path
      file.path = mapToDest(file.path)
      callback(null, file)
    }))
    .pipe(newer(dest))
    .pipe(through.obj((file, enc, callback) => {
      gutil.log('Copying', `'${chalk.cyan(file._path)}'...`)
      callback(null, file)
    }))
    .pipe(gulp.dest(dest))
})

gulp.task('watch', ['watch-js', 'watch-assets'], callback => {
  watch(scripts, {debounceDelay: 200}, () => {
    gulp.start('watch-js')
  })

  watch(assets, {debounceDelay: 200}, () => {
    gulp.start('watch-assets')
  })
})

gulp.task('dev', ['watch-js', 'watch-assets'], cb => {
  watch(scripts, {debounceDelay: 200}, () => {
    gulp.start('watch-js')
  })

  watch(assets, {debounceDelay: 200}, () => {
    gulp.start('watch-assets')
  })

  const projectPath = path.join(__dirname, 'packages', 'test-studio')
  const proc = childProcess.spawn('sanity', ['start', '--host', '0.0.0.0'], {
    shell: isWindows,
    cwd: projectPath,
    env: getProjectEnv(projectPath)
  })

  proc.stdout.pipe(process.stdout)
  proc.stderr.pipe(process.stderr)
})

gulp.task('example', ['watch-js', 'watch-assets'], cb => {
  watch(scripts, {debounceDelay: 200}, () => {
    gulp.start('watch-js')
  })

  watch(assets, {debounceDelay: 200}, () => {
    gulp.start('watch-assets')
  })

  const projectPath = path.join(__dirname, 'packages', 'example-studio')
  const proc = childProcess.spawn('sanity', ['start', '--host', '0.0.0.0'], {
    shell: isWindows,
    cwd: projectPath,
    env: getProjectEnv(projectPath)
  })

  proc.stdout.pipe(process.stdout)
  proc.stderr.pipe(process.stderr)
})

gulp.task('storybook', ['watch-js', 'watch-assets'], () => {
  watch(scripts, {debounceDelay: 200}, () => {
    gulp.start('watch-js')
  })

  watch(assets, {debounceDelay: 200}, () => {
    gulp.start('watch-assets')
  })

  const projectPath = path.join(__dirname, 'packages', 'storybook')
  const proc = childProcess.spawn('npm', ['start'], {
    shell: isWindows,
    cwd: projectPath,
    env: getProjectEnv(projectPath)
  })

  proc.stdout.pipe(process.stdout)
  proc.stderr.pipe(process.stderr)
})
<|endoftext|>


<commit_before>/*
These are routes as defined in https://docs.google.com/document/d/1337m6i7Y0GPULKLsKpyHR4NRzRwhoxJnAZNnDFCigkc/edit#
Each route implementes a basic parameter/payload validation and a swagger API documentation description
*/
'use strict';

const Joi = require('joi'),
  handlers = require('./controllers/handler');

module.exports = function(server) {
  //Get discussion with content id id from database and return the entire tree (when not available, return NOT FOUND). Validate id
  server.route({
    method: 'GET',
    path: '/discussion/{content_kind}/{id}',
    handler: handlers.getDiscussion,
    config: {
      validate: {
        params: {
          content_kind: Joi.string().valid('deck', 'slide'),
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Get a discussion'
    }
  });

  //Get discussion with content id id from database and return the entire tree (when not available, return NOT FOUND). Validate id
  server.route({
    method: 'GET',
    path: '/discussion/{id}',
    handler: handlers.getDiscussion,
    config: {
      validate: {
        params: {
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Get a discussion (for slides)'
    }
  });

  //Get the number of comments in a discussion with content id id from database
  server.route({
    method: 'GET',
    path: '/discussion/count/{content_kind}/{id}',
    handler: handlers.getDiscussionCount,
    config: {
      validate: {
        params: {
          content_kind: Joi.string().valid('deck', 'slide'),
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Get the number of comments in a discussion'
    }
  });

  //Get all discussions from database and return the entire tree (when not available, return NOT FOUND).
  server.route({
    method: 'GET',
    path: '/discussion/all',
    handler: handlers.getAllDiscussions,
    config: {
      tags: ['api'],
      description: 'Get all discussions'
    }
  });

  //Get comment with id id from database and return it (when not available, return NOT FOUND). Validate id
  server.route({
    method: 'GET',
    path: '/comment/{id}',
    handler: handlers.getComment,
    config: {
      validate: {
        params: {
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Get a comment'
    }
  });

  //Create new comment (by payload) and return it (...). Validate payload
  server.route({
    method: 'POST',
    path: '/comment/new',
    handler: handlers.newComment,
    config: {
      validate: {
        payload: Joi.object().keys({
          title: Joi.string(),
          text: Joi.string(),
          user_id: Joi.string(),
          content_id: Joi.string(),
          content_kind: Joi.string().valid('deck', 'slide'),
          parent_comment: Joi.string(),
          is_activity: Joi.boolean()
        }).requiredKeys('content_id', 'user_id'),
      },
      tags: ['api'],
      description: 'Create a new comment'
    }
  });

  //Update comment with id id (by payload) and return it (...). Validate payload
  server.route({
    method: 'PUT',
    path: '/comment/{id}',
    handler: handlers.updateComment,
    config: {
      validate: {
        params: {
          id: Joi.string().alphanum().lowercase()
        },
        payload: Joi.object().keys({
          title: Joi.string(),
          text: Joi.string(),
          user_id: Joi.string(),
          content_id: Joi.string(),
          content_kind: Joi.string().valid('deck', 'slide'),
          parent_comment: Joi.string(),
          is_activity: Joi.boolean()
        }).requiredKeys('content_id', 'user_id'),
      },
      tags: ['api'],
      description: 'Replace a comment'
    }
  });

  //Delete comment with id id (by payload) . Validate payload
  server.route({
    method: 'DELETE',
    path: '/comment/delete',
    handler: handlers.deleteComment,
    config: {
      validate: {
        payload: {
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Delete a comment'
    }
  });

  //Delete discussion with content id id (by payload) . Validate payload
  server.route({
    method: 'DELETE',
    path: '/discussion/delete',
    handler: handlers.deleteDiscussion,
    config: {
      validate: {
        payload: {
          content_id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Delete a discussion (example id: 8)'
    }
  });
};
<commit_msg>Allow empty comment text<commit_after>/*
These are routes as defined in https://docs.google.com/document/d/1337m6i7Y0GPULKLsKpyHR4NRzRwhoxJnAZNnDFCigkc/edit#
Each route implementes a basic parameter/payload validation and a swagger API documentation description
*/
'use strict';

const Joi = require('joi'),
  handlers = require('./controllers/handler');

module.exports = function(server) {
  //Get discussion with content id id from database and return the entire tree (when not available, return NOT FOUND). Validate id
  server.route({
    method: 'GET',
    path: '/discussion/{content_kind}/{id}',
    handler: handlers.getDiscussion,
    config: {
      validate: {
        params: {
          content_kind: Joi.string().valid('deck', 'slide'),
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Get a discussion'
    }
  });

  //Get discussion with content id id from database and return the entire tree (when not available, return NOT FOUND). Validate id
  server.route({
    method: 'GET',
    path: '/discussion/{id}',
    handler: handlers.getDiscussion,
    config: {
      validate: {
        params: {
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Get a discussion (for slides)'
    }
  });

  //Get the number of comments in a discussion with content id id from database
  server.route({
    method: 'GET',
    path: '/discussion/count/{content_kind}/{id}',
    handler: handlers.getDiscussionCount,
    config: {
      validate: {
        params: {
          content_kind: Joi.string().valid('deck', 'slide'),
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Get the number of comments in a discussion'
    }
  });

  //Get all discussions from database and return the entire tree (when not available, return NOT FOUND).
  server.route({
    method: 'GET',
    path: '/discussion/all',
    handler: handlers.getAllDiscussions,
    config: {
      tags: ['api'],
      description: 'Get all discussions'
    }
  });

  //Get comment with id id from database and return it (when not available, return NOT FOUND). Validate id
  server.route({
    method: 'GET',
    path: '/comment/{id}',
    handler: handlers.getComment,
    config: {
      validate: {
        params: {
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Get a comment'
    }
  });

  //Create new comment (by payload) and return it (...). Validate payload
  server.route({
    method: 'POST',
    path: '/comment/new',
    handler: handlers.newComment,
    config: {
      validate: {
        payload: Joi.object().keys({
          title: Joi.string(),
          text: Joi.string().allow(''),
          user_id: Joi.string(),
          content_id: Joi.string(),
          content_kind: Joi.string().valid('deck', 'slide'),
          parent_comment: Joi.string(),
          is_activity: Joi.boolean()
        }).requiredKeys('content_id', 'user_id'),
      },
      tags: ['api'],
      description: 'Create a new comment'
    }
  });

  //Update comment with id id (by payload) and return it (...). Validate payload
  server.route({
    method: 'PUT',
    path: '/comment/{id}',
    handler: handlers.updateComment,
    config: {
      validate: {
        params: {
          id: Joi.string().alphanum().lowercase()
        },
        payload: Joi.object().keys({
          title: Joi.string(),
          text: Joi.string().allow(''),
          user_id: Joi.string(),
          content_id: Joi.string(),
          content_kind: Joi.string().valid('deck', 'slide'),
          parent_comment: Joi.string(),
          is_activity: Joi.boolean()
        }).requiredKeys('content_id', 'user_id'),
      },
      tags: ['api'],
      description: 'Replace a comment'
    }
  });

  //Delete comment with id id (by payload) . Validate payload
  server.route({
    method: 'DELETE',
    path: '/comment/delete',
    handler: handlers.deleteComment,
    config: {
      validate: {
        payload: {
          id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Delete a comment'
    }
  });

  //Delete discussion with content id id (by payload) . Validate payload
  server.route({
    method: 'DELETE',
    path: '/discussion/delete',
    handler: handlers.deleteDiscussion,
    config: {
      validate: {
        payload: {
          content_id: Joi.string()
        },
      },
      tags: ['api'],
      description: 'Delete a discussion (example id: 8)'
    }
  });
};
<|endoftext|>


<commit_before>define(function() {

  'use strict';

  function Terp() {
  }

  var validTerpScripts = new WeakMap();

  // modified version of JSON.stringify with specialized whitespace rules
  function stringifyStepOrBlock(stepOrBlock, indent) {
    if (typeof stepOrBlock[0] === 'string') {
      // step mode
      function stringifyElement(element) {
        if (typeof element === 'object' && element !== null) {
          if (!Array.isArray(element)) {
            throw new SyntaxError('Non-Array objects are not currently supported in TerpScript');
          }
          return stringifyStepOrBlock(element, indent);
        }
        return JSON.stringify(element);
      }
      return '[' + stepOrBlock.map(stringifyElement).join(', ') + ']';
    }
    if (stepOrBlock.length === 0) return '[ ]';
    if (stepOrBlock.length === 1) {
      indent = indent || '';
      var single = stringifyStepOrBlock(stepOrBlock[0], indent);
      if (!/\n/.test(single)) {
        return '[ ' + single + ' ]';
      }
      return '[\n' + indent + single + '\n' + indent + ']';
    }
    if (typeof indent !== 'string') {
      indent = '';
      function stringifyStepTop(step) {
        return stringifyStepOrBlock(step, indent);
      }
      return '[\n\n' + stepOrBlock.map(stringifyStepTop).join(',\n') + '\n\n]';
    }
    indent = indent || '';
    var newIndent = indent + '  ';
    function stringifyStep(step) {
      return stringifyStepOrBlock(step, newIndent);
    }
    return '[\n' + newIndent + stepOrBlock.map(stringifyStep).join(',\n' + newIndent) + '\n' + indent + ']';
  }

  var emptyScript = Object.freeze([]);
  validTerpScripts.set(emptyScript, true);

  const PARENT_SCOPE = Symbol('scope');
  const SCOPE_DEPTH = Symbol('depth');

  function toTerpScript(stepOrBlock, okToModify, scope) {
    if (stepOrBlock.length === 0) return emptyScript;
    if (stepOrBlock.length === 1 && scope && typeof stepOrBlock[0] === 'string' && stepOrBlock[0] in scope) {
      return scope[stepOrBlock[0]];
    }
    if (!okToModify) {
      stepOrBlock = stepOrBlock.slice();
    }
    var scopeDepth = scope ? scope[SCOPE_DEPTH] : 0;
    var usedScope = false;
    for (var i = 0; i < stepOrBlock.length; i++) {
      if (typeof stepOrBlock[i] !== 'object' || stepOrBlock[i] === null || validTerpScripts.has(stepOrBlock[i])) {
        continue;
      }
      if (!Array.isArray(stepOrBlock[i], scope)) {
        throw new SyntaxError('Non-Array objects are not currently supported in TerpScript');
      }
      stepOrBlock[i] = toTerpScript(stepOrBlock[i], okToModify, scope);
      if (PARENT_SCOPE in stepOrBlock[i]) {
        usedScope = true;
      }
      if (typeof stepOrBlock[i][0] !== 'string') continue;
      switch (stepOrBlock[i][0]) {
        case '</>':
          if (!scope || scope[SCOPE_DEPTH] !== scopeDepth + 1) {
            throw new SyntaxError('End-of-Scope step without corresponding Scope step');
          }
          scope = scope[PARENT_SCOPE];
          break;
        case '< >':
          var newScope = scope ? Object.assign({}, scope) : {};
          if (scope) {
            newScope[PARENT_SCOPE] = scope;
            newScope[SCOPE_DEPTH] = scope[SCOPE_DEPTH] + 1;
          }
          else {
            newScope[SCOPE_DEPTH] = 0;
          }
          for (var j = 1; j < stepOrBlock[i].length; i++) {
            var scopedName = stepOrBlock[i][j];
            if (typeof scopedName !== 'string') {
              throw new SyntaxError('Scope step parameters must be strings');
            }
            var scopedRef = [scopedName];
            scopedRef[PARENT_SCOPE] = newScope;
            newScope[scopedName] = Object.freeze(scopedRef);
          }
          scope = Object.freeze(newScope);
          break;
      }
    }
    if (usedScope) {
      stepOrBlock[PARENT_SCOPE] = scope;
    }
    else {
      validTerpScripts.set(stepOrBlock, true);
    }
    return Object.freeze(stepOrBlock);
  }

  function script(v, isTheOnlyReference) {
    if (validTerpScripts.has(v)) return v;
    if (typeof v === 'string') {
      v = JSON.parse(v);
      if (!Array.isArray(v)) {
        throw new SyntaxError('TerpScripts must be contained in an Array');
      }
      return toTerpScript(JSON.parse(v), true);
    }
    if (!Array.isArray(v)) {
      if (typeof v.toJSON !== 'function' || !Array.isArray(v = v.toJSON())) {
        throw new SyntaxError('TerpScripts must be contained in an Array');
      }
      return toTerpScript(v, true);
    }
    return toTerpScript(v, isTheOnlyReference);
  }

  Object.assign(Terp, {
    script: Object.assign(script, {
      stringify: function(script) {
        if (typeof script === 'string') {
          script = JSON.parse(script);
          if (Array.isArray(script)) {
            return stringifyStepOrBlock(script);
          }
        }
        else {
          if (Array.isArray(script)) {
            return stringifyStepOrBlock(script);
          }
          if (typeof script.toJSON === 'function' && Array.isArray(script = script.toJSON())) {
            return stringifyStepOrBlock(script);
          }
        }
        throw new SyntaxError('TerpScript must be an contained in an Array');
      },
      empty: emptyScript,
    }),
  });

  return Terp;

});
<commit_msg>Fix incrementing the wrong counter<commit_after>define(function() {

  'use strict';

  function Terp() {
  }

  var validTerpScripts = new WeakMap();

  // modified version of JSON.stringify with specialized whitespace rules
  function stringifyStepOrBlock(stepOrBlock, indent) {
    if (typeof stepOrBlock[0] === 'string') {
      // step mode
      function stringifyElement(element) {
        if (typeof element === 'object' && element !== null) {
          if (!Array.isArray(element)) {
            throw new SyntaxError('Non-Array objects are not currently supported in TerpScript');
          }
          return stringifyStepOrBlock(element, indent);
        }
        return JSON.stringify(element);
      }
      return '[' + stepOrBlock.map(stringifyElement).join(', ') + ']';
    }
    if (stepOrBlock.length === 0) return '[ ]';
    if (stepOrBlock.length === 1) {
      indent = indent || '';
      var single = stringifyStepOrBlock(stepOrBlock[0], indent);
      if (!/\n/.test(single)) {
        return '[ ' + single + ' ]';
      }
      return '[\n' + indent + single + '\n' + indent + ']';
    }
    if (typeof indent !== 'string') {
      indent = '';
      function stringifyStepTop(step) {
        return stringifyStepOrBlock(step, indent);
      }
      return '[\n\n' + stepOrBlock.map(stringifyStepTop).join(',\n') + '\n\n]';
    }
    indent = indent || '';
    var newIndent = indent + '  ';
    function stringifyStep(step) {
      return stringifyStepOrBlock(step, newIndent);
    }
    return '[\n' + newIndent + stepOrBlock.map(stringifyStep).join(',\n' + newIndent) + '\n' + indent + ']';
  }

  var emptyScript = Object.freeze([]);
  validTerpScripts.set(emptyScript, true);

  const PARENT_SCOPE = Symbol('scope');
  const SCOPE_DEPTH = Symbol('depth');

  function toTerpScript(stepOrBlock, okToModify, scope) {
    if (stepOrBlock.length === 0) return emptyScript;
    if (stepOrBlock.length === 1 && scope && typeof stepOrBlock[0] === 'string' && stepOrBlock[0] in scope) {
      return scope[stepOrBlock[0]];
    }
    if (!okToModify) {
      stepOrBlock = stepOrBlock.slice();
    }
    var scopeDepth = scope ? scope[SCOPE_DEPTH] : 0;
    var usedScope = false;
    for (var i = 0; i < stepOrBlock.length; i++) {
      if (typeof stepOrBlock[i] !== 'object' || stepOrBlock[i] === null || validTerpScripts.has(stepOrBlock[i])) {
        continue;
      }
      if (!Array.isArray(stepOrBlock[i], scope)) {
        throw new SyntaxError('Non-Array objects are not currently supported in TerpScript');
      }
      stepOrBlock[i] = toTerpScript(stepOrBlock[i], okToModify, scope);
      if (PARENT_SCOPE in stepOrBlock[i]) {
        usedScope = true;
      }
      if (typeof stepOrBlock[i][0] !== 'string') continue;
      switch (stepOrBlock[i][0]) {
        case '</>':
          if (!scope || scope[SCOPE_DEPTH] !== scopeDepth + 1) {
            throw new SyntaxError('End-of-Scope step without corresponding Scope step');
          }
          scope = scope[PARENT_SCOPE];
          break;
        case '< >':
          var newScope = scope ? Object.assign({}, scope) : {};
          if (scope) {
            newScope[PARENT_SCOPE] = scope;
            newScope[SCOPE_DEPTH] = scope[SCOPE_DEPTH] + 1;
          }
          else {
            newScope[SCOPE_DEPTH] = 0;
          }
          for (var j = 1; j < stepOrBlock[i].length; j++) {
            var scopedName = stepOrBlock[i][j];
            if (typeof scopedName !== 'string') {
              throw new SyntaxError('Scope step parameters must be strings');
            }
            var scopedRef = [scopedName];
            scopedRef[PARENT_SCOPE] = newScope;
            newScope[scopedName] = Object.freeze(scopedRef);
          }
          scope = Object.freeze(newScope);
          break;
      }
    }
    if (usedScope) {
      stepOrBlock[PARENT_SCOPE] = scope;
    }
    else {
      validTerpScripts.set(stepOrBlock, true);
    }
    return Object.freeze(stepOrBlock);
  }

  function script(v, isTheOnlyReference) {
    if (validTerpScripts.has(v)) return v;
    if (typeof v === 'string') {
      v = JSON.parse(v);
      if (!Array.isArray(v)) {
        throw new SyntaxError('TerpScripts must be contained in an Array');
      }
      return toTerpScript(JSON.parse(v), true);
    }
    if (!Array.isArray(v)) {
      if (typeof v.toJSON !== 'function' || !Array.isArray(v = v.toJSON())) {
        throw new SyntaxError('TerpScripts must be contained in an Array');
      }
      return toTerpScript(v, true);
    }
    return toTerpScript(v, isTheOnlyReference);
  }

  Object.assign(Terp, {
    script: Object.assign(script, {
      stringify: function(script) {
        if (typeof script === 'string') {
          script = JSON.parse(script);
          if (Array.isArray(script)) {
            return stringifyStepOrBlock(script);
          }
        }
        else {
          if (Array.isArray(script)) {
            return stringifyStepOrBlock(script);
          }
          if (typeof script.toJSON === 'function' && Array.isArray(script = script.toJSON())) {
            return stringifyStepOrBlock(script);
          }
        }
        throw new SyntaxError('TerpScript must be an contained in an Array');
      },
      empty: emptyScript,
    }),
  });

  return Terp;

});
<|endoftext|>