function extendMulti () {
        var args = argsToArray(arguments),
            deep = extractBoolFromArrayStart(args),
            arg0 = args.shift();

        // Extend object `0` with other objects
        args.forEach(function (arg) {
            // Extend `arg0` if `arg` is an object
            if (isObject(arg)) {
                extend(arg0, arg, deep);
            }
        });

        return arg0;
    }

function
extendMulti
(
)
{
var
args
=
argsToArray
(
arguments
)
,
deep
=
extractBoolFromArrayStart
(
args
)
,
arg0
=
args
.
shift
(
)
;
// Extend object `0` with other objects
args
.
forEach
(
function
(
arg
)
{
// Extend `arg0` if `arg` is an object
if
(
isObject
(
arg
)
)
{
extend
(
arg0
,
arg
,
deep
)
;
}
}
)
;
return
arg0
;
}

Extends first object passed in with all other object passed in after.
First param could be a boolean indicating whether or not to perform a deep extend.
Last param could also be a boolean indicating whether to use legacy setters if they are available
on the receiving object.

@example (if last param to passed in to `sjl.extend` is `true`
var o = {setGreeting: v => this.greeting = 'Hello ' + v},
otherObject = {greeting: 'Junior'};
// Calls o.setGreeting when merging otherObject because `true` was passed in
// as the last parameter
sjl.extend(o, otherObject, true);

@function module:sjl.extend
@arg `0`    {Object|Boolean} - If boolean, causes `extend` to perform a deep extend.  Optional.
@arg `1-*`  {Object} - Objects to merge on @arg 0.
@arg `last` {Boolean} - Optional.
@returns    {Object|null} - Returns first object passed in or null if no values were passed in.

Extends first object passed in with all other object passed in after . First param could be a boolean indicating whether or not to perform a deep extend . Last param could also be a boolean indicating whether to use legacy setters if they are available on the receiving object .


function normalizeArgsForDefineSubClass (superClass, constructor, methods, statics) {
        superClass = superClass || Object.create(Object.prototype);

        // Snatched statics
        var _statics;

        // Should extract statics?
        if (isFunction(superClass)) {
            // Extract statics
            _statics = Object.keys(superClass).reduce(function (agg, key) {
                if (key === 'extend' || key === 'extendWith') { return agg; }
                agg[key] = superClass[key];
                return agg;
            }, {});
        }

        // Re-arrange args if constructor is object
        if (isObject(constructor)) {
            statics = methods;
            methods = clone(constructor);
            constructor = ! isFunction(methods.constructor) ? standInConstructor(superClass) : methods.constructor;
            unset(methods, 'constructor');
        }

        // Ensure constructor
        constructor = isset(constructor) ? constructor : standInConstructor(superClass);

        // Returned normalized args
        return {
            constructor: constructor,
            methods: methods,
            statics: extend(_statics || {}, statics || {}, true),
            superClass: superClass
        };
    }

Normalized the parameters required for `defineSubClassPure` and `defineSubClass` to operate.
@param superClass {Function} - Superclass to inherit from.
@param constructor {Function|Object} - Required.  Note:  If this param is an object, then other params shift over by 1 (`methods` becomes `statics` and this param becomes `methods` (constructor key expected else empty stand in constructor is used).
@param methods {Object|undefined} - Methods for prototype.  Optional.  Note:  If `constructor` param is an object, this param takes the place of the `statics` param.
@param statics {Object|undefined} - Constructor's static methods.  Optional.  Note:  If `constructor` param is an object, this param is not used.
@returns {{constructor: (Function|*), methods: *, statics: *, superClass: (*|Object)}}

Normalized the parameters required for defineSubClassPure and defineSubClass to operate .


function makeExtendableConstructor (constructor) {
        var extender = function (constructor_, methods_, statics_) {
            return defineSubClass(constructor, constructor_, methods_, statics_);
        };

        /**
         * Extends a new copy of self with passed in parameters.
         * @memberof class:sjl.stdlib.Extendable
         * @static sjl.stdlib.Extendable.extend
         * @param constructor {Function|Object} - Required.  Note: if is an object, then other params shift over by 1 (`methods` becomes `statics` and this param becomes `methods`).
         * @param methods {Object|undefined} - Methods.  Optional.  Note:  If `constructor` param is an object, this gets cast as `statics` param.  Also for overriding
         * @param statics {Object|undefined} - Static methods.  Optional.  Note:  If `constructor` param is an object, it is not used.
         */
        constructor.extend =
            constructor.extendWith =
                extender;

        // Return constructor
        return constructor;
    }

Adds `extend` and `extendWith` static methods to the passed in constructor for having easy extensibility via said
methods;  I.e., passed in constructor will now be extendable via added methods.
@see sjl.defineSubClass(superClass, constructor, methods, statics)
@function module:sjl.makeExtendableConstructor
@param constructor {Function}
@returns {*}

Adds extend and extendWith static methods to the passed in constructor for having easy extensibility via said methods ; I . e . passed in constructor will now be extendable via added methods .


function defineSubClassPure (superClass, constructor, methods, statics) {
        var normalizedArgs = normalizeArgsForDefineSubClass.apply(null, arguments),
            _superClass = normalizedArgs.superClass,
            _statics = normalizedArgs.statics,
            _constructor = normalizedArgs.constructor,
            _methods = normalizedArgs.methods;

        // Set prototype
        _constructor.prototype = Object.create(_superClass.prototype);

        // Define constructor
        Object.defineProperty(_constructor.prototype, 'constructor', {value: _constructor});

        // Extend constructor
        extend(_constructor.prototype, _methods);
        extend(_constructor, _statics, true);

        // Return constructor
        return _constructor;
    }

function
defineSubClassPure
(
superClass
,
constructor
,
methods
,
statics
)
{
var
normalizedArgs
=
normalizeArgsForDefineSubClass
.
apply
(
,
arguments
)
,
_superClass
=
normalizedArgs
.
superClass
,
_statics
=
normalizedArgs
.
statics
,
_constructor
=
normalizedArgs
.
constructor
,
_methods
=
normalizedArgs
.
methods
;
// Set prototype
_constructor
.
prototype
=
Object
.
create
(
_superClass
.
prototype
)
;
// Define constructor
Object
.
defineProperty
(
_constructor
.
prototype
,
'constructor'
,
{
value
:
_constructor
}
)
;
// Extend constructor
extend
(
_constructor
.
prototype
,
_methods
)
;
extend
(
_constructor
,
_statics
,
true
)
;
// Return constructor
return
_constructor
;
}

Same as `defineSubClass` with out side-effect of `extend` method and `toString` method.
@function module:sjl.defineSubClassPure
@param superClass {Function} - Superclass to inherit from.
@param constructor {Function|Object} - Required.  Note:  If this param is an object, then other params shift over by 1 (`methods` becomes `statics` and this param becomes `methods` (constructor key expected else empty stand in constructor is used).
@param methods {Object|undefined} - Methods for prototype.  Optional.  Note:  If `constructor` param is an object, this param takes the place of the `statics` param.
@param statics {Object|undefined} - Constructor's static methods.  Optional.  Note:  If `constructor` param is an object, this param is not used.
@returns {Function} - Constructor with extended prototype and added statics.

Same as defineSubClass with out side - effect of extend method and toString method .


function throwTypeErrorIfEmpty (prefix, paramName, value, type, suffix) {
        throwTypeErrorIfEmptyOrNotOfType (prefix, paramName, value, type, suffix);
    }

function throwTypeErrorIfEmpty ( prefix , paramName , value , type , suffix ) { throwTypeErrorIfEmptyOrNotOfType ( prefix , paramName , value , type , suffix ) ; }

Same as sjl.throwErrorIfEmptyOrNotType but named shorter.
@see sjl.throwErrorIfEmptyOrNotType for full function description and param descriptions.
@function module:sjl.throwTypeErrorIfEmpty
@param prefix {String}
@param paramName {String}
@param value {String}
@param type {String|Function|undefined}
@param suffix {String}
@throws {TypeError}
@returns {void}

Same as sjl . throwErrorIfEmptyOrNotType but named shorter .


function valueOrDefault (value, defaultValue, type) {
        defaultValue = typeof defaultValue === _undefined ? null : defaultValue;
        var retVal;
        if (isset(type)) {
            retVal = issetAndOfType.apply(null, [value].concat(sjl.restArgs(arguments, 2))) ? value : defaultValue;
        }
        else {
            retVal = isset(value) ? value : defaultValue;
        }
        return retVal;
    }

function valueOrDefault ( value , defaultValue , type ) { defaultValue = typeof defaultValue === _undefined ? null : defaultValue ; var retVal ; if ( isset ( type ) ) { retVal = issetAndOfType . apply ( null , [ value ] . concat ( sjl . restArgs ( arguments , 2 ) ) ) ? value : defaultValue ; } else { retVal = isset ( value ) ? value : defaultValue ; } return retVal ; }

Returns value if it is set and of type else returns `defaultValue`
@function module:sjl.valueOrDefault
@param value {*} - Value to pass through.
@param defaultValue {*} - Optional.  Value to use as default value if value is not set.  Default `null`.
@param type {String|Function} - Optional.  Constructor or string representation of type;  E.g., String or 'String'

Returns value if it is set and of type else returns defaultValue


function defineEnumProp(obj, key, value) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true
        });
    }

function defineEnumProp ( obj , key , value ) { Object . defineProperty ( obj , key , { value : value , enumerable : true } ) ; }

Sets an enumerable property on `obj` as not `configurable` and not `writable`.
@function module:sjl.defineEnumProp
@param obj {Object}
@param key {String} - Prop name.
@param value {*}
@return {void}

Sets an enumerable property on obj as not configurable and not writable .


function unConfigurableNamespace(ns_string, objToSearch, valueToSet) {
        var parent = objToSearch,
            shouldSetValue = typeof valueToSet !== _undefined,
            hasOwnProperty;

        ns_string.split('.').forEach(function (key, i, parts) {
            hasOwnProperty = parent.hasOwnProperty(key);
            if (i === parts.length - 1
                && shouldSetValue && !hasOwnProperty) {
                defineEnumProp(parent, key, valueToSet);
            }
            else if (typeof parent[key] === _undefined && !hasOwnProperty) {
                defineEnumProp(parent, key, {});
            }
            parent = parent[key];
        });

        return parent;
    }

function unConfigurableNamespace ( ns_string , objToSearch , valueToSet ) { var parent = objToSearch , shouldSetValue = typeof valueToSet !== _undefined , hasOwnProperty ; ns_string . split ( '.' ) . forEach ( function ( key , i , parts ) { hasOwnProperty = parent . hasOwnProperty ( key ) ; if ( i === parts . length - 1 && shouldSetValue && ! hasOwnProperty ) { defineEnumProp ( parent , key , valueToSet ) ; } else if ( typeof parent [ key ] === _undefined && ! hasOwnProperty ) { defineEnumProp ( parent , key , { } ) ; } parent = parent [ key ] ; } ) ; return parent ; }

Sets namespace string on obj and makes namespace configurable (@see Object.defineProper(ty|ties)).
@param ns_string {String} - Namespace string; E.g., 'all.your.base'
@param objToSearch {Object} - Object to set namespace string on.
@param valueToSet {*|undefined} - Value to set at end of namespace string.
@returns {*} - Value that was set at the end of the namespace propagation.


function changeCaseOfFirstChar(str, func, thisFuncsName) {
        var search, char, right, left;

        // If typeof `str` is not of type "String" then bail
        throwTypeErrorIfNotOfType(thisFuncsName, 'str', str, _String);

        // Search for first alpha char
        search = str.search(/[a-z]/i);

        // If alpha char
        if (isNumber(search) && search > -1) {

            // Make it lower case
            char = str.substr(search, 1)[func]();

            // Get string from `char`'s index
            right = str.substr(search + 1, str.length - 1);

            // Get string upto `char`'s index
            left = search !== 0 ? str.substr(0, search) : '';

            // Concatenate original string with lower case char in it
            str = left + char + right;
        }

        return str;
    }

Used when composing a function that needs to operate on the first character found and needs to
return the original string with the modified character within it.
@see sjl.lcaseFirst or sjl.ucaseFirst (search within this file)
@param str {String} - string to search for first alpha char on
@param func {String} - function to run on first alpha char found; i.e., found[func]()
@param thisFuncsName {String} - the function name that is using this function (in order
to present a prettier error message on `TypeError`)
@throws {TypeError} - If str is not of type "String"
@returns {String} - composed string

Used when composing a function that needs to operate on the first character found and needs to return the original string with the modified character within it .


function extractBoolFromArray(array, startOrEndBln) {
        var extractedValue = extractFromArrayAt(
            array,
            startOrEndBln ? 0 : array.length - 1,
            _Boolean,
            false
        )[0];
        return isBoolean(extractedValue) ? extractedValue : false;
    }

function extractBoolFromArray ( array , startOrEndBln ) { var extractedValue = extractFromArrayAt ( array , startOrEndBln ? 0 : array . length - 1 , _Boolean , false ) [ 0 ] ; return isBoolean ( extractedValue ) ? extractedValue : false ; }

Extracts a boolean from the beginning or ending of an array depending on startOrEndBln.
@note Method does not create a new array when doing extraction and alters originally passed in array.
@param array {Array}
@param startOrEndBln {Boolean}
@returns {Boolean}

Extracts a boolean from the beginning or ending of an array depending on startOrEndBln .


function mergeOnPropsMulti (obj1, obj2) {
        var args = argsToArray(arguments),
            deep = extractBoolFromArrayStart(args),
            arg0 = args.shift();

        // Extend object `0` with other objects
        args.forEach(function (arg) {
            if (!isObject(arg)) {
                return;
            }
            // Extend `arg0` with `arg`
            mergeOnProps(arg0, arg, deep);
        });

        return arg0;
    }

function
mergeOnPropsMulti
(
obj1
,
obj2
)
{
var
args
=
argsToArray
(
arguments
)
,
deep
=
extractBoolFromArrayStart
(
args
)
,
arg0
=
args
.
shift
(
)
;
// Extend object `0` with other objects
args
.
forEach
(
function
(
arg
)
{
if
(
!
isObject
(
arg
)
)
{
return
;
}
// Extend `arg0` with `arg`
mergeOnProps
(
arg0
,
arg
,
deep
)
;
}
)
;
return
arg0
;
}

A strict version of sjl.extend;  I.e., only merges on properties existing on `obj1`.
@function module:sjl.mergeOnPropsMulti
@param obj1 {Object|Boolean} - If this param is set to a boolean then deep merge takes place.
@param [obj2,] {Object} - One or more objects to operate on.
@note In the case of `obj1` being a boolean method will expect 2 or more objects following param `obj1`.
@returns {*}

A strict version of sjl . extend ; I . e . only merges on properties existing on obj1 .


function (keyOrNsKey, value) {
                var self = this;
                if (sjl.isObject(keyOrNsKey)) {
                    sjl.extend.apply(sjl, [true, self].concat(sjl.argsToArray(arguments)));
                }
                else if (sjl.isString(keyOrNsKey)) {
                    sjl.autoNamespace(keyOrNsKey, self, value);
                }
                else if (sjl.isset(keyOrNsKey)) {
                    throw new TypeError(contextName + '.set only allows strings or objects as it\'s first parameter.  ' +
                        'Param type received: `' + sjl.classOf(keyOrNsKey) + '`.');
                }
                return self;
            }

Sets any value on config by key or namespace key.
@method sjl.stdlib.Config#set
@param keyOrNsKey {String}
@param value {*}
@returns {sjl.stdlib.Config} - Returns self.

Sets any value on config by key or namespace key .


function () {
            var self = this;
            return self.valid() ? {
                done: false,
                value: self._values[self.pointer]
            } : {
                done: true
            };
        }

function ( ) { var self = this ; return self . valid ( ) ? { done : false , value : self . _values [ self . pointer ] } : { done : true } ; }

Returns the current value that `pointer` is pointing to.
@method sjl.stdlib.Iterator#current
@returns {{done: boolean, value: *}}

Returns the current value that pointer is pointing to .


function (callback, context) {
            var self = this,
                values = self._values;
            context = context || self;
            self._keys.forEach(function (key, index, keys) {
                callback.call(context, values[index], key, keys);
            });
            return this;
        }

function ( callback , context ) { var self = this , values = self . _values ; context = context || self ; self . _keys . forEach ( function ( key , index , keys ) { callback . call ( context , values [ index ] , key , keys ) ; } ) ; return this ; }

Iterates through all elements in iterator.  @note Delegates to it's values `forEach` method.
@param callback {Function}
@param context {Object}
@method sjl.stdlib.ObjectIterator#forEach
@returns {sjl.stdlib.Iterator}

Iterates through all elements in iterator .


function (value) {
            var _index = this._values.indexOf(value);
            if (_index > -1 && _index <= this._values.length) {
                this._values.splice(_index, 1);
            }
            return this;
        }

function ( value ) { var _index = this . _values . indexOf ( value ) ; if ( _index > - 1 && _index <= this . _values . length ) { this . _values . splice ( _index , 1 ) ; } return this ; }

Deletes a value from Set.
@method sjl.stdlib.SjlSet#delete
@param value {*}
@returns {sjl.stdlib.SjlSet}


function (key) {
                if (this.has(key)) {
                    var _index = this._keys.indexOf(key);
                    this._values.splice(_index, 1);
                    this._keys.splice(_index, 1);
                }
                return this;
            }

function ( key ) { if ( this . has ( key ) ) { var _index = this . _keys . indexOf ( key ) ; this . _values . splice ( _index , 1 ) ; this . _keys . splice ( _index , 1 ) ; } return this ; }

Deletes an entry in the `SjlMap`.
@method sjl.stdlib.SjlMap#delete
@param key {*} - Key of key-value pair to remove.
@returns {SjlMap}


function (key, value) {
            var index = this._keys.indexOf(key);
            if (index > -1) {
                this._keys[index] = key;
                this._values[index] = value;
            }
            else {
                this._keys.push(key);
                this._values.push(value);
            }
            return this;
        }

function ( key , value ) { var index = this . _keys . indexOf ( key ) ; if ( index > - 1 ) { this . _keys [ index ] = key ; this . _values [ index ] = value ; } else { this . _keys . push ( key ) ; this . _values . push ( value ) ; } return this ; }

Sets a key-value pair in this instance.
@method sjl.stdlib.SjlMap#set
@param key {*} - Key to set.
@param value {*} - Value to set.
@returns {SjlMap}

Sets a key - value pair in this instance .


function (object) {
            sjl.throwTypeErrorIfNotOfType(SjlMap.name, 'object', object, 'Object',
                'Only `Object` types allowed.');
            var self = this,
                entry,
                objectIt = new ObjectIterator(object);
            while (objectIt.valid()) {
                entry = objectIt.next();
                self.set(entry.value[0], entry.value[1]);
            }
            return self;
        }

function
(
object
)
{
sjl
.
throwTypeErrorIfNotOfType
(
SjlMap
.
name
,
'object'
,
object
,
'Object'
,
'Only `Object` types allowed.'
)
;
var
self
=
this
,
entry
,
objectIt
=
new
ObjectIterator
(
object
)
;
while
(
objectIt
.
valid
(
)
)
{
entry
=
objectIt
.
next
(
)
;
self
.
set
(
entry
.
value
[
0
]
,
entry
.
value
[
1
]
)
;
}
return
self
;
}

Add all the `object`'s instance's own property key-value pairs to this instance.
@method sjl.stdlib.SjlMap#addFromObject
@param object {Object} - Object to operate on.
@returns {SjlMap}

Add all the object s instance s own property key - value pairs to this instance .


function () {
            var self = this,
                out = {};
            this._keys.forEach(function (key, i) {
                out[key] = self._values[i];
            });
            return out;
        }

function ( ) { var self = this , out = { } ; this . _keys . forEach ( function ( key , i ) { out [ key ] = self . _values [ i ] ; } ) ; return out ; }

Shallow to json method.
@method sjl.stdlib.SjlMap#toJSON
@returns {{}}


function () {
            var next = Iterator.prototype.next.call(this);
            if (!next.done && this.wrapItems) {
                next.value = next.value.value;
            }
            return next;
        }

function ( ) { var next = Iterator . prototype . next . call ( this ) ; if ( ! next . done && this . wrapItems ) { next . value = next . value . value ; } return next ; }

Returns the next iterator result for item at own `pointer`'s current position.
@method sjl.stdlib.PriorityList#next
@overrides sjl.stdlib.Iterator#next
@returns {{done: boolean, value: *}|{done: boolean}} - Returns `value` key in result only while `done` is `false`.

Returns the next iterator result for item at own pointer s current position .


function () {
            return this.sort().wrapItems ?
                new ObjectIterator(this._keys, this._values.map(function (item) {
                    return item.value;
                })) :
                new SjlMap.prototype.entries.call(this.sort());
        }

function ( ) { return this . sort ( ) . wrapItems ? new ObjectIterator ( this . _keys , this . _values . map ( function ( item ) { return item . value ; } ) ) : new SjlMap . prototype . entries . call ( this . sort ( ) ) ; }

Returns a key-value es6 compliant iterator.
@method sjl.stdlib.ObjectIterator#entries
@overrides sjl.stdlib.SjlMap#entries
@returns {sjl.stdlib.ObjectIterator}

Returns a key - value es6 compliant iterator .


function (callback, context) {
            SjlMap.prototype.forEach.call(this.sort(), function (value, key, map) {
                callback.call(context, this.wrapItems ? value.value : value, key, map);
            }, this);
            return this;
        }

function ( callback , context ) { SjlMap . prototype . forEach . call ( this . sort ( ) , function ( value , key , map ) { callback . call ( context , this . wrapItems ? value . value : value , key , map ) ; } , this ) ; return this ; }

Allows you to loop through priority items in priority list.
Same function signature as Array.prorotype.forEach.
@param callback {Function} - Same signature as SjlMap.prorotype.forEach; I.e., {Function<value, key, obj>}.
@param context {undefined|*}
@method sjl.stdlib.PriorityList#forEach
@overrides sjl.stdlib.SjlMap#forEach
@returns {sjl.stdlib.PriorityList}

Allows you to loop through priority items in priority list . Same function signature as Array . prorotype . forEach .


function () {
            if (this.wrapItems) {
                return new Iterator(this.sort()._values.map(function (item) {
                    return item.value;
                }));
            }
            return new SjlMap.prototype.values.call(this.sort());
        }

function ( ) { if ( this . wrapItems ) { return new Iterator ( this . sort ( ) . _values . map ( function ( item ) { return item . value ; } ) ) ; } return new SjlMap . prototype . values . call ( this . sort ( ) ) ; }

Returns an iterator for values in this priority list.
@method sjl.stdlib.PriorityList#values
@overrides sjl.stdlib.SjlMap#values
@returns {sjl.stdlib.Iterator}

Returns an iterator for values in this priority list .


function (key, value, priority) {
            SjlMap.prototype.set.call(this, key, this.resolveItemWrapping(key, value, priority));
            this._sorted = false;
            return this;
        }

function ( key , value , priority ) { SjlMap . prototype . set . call ( this , key , this . resolveItemWrapping ( key , value , priority ) ) ; this . _sorted = false ; return this ; }

Sets an item onto Map at passed in priority.  If no
priority is passed in value is set at internally incremented
priority.
@param key {*}
@param value {*}
@param priority {Number}
@overrides sjl.stdlib.SjlMap#set
@method sjl.stdlib.PriorityList#set
@returns {sjl.stdlib.PriorityList}

Sets an item onto Map at passed in priority . If no priority is passed in value is set at internally incremented priority .


function (priority) {
            var retVal;
            if (sjl.classOfIs(priority, Number)) {
                retVal = priority;
            }
            else {
                this._internalPriorities += 1;
                retVal = +this._internalPriorities;
            }
            return retVal;
        }

function ( priority ) { var retVal ; if ( sjl . classOfIs ( priority , Number ) ) { retVal = priority ; } else { this . _internalPriorities += 1 ; retVal = + this . _internalPriorities ; } return retVal ; }

Ensures priority returned is a number or increments it's internal priority counter
and returns it.
@param priority {Number}
@method sjl.stdlib.PriorityList#normalizePriority
@returns {Number}

Ensures priority returned is a number or increments it s internal priority counter and returns it .


function (key, value, priority) {
            var normalizedPriority = this.normalizePriority(priority),
                serial = this._internalSerialNumbers++;
            if (this.wrapItems) {
                return new (this.itemWrapperConstructor) (key, value, normalizedPriority, serial);
            }
            try {
                value.key = key;
                value.priority = priority;
                value.serial = serial;
            }
            catch (e) {
                throw new TypeError('PriorityList can only work in "unwrapped" mode with values/objects' +
                    ' that can have properties created/set on them.  Type encountered: `' + sjl.classOf(value) + '`;' +
                    '  Original error: ' + e.message);
            }
            return value;
        }

Used internally to get value either raw or wrapped as specified by the `wrapItems` flag.
@param key {*}
@param value {*}
@param priority {Number}
@method sjl.stdlib.PriorityList#resolveItemWrapping
@returns {*|PriorityListItem}

Used internally to get value either raw or wrapped as specified by the wrapItems flag .


function doesSecurityGroupExist (ec2, securityGroupName) {
  function inspectError (err) {
    if (err.code === 'InvalidGroup.NotFound') {
      return false
    }

    return Bluebird.reject(err)
  }

  return ec2
    .describeSecurityGroupsPromised({
      GroupNames: [ securityGroupName ]
    })
    .then(_.constant(true))
    .error(inspectError)
}

function doesSecurityGroupExist ( ec2 , securityGroupName ) { function inspectError ( err ) { if ( err . code === 'InvalidGroup.NotFound' ) { return false } return Bluebird . reject ( err ) } return ec2 . describeSecurityGroupsPromised ( { GroupNames : [ securityGroupName ] } ) . then ( _ . constant ( true ) ) . error ( inspectError ) }

Uses EC2.describeSecurity groups to check the existence of the security
group. If the response comes back successful doesSecurityGroupExist is
resolved with True. If an operational error occurs in the underlying ec2
client call, the error is inspected to see if it is an
"InvalidGroup.NotFound" error. This means the security group is not present,
so doesSecurityGroupExist is resolved with false. All other errors are
propagated along via a rejection.

@param ec2
@param securityGroupName

@returns {Promise}

Uses EC2 . describeSecurity groups to check the existence of the security group . If the response comes back successful doesSecurityGroupExist is resolved with True . If an operational error occurs in the underlying ec2 client call the error is inspected to see if it is an InvalidGroup . NotFound error . This means the security group is not present so doesSecurityGroupExist is resolved with false . All other errors are propagated along via a rejection .


function doesAutoScalingGroupExist (autoScaling, asgName) {
  return autoScaling
    .describeAutoScalingGroupsPromised({
      AutoScalingGroupNames: [ asgName ]
    })
    .then(function found (data) {
      return !_.isEmpty(data.AutoScalingGroups)
    })
}

function doesAutoScalingGroupExist ( autoScaling , asgName ) { return autoScaling . describeAutoScalingGroupsPromised ( { AutoScalingGroupNames : [ asgName ] } ) . then ( function found ( data ) { return ! _ . isEmpty ( data . AutoScalingGroups ) } ) }

Uses AutoScaling.describeAutoScalingGroups to check existence of the
auto scaling group. If the list of AutoScalingGroups returned is empty
doesAutoScalingGroupExist is resolved as False, if it's not empty it is
resolved as True.

@param autoScaling
@param asgName

@returns {Promise}

Uses AutoScaling . describeAutoScalingGroups to check existence of the auto scaling group . If the list of AutoScalingGroups returned is empty doesAutoScalingGroupExist is resolved as False if it s not empty it is resolved as True .


function buildParams (identifier, instanceState) {
  var params = {}

  if (instanceState) {
    params.Filters = [
      {
        Name: 'instance-state-name',
        Values: [instanceState]
      }
    ]
  }

  if (isInstanceId(identifier)) {
    params.InstanceIds = [identifier]
    return params
  }

  params.Filters = params.Filters || []

  params.Filters.push({
    Name: 'tag:Name',
    Values: [identifier]
  })

  return params
}

function buildParams ( identifier , instanceState ) { var params = { } if ( instanceState ) { params . Filters = [ { Name : 'instance-state-name' , Values : [ instanceState ] } ] } if ( isInstanceId ( identifier ) ) { params . InstanceIds = [ identifier ] return params } params . Filters = params . Filters || [ ] params . Filters . push ( { Name : 'tag:Name' , Values : [ identifier ] } ) return params }

Builds the correct set of params depending on whether or not the
identifier is an instanceId or a name.

@param {state} instanceState
@param {string} identifier
@returns {object} params for the ec2.describeInstances call.

Builds the correct set of params depending on whether or not the identifier is an instanceId or a name .


function doesInstanceExist (ec2, identifier, instanceState) {
  var params = buildParams(identifier, instanceState)

  function inspectError (err) {
    if (err.code === 'InvalidInstanceID.NotFound') {
      return false
    }

    return Bluebird.reject(err)
  }

  return ec2
    .describeInstancesPromised(params)
    .then(function checkResult (data) {
      return !isEmpty(data.Reservations)
    })
    .catch(inspectError)
}

function doesInstanceExist ( ec2 , identifier , instanceState ) { var params = buildParams ( identifier , instanceState ) function inspectError ( err ) { if ( err . code === 'InvalidInstanceID.NotFound' ) { return false } return Bluebird . reject ( err ) } return ec2 . describeInstancesPromised ( params ) . then ( function checkResult ( data ) { return ! isEmpty ( data . Reservations ) } ) . catch ( inspectError ) }

Takes an identifier, either an InstanceId or Name Tag and returns whether the
instance exists in any state. The second instanceState allows specification
of the state the machine is in. Will also return false if an error is thrown
when given an invalid or non existent instance ID.

i.e
doesInstanceExist('i-456ae390', 'running')
Will only return true if that instance exists, and is in a running state.

@param ec2
@param {string} identifier Instance Name Tag or InstanceId
@param instanceState
@returns {*}

Takes an identifier either an InstanceId or Name Tag and returns whether the instance exists in any state . The second instanceState allows specification of the state the machine is in . Will also return false if an error is thrown when given an invalid or non existent instance ID .


function EdmundsClient(config) {
  if (!(this instanceof EdmundsClient)) {
    return new EdmundsClient(config);
  }

  var defaultConfig = {};
  defaultConfig.responseFormat = 'json';
  defaultConfig.baseUrl = 'https://api.edmunds.com';

  this.config = extend(defaultConfig, config);

  if (!this.config.apiKey) {
    throw new Error('API key must be provided');
  }
}

function
EdmundsClient
(
config
)
{
if
(
!
(
this
instanceof
EdmundsClient
)
)
{
return
new
EdmundsClient
(
config
)
;
}
var
defaultConfig
=
{
}
;
defaultConfig
.
responseFormat
=
'json'
;
defaultConfig
.
baseUrl
=
'https://api.edmunds.com'
;
this
.
config
=
extend
(
defaultConfig
,
config
)
;
if
(
!
this
.
config
.
apiKey
)
{
throw
new
Error
(
'API key must be provided'
)
;
}
}

The client constructor

@param config - configuration object
@constructor


function addDefinition(defName) {
  var definition = definitions[defName];
  return function(params, done) {
    if (!done && typeof params === 'function') {
      done = params;
      params = {};
    }

    var url = this.config.baseUrl + definition.url;
    var xtraParams = {};
    xtraParams.fmt = this.config.responseFormat;
    xtraParams.api_key = this.config.apiKey;

    try {
      Object.keys(definition.params).forEach(function(paramName) {
        var paramDef = definition.params[paramName];
        if (!params[paramName]) {
          if (paramDef.required) {
            throw new Error('Parameter ' + paramName + ' is required');
          } else {
            return;
          }
        }
        if (paramDef.location === 'url') {
          url = url.replace(new RegExp('{' + paramName + '}', 'g'), params[paramName]);
        } else if (paramDef.location === 'querystring') {
          xtraParams[paramName] = params[paramName];
        }
      });
    } catch (e) {
      return done(e);
    }

    return request
      .get(url)
      .query(xtraParams)
      .end(function onEnd(err, res) {
        return done(err, res.body);
      });
  };
}

function
addDefinition
(
defName
)
{
var
definition
=
definitions
[
defName
]
;
return
function
(
params
,
done
)
{
if
(
!
done
&&
typeof
params
===
'function'
)
{
done
=
params
;
params
=
{
}
;
}
var
url
=
this
.
config
.
baseUrl
+
definition
.
url
;
var
xtraParams
=
{
}
;
xtraParams
.
fmt
=
this
.
config
.
responseFormat
;
xtraParams
.
api_key
=
this
.
config
.
apiKey
;
try
{
Object
.
keys
(
definition
.
params
)
.
forEach
(
function
(
paramName
)
{
var
paramDef
=
definition
.
params
[
paramName
]
;
if
(
!
params
[
paramName
]
)
{
if
(
paramDef
.
required
)
{
throw
new
Error
(
'Parameter '
+
paramName
+
' is required'
)
;
}
else
{
return
;
}
}
if
(
paramDef
.
location
===
'url'
)
{
url
=
url
.
replace
(
new
RegExp
(
'{'
+
paramName
+
'}'
,
'g'
)
,
params
[
paramName
]
)
;
}
else
if
(
paramDef
.
location
===
'querystring'
)
{
xtraParams
[
paramName
]
=
params
[
paramName
]
;
}
}
)
;
}
catch
(
e
)
{
return
done
(
e
)
;
}
return
request
.
get
(
url
)
.
query
(
xtraParams
)
.
end
(
function
onEnd
(
err
,
res
)
{
return
done
(
err
,
res
.
body
)
;
}
)
;
}
;
}


function createClient (host, port, concurrent, frequency, duration, gen, iteration) {
  var auth = defaults.auth
  var getMessage = defaults.getMessage
  emitter.emit('start')

  if (typeof gen.authenticate === 'function') {
    auth = gen.authenticate
  }

  if (typeof gen.clientIterateMessage === 'function') {
    getMessage = gen.clientIterateMessage
  }

  /**
   * Once auth is complete, this actually initiates the client
   * @method  postAuth
   * @async
   * @private
   * @param   {object} err Error from auth, if any
   * @param   {object} cookies Any cookies to pass through to the socket object
   * @param   {string} user The username used to login
   * @param   {string} pass The password used to login
   * @returns {object} undefined
   */
  var postAuth = function (err, cookies, user, pass) {
    ++clientsAttempted
    if (err) {
      emitter.emit('error', err)
      if (clientsAttempted === concurrent && _intervals.length === 0) {
        emitter.emit('end')
      }
      return
    }

    var socketUrl = gen.getSocketURL(host, port, cookies, user, pass) || host + ':' + port
    var socket = io(socketUrl, { multiplex: false })
      .on('connect', function () {
        emitter.emit('client-connected')
        if (typeof gen.events.connect === 'function') {
          gen.events.connect('connect', cookies, user, pass, {}, socket, emitter)
        }

        Object.keys(gen.events).forEach(function (eventName) {
          socket.on(eventName, function (data) {
            gen.events[eventName].call(null, eventName, cookies, user, pass, data, socket, emitter)
          })
        })

        var sendMessage = function () {
          var message = getMessage(cookies, user, pass)
          if (!Array.isArray(message)) {
            message = [message]
          }

          for (var i = 0, len = message.length; i < len; i++) {
            if (message[i]) {
              socket.json.send(message[i])
              emitter.emit('message', message[i])
            }
          }
        }

        _intervals.push(setInterval(sendMessage, frequency))

        setTimeout(function () {
          clearInterval(_intervals.pop())
          socket.emit('disconnect')
          emitter.emit('disconnect')
          socket.close()
          if (_intervals.length === 0) {
            done()
          }
        }, duration)
      })
      .on('connect_error', function (err) {
        emitter.emit('error', err)
        if (clientsAttempted === concurrent && _intervals.length === 0) {
          emitter.emit('end')
        }
      })
  }

  auth(host, port, iteration, postAuth)
}

Create a websocket client and set it off at the server
@method  createClient
@private
@param   {string} host Hostname
@param   {integer} port Port number
@param   {integer} concurrent Number of clients to spin up
@param   {integer} frequency Amount of time, in ms, to wait between emitting messages
@param   {integer} duration Amoutn of time, in ms, to run each client for
@param   {object} gen The generator object, required and parse
@param   {integer} iteration What client number you're on
@returns {object} undefined


function(file) {
    var xml = file.contents;
    var xmlDoc = libxmljs.parseXml(xml);
    var rootNode = xmlDoc.root();

    var resourceObject = {};
    var valueNodes = rootNode.find("data");
    valueNodes.forEach(function(element) {
      var name = element.attr("name").value();
      var value = element.get("value").text();
      resourceObject[name] = value;
    });

    return JSON.stringify(resourceObject);
  }

function ( file ) { var xml = file . contents ; var xmlDoc = libxmljs . parseXml ( xml ) ; var rootNode = xmlDoc . root ( ) ; var resourceObject = { } ; var valueNodes = rootNode . find ( "data" ) ; valueNodes . forEach ( function ( element ) { var name = element . attr ( "name" ) . value ( ) ; var value = element . get ( "value" ) . text ( ) ; resourceObject [ name ] = value ; } ) ; return JSON . stringify ( resourceObject ) ; }


function doesLaunchConfigurationExist (autoScaling, launchConfigurationName) {
  return autoScaling.
    describeLaunchConfigurationsPromised({
      LaunchConfigurationNames: [ launchConfigurationName ]
    })
    .then(function found (data) {
      return !_.isEmpty(data.LaunchConfigurations)
    })
}

function doesLaunchConfigurationExist ( autoScaling , launchConfigurationName ) { return autoScaling . describeLaunchConfigurationsPromised ( { LaunchConfigurationNames : [ launchConfigurationName ] } ) . then ( function found ( data ) { return ! _ . isEmpty ( data . LaunchConfigurations ) } ) }

Uses AutoScaling.describeLaunchConfigurations to check existence of the
launch configuration. If the list of LaunchConfigurations returned is empty
doesLaunchConfigurationExist is resolved as False, if it's not empty it is
resolved as True.

@param autoScaling
@param launchConfigurationName

@returns {Promise}

Uses AutoScaling . describeLaunchConfigurations to check existence of the launch configuration . If the list of LaunchConfigurations returned is empty doesLaunchConfigurationExist is resolved as False if it s not empty it is resolved as True .


function KJU(configuration) {
  var self = this
    , option;

  // defaults
  this.limit = 500;
  this.ms = 100;
  this.interval = 15000;
  this.warnings = true;
  this.enabled = true;
  this.recover = true;
  this.dump = true;
  this.path = process.cwd() + '/';
  this.name = 'node_kju_backup.{sequence}.kju';

  // apply the configuration
  for (option in configuration)
    this[option] = configuration[option];

  // these values should not be configured
  this.buffer = [];
  this.length = 0;

  this.drained = 0;
  this.processed = 0;
  this.since = Date.now();

  this.minimum = this.interval / 2;
  this.maximum = this.interval * 2;

  // initialize the event emitter
  EventEmitter2.call(this, { wildcard: true });

  if (this.recover) this.recovery();
  if (this.enabled) this.enable();

  // make sure our backup path exists
  fsExists(this.path, function existing(exists) {
    if (!exists) {
      return self.emit('error', new Error(self.path + ' does not exist.'));
    }

    if (self.path[self.path.length - 1] !== '/') {
      return self.emit('error', new Error(self.path + ' should end with a slash'));
    }
  });
}

Initialize our queue.

Options:

- `limit` Limit of the buffer. Defaults to 500 items.
- `ms` Amount of milliseconds to increase or decrease the interval. Defaults
to 100 ms
- `interval` Baseline interval for queue, this is where the minimum and
maximum levels are based off.  Defaults to 15000 ms
- `warnings` When enabled we will emit events when our maximum or minimum
interval has been reached. Defaults to true.
- `enabled` Enable the queue by default. Defaults to true.
- `recover` Enable recovery of old `.kju` storage files so no data is lost
when the process is exiting. Defaults to true.
- `dump` In addition to the storage of `.kju` files also dump JSON to
stderr. Defaults to false.
- `path` Location where the `.kju` recover files are stored. Defaults to
the current working directory.
- `name` Name of the `.kju` recover files.

@constructor
@param {Object} configuration kju configuration
@api public


function filter(err, files) {
    if (err) return self.emit('error', err);

    var kjud = files.filter(function filterfiles(file) {
      return (/(\d)\.kju$/).test(file);
    });

    // if we don't have any files we don't really need to emit 'recovered' so
    // no need to check for the length here. We are only gonna use the length
    // if there are files.
    processed = kjud.length;
    kjud.forEach(read);
  }

filter all none `.kju` files out of the array.

@param {Error} err Set when a error occurred
@param {Array} files Files to filter
@api private

filter all none . kju files out of the array .


function read(file, index, files) {
    fs.readFile(self.path + file, function readFile(err, contents) {
      if (err) return done(), self.emit('error', err);

      // try to parse the file as JSON, if that doesn't work we have big issue
      // because the file is damaged.
      try {
        var todo = JSON.parse(contents.toString('utf8'));

        // pfew, it worked re-add it to kju and remove the file, I don't really
        // care about the clean up process. So I'm not gonna handle the errors
        // that could occur there.
        self.push.apply(self, todo);
        fs.unlink(self.path + file, function ignore(err) {});
      } catch (e) {
        self.emit('error'
          , new Error('Corrupted file, unable to parse contents of ' + file)
        );
      }

      done();
    });
  }

Read file and process it.

@param {String} file
@param {Number} index
@param {Array} files
@api private


function () {
	var s4 = function () {
		return Math.floor((1 + Math.random()) * 0x10000)
		.toString(16)
		.substring(1);
	};
	return s4() + s4() + '-' + s4();
}

function ( ) { var s4 = function ( ) { return Math . floor ( ( 1 + Math . random ( ) ) * 0x10000 ) . toString ( 16 ) . substring ( 1 ) ; } ; return s4 ( ) + s4 ( ) + '-' + s4 ( ) ; }


function (raw) {
	if (typeof raw !== 'object' || raw === null || util.isArray( raw )) {
		return false;
	}
	if (raw.wiretree) {
		return true;
	}
	return false;
}

function ( raw ) { if ( typeof raw !== 'object' || raw === null || util . isArray ( raw ) ) { return false ; } if ( raw . wiretree ) { return true ; } return false ; }

detect if is a wiretree plugin or a module


function (func) {
	var fnStr = func.toString().replace( /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '' );
	return fnStr.slice( fnStr.indexOf( '(' ) + 1, fnStr.indexOf( ')' )).match(/([^\s,]+)/g) || [];
}

function ( func ) { var fnStr = func . toString ( ) . replace ( / ((\/\/.*$)|(\/\*[\s\S]*?\*\/)) / mg , '' ) ; return fnStr . slice ( fnStr . indexOf ( '(' ) + 1 , fnStr . indexOf ( ')' ) ) . match ( / ([^\s,]+) / g ) || [ ] ; }


function (mod) {
		self.res = getProcessed( self.processing, mod, self.raw.settings );
		self.resolved = true;
		callback();
	}

function ( mod ) { self . res = getProcessed ( self . processing , mod , self . raw . settings ) ; self . resolved = true ; callback ( ) ; }


function(width, height, camera) {
		var id;
		var w = width, h = height;

		this.orientation = 'landscape';

		this.listeners = {};

		if (typeof width !== 'number') {
			var image = width;
			camera = height;
			w = image.videoWidth || image.width;
			h = image.videoHeight || image.height;
			this.image = image;
		}

		this.defaultMarkerWidth = 1;
		this.patternMarkers = {};
		this.barcodeMarkers = {};
		this.transform_mat = new Float32Array(16);

		this.canvas = document.createElement('canvas');
		this.canvas.width = w;
		this.canvas.height = h;
		this.ctx = this.canvas.getContext('2d');

		this.videoWidth = w;
		this.videoHeight = h;

		if (typeof camera === 'string') {

			var self = this;
			this.cameraParam = new ARCameraParam(camera, function() {
				self._initialize();
			}, function(err) {
				console.error("ARController: Failed to load ARCameraParam", err);
			});

		} else {

			this.cameraParam = camera;
			this._initialize();

		}
	}

The ARController is the main object for doing AR marker detection with JSARToolKit.

To use an ARController, you need to tell it the dimensions to use for the AR processing canvas and
pass it an ARCameraParam to define the camera parameters to use when processing images.
The ARCameraParam defines the lens distortion and aspect ratio of the camera used.
See https://www.artoolworks.com/support/library/Calibrating_your_camera for more information about AR camera parameteters and how to make and use them.

If you pass an image as the first argument, the ARController uses that as the image to process,
using the dimensions of the image as AR processing canvas width and height. If the first argument
to ARController is an image, the second argument is used as the camera param.

The camera parameters argument can be either an ARCameraParam or an URL to a camera definition file.
If the camera argument is an URL, it is loaded into a new ARCameraParam, and the ARController dispatches
a 'load' event and calls the onload method if it is defined.

@exports ARController
@constructor

@param {number} width The width of the images to process.
@param {number} height The height of the images to process.
@param {ARCameraParam | string} camera The ARCameraParam to use for image processing. If this is a string, the ARController treats it as an URL and tries to load it as a ARCameraParam definition file, calling ARController#onload on success.

The ARController is the main object for doing AR marker detection with JSARToolKit .


function(src, onload, onerror) {
		this.id = -1;
		this._src = '';
		this.complete = false;
		this.onload = onload;
		this.onerror = onerror;
		if (src) {
			this.load(src);
		}
	}

function ( src , onload , onerror ) { this . id = - 1 ; this . _src = '' ; this . complete = false ; this . onload = onload ; this . onerror = onerror ; if ( src ) { this . load ( src ) ; } }

ARCameraParam is used for loading AR camera parameters for use with ARController.
Use by passing in an URL and a callback function.

var camera = new ARCameraParam('Data/camera_para.dat', function() {
console.log('loaded camera', this.id);
},
function(err) {
console.log('failed to load camera', err);
});

@exports ARCameraParam
@constructor

@param {string} src URL to load camera parameters from.
@param {string} onload Onload callback to be called on successful parameter loading.
@param {string} onerror Error callback to called when things don't work out.

ARCameraParam is used for loading AR camera parameters for use with ARController . Use by passing in an URL and a callback function .


function PackageMemberListReadStream(dirToScan) {
    sjl.throwTypeErrorIfEmpty('PackageMemberListReadStream', 'dirToScan', dirToScan, String);
    this._pathToRead = dirToScan;
    Readable.call(this, {
        encoding: 'utf8',
        objectMode: false,
        highWaterMark: 100000,
    });
}

function PackageMemberListReadStream ( dirToScan ) { sjl . throwTypeErrorIfEmpty ( 'PackageMemberListReadStream' , 'dirToScan' , dirToScan , String ) ; this . _pathToRead = dirToScan ; Readable . call ( this , { encoding : 'utf8' , objectMode : false , highWaterMark : 100000 , } ) ; }

Our package member list to markdown-fragments readable stream.  It
reads our srcs directory and outputs a markdown-fragments friendly list
of all the packages and members in said directory.
@param dirToScan {String} - Dir to scan for list.
@param options {Object|undefined} - Optional.  Readable stream options.
@constructor {PackageMemberListReadStream}

Our package member list to markdown - fragments readable stream . It reads our srcs directory and outputs a markdown - fragments friendly list of all the packages and members in said directory .


function doesLoadBalancerExist (elb, loadBalancerName) {
  function inspectError (err) {
    if (err.code === 'LoadBalancerNotFound') {
      return false
    }

    return Bluebird.reject(err)
  }

  return elb
    .describeLoadBalancersPromised({
      LoadBalancerNames: [ loadBalancerName ]
    })
    .then(_.constant(true))
    .error(inspectError)
}

function doesLoadBalancerExist ( elb , loadBalancerName ) { function inspectError ( err ) { if ( err . code === 'LoadBalancerNotFound' ) { return false } return Bluebird . reject ( err ) } return elb . describeLoadBalancersPromised ( { LoadBalancerNames : [ loadBalancerName ] } ) . then ( _ . constant ( true ) ) . error ( inspectError ) }

Uses the ELB.describeLoadBalancers method to check the existence of a load
balancer. If the list of LoadBalancerDescriptions returned by the request
is empty, doesLoadBalancerExist is resolved as False, if it's not empty it
is resolved as True.

@param elb
@param loadBalancerName
@returns {Promise}

Uses the ELB . describeLoadBalancers method to check the existence of a load balancer . If the list of LoadBalancerDescriptions returned by the request is empty doesLoadBalancerExist is resolved as False if it s not empty it is resolved as True .


function lint(files) {
    return gulp.src(files)
        .pipe($.plumber())
        .pipe($.eslint())
        .pipe($.eslint.format())
        .pipe($.eslint.failOnError())
        .pipe($.jscs())
        .pipe($.notify(_jscsNotify));
}

function lint ( files ) { return gulp . src ( files ) . pipe ( $ . plumber ( ) ) . pipe ( $ . eslint ( ) ) . pipe ( $ . eslint . format ( ) ) . pipe ( $ . eslint . failOnError ( ) ) . pipe ( $ . jscs ( ) ) . pipe ( $ . notify ( _jscsNotify ) ) ; }


function _browserifyBundle() {
    let bundler = browserifyBundler();
    // Watch the bundler, and re-bundle it whenever files change
    bundler = watchify(bundler);
    bundler.on('update', () => _runBrowserifyBundle(bundler));

    return _runBrowserifyBundle(bundler);
}

Build the unit test suite for running tests in the browser


function PauseCommand(args, define) {
    if (args.length) {
        this.message = new statements.ExpressionStatement(args, define);
        if (this.message.error) throw this.message.error;
    } else this.message = new statements.StringStatement("[<< Paused, Press RETURN to Continue >>]");
}

Pauses execution until RETURN is pressed

@param {String} args The arguments to the command
@param {Function} define
@constructor


function ValidationErrors(errors) {
  this.errors = errors ? errors : {};

  this.addError = function(field, message) {
    if (!this.errors[field]) { this.errors[field] = []; }
    this.errors[field].push(util.format(message, field));
  };

  // omit field for full hash of errors
  this.getErrors = function(field) {
    if (field) {
      return this.errors[field];
    } else {
      return this.errors;
    }
  };

  this.hasErrors = function() {
    return _.keys(this.errors).length > 0;
  };

  this.isValidationErrors = function() {
    return true;
  };
}

function
ValidationErrors
(
errors
)
{
this
.
errors
=
errors
errors
:
{
}
;
this
.
addError
=
function
(
field
,
message
)
{
if
(
!
this
.
errors
[
field
]
)
{
this
.
errors
[
field
]
=
[
]
;
}
this
.
errors
[
field
]
.
push
(
util
.
format
(
message
,
field
)
)
;
}
;
// omit field for full hash of errors
this
.
getErrors
=
function
(
field
)
{
if
(
field
)
{
return
this
.
errors
[
field
]
;
}
else
{
return
this
.
errors
;
}
}
;
this
.
hasErrors
=
function
(
)
{
return
_
.
keys
(
this
.
errors
)
.
length
>
0
;
}
;
this
.
isValidationErrors
=
function
(
)
{
return
true
;
}
;
}


function LineCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 4) throw new SyntaxError('LINE command requires 4 arguments');
    this.x1 = parsed.args[0];
    this.y1 = parsed.args[1];
    this.x2 = parsed.args[2];
    this.y2 = parsed.args[3];
    this.width = parsed.args.length > 4 ? parsed.args[4] : false;
}

function
LineCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
4
)
throw
new
SyntaxError
(
'LINE command requires 4 arguments'
)
;
this
.
x1
=
parsed
.
args
[
0
]
;
this
.
y1
=
parsed
.
args
[
1
]
;
this
.
x2
=
parsed
.
args
[
2
]
;
this
.
y2
=
parsed
.
args
[
3
]
;
this
.
width
=
parsed
.
args
.
length
>
4
parsed
.
args
[
4
]
:
false
;
}

Draws a line

@param {String} args The arguments to the command


function PointCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 2) throw new SyntaxError('POINT command requires 2 arguments');
    this.x = parsed.args[0];
    this.y = parsed.args[1];
    if (parsed.args.length > 2) this.size = parsed.args[2];
    else this.size = false;
}

function
PointCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
2
)
throw
new
SyntaxError
(
'POINT command requires 2 arguments'
)
;
this
.
x
=
parsed
.
args
[
0
]
;
this
.
y
=
parsed
.
args
[
1
]
;
if
(
parsed
.
args
.
length
>
2
)
this
.
size
=
parsed
.
args
[
2
]
;
else
this
.
size
=
false
;
}

Draws a point

@param {String} args The arguments to the command


function getRandom(data) {
    var x = Math.sin(data.getPrivate('rnd_seed')) * 10000;
    data.setPrivate('rnd_seed', data.getPrivate('rnd_seed') + 1);
    return x - Math.floor(x);
}

function getRandom ( data ) { var x = Math . sin ( data . getPrivate ( 'rnd_seed' ) ) * 10000 ; data . setPrivate ( 'rnd_seed' , data . getPrivate ( 'rnd_seed' ) + 1 ) ; return x - Math . floor ( x ) ; }

Gets a random number using a seed

@returns {number}


function ForCommand(args, define) {
    var lowerArgs = args.toLowerCase();
    var toIndex = lowerArgs.indexOf(' to ');
    if (toIndex === -1) throw new SyntaxError('FOR has no TO');
    var assignmentText = args.substring(0, toIndex).trim();

    var stepIndex = lowerArgs.indexOf(' step ');
    var upperLimitText, stepText;
    if (stepIndex === -1) {
        upperLimitText = args.substring(toIndex + 4).trim();
        stepText = '1';
    } else {
        upperLimitText = args.substring(toIndex + 4, stepIndex).trim();
        stepText = args.substring(stepIndex + 6).trim();
    }

    var assignmentEquals = assignmentText.indexOf('=');
    if (assignmentEquals === -1) throw new SyntaxError('Expected assignment');
    var variableName = assignmentText.substring(0, assignmentEquals).trim();
    var equalsExpression = assignmentText.substring(assignmentEquals + 1).trim();
    var assignmentExpr = new statements.AssignmentStatement(
            new statements.VariableStatement(variableName),
            new statements.ExpressionStatement(equalsExpression, define)
    );

    var upperLimitExpr = new statements.ExpressionStatement(upperLimitText, define);
    if (upperLimitExpr.error) throw upperLimitExpr.error;

    var stepExpr = new statements.ExpressionStatement(stepText, define);
    if (stepExpr.error) throw stepExpr.error;

    this.assignmentExpr = assignmentExpr;
    this.upperLimitExpr = upperLimitExpr;
    this.stepExpr = stepExpr;

    this.block = define({
        start: 'FOR',
        end: 'NEXT'
    });

    this.loopCount = 0;
}

function
ForCommand
(
args
,
define
)
{
var
lowerArgs
=
args
.
toLowerCase
(
)
;
var
toIndex
=
lowerArgs
.
indexOf
(
' to '
)
;
if
(
toIndex
===
1
)
throw
new
SyntaxError
(
'FOR has no TO'
)
;
var
assignmentText
=
args
.
substring
(
0
,
toIndex
)
.
trim
(
)
;
var
stepIndex
=
lowerArgs
.
indexOf
(
' step '
)
;
var
upperLimitText
,
stepText
;
if
(
stepIndex
===
1
)
{
upperLimitText
=
args
.
substring
(
toIndex
+
4
)
.
trim
(
)
;
stepText
=
'1'
;
}
else
{
upperLimitText
=
args
.
substring
(
toIndex
+
4
,
stepIndex
)
.
trim
(
)
;
stepText
=
args
.
substring
(
stepIndex
+
6
)
.
trim
(
)
;
}
var
assignmentEquals
=
assignmentText
.
indexOf
(
'='
)
;
if
(
assignmentEquals
===
1
)
throw
new
SyntaxError
(
'Expected assignment'
)
;
var
variableName
=
assignmentText
.
substring
(
0
,
assignmentEquals
)
.
trim
(
)
;
var
equalsExpression
=
assignmentText
.
substring
(
assignmentEquals
+
1
)
.
trim
(
)
;
var
assignmentExpr
=
new
statements
.
AssignmentStatement
(
new
statements
.
VariableStatement
(
variableName
)
,
new
statements
.
ExpressionStatement
(
equalsExpression
,
define
)
)
;
var
upperLimitExpr
=
new
statements
.
ExpressionStatement
(
upperLimitText
,
define
)
;
if
(
upperLimitExpr
.
error
)
throw
upperLimitExpr
.
error
;
var
stepExpr
=
new
statements
.
ExpressionStatement
(
stepText
,
define
)
;
if
(
stepExpr
.
error
)
throw
stepExpr
.
error
;
this
.
assignmentExpr
=
assignmentExpr
;
this
.
upperLimitExpr
=
upperLimitExpr
;
this
.
stepExpr
=
stepExpr
;
this
.
block
=
define
(
{
start
:
'FOR'
,
end
:
'NEXT'
}
)
;
this
.
loopCount
=
0
;
}

Iterates over the body a certain amount of times

@param {String} args The arguments to the command
@param {Function} define
@constructor


function Emitter(opts) {
  Transform.call(this);
  this._writableState.objectMode = true;
  this._readableState.objectMode = true;
  opts = opts || {};
  // emit a fixed event name
  // rather than the default type
  this.name = opts.name;

  this.passthrough = opts.passthrough;
}

function
Emitter
(
opts
)
{
Transform
.
call
(
this
)
;
this
.
_writableState
.
objectMode
=
true
;
this
.
_readableState
.
objectMode
=
true
;
opts
=
opts
||
{
}
;
// emit a fixed event name
// rather than the default type
this
.
name
=
opts
.
name
;
this
.
passthrough
=
opts
.
passthrough
;
}

Emits the output of the decoder as named events.

Emits the output of the decoder as named events .


function freeMemory (mappedVars /*: Array<SublimeObject>*/, step /*: ?StepObject*/) /*: Promise<any> | void*/ {
  if (mappedVars.length > 0) {
    let mappedVarsStringify = []
    for (let mappedVar /*: Object*/ of mappedVars) {
      if (mappedVar.hasOwnProperty("self") && mappedVar.self) {
        delete mappedVar.self.code
        mappedVarsStringify.push(JSON.stringify(mappedVar.self))
      }
    }
    return simpleEval(`freeMemory(json.loads("""[${mappedVarsStringify.join(',')}]"""))`, false, step)
  }
}

function
freeMemory
(
mappedVars
/*: Array<SublimeObject>*/
,
step
/*: ?StepObject*/
)
/*: Promise<any> | void*/
{
if
(
mappedVars
.
length
>
0
)
{
let
mappedVarsStringify
=
[
]
for
(
let
mappedVar
/*: Object*/
of
mappedVars
)
{
if
(
mappedVar
.
hasOwnProperty
(
"self"
)
&&
mappedVar
.
self
)
{
delete
mappedVar
.
self
.
code
mappedVarsStringify
.
push
(
JSON
.
stringify
(
mappedVar
.
self
)
)
}
}
return
simpleEval
(
`
${
mappedVarsStringify
.
join
(
','
)
}
`
,
false
,
step
)
}
}

Free memory of ```mappedVars``` on the Python server side.

Free memory of mappedVars on the Python server side .


function DrawtextCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length < 3) throw new SyntaxError('DRAWTEXT command requires 3 arguments');
    else if (parsed.args.length > 3 && parsed.args.length < 5) throw new SyntaxError('DRAWTEXT command requires 5 arguments');

    this.text = parsed.args[0];
    this.x1 = parsed.args[1];
    this.y1 = parsed.args[2];
    if (parsed.args.length > 3) {
        this.x2 = parsed.args[3];
        this.y2 = parsed.args[4];
    } else {
        this.x2 = false;
        this.y2 = false;
    }
}

function
DrawtextCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
3
)
throw
new
SyntaxError
(
'DRAWTEXT command requires 3 arguments'
)
;
else
if
(
parsed
.
args
.
length
>
3
&&
parsed
.
args
.
length
<
5
)
throw
new
SyntaxError
(
'DRAWTEXT command requires 5 arguments'
)
;
this
.
text
=
parsed
.
args
[
0
]
;
this
.
x1
=
parsed
.
args
[
1
]
;
this
.
y1
=
parsed
.
args
[
2
]
;
if
(
parsed
.
args
.
length
>
3
)
{
this
.
x2
=
parsed
.
args
[
3
]
;
this
.
y2
=
parsed
.
args
[
4
]
;
}
else
{
this
.
x2
=
false
;
this
.
y2
=
false
;
}
}

Draws text either at a point or inside a rectangle

@param {String} args The arguments to the command


function writeLockFile(path, data, cb) { // Like fs.writeFile within a lock.
    lock(path, function (unlock) {
        fse.writeFile(path, data, function (e, d) { unlock(); cb(e, d); });
    });
}

function
writeLockFile
(
path
,
data
,
cb
)
{
// Like fs.writeFile within a lock.
lock
(
path
,
function
(
unlock
)
{
fse
.
writeFile
(
path
,
data
,
function
(
e
,
d
)
{
unlock
(
)
;
cb
(
e
,
d
)
;
}
)
;
}
)
;
}

Should we consider using the operating system's synchronization or exclusivity utilities instead of our own locks?

Should we consider using the operating system s synchronization or exclusivity utilities instead of our own locks?


function callHandlers(cults, e) {
    var broken = false;

    for (var i = 0; i < cults.length; i++) {
        var cult = cults[i];
        var handlers = cult && cult.events && cult.events[e.type];

        if (!handlers) continue;

        var selectors = Object.keys(handlers);

        if (callHandler(cult, e, handlers, selectors) === false) {
            broken = true;
            break;
        }
    }

    return broken;
}

function callHandlers ( cults , e ) { var broken = false ; for ( var i = 0 ; i < cults . length ; i ++ ) { var cult = cults [ i ] ; var handlers = cult && cult . events && cult . events [ e . type ] ; if ( ! handlers ) continue ; var selectors = Object . keys ( handlers ) ; if ( callHandler ( cult , e , handlers , selectors ) === false ) { broken = true ; break ; } } return broken ; }

Given a list of cultsRegistry, checks whether any component would respond to the given event and if so, executes the
event handler defined in the component.

Given a list of cultsRegistry checks whether any component would respond to the given event and if so executes the event handler defined in the component .


function(def) {
        var start = Array.isArray(def.start) ? def.start : [def.start];
        var end = Array.isArray(def.end) ? def.end : [def.end];
        var then = def.then ? (Array.isArray(def.then) ? def.then : [def.then]) : [];

        var child = new Block(line, {
            start: start,
            end: end,
            then: then
        }, self);
        self.children.push(child);
        return child;
    }

function ( def ) { var start = Array . isArray ( def . start ) ? def . start : [ def . start ] ; var end = Array . isArray ( def . end ) ? def . end : [ def . end ] ; var then = def . then ? ( Array . isArray ( def . then ) ? def . then : [ def . then ] ) : [ ] ; var child = new Block ( line , { start : start , end : end , then : then } , self ) ; self . children . push ( child ) ; return child ; }

Creates a block with the specified definition

@param {Object} def The block definition
@returns {Block}


function entry(object) {
  var buffer;
  switch(object.type) {
    case 'header':
      buffer = this.header(object.version);
      break;
    case 'database':
      buffer = this.database(object.number);
      break;
    case 'key':
      buffer = this.key(object);
      //console.dir(object.type);
      //console.dir(buffer);
      break;
    case 'eof':
      buffer = this.eof();
      break;
  }
  return buffer;
}

function entry ( object ) { var buffer ; switch ( object . type ) { case 'header' : buffer = this . header ( object . version ) ; break ; case 'database' : buffer = this . database ( object . number ) ; break ; case 'key' : buffer = this . key ( object ) ; //console.dir(object.type); //console.dir(buffer); break ; case 'eof' : buffer = this . eof ( ) ; break ; } return buffer ; }


function database(n) {
  var dbid = new Buffer([0xFE])
    , len = this.getLengthEncoding(n, false);
  return Buffer.concat([dbid, len], dbid.length + len.length);
}

function database ( n ) { var dbid = new Buffer ( [ 0xFE ] ) , len = this . getLengthEncoding ( n , false ) ; return Buffer . concat ( [ dbid , len ] , dbid . length + len . length ) ; }


function key(obj, vonly) {
  var buffer = new Buffer(0)
    , item;
  if(obj.expiry !== undefined && !vonly) {
    buffer = this.expiry(obj.expiry);
  }
  item = this[obj.rtype](obj, vonly);
  return Buffer.concat(
    [
      buffer,
      item
    ],
    buffer.length + item.length
  )
}

function key ( obj , vonly ) { var buffer = new Buffer ( 0 ) , item ; if ( obj . expiry !== undefined && ! vonly ) { buffer = this . expiry ( obj . expiry ) ; } item = this [ obj . rtype ] ( obj , vonly ) ; return Buffer . concat ( [ buffer , item ] , buffer . length + item . length ) }

Get the buffer for a key.

@param obj The object representing the key and value.
@param vonly A boolean that forces only the value to be encoded.


function expiry(expires) {
  var buffer
    , int64;
  if(expires % 1000 === 0) {
    buffer = new Buffer(5);
    buffer.writeUInt8(0xFD, 0);
    buffer.writeInt32LE(expires / 1000, 1);
  }else{
    buffer = new Buffer(9);
    int64 = new Int64(expires);
    buffer.writeUInt8(0xFC, 0);
    buffer.writeUInt32LE(int64.low32(), 1);
    buffer.writeUInt32LE(int64.high32(), 5);
  }
  return buffer;
}

function expiry ( expires ) { var buffer , int64 ; if ( expires % 1000 === 0 ) { buffer = new Buffer ( 5 ) ; buffer . writeUInt8 ( 0xFD , 0 ) ; buffer . writeInt32LE ( expires / 1000 , 1 ) ; } else { buffer = new Buffer ( 9 ) ; int64 = new Int64 ( expires ) ; buffer . writeUInt8 ( 0xFC , 0 ) ; buffer . writeUInt32LE ( int64 . low32 ( ) , 1 ) ; buffer . writeUInt32LE ( int64 . high32 ( ) , 5 ) ; } return buffer ; }


function string(obj, vonly) {
  var vtype = this.type(0)
    , key = !vonly ? this.getStringBuffer(obj.key) : new Buffer(0)
    , value = this.getStringBuffer(obj.value);
  return Buffer.concat(
    [
      vtype,
      key,
      value
    ],
    vtype.length + key.length + value.length
  )
}

function string ( obj , vonly ) { var vtype = this . type ( 0 ) , key = ! vonly ? this . getStringBuffer ( obj . key ) : new Buffer ( 0 ) , value = this . getStringBuffer ( obj . value ) ; return Buffer . concat ( [ vtype , key , value ] , vtype . length + key . length + value . length ) }


function list(obj, vonly) {
  var vtype = this.type(1)
    , key = !vonly ? this.getStringBuffer(obj.key) : new Buffer(0)
    , len = this.getLengthEncoding(obj.value.length, false)
    , value = this.array(obj.value);
  return Buffer.concat(
    [
      vtype,
      key,
      len,
      value
    ],
    vtype.length + key.length + len.length + value.length
  )
}

function list ( obj , vonly ) { var vtype = this . type ( 1 ) , key = ! vonly ? this . getStringBuffer ( obj . key ) : new Buffer ( 0 ) , len = this . getLengthEncoding ( obj . value . length , false ) , value = this . array ( obj . value ) ; return Buffer . concat ( [ vtype , key , len , value ] , vtype . length + key . length + len . length + value . length ) }


function zset(obj, vonly) {
  var vtype = this.type(3)
    , key = !vonly ? this.getStringBuffer(obj.key) : new Buffer(0)
    , length = obj.length !== undefined
        ? obj.length : Object.keys(obj.value).length
    , len = this.getLengthEncoding(length, false)
    , value = this.object(obj.value);
  return Buffer.concat(
    [
      vtype,
      key,
      len,
      value
    ],
    vtype.length + key.length + len.length + value.length
  )
}

function zset ( obj , vonly ) { var vtype = this . type ( 3 ) , key = ! vonly ? this . getStringBuffer ( obj . key ) : new Buffer ( 0 ) , length = obj . length !== undefined ? obj . length : Object . keys ( obj . value ) . length , len = this . getLengthEncoding ( length , false ) , value = this . object ( obj . value ) ; return Buffer . concat ( [ vtype , key , len , value ] , vtype . length + key . length + len . length + value . length ) }


function array(arr) {
  var buffers = []
    , buf
    , i
    , len = 0;
  for(i = 0; i < arr.length; i++) {
    buf = this.getStringBuffer(arr[i]);
    len += buf.length;
    buffers.push(buf);
  }
  return Buffer.concat(buffers, len);
}

function array ( arr ) { var buffers = [ ] , buf , i , len = 0 ; for ( i = 0 ; i < arr . length ; i ++ ) { buf = this . getStringBuffer ( arr [ i ] ) ; len += buf . length ; buffers . push ( buf ) ; } return Buffer . concat ( buffers , len ) ; }


function object(obj) {
  var buffers = []
    , buf
    , k
    , v
    , len = 0;
  for(k in obj) {
    buf = this.getStringBuffer(k);
    len += buf.length;
    buffers.push(buf);

    buf = this.getStringBuffer(obj[k]);
    len += buf.length;
    buffers.push(buf);
  }
  return Buffer.concat(buffers, len);
}

function object ( obj ) { var buffers = [ ] , buf , k , v , len = 0 ; for ( k in obj ) { buf = this . getStringBuffer ( k ) ; len += buf . length ; buffers . push ( buf ) ; buf = this . getStringBuffer ( obj [ k ] ) ; len += buf . length ; buffers . push ( buf ) ; } return Buffer . concat ( buffers , len ) ; }


function getStringBuffer(s) {
  var buffer
    , n = typeof s === 'number' ? s : null
    // compressed header buffer
    , cheader
    , compressed;

  // Does it look like a number?
  if(n !== null
    || typeof s === 'string' && s.match(/^-?\d+$/)) {
    if(n === null) {
      n = parseInt(s);
    }
    if (n >= -128 && n <= 127) {
      buffer = new Buffer(1);
      buffer.writeInt8(n, 0);
      buffer = this.length(buffer, 0, true);
      return buffer;
    } else if (n >= -32768 && n <= 32767) {
      buffer = new Buffer(2);
      buffer.writeInt16LE(n, 0);
      buffer = this.length(buffer, 1, true);
      return buffer;
    } else if (n >= -2147483648 && n <= 2147483647) {
      buffer = new Buffer(4);
      buffer.writeInt32LE(n, 0);
      buffer = this.length(buffer, 2, true);
      return buffer;
    }
  }

  // It doesn't look like a number, or it's too big
  if(typeof s === 'string') {
    buffer = new Buffer(s, this.encoding);
  }else if(s instanceof Buffer){
    buffer = s;
  }

  if(buffer.length > this.compressionThreshold) {
    compressed = lzf.compress(buffer);
    if (compressed.length < buffer.length) {
      // It saved some space
      cheader = Buffer.concat(
        [
          this.getLengthEncoding(3, true),
          this.getLengthEncoding(compressed.length, false),
          this.getLengthEncoding(buffer.length, false)
        ]);
      return Buffer.concat(
        [cheader, compressed], cheader.length + compressed.length);
    }
  }

  buffer = this.length(buffer, buffer.length, false);
  return buffer;
}


function length(buffer, n, special) {
  var len = this.getLengthEncoding(n, special);
  return Buffer.concat([len, buffer], len.length + buffer.length);
}

function length ( buffer , n , special ) { var len = this . getLengthEncoding ( n , special ) ; return Buffer . concat ( [ len , buffer ] , len . length + buffer . length ) ; }

Concatenate a buffer with length encoding.

Concatenate a buffer with length encoding .


function getLengthEncoding(n, special) {
  if(n < 0) throw new Error('Cannot write negative length encoding: ' + n);
  if(!special) {
    if(n <= 0x3F) {
      return new Buffer([n]);
    }else if (n <= 0x3FFF) {
      return new Buffer([0x40 | (n >> 8), n & 0xFF]);
    }else if (n <= 0xFFFFFFFF) {
      var buffer = new Buffer(5);
      buffer.writeUInt8(0x80, 0);
      buffer.writeUInt32BE(n, 1);
      return buffer;
    }
    throw new Error('Failed to write length encoding: ' + n);
  }else{
    if (n > 0x3F) {
      throw new Error('Cannot encode ' + n + ' using special length encoding');
    }
    return new Buffer([0xC0 | n]);
  }
}


function TextfontCommand(args) {
    var parsed = new statements.ArgumentStatement(args);

    if (parsed.args.length > 2) {
        this.family = parsed.args[0];
        this.style = parsed.args[1];
        this.size = parsed.args[2];
    } else if (parsed.args.length > 1) {
        this.familyOrStyle = parsed.args[0];
        this.size = parsed.args[1];
    } else if (parsed.args.length > 0) {
        var arg = parsed.args[0];
        if (arg.child.type === 'string' || arg.child instanceof statements.StringStatement) this.familyOrStyle = arg;
        else this.size = arg;
    } else {
        this.reset = true;
    }
}

function TextfontCommand ( args ) { var parsed = new statements . ArgumentStatement ( args ) ; if ( parsed . args . length > 2 ) { this . family = parsed . args [ 0 ] ; this . style = parsed . args [ 1 ] ; this . size = parsed . args [ 2 ] ; } else if ( parsed . args . length > 1 ) { this . familyOrStyle = parsed . args [ 0 ] ; this . size = parsed . args [ 1 ] ; } else if ( parsed . args . length > 0 ) { var arg = parsed . args [ 0 ] ; if ( arg . child . type === 'string' || arg . child instanceof statements . StringStatement ) this . familyOrStyle = arg ; else this . size = arg ; } else { this . reset = true ; } }

Modifies the DRAWTEXT font

@param {String} args The arguments to the command


function MerchantCalculations (objGoogleCheckout) {
	var self = this;

	//todo: check the constructor name
	assert.ok(objGoogleCheckout, "A GoogleCheckout object is the only required argument");

	self.gc = objGoogleCheckout;
	self.settings = self.gc.settings;
}

Instantiate an instance of the GoogleCheckout MerchantCalculations prototype

Examples:

@param {Object} objGoogleCheckout an instance of a `GoogleCheckout` object object
@return {Object} Polling Object
@api public


function replace(value, configData) {
    if (typeof value != "string") {
        return value;
    } else {
        return value.replace(propStringTmplRe, function(match, path) {
            var value = get(configData, path);
            if (!(value instanceof Error)) {
                return value;
            } else {
                return match;
            }
        });
    }
}

function replace ( value , configData ) { if ( typeof value != "string" ) { return value ; } else { return value . replace ( propStringTmplRe , function ( match , path ) { var value = get ( configData , path ) ; if ( ! ( value instanceof Error ) ) { return value ; } else { return match ; } } ) ; } }

Get the value of a configuration parameter that might use templates
@param {String} value Configuration value
@param {Object} configData Container object
@return {String} String with replacements


function get(object, path) {
    if (memoGet[path]) {
        return new Error("circular reference for " + path);
    }
    var parts = path.split(".");
    var obj = object;

    while (typeof obj === "object" && obj && parts.length) {
        var part = parts.shift();
        if (!(part in obj)) {
            return new Error("invalid path");
        }
        obj = obj[part];
    }
    memoGet[path] = true;
    // The replace can cause a circular reference
    var value = replace(obj, object);
    delete memoGet[path];
    return value;
}

Get the value of a json object at a given path
@param {Object} object Container object
@param {String} path Path, delimited by dots
@return {Object} value


function checkBug() {
    // Check if it works on newly created node (fails in IE 9)
    var a = document.createElement('div');
    if (method.call(a, 'div')) {
        return false;
    }

    // Check if it works when node is appended to another node (works in IE 9)
    var b = document.createElement('div');
    a.appendChild(b);
    return method.call(b, 'div');
}

Work around IE 9 bug where it always returns false when not attached to another DOM node. Check if the bug exists in this browser

Work around IE 9 bug where it always returns false when not attached to another DOM node . Check if the bug exists in this browser


function workaround() {
    var node = document.createElement('div');

    function matches(element, selector) {
        if (method.call(element, selector)) {
            return true;
        } else if (!element.parentNode) {
            // If node is not attached, temporarily attach to node
            node.appendChild(element);
            var result = method.call(element, selector);
            node.removeChild(element);
            return result;
        } else {
            return false;
        }
    }

    return matches;
}

Return a workaround function to fix the bug. Note that this will slow down matching, but only if the bug exists in this browser.

Return a workaround function to fix the bug . Note that this will slow down matching but only if the bug exists in this browser .


function allow(action, req, res, cb) {
		// call the allow method in our options if it exists
		// or we will just assume it is always allowed
		if (options.allow) {
			return options.allow.apply(this, arguments);
		}

		return cb && cb(null, true);
	}

calls a method called 'allow' in our options that will
perform any access checking

@author Tim Golen 2015-03-01
@access private

@param  {string} action the CRUD actions being done
@param  {object} req an Express or Restify Request object
@param  {object} res an Express or Restify Response object
@param  {Function} cb
if request is allowed, cb(null, true)
if request is not allowed, cb(null, false)

@return {void}

calls a method called allow in our options that will perform any access checking


function clean(action, result, req, res, cb) {
		// call the clean method in our options if it exists
		// or we will just assume it is always clean
		if (options.clean) {
			return options.clean.apply(this, arguments);
		}
		return cb && cb();
	}

calls a method called 'clean' in our options that will
perform any cleaning on the object being acted upon.
If we're doing a create, then it gets cleaned before going into the DB
If we're doing an update, then it gets cleaned before the response
is sent

@author Tim Golen 2015-03-01
@access private

@param  {string} action the CRUD actions being done
@param  {object} result that needs to be cleaned
@param  {object} req an Express or Restify Request object
@param  {object} res an Express or Restify Response object
@param  {Function} cb
will pass a server error as the first argument if necessary

@return {void}

calls a method called clean in our options that will perform any cleaning on the object being acted upon . If we re doing a create then it gets cleaned before going into the DB If we re doing an update then it gets cleaned before the response is sent


function find(action, req, res, cb) {
		var result = {};
		// TODO: run our query

		// clean our result
		clean(action, result, req, res, function(err) {
			if (err) {
				return cb(err);
			}

			// see if there is a method in our options that we need
			// to run once we have found our results
			if (options.found) {
				options.found(result, req, res, cb);
			} else {
				cb && cb(null, result);
			}
		});
	}

Runs a query to get our result, then cleans the result
calls an optional 'found' method if it exists in the options

@author Tim Golen 2015-03-01
@access private

@param  {string} action the CRUD actions being done
@param  {object} req an Express or Restify Request object
@param  {object} res an Express or Restify Response object
@param  {Function} cb
passed an error as the first argument if it exists
passes the result as the second argument

@return {void}

Runs a query to get our result then cleans the result calls an optional found method if it exists in the options


function dispatch(ctx) {

        if (_curCtx) {
            var ret = _curCtx.route.exit({
                path: _curCtx.path,
                params: _curCtx.params
            }, true);
            if (!ret) {
                return;
            }
        }

        _prevCtx = _curCtx;
        _curCtx = ctx;
        if (!_curCtx.route) {
            var m = map(_curCtx.path);
            _curCtx.route = m.route;
            _curCtx.params = m.params;
        }

        var r = _curCtx.route.enter({
            force: _curCtx.force,
            path: _curCtx.path,
            params: _curCtx.params
        },true);

        langx.Deferred.when(r).then(function() {
            _hub.trigger(createEvent("routing", {
                current: _curCtx,
                previous: _prevCtx
            }));

            _curCtx.route.enter({
                path: _curCtx.path,
                params: _curCtx.params
            },false);

            if (_prevCtx) {
                _prevCtx.route.exit({
                    path: _prevCtx.path,
                    params: _prevCtx.params
                }, false);
            }

            _hub.trigger(createEvent("routed", {
                current: _curCtx,
                previous: _prevCtx
            }));
        });
    }

function dispatch ( ctx ) { if ( _curCtx ) { var ret = _curCtx . route . exit ( { path : _curCtx . path , params : _curCtx . params } , true ) ; if ( ! ret ) { return ; } } _prevCtx = _curCtx ; _curCtx = ctx ; if ( ! _curCtx . route ) { var m = map ( _curCtx . path ) ; _curCtx . route = m . route ; _curCtx . params = m . params ; } var r = _curCtx . route . enter ( { force : _curCtx . force , path : _curCtx . path , params : _curCtx . params } , true ) ; langx . Deferred . when ( r ) . then ( function ( ) { _hub . trigger ( createEvent ( "routing" , { current : _curCtx , previous : _prevCtx } ) ) ; _curCtx . route . enter ( { path : _curCtx . path , params : _curCtx . params } , false ) ; if ( _prevCtx ) { _prevCtx . route . exit ( { path : _prevCtx . path , params : _prevCtx . params } , false ) ; } _hub . trigger ( createEvent ( "routed" , { current : _curCtx , previous : _prevCtx } ) ) ; } ) ; }


function start() {
        if (router.useHashbang == null && router.useHistoryApi == null) {
            if (window.location.host  && window.history.pushState) {
                //web access
                router.useHistoryApi = true;
            } else {
                // local access
                router.useHashbang = true;
            }
        }

        var initPath = "";

        if (router.useHistoryApi) {
            initPath = window.location.pathname;
            if (_baseUrl === undefined) {
                _baseUrl = initPath.replace(/\/$/, "");
            }
            initPath = initPath.replace(_baseUrl, "") || _homePath || "/";
        } else if (router.useHashbang) {
            initPath = window.location.hash.replace("#!", "") || _homePath || "/";
        } else {
            initPath = "/";
        }

        if (!initPath.startsWith("/")) {
            initPath = "/" + initPath;
        }
        /*
        eventer.on(document.body, "click", "a[href]", function(e) {
            var elm = e.currentTarget,
                url = elm.getAttribute("href");

            if (url == "#") {
                return;
            }
            if (url && langx.isSameOrigin(elm.href)) {
                if (url.indexOf(_baseUrl) === 0) {
                    url = url.substr(_baseUrl.length);
                    eventer.stop(e);
                    url = url.replace('#!', '');
                    go(url);
                }
            }
        });
        */
        if (router.useHistoryApi) {
            window.addEventListener("popstate", function(e) {
                if(e.state) dispatch(e.state);
                e.preventDefault();
            });
        } else if (router.useHashbang) {
            window.addEventListener("hashchange", function(e) {
                dispatch({
                    path: window.location.hash.replace(/^#!/, "")
                });
                e.preventDefault();
            });
        }

        go(initPath);
    }


function() {
            var curCtx = router.current(),
                prevCtx = router.previous();
            var content = curCtx.route.render(curCtx);
            if (content===undefined || content===null) {
                return;
            }
            if (langx.isString(content)) {
                this._rvc.innerHTML = content;
            } else {
                this._rvc.innerHTML = "";
                this._rvc.appendChild(content);
            }
            curCtx.route.trigger(createEvent("rendered", {
                route: curCtx.route,
                content: content
            }));
        }

function ( ) { var curCtx = router . current ( ) , prevCtx = router . previous ( ) ; var content = curCtx . route . render ( curCtx ) ; if ( content === undefined || content === null ) { return ; } if ( langx . isString ( content ) ) { this . _rvc . innerHTML = content ; } else { this . _rvc . innerHTML = "" ; this . _rvc . appendChild ( content ) ; } curCtx . route . trigger ( createEvent ( "rendered" , { route : curCtx . route , content : content } ) ) ; }


function(key) {
        var value;
        if (key.indexOf('.') == -1) {
            value = this.configObj[key];
        } else {
            var keyArray = key.split('.');
            var keyStr = keyArray[0];
            value = this.configObj[keyStr];
            for(var i= 1,len=keyArray.length;i<len;i++) {
                if (!value && i < len-1) {
                    exitProcess('the var ['+keyStr + '] is empty.', this.alarm);
                    return undefined;
                }
                var keyNow = keyArray[i];
                keyStr += '.'+keyNow;
                value = value[keyNow];
            }
        }
        slogger.debug('load var ['+key+'],value:',value);
        return value;
    }

function
(
key
)
{
var
value
;
if
(
key
.
indexOf
(
'.'
)
==
1
)
{
value
=
this
.
configObj
[
key
]
;
}
else
{
var
keyArray
=
key
.
split
(
'.'
)
;
var
keyStr
=
keyArray
[
0
]
;
value
=
this
.
configObj
[
keyStr
]
;
for
(
var
i
=
1
,
len
=
keyArray
.
length
;
i
<
len
;
i
++
)
{
if
(
!
value
&&
i
<
len
1
)
{
exitProcess
(
'the var ['
+
keyStr
+
'] is empty.'
,
this
.
alarm
)
;
return
undefined
;
}
var
keyNow
=
keyArray
[
i
]
;
keyStr
+=
'.'
+
keyNow
;
value
=
value
[
keyNow
]
;
}
}
slogger
.
debug
(
'load var ['
+
key
+
'],value:'
,
value
)
;
return
value
;
}

Get value by key

@param {KeyItem} key
@returns {String|Object}


function(key) {
        var value = this.loadVar(key);
        if (typeof(value) =='undefined') {
            exitProcess('the value of ' + key + ' is necessary , but now is undefined', this.alarm);
            return false;
        }
        return value;
    }

function
(
key
)
{
var
value
=
this
.
loadVar
(
key
)
;
if
(
typeof
(
value
)
==
'undefined'
)
{
exitProcess
(
'the value of '
+
key
+
' is necessary , but now is undefined'
,
this
.
alarm
)
;
return
false
;
}
return
value
;
}

Get value by key, the value must be exist, otherwise the process will exit.

@param {KeyItem} key
@returns {String|Object}

Get value by key the value must be exist otherwise the process will exit .


function(key) {
        var str = this.loadVar(key);
        if (typeof (str) != 'string') {
            exitProcess('the value of ' + key + ' is a necessary string, but get ' + str, this.alarm);
            return false;
        }
        return str;
    }

function
(
key
)
{
var
str
=
this
.
loadVar
(
key
)
;
if
(
typeof
(
str
)
!=
'string'
)
{
exitProcess
(
'the value of '
+
key
+
' is a necessary string, but get '
+
str
,
this
.
alarm
)
;
return
false
;
}
return
str
;
}

Get string value by key, the value must be exist, otherwise the process will exit.

@param {KeyItem} key
@returns {String}

Get string value by key the value must be exist otherwise the process will exit .


function(key) {
        var num = parseInt(this.loadVar(key));
        if (isNaN(num)) {
            exitProcess('the value of ' +key+' is a necessary int ,but get ' + num, this.alarm);
            return false;
        }
        return num;
    }

function
(
key
)
{
var
num
=
parseInt
(
this
.
loadVar
(
key
)
)
;
if
(
isNaN
(
num
)
)
{
exitProcess
(
'the value of '
+
key
+
' is a necessary int ,but get '
+
num
,
this
.
alarm
)
;
return
false
;
}
return
num
;
}

Get integer value by key, the value must be exist, otherwise the process will exit.

@param {KeyItem} key
@returns {Integer}

Get integer value by key the value must be exist otherwise the process will exit .


function(key) {
        var obj = this.loadVar(key);
        if (!obj || typeof (obj) != 'object') {
            exitProcess('the value of ' +key+' is a necessary object ,but get '+ obj, this.alarm);
            return false;
        }
        return obj;
    }

function
(
key
)
{
var
obj
=
this
.
loadVar
(
key
)
;
if
(
!
obj
||
typeof
(
obj
)
!=
'object'
)
{
exitProcess
(
'the value of '
+
key
+
' is a necessary object ,but get '
+
obj
,
this
.
alarm
)
;
return
false
;
}
return
obj
;
}

Get object value by key, the value must be exist, otherwise the process will exit.

@param {KeyItem} key
@returns {Object}

Get object value by key the value must be exist otherwise the process will exit .


function(key,onlyCheckDirectory) {
        var filePath = this.loadVar(key);
        if (!filePath) {
            exitProcess('empty file path for ' + key, this.alarm);
            return false;
        }
        if (!onlyCheckDirectory) {
            if (!fs.existsSync(filePath)) {
                exitProcess('the value of ' +key+' is a necessary file ,but not exists in '+ filePath, this.alarm);
                return false;
            }
        } else {
            var dirname = path.dirname(filePath);
            if (!fs.lstatSync(dirname).isDirectory()) {
                exitProcess('the path '+dirname + ' must exist and be a directory', this.alarm);
                return false;
            }
        }

        return filePath;
    }

Get file path by key, the value must be exist, otherwise the process will exit.

@param {KeyItem} key
@param {Boolean} [onlyCheckDirectory=false] If set true, only check whether the directory that the file saved is exist.
@returns {String}

Get file path by key the value must be exist otherwise the process will exit .


function(key,endWithSeparator) {
        var filepath = this.loadNecessaryFile(key);
        if (!filepath) {
            exitProcess('empty directory for ' + key, this.alarm);
            return false;
        }
        if (!fs.lstatSync(filepath).isDirectory()) {
            exitProcess('the path '+filepath + ' must be a directory', this.alarm);
            return false;
        }
        if (endWithSeparator && !filepath.endWith(path.sep)) {
            exitProcess('the path '+filepath + ' must be end with a separator', this.alarm);
            return false;
        }
        return filepath;
    }

function
(
key
,
endWithSeparator
)
{
var
filepath
=
this
.
loadNecessaryFile
(
key
)
;
if
(
!
filepath
)
{
exitProcess
(
'empty directory for '
+
key
,
this
.
alarm
)
;
return
false
;
}
if
(
!
fs
.
lstatSync
(
filepath
)
.
isDirectory
(
)
)
{
exitProcess
(
'the path '
+
filepath
+
' must be a directory'
,
this
.
alarm
)
;
return
false
;
}
if
(
endWithSeparator
&&
!
filepath
.
endWith
(
path
.
sep
)
)
{
exitProcess
(
'the path '
+
filepath
+
' must be end with a separator'
,
this
.
alarm
)
;
return
false
;
}
return
filepath
;
}

Get directory path by key, the value must be exist, otherwise the process will exit.

@param {KeyItem} key
@param {Boolean} [endWithSeparator=false] If set ture, the key must be end with `/`(Linux) or `\`(Windows).
@returns {String}

Get directory path by key the value must be exist otherwise the process will exit .


function(key,endWithSeparator) {
        var url = this.loadNecessaryString(key);
        if (!url) {
            exitProcess('empty url for ' + key, this.alarm);
            return false;
        }
        if (!url.startWith('http://') && !url.startWith('https://')) {
            exitProcess('invalid url:' + url, this.alarm);
            return false;
        }
        if (endWithSeparator && !url.endWith('/')) {
            exitProcess('the url['+url+'] must be end with /', this.alarm);
            return false;
        }
        if (!endWithSeparator && url.endWith('/')) {
            exitProcess('the url['+url+'] must not be end with /', this.alarm);
            return false;
        }
        return url;
    }

function
(
key
,
endWithSeparator
)
{
var
url
=
this
.
loadNecessaryString
(
key
)
;
if
(
!
url
)
{
exitProcess
(
'empty url for '
+
key
,
this
.
alarm
)
;
return
false
;
}
if
(
!
url
.
startWith
(
'http://'
)
&&
!
url
.
startWith
(
'https://'
)
)
{
exitProcess
(
'invalid url:'
+
url
,
this
.
alarm
)
;
return
false
;
}
if
(
endWithSeparator
&&
!
url
.
endWith
(
'/'
)
)
{
exitProcess
(
'the url['
+
url
+
'] must be end with /'
,
this
.
alarm
)
;
return
false
;
}
if
(
!
endWithSeparator
&&
url
.
endWith
(
'/'
)
)
{
exitProcess
(
'the url['
+
url
+
'] must not be end with /'
,
this
.
alarm
)
;
return
false
;
}
return
url
;
}

Get URL by key, the value must be exist, otherwise the process will exit.

@param {KeyItem} key
@param {Boolean} [endWithSeparator=false] If set ture, the key must be end with `/`.
@returns {String}

Get URL by key the value must be exist otherwise the process will exit .


function VariableStatement(name) {
    var bracketIndex = name.indexOf('(');
    if (bracketIndex !== -1) {
        var endBracketIndex = name.indexOf(')');
        if (endBracketIndex === -1) throw new SyntaxError('Expected end bracket');

        var arrayName = name.substring(0, bracketIndex);
        var arrayDimensionsText = name.substring(bracketIndex + 1, endBracketIndex).trim();
        var arrayDimensions = new statements.ArgumentStatement(arrayDimensionsText);

        name = arrayName;
        this.isArray = true;
        this.dimensions = arrayDimensions.args;
    } else this.isArray = false;

    if (name[name.length - 1] === '$') {
        this.type = 'string';
        this.name = name.substring(0, name.length - 1);
    } else {
        this.type = 'number';
        this.name = name;
    }
}

function
VariableStatement
(
name
)
{
var
bracketIndex
=
name
.
indexOf
(
'('
)
;
if
(
bracketIndex
!==
1
)
{
var
endBracketIndex
=
name
.
indexOf
(
')'
)
;
if
(
endBracketIndex
===
1
)
throw
new
SyntaxError
(
'Expected end bracket'
)
;
var
arrayName
=
name
.
substring
(
0
,
bracketIndex
)
;
var
arrayDimensionsText
=
name
.
substring
(
bracketIndex
+
1
,
endBracketIndex
)
.
trim
(
)
;
var
arrayDimensions
=
new
statements
.
ArgumentStatement
(
arrayDimensionsText
)
;
name
=
arrayName
;
this
.
isArray
=
true
;
this
.
dimensions
=
arrayDimensions
.
args
;
}
else
this
.
isArray
=
false
;
if
(
name
[
name
.
length
1
]
===
'$'
)
{
this
.
type
=
'string'
;
this
.
name
=
name
.
substring
(
0
,
name
.
length
1
)
;
}
else
{
this
.
type
=
'number'
;
this
.
name
=
name
;
}
}

Represents a variable

@param {String} name The name of the variable


function() {
    var versions = ["Msxml2.XMLHTTP",
                    "Msxml3.XMLHTTP",
                    "Microsoft.XMLHTTP",
                    "MSXML2.XmlHttp.6.0",
                    "MSXML2.XmlHttp.5.0",
                    "MSXML2.XmlHttp.4.0",
                    "MSXML2.XmlHttp.3.0",
                    "MSXML2.XmlHttp.2.0"
    ]

    if(XMLHttpRequest !== undefined) {  // For non-IE browsers
        createXMLHTTPObject = function() {  // Use memoization to cache the factory
            return new XMLHttpRequest()
        }
        return createXMLHTTPObject()

    } else { // IE
        for(var i=0, n=versions.length; i<n; i++) {
            try {
                var version = versions[i]
                var fn = function() {
                    return new ActiveXObject(version)
                }
                createXMLHTTPObject = fn   // Use memoization to cache the factory
                return createXMLHTTPObject()

            } catch(e) {   }
        }
    }

    throw new Error('Cant get XmlHttpRequest object')
}

function
(
)
{
var
versions
=
[
"Msxml2.XMLHTTP"
,
"Msxml3.XMLHTTP"
,
"Microsoft.XMLHTTP"
,
"MSXML2.XmlHttp.6.0"
,
"MSXML2.XmlHttp.5.0"
,
"MSXML2.XmlHttp.4.0"
,
"MSXML2.XmlHttp.3.0"
,
"MSXML2.XmlHttp.2.0"
]
if
(
XMLHttpRequest
!==
undefined
)
{
// For non-IE browsers
createXMLHTTPObject
=
function
(
)
{
// Use memoization to cache the factory
return
new
XMLHttpRequest
(
)
}
return
createXMLHTTPObject
(
)
}
else
{
// IE
for
(
var
i
=
0
,
n
=
versions
.
length
;
i
<
n
;
i
++
)
{
try
{
var
version
=
versions
[
i
]
var
fn
=
function
(
)
{
return
new
ActiveXObject
(
version
)
}
createXMLHTTPObject
=
fn
// Use memoization to cache the factory
return
createXMLHTTPObject
(
)
}
catch
(
e
)
{
}
}
}
throw
new
Error
(
'Cant get XmlHttpRequest object'
)
}

returns the XHR function or equivalent for use with ajax memoizes the function for faster repeated use


function isLikeAFuture(x) {
    return x.isResolved !== undefined && x.queue !== undefined && x.then !== undefined
}

function isLikeAFuture ( x ) { return x . isResolved !== undefined && x . queue !== undefined && x . then !== undefined }

duck typing to determine if something is or isn't a future

duck typing to determine if something is or isn t a future