<commit_before>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

(function (root, factory) {

    var MessageFormat = factory();

    // register in -all- the module systems (at once)
    if (typeof define === 'function' && define.amd) {
        define(MessageFormat);
    }

    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = MessageFormat;
    }

    if (root) {
        root.IntlMessageFormat = MessageFormat;
    }

})(typeof global !== 'undefined' ? global : this, function() {

    "use strict";

    var DEFAULT_LOCALE = (typeof Intl === 'object') && (typeof Intl.DefaultLocale === 'function') ? Intl.DefaultLocale() : 'en',
        // localeData registered by __addLocaleData()
        localeData = {};

    /**
     Creates MessageFormat object from a pattern, locale and field formatters.
     String patterns are broken down Arrays. Objects should match the
     following pattern:

     ```
     {
        type: 'plural|gender|select',
        valueName: 'string',
        offset: 1, // consistent offsets for plurals
        options: {}, // keys match options for plurals, gender and selects
        formatter: 'string|function' // strings are matched to internal formatters
     }
     ```

     @constructor

     @param {Array|String} pattern Array or string that serves as formatting pattern.
         Use array for plural and select messages, otherwise use string form.
     @param {LocaleList|String} locale Locale for string formatting
     @param {Object} optFieldFormatters Holds user defined formatters for each field (Dojo like).
     */
    function MessageFormat (pattern, locale, optFieldFormatters) {
        var chunks,
            len,
            i,
            p;

        // store locale
        this.locale = locale;

        if (!locale && JSON.stringify(localeData) === '{}') {
            throw new ReferenceError('No locale data has been provided for this object yet.');
        }

        // We calculate the pluralization function used for the specific locale.
        // Since this is a bit expensive (if repeated too much) and since the
        // locale can change on us without notice, we need to keep track of
        // which locale was used in choosing the pluralization function.
        // (It's expected that the locale will change very infrequently for
        // each MessageFormat object.)
        this._pluralLocale = undefined;
        this._pluralFunc = undefined;

        // Assume the string passed in is a simple pattern for replacement.
        if (typeof pattern === 'string') {
            // break apart the string into chunks and tokens
            chunks = pattern.match(/((\$?\{)?[^\$\{\}]*\}?)/gi);

            // loop through each chunk and replace tokens when found
            for (i = 0, len = chunks.length; i < len; i++) {
                // create an object for the token when found
                if (/\$?\{(\w*):?(\w*)?\}/.test(chunks[i])) {

                    chunks[i] = {
                        // the valuename is the "key" for the token ... ${key}
                        valueName: chunks[i].match(/\$?\{(\w*):?(\w*)?\}/)[1],
                        formatter: chunks[i].match(/\$?\{(\w*):?(\w*)?\}/)[2],
                    };
                }
            }

            // our pattern should now be the chunked array
            pattern = chunks;
        }

        // save the pattern internally
        this.pattern = pattern;

        // store formatters
        this.formatters = {};

        if (optFieldFormatters) {
            for (p in optFieldFormatters) {
                if (optFieldFormatters.hasOwnProperty(p)) {
                    this.formatters[p] = optFieldFormatters[p];
                }
            }
        }
    }

    /**
     Formats pattern with supplied parameters.
     Dates, times and numbers are formatted in locale sensitive way.
     @param {Array|Object} params
     @return {String}
     */
    MessageFormat.prototype.format = function (obj) {

        var pattern = this.pattern,
            tokens,
            key,
            len,
            i;

        // the pattern we have is an array, we need to stitch it together
        // before moving forward
        if (Object.prototype.toString.call(pattern) === '[object Array]') {
            // let's not destroy the local pattern
            pattern = pattern.concat();

            // turn the array into a string
            pattern = this._processArray.call(this, pattern, obj);
        }

        // make sure we have a string
        pattern += '';

        // find tokens and replace with the object
        tokens = pattern.match(/\$?\{([^\} ]*)\}/g);

        // if there were any tokens found, we need to replace them with the
        if (tokens) {
            for (i = 0, len = tokens.length; i < len; i++) {
                // extract key out of ${key} or {key}
                key = tokens[i].charAt(0) === '$' ?
                        tokens[i].substr(2) :
                        tokens[i].substr(1);

                // remove trailing }
                key = key.substr(0, key.length - 1);

                // replace the token with obj[key]
                if (obj.hasOwnProperty(key)) {
                    pattern = pattern.replace(tokens[i], obj[key]);
                }
            }
        }

        return pattern;
    };

    /**
     Returns resolved options, in this case supported locale.
     @return {Object}
     */
    MessageFormat.prototype.resolvedOptions = function () {
        // TODO: Figure out what options should be returned for messages
        return {};
    };

    /**
     Normalizes the number to option values for plural identification
     @param {Number} count Number to normalize
     @return {String}
     */
    MessageFormat.prototype._normalizeCount = function (count) {
        var locale = this.locale || DEFAULT_LOCALE,
            data,
            fn,
            parts;
        // cache the choice of pluralization function
        if (this._pluralLocale !== locale) {
            if (locale !== DEFAULT_LOCALE) {
                parts = this.locale.toLowerCase().split('-');
                while (parts.length) {
                    data = localeData[parts.join('_')];
                    if (data && data.pluralFunction) {
                        fn = data.pluralFunction;
                        break;
                    }
                    parts.pop();
                }
            }
            if (!fn) {
                // While this seems excessive, it's possible the user has a
                // complex default locale (such as "zh-hans-CN") since the
                // default locale can come from a browser setting.
                parts = DEFAULT_LOCALE.toLowerCase().split('-');
                while (parts.length) {
                    data = localeData[parts.join('_')];
                    if (data && data.pluralFunction) {
                        fn = data.pluralFunction;
                        break;
                    }
                    parts.pop();
                }
            }
            if (!fn) {
                data = localeData.en;
                fn = (data && data.pluralFunction) || function() {
                    return 'other';
                };
            }
            this._pluralLocale = locale;
            this._pluralFunc = fn;
        }
        return this._pluralFunc(count) || 'other';
    };

    /**
     Processes an array to return a string back once it's located. Arrays are
     concatenated. Each item is also processed based on whether it is an
     object or an array.
     @param {Array} arr
     @param {Object} obj
     @return {String}
     */
    MessageFormat.prototype._processArray = function (arr, obj) {
        var str = '',
            valType,
            val,
            len,
            i;

        // parse through the array to get the appropriate string value for each index
        for (i = 0, len = arr.length; i < len; i++) {

            val = arr[i];

            // If we don't already have a string, let's try to make it one
            if (typeof val !== 'string') {
                while (typeof val !== 'string') {
                    // let's find out what we are working with in the loop
                    valType = {}.toString.call(val);

                    if (valType === '[object Array]') {
                        val = this._processArray.call(this, val, obj);
                    } else if (valType === '[object Object]') {
                        val = this._processObject.call(this, val, obj);
                    } else {
                        // not an array or object, let's cast it and move on
                        val += '';
                    }
                }
            }

            // concat our new value to the return string
            str += val;
        }

        return str;
    };

    /**
     Processes the Object based on the lookUp object. Each object should have
     a `valueName` property; this property is used to located the value in the
     lookUp object.

     If the lookUp object returns a string, it will be sandwiched between
     `obj.prefix` and `obj.postfix` if they exist.

     @param {Ojbect} obj
     @param {Object} lookUp
     @return {String|Array|Object}
     */
    MessageFormat.prototype._processObject = function (obj, lookUp) {
        var val = lookUp[obj.valueName],
            valName = val,
            valType,
            formatterFn;

        // our look up object isn't in the provided lookUp object
        if (typeof val === 'undefined' || val === null) {
            throw 'The valueName `' + obj.valueName + '` was not found.';
        }

        // if we are dealing with plurals and we have a number, we need to
        // normalize the number's value based on the locale
        if (obj.type === 'plural' && typeof val === 'number') {
            if (obj.offset) {
                val += obj.offset;
            }

            val = this._normalizeCount(val);
        }

        // if we have an options property, we need the value from this object
        // as it relates to our value
        if (obj.options) {
            // options should always fallback to an "other" option when not found
            val = obj.options[val] || obj.options.other;
        }

        valType = typeof val;

        // if we have a string or number to return, we need to sandwich it
        // with (pre|post)fix
        if (valType === 'string' || valType === 'number') {

            // strings should be checked for hash tokens
            if (valType === 'string') {
                // We need to make sure we aren't doing a context look up `${#}`
                val = val.replace('${#}', valName);
            }

            // process with a formatter if one exists
            if (obj.formatter) {
                formatterFn = {}.toString.call(obj.formatter) === '[object Function]' ? obj.formatter : this.formatters[obj.formatter];

                if (formatterFn) {
                    val = formatterFn.call(this, val, this.locale);
                }
            }

            // sandwich
            val = (obj.prefix || '') + val + (obj.postfix || '');
        }

        return val;
    };

    /**
     Registers localization data for a particular locale.
     The format is:

     ```
     {
        locale: 'the locale',
        messageformat: {
            // This function takes a number (count) and turns it into a
            // pluralization group (e.g. 'one', 'few', 'many', 'other').
            pluralFunction: function(count) { return 'plural group' }
        }
     }
     ```

     @method __addLocaleData
     @param {Object} The locale data as described above.
     @return {nothing}
     */
    MessageFormat.__addLocaleData = function(data) {
        localeData[data.locale] = data.messageformat;
    };

    return MessageFormat;
});

<commit_msg>The first locale lang-pack to be loaded becomes the default and is used when no locale arg is provided.<commit_after>/*
 * Copyright (c) 2011-2013, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

(function (root, factory) {

    var MessageFormat = factory();

    // register in -all- the module systems (at once)
    if (typeof define === 'function' && define.amd) {
        define(MessageFormat);
    }

    if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = MessageFormat;
    }

    if (root) {
        root.IntlMessageFormat = MessageFormat;
    }

})(typeof global !== 'undefined' ? global : this, function() {

    "use strict";

    var DEFAULT_LOCALE = (typeof Intl === 'object') && (typeof Intl.DefaultLocale === 'function') ? Intl.DefaultLocale() : null,
        // localeData registered by __addLocaleData()
        localeData = {};

    /**
     Creates MessageFormat object from a pattern, locale and field formatters.
     String patterns are broken down Arrays. Objects should match the
     following pattern:

     ```
     {
        type: 'plural|gender|select',
        valueName: 'string',
        offset: 1, // consistent offsets for plurals
        options: {}, // keys match options for plurals, gender and selects
        formatter: 'string|function' // strings are matched to internal formatters
     }
     ```

     @constructor

     @param {Array|String} pattern Array or string that serves as formatting pattern.
         Use array for plural and select messages, otherwise use string form.
     @param {LocaleList|String} locale Locale for string formatting
     @param {Object} optFieldFormatters Holds user defined formatters for each field (Dojo like).
     */
    function MessageFormat (pattern, locale, optFieldFormatters) {
        var chunks,
            len,
            i,
            p;

        // store locale
        this.locale = locale;

        if (!locale && JSON.stringify(localeData) === '{}') {
            throw new ReferenceError('No locale data has been provided for this object yet.');
        }

        // We calculate the pluralization function used for the specific locale.
        // Since this is a bit expensive (if repeated too much) and since the
        // locale can change on us without notice, we need to keep track of
        // which locale was used in choosing the pluralization function.
        // (It's expected that the locale will change very infrequently for
        // each MessageFormat object.)
        this._pluralLocale = undefined;
        this._pluralFunc = undefined;

        // Assume the string passed in is a simple pattern for replacement.
        if (typeof pattern === 'string') {
            // break apart the string into chunks and tokens
            chunks = pattern.match(/((\$?\{)?[^\$\{\}]*\}?)/gi);

            // loop through each chunk and replace tokens when found
            for (i = 0, len = chunks.length; i < len; i++) {
                // create an object for the token when found
                if (/\$?\{(\w*):?(\w*)?\}/.test(chunks[i])) {

                    chunks[i] = {
                        // the valuename is the "key" for the token ... ${key}
                        valueName: chunks[i].match(/\$?\{(\w*):?(\w*)?\}/)[1],
                        formatter: chunks[i].match(/\$?\{(\w*):?(\w*)?\}/)[2],
                    };
                }
            }

            // our pattern should now be the chunked array
            pattern = chunks;
        }

        // save the pattern internally
        this.pattern = pattern;

        // store formatters
        this.formatters = {};

        if (optFieldFormatters) {
            for (p in optFieldFormatters) {
                if (optFieldFormatters.hasOwnProperty(p)) {
                    this.formatters[p] = optFieldFormatters[p];
                }
            }
        }
    }

    /**
     Formats pattern with supplied parameters.
     Dates, times and numbers are formatted in locale sensitive way.
     @param {Array|Object} params
     @return {String}
     */
    MessageFormat.prototype.format = function (obj) {

        var pattern = this.pattern,
            tokens,
            key,
            len,
            i;

        // the pattern we have is an array, we need to stitch it together
        // before moving forward
        if (Object.prototype.toString.call(pattern) === '[object Array]') {
            // let's not destroy the local pattern
            pattern = pattern.concat();

            // turn the array into a string
            pattern = this._processArray.call(this, pattern, obj);
        }

        // make sure we have a string
        pattern += '';

        // find tokens and replace with the object
        tokens = pattern.match(/\$?\{([^\} ]*)\}/g);

        // if there were any tokens found, we need to replace them with the
        if (tokens) {
            for (i = 0, len = tokens.length; i < len; i++) {
                // extract key out of ${key} or {key}
                key = tokens[i].charAt(0) === '$' ?
                        tokens[i].substr(2) :
                        tokens[i].substr(1);

                // remove trailing }
                key = key.substr(0, key.length - 1);

                // replace the token with obj[key]
                if (obj.hasOwnProperty(key)) {
                    pattern = pattern.replace(tokens[i], obj[key]);
                }
            }
        }

        return pattern;
    };

    /**
     Returns resolved options, in this case supported locale.
     @return {Object}
     */
    MessageFormat.prototype.resolvedOptions = function () {
        // TODO: Figure out what options should be returned for messages
        return {};
    };

    /**
     Normalizes the number to option values for plural identification
     @param {Number} count Number to normalize
     @return {String}
     */
    MessageFormat.prototype._normalizeCount = function (count) {
        var locale = this.locale || DEFAULT_LOCALE,
            data,
            fn,
            parts;
        // cache the choice of pluralization function
        if (this._pluralLocale !== locale) {
            if (locale !== DEFAULT_LOCALE) {
                parts = this.locale.toLowerCase().split('-');
                while (parts.length) {
                    data = localeData[parts.join('_')];
                    if (data && data.pluralFunction) {
                        fn = data.pluralFunction;
                        break;
                    }
                    parts.pop();
                }
            }
            if (!fn) {
                // While this seems excessive, it's possible the user has a
                // complex default locale (such as "zh-hans-CN") since the
                // default locale can come from a browser setting.
                parts = DEFAULT_LOCALE.toLowerCase().split('-');
                while (parts.length) {
                    data = localeData[parts.join('_')];
                    if (data && data.pluralFunction) {
                        fn = data.pluralFunction;
                        break;
                    }
                    parts.pop();
                }
            }
            if (!fn) {
                data = localeData[DEFAULT_LOCALE];
                fn = (data && data.pluralFunction) || function() {
                    return 'other';
                };
            }
            this._pluralLocale = locale;
            this._pluralFunc = fn;
        }
        return this._pluralFunc(count) || 'other';
    };

    /**
     Processes an array to return a string back once it's located. Arrays are
     concatenated. Each item is also processed based on whether it is an
     object or an array.
     @param {Array} arr
     @param {Object} obj
     @return {String}
     */
    MessageFormat.prototype._processArray = function (arr, obj) {
        var str = '',
            valType,
            val,
            len,
            i;

        // parse through the array to get the appropriate string value for each index
        for (i = 0, len = arr.length; i < len; i++) {

            val = arr[i];

            // If we don't already have a string, let's try to make it one
            if (typeof val !== 'string') {
                while (typeof val !== 'string') {
                    // let's find out what we are working with in the loop
                    valType = {}.toString.call(val);

                    if (valType === '[object Array]') {
                        val = this._processArray.call(this, val, obj);
                    } else if (valType === '[object Object]') {
                        val = this._processObject.call(this, val, obj);
                    } else {
                        // not an array or object, let's cast it and move on
                        val += '';
                    }
                }
            }

            // concat our new value to the return string
            str += val;
        }

        return str;
    };

    /**
     Processes the Object based on the lookUp object. Each object should have
     a `valueName` property; this property is used to located the value in the
     lookUp object.

     If the lookUp object returns a string, it will be sandwiched between
     `obj.prefix` and `obj.postfix` if they exist.

     @param {Ojbect} obj
     @param {Object} lookUp
     @return {String|Array|Object}
     */
    MessageFormat.prototype._processObject = function (obj, lookUp) {
        var val = lookUp[obj.valueName],
            valName = val,
            valType,
            formatterFn;

        // our look up object isn't in the provided lookUp object
        if (typeof val === 'undefined' || val === null) {
            throw 'The valueName `' + obj.valueName + '` was not found.';
        }

        // if we are dealing with plurals and we have a number, we need to
        // normalize the number's value based on the locale
        if (obj.type === 'plural' && typeof val === 'number') {
            if (obj.offset) {
                val += obj.offset;
            }

            val = this._normalizeCount(val);
        }

        // if we have an options property, we need the value from this object
        // as it relates to our value
        if (obj.options) {
            // options should always fallback to an "other" option when not found
            val = obj.options[val] || obj.options.other;
        }

        valType = typeof val;

        // if we have a string or number to return, we need to sandwich it
        // with (pre|post)fix
        if (valType === 'string' || valType === 'number') {

            // strings should be checked for hash tokens
            if (valType === 'string') {
                // We need to make sure we aren't doing a context look up `${#}`
                val = val.replace('${#}', valName);
            }

            // process with a formatter if one exists
            if (obj.formatter) {
                formatterFn = {}.toString.call(obj.formatter) === '[object Function]' ? obj.formatter : this.formatters[obj.formatter];

                if (formatterFn) {
                    val = formatterFn.call(this, val, this.locale);
                }
            }

            // sandwich
            val = (obj.prefix || '') + val + (obj.postfix || '');
        }

        return val;
    };

    /**
     Registers localization data for a particular locale.
     The format is:

     ```
     {
        locale: 'the locale',
        messageformat: {
            // This function takes a number (count) and turns it into a
            // pluralization group (e.g. 'one', 'few', 'many', 'other').
            pluralFunction: function(count) { return 'plural group' }
        }
     }
     ```

     @method __addLocaleData
     @param {Object} The locale data as described above.
     @return {nothing}
     */
    MessageFormat.__addLocaleData = function(data) {

        // if there isn't a default locale set, set it out of the data.locale
        if (DEFAULT_LOCALE === null) {
            DEFAULT_LOCALE = data.locale || null;
        }

        localeData[data.locale] = data.messageformat;
    };

    return MessageFormat;
});

<|endoftext|>


<commit_before>'use strict';

/**
 * A typeahead component for inputs
 * @class Suggestions
 *
 * @param {HTMLInputElement} el A valid HTML input element
 * @param {Array} data An array of data used for results
 * @param {Object} options
 * @param {Number} [options.limit=5] Max number of results to display in the auto suggest list.
 * @param {Number} [options.minLength=2] Number of characters typed into an input to trigger suggestions.
 * @return {Suggestions} `this`
 * @example
 * // in the browser
 * var input = document.querySelector('input');
 * var data = [
 *   'Roy Eldridge',
 *   'Roy Hargrove',
 *   'Rex Stewart'
 * ];
 *
 * new Suggestions(input, data);
 *
 * // with options
 * var input = document.querySelector('input');
 * var data = [{
 *   name: 'Roy Eldridge',
 *   year: 1911
 * }, {
 *   name: 'Roy Hargrove',
 *   year: 1969
 * }, {
 *   name: 'Rex Stewart',
 *   year: 1907
 * }];
 *
 * var typeahead = new Suggestions(input, data, {
 *   minLength: 3, // Number of characters typed into an input to trigger suggestions.
 *   limit: 3 //  Max number of results to display.
 * });
 *
 * // As we're passing an object of an arrays as data, override
 * // `getItemValue` by specifying the specific property to search on.
 * typeahead.getItemValue = function(item) { return item.name };
 *
 * input.addEventListener('change', function() {
 *   console.log(typeahead.selected); // Current selected item.
 * });
 *
 * // With browserify
 * var Suggestions = require('suggestions');
 *
 * new Suggestions(input, data);
 */
var Suggestions = require('./src/suggestions');

function exportFn(el, data, options) {
  return new Suggestions(el, data, options);
}

window.Suggestions = module.exports = exportFn;
<commit_msg>Export suggestions as a class<commit_after>'use strict';

/**
 * A typeahead component for inputs
 * @class Suggestions
 *
 * @param {HTMLInputElement} el A valid HTML input element
 * @param {Array} data An array of data used for results
 * @param {Object} options
 * @param {Number} [options.limit=5] Max number of results to display in the auto suggest list.
 * @param {Number} [options.minLength=2] Number of characters typed into an input to trigger suggestions.
 * @return {Suggestions} `this`
 * @example
 * // in the browser
 * var input = document.querySelector('input');
 * var data = [
 *   'Roy Eldridge',
 *   'Roy Hargrove',
 *   'Rex Stewart'
 * ];
 *
 * new Suggestions(input, data);
 *
 * // with options
 * var input = document.querySelector('input');
 * var data = [{
 *   name: 'Roy Eldridge',
 *   year: 1911
 * }, {
 *   name: 'Roy Hargrove',
 *   year: 1969
 * }, {
 *   name: 'Rex Stewart',
 *   year: 1907
 * }];
 *
 * var typeahead = new Suggestions(input, data, {
 *   minLength: 3, // Number of characters typed into an input to trigger suggestions.
 *   limit: 3 //  Max number of results to display.
 * });
 *
 * // As we're passing an object of an arrays as data, override
 * // `getItemValue` by specifying the specific property to search on.
 * typeahead.getItemValue = function(item) { return item.name };
 *
 * input.addEventListener('change', function() {
 *   console.log(typeahead.selected); // Current selected item.
 * });
 *
 * // With browserify
 * var Suggestions = require('suggestions');
 *
 * new Suggestions(input, data);
 */
var Suggestions = require('./src/suggestions');
window.Suggestions = module.exports = Suggestions;
<|endoftext|>


<commit_before>/*
*   File:       index.js (pdffiller)
*   Project:    PDF Filler
*   Date:       May 2015.
*
*   Description: This PDF filler module takes a data set and creates a filled out
*                PDF file with the form fields populated.
*/
(function(){
    var child_process = require('child_process'),
        execFile = require('child_process').execFile,
        fdf = require('utf8-fdf-generator'),
        _ = require('lodash'),
        fs = require('fs');

    var pdffiller = {

        mapForm2PDF: function( formFields, convMap ){
            var tmpFDFData = this.convFieldJson2FDF(formFields);
            tmpFDFData = _.mapKeys(tmpFDFData, function(value, key){
                try {
                    convMap[key];
                } catch(err){

                    return key;
                }
                return convMap[key];
            });

            return tmpFDFData;
        },

        convFieldJson2FDF: function(fieldJson){
            var _keys = _.pluck(fieldJson, 'title'),
                _values = _.pluck(fieldJson, 'fieldValue');

            _values = _.map(_values, function(val){
                if(val === true){
                    return 'Yes';
                }else if(val === false) {
                    return 'Off';
                }
                return val;
            });

            var jsonObj = _.zipObject(_keys, _values);

            return jsonObj;
        },

        generateFieldJson: function( sourceFile, nameRegex, callback){
            var regName = /FieldName: ([^\n]*)/,
                regType = /FieldType: ([A-Za-z\t .]+)/,
                regFlags = /FieldFlags: ([0-9\t .]+)/,
                fieldArray = [],
                currField = {};

            if(nameRegex !== null && (typeof nameRegex) == 'object' ) regName = nameRegex;

            execFile( "pdftk", [sourceFile, "dump_data_fields_utf8"], function (error, stdout, stderr) {
                if (error) {
                    console.log('exec error: ' + error);
                    return callback(error, null);
                }

                fields = stdout.toString().split("---").slice(1);
                fields.forEach(function(field){
                    currField = {};

                    currField['title'] = field.match(regName)[1].trim() || '';

                    if(field.match(regType)){
                        currField['fieldType'] = field.match(regType)[1].trim() || '';
                    }else {
                        currField['fieldType'] = '';
                    }

                    if(field.match(regFlags)){
                        currField['fieldFlags'] = field.match(regFlags)[1].trim()|| '';
                    }else{
                        currField['fieldFlags'] = '';
                    }

                    currField['fieldValue'] = '';

                    fieldArray.push(currField);
                });

                return callback(null, fieldArray);
            });
        },

        generateFDFTemplate: function( sourceFile, nameRegex, callback ){
            this.generateFieldJson(sourceFile, nameRegex, function(err, _form_fields){
                if (err) {
                  console.log('exec error: ' + err);
                  return callback(err, null);
                }

                return callback(null, convFieldJson2FDF(_form_fields));

            });
        },

        fillFormWithFlatten: function( sourceFile, destinationFile, fieldValues, shouldFlatten,  callback ) {

            //Generate the data from the field values.
            var tempFDF = "data" + (new Date().getTime()) + ".fdf",
                formData = fdf.generator( fieldValues, tempFDF );

            var args = [sourceFile, "fill_form", tempFDF, "output", destinationFile];
            if (shouldFlatten) {
                args.push("flatten");
            }
            execFile( "pdftk", args, function (error, stdout, stderr) {

                if ( error ) {
                    console.log('exec error: ' + error);
                    return callback(error);
                }
                //Delete the temporary fdf file.
                fs.unlink( tempFDF, function( err ) {

                    if ( err ) {
                        return callback(err);
                    }
                    // console.log( 'Sucessfully deleted temp file ' + tempFDF );
                    return callback();
                });
            } );
        },

        fillForm: function( sourceFile, destinationFile, fieldValues, callback) {
            this.fillFormWithFlatten( sourceFile, destinationFile, fieldValues, true, callback);
        }

    };

    module.exports = pdffiller;

}())
<commit_msg>added temp suffix to fdf to alert user<commit_after>/*
*   File:       index.js (pdffiller)
*   Project:    PDF Filler
*   Date:       May 2015.
*
*   Description: This PDF filler module takes a data set and creates a filled out
*                PDF file with the form fields populated.
*/
(function(){
    var child_process = require('child_process'),
        execFile = require('child_process').execFile,
        fdf = require('utf8-fdf-generator'),
        _ = require('lodash'),
        fs = require('fs');

    var pdffiller = {

        mapForm2PDF: function( formFields, convMap ){
            var tmpFDFData = this.convFieldJson2FDF(formFields);
            tmpFDFData = _.mapKeys(tmpFDFData, function(value, key){
                try {
                    convMap[key];
                } catch(err){

                    return key;
                }
                return convMap[key];
            });

            return tmpFDFData;
        },

        convFieldJson2FDF: function(fieldJson){
            var _keys = _.pluck(fieldJson, 'title'),
                _values = _.pluck(fieldJson, 'fieldValue');

            _values = _.map(_values, function(val){
                if(val === true){
                    return 'Yes';
                }else if(val === false) {
                    return 'Off';
                }
                return val;
            });

            var jsonObj = _.zipObject(_keys, _values);

            return jsonObj;
        },

        generateFieldJson: function( sourceFile, nameRegex, callback){
            var regName = /FieldName: ([^\n]*)/,
                regType = /FieldType: ([A-Za-z\t .]+)/,
                regFlags = /FieldFlags: ([0-9\t .]+)/,
                fieldArray = [],
                currField = {};

            if(nameRegex !== null && (typeof nameRegex) == 'object' ) regName = nameRegex;

            execFile( "pdftk", [sourceFile, "dump_data_fields_utf8"], function (error, stdout, stderr) {
                if (error) {
                    console.log('exec error: ' + error);
                    return callback(error, null);
                }

                fields = stdout.toString().split("---").slice(1);
                fields.forEach(function(field){
                    currField = {};

                    currField['title'] = field.match(regName)[1].trim() || '';

                    if(field.match(regType)){
                        currField['fieldType'] = field.match(regType)[1].trim() || '';
                    }else {
                        currField['fieldType'] = '';
                    }

                    if(field.match(regFlags)){
                        currField['fieldFlags'] = field.match(regFlags)[1].trim()|| '';
                    }else{
                        currField['fieldFlags'] = '';
                    }

                    currField['fieldValue'] = '';

                    fieldArray.push(currField);
                });

                return callback(null, fieldArray);
            });
        },

        generateFDFTemplate: function( sourceFile, nameRegex, callback ){
            this.generateFieldJson(sourceFile, nameRegex, function(err, _form_fields){
                if (err) {
                  console.log('exec error: ' + err);
                  return callback(err, null);
                }

                return callback(null, convFieldJson2FDF(_form_fields));

            });
        },

        fillFormWithFlatten: function( sourceFile, destinationFile, fieldValues, shouldFlatten,  callback ) {

            //Generate the temporary data from the field values.
            var tempFDF = "temporary_" + (new Date().getTime()) + ".fdf",
                formData = fdf.generator( fieldValues, tempFDF );

            var args = [sourceFile, "fill_form", tempFDF, "output", destinationFile];
            if (shouldFlatten) {
                args.push("flatten");
            }
            execFile( "pdftk", args, function (error, stdout, stderr) {

                if ( error ) {
                    console.log('exec error: ' + error);
                    return callback(error);
                }
                //Delete the temporary fdf file.
                fs.unlink( tempFDF, function( err ) {

                    if ( err ) {
                        return callback(err);
                    }
                    // console.log( 'Sucessfully deleted temp file ' + tempFDF );
                    return callback();
                });
            } );
        },

        fillForm: function( sourceFile, destinationFile, fieldValues, callback) {
            this.fillFormWithFlatten( sourceFile, destinationFile, fieldValues, true, callback);
        }

    };

    module.exports = pdffiller;

}())
<|endoftext|>


<commit_before>/**
 * Web services logging with s3 integration.
 *
 * @author Wells Johnston <wells@littlstar.com>
 */

'use strict'

const morgan = require('morgan');
const through = require('through');
const S3Transport = require('./lib/S3Transport');
const levels = ['access', 'log', 'info', 'warn', 'debug', 'error'];

class Lager {

  /**
   * @constructor
   * @param {Object} opts
   * @param {Array} [opts.levels]
   * @param {Array} [opts.transports]
   */

  constructor(opts) {
    this.levels = opts.levels || levels;
    opts.transports = opts.transports || [];

    if (opts.transports != null) {
      this.transports = opts.transports.map(transportOpts => {
        if (transportOpts.type == 's3') {
          transportOpts.aws = transportOpts.aws || opts.aws || null;
          return new S3Transport(transportOpts);
        }
      });
    }

    var self = this;
    this.accessStream = through(function(line) {
      if (line != null && line[0] != null) {
        this.push(line.trim());
        self.access(line.trim());
      }
    });
  }

  /**
   * Enables access logging middleware for Express.
   */

  accessLogMiddleware() {
    return morgan('combined', { stream: this.accessStream });
  }

  /**
   * Enables a log level.
   * @param {String} level The logging level to enable.
   */

  enable(level) {
    if (!this.isEnabled(level)) {
      this.levels.push(level);
    }
  }

  /**
   * Disables a log level.
   * @param {String} level The logging level to disable.
   */

  disable(level) {
    while (this.isEnabled(level)) {
      this.levels.splice(this.levels.indexOf(level), 1);
    }
  }

  /**
   * @param {String} level
   * @return {Boolean} Whether the level is enabled on this instance.
   */

  isEnabled(level) {
    return this.levels.indexOf(level) >= 0;
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  log() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('log', args);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  access(accessLog) {
    this.transport('access', accessLog);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  info() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('info', args);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  warn() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('warn', args);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  debug() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('debug', args);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  error() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('error', args);
  }

  /**
   * Send the log to different transports.
   * @param {String} level The logging level.
   * @param {Array} entries An array of strings to put in the log.
   */

  transport(level, entries) {
    var entry;

    if (!this.isEnabled(level)) {
      return;
    }

    if (level != 'access') {
      let timestamp = new Date().toJSON();
      entries = entries.map(e => {
        return typeof e == 'object' ? JSON.stringify(e, null, 2) : e;
      });
      entry = [timestamp, level.toUpperCase(), entries.join(' ')].join('\t');
    } else {
      // if it's an access log, it's already formatted
      entry = entries;
    }

    // send log to stdout / stderr
    if (level == 'access' || level == 'log' || level == 'info' || level == 'debug') {
      console.log(entry);
    } else if (level == 'warn' || level == 'error') {
      console.error(entry);
    }

    // log to each of the transports
    this.transports.forEach(t => {
      t.log(level, entry);
    });
  }

}

module.exports = Lager;
<commit_msg>formatting<commit_after>/**
 * Web services logging with s3 integration.
 *
 * @author Wells Johnston <wells@littlstar.com>
 */

'use strict'

const morgan = require('morgan');
const through = require('through');
const S3Transport = require('./lib/S3Transport');
const levels = ['access', 'log', 'info', 'warn', 'debug', 'error'];

class Lager {

  /**
   * @constructor
   * @param {Object} opts
   * @param {Array} [opts.levels]
   * @param {Array} [opts.transports]
   */

  constructor(opts) {
    this.levels = opts.levels || levels;
    opts.transports = opts.transports || [];

    if (opts.transports != null) {
      this.transports = opts.transports.map(transportOpts => {
        if (transportOpts.type == 's3') {
          transportOpts.aws = transportOpts.aws || opts.aws || null;
          return new S3Transport(transportOpts);
        }
      });
    }

    var self = this;
    this.accessStream = through(function(line) {
      if (line != null && line[0] != null) {
        this.push(line.trim());
        self.access(line.trim());
      }
    });
  }

  /**
   * Enables access logging middleware for Express.
   */

  accessLogMiddleware() {
    return morgan('combined', { stream: this.accessStream });
  }

  /**
   * Enables a log level.
   * @param {String} level The logging level to enable.
   */

  enable(level) {
    if (!this.isEnabled(level)) {
      this.levels.push(level);
    }
  }

  /**
   * Disables a log level.
   * @param {String} level The logging level to disable.
   */

  disable(level) {
    while (this.isEnabled(level)) {
      this.levels.splice(this.levels.indexOf(level), 1);
    }
  }

  /**
   * @param {String} level
   * @return {Boolean} Whether the level is enabled on this instance.
   */

  isEnabled(level) {
    return this.levels.indexOf(level) >= 0;
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  log() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('log', args);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  access(accessLog) {
    this.transport('access', accessLog);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  info() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('info', args);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  warn() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('warn', args);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  debug() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('debug', args);
  }

  /**
   * @param {...*} args Any number of arguments of any type to be logged
   */

  error() {
    let args = Array.prototype.slice.call(arguments);
    this.transport('error', args);
  }

  /**
   * Send the log to different transports.
   * @param {String} level The logging level.
   * @param {Array} entries An array of strings to put in the log.
   */

  transport(level, entries) {

    if (!this.isEnabled(level)) return;
    let entry = null;

    if (level != 'access') {
      let timestamp = new Date().toJSON();
      entries = entries.map(e => {
        return typeof e == 'object' ? JSON.stringify(e, null, 2) : e;
      });
      entry = [timestamp, level.toUpperCase(), entries.join(' ')].join('\t');
    } else {

      /* if it's an access log, it's already formatted */
      entry = entries;
    }

    /* send log to stdout or stderr */
    if (level == 'access' || level == 'log' || level == 'info' || level == 'debug') {
      console.log(entry);
    } else if (level == 'warn' || level == 'error') {
      console.error(entry);
    }

    /* log to each of the transports */
    this.transports.forEach(t => {
      t.log(level, entry);
    });
  }

}

module.exports = Lager;
<|endoftext|>


<commit_before>var jws = require('jws');
var ms = require('ms');
var timespan = require('./lib/timespan');
var xtend = require('xtend');

var JWT = module.exports;

var JsonWebTokenError = JWT.JsonWebTokenError = require('./lib/JsonWebTokenError');
var NotBeforeError = module.exports.NotBeforeError = require('./lib/NotBeforeError');
var TokenExpiredError = JWT.TokenExpiredError = require('./lib/TokenExpiredError');

JWT.decode = function (jwt, options) {
  options = options || {};
  var decoded = jws.decode(jwt, options);
  if (!decoded) { return null; }
  var payload = decoded.payload;

  //try parse the payload
  if(typeof payload === 'string') {
    try {
      var obj = JSON.parse(payload);
      if(typeof obj === 'object') {
        payload = obj;
      }
    } catch (e) { }
  }

  //return header if `complete` option is enabled.  header includes claims
  //such as `kid` and `alg` used to select the key within a JWKS needed to
  //verify the signature
  if (options.complete === true) {
    return {
      header: decoded.header,
      payload: payload,
      signature: decoded.signature
    };
  }
  return payload;
};

var payload_options = [
  'expiresIn',
  'notBefore',
  'expiresInMinutes',
  'expiresInSeconds',
  'audience',
  'issuer',
  'subject',
  'jwtid'
];

JWT.sign = function(payload, secretOrPrivateKey, options, callback) {
  options = options || {};
  var header = {};

  if (typeof payload === 'object') {
    header.typ = 'JWT';
    payload = xtend(payload);
  } else {
    var invalid_option = payload_options.filter(function (key) {
      return typeof options[key] !== 'undefined';
    })[0];

    if (invalid_option) {
      console.warn('invalid "' + invalid_option + '" option for ' + (typeof payload) + ' payload');
    }
  }

  header.alg = options.algorithm || 'HS256';

  if (options.headers) {
    Object.keys(options.headers).forEach(function (k) {
      header[k] = options.headers[k];
    });
  }

  var timestamp = Math.floor(Date.now() / 1000);
  if (!options.noTimestamp) {
    if (typeof payload.iat !== 'undefined' && typeof payload.iat !== 'number') {
      throw new Error('"iat" if present should be a number');
    }
    payload.iat = payload.iat || timestamp;
  }

  if (typeof options.notBefore !== 'undefined') {
    payload.nbf = timespan(options.notBefore);
    if (typeof payload.nbf === 'undefined') {
      throw new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
    }
  }

  if (options.expiresInSeconds || options.expiresInMinutes) {
    var deprecated_line;
    try {
      deprecated_line = /.*\((.*)\).*/.exec((new Error()).stack.split('\n')[2])[1];
    } catch(err) {
      deprecated_line = '';
    }

    console.warn('jsonwebtoken: expiresInMinutes and expiresInSeconds is deprecated. (' + deprecated_line + ')\n' +
                 'Use "expiresIn" expressed in seconds.');

    var expiresInSeconds = options.expiresInMinutes ?
        options.expiresInMinutes * 60 :
        options.expiresInSeconds;

    payload.exp = timestamp + expiresInSeconds;
  } else if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') {
    payload.exp = timespan(options.expiresIn);
    if (typeof payload.exp === 'undefined') {
      throw new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
    }
  }

  if (options.audience)
    payload.aud = options.audience;

  if (options.issuer)
    payload.iss = options.issuer;

  if (options.subject)
    payload.sub = options.subject;

  if (options.jwtid)
    payload.jti = options.jwtid;

  var encoding = 'utf8';
  if (options.encoding) {
    encoding = options.encoding;
  }

  if(typeof callback === 'function') {
    jws.createSign({
      header: header,
      privateKey: secretOrPrivateKey,
      payload: JSON.stringify(payload)
    }).on('done', callback);
  } else {
    return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
  }
};

JWT.verify = function(jwtString, secretOrPublicKey, options, callback) {
  if ((typeof options === 'function') && !callback) {
    callback = options;
    options = {};
  }

  if (!options) options = {};

  var done;

  if (callback) {
    done = function() {
      var args = Array.prototype.slice.call(arguments, 0);
      return process.nextTick(function() {
        callback.apply(null, args);
      });
    };
  } else {
    done = function(err, data) {
      if (err) throw err;
      return data;
    };
  }

  if (!jwtString){
    return done(new JsonWebTokenError('jwt must be provided'));
  }

  var parts = jwtString.split('.');

  if (parts.length !== 3){
    return done(new JsonWebTokenError('jwt malformed'));
  }

  if (parts[2].trim() === '' && secretOrPublicKey){
    return done(new JsonWebTokenError('jwt signature is required'));
  }

  if (!secretOrPublicKey) {
    return done(new JsonWebTokenError('secret or public key must be provided'));
  }

  if (!options.algorithms) {
    options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') ||
                         ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ?
                          [ 'RS256','RS384','RS512','ES256','ES384','ES512' ] :
                         ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ?
                          [ 'RS256','RS384','RS512' ] :
                          [ 'HS256','HS384','HS512' ];

  }

  var decodedToken;
  try {
    decodedToken = jws.decode(jwtString);
  } catch(err) {
    return done(new JsonWebTokenError('invalid token'));
  }

  if (!decodedToken) {
    return done(new JsonWebTokenError('invalid token'));
  }

  var header = decodedToken.header;

  if (!~options.algorithms.indexOf(header.alg)) {
    return done(new JsonWebTokenError('invalid algorithm'));
  }

  var valid;

  try {
    valid = jws.verify(jwtString, header.alg, secretOrPublicKey);
  } catch (e) {
    return done(e);
  }

  if (!valid)
    return done(new JsonWebTokenError('invalid signature'));

  var payload;

  try {
    payload = JWT.decode(jwtString);
  } catch(err) {
    return done(err);
  }

  if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) {
    if (typeof payload.nbf !== 'number') {
      return done(new JsonWebTokenError('invalid nbf value'));
    }
    if (payload.nbf > Math.floor(Date.now() / 1000) + (options.clockTolerance || 0)) {
      return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000)));
    }
  }

  if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) {
    if (typeof payload.exp !== 'number') {
      return done(new JsonWebTokenError('invalid exp value'));
    }
    if (Math.floor(Date.now() / 1000) >= payload.exp + (options.clockTolerance || 0))
      return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000)));
  }

  if (options.audience) {
    var audiences = Array.isArray(options.audience)? options.audience : [options.audience];
    var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];

    var match = target.some(function(aud) { return audiences.indexOf(aud) != -1; });

    if (!match)
      return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or ')));
  }

  if (options.issuer) {
    var invalid_issuer =
        (typeof options.issuer === 'string' && payload.iss !== options.issuer) ||
        (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1);

    if (invalid_issuer) {
      return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer));
    }
  }

  if (options.subject) {
    if (payload.sub !== options.subject) {
      return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject));
    }
  }

  if (options.jwtid) {
    if (payload.jti !== options.jwtid) {
      return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid));
    }
  }

  if (options.maxAge) {
    var maxAge = ms(options.maxAge);
    if (typeof payload.iat !== 'number') {
      return done(new JsonWebTokenError('iat required when maxAge is specified'));
    }
    if (Date.now() - (payload.iat * 1000) > maxAge + (options.clockTolerance || 0)) {
      return done(new TokenExpiredError('maxAge exceeded', new Date(payload.iat * 1000 + maxAge)));
    }
  }

  return done(null, payload);
};
<commit_msg>maxAge is in milliseconds, not seconds<commit_after>var jws = require('jws');
var ms = require('ms');
var timespan = require('./lib/timespan');
var xtend = require('xtend');

var JWT = module.exports;

var JsonWebTokenError = JWT.JsonWebTokenError = require('./lib/JsonWebTokenError');
var NotBeforeError = module.exports.NotBeforeError = require('./lib/NotBeforeError');
var TokenExpiredError = JWT.TokenExpiredError = require('./lib/TokenExpiredError');

JWT.decode = function (jwt, options) {
  options = options || {};
  var decoded = jws.decode(jwt, options);
  if (!decoded) { return null; }
  var payload = decoded.payload;

  //try parse the payload
  if(typeof payload === 'string') {
    try {
      var obj = JSON.parse(payload);
      if(typeof obj === 'object') {
        payload = obj;
      }
    } catch (e) { }
  }

  //return header if `complete` option is enabled.  header includes claims
  //such as `kid` and `alg` used to select the key within a JWKS needed to
  //verify the signature
  if (options.complete === true) {
    return {
      header: decoded.header,
      payload: payload,
      signature: decoded.signature
    };
  }
  return payload;
};

var payload_options = [
  'expiresIn',
  'notBefore',
  'expiresInMinutes',
  'expiresInSeconds',
  'audience',
  'issuer',
  'subject',
  'jwtid'
];

JWT.sign = function(payload, secretOrPrivateKey, options, callback) {
  options = options || {};
  var header = {};

  if (typeof payload === 'object') {
    header.typ = 'JWT';
    payload = xtend(payload);
  } else {
    var invalid_option = payload_options.filter(function (key) {
      return typeof options[key] !== 'undefined';
    })[0];

    if (invalid_option) {
      console.warn('invalid "' + invalid_option + '" option for ' + (typeof payload) + ' payload');
    }
  }

  header.alg = options.algorithm || 'HS256';

  if (options.headers) {
    Object.keys(options.headers).forEach(function (k) {
      header[k] = options.headers[k];
    });
  }

  var timestamp = Math.floor(Date.now() / 1000);
  if (!options.noTimestamp) {
    if (typeof payload.iat !== 'undefined' && typeof payload.iat !== 'number') {
      throw new Error('"iat" if present should be a number');
    }
    payload.iat = payload.iat || timestamp;
  }

  if (typeof options.notBefore !== 'undefined') {
    payload.nbf = timespan(options.notBefore);
    if (typeof payload.nbf === 'undefined') {
      throw new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
    }
  }

  if (options.expiresInSeconds || options.expiresInMinutes) {
    var deprecated_line;
    try {
      deprecated_line = /.*\((.*)\).*/.exec((new Error()).stack.split('\n')[2])[1];
    } catch(err) {
      deprecated_line = '';
    }

    console.warn('jsonwebtoken: expiresInMinutes and expiresInSeconds is deprecated. (' + deprecated_line + ')\n' +
                 'Use "expiresIn" expressed in seconds.');

    var expiresInSeconds = options.expiresInMinutes ?
        options.expiresInMinutes * 60 :
        options.expiresInSeconds;

    payload.exp = timestamp + expiresInSeconds;
  } else if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') {
    payload.exp = timespan(options.expiresIn);
    if (typeof payload.exp === 'undefined') {
      throw new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60');
    }
  }

  if (options.audience)
    payload.aud = options.audience;

  if (options.issuer)
    payload.iss = options.issuer;

  if (options.subject)
    payload.sub = options.subject;

  if (options.jwtid)
    payload.jti = options.jwtid;

  var encoding = 'utf8';
  if (options.encoding) {
    encoding = options.encoding;
  }

  if(typeof callback === 'function') {
    jws.createSign({
      header: header,
      privateKey: secretOrPrivateKey,
      payload: JSON.stringify(payload)
    }).on('done', callback);
  } else {
    return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding});
  }
};

JWT.verify = function(jwtString, secretOrPublicKey, options, callback) {
  if ((typeof options === 'function') && !callback) {
    callback = options;
    options = {};
  }

  if (!options) options = {};

  var done;

  if (callback) {
    done = function() {
      var args = Array.prototype.slice.call(arguments, 0);
      return process.nextTick(function() {
        callback.apply(null, args);
      });
    };
  } else {
    done = function(err, data) {
      if (err) throw err;
      return data;
    };
  }

  if (!jwtString){
    return done(new JsonWebTokenError('jwt must be provided'));
  }

  var parts = jwtString.split('.');

  if (parts.length !== 3){
    return done(new JsonWebTokenError('jwt malformed'));
  }

  if (parts[2].trim() === '' && secretOrPublicKey){
    return done(new JsonWebTokenError('jwt signature is required'));
  }

  if (!secretOrPublicKey) {
    return done(new JsonWebTokenError('secret or public key must be provided'));
  }

  if (!options.algorithms) {
    options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') ||
                         ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ?
                          [ 'RS256','RS384','RS512','ES256','ES384','ES512' ] :
                         ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ?
                          [ 'RS256','RS384','RS512' ] :
                          [ 'HS256','HS384','HS512' ];

  }

  var decodedToken;
  try {
    decodedToken = jws.decode(jwtString);
  } catch(err) {
    return done(new JsonWebTokenError('invalid token'));
  }

  if (!decodedToken) {
    return done(new JsonWebTokenError('invalid token'));
  }

  var header = decodedToken.header;

  if (!~options.algorithms.indexOf(header.alg)) {
    return done(new JsonWebTokenError('invalid algorithm'));
  }

  var valid;

  try {
    valid = jws.verify(jwtString, header.alg, secretOrPublicKey);
  } catch (e) {
    return done(e);
  }

  if (!valid)
    return done(new JsonWebTokenError('invalid signature'));

  var payload;

  try {
    payload = JWT.decode(jwtString);
  } catch(err) {
    return done(err);
  }

  if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) {
    if (typeof payload.nbf !== 'number') {
      return done(new JsonWebTokenError('invalid nbf value'));
    }
    if (payload.nbf > Math.floor(Date.now() / 1000) + (options.clockTolerance || 0)) {
      return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000)));
    }
  }

  if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) {
    if (typeof payload.exp !== 'number') {
      return done(new JsonWebTokenError('invalid exp value'));
    }
    if (Math.floor(Date.now() / 1000) >= payload.exp + (options.clockTolerance || 0))
      return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000)));
  }

  if (options.audience) {
    var audiences = Array.isArray(options.audience)? options.audience : [options.audience];
    var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud];

    var match = target.some(function(aud) { return audiences.indexOf(aud) != -1; });

    if (!match)
      return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or ')));
  }

  if (options.issuer) {
    var invalid_issuer =
        (typeof options.issuer === 'string' && payload.iss !== options.issuer) ||
        (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1);

    if (invalid_issuer) {
      return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer));
    }
  }

  if (options.subject) {
    if (payload.sub !== options.subject) {
      return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject));
    }
  }

  if (options.jwtid) {
    if (payload.jti !== options.jwtid) {
      return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid));
    }
  }

  if (options.maxAge) {
    var maxAge = ms(options.maxAge);
    if (typeof payload.iat !== 'number') {
      return done(new JsonWebTokenError('iat required when maxAge is specified'));
    }
    if (Date.now() - (payload.iat * 1000) > maxAge + (options.clockTolerance || 0) * 1000) {
      return done(new TokenExpiredError('maxAge exceeded', new Date(payload.iat * 1000 + maxAge)));
    }
  }

  return done(null, payload);
};
<|endoftext|>


<commit_before>/***********************8
Deals with importing and exporting
************************/

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // Great success! All the File APIs are supported.
  document.getElementById('importDisplayError').innerHTML = 'Import supported.';
} else {
  document.getElementById('importDisplayError').innerHTML = 'Importing and Exporting are not fully supported in this browser.';
}

function importView(){

	var fileInput = document.getElementById('fileInput');
	var fileDisplayArea = document.getElementById('fileDisplayArea');

	fileInput.addEventListener('change', function(e) {
		var file = fileInput.files[0];
		var fileTypes = ['lif', 'cells'];

		var extension = file.name.split('.').pop().toLowerCase(),  //file extension from input file
	    validExtension = fileTypes.indexOf(extension) > -1;  //is extension in acceptable types

		if (validExtension) {
			var reader = new FileReader();

			reader.onload = function(e) {
				fileDisplayArea.innerText = reader.result;
				display(reader.result);

				newMat = extractMat(reader.result);

			}

			reader.readAsText(file);
		} else {
			fileDisplayArea.innerText = "File not supported!"
		}
	});
	function display(content){
				var display = content;
				console.log(display);

	}

	function extractMat(result){
		var lines = result.split('\n');
		var coordinateX = [];
		var coordinateY = [];
		var counterX = 0;
		var counterY = 0;
	    for(var line = 0; line < lines.length; line++){
	      //console.log(lines[line]);
	      /*if(lines[line].charAt(0) != "*" || lines[line].charAt(0) != "O"){
	      	counterX = 0;
	      	counterY = 0;
	      }*/
	      for(var i = 0; i < lines[line].length; i++){

	      	//console.log(lines[line].charAt(i));
	      	if(lines[line].charAt(i) == "."){
	      		counterX++;
	      	} else if(lines[line].charAt(i) == "*" || lines[line].charAt(i) == "O"){
	      		coordinateX[coordinateX.length] = counterX;
	      		coordinateY[coordinateY.length] = counterY;
	      		counterX++;
	      	}
	      	//if(lines[line])

	      }
	      if(lines[line].charAt(0) == "*" || lines[line].charAt(0) == "O" || lines[line].charAt(0) == ".")
	      	counterY++;
	      counterX = 0;

	    }
	    //console.log(coordinateX);
	    //console.log(coordinateY);
	    s = createMatrix(coordinateX.length,coordinateY.length,0);
	    s = toggleCells(coordinateX, coordinateY, s);
	    //Display in console
	    //console.log("Matrix: \n");
		for(var z = 0; z < s.length; z++) {
		 console.log(s[z]);
		}

	    return s;
	}

	function toggleCells(row, col, m){
	    for( var j = 0; j<row.length; j++){
	    	//console.log("x coordinate: " + row[j]);
	    	//console.log("y coordinate: " + col[j]);
				m[row[j]][col[j]] = 1;

	    }

		return m;
	}
}	<commit_msg>bug fix in displaying matrix<commit_after>/***********************8
Deals with importing and exporting
************************/

// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
  // Great success! All the File APIs are supported.
  document.getElementById('importDisplayError').innerHTML = 'Import supported.';
} else {
  document.getElementById('importDisplayError').innerHTML = 'Importing and Exporting are not fully supported in this browser.';
}

function importView(){

	var fileInput = document.getElementById('fileInput');
	var fileDisplayArea = document.getElementById('fileDisplayArea');

	fileInput.addEventListener('change', function(e) {
		var file = fileInput.files[0];
		var fileTypes = ['lif', 'cells'];

		var extension = file.name.split('.').pop().toLowerCase(),  //file extension from input file
	    validExtension = fileTypes.indexOf(extension) > -1;  //is extension in acceptable types

		if (validExtension) {
			var reader = new FileReader();

			reader.onload = function(e) {

				display(reader.result);

				newMat = extractMat(reader.result);
			}
			reader.readAsText(file);
		} else {
			fileDisplayArea.innerText = "File not supported!"
		}
	});
	function display(content){
		fileDisplayArea.innerText = content;
	}

	function extractMat(result){
		var lines = result.split('\n');
		var coordinateX = [];
		var coordinateY = [];
		var counterX = 0;
		var counterY = 0;
	    for(var line = 0; line < lines.length; line++){
	      for(var i = 0; i < lines[line].length; i++){
	      	if(lines[line].charAt(i) == "."){
	      		counterX++;
	      	} else if(lines[line].charAt(i) == "*" || lines[line].charAt(i) == "O"){
	      		coordinateX[coordinateX.length] = counterX;
	      		coordinateY[coordinateY.length] = counterY;
	      		counterX++;
	      	}
	      }
	      if(lines[line].charAt(0) == "*" || lines[line].charAt(0) == "O" || lines[line].charAt(0) == ".")
	      	counterY++;
	      counterX = 0;

	    }

	    s = createMatrix(Math.max.apply(Math,coordinateX)+1,Math.max.apply(Math,coordinateY)+1,0);
	    s = toggleCells(coordinateX, coordinateY, s);

		for(var z = 0; z < s.length; z++) {
		 console.log(s[z]);
		}
	    return s;
	}

	function toggleCells(row, col, m){
	    for( var j = 0; j<row.length; j++){
				m[row[j]][col[j]] = 1;
	    }
		return m;
	}
}	<|endoftext|>


<commit_before>"use strict";

var gulp = require("gulp"),
        path = require("path"),
	gutil = require("gulp-util"),
	through2 = require("through2"),
	util = require("util"),
	fs = require("fs"),
	toposort = require("toposort-class"),
	concat = require("gulp-concat");

module.exports = function(filename, sources) {
	if (!filename) {
		throw new gutil.PluginError("gulp-concat-vendor", "Required parameter filename is missing");
	}

	var mySources = {},
		myLibs = [],
		myFiles = [],
		myInfo = [];

	var bufferContents = function(file, enc, callback) {
		if(file.isStream()) {
			this.emit("error", new gutil.PluginError("gulp-concat-vendor", "Streaming not supported"));
			return callback();
		}

		if(!file.isNull()) {
			myFiles.push(file.path);
			return callback();
		}

		var myPath = util.format("%s/.bower.json", file.path);
		fs.exists(myPath, function(exists) {
  			if (exists) {
				fs.readFile(myPath, "utf8", function(error, data) {
					if(!!error || !data) {
						return callback();
					}

					var myData = JSON.parse(data);

					if(!!myData.main && (path.extname( myData.main ) == '.js' || myData.main.constructor === Array)) {
						var myMain = [].concat(myData.main),
							mySourcePath = util.format("%s/%s", file.path, myMain[0]);

						myInfo.push(myData);
						mySources[myData.name] = mySourcePath;

						callback();
					}
					else {
						console.log(util.format("Skipping library @ %s. Bower.js is missing 'main' property or it is not a JS filetype.", file.path));
						callback();
					}
				});
  			} else {
    			console.log(util.format("Skipping library @ %s. Couldn't find %s", file.path, myPath));
    			callback();
  			}
		});
	};

	var endStream = function() {
		var mySort = new toposort();

		myInfo.forEach(function(data) {
			var myDependencies = [];
			if(!!data.dependencies) {
				myDependencies = Object.keys(data.dependencies);
			}

			mySort.add(data.name, myDependencies);
		});

		myLibs.push.apply(myLibs, mySort.sort().reverse().map(function(name) {
			return mySources[name];
		}));

		myLibs = myLibs.concat(myFiles);

		gulp.src(myLibs)
			.pipe(concat(filename))
			.on("data", function(data) {
				this.push(data);
				this.emit("end");
			}.bind(this));
	}

	return through2.obj(bufferContents, endStream);
};
<commit_msg>handle ignoredDependencies<commit_after>"use strict";

var gulp = require("gulp"),
        path = require("path"),
	gutil = require("gulp-util"),
	through2 = require("through2"),
	util = require("util"),
	fs = require("fs"),
	toposort = require("toposort-class"),
	concat = require("gulp-concat");

module.exports = function(filename, sources) {
	if (!filename) {
		throw new gutil.PluginError("gulp-concat-vendor", "Required parameter filename is missing");
	}

	var mySources = {},
		myLibs = [],
		myFiles = [],
		myInfo = [];

	var bufferContents = function(file, enc, callback) {
		if(file.isStream()) {
			this.emit("error", new gutil.PluginError("gulp-concat-vendor", "Streaming not supported"));
			return callback();
		}

		if(!file.isNull()) {
			myFiles.push(file.path);
			return callback();
		}

		var myPath = util.format("%s/.bower.json", file.path);
		fs.exists(myPath, function(exists) {
  			if (exists) {
				fs.readFile(myPath, "utf8", function(error, data) {
					if(!!error || !data) {
						return callback();
					}

					var myData = JSON.parse(data);

					if(!!myData.main && (path.extname( myData.main ) == '.js' || myData.main.constructor === Array)) {
						var myMain = [].concat(myData.main),
							mySourcePath = util.format("%s/%s", file.path, myMain[0]);

						myInfo.push(myData);
						mySources[myData.name] = mySourcePath;

						callback();
					}
					else {
						console.log(util.format("Skipping library @ %s. Bower.js is missing 'main' property or it is not a JS filetype.", file.path));
						callback();
					}
				});
  			} else {
    			console.log(util.format("Skipping library @ %s. Couldn't find %s", file.path, myPath));
    			callback();
  			}
		});
	};

	var endStream = function() {
		var mySort = new toposort();

		myInfo.forEach(function(data) {
			var myDependencies = [];
			if(!!data.dependencies) {
				myDependencies = Object.keys(data.dependencies);
			}

			mySort.add(data.name, myDependencies);
		});

		myLibs.push.apply(myLibs, mySort.sort().reverse().map(function(name) {
			return mySources[name];
		}));

		myLibs = myLibs.filter(function(n){ return n != undefined });

		myLibs = myLibs.concat(myFiles);

		gulp.src(myLibs)
			.pipe(concat(filename))
			.on("data", function(data) {
				this.push(data);
				this.emit("end");
			}.bind(this));
	}

	return through2.obj(bufferContents, endStream);
};
<|endoftext|>


<commit_before>//filter will reemit the data if cb(err,pass) pass is truthy

// reduce is more tricky
// maybe we want to group the reductions or emit progress updates occasionally
// the most basic reduce just emits one 'data' event after it has recieved 'end'

var Stream = require('stream').Stream

//create an event stream and apply function to each .write
//emitting each response as data
//unless it's an empty callback

module.exports = function (mapper) {
  var stream = new Stream()
    , inputs = 0
    , outputs = 0
    , ended = false
    , paused = false
    , destroyed = false
    , lastWritten = 0

  // Items that are not ready to be written yet (because they would come out of
  // oredr) get stuck in a queue for later.
  var writeQueue = {}

  stream.writable = true
  stream.readable = true

  function queueData (data, number) {
    var nextToWrite = lastWritten + 1

    if (number === nextToWrite) {
      // If it's next, and its not undefined write it
      if (data !== undefined) {
        stream.emit.apply(stream, ['data', data])
      }
      lastWritten ++
      nextToWrite ++
    } else {
      // Otherwise queue it for later.
      writeQueue[number] = data
    }

    // If the next value is in the queue, write it
    if (writeQueue.hasOwnProperty(nextToWrite)) {
      var dataToWrite = writeQueue[nextToWrite]
      delete writeQueue[nextToWrite]
      return queueData(dataToWrite, nextToWrite)
    }

    outputs ++
    if(inputs === outputs) {
      if(paused) paused = false, stream.emit('drain') //written all the incoming events
      if(ended) end()
    }
  }

  function next (err, data, number) {
    if(destroyed) return
    inNext = true
    if(err) {
      return inNext = false, stream.emit.apply(stream, ['error', err])
    }

    queueData(data, number)

    inNext = false
  }

  // Wrap the mapper function by calling its callback with the order number of
  // the item in the stream.
  function wrappedMapper (input, number, callback) {
    return mapper.call(null, input, function(err, data){
      callback(err, data, number)
    })
  }

  stream.write = function (data) {
    if(ended) throw new Error('map stream is not writable')
    var inNext = false
    inputs ++

    try {
      //catch sync errors and handle them like async errors
      var written = wrappedMapper(data, inputs, next)
      paused = (written === false)
      return !paused
    } catch (err) {
      //if the callback has been called syncronously, and the error
      //has occured in an listener, throw it again.
      if(inNext)
        throw err
      next(err)
      return !paused
    }
  }

  function end (data) {
    //if end was called with args, write it,
    ended = true //write will emit 'end' if ended is true
    stream.writable = false
    if(data !== undefined) {
      return queueData(data, inputs)
    } else if (inputs == outputs) { //wait for processing
      stream.readable = false, stream.emit('end'), stream.destroy()
    }
  }

  stream.end = function (data) {
    if(ended) return
    end()
  }

  stream.destroy = function () {
    ended = destroyed = true
    stream.writable = stream.readable = paused = false
    process.nextTick(function () {
      stream.emit('close')
    })
  }
  stream.pause = function () {
    paused = true
  }

  stream.resume = function () {
    paused = false
  }

  return stream
}

<commit_msg>fix typo in comment<commit_after>//filter will reemit the data if cb(err,pass) pass is truthy

// reduce is more tricky
// maybe we want to group the reductions or emit progress updates occasionally
// the most basic reduce just emits one 'data' event after it has recieved 'end'

var Stream = require('stream').Stream

//create an event stream and apply function to each .write
//emitting each response as data
//unless it's an empty callback

module.exports = function (mapper) {
  var stream = new Stream()
    , inputs = 0
    , outputs = 0
    , ended = false
    , paused = false
    , destroyed = false
    , lastWritten = 0

  // Items that are not ready to be written yet (because they would come out of
  // order) get stuck in a queue for later.
  var writeQueue = {}

  stream.writable = true
  stream.readable = true

  function queueData (data, number) {
    var nextToWrite = lastWritten + 1

    if (number === nextToWrite) {
      // If it's next, and its not undefined write it
      if (data !== undefined) {
        stream.emit.apply(stream, ['data', data])
      }
      lastWritten ++
      nextToWrite ++
    } else {
      // Otherwise queue it for later.
      writeQueue[number] = data
    }

    // If the next value is in the queue, write it
    if (writeQueue.hasOwnProperty(nextToWrite)) {
      var dataToWrite = writeQueue[nextToWrite]
      delete writeQueue[nextToWrite]
      return queueData(dataToWrite, nextToWrite)
    }

    outputs ++
    if(inputs === outputs) {
      if(paused) paused = false, stream.emit('drain') //written all the incoming events
      if(ended) end()
    }
  }

  function next (err, data, number) {
    if(destroyed) return
    inNext = true
    if(err) {
      return inNext = false, stream.emit.apply(stream, ['error', err])
    }

    queueData(data, number)

    inNext = false
  }

  // Wrap the mapper function by calling its callback with the order number of
  // the item in the stream.
  function wrappedMapper (input, number, callback) {
    return mapper.call(null, input, function(err, data){
      callback(err, data, number)
    })
  }

  stream.write = function (data) {
    if(ended) throw new Error('map stream is not writable')
    var inNext = false
    inputs ++

    try {
      //catch sync errors and handle them like async errors
      var written = wrappedMapper(data, inputs, next)
      paused = (written === false)
      return !paused
    } catch (err) {
      //if the callback has been called syncronously, and the error
      //has occured in an listener, throw it again.
      if(inNext)
        throw err
      next(err)
      return !paused
    }
  }

  function end (data) {
    //if end was called with args, write it,
    ended = true //write will emit 'end' if ended is true
    stream.writable = false
    if(data !== undefined) {
      return queueData(data, inputs)
    } else if (inputs == outputs) { //wait for processing
      stream.readable = false, stream.emit('end'), stream.destroy()
    }
  }

  stream.end = function (data) {
    if(ended) return
    end()
  }

  stream.destroy = function () {
    ended = destroyed = true
    stream.writable = stream.readable = paused = false
    process.nextTick(function () {
      stream.emit('close')
    })
  }
  stream.pause = function () {
    paused = true
  }

  stream.resume = function () {
    paused = false
  }

  return stream
}

<|endoftext|>


<commit_before>module.exports = deepEqual

function deepEqual(a, b) {
  var aKeys
    , bKeys
    , i

  if(a === b) {
    return true
  }

  if(isNan(a) || isNan(b)) {
    return isNan(a) && isNan(b)
  }

  if(typeof a !== 'object' || typeof b !== 'object') {
    return false
  }

  if(a instanceof Date || b instanceof Date) {
    if(a instanceof Date && b instanceof Date) {
      return a.getTime() === b.getTime()
    }

    return false
  }

  if(a instanceof RegExp || b instanceof RegExp) {
    if(a instanceof RegExp && b instanceof RegExp) {
      return RegExp.prototype.toString.call(a) ===
        RegExp.prototype.toString.call(b)
    }

    return false
  }

  if(isArguments(a) || isArguments(b)) {
    if(!isArguments(a) || !isArguments(b)) {
      return false
    }

    return deepEqual([].slice.call(a), [].slice.call(b))
  }

  aKeys = Object.keys(a)
  bKeys = Object.keys(b)

  if(aKeys.length !== bKeys.length) {
    return false
  }

  for(i = 0; i < aKeys.length; i++) {
    var key = aKeys[i]

    if(!deepEqual(a[key], b[key])) {
      return false
    }
  }

  return true
}

function isNan(v) {
  return v !== v
}

function isArguments(o) {
  return Object.prototype.toString.call(o) === '[object Arguments]'
}

function isBuffer (x) {
  if(!x || typeof x !== 'object' || typeof x.length !== 'number' ||
      typeof x.copy !== 'function' || typeof x.slice !== 'function') {
    return false
  }

  if(x.length > 0 && typeof x[0] !== 'number') {
    return false
  }

  return true
}

function buffersEqual(a, b) {
  if(!isBuffer(a) || !isBuffer(b)) {
    return false
  }

  if(a.length !== b.length) {
    return false
  }

  for(var i = 0; i < a.length; i++) {
    if(a[i] !== b[i]) {
      return false
    }
  }

  return true
}<commit_msg>Compare buffers<commit_after>module.exports = deepEqual

function deepEqual(a, b) {
  var aKeys
    , bKeys
    , i

  if(a === b) {
    return true
  }

  if(isNan(a) || isNan(b)) {
    return isNan(a) && isNan(b)
  }

  if(typeof a !== 'object' || typeof b !== 'object') {
    return false
  }

  if(a instanceof Date || b instanceof Date) {
    if(a instanceof Date && b instanceof Date) {
      return a.getTime() === b.getTime()
    }

    return false
  }

  if(a instanceof RegExp || b instanceof RegExp) {
    if(a instanceof RegExp && b instanceof RegExp) {
      return RegExp.prototype.toString.call(a) ===
        RegExp.prototype.toString.call(b)
    }

    return false
  }

  if(isBuffer(a) || isBuffer(b)) {
    return buffersEqual(a, b)
  }

  if(isArguments(a) || isArguments(b)) {
    if(!isArguments(a) || !isArguments(b)) {
      return false
    }

    return deepEqual([].slice.call(a), [].slice.call(b))
  }

  aKeys = Object.keys(a)
  bKeys = Object.keys(b)

  if(aKeys.length !== bKeys.length) {
    return false
  }

  for(i = 0; i < aKeys.length; i++) {
    var key = aKeys[i]

    if(!deepEqual(a[key], b[key])) {
      return false
    }
  }

  return true
}

function isNan(v) {
  return v !== v
}

function isArguments(o) {
  return Object.prototype.toString.call(o) === '[object Arguments]'
}

function isBuffer(x) {
  if(!x || typeof x !== 'object' || typeof x.length !== 'number' ||
      typeof x.copy !== 'function' || typeof x.slice !== 'function') {
    return false
  }

  if(x.length > 0 && typeof x[0] !== 'number') {
    return false
  }

  return true
}

function buffersEqual(a, b) {
  if(!isBuffer(a) || !isBuffer(b)) {
    return false
  }

  if(a.length !== b.length) {
    return false
  }

  for(var i = 0; i < a.length; i++) {
    if(a[i] !== b[i]) {
      return false
    }
  }

  return true
}<|endoftext|>


<commit_before>var less = require('less'),
    Parser = less.Parser,
    path = require('path'),
    fs = require('fs');

var createLessPreprocessor = function (args, config, basePath, logger, helper) {
  var config = config || {},
      options = config.options || {},
      additionalData = config.additionalData || {},
      translatedPaths = Array(),
      log = logger.create('preprocessor:less');

  // provide default values
  options.compress = config.options.compress || false;
  options.save = config.options.save || false;
  options.paths = config.options.paths || Array();

  var transformPath = args.transformPath || config.transformPath || function (filePath) {
    return filePath.replace(/\.less$/, '.css');
  };

  var rendered = function (done, filePath, error, css) {
    if (error !== null && error !== undefined) {
      log.error('Error:%s\n', error);
    } else {
      content = css.toCSS({compress: options.compress})
      if (options.save) {
        var p = path.resolve(filePath.replace(/\/([\.a-zA-Z0-9\-\_]+).css$/, '/'));
        helper.mkdirIfNotExists(p, function () {
          var n = filePath.match(/[a-zA-Z\-\.\_]+.css$/).reverse()[0];
          fs.writeFile(path.join(p, n), content, 'utf-8', function (error) {
            if (error) {
              log.error("Error:%s", error);
            }
            done(content);
          });
        });
      } else {
        done(content);
      }
    }
  };

  return function (content, file, done) {
    file.path = transformPath(file.originalPath);

    options.paths.forEach(function(element, index, array) {
      translatedPaths[index] = basePath + '/' + element;
    });

    var parser = new Parser({
      paths: translatedPaths
    });

    try {
      parser.parse(content, rendered.bind(null, done, file.path), additionalData);
    } catch (error) {
      log.error('%s\n  at %s', error.message, file.originalPath);
      return;
    }
  };
};

createLessPreprocessor.$inject = ['args', 'config.lessPreprocessor', 'config.basePath', 'logger', 'helper'];

// PUBLISH DI MODULE
module.exports = {
  'preprocessor:less': ['factory', createLessPreprocessor]
};
<commit_msg>minor refactoring<commit_after>var less = require('less'),
    Parser = less.Parser,
    path = require('path'),
    fs = require('fs');

var createLessPreprocessor = function (args, config, basePath, logger, helper) {
  var config = config || {},
      options = config.options || {},
      additionalData = config.additionalData || {},
      translatedPaths = Array(),
      log = logger.create('preprocessor:less');

  // provide default values
  options.compress = options.compress || false;
  options.save = options.save || false;
  options.paths = options.paths || Array();

  var transformPath = args.transformPath || config.transformPath || function (filePath) {
    return filePath.replace(/\.less$/, '.css');
  };

  var rendered = function (done, filePath, error, css) {
    if (error !== null && error !== undefined) {
      log.error('Error:%s\n', error);
    } else {
      content = css.toCSS({compress: options.compress})
      if (options.save) {
        var p = path.resolve(filePath.replace(/\/([\.a-zA-Z0-9\-\_]+).css$/, '/'));
        helper.mkdirIfNotExists(p, function () {
          var n = filePath.match(/[a-zA-Z\-\.\_]+.css$/).reverse()[0];
          fs.writeFile(path.join(p, n), content, 'utf-8', function (error) {
            if (error) {
              log.error("Error:%s", error);
            }
            done(content);
          });
        });
      } else {
        done(content);
      }
    }
  };

  return function (content, file, done) {
    file.path = transformPath(file.originalPath);

    options.paths.forEach(function(element, index, array) {
      translatedPaths[index] = basePath + '/' + element;
    });

    var parser = new Parser({
      paths: translatedPaths
    });

    try {
      parser.parse(content, rendered.bind(null, done, file.path), additionalData);
    } catch (error) {
      log.error('%s\n  at %s', error.message, file.originalPath);
      return;
    }
  };
};

createLessPreprocessor.$inject = ['args', 'config.lessPreprocessor', 'config.basePath', 'logger', 'helper'];

// PUBLISH DI MODULE
module.exports = {
  'preprocessor:less': ['factory', createLessPreprocessor]
};
<|endoftext|>


<commit_before>"use strict";

function promisify(fn) {
	return function () {
		var self = this,
		    args = arguments;
		return new Promise(function (res, rej) {
			args[args.length++] = function (err, data) {
				if (err)
					rej(err)
				else
					res(data);
			};
			fn.apply(self, args);
		});
	};
}

module.exports = function (something) {
	switch (typeof something) {
	case 'function':
		return promisify(something);
	default:
		throw TypeError('not a object');
	case 'object':
	}
	var o = {};
	for (var id in something) {
		var f = something[id], arg;
		if (typeof f !== 'function' || !((arg = /^\s*function\s+(?:\w+\s*)?\(\s*(?:[a-z0-9_$]+,\s*)*([^)]*)\s*\)/.exec(f.toString())))) {
			o[id] = f;
			continue;
		}
		var last = arg[1];
		if (last === 'callback' || last === 'callback_' || last === 'cb' || last === 'done')
			o[id] = promisify(f);
		else
			o[id] = f;
	}
	return o;
};
<commit_msg>code compacting<commit_after>"use strict";

function promisify(fn) {
	return function () {
		var self = this,
		    args = Array.prototype.concat.apply([], arguments);
		return new Promise(function (res, rej) {
			args[args.length++] = function (err, data) {
				if (err)
					rej(err)
				else
					res(data);
			};
			fn.apply(self, args);
		});
	};
}

var is_callback_fn = /^\s*function\s+(?:\w+\s*)?\(\s*(?:[a-z0-9_$]+,\s*)*(?:callback_?|cb|done)\s*\)/;

module.exports = function (something) {
	switch (typeof something) {
	case 'function':
		return promisify(something);
	default:
		throw TypeError('not a object');
	case 'object':
	}
	var o = {};
	for (var id in something) {
		var f = something[id];
		o[id] = typeof f === 'function' && is_callback_fn.test(f.toString()) ?
			promisify(f) : f;
	}
	return o;
};
<|endoftext|>