function __ENFORCETYPE(a, ...types) {
     if (env.application_env !== "development") return;
     let hasError = false;
     let expecting;
     let got;
     let i = 0;

     types.map( (t, index) => {
         if (a[index] === null) {
             hasError = true;
             expecting = t;
             got = "null";
             i = index;
             return;
         }
         switch (t) {
             case "mixed":
             break;
             case "jsx":
             if (!React.isValidElement(a[index])) {
                 hasError = true;
                 expecting = "jsx";
                 got = typeof a[index];
                 i = index;
             }
             case "array":
             if (!Array.isArray(a[index])) {
                 hasError = true;
                 expecting = "array";
                 got = typeof a[index];
                 i = index;
             }
             break;
             case "object":
                 if (typeof a[index] !== 'object' || Array.isArray(a[index]) || a[index] === null) {
                     hasError = true;
                     expecting = "object";
                     i = index;
                     if (a[index] === null) {
                         got = 'null';
                     } else {
                         got = Array.isArray(a[index]) ? "array" : typeof a[index];
                     }

                 }

             default:
             if (typeof a[index] !== t) {
                 hasError = true;{
                 expecting = t;
                 got = typeof a[index];}
                 i = index;
             }
         }
     });

     if (hasError) {
         let err = new Error();
         console.error(`ENFORCETYPE: param ${i + 1} is expecting ${expecting} got ${got} instead.`, err.stack);
     }
 }

function __ENFORCETYPE ( a , ... types ) { if ( env . application_env !== "development" ) return ; let hasError = false ; let expecting ; let got ; let i = 0 ; types . map ( ( t , index ) => { if ( a [ index ] === null ) { hasError = true ; expecting = t ; got = "null" ; i = index ; return ; } switch ( t ) { case "mixed" : break ; case "jsx" : if ( ! React . isValidElement ( a [ index ] ) ) { hasError = true ; expecting = "jsx" ; got = typeof a [ index ] ; i = index ; } case "array" : if ( ! Array . isArray ( a [ index ] ) ) { hasError = true ; expecting = "array" ; got = typeof a [ index ] ; i = index ; } break ; case "object" : if ( typeof a [ index ] !== 'object' || Array . isArray ( a [ index ] ) || a [ index ] === null ) { hasError = true ; expecting = "object" ; i = index ; if ( a [ index ] === null ) { got = 'null' ; } else { got = Array . isArray ( a [ index ] ) ? "array" : typeof a [ index ] ; } } default : if ( typeof a [ index ] !== t ) { hasError = true ; { expecting = t ; got = typeof a [ index ] ; } i = index ; } } } ) ; if ( hasError ) { let err = new Error ( ) ; console . error ( ` ${ i + 1 } ${ expecting } ${ got } ` , err . stack ) ; } }

Takes the arguments of a function ensures that the type provided is the type
being bassed.
@function
@param {object} a - The arguments object of the function.
@param {string} [types] - The types of variables you are expecting. (string, array, object, null, number)

Takes the arguments of a function ensures that the type provided is the type being bassed .


function assign(parent, val, keyOpts) {
  var target   = parent,
      keyParts = keyOpts.val.toString().split('.');

  keyParts.forEach(function(keyPart, idx) {
    if (keyParts.length === idx + 1) {
      if (val !== undefined) {
        if (Array.isArray(val) && Array.isArray(target[keyPart])) {
          val = target[keyPart].concat(val);
        }

        if (!((Array.isArray(val) && !val.length)
          || (typeof val === 'object' && !Object.keys(val || {}).length))) {
            target[keyPart] = val;
        }
      }
    } else if (!(keyPart in target)) {
      target[keyPart] = {};
    }
  });
}

function assign ( parent , val , keyOpts ) { var target = parent , keyParts = keyOpts . val . toString ( ) . split ( '.' ) ; keyParts . forEach ( function ( keyPart , idx ) { if ( keyParts . length === idx + 1 ) { if ( val !== undefined ) { if ( Array . isArray ( val ) && Array . isArray ( target [ keyPart ] ) ) { val = target [ keyPart ] . concat ( val ) ; } if ( ! ( ( Array . isArray ( val ) && ! val . length ) || ( typeof val === 'object' && ! Object . keys ( val || { } ) . length ) ) ) { target [ keyPart ] = val ; } } } else if ( ! ( keyPart in target ) ) { target [ keyPart ] = { } ; } } ) ; }

Ensure object tree exists as dictated by the key


function(node1, node2) {
        // A shortcut for siblings
        if (node1.parentNode === node2.parentNode) {
            return (node1.data.index < node2.data.index) ? -1 : 1;
        }

        // @NOTE: with the following algorithm we can only go 80 levels deep in the tree
        // and each node can contain 10000 direct children max
        var weight1 = 0,
            weight2 = 0,
            parent1 = node1,
            parent2 = node2;

        while (parent1) {
            weight1 += (Math.pow(10, (parent1.data.depth+1) * -4) * (parent1.data.index+1));
            parent1 = parent1.parentNode;
        }
        while (parent2) {
            weight2 += (Math.pow(10, (parent2.data.depth+1) * -4) * (parent2.data.index+1));
            parent2 = parent2.parentNode;
        }

        if (weight1 > weight2) {
            return 1;
        } else if (weight1 < weight2) {
            return -1;
        }
        return (node1.data.index > node2.data.index) ? 1 : -1;
    }

This is a custom tree sorting algorithm. It uses the index property on each node to determine
how to sort siblings. It uses the depth property plus the index to create a weight for each node.
This weight algorithm has the limitation of not being able to go more then 80 levels in depth, or
more then 10k nodes per parent. The end result is a flat collection being correctly sorted based
on this one single sort function.
@param {Ext.data.NodeInterface} node1
@param {Ext.data.NodeInterface} node2
@return {Number}
@private

This is a custom tree sorting algorithm . It uses the index property on each node to determine how to sort siblings . It uses the depth property plus the index to create a weight for each node . This weight algorithm has the limitation of not being able to go more then 80 levels in depth or more then 10k nodes per parent . The end result is a flat collection being correctly sorted based on this one single sort function .


function(root) {
        var node = this.getNode(),
            recursive = this.getRecursive(),
            added = [],
            child = root;

        if (!root.childNodes.length || (!recursive && root !== node)) {
            return added;
        }

        if (!recursive) {
            return root.childNodes;
        }

        while (child) {
            if (child._added) {
                delete child._added;
                if (child === root) {
                    break;
                } else {
                    child = child.nextSibling || child.parentNode;
                }
            } else {
                if (child !== root) {
                    added.push(child);
                }
                if (child.firstChild) {
                    child._added = true;
                    child = child.firstChild;
                } else {
                    child = child.nextSibling || child.parentNode;
                }
            }
        }

        return added;
    }

function ( root ) { var node = this . getNode ( ) , recursive = this . getRecursive ( ) , added = [ ] , child = root ; if ( ! root . childNodes . length || ( ! recursive && root !== node ) ) { return added ; } if ( ! recursive ) { return root . childNodes ; } while ( child ) { if ( child . _added ) { delete child . _added ; if ( child === root ) { break ; } else { child = child . nextSibling || child . parentNode ; } } else { if ( child !== root ) { added . push ( child ) ; } if ( child . firstChild ) { child . _added = true ; child = child . firstChild ; } else { child = child . nextSibling || child . parentNode ; } } } return added ; }

Private method used to deeply retrieve the children of a record without recursion.
@private
@param {Ext.data.NodeInterface} root
@return {Array}

Private method used to deeply retrieve the children of a record without recursion .


function(config) {
        var me = this;
        config = Ext.device.filesystem.Abstract.prototype.requestFileSystem(config);

        var successCallback = function(fs) {
            var fileSystem = Ext.create('Ext.device.filesystem.FileSystem', fs);
            config.success.call(config.scope || me, fileSystem);
        };

        if (config.type == window.PERSISTENT) {
            if(navigator.webkitPersistentStorage) {
                navigator.webkitPersistentStorage.requestQuota(config.size, function(grantedBytes) {
                    window.webkitRequestFileSystem(
                        config.type,
                        grantedBytes,
                        successCallback,
                        config.failure
                    );
                })
            }else {
                window.webkitStorageInfo.requestQuota(window.PERSISTENT, config.size, function(grantedBytes) {
                    window.webkitRequestFileSystem(
                        config.type,
                        grantedBytes,
                        successCallback,
                        config.failure
                    );
                })
            }
        } else {
            window.webkitRequestFileSystem(
                config.type,
                config.size,
                successCallback,
                config.failure
            );
        }
    }

function ( config ) { var me = this ; config = Ext . device . filesystem . Abstract . prototype . requestFileSystem ( config ) ; var successCallback = function ( fs ) { var fileSystem = Ext . create ( 'Ext.device.filesystem.FileSystem' , fs ) ; config . success . call ( config . scope || me , fileSystem ) ; } ; if ( config . type == window . PERSISTENT ) { if ( navigator . webkitPersistentStorage ) { navigator . webkitPersistentStorage . requestQuota ( config . size , function ( grantedBytes ) { window . webkitRequestFileSystem ( config . type , grantedBytes , successCallback , config . failure ) ; } ) } else { window . webkitStorageInfo . requestQuota ( window . PERSISTENT , config . size , function ( grantedBytes ) { window . webkitRequestFileSystem ( config . type , grantedBytes , successCallback , config . failure ) ; } ) } } else { window . webkitRequestFileSystem ( config . type , config . size , successCallback , config . failure ) ; } }

Requests access to the Local File System

var me = this;
var fs = Ext.create("Ext.device.File", {});
fs.requestFileSystem({
type: window.PERSISTENT,
size: 1024 * 1024,
success: function(fileSystem) {
me.fs = fileSystem;
},
failure: function(err) {
console.log("FileSystem Failure: " + err.code);
}
});

@param {Object} config An object which contains the follow options
@param {Number} config.type
window.TEMPORARY (0) or window.PERSISTENT (1)

@param {Number} config.size
Storage space, in Bytes, needed by the application

@param {Function} config.success
The function called when the filesystem is returned successfully

@param {FileSystem} config.success.fs

@param {Function} config.failure
The function called when the filesystem request causes and error

@param {FileError} config.failure.error


function(operation, callback, scope) {
        var me = this,
            writer  = me.getWriter(),
            request = me.buildRequest(operation);

        request.setConfig({
            headers: me.getHeaders(),
            timeout: me.getTimeout(),
            method: me.getMethod(request),
            callback: me.createRequestCallback(request, operation, callback, scope),
            scope: me,
            proxy: me,
            useDefaultXhrHeader: me.getUseDefaultXhrHeader()
        });

        if (operation.getWithCredentials() || me.getWithCredentials()) {
            request.setWithCredentials(true);
            request.setUsername(me.getUsername());
            request.setPassword(me.getPassword());
        }

        // We now always have the writer prepare the request
        request = writer.write(request);

        Ext.Ajax.request(request.getCurrentConfig());

        return request;
    }

Performs Ajax request.
@protected
@param {Ext.data.Operation} operation
@param {Function} callback
@param {Object} scope
@return {Object}


function(err) {
	var output;

	try {
		var fieldName = err.err.substring(err.err.lastIndexOf('.$') + 2, err.err.lastIndexOf('_1'));
		output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exists';

	} catch (ex) {
		output = 'Unique field already exists';
	}

	return output;
}

function
(
err
)
{
var
output
;
try
{
var
fieldName
=
err
.
err
.
substring
(
err
.
err
.
lastIndexOf
(
'.$'
)
+
2
,
err
.
err
.
lastIndexOf
(
'_1'
)
)
;
output
=
fieldName
.
charAt
(
0
)
.
toUpperCase
(
)
+
fieldName
.
slice
(
1
)
+
' already exists'
;
}
catch
(
ex
)
{
output
=
'Unique field already exists'
;
}
return
output
;
}


function( project ) {
        var current = process.cwd();

        console.log( '\nCreating folder "' + project + '"...' );

        // First, create the directory
        fs.mkdirSync( path.join( current, project ) );

        console.log( '\nCopying the files in "' + project + '"...' );

        // Then, copy the files into it
        wrench.copyDirSyncRecursive(
            path.join( __dirname, 'default', 'project' ),
            path.join( current, project )
        );

        console.log( '\nCreating the package.json file...' );

        // Open the package.json file and fill it in
        // with the correct datas.

        var packagePath = path.join( current, project, 'package.json' );

        // First, get the datas
        var pack = JSON.parse( fs.readFileSync( packagePath ));

        // Add the properties in the object
        pack.name = project;
        pack.version = '0.0.1';
        pack.dependencies = {
            'tartempion': '0.0.x'
        };

        // And write the object to the package.json file
        // by overriding everything in it.
        fs.writeFileSync( packagePath, JSON.stringify( pack, null, 4 ) );

        console.log( '\nProject "' + project + '" created.\n' );
    }

Create a project with the default files and folders.

The default hierarchy can be found in the folder cli/default/
of the tartempion module.

The only thing to dynamically create is the package.json file.

Create a project with the default files and folders .


function prewatch(theOptions) {
			if (config.watch) {
				return _.defaults(theOptions, watchify.args);
			}
			return theOptions;
		}

function prewatch ( theOptions ) { if ( config . watch ) { return _ . defaults ( theOptions , watchify . args ) ; } return theOptions ; }


function(index, filters) {
        // We begin by making sure we are dealing with an array of sorters
        if (!Ext.isArray(filters)) {
            filters = [filters];
        }

        var ln = filters.length,
            filterRoot = this.getFilterRoot(),
            currentFilters = this.getFilters(),
            newFilters = [],
            filterConfig, i, filter;

        if (!currentFilters) {
            currentFilters = this.createFiltersCollection();
        }

        // We first have to convert every sorter into a proper Sorter instance
        for (i = 0; i < ln; i++) {
            filter = filters[i];
            filterConfig = {
                root: filterRoot
            };

            if (Ext.isFunction(filter)) {
                filterConfig.filterFn = filter;
            }
            // If we are dealing with an object, we assume its a Sorter configuration. In this case
            // we create an instance of Sorter passing this configuration.
            else if (Ext.isObject(filter)) {
                if (!filter.isFilter) {
                    if (filter.fn) {
                        filter.filterFn = filter.fn;
                        delete filter.fn;
                    }

                    filterConfig = Ext.apply(filterConfig, filter);
                }
                else {
                    newFilters.push(filter);
                    if (!filter.getRoot()) {
                        filter.setRoot(filterRoot);
                    }
                    continue;
                }
            }
            // Finally we get to the point where it has to be invalid
            // <debug>
            else {
                Ext.Logger.warn('Invalid filter specified:', filter);
            }
            // </debug>

            // If a sorter config was created, make it an instance
            filter = Ext.create('Ext.util.Filter', filterConfig);
            newFilters.push(filter);
        }

        // Now lets add the newly created sorters.
        for (i = 0, ln = newFilters.length; i < ln; i++) {
            currentFilters.insert(index + i, newFilters[i]);
        }

        this.dirtyFilterFn = true;

        if (currentFilters.length) {
            this.filtered = true;
        }

        return currentFilters;
    }

This method inserts all the filters in the passed array at the given index.
@param {Number} index The index at which to insert the filters.
@param {Array} filters Each filter can be an instance of {@link Ext.util.Filter},
an object representing an Ext.util.Filter configuration, or a filter function.
@return {Array}

This method inserts all the filters in the passed array at the given index .


function(filters) {
        // We begin by making sure we are dealing with an array of sorters
        if (!Ext.isArray(filters)) {
            filters = [filters];
        }

        var ln = filters.length,
            currentFilters = this.getFilters(),
            i, filter;

        for (i = 0; i < ln; i++) {
            filter = filters[i];

            if (typeof filter === 'string') {
                currentFilters.each(function(item) {
                    if (item.getProperty() === filter) {
                        currentFilters.remove(item);
                    }
                });
            }
            else if (typeof filter === 'function') {
                currentFilters.each(function(item) {
                    if (item.getFilterFn() === filter) {
                        currentFilters.remove(item);
                    }
                });
            }
            else {
                if (filter.isFilter) {
                    currentFilters.remove(filter);
                }
                else if (filter.property !== undefined && filter.value !== undefined) {
                    currentFilters.each(function(item) {
                        if (item.getProperty() === filter.property && item.getValue() === filter.value) {
                            currentFilters.remove(item);
                        }
                    });
                }
            }
        }

        if (!currentFilters.length) {
            this.filtered = false;
        }
    }

This method removes all the filters in a passed array.
@param {Array} filters Each value in the array can be a string (property name),
function (sorterFn), an object containing a property and value keys or
{@link Ext.util.Sorter Sorter} instance.

This method removes all the filters in a passed array .


function wrapperMergeResult(srcFunc, objFunc, ...args) {
    let resultObjFunction = {};
    let resultSrcFunction = {};

    if (isFunction(objFunc)) {
        resultObjFunction = objFunc.apply(this, args);
    }

    if (isFunction(srcFunc)) {
        resultSrcFunction = srcFunc.apply(this, args);
    }

    return merge({}, resultObjFunction, resultSrcFunction);
}

function wrapperMergeResult ( srcFunc , objFunc , ... args ) { let resultObjFunction = { } ; let resultSrcFunction = { } ; if ( isFunction ( objFunc ) ) { resultObjFunction = objFunc . apply ( this , args ) ; } if ( isFunction ( srcFunc ) ) { resultSrcFunction = srcFunc . apply ( this , args ) ; } return merge ( { } , resultObjFunction , resultSrcFunction ) ; }

The implementation of the merger result.
@example
// call objFunc, srcFunc
_.wrap(objFunc, _.wrap(srcFunc, wrapperMergeResult));
@param {function} [srcFunc]
@param {function} [objFunc]
@param {...*} args
@returns {Object}
@private

The implementation of the merger result .


function wrapperOrResult(srcFunc, objFunc, ...args) {
    let resultObjFunction = false;
    let resultSrcFunction = false;

    if (isFunction(objFunc)) {
        resultObjFunction = objFunc.apply(this, args);
    }

    if (isFunction(srcFunc)) {
        resultSrcFunction = srcFunc.apply(this, args);
    }

    return resultObjFunction || resultSrcFunction;
}

function wrapperOrResult ( srcFunc , objFunc , ... args ) { let resultObjFunction = false ; let resultSrcFunction = false ; if ( isFunction ( objFunc ) ) { resultObjFunction = objFunc . apply ( this , args ) ; } if ( isFunction ( srcFunc ) ) { resultSrcFunction = srcFunc . apply ( this , args ) ; } return resultObjFunction || resultSrcFunction ; }

Merging the result of the logical "or".
@example
// call objFunc, srcFunc
_.wrap(objFunc, _.wrap(srcFunc, wrapperOrResult));
@param {function} [srcFunc]
@param {function} [objFunc]
@param {...*} args
@returns {boolean}
@private


function(instance) {
	this._model = instance._model;
	this._instance = instance;
	this.id = instance.id;
	this.eachAttribute = function(cb) { return this._model.eachAttribute(cb); };
	this.eachRelationship = function (cb) { return this._model.eachRelationship(cb); }
	this.attr = function(name) { return this._instance[name]; };
	this.belongsTo = function(name, opts) {
		return (opts.id ? this._instance[name].id : new Snapshot(this._instance[name]));
	};
}

function ( instance ) { this . _model = instance . _model ; this . _instance = instance ; this . id = instance . id ; this . eachAttribute = function ( cb ) { return this . _model . eachAttribute ( cb ) ; } ; this . eachRelationship = function ( cb ) { return this . _model . eachRelationship ( cb ) ; } this . attr = function ( name ) { return this . _instance [ name ] ; } ; this . belongsTo = function ( name , opts ) { return ( opts . id ? this . _instance [ name ] . id : new Snapshot ( this . _instance [ name ] ) ) ; } ; }


function(val) {
		var trimmed = val.trim();
		if(trimmed.indexOf("'") === 0 && trimmed.lastIndexOf("'") === (trimmed.length - 1))
			return '"' + trimmed.substring(1, trimmed.length - 1) + '"';
		return val;
	}

function ( val ) { var trimmed = val . trim ( ) ; if ( trimmed . indexOf ( "'" ) === 0 && trimmed . lastIndexOf ( "'" ) === ( trimmed . length - 1 ) ) return '"' + trimmed . substring ( 1 , trimmed . length - 1 ) + '"' ; return val ; }

Normalises a json string to a valid deserialisable json string


function(typeName, obj) {
		this.type = typeName;
		if(typeof obj !== 'undefined')
			for(var key in obj)
				this[key] = obj[key];
	}

function ( typeName , obj ) { this . type = typeName ; if ( typeof obj !== 'undefined' ) for ( var key in obj ) this [ key ] = obj [ key ] ; }


function() {
			var idStr = '' + sforce.db.id++;
			return sforce.db._idTemplate.substring(0, 18 - idStr.length) + idStr;
		}

function ( ) { var idStr = '' + sforce . db . id ++ ; return sforce . db . _idTemplate . substring ( 0 , 18 - idStr . length ) + idStr ; }


function(select) {
			var chars = new antlr4.InputStream(input);
			var lexer = new SelectLexer(chars);
			var tokens  = new antlr4.CommonTokenStream(lexer);
			var parser = new SelectParser(tokens);
			parser.buildParseTrees = true;
			return parser.select();
		}

function ( select ) { var chars = new antlr4 . InputStream ( input ) ; var lexer = new SelectLexer ( chars ) ; var tokens = new antlr4 . CommonTokenStream ( lexer ) ; var parser = new SelectParser ( tokens ) ; parser . buildParseTrees = true ; return parser . select ( ) ; }

Returns an antlr4 parse tree for a select query string


function(obj) {
			var schema = sforce.db.schema;
			var objDesc = schema[obj.type];
			if(typeof objDesc === 'undefined')
				throw 'No type exists by the name: ' + obj.type;
			for(var key in obj) {
				if({ Id:false, type:true }[key])
					continue;
				var fieldDesc = null;
				for(var i = 0; i < objDesc.fields.length; i++) {
					var fd = objDesc.fields[i];
					if(fd.name === key) {
						fieldDesc = fd;
						break;
					}
				}
				if(fieldDesc == null)
					throw 'No field exists by the name: ' + key + 'in the type: ' + obj.type;
			}
		}

function
(
obj
)
{
var
schema
=
sforce
.
db
.
schema
;
var
objDesc
=
schema
[
obj
.
type
]
;
if
(
typeof
objDesc
===
'undefined'
)
throw
'No type exists by the name: '
+
obj
.
type
;
for
(
var
key
in
obj
)
{
if
(
{
Id
:
false
,
type
:
true
}
[
key
]
)
continue
;
var
fieldDesc
=
;
for
(
var
i
=
0
;
i
<
objDesc
.
fields
.
length
;
i
++
)
{
var
fd
=
objDesc
.
fields
[
i
]
;
if
(
fd
.
name
===
key
)
{
fieldDesc
=
fd
;
break
;
}
}
if
(
fieldDesc
==
)
throw
'No field exists by the name: '
+
key
+
'in the type: '
+
obj
.
type
;
}
}

Validates a given objects against the schema


function(type, fields) {
			for(var i = 0; i < fields.length; i++)
				sforce.db.validateField(type, fields[i]);
		}

function ( type , fields ) { for ( var i = 0 ; i < fields . length ; i ++ ) sforce . db . validateField ( type , fields [ i ] ) ; }

Validates a list of field names against a type in the schema


function(type, field) {
			var objDesc = sforce.db.schema[type];
			for(var i = 0; i < objDesc.fields.length; i++)
				if(objDesc.fields[i].name === field)
					return;
			throw 'No field exists by the name: ' + field + 'in the type: ' + type;
		}

function
(
type
,
field
)
{
var
objDesc
=
sforce
.
db
.
schema
[
type
]
;
for
(
var
i
=
0
;
i
<
objDesc
.
fields
.
length
;
i
++
)
if
(
objDesc
.
fields
[
i
]
.
name
===
field
)
return
;
throw
'No field exists by the name: '
+
field
+
'in the type: '
+
type
;
}

Validates a field name against a type in the schema


function(type, rel) {
			var objDesc = sforce.db.schema[type];
			for(var i = 0; i < objDesc.childRelationships.length; i++)
				if(objDesc.childRelationships[i].relationshipName === rel)
					return;
			throw 'No child relationship exists by the name: ' + rel + 'in the type: ' + type;
		}

Validates a relationship name against a type in the schema


function(type) {
			var sos = sforce.db.sobjects;
			if(typeof sos[type] !== 'object')
				sos[type] = {};
			return sos[type];
		}

function ( type ) { var sos = sforce . db . sobjects ; if ( typeof sos [ type ] !== 'object' ) sos [ type ] = { } ; return sos [ type ] ; }


function(resultAry, isRoot) {
			if(resultAry.length == 0) {
				if(isRoot)
					return {
						done : 'true',
						queryLocator : null,
						size : 0,
					};
				return null;
			}
			var records = null;
			if(resultAry.length == 1)
				records = resultAry[0];
			else
				records = resultAry;
			return {
				done : 'true',
				queryLocator : null,
				records : records,
				size : resultAry.length,
			};
		}

function ( resultAry , isRoot ) { if ( resultAry . length == 0 ) { if ( isRoot ) return { done : 'true' , queryLocator : null , size : 0 , } ; return null ; } var records = null ; if ( resultAry . length == 1 ) records = resultAry [ 0 ] ; else records = resultAry ; return { done : 'true' , queryLocator : null , records : records , size : resultAry . length , } ; }

Creates a wrapped result in the form that you would expect the salesforce soap api to return a result


function(obj) {
		var matches = this.sequence[0].matches(obj);
		for(var i = 1; i < this.sequence.length; i += 2) {
			if(this.sequence[i] === '&')
				matches = matches && this.sequence[i+1].matches(obj);
			else
				matches = matches || this.sequence[i+1].matches(obj);
		}
		return matches;
	}

function ( obj ) { var matches = this . sequence [ 0 ] . matches ( obj ) ; for ( var i = 1 ; i < this . sequence . length ; i += 2 ) { if ( this . sequence [ i ] === '&' ) matches = matches && this . sequence [ i + 1 ] . matches ( obj ) ; else matches = matches || this . sequence [ i + 1 ] . matches ( obj ) ; } return matches ; }

Runs the conditions in the condition set and returns a boolean as a result


function addContents($, contents) {
    console.log('addContents', contents);
    var body = document.getElementsByTagName('BODY');
    if (!body) return;

    var $body = $(body[0]),
      contentsStyle = [
        'position:fixed;right:1em;top:1em;',
        'padding:0.5em;min-width:120px;',
        'font-size:90%;line-height:18px;',
        'border:1px solid #aaa;background: #F9F9F9;'
      ].join(''),
      html = [],
      order = [],
      hash = [];

    for (var i = 0; i < contents.length; ++i) {
      order[i] = 0;
      hash[i] = '';
    }

    function indexOf(tag) {
      for (var i = 0; i < contents.length && contents[i].toLowerCase() !== tag; ++i);
      return i;
    }

    $(contents.join(',')).each(function (i, obj) {
      var index = indexOf(obj.tagName.toLowerCase());
      order[index]++;
      hash[index] = $(obj).text();
      for (var j = index + 1; j < contents.length; ++j) {
        // Clear low level order
        order[j] = 0;
        hash[j] = '';
      }
      var anchor = hash.slice(0, index + 1).join('-');
      //anchor = '__id_' + tag + Math.floor(9999999 * Math.random());

      // Add anchor
      $(obj).append(fm('', anchor));
      // Add contents item
      html.push(fm('
{1}
',
        index * 1.5, order.slice(0, index + 1).join('.') + ' ' + hash[index], anchor));
    });

    var $contentsWrap = $(fm(['
',
        '
',
        'Contents hide',
        '
',
        '
{1}
',
        '
'].join(''), contentsStyle, html.join(''))).prependTo($body),
      $toggle = $contentsWrap.find('> :first').find('> :last'),
      $contents = $contentsWrap.find('> :last');
    console.log($contentsWrap, $toggle, $contents);

    $toggle.click(function () {
      $contents.slideToggle();
      $toggle.html($toggle.html() === 'show' ? 'hide' : 'show');
    });
  }


function addTop($, top) {
    console.log('addTop', top);

    $(top.join(',')).each(function (i, obj) {
      //$(obj).append(' Top');
      $(obj).prepend(['
',
        '',
        '✦',
        '
'].join(''));

      var $prefix = $(this).find(':first').find(':first');
      //var $top = $(this).find('a:last');
      //console.log($prefix, $top);
      var rawCol = $(obj).css('background-color');
      $(obj).mouseover(
        function () {
          $prefix.css('height', $(this).css('height'));
          $prefix.css('line-height', $(this).css('line-height'));
          $prefix.css('visibility', 'visible');
          $(this).css('background-color', '#FFF8D7');
        }).mouseout(function () {
          $prefix.css('visibility', 'hidden');
          $(this).css('background-color', rawCol);
        });
    });
  }

'<div style="position: relative;width: 1px;">'


function() {
        var actions = this.getActions(),
            namespace = this.getNamespace(),
            action, cls, methods,
            i, ln, method;

        for (action in actions) {
            if (actions.hasOwnProperty(action)) {
                cls = namespace[action];
                if (!cls) {
                    cls = namespace[action] = {};
                }
                methods = actions[action];

                for (i = 0, ln = methods.length; i < ln; ++i) {
                    method = Ext.create('Ext.direct.RemotingMethod', methods[i]);
                    cls[method.getName()] = this.createHandler(action, method);
                }
            }
        }
    }

function ( ) { var actions = this . getActions ( ) , namespace = this . getNamespace ( ) , action , cls , methods , i , ln , method ; for ( action in actions ) { if ( actions . hasOwnProperty ( action ) ) { cls = namespace [ action ] ; if ( ! cls ) { cls = namespace [ action ] = { } ; } methods = actions [ action ] ; for ( i = 0 , ln = methods . length ; i < ln ; ++ i ) { method = Ext . create ( 'Ext.direct.RemotingMethod' , methods [ i ] ) ; cls [ method . getName ( ) ] = this . createHandler ( action , method ) ; } } } }


function(transaction, event) {
        var success = !!event.getStatus(),
            functionName = success ? 'success' : 'failure',
            callback = transaction && transaction.getCallback(),
            result;

        if (callback) {
            // this doesnt make any sense. why do we have both result and data?
            // result = Ext.isDefined(event.getResult()) ? event.result : event.data;
            result = event.getResult();
            if (Ext.isFunction(callback)) {
                callback(result, event, success);
            } else {
                Ext.callback(callback[functionName], callback.scope, [result, event, success]);
                Ext.callback(callback.callback, callback.scope, [result, event, success]);
            }
        }
    }

Run any callbacks related to the transaction.
@private
@param {Ext.direct.Transaction} transaction The transaction
@param {Ext.direct.Event} event The event

Run any callbacks related to the transaction .


function(options, success, response) {
        var me = this,
            i = 0,
            ln, events, event,
            transaction, transactions;

        if (success) {
            events = me.createEvents(response);
            for (ln = events.length; i < ln; ++i) {
                event = events[i];
                transaction = me.getTransaction(event);
                me.fireEvent('data', me, event);
                if (transaction) {
                    me.runCallback(transaction, event, true);
                    Ext.direct.Manager.removeTransaction(transaction);
                }
            }
        } else {
            transactions = [].concat(options.transaction);
            for (ln = transactions.length; i < ln; ++i) {
                transaction = me.getTransaction(transactions[i]);
                if (transaction && transaction.getRetryCount() < me.getMaxRetries()) {
                    transaction.retry();
                } else {
                    event = Ext.create('Ext.direct.ExceptionEvent', {
                        data: null,
                        transaction: transaction,
                        code: Ext.direct.Manager.exceptions.TRANSPORT,
                        message: 'Unable to connect to the server.',
                        xhr: response
                    });

                    me.fireEvent('data', me, event);
                    if (transaction) {
                        me.runCallback(transaction, event, false);
                        Ext.direct.Manager.removeTransaction(transaction);
                    }
                }
            }
        }
    }

function
(
options
,
success
,
response
)
{
var
me
=
this
,
i
=
0
,
ln
,
events
,
event
,
transaction
,
transactions
;
if
(
success
)
{
events
=
me
.
createEvents
(
response
)
;
for
(
ln
=
events
.
length
;
i
<
ln
;
++
i
)
{
event
=
events
[
i
]
;
transaction
=
me
.
getTransaction
(
event
)
;
me
.
fireEvent
(
'data'
,
me
,
event
)
;
if
(
transaction
)
{
me
.
runCallback
(
transaction
,
event
,
true
)
;
Ext
.
direct
.
Manager
.
removeTransaction
(
transaction
)
;
}
}
}
else
{
transactions
=
[
]
.
concat
(
options
.
transaction
)
;
for
(
ln
=
transactions
.
length
;
i
<
ln
;
++
i
)
{
transaction
=
me
.
getTransaction
(
transactions
[
i
]
)
;
if
(
transaction
&&
transaction
.
getRetryCount
(
)
<
me
.
getMaxRetries
(
)
)
{
transaction
.
retry
(
)
;
}
else
{
event
=
Ext
.
create
(
'Ext.direct.ExceptionEvent'
,
{
data
:
,
transaction
:
transaction
,
code
:
Ext
.
direct
.
Manager
.
exceptions
.
TRANSPORT
,
message
:
'Unable to connect to the server.'
,
xhr
:
response
}
)
;
me
.
fireEvent
(
'data'
,
me
,
event
)
;
if
(
transaction
)
{
me
.
runCallback
(
transaction
,
event
,
false
)
;
Ext
.
direct
.
Manager
.
removeTransaction
(
transaction
)
;
}
}
}
}
}

React to the AJAX request being completed.
@private

React to the AJAX request being completed .


function(options) {
        return options && options.getTid ? Ext.direct.Manager.getTransaction(options.getTid()) : null;
    }

function ( options ) { return options && options . getTid ? Ext . direct . Manager . getTransaction ( options . getTid ( ) ) : null ; }

Get transaction from XHR options.
@private
@param {Object} options The options sent to the AJAX request.
@return {Ext.direct.Transaction/null} The transaction, `null` if not found.


function(action, method, args) {
        var me = this,
            callData = method.getCallData(args),
            data = callData.data,
            callback = callData.callback,
            scope = callData.scope,
            transaction;

        transaction = Ext.create('Ext.direct.Transaction', {
            provider: me,
            args: args,
            action: action,
            method: method.getName(),
            data: data,
            callback: scope && Ext.isFunction(callback) ? Ext.Function.bind(callback, scope) : callback
        });

        if (me.fireEvent('beforecall', me, transaction, method) !== false) {
            Ext.direct.Manager.addTransaction(transaction);
            me.queueTransaction(transaction);
            me.fireEvent('call', me, transaction, method);
        }
    }

function ( action , method , args ) { var me = this , callData = method . getCallData ( args ) , data = callData . data , callback = callData . callback , scope = callData . scope , transaction ; transaction = Ext . create ( 'Ext.direct.Transaction' , { provider : me , args : args , action : action , method : method . getName ( ) , data : data , callback : scope && Ext . isFunction ( callback ) ? Ext . Function . bind ( callback , scope ) : callback } ) ; if ( me . fireEvent ( 'beforecall' , me , transaction , method ) !== false ) { Ext . direct . Manager . addTransaction ( transaction ) ; me . queueTransaction ( transaction ) ; me . fireEvent ( 'call' , me , transaction , method ) ; } }

Configure a direct request.
@private
@param {String} action The action being executed.
@param {Object} method The method being executed.
@param {Array} args


function(transaction) {
        return {
            action: transaction.getAction(),
            method: transaction.getMethod(),
            data: transaction.getData(),
            type: 'rpc',
            tid: transaction.getId()
        };
    }

function ( transaction ) { return { action : transaction . getAction ( ) , method : transaction . getMethod ( ) , data : transaction . getData ( ) , type : 'rpc' , tid : transaction . getId ( ) } ; }

Gets the AJAX call info for a transaction.
@private
@param {Ext.direct.Transaction} transaction The transaction.
@return {Object} The call params.

Gets the AJAX call info for a transaction .


function(transaction) {
        var me = this,
            enableBuffer = me.getEnableBuffer();

        if (transaction.getForm()) {
            me.sendFormRequest(transaction);
            return;
        }

        me.callBuffer.push(transaction);
        if (enableBuffer) {
            if (!me.callTask) {
                me.callTask = Ext.create('Ext.util.DelayedTask', me.combineAndSend, me);
            }
            me.callTask.delay(Ext.isNumber(enableBuffer) ? enableBuffer : 10);
        } else {
            me.combineAndSend();
        }
    }

function ( transaction ) { var me = this , enableBuffer = me . getEnableBuffer ( ) ; if ( transaction . getForm ( ) ) { me . sendFormRequest ( transaction ) ; return ; } me . callBuffer . push ( transaction ) ; if ( enableBuffer ) { if ( ! me . callTask ) { me . callTask = Ext . create ( 'Ext.util.DelayedTask' , me . combineAndSend , me ) ; } me . callTask . delay ( Ext . isNumber ( enableBuffer ) ? enableBuffer : 10 ) ; } else { me . combineAndSend ( ) ; } }

Add a new transaction to the queue.
@private
@param {Ext.direct.Transaction} transaction The transaction.


function() {
        var buffer = this.callBuffer,
            ln = buffer.length;

        if (ln > 0) {
            this.sendRequest(ln == 1 ? buffer[0] : buffer);
            this.callBuffer = [];
        }
    }

function ( ) { var buffer = this . callBuffer , ln = buffer . length ; if ( ln > 0 ) { this . sendRequest ( ln == 1 ? buffer [ 0 ] : buffer ) ; this . callBuffer = [ ] ; } }

Combine any buffered requests and send them off.
@private

Combine any buffered requests and send them off .


function(action, method, form, callback, scope) {
        var me = this,
            transaction, isUpload, params;

        transaction = new Ext.direct.Transaction({
            provider: me,
            action: action,
            method: method.getName(),
            args: [form, callback, scope],
            callback: scope && Ext.isFunction(callback) ? Ext.Function.bind(callback, scope) : callback,
            isForm: true
        });

        if (me.fireEvent('beforecall', me, transaction, method) !== false) {
            Ext.direct.Manager.addTransaction(transaction);
            isUpload = String(form.getAttribute('enctype')).toLowerCase() == 'multipart/form-data';

            params = {
                extTID: transaction.id,
                extAction: action,
                extMethod: method.getName(),
                extType: 'rpc',
                extUpload: String(isUpload)
            };

            // change made from typeof callback check to callback.params
            // to support addl param passing in DirectSubmit EAC 6/2
            Ext.apply(transaction, {
                form: Ext.getDom(form),
                isUpload: isUpload,
                params: callback && Ext.isObject(callback.params) ? Ext.apply(params, callback.params) : params
            });

            me.fireEvent('call', me, transaction, method);
            me.sendFormRequest(transaction);
        }
    }

Configure a form submission request

@param {String} action The action being executed
@param {Object} method The method being executed
@param {HTMLElement} form The form being submitted
@param {Function} [callback] A callback to run after the form submits
@param {Object} [scope] A scope to execute the callback in

@private


function(transaction) {
        var me = this;

        Ext.Ajax.request({
            url: me.getUrl(),
            params: transaction.params,
            callback: me.onData,
            scope: me,
            form: transaction.form,
            isUpload: transaction.isUpload,
            transaction: transaction
        });
    }

function ( transaction ) { var me = this ; Ext . Ajax . request ( { url : me . getUrl ( ) , params : transaction . params , callback : me . onData , scope : me , form : transaction . form , isUpload : transaction . isUpload , transaction : transaction } ) ; }

Sends a form request

@param {Ext.direct.Transaction} transaction The transaction to send

@private


function inlineBlockFix(decl){
    	var origRule = decl.parent;
    	origRule.append(
	    	{
	    		prop:'*display',
	    		value:'inline'
	    	},
	    	{
	    		prop:'*zoom',
	    		value:'1'
	    	}
    	);
    }

function inlineBlockFix ( decl ) { var origRule = decl . parent ; origRule . append ( { prop : '*display' , value : 'inline' } , { prop : '*zoom' , value : '1' } ) ; }


function stubPlainTextFiles(resourceRoots, destination) {
  _.forEach(resourceRoots, function (resource) {
    // Replace the webstorm file:// scheme with an absolute file path
    var filePath = resource.replace('file://$PROJECT_DIR$', destination);
    filePath = filePath.replace('.idea/', '');
    // Extract the location from the file path to recursively create it if it doesn't exist.
    var location = filePath.replace(/[^\/]*$/, '');

    if (!fs.existsSync(location))
      mkdir('-p', location);

    if (!fs.existsSync(filePath))
      fs.writeFileSync(filePath, ' ', 'utf8');
  });
}

When generating the .idea project WebStorm will remove any plain text files specified
on first open if they do not exist.
For example this lets files from a build be marked as plain text before they exist
by stubbing an empty file at their expected position.
@param resourceRoots
@param destination

When generating the . idea project WebStorm will remove any plain text files specified on first open if they do not exist . For example this lets files from a build be marked as plain text before they exist by stubbing an empty file at their expected position .


function resolveJetbrainsExe(jetbrainsDirectory) {
  var exists = false;
  var webstormInstallPaths = io.resolveDirMatches(jetbrainsDirectory, /^WebStorm\s*[.\d]+$/);

  // Check that the Webstorm folder have a bin folder, empty folders are a known issue.
  for (var j = 0; j < webstormInstallPaths.length; j++) {
    var webstormPath = [jetbrainsDirectory, webstormInstallPaths[j], 'bin'];
    var resolvedWebstorm = resolveMaxedPath(webstormPath);
    if(resolvedWebstorm === null) break;

    exists = path.resolve(resolvedWebstorm.join(path.sep), 'Webstorm.exe');
    if(fs.existsSync(exists)) {
      return exists;
    }
  }

  return exists;
}

Check if a Webstorm.exe exists in a given windows program files directory.
@param {string} Jetbrains install directory eg, C:/Program Files/JetBrains.
@returns {string|boolean} A true concatenated path where found, else false.

Check if a Webstorm . exe exists in a given windows program files directory .


function Route (method, path, callback, options) {
  this.path = path;
  this.method = method;
  this.callback = callback;
  this.regexp = utils.pathRegexp(path, this.keys = [], options.sensitive, options.strict);
}

function Route ( method , path , callback , options ) { this . path = path ; this . method = method ; this . callback = callback ; this . regexp = utils . pathRegexp ( path , this . keys = [ ] , options . sensitive , options . strict ) ; }

Mostly from Express' router `Route`.

Initialize `Route` with the given HTTP `method`, `path`,
and an array of `callbacks` and `options`.

Options:

- `sensitive`    enable case-sensitive routes
- `strict`       enable strict matching for trailing slashes

@param {String} method
@param {String} path
@param {Array} callbacks
@param {Object} options


function TransportDecorator (Transport) {

  function TelemetryTransport (contact, options) {
    if (!(this instanceof TelemetryTransport)) {
      return new TelemetryTransport(contact, options)
    }

    assert.ok(options, 'Missing required options parameter')

    this._telopts = options.telemetry
    this.telemetry = new Persistence(this._telopts.storage)

    Transport.call(this, contact, options)
  }

  inherits(TelemetryTransport, Transport)

  TelemetryTransport.DEFAULT_METRICS = [
    metrics.Latency,
    metrics.Availability,
    metrics.Reliability,
    metrics.Throughput
  ]

  /**
   * Wraps _open with telemetry hooks setup
   * #_open
   * @param {Function} callback
   */
  TelemetryTransport.prototype._open = function (callback) {
    var self = this
    var metrics = this._telopts.metrics

    if (!metrics || metrics.length === 0) {
      this._telopts.metrics = TelemetryTransport.DEFAULT_METRICS
    }

    this._telopts.metrics.forEach(function (Metric) {
      var metric = new Metric()

      metric.hooks.forEach(function (hook) {
        self[hook.trigger](
          hook.event,
          hook.handler(metric, self.telemetry)
        )
      })
    })

    return Transport.prototype._open.call(this, callback)
  }

  return TelemetryTransport
}

Returns a decorated transport adapter that writes telemetry data
@constructor
@param {kad.RPC} Transport


function getRandomArrValue(arr, min = 0, max = arr.length - 1) {
  return arr[getRandomInt(min, max)];
}

function getRandomArrValue ( arr , min = 0 , max = arr . length - 1 ) { return arr [ getRandomInt ( min , max ) ] ; }

Get a random value from an array
@param  {Array}  arr Array of values
@param  {Number} min Minimum key value
@param  {Number} max Maximum key value
@return              Random value from initial array


function random(number = 1) {
  if (1 > number) {
    throw Error(`Can't use numbers bellow 1, ${number} passed`);
  }

  if (number === 1) {
    return getRandomArrValue(dinosaurs);
  } else {
    const l = dinosaurs.length - 1;
    return new Array(number).fill().map(() => getRandomArrValue(dinosaurs, 0, l));
  }
}

function random ( number = 1 ) { if ( 1 > number ) { throw Error ( ` ${ number } ` ) ; } if ( number === 1 ) { return getRandomArrValue ( dinosaurs ) ; } else { const l = dinosaurs . length - 1 ; return new Array ( number ) . fill ( ) . map ( ( ) => getRandomArrValue ( dinosaurs , 0 , l ) ) ; } }

Returns a random dinosaur or more random dinosaurs if number is set
@param  {Number}       number If set, returns an array of dinosaurs
@return {String|Array}        Single dinosaur or array of dinosaurs


function Response (ghosttrain, callback) {
  this.charset = '';
  this.headers = {};
  this.statusCode = 200;

  this.app = ghosttrain;
  this._callback = callback;
}

function Response ( ghosttrain , callback ) { this . charset = '' ; this . headers = { } ; this . statusCode = 200 ; this . app = ghosttrain ; this . _callback = callback ; }

Shims features of Express's `response` object in routes.
Accepts a `callback` function to be called with the data to send.

@param {Object} ghosttrain
@param {Function} callback
@return {Object}

Shims features of Express s response object in routes . Accepts a callback function to be called with the data to send .


function () {
    var body;
    var app = this.app;

    // If status provide, set that, and set `body` to the content correctly
    if (typeof arguments[0] === 'number') {
      this.status(arguments[0]);
      body = arguments[1];
    } else {
      body = arguments[0];
    }

    var type = this.get('Content-Type');

    if (!body && type !== 'application/json') {
      body = utils.STATUS_CODES[this.statusCode];
      if (!type)
        this.type('txt');
    }
    else if (typeof body === 'string') {
      if (!type) {
        this.charset = this.charset || 'utf-8';
        this.type('html');
      }
    }
    else if (typeof body === 'object') {
      if (body === null)
        body = '';
      else if (!type || type === 'application/json') {
        this.contentType('application/json');
        // Cast object to string to normalize response
        var replacer = app.get('json replacer');
        var spaces = app.get('json spaces');
        body = JSON.stringify(body, replacer, spaces);
      }
    }

    this.end(body);
    return this;
  }

Sends a response

Examples:
res.send({})
res.send('text')
res.send(404, 'Message')
res.send(200)

@param {Mixed} body or status code
@param {Mixed} body
@return {Response}


function () {
    var data;
    if (arguments.length === 2) {
      this.status(arguments[0]);
      data = arguments[1];
    } else {
      data = arguments[0];
    }

    if (!this.get('Content-Type'))
      this.contentType('application/json');

    return this.send(data);
  }

function ( ) { var data ; if ( arguments . length === 2 ) { this . status ( arguments [ 0 ] ) ; data = arguments [ 1 ] ; } else { data = arguments [ 0 ] ; } if ( ! this . get ( 'Content-Type' ) ) this . contentType ( 'application/json' ) ; return this . send ( data ) ; }

Sends a JSON response

Examples:
res.json(null);
res.json({});
res.json(200, 'text');
res.json(404, 'woops');

@param {Mixed} body or status code
@param {Mixed} object data
@return {Response}


function (field, value) {
    if (arguments.length === 2)
      this.headers[field] = value;
    else {
      for (var prop in field)
        this.headers[prop] = field[prop];
    }
    return this;
  }

function ( field , value ) { if ( arguments . length === 2 ) this . headers [ field ] = value ; else { for ( var prop in field ) this . headers [ prop ] = field [ prop ] ; } return this ; }

Sets `field` header to `value`, or accepts an object and applies
those key value pairs to the Response object's headers.

@param {String|Object} field
@param {String} value
@return {Response}

Sets field header to value or accepts an object and applies those key value pairs to the Response object s headers .


function (body) {
    var type = this.get('Content-Type');

    if (type === 'application/json')
      this._callback(JSON.parse(body || '{}'));
    else
      this._callback(body);
  }

function ( body ) { var type = this . get ( 'Content-Type' ) ; if ( type === 'application/json' ) this . _callback ( JSON . parse ( body || '{}' ) ) ; else this . _callback ( body ) ; }

Formats response and calls initial callback

@param {String} body


function (args) {
   // Find the minimum expected length.
   var expected = Array.prototype.slice.call(arguments, 1);
   var minimum = expected.length
   var hasOptionalTypes = false;

   for (var i = 0; i < expected.length; i++) {
      if (!isValidType(expected[i])) {
         throw Error('Expected argument ' + i + ' is not a valid type.');
      }
      if (isOptionalType(expected[i])) {
         minimum--;
         hasOptionalTypes = true;
      }
   };
   // Exit early if in production, INSIST_IN_PROD is not equal to true and there are no optional
   // options.
   if (isDisabled && !hasOptionalTypes) {
      return [];
   }

   // Check if the args and expected lengths are different (and there are no optional args).
   if (minimum == expected.length && args.length != expected.length) {
      throw Error(getExpectedVsRecieved_(expected, args));
   }
   // Check if the args are within the expected range.
   if (args.length < minimum || args.length > expected.length) {
      throw Error(getExpectedVsRecieved_(expected, args));
   }

   // We don't have to worry about shifting if all the arguments are present.
   if (args.length === expected.length) {
      for (var i = 0; i < expected.length; i++) {
         if (!isOfType(args[i], expected[i])) {
            throw Error(getExpectedVsRecieved_(expected, args));
         }
      };
      return args;
   }

   return shiftArguments_(expected, args, minimum);
}

Asserts that the arguments supplied are what's expected. If an argument can be multiples
types, use an array of acceptable types.
@param {Array.<?>} args
@param {?,..} expected types
@return Returns an array with the arguments shifted into the correct indices.

Asserts that the arguments supplied are what s expected . If an argument can be multiples types use an array of acceptable types .


function (expected, args, minimum) {
   var shiftedArgs = [];
   var curArg = args.length - 1;
   var remainingOptionalArgs = expected.length - minimum;
   var optionalIndiceSegments = [];
   var optionalIndiceSegment = [];
   var availableArgsSegments = [];
   var availableArgsSegment = [];

   // Fill the return array with nulls first.
   for (var i = 0; i < expected.length; i++) shiftedArgs[i] = null;

   // Capture groups of available arguments separated by ones that have been used.
   var advanceArg = function () {
      availableArgsSegment.unshift(curArg);
      curArg--;
      remainingOptionalArgs--;
      if (curArg < 0 || remainingOptionalArgs < 0) {
         throw Error(getExpectedVsRecieved_(expected, args));
      }
   };

   // Fill in all of the required types, starting from the last expected argument and working
   // towards the first.
   for (i = expected.length - 1; i >= 0; i--) {
      var type = expected[i];
      if (isOptionalType(type)) {
         optionalIndiceSegment.unshift(i);
         continue;
      }
      // Keep moving down the line of arguments until one matches.
      while (!isOfType(args[curArg], type)) {
         advanceArg();
      }

      // Check if this argument should be left for a trailing optional argument.
      if (checkIfShouldLeaveArgument_(expected, i, args, curArg)) {
         // Found enough matches to let this be an optional argument. Advance the argument and
         // then restart on this same function.
         advanceArg();
         i++;
         continue;
      }

      // Capture groups of optional arguments separated by required arguments.
      optionalIndiceSegments.unshift(optionalIndiceSegment);
      optionalIndiceSegment = [];
      availableArgsSegments.unshift(availableArgsSegment);
      availableArgsSegment = []
      shiftedArgs[i] = args[curArg--];
   }
   // Now that we have found all the required arguments, group the rest for processing with optional
   // arguments.
   while (curArg >= 0) availableArgsSegment.unshift(curArg--);
   availableArgsSegments.unshift(availableArgsSegment);
   optionalIndiceSegments.unshift(optionalIndiceSegment);

   // Make sure that the optional argument count matches up correctly.
   if (availableArgsSegments.length != optionalIndiceSegments.length) {
      throw Error(getExpectedVsRecieved_(expected, args));
   }

   // Go through all the optional segments and argument segments to match up the optional arguments.
   optionalIndiceSegments.forEach(function (optionalIndices, index) {
      availableArgsSegment = availableArgsSegments[index];
      i = 0;
      availableArgsSegment.forEach(function (argIndex) {
         arg = args[argIndex]
         // Skip forward until we find an optional expected argument that matches.
         while (!isOfType(arg, expected[optionalIndices[i]]) && i < optionalIndices.length) {
            i++;
         }
         // If none match then the arguments are invalid.
         if (i >= optionalIndices.length) {
            throw Error(getExpectedVsRecieved_(expected, args));
         }
         // Success! This is an optional expected argument.
         shiftedArgs[optionalIndices[i++]] = arg;
      });
   });

   return shiftedArgs;
}

Returns an array of all of the arguments shifted into the correct place.
@param {Array} expected
@param {Array} actual
@returns {Array}
@private

Returns an array of all of the arguments shifted into the correct place .


function () {
      availableArgsSegment.unshift(curArg);
      curArg--;
      remainingOptionalArgs--;
      if (curArg < 0 || remainingOptionalArgs < 0) {
         throw Error(getExpectedVsRecieved_(expected, args));
      }
   }

function ( ) { availableArgsSegment . unshift ( curArg ) ; curArg -- ; remainingOptionalArgs -- ; if ( curArg < 0 || remainingOptionalArgs < 0 ) { throw Error ( getExpectedVsRecieved_ ( expected , args ) ) ; } }

Capture groups of available arguments separated by ones that have been used.

Capture groups of available arguments separated by ones that have been used .


function (expected, expectedIndex, actual, actualIndex) {
   // Check how many optional types in front of this argument that match the current value.
   var consecutiveOptionals = countTrailingOptionals_(expected, expectedIndex, actual[actualIndex]);

   // Check how many required types are behind this argument that match the current value. We
   // will then use this value to determine if the current argument can be allowed to fill an
   // optional spot instead of a required one.
   var matchingRequires = countLeadingMatchingRequires_(expected, expectedIndex,
         actual[actualIndex]);

   // Now that we have found the consecutive matching types, more forward through the arguments
   // to see if there are enough to fill the option types.
   var matchesRequired = 1 + matchingRequires;
   var availableDistance = matchingRequires + consecutiveOptionals;

   // Determine if there are enough optional arguments.
   var i = actualIndex - 1;
   var type = expected[expectedIndex];
   while (i >= 0 && availableDistance > 0 && matchesRequired > 0) {
      if (isOfType(actual[i], type)) {
         matchesRequired--;
      }
      availableDistance--;
      i--;
   }
   return matchesRequired <= 0;
}

Checks if the current argument should be left for an optional argument.
@param {Array} expected
@param {number} expectedIndex
@param {?} value
@returns {bool}
@private

Checks if the current argument should be left for an optional argument .


function (expected, expectedIndex, value) {
   var i = expectedIndex + 1;
   var matchingOptionals = 0;
   var inBetweenOptionals = 0;
   var tmpInBetween = 0;
   while (i < expected.length && isOptionalType(expected[i])) {
      if (isOfType(value, expected[i])) {
         matchingOptionals++;
         inBetweenOptionals += tmpInBetween;
         tmpInBetween = 0;
      } else {
         tmpInBetween++;
      }
      i++;
   }
   return matchingOptionals + inBetweenOptionals;
}

function ( expected , expectedIndex , value ) { var i = expectedIndex + 1 ; var matchingOptionals = 0 ; var inBetweenOptionals = 0 ; var tmpInBetween = 0 ; while ( i < expected . length && isOptionalType ( expected [ i ] ) ) { if ( isOfType ( value , expected [ i ] ) ) { matchingOptionals ++ ; inBetweenOptionals += tmpInBetween ; tmpInBetween = 0 ; } else { tmpInBetween ++ ; } i ++ ; } return matchingOptionals + inBetweenOptionals ; }

Counts the number of trailing, consecutive optional arguments.
@param {Array} expected
@param {number} expectedIndex
@param {?} value
@returns {number}
@private

Counts the number of trailing consecutive optional arguments .


function (expected, expectedIndex, value) {
   var i = expectedIndex - 1;
   var matchingRequires = 0
   while (i >= 0) {
      if (!isOptionalType(expected[i]) && isOfType(value, expected[i])) {
         matchingRequires++;
      }
      i--;
   }
   return matchingRequires;
}

function ( expected , expectedIndex , value ) { var i = expectedIndex - 1 ; var matchingRequires = 0 while ( i >= 0 ) { if ( ! isOptionalType ( expected [ i ] ) && isOfType ( value , expected [ i ] ) ) { matchingRequires ++ ; } i -- ; } return matchingRequires ; }

Counts the number of leading required arguments.
@param {Array} expected
@param {number} expectedIndex
@param {?} value
@returns {number}
@private

Counts the number of leading required arguments .


function (expected, actual) {
   var argNames = [];
   var expectedNames = [];
   for (var i = 0; i < actual.length; i++) {
      argNames.push(getNameForValue(actual[i]));
   };
   for (var i = 0; i < expected.length; i++) {
      expectedNames.push(getNameForType(expected[i]));
   };
   return 'Expected arguments to be (' + expectedNames.join(', ') + ') but received (' +
         argNames.join(', ') + ') instead.';
}

function
(
expected
,
actual
)
{
var
argNames
=
[
]
;
var
expectedNames
=
[
]
;
for
(
var
i
=
0
;
i
<
actual
.
length
;
i
++
)
{
argNames
.
push
(
getNameForValue
(
actual
[
i
]
)
)
;
}
;
for
(
var
i
=
0
;
i
<
expected
.
length
;
i
++
)
{
expectedNames
.
push
(
getNameForType
(
expected
[
i
]
)
)
;
}
;
return
'Expected arguments to be ('
+
expectedNames
.
join
(
', '
)
+
') but received ('
+
argNames
.
join
(
', '
)
+
') instead.'
;
}

Returns a string of expected arguments vs actual.
@param {Array} expected
@param {Array} actual
@returns {string}
@private

Returns a string of expected arguments vs actual .


function (value, type) {
   if (!isValidType(type)) {
      throw Error('Invalid type supplied.');
   }
   if (!isOfType(value, type)) {
      argName = getNameForValue(value);
      typeName = getNameForType(type);
      throw Error('Expected ' + argName + ' to be an instance of ' + typeName + '.');
   }
}

function
(
value
,
type
)
{
if
(
!
isValidType
(
type
)
)
{
throw
Error
(
'Invalid type supplied.'
)
;
}
if
(
!
isOfType
(
value
,
type
)
)
{
argName
=
getNameForValue
(
value
)
;
typeName
=
getNameForType
(
type
)
;
throw
Error
(
'Expected '
+
argName
+
' to be an instance of '
+
typeName
+
'.'
)
;
}
}

Asserts that the supplied value is of the supplied type.
@param {?} value
@param {type} types

Asserts that the supplied value is of the supplied type .


function (type) {
   if (type === null) return true;
   if (type === undefined) return true;
   if (type instanceof AnyType) return true;
   if (type instanceof Array) {
      // An array is only valid if it contains one or more valid types.
      if (!type.length) return false;
      for (var i = 0; i < type.length; i++) {
          if (!isValidType(type[i])) return false;
      };
      return true;
   }
   if (type instanceof ArrayOf) return isValidType(type.type);
   if (type instanceof EnumType) return (type.enumerable instanceof Object);
   return (type instanceof Object);
}

Determines if the argument is a valid type.
@param {type} type
@return {boolean}

Determines if the argument is a valid type .


function (value) {
   if (value === undefined) return 'undefined';
   if (value === null) return 'null';

   // Look inside the array to determine the inner type.
   if (value instanceof Array) {
      if (!value.length) return 'Array(empty)';
      var innerType = undefined;
      for (var i = 0; i < value.length; i++) {
         type = getNameForValue(value[i]);
         if (innerType !== undefined && innerType !== type) {
            return 'Array(mixed)';
         }
         innerType = type;
      };
      return 'Array<' + innerType + '>';
   }

   if (value instanceof Function) {
      if (value.name) return value.name;
      return 'Anonymous function';
   }

   // Try and use the constructor to find the name of the type.
   if (value instanceof Object) {
      if (value.constructor) return value.constructor.name;
      return 'Object';
   }

   // No other way to determine the name of the type, just capitilize the typeof value.
   name = typeof value;
   return name[0].toUpperCase() + name.substring(1);
}

Gets the pretty name for the type of the value.
@param {?} value
@return {string}

Gets the pretty name for the type of the value .


function (type) {
   if (type === undefined) return 'undefined';
   if (type === null) return 'null';

   // Create a list of all the possible types.
   if (type instanceof Array) {
      if (!type.length) return 'None';
      var possibleTypes = [];
      for (var i = 0; i < type.length; i++) {
         possibleTypes.push(getNameForType(type[i]));
      };
      return possibleTypes.join(' or ');
   }

   // Look inside the array to determine the inner type.
   if (type instanceof ArrayOf) {
      return 'Array<' + getNameForType(type.type) + '>';
   }

   // All types should be functions.
   if (type instanceof Function) return type.name
   return 'Invalid type';
}

Gets the pretty name for the type.
@param {type} type
@return {string}


function(request) {
        var me      = this,
            url     = me.callParent(arguments),
            params  = Ext.apply({}, request.getParams()),
            filters = params.filters,
            filter, i, value;

        delete params.filters;

        if (me.getAutoAppendParams()) {
            url = Ext.urlAppend(url, Ext.Object.toQueryString(params));
        }

        if (filters && filters.length) {
            for (i = 0; i < filters.length; i++) {
                filter = filters[i];
                value = filter.getValue();
                if (value) {
                    url = Ext.urlAppend(url, filter.getProperty() + "=" + value);
                }
            }
        }

        return url;
    }

function ( request ) { var me = this , url = me . callParent ( arguments ) , params = Ext . apply ( { } , request . getParams ( ) ) , filters = params . filters , filter , i , value ; delete params . filters ; if ( me . getAutoAppendParams ( ) ) { url = Ext . urlAppend ( url , Ext . Object . toQueryString ( params ) ) ; } if ( filters && filters . length ) { for ( i = 0 ; i < filters . length ; i ++ ) { filter = filters [ i ] ; value = filter . getValue ( ) ; if ( value ) { url = Ext . urlAppend ( url , filter . getProperty ( ) + "=" + value ) ; } } } return url ; }

Generates a url based on a given Ext.data.Request object. Adds the params and callback function name to the url
@param {Ext.data.Request} request The request object.
@return {String} The url.

Generates a url based on a given Ext . data . Request object . Adds the params and callback function name to the url


function getStateFromOptions (options, propertyName) {
  propertyName = propertyName || 'state';
  const stateName = options[propertyName] || options.resource.defaultState;
  let stateObj = options.resource.states[stateName] || {validate: false};
  stateObj.name = stateName;
  return stateObj;
}

function getStateFromOptions ( options , propertyName ) { propertyName = propertyName || 'state' ; const stateName = options [ propertyName ] || options . resource . defaultState ; let stateObj = options . resource . states [ stateName ] || { validate : false } ; stateObj . name = stateName ; return stateObj ; }

Retreive the state object descriptor from its name
@param {object} options
@param {string} [propertyName]
@returns {State}


function validate (resource, doc, doValidate) {
  return new Promise((resolve, reject) => {
    if (doValidate !== true) {
      return resolve();
    }
    if (resource.validate(doc)) {
      return resolve();
    } else {
      debug('model have %d error(s)', resource.validate.errors.length);
      return reject(resource.validate.errors);
    }
  });
}

function
validate
(
resource
,
doc
,
doValidate
)
{
return
new
Promise
(
(
resolve
,
reject
)
=>
{
if
(
doValidate
!==
true
)
{
return
resolve
(
)
;
}
if
(
resource
.
validate
(
doc
)
)
{
return
resolve
(
)
;
}
else
{
debug
(
'model have %d error(s)'
,
resource
.
validate
.
errors
.
length
)
;
return
reject
(
resource
.
validate
.
errors
)
;
}
}
)
;
}

Validate a document against its resource
@param {object} resource
@param {object} doc
@param {boolean} doValidate
@returns {Promise}


function prune(str, max, nice, suf) {
  max = max || 140
  nice = _.isBoolean(nice) ? nice : false
  if (!str || max <= 0 || str.length <= max) return str
  suf = suf || "..."
  str = str.substr(0, max)
  return nice ? str.substr(0, Math.min(str.length, str.lastIndexOf(" "))) + suf : str
}

function
prune
(
str
,
max
,
nice
,
suf
)
{
max
=
max
||
140
nice
=
_
.
isBoolean
(
nice
)
nice
:
false
if
(
!
str
||
max
<=
0
||
str
.
length
<=
max
)
return
str
suf
=
suf
||
"..."
str
=
str
.
substr
(
0
,
max
)
return
nice
str
.
substr
(
0
,
Math
.
min
(
str
.
length
,
str
.
lastIndexOf
(
" "
)
)
)
+
suf
:
str
}

trims end of string, can trimmed back to next clean word, or add suffix to end of trimmed string

trims end of string can trimmed back to next clean word or add suffix to end of trimmed string


function attemptRender(reporter, filename, src, resolve, reject, globals) {
	globals = globals || {};
	less.render(src, {
		// Specify search paths for @import directives
		paths : [
			"public/static/less"
		],
		// Specify a filename, for better error messages
		filename : filename,
		modifyVars : globals,
		compress : false
	}, function(e, css) {
		if (e) {
			if ((/^variable @(.+?) is undefined$/).test(e.message)) {
				// ignore undef variable
				globals[(/^variable @(.+?) is undefined$/).exec(e.message)[1]] = "1";
				attemptRender(reporter, filename, src, resolve, reject, globals);
				return;
			}
			reporter("LESS", filename, e.line, e.message);
			reject();
			return;
		}
		resolve({
			filename : filename,
			src : css.css || css
		});
	});
}

Attempt to validate the less file
@param {Function} reporter
@param {String} filename
@param {String} src
@param {Function} resolve
@param {Function} reject
@param {Object} [globals]


function validateArray(indexes) {
  var valid = false;

  if (typeof indexes === 'string') {
    if (indexes.match(TYPE_ARRAY_REGEX)) {
      valid = true;
    }
  }

  return valid;
}

function validateArray ( indexes ) { var valid = false ; if ( typeof indexes === 'string' ) { if ( indexes . match ( TYPE_ARRAY_REGEX ) ) { valid = true ; } } return valid ; }

Validate the given value and make sure it is valid array indexes. The value must
be a valid String

@param {String} indexes   the value to validate
@return {Boolean}         true if the val is valid, false otherwise

Validate the given value and make sure it is valid array indexes . The value must be a valid String


function addRoutes( pies, pie, routes, app ) {
    // Add the GET routes
    if ( 'get' in routes ) {
        routes.get.forEach( function( route ) {
            Object.keys( route ).forEach( function( r ) {
                var middlewares = true;
                if ( typeof route[ r ] === 'string' ) {
                    middlewares = false;
                }
                loadRoute( app, 'get', r, pies[ pie ].path, route[ r ], middlewares );
            });
        });
    }

    // Add the POST routes
    if ( 'post' in routes ) {
        routes.post.forEach( function( route ) {
            Object.keys( route ).forEach( function( r ) {
                var middlewares = true;
                if ( typeof route[ r ] === 'string' ) {
                    middlewares = false;
                }
                loadRoute( app, 'post', r, pies[ pie ].path, route[ r ], middlewares );
            });
        });
    }
}

function
addRoutes
(
pies
,
pie
,
routes
,
app
)
{
// Add the GET routes
if
(
'get'
in
routes
)
{
routes
.
get
.
forEach
(
function
(
route
)
{
Object
.
keys
(
route
)
.
forEach
(
function
(
r
)
{
var
middlewares
=
true
;
if
(
typeof
route
[
r
]
===
'string'
)
{
middlewares
=
false
;
}
loadRoute
(
app
,
'get'
,
r
,
pies
[
pie
]
.
path
,
route
[
r
]
,
middlewares
)
;
}
)
;
}
)
;
}
// Add the POST routes
if
(
'post'
in
routes
)
{
routes
.
post
.
forEach
(
function
(
route
)
{
Object
.
keys
(
route
)
.
forEach
(
function
(
r
)
{
var
middlewares
=
true
;
if
(
typeof
route
[
r
]
===
'string'
)
{
middlewares
=
false
;
}
loadRoute
(
app
,
'post'
,
r
,
pies
[
pie
]
.
path
,
route
[
r
]
,
middlewares
)
;
}
)
;
}
)
;
}
}


function generateUUID() {
    let dat = new Date().getTime();

    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (cha) => {
        const ran = (dat + (Math.random() * 16)) % 16 | 0;
        dat = Math.floor(dat / 16);

        return (cha === 'x' ? ran : ran & 0x3 | 0x8).toString(16);
    });
}

function generateUUID ( ) { let dat = new Date ( ) . getTime ( ) ; return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' . replace ( / [xy] / g , ( cha ) => { const ran = ( dat + ( Math . random ( ) * 16 ) ) % 16 | 0 ; dat = Math . floor ( dat / 16 ) ; return ( cha === 'x' ? ran : ran & 0x3 | 0x8 ) . toString ( 16 ) ; } ) ; }

Generates a unique 36 character hyphenated GUID
@method utilitarian.string.util#generateUUID
@returns {string} A string GUID


function randomString(length, charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
    let str = '',
        isAllNumeric = false,
        isNegative = false,
        useCharSet = charSet;

    if (+length) {
        if (!isString(charSet)) {
            if (isNumber(charSet)) {
                if (+charSet) {
                    isAllNumeric = true;
                    isNegative = +charSet < 0;
                    useCharSet = `${Math.abs(+charSet)}`;
                } else {
                    useCharSet = ALPHANUMERIC_CHARS;
                }
            } else {
                useCharSet = ALPHANUMERIC_CHARS;
            }
        }

        const generateChar = function gc(len) {
            return Math.round(Math.random() * (len - 1));
        }.bind(null, useCharSet.length);

        str = Array(+length).fill().map((v, index) => {
            const newChar = generateChar();
            /* If we are generating a random number, make sure the first digit is not zero */
            if (!index && isAllNumeric && !newChar) {
                return useCharSet.charAt(newChar + 1);
            }

            return useCharSet.charAt(newChar);
        }).join('');
    }

    if (isAllNumeric) {
        return isNegative ? -+str : +str;
    }

    return str;
}

Generates a random string of text of a given length.
Will generate an alpha-numeric string unless you specify a different character set as the second argument
@method utilitarian.string.util#randomString
@param {number} length The length of the string to generate
@param {string|number} [charSet] optional set of characters to use when generating a random string
(defaults to full alpha-numeric set)
@returns {string|number} A randomly generated string or number

Generates a random string of text of a given length . Will generate an alpha - numeric string unless you specify a different character set as the second argument


function toUint(str) {
    const string = window.btoa(unescape(encodeURIComponent(str))),
        chars = string.split(''),
        len = chars.length,
        uintArray = [];

    Array(len).fill().forEach((val, i) => uintArray.push(chars[i].charCodeAt(0)));

    return new Uint8Array(uintArray);
}

function toUint ( str ) { const string = window . btoa ( unescape ( encodeURIComponent ( str ) ) ) , chars = string . split ( '' ) , len = chars . length , uintArray = [ ] ; Array ( len ) . fill ( ) . forEach ( ( val , i ) => uintArray . push ( chars [ i ] . charCodeAt ( 0 ) ) ) ; return new Uint8Array ( uintArray ) ; }

Converts a string value to `Uint8array`
@method utilitarian.string.util#toUint
@param {string} str A string value to convert to `Uint8array`
@returns {Uint8Array} A `Uint8Array` representation of the original string


function toArrayBuffer(str) {
    /* eslint no-bitwise: "off" */
    const len = isString(str) ? str.length : 0,
        buf = new ArrayBuffer(len),
        view = new Uint8Array(buf);

    Array(len).fill().forEach((val, i) => (view[i] = str.charCodeAt(i) & 0xFF));

    return view;
}

function
toArrayBuffer
(
str
)
{
/* eslint no-bitwise: "off" */
const
len
=
isString
(
str
)
str
.
length
:
0
,
buf
=
new
ArrayBuffer
(
len
)
,
view
=
new
Uint8Array
(
buf
)
;
Array
(
len
)
.
fill
(
)
.
forEach
(
(
val
,
i
)
=>
(
view
[
i
]
=
str
.
charCodeAt
(
i
)
&
0xFF
)
)
;
return
view
;
}

Converts a string value to an `ArrayBuffer`
@method utilitarian.string.util#toArrayBuffer
@param {string} str A string value to convert to `ArrayBuffer`
@returns {Uint8Array} An `ArrayBuffer` representation of the original string

Converts a string value to an ArrayBuffer


function() {
        if (!this.$backButtonContainer) {
            return;
        }
        var i = 0,
            backButtonContainer = this.$backButtonContainer,
            items = backButtonContainer.items,
            item;

        for(;i < items.length; i++) {
            item = items.get(i);
            if(!item.isHidden()) {
                this.$backButtonContainer.show();
                return;
            }
        }

        this.$backButtonContainer.hide();
    }

function ( ) { if ( ! this . $backButtonContainer ) { return ; } var i = 0 , backButtonContainer = this . $backButtonContainer , items = backButtonContainer . items , item ; for ( ; i < items . length ; i ++ ) { item = items . get ( i ) ; if ( ! item . isHidden ( ) ) { this . $backButtonContainer . show ( ) ; return ; } } this . $backButtonContainer . hide ( ) ; }

This is used for Blackberry SplitNavigation to monitor the state of child items in the bottom toolbar.
if no visible children exist the toolbar will be hidden
@private

This is used for Blackberry SplitNavigation to monitor the state of child items in the bottom toolbar . if no visible children exist the toolbar will be hidden


function(message, priority, callerId) {
        if (!this.getEnabled()) {
            return this;
        }

        var statics = Logger,
            priorities = statics.priorities,
            priorityValue = priorities[priority],
            caller = this.log.caller,
            callerDisplayName = '',
            writers = this.getWriters(),
            event, i, originalCaller;

        if (!priority) {
            priority = 'info';
        }

        if (priorities[this.getMinPriority()] > priorityValue) {
            return this;
        }

        if (!callerId) {
            callerId = 1;
        }

        if (Ext.isArray(message)) {
            message = message.join(" ");
        }
        else {
            message = String(message);
        }

        if (typeof callerId == 'number') {
            i = callerId;

            do {
                i--;

                caller = caller.caller;

                if (!caller) {
                    break;
                }

                if (!originalCaller) {
                    originalCaller = caller.caller;
                }

                if (i <= 0 && caller.displayName) {
                    break;
                }
            }
            while (caller !== originalCaller);

            callerDisplayName = Ext.getDisplayName(caller);
        }
        else {
            caller = caller.caller;
            callerDisplayName = Ext.getDisplayName(callerId) + '#' + caller.$name;
        }

        event = {
            time: Ext.Date.now(),
            priority: priorityValue,
            priorityName: priority,
            message: message,
            caller: caller,
            callerDisplayName: callerDisplayName
        };

        for (i in writers) {
            if (writers.hasOwnProperty(i)) {
                writers[i].write(Ext.merge({}, event));
            }
        }

        return this;
    }

function
(
message
,
priority
,
callerId
)
{
if
(
!
this
.
getEnabled
(
)
)
{
return
this
;
}
var
statics
=
Logger
,
priorities
=
statics
.
priorities
,
priorityValue
=
priorities
[
priority
]
,
caller
=
this
.
log
.
caller
,
callerDisplayName
=
''
,
writers
=
this
.
getWriters
(
)
,
event
,
i
,
originalCaller
;
if
(
!
priority
)
{
priority
=
'info'
;
}
if
(
priorities
[
this
.
getMinPriority
(
)
]
>
priorityValue
)
{
return
this
;
}
if
(
!
callerId
)
{
callerId
=
1
;
}
if
(
Ext
.
isArray
(
message
)
)
{
message
=
message
.
join
(
" "
)
;
}
else
{
message
=
String
(
message
)
;
}
if
(
typeof
callerId
==
'number'
)
{
i
=
callerId
;
do
{
i
;
caller
=
caller
.
caller
;
if
(
!
caller
)
{
break
;
}
if
(
!
originalCaller
)
{
originalCaller
=
caller
.
caller
;
}
if
(
i
<=
0
&&
caller
.
displayName
)
{
break
;
}
}
while
(
caller
!==
originalCaller
)
;
callerDisplayName
=
Ext
.
getDisplayName
(
caller
)
;
}
else
{
caller
=
caller
.
caller
;
callerDisplayName
=
Ext
.
getDisplayName
(
callerId
)
+
'#'
+
caller
.
$name
;
}
event
=
{
time
:
Ext
.
Date
.
now
(
)
,
priority
:
priorityValue
,
priorityName
:
priority
,
message
:
message
,
caller
:
caller
,
callerDisplayName
:
callerDisplayName
}
;
for
(
i
in
writers
)
{
if
(
writers
.
hasOwnProperty
(
i
)
)
{
writers
[
i
]
.
write
(
Ext
.
merge
(
{
}
,
event
)
)
;
}
}
return
this
;
}

Logs a message to help with debugging.
@param {String} message  Message to log.
@param {Number} priority Priority of the log message.


function copyFileSync(source, destination) {
  if (validateFileSync(source)) {
    fs.writeFileSync(destination, fs.readFileSync(source));
  }
}

function copyFileSync ( source , destination ) { if ( validateFileSync ( source ) ) { fs . writeFileSync ( destination , fs . readFileSync ( source ) ) ; } }

Shortcut to copy a file Synchronously
@param source
@param destination


function copyFilesMatchSync(match, source, destination) {
  fs.readdirSync(source).forEach(function eachTemplate(filename) {
    var sourceFile = path.join(source, filename);
    var destinationFile = path.join(destination, filename);
    if (match.test(path.basename(filename))) {
      fs.writeFileSync(destinationFile, fs.readFileSync(sourceFile));
    }
  });
}

function copyFilesMatchSync ( match , source , destination ) { fs . readdirSync ( source ) . forEach ( function eachTemplate ( filename ) { var sourceFile = path . join ( source , filename ) ; var destinationFile = path . join ( destination , filename ) ; if ( match . test ( path . basename ( filename ) ) ) { fs . writeFileSync ( destinationFile , fs . readFileSync ( sourceFile ) ) ; } } ) ; }

If there are any files in the source folder that are a match copy them to the destination.
@param match
@param source
@param destination

If there are any files in the source folder that are a match copy them to the destination .


function replaceMatchFilesSync(match, source, destination) {
  unlinkFilesMatchSync(match, destination);
  copyFilesMatchSync(match, source, destination);
}

function replaceMatchFilesSync ( match , source , destination ) { unlinkFilesMatchSync ( match , destination ) ; copyFilesMatchSync ( match , source , destination ) ; }

Copy any number files that are a match to a regex to a given destination.
If there are any files in the destination that are also a match replace them.
@param match
@param source
@param destination

Copy any number files that are a match to a regex to a given destination . If there are any files in the destination that are also a match replace them .


function unlinkFilesMatchSync(match, location) {
  fs.readdirSync(location).forEach(function eachTemplate(filename) {
    if (match.test(path.basename(filename))) {
      var filePath = path.join(location, filename);
      if (validateFileSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }
  });
}

function unlinkFilesMatchSync ( match , location ) { fs . readdirSync ( location ) . forEach ( function eachTemplate ( filename ) { if ( match . test ( path . basename ( filename ) ) ) { var filePath = path . join ( location , filename ) ; if ( validateFileSync ( filePath ) ) { fs . unlinkSync ( filePath ) ; } } } ) ; }

If there are any files in the location folder that are a match remove them.
@param match
@param location

If there are any files in the location folder that are a match remove them .


function validateDirectorySync(path, errorMessage) {
  errorMessage = errorMessage || 'Error validateDirectorySync() the directory path is not valid ' + path;
  var isValid = existsDirectorySync(path);
  if (!isValid) {
    console.error(errorMessage);
  }
  return isValid;
}

Validate if a given path has a valid directory, is it doesn't console.error with an optional custom message.
@param path
@param errorMessage
@returns {Boolean}

Validate if a given path has a valid directory is it doesn t console . error with an optional custom message .


function validateFileSync(path, errorMessage) {
  errorMessage = errorMessage || 'Error validateFileSync() the file path is not valid ' + path;
  var isValid = existsFileSync(path);
  if (!isValid) {
    console.error(errorMessage);
  }
  return isValid;
}

Validate if a given path has a valid file, is it doesn't console.error with an optional custom message.
@param path
@param errorMessage
@returns {Boolean}

Validate if a given path has a valid file is it doesn t console . error with an optional custom message .


function subDirectoriesWithFile(base, filename) {
  var result = [];
  if (fs.existsSync(base) && fs.statSync(base).isDirectory()) {
    if (fs.existsSync(path.join(base, filename))) {
      result.push(base);
    }
    fs.readdirSync(base)
      .forEach(function (subdir) {
        result.push.apply(result, subDirectoriesWithFile(path.join(base, subdir), filename));
      });
  }
  return result;
}

function subDirectoriesWithFile ( base , filename ) { var result = [ ] ; if ( fs . existsSync ( base ) && fs . statSync ( base ) . isDirectory ( ) ) { if ( fs . existsSync ( path . join ( base , filename ) ) ) { result . push ( base ) ; } fs . readdirSync ( base ) . forEach ( function ( subdir ) { result . push . apply ( result , subDirectoriesWithFile ( path . join ( base , subdir ) , filename ) ) ; } ) ; } return result ; }

Find all subdirectories of the base, recursively.
@param base The base directory to start in
@param filename A filename that needs to be found for the path to be added
@return all subdirectories of the base, split by path separator

Find all subdirectories of the base recursively .


function maximisePath() {
  // Ensure each element in the path exists,
  // where it is a regex, match it and replace the element with a string
  var elements = Array.prototype.slice.call(arguments);

  for (var i = 1; i < elements.length; i++) {
    // the directory is elements 0 .. i-1 joined
    var directory = path.resolve(path.join.apply(path, elements.slice(0, i)));

    // no directory implies failure
    if (!fs.existsSync(directory)) {
      return null;
    }
    // regex element is matched
    else if ((typeof elements[i] !== 'string') && ('test' in elements[i])) {

      var matches = resolveDirMatches(directory, elements[i]);

      // no match implies failure, else use the item with the highest numeric index
      if (matches.length === 0) {
        return null;
      } else {
        elements[i] = matches[0];
      }
    }
    // anything else is cast to string
    else {
      elements[i] = String(elements[i]);
    }
  }

  // now join them all together
  // do a final check to make sure it exists
  var result = path.resolve(elements.join(path.sep));
  return fs.existsSync(result) && result;
}

Match the path defined by path elements, where some may be RegExp.
When there is more than one candidate, prefer the one with greatest interger value.
@param {...string|RegExp} elements Any number of path elements
@returns {string|boolean} A true concatenated path where found, else false

Match the path defined by path elements where some may be RegExp . When there is more than one candidate prefer the one with greatest interger value .


function resolveDirMatches(directory, match) {
  if (validateDirectorySync(directory)) {
    return fs.readdirSync(directory)
      .filter(function eachDirectoryItem(item) {
        var resolved = path.resolve(path.join(directory, item));
        return match.test(item) && fs.statSync(resolved).isDirectory();
      })
      .sort(compareHigher);
  } else {
    return [];
  }
}

function resolveDirMatches ( directory , match ) { if ( validateDirectorySync ( directory ) ) { return fs . readdirSync ( directory ) . filter ( function eachDirectoryItem ( item ) { var resolved = path . resolve ( path . join ( directory , item ) ) ; return match . test ( item ) && fs . statSync ( resolved ) . isDirectory ( ) ; } ) . sort ( compareHigher ) ; } else { return [ ] ; } }

For a given directory find all files that match, the result will be sorted with highest numeric index first.
@param directory
@param match
@returns {T[]}

For a given directory find all files that match the result will be sorted with highest numeric index first .


function compareHigher(a, b) {
  var numA = parseFloat(/[\d\.]+$/.exec(a)[0]);
  var numB = parseFloat(/[\d\.]+$/.exec(b)[0]);
  if (isNaN(numA) || (numB > numA)) {
    return +1;
  } else if (isNaN(numB) || (numA > numB)) {
    return -1;
  } else {
    return 0;
  }
}

function compareHigher ( a , b ) { var numA = parseFloat ( / [\d\.]+$ / . exec ( a ) [ 0 ] ) ; var numB = parseFloat ( / [\d\.]+$ / . exec ( b ) [ 0 ] ) ; if ( isNaN ( numA ) || ( numB > numA ) ) { return + 1 ; } else if ( isNaN ( numB ) || ( numA > numB ) ) { return - 1 ; } else { return 0 ; } }

Rank a vs b based on any numeric component in their string.

Rank a vs b based on any numeric component in their string .


function reduceDirectories() {
  return Array.prototype.slice.call(arguments)
    .map(function (candidate) {
      return path.normalize(candidate);
    })
    .filter(function (candidate) {
      return fs.existsSync(candidate) && fs.statSync(candidate).isDirectory();
    })
    .shift();
}

function reduceDirectories ( ) { return Array . prototype . slice . call ( arguments ) . map ( function ( candidate ) { return path . normalize ( candidate ) ; } ) . filter ( function ( candidate ) { return fs . existsSync ( candidate ) && fs . statSync ( candidate ) . isDirectory ( ) ; } ) . shift ( ) ; }

Pick the first existing directory from any of the given arguments.
@param {...string} candidates Any number of possible directories
@returns {string} The first valid directory or else undefined

Pick the first existing directory from any of the given arguments .


function(side) {
        var menus = this.getMenus() || {},
            menu = menus[side];

        if(menu) this.hideMenu(side);
        delete menus[side];
        this.setMenus(menus);
    }

function ( side ) { var menus = this . getMenus ( ) || { } , menu = menus [ side ] ; if ( menu ) this . hideMenu ( side ) ; delete menus [ side ] ; this . setMenus ( menus ) ; }

Removes a menu from a specified side.
@param {String} side The side to remove the menu from


function(side) {
        var menus = this.getMenus(),
            menu = menus[side],
            before, after,
            viewportBefore, viewportAfter;

        if (!menu || menu.isAnimating) {
            return;
        }

        this.hideOtherMenus(side);

        before = {
            translateX: 0,
            translateY: 0
        };

        after = {
            translateX: 0,
            translateY: 0
        };

        viewportBefore = {
            translateX: 0,
            translateY: 0
        };

        viewportAfter = {
            translateX: 0,
            translateY: 0
        };

        if (menu.$reveal) {
            Ext.getBody().insertFirst(menu.element);
        }
        else {
            Ext.Viewport.add(menu);
        }

        menu.show();
        menu.addCls('x-' + side);

        var size = (side == 'left' || side == 'right') ? menu.element.getWidth() : menu.element.getHeight();

        if (side == 'left') {
            before.translateX = -size;
            viewportAfter.translateX = size;
        }
        else if (side == 'right') {
            before.translateX = size;
            viewportAfter.translateX = -size;
        }
        else if (side == 'top') {
            before.translateY = -size;
            viewportAfter.translateY = size;
        }
        else if (side == 'bottom') {
            before.translateY = size;
            viewportAfter.translateY = -size;
        }

        if (menu.$reveal) {
            if (Ext.browser.getPreferredTranslationMethod() != 'scrollposition') {
                menu.translate(0, 0);
            }
        }
        else {
            menu.translate(before.translateX, before.translateY);
        }

        if (menu.$cover) {
            menu.getTranslatable().on('animationend', function() {
                menu.isAnimating = false;
            }, this, {
                single: true
            });

            menu.translate(after.translateX, after.translateY, {
                preserveEndState: true,
                duration: 200
            });

        }
        else {
            this.translate(viewportBefore.translateX, viewportBefore.translateY);

            this.getTranslatable().on('animationend', function() {
                menu.isAnimating = false;
            }, this, {
                single: true
            });

            this.translate(viewportAfter.translateX, viewportAfter.translateY, {
                preserveEndState: true,
                duration: 200
            });
        }

        // Make the menu as animating
        menu.isAnimating = true;
    }

function
(
side
)
{
var
menus
=
this
.
getMenus
(
)
,
menu
=
menus
[
side
]
,
before
,
after
,
viewportBefore
,
viewportAfter
;
if
(
!
menu
||
menu
.
isAnimating
)
{
return
;
}
this
.
hideOtherMenus
(
side
)
;
before
=
{
translateX
:
0
,
translateY
:
0
}
;
after
=
{
translateX
:
0
,
translateY
:
0
}
;
viewportBefore
=
{
translateX
:
0
,
translateY
:
0
}
;
viewportAfter
=
{
translateX
:
0
,
translateY
:
0
}
;
if
(
menu
.
$reveal
)
{
Ext
.
getBody
(
)
.
insertFirst
(
menu
.
element
)
;
}
else
{
Ext
.
Viewport
.
add
(
menu
)
;
}
menu
.
show
(
)
;
menu
.
addCls
(
'x-'
+
side
)
;
var
size
=
(
side
==
'left'
||
side
==
'right'
)
menu
.
element
.
getWidth
(
)
:
menu
.
element
.
getHeight
(
)
;
if
(
side
==
'left'
)
{
before
.
translateX
=
size
;
viewportAfter
.
translateX
=
size
;
}
else
if
(
side
==
'right'
)
{
before
.
translateX
=
size
;
viewportAfter
.
translateX
=
size
;
}
else
if
(
side
==
'top'
)
{
before
.
translateY
=
size
;
viewportAfter
.
translateY
=
size
;
}
else
if
(
side
==
'bottom'
)
{
before
.
translateY
=
size
;
viewportAfter
.
translateY
=
size
;
}
if
(
menu
.
$reveal
)
{
if
(
Ext
.
browser
.
getPreferredTranslationMethod
(
)
!=
'scrollposition'
)
{
menu
.
translate
(
0
,
0
)
;
}
}
else
{
menu
.
translate
(
before
.
translateX
,
before
.
translateY
)
;
}
if
(
menu
.
$cover
)
{
menu
.
getTranslatable
(
)
.
on
(
'animationend'
,
function
(
)
{
menu
.
isAnimating
=
false
;
}
,
this
,
{
single
:
true
}
)
;
menu
.
translate
(
after
.
translateX
,
after
.
translateY
,
{
preserveEndState
:
true
,
duration
:
200
}
)
;
}
else
{
this
.
translate
(
viewportBefore
.
translateX
,
viewportBefore
.
translateY
)
;
this
.
getTranslatable
(
)
.
on
(
'animationend'
,
function
(
)
{
menu
.
isAnimating
=
false
;
}
,
this
,
{
single
:
true
}
)
;
this
.
translate
(
viewportAfter
.
translateX
,
viewportAfter
.
translateY
,
{
preserveEndState
:
true
,
duration
:
200
}
)
;
}
// Make the menu as animating
menu
.
isAnimating
=
true
;
}

Shows a menu specified by the menu's side.
@param {String} side The side which the menu is placed.

Shows a menu specified by the menu s side .