function parseOptions(options={}, vinylCjsDeps) {
	const _options = Object.assign({
		gulp: vinylCjsDeps.gulp || require('gulp'),
		base: options.cwd || process.cwd(),
		cwd: options.base || process.cwd(),
		internalOnly: false,
		debugVcjd: false
	}, options);

	_options.mapper = Object.assign({}, options.mapper || {});
	_options.lookup = new Map(options.lookup || []);
	_options.resolver = createResolver(options);

	return _options;
}

function parseOptions ( options = { } , vinylCjsDeps ) { const _options = Object . assign ( { gulp : vinylCjsDeps . gulp || require ( 'gulp' ) , base : options . cwd || process . cwd ( ) , cwd : options . base || process . cwd ( ) , internalOnly : false , debugVcjd : false } , options ) ; _options . mapper = Object . assign ( { } , options . mapper || { } ) ; _options . lookup = new Map ( options . lookup || [ ] ) ; _options . resolver = createResolver ( options ) ; return _options ; }

Parse the src options adding defaults.

@param {object} options			Options object.
@param {Object} vinylCjsDeps		The module.
@returns {Object}				Mutated options (defaults added).


function(){
        var me = this,
            prev = me.store.currentPage - 1;

        if (prev > 0) {
            if (me.fireEvent('beforechange', me, prev) !== false) {
                me.store.previousPage();
            }
        }
    }

function ( ) { var me = this , prev = me . store . currentPage - 1 ; if ( prev > 0 ) { if ( me . fireEvent ( 'beforechange' , me , prev ) !== false ) { me . store . previousPage ( ) ; } } }

Move to the previous page, has the same effect as clicking the 'previous' button.

Move to the previous page has the same effect as clicking the previous button .


function(){
        var me = this,
            total = me.getPageData().pageCount,
            next = me.store.currentPage + 1;

        if (next <= total) {
            if (me.fireEvent('beforechange', me, next) !== false) {
                me.store.nextPage();
            }
        }
    }

function ( ) { var me = this , total = me . getPageData ( ) . pageCount , next = me . store . currentPage + 1 ; if ( next <= total ) { if ( me . fireEvent ( 'beforechange' , me , next ) !== false ) { me . store . nextPage ( ) ; } } }

Move to the next page, has the same effect as clicking the 'next' button.

Move to the next page has the same effect as clicking the next button .


function(){
        var me = this,
            last = me.getPageData().pageCount;

        if (me.fireEvent('beforechange', me, last) !== false) {
            me.store.loadPage(last);
        }
    }

function ( ) { var me = this , last = me . getPageData ( ) . pageCount ; if ( me . fireEvent ( 'beforechange' , me , last ) !== false ) { me . store . loadPage ( last ) ; } }

Move to the last page, has the same effect as clicking the 'last' button.

Move to the last page has the same effect as clicking the last button .


function(){
        var me = this,
            current = me.store.currentPage;

        if (me.fireEvent('beforechange', me, current) !== false) {
            me.store.loadPage(current);
        }
    }

function ( ) { var me = this , current = me . store . currentPage ; if ( me . fireEvent ( 'beforechange' , me , current ) !== false ) { me . store . loadPage ( current ) ; } }

Refresh the current page, has the same effect as clicking the 'refresh' button.

Refresh the current page has the same effect as clicking the refresh button .


function(fromClass, members) {
            //<debug>
            Ext.classSystemMonitor && Ext.classSystemMonitor(this, 'Ext.Base#borrow', arguments);
            //</debug>

            var prototype = this.prototype,
                fromPrototype = fromClass.prototype,
                //<debug>
                className = Ext.getClassName(this),
                //</debug>
                i, ln, name, fn, toBorrow;

            members = Ext.Array.from(members);

            for (i = 0,ln = members.length; i < ln; i++) {
                name = members[i];

                toBorrow = fromPrototype[name];

                if (typeof toBorrow == 'function') {
                    fn = Ext.Function.clone(toBorrow);

                    //<debug>
                    if (className) {
                        fn.displayName = className + '#' + name;
                    }
                    //</debug>

                    fn.$owner = this;
                    fn.$name = name;

                    prototype[name] = fn;
                }
                else {
                    prototype[name] = toBorrow;
                }
            }

            return this;
        }

function ( fromClass , members ) { //<debug> Ext . classSystemMonitor && Ext . classSystemMonitor ( this , 'Ext.Base#borrow' , arguments ) ; //</debug> var prototype = this . prototype , fromPrototype = fromClass . prototype , //<debug> className = Ext . getClassName ( this ) , //</debug> i , ln , name , fn , toBorrow ; members = Ext . Array . from ( members ) ; for ( i = 0 , ln = members . length ; i < ln ; i ++ ) { name = members [ i ] ; toBorrow = fromPrototype [ name ] ; if ( typeof toBorrow == 'function' ) { fn = Ext . Function . clone ( toBorrow ) ; //<debug> if ( className ) { fn . displayName = className + '#' + name ; } //</debug> fn . $owner = this ; fn . $name = name ; prototype [ name ] = fn ; } else { prototype [ name ] = toBorrow ; } } return this ; }

Borrow another class' members to the prototype of this class.

Ext.define('Bank', {
money: '$$$',
printMoney: function() {
alert('$$$$$$$');
}
});

Ext.define('Thief', {
...
});

Thief.borrow(Bank, ['money', 'printMoney']);

var steve = new Thief();

alert(steve.money); // alerts '$$$'
steve.printMoney(); // alerts '$$$$$$$'

@param {Ext.Base} fromClass The class to borrow members from
@param {Array/String} members The names of the members to borrow
@return {Ext.Base} this
@static
@inheritable
@private

Borrow another class members to the prototype of this class .


function getOptions(opts) {
    opts = opts || {};

    // command line arguments override options
    _.extend(opts, argv);
    delete opts.$0;
    delete opts._;

    // these values are used in multiple tasks, so set defaults here
    opts.unitTestCode = opts.unitTestCode || 'test/unit/**/*.js';
    opts.unitTargetCode = opts.unitTargetCode || 'lib/**/*.js';
    opts.testDir = opts.testDir || 'test';
    opts.rootDir = opts.rootDir || process.cwd();
    opts.targetDir = opts.targetDir || (opts.rootDir + '/lib');
    opts.tasksets = _.extend({ 'default': ['lint', 'test'] }, opts.tasksets);

    return opts;
}

Set options defaults that are used for batter tasks
@param opts Object with options for batter
@returns {*|{}}


function getPlugins(opts) {
    var batterRootDir = __dirname.replace(delim + 'lib', '');
    var batterTasks = { rootDir: batterRootDir };
    var currentProject = { rootDir: opts.rootDir };
    var plugins = opts.plugins || [];

    // tasks in batter go to the front of the list; current project at the end (i.e. most important)
    plugins.unshift(batterTasks);

    if (batterRootDir !== opts.rootDir) {
        plugins.push(currentProject);
    }

    return plugins;
}

Helper function to get the plugins for which we will look for tasks
@param opts


function whip(gulp, taste, opts) {
    opts = getOptions(opts);
    opts.taste = taste;

    var tasks = _.extend({}, opts.tasksets);

    // loop through plugins so we can get tasks from them
    _.each(getPlugins(opts), function (plugin) {
        var pluginRoot = plugin.rootDir;
        var pluginBuildDir = pluginRoot + delim + 'build';

        // look through files in the plugin build directory to try and find tasks
        if (fs.existsSync(pluginBuildDir)) {
            _.each(fs.readdirSync(pluginBuildDir), function (pluginFile) {
                var taskName, task;

                // if the file name starts with 'task.' then it is a task file
                if (taskRegex.test(pluginFile)) {

                    // the task name is the middle part of the file name (i.e. blah for task.blah.js)
                    taskName = pluginFile.match(taskRegex)[1];
                    task = require(pluginBuildDir + delim + pluginFile)(gulp, opts);

                    // if task is function or an object with deps and task
                    if (_.isFunction(task) || (task.deps && task.task)) {
                        tasks[taskName] = task;
                    }
                    // else if it's an object, then there are subtasks
                    else if (_.isObject(task)) {
                        _.each(task, function (subtask, subtaskName) {
                            var fullTaskName = subtaskName === '' ? taskName : taskName + '.' + subtaskName;
                            tasks[fullTaskName] = subtask;
                        });
                    }
                    else {
                        throw new Error(pluginBuildDir + delim + pluginFile + ' is invalid');
                    }
                }
            });
        }
    });

    // now we have all the tasks in an object so let's add them to gulp
    _.each(tasks, function (task, taskName) {
        if (_.isFunction(task) || _.isArray(task)) {
            gulp.task(taskName, task);
        }
        else if (task.deps && task.task) {
            gulp.task(taskName, task.deps, task.task);
        }
        else {
            throw new Error('Invalid task for ' + taskName);
        }
    });
}

Whip up tasks by adding them to gulpkl
@param gulp
@param taste
@param opts


function(module, method) {

            var all = {urlparams:[]}

            for(var i=2;i<u.length;i++) all.urlparams.push(decodeURIComponent(u[i]));

            req.cookies = {}

            req.headers.cookie && req.headers.cookie.split(';').forEach(function( cookie ) {
                var parts = cookie.split('=')
                    ,key = parts[0].trim()
                    ,val = decodeURIComponent((parts[1] || '').trim());
                all[key] = val;
                req.cookies[key] = val
            });
            if(url.query != null) for(var i in url.query) all[i] = url.query[i]
            if(post != null) for(var i in post) all[i] = post[i]

            all.response = res
            all.request = req
            all._query = url.query

            if(me.config.LOCALE && !all.locale) {
                all.locale = req.url.substr(1,2)
                if(!me.config.LOCALE[all.locale]) delete all.locale
            }

            // Проверяем JSON в запросе
            if(all.jsonData) {
                try{
                    all.RequestData = JSON.parse(all.jsonData)
                } catch(e) {}
                if(all.RequestData && !me.checkVersion(all.RequestData)) {
                    mcallback({}, {code: 4})
                    return;
                }
            }
            if(!all.RequestData) all.RequestData = {}

            var run = function(auth) {
                all.href = req.url
                if(all.about !== null && all.about !== undefined && module[method].aboutObject !== null) {
                    mcallback(module[method].aboutObject)
                } else {
                    module[method](all, mcallback, auth);
                }
            }

            if(me.inits.checkauth != null) {  // if isser user checkauth function
                me.inits.checkauth(all, function(a) {run(a)})
            } else {
                run(null);
            }
            return true;
        }

// Проверяем JSON в запросе


function(request){
        var me = this,
            requests = me.requests,
            key;

        if (request) {
            if (!request.id) {
                request = requests[request];
            }
            me.handleAbort(request);
        } else {
            for (key in requests) {
                if (requests.hasOwnProperty(key)) {
                    me.abort(requests[key]);
                }
            }
        }
    }

function ( request ) { var me = this , requests = me . requests , key ; if ( request ) { if ( ! request . id ) { request = requests [ request ] ; } me . handleAbort ( request ) ; } else { for ( key in requests ) { if ( requests . hasOwnProperty ( key ) ) { me . abort ( requests [ key ] ) ; } } } }

Abort a request. If the request parameter is not specified all open requests will
be aborted.
@param {Object/String} request (Optional) The request to abort

Abort a request . If the request parameter is not specified all open requests will be aborted .


function(result, request){

        var success = true;

        if (request.timeout) {
            clearTimeout(request.timeout);
        }
        delete this[request.callbackName];
        delete this.requests[request.id];
        this.cleanupErrorHandling(request);
        Ext.fly(request.script).remove();

        if (request.errorType) {
            success = false;
            Ext.callback(request.failure, request.scope, [request.errorType]);
        } else {
            Ext.callback(request.success, request.scope, [result]);
        }
        Ext.callback(request.callback, request.scope, [success, result, request.errorType]);
        Ext.EventManager.idleEvent.fire();
    }

function ( result , request ) { var success = true ; if ( request . timeout ) { clearTimeout ( request . timeout ) ; } delete this [ request . callbackName ] ; delete this . requests [ request . id ] ; this . cleanupErrorHandling ( request ) ; Ext . fly ( request . script ) . remove ( ) ; if ( request . errorType ) { success = false ; Ext . callback ( request . failure , request . scope , [ request . errorType ] ) ; } else { Ext . callback ( request . success , request . scope , [ result ] ) ; } Ext . callback ( request . callback , request . scope , [ success , result , request . errorType ] ) ; Ext . EventManager . idleEvent . fire ( ) ; }

Handle a successful response
@private
@param {Object} result The result from the request
@param {Object} request The request


function(url, params, options) {
        var script = document.createElement('script');
        script.setAttribute("src", Ext.urlAppend(url, Ext.Object.toQueryString(params)));
        script.setAttribute("async", true);
        script.setAttribute("type", "text/javascript");
        return script;
    }

function ( url , params , options ) { var script = document . createElement ( 'script' ) ; script . setAttribute ( "src" , Ext . urlAppend ( url , Ext . Object . toQueryString ( params ) ) ) ; script . setAttribute ( "async" , true ) ; script . setAttribute ( "type" , "text/javascript" ) ; return script ; }

Create the script tag given the specified url, params and options. The options
parameter is passed to allow an override to access it.
@private
@param {String} url The url of the request
@param {Object} params Any extra params to be sent
@param {Object} options The object passed to {@link #request}.

Create the script tag given the specified url params and options . The options parameter is passed to allow an override to access it .


function createTableGrid(node) {
				var selection = ed.selection, tblElm = ed.dom.getParent(node || selection.getNode(), 'table');

				if (tblElm)
					return new TableGrid(tblElm, ed.dom, selection);
			}

function createTableGrid ( node ) { var selection = ed . selection , tblElm = ed . dom . getParent ( node || selection . getNode ( ) , 'table' ) ; if ( tblElm ) return new TableGrid ( tblElm , ed . dom , selection ) ; }


function fixTableCellSelection(ed) {
					if (!tinymce.isWebKit)
						return;

					var rng = ed.selection.getRng();
					var n = ed.selection.getNode();
					var currentCell = ed.dom.getParent(rng.startContainer, 'TD,TH');

					if (!tableCellSelected(ed, rng, n, currentCell))
						return;
						if (!currentCell) {
							currentCell=n;
						}

					// Get the very last node inside the table cell
					var end = currentCell.lastChild;
					while (end.lastChild)
						end = end.lastChild;

					// Select the entire table cell. Nothing outside of the table cell should be selected.
					rng.setEnd(end, end.nodeValue.length);
					ed.selection.setRng(rng);
				}

this nasty hack is here to work around some WebKit selection bugs.

this nasty hack is here to work around some WebKit selection bugs .


function fixTableCaretPos() {
					var last;

					// Skip empty text nodes form the end
					for (last = ed.getBody().lastChild; last && last.nodeType == 3 && !last.nodeValue.length; last = last.previousSibling) ;

					if (last && last.nodeName == 'TABLE') {
						if (ed.settings.forced_root_block)
							ed.dom.add(ed.getBody(), ed.settings.forced_root_block, null, tinymce.isIE ? ' ' : '<br data-mce-bogus="1" />');
						else
							ed.dom.add(ed.getBody(), 'br', {'data-mce-bogus': '1'});
					}
				}

function
fixTableCaretPos
(
)
{
var
last
;
// Skip empty text nodes form the end
for
(
last
=
ed
.
getBody
(
)
.
lastChild
;
last
&&
last
.
nodeType
==
3
&&
!
last
.
nodeValue
.
length
;
last
=
last
.
previousSibling
)
;
if
(
last
&&
last
.
nodeName
==
'TABLE'
)
{
if
(
ed
.
settings
.
forced_root_block
)
ed
.
dom
.
add
(
ed
.
getBody
(
)
,
ed
.
settings
.
forced_root_block
,
,
tinymce
.
isIE
' '
:
'<br data-mce-bogus="1" />'
)
;
else
ed
.
dom
.
add
(
ed
.
getBody
(
)
,
'br'
,
{
'data-mce-bogus'
:
'1'
}
)
;
}
}

Fixes an issue on Gecko where it's impossible to place the caret behind a table This fix will force a paragraph element after the table but only when the forced_root_block setting is enabled

Fixes an issue on Gecko where it s impossible to place the caret behind a table This fix will force a paragraph element after the table but only when the forced_root_block setting is enabled


function(column) {
        var result = column.width || 0,
            subcols, len, i;

        // <debug>
        if (column.flex) {
            Ext.Error.raise("Columns which are locked do NOT support a flex width. You must set a width on the " + column.text + "column.");
        }
        // </debug>
        if (!result && column.isGroupHeader) {
            subcols = column.items.items;
            len = subcols.length;
            for (i = 0; i < len; i++) {
                result += this.getColumnWidth(subcols[i]);
            }
        }
        return result;
    }

Used when calculating total locked column width in processColumns Use shrinkwrapping of child columns if no top level width.

Used when calculating total locked column width in processColumns Use shrinkwrapping of child columns if no top level width .


function(activeHd, toIdx) {
        var me         = this,
            normalGrid = me.normalGrid,
            lockedGrid = me.lockedGrid,
            normalHCt  = normalGrid.headerCt,
            lockedHCt  = lockedGrid.headerCt,
            refreshFlags,
            ownerCt;

        activeHd = activeHd || normalHCt.getMenu().activeHeader;
        ownerCt = activeHd.ownerCt;

        // if column was previously flexed, get/set current width
        // and remove the flex
        if (activeHd.flex) {
            activeHd.width = activeHd.getWidth();
            delete activeHd.flex;
        }

        Ext.suspendLayouts();
        ownerCt.remove(activeHd, false);
        activeHd.locked = true;

        // Flag to the locked column add listener to do nothing
        me.ignoreAddLockedColumn = true;
        if (Ext.isDefined(toIdx)) {
            lockedHCt.insert(toIdx, activeHd);
        } else {
            lockedHCt.add(activeHd);
        }
        me.ignoreAddLockedColumn = false;

        refreshFlags = me.syncLockedWidth();
        if (refreshFlags[0]) {
            lockedGrid.getView().refresh();
        }
        if (refreshFlags[1]) {
            normalGrid.getView().refresh();
        }
        Ext.resumeLayouts(true);

        me.fireEvent('lockcolumn', me, activeHd);
    }

going from unlocked section to locked
Locks the activeHeader as determined by which menu is open OR a header
as specified.
@param {Ext.grid.column.Column} [header] Header to unlock from the locked section.
Defaults to the header which has the menu open currently.
@param {Number} [toIdx] The index to move the unlocked header to.
Defaults to appending as the last item.
@private

going from unlocked section to locked Locks the activeHeader as determined by which menu is open OR a header as specified .


function(store, columns) {
        var me = this,
            oldStore = me.store,
            lockedGrid = me.lockedGrid,
            normalGrid = me.normalGrid;

        Ext.suspendLayouts();
        if (columns) {
            lockedGrid.headerCt.removeAll();
            normalGrid.headerCt.removeAll();

            columns = me.processColumns(columns);

            // Flag to the locked column add listener to do nothing
            me.ignoreAddLockedColumn = true;
            lockedGrid.headerCt.add(columns.locked.items);
            me.ignoreAddLockedColumn = false;
            normalGrid.headerCt.add(columns.normal.items);

            // Ensure locked grid is set up correctly with correct width and bottom border,
            // and that both grids' visibility and scrollability status is correct
            me.syncLockedWidth();
        }

        if (store && store !== oldStore) {
            store = Ext.data.StoreManager.lookup(store);
            me.store = store;
            lockedGrid.bindStore(store);
            normalGrid.bindStore(store);
        } else {
            lockedGrid.getView().refresh();
            normalGrid.getView().refresh();
        }
        Ext.resumeLayouts(true);
    }

we want to totally override the reconfigure behaviour here, since we're creating 2 sub-grids

we want to totally override the reconfigure behaviour here since we re creating 2 sub - grids


function defaultTransformer(...args) {
  try {
    let [record, ...rest] = args
    try {
      record = typeof record === 'string' ? JSON.parse(record) : record
    } catch(err) {
      return { type: 'bunyan', record: { err: new Error('Could not parse message.') } }
    }
    return { type: 'bunyan', record }
  } catch(err) {
    return { type: 'bunyan', record: { err: new Error('Internal error occurred.')}}
  }
}

function
defaultTransformer
(
...
args
)
{
try
{
let
[
record
,
...
rest
]
=
args
try
{
record
=
typeof
record
===
'string'
JSON
.
parse
(
record
)
:
record
}
catch
(
err
)
{
return
{
type
:
'bunyan'
,
record
:
{
err
:
new
Error
(
'Could not parse message.'
)
}
}
}
return
{
type
:
'bunyan'
,
record
}
}
catch
(
err
)
{
return
{
type
:
'bunyan'
,
record
:
{
err
:
new
Error
(
'Internal error occurred.'
)
}
}
}
}

defaultTransformer takes arguments from a bunyan WritableStream's write method and formats output in a standard way that can be interpreted by parent process.
@param  {...Object} args - args that were passed to WritableStream.prototype.write()
@return {Object}           Object to pass through IPC communication channel to parent process.

defaultTransformer takes arguments from a bunyan WritableStream s write method and formats output in a standard way that can be interpreted by parent process .


function getString(ref)
		{
			try
			{
				if (ref)
				{
					try
					{
						return ref;
					} catch (e) {
						return ref.toString();
					}
				}
				else {
					try
					{
						return ref.toString();
					}
					catch (e)
					{
						return "undefined";
					}
				}

			} catch (e)
			{
				// if we can not convert it to a string write "undefined" just like javascript
				return "undefined";
			}
		}

Sometimes calling the toString of an object generates an error so we catch it here


function clickMe (print_r, str)
	{
		return (function(){
			print_r.objRef = eval(str);
			print_r.strObjRef = str;
			print_r.refresh();
		});
	}

function clickMe ( print_r , str ) { return ( function ( ) { print_r . objRef = eval ( str ) ; print_r . strObjRef = str ; print_r . refresh ( ) ; } ) ; }

internal function for the clickable Elements


function arrSort(a,b)
	{
		var acomp = a['name'].toString(10);
		var bcomp = b['name'].toString(10);
		if (!isNaN(Number(acomp)))
		{
			acomp = Number(acomp);
		}
		if (!isNaN(Number(bcomp)))
		{
			bcomp = Number(bcomp);
		}
		if (acomp < bcomp)
		{
			return -1;
		}
		if (acomp > bcomp)
		{
			return 1;
		}
		return 0;
	}

function arrSort ( a , b ) { var acomp = a [ 'name' ] . toString ( 10 ) ; var bcomp = b [ 'name' ] . toString ( 10 ) ; if ( ! isNaN ( Number ( acomp ) ) ) { acomp = Number ( acomp ) ; } if ( ! isNaN ( Number ( bcomp ) ) ) { bcomp = Number ( bcomp ) ; } if ( acomp < bcomp ) { return - 1 ; } if ( acomp > bcomp ) { return 1 ; } return 0 ; }


function(filter, index, list) {
        // Shortcuts
        if (filter === 'combine') {
            list[index] = self.filters.combine;
            return;
        }

        // Solfege URI
        if (typeof filter === 'string' && self.application.isSolfegeUri(filter)) {
            list[index] = self.application.resolveSolfegeUri(filter, self);
        }
    }

function
(
filter
,
index
,
list
)
{
// Shortcuts
if
(
filter
===
'combine'
)
{
list
[
index
]
=
self
.
filters
.
combine
;
return
;
}
// Solfege URI
if
(
typeof
filter
===
'string'
&&
self
.
application
.
isSolfegeUri
(
filter
)
)
{
list
[
index
]
=
self
.
application
.
resolveSolfegeUri
(
filter
,
self
)
;
}
}


function getCurrentExpectedTypes(type) {
		var currentType;
		var expectedType;

		if (type.name) {
			currentType = type.name;
		} else if (type.expression) {
			currentType = type.expression.name;
		}

		expectedType = currentType && preferType[currentType];

		return {
			currentType: currentType,
			expectedType: expectedType
		};
	}

function getCurrentExpectedTypes ( type ) { var currentType ; var expectedType ; if ( type . name ) { currentType = type . name ; } else if ( type . expression ) { currentType = type . expression . name ; } expectedType = currentType && preferType [ currentType ] ; return { currentType : currentType , expectedType : expectedType } ; }

Extract the current and expected type based on the input type object
@param {Object} type JSDoc tag
@returns {Object} current and expected type object
@private


function validateType(jsdocNode, type) {
		if (!type || !canTypeBeValidated(type.type)) {
			return;
		}

		var typesToCheck = [];
		var elements = [];

		switch (type.type) {
			case 'TypeApplication':	 // {Array.<String>}
				elements = type.applications[0].type === 'UnionType' ? type.applications[0].elements : type.applications;
				typesToCheck.push(getCurrentExpectedTypes(type));
				break;
			case 'RecordType':	// {{20:String}}
				elements = type.fields;
				break;
			case 'UnionType':  // {String|number|Test}
			case 'ArrayType':  // {[String, number, Test]}
				elements = type.elements;
				break;
			case 'FieldType':  // Array.<{count: number, votes: number}>
				typesToCheck.push(getCurrentExpectedTypes(type.value));
				break;
			default:
				typesToCheck.push(getCurrentExpectedTypes(type));
		}

		elements.forEach(validateType.bind(null, jsdocNode));

		typesToCheck.forEach(function(typeToCheck) {
			if (typeToCheck.expectedType &&
				typeToCheck.expectedType !== typeToCheck.currentType) {
				context.report({
					node: jsdocNode,
					message: 'Use \'{{expectedType}}\' instead of \'{{currentType}}\'.',
					data: {
						currentType: typeToCheck.currentType,
						expectedType: typeToCheck.expectedType
					}
				});
			}
		});
	}

Check if return tag type is void or undefined
@param {Object} jsdocNode JSDoc node
@param {Object} type JSDoc tag
@returns {void}
@private


function requireJsDoc(node, isVirtual, paramsToCheck) {
		var lines = sourceCode.lines;
		var index = node.loc.start.line;
		lines = lines.slice(0, index);
		var matches = lines.filter(function(line) {
			return line.match(/\/\*\*/gi);
		});

		var lastIndex = lines.lastIndexOf(matches[matches.length - 1]);

		var jsdocComment = findJSDocComment(sourceCode.ast.comments, lastIndex);
		if (!jsdocComment) {
			report(node);
			return;
		}

		checkJSDoc(node, jsdocComment, isVirtual, paramsToCheck);
	}

function requireJsDoc ( node , isVirtual , paramsToCheck ) { var lines = sourceCode . lines ; var index = node . loc . start . line ; lines = lines . slice ( 0 , index ) ; var matches = lines . filter ( function ( line ) { return line . match ( / \/\*\* / gi ) ; } ) ; var lastIndex = lines . lastIndexOf ( matches [ matches . length - 1 ] ) ; var jsdocComment = findJSDocComment ( sourceCode . ast . comments , lastIndex ) ; if ( ! jsdocComment ) { report ( node ) ; return ; } checkJSDoc ( node , jsdocComment , isVirtual , paramsToCheck ) ; }

Check if the jsdoc comment is present or not.
@param {ASTNode} node node to examine
@returns {void}

Check if the jsdoc comment is present or not .


function SelectionType(typeSpec) {
    if (!Array.isArray(typeSpec.data) && typeof typeSpec.data !== 'function') {
        throw new Error('instances of SelectionType need typeSpec.data to be an array or function that returns an array:' + JSON.stringify(typeSpec));
    }
    Object.keys(typeSpec).forEach(function(key) {
        this[key] = typeSpec[key];
    }, this);
}


function DeferredType(typeSpec) {
    if (typeof typeSpec.defer !== 'function') {
        throw new Error('Instances of DeferredType need typeSpec.defer to be a function that returns a type');
    }
    Object.keys(typeSpec).forEach(function(key) {
        this[key] = typeSpec[key];
    }, this);
}

A we don't know right now, but hope to soon.

A we don t know right now but hope to soon .


function ArrayType(typeSpec) {
    if (typeSpec instanceof Type) {
        this.subtype = typeSpec;
    }
    else if (typeof typeSpec === 'string') {
        this.subtype = types.getType(typeSpec);
        if (this.subtype == null) {
            throw new Error('Unknown array subtype: ' + typeSpec);
        }
    }
    else {
        throw new Error('Can\' handle array subtype');
    }
}

function
ArrayType
(
typeSpec
)
{
if
(
typeSpec
instanceof
Type
)
{
this
.
subtype
=
typeSpec
;
}
else
if
(
typeof
typeSpec
===
'string'
)
{
this
.
subtype
=
types
.
getType
(
typeSpec
)
;
if
(
this
.
subtype
==
)
{
throw
new
Error
(
'Unknown array subtype: '
+
typeSpec
)
;
}
}
else
{
throw
new
Error
(
'Can\' handle array subtype'
)
;
}
}


function() {
        var conversion = this.parse('');
        if (lastSetting) {
            var current = lastSetting.get();
            if (conversion.predictions.length === 0) {
                conversion.predictions.push(current);
            }
            else {
                // Remove current from predictions
                var removed = false;
                while (true) {
                    var index = conversion.predictions.indexOf(current);
                    if (index === -1) {
                        break;
                    }
                    conversion.predictions.splice(index, 1);
                    removed = true;
                }
                // If the current value wasn't something we would predict, leave it
                if (removed) {
                    conversion.predictions.push(current);
                }
            }
        }
        return conversion;
    }

Promote the current value in any list of predictions, and add it if
there are none.

Promote the current value in any list of predictions and add it if there are none .


function ConversionHint(conversion, arg) {
    this.status = conversion.status;
    this.message = conversion.message;
    if (arg) {
        this.start = arg.start;
        this.end = arg.end;
    }
    else {
        this.start = 0;
        this.end = 0;
    }
    this.predictions = conversion.predictions;
}

function ConversionHint ( conversion , arg ) { this . status = conversion . status ; this . message = conversion . message ; if ( arg ) { this . start = arg . start ; this . end = arg . end ; } else { this . start = 0 ; this . end = 0 ; } this . predictions = conversion . predictions ; }

A Hint that arose as a result of a Conversion


function Argument(emitter, text, start, end, prefix, suffix) {
    this.emitter = emitter;
    this.setText(text);
    this.start = start;
    this.end = end;
    this.prefix = prefix;
    this.suffix = suffix;
}

function Argument ( emitter , text , start , end , prefix , suffix ) { this . emitter = emitter ; this . setText ( text ) ; this . start = start ; this . end = end ; this . prefix = prefix ; this . suffix = suffix ; }

We record where in the input string an argument comes so we can report errors
against those string positions.
We publish a 'change' event when-ever the text changes
@param emitter Arguments use something else to pass on change events.
Currently this will be the creating Requisition. This prevents dependency
loops and prevents us from needing to merge listener lists.
@param text The string (trimmed) that contains the argument
@param start The position of the text in the original input string
@param end See start
@param prefix Knowledge of quotation marks and whitespace used prior to the
text in the input string allows us to re-generate the original input from
the arguments.
@param suffix Any quotation marks and whitespace used after the text.
Whitespace is normally placed in the prefix to the succeeding argument, but
can be used here when this is the last argument.
@constructor

We record where in the input string an argument comes so we can report errors against those string positions . We publish a change event when - ever the text changes


function(text) {
        if (text == null) {
            throw new Error('Illegal text for Argument: ' + text);
        }
        var ev = { argument: this, oldText: this.text, text: text };
        this.text = text;
        this.emitter._dispatchEvent('argumentChange', ev);
    }

function
(
text
)
{
if
(
text
==
)
{
throw
new
Error
(
'Illegal text for Argument: '
+
text
)
;
}
var
ev
=
{
argument
:
this
,
oldText
:
this
.
text
,
text
:
text
}
;
this
.
text
=
text
;
this
.
emitter
.
_dispatchEvent
(
'argumentChange'
,
ev
)
;
}

See notes on events in Assignment. We might need to hook changes here
into a CliRequisition so they appear of the command line.

See notes on events in Assignment . We might need to hook changes here into a CliRequisition so they appear of the command line .


function(command, arg) {
        var docs = [];
        docs.push('<tt> > ');
        docs.push(command.name);
        if (command.params && command.params.length > 0) {
            command.params.forEach(function(param) {
                if (param.defaultValue === undefined) {
                    docs.push(' [' + param.name + ']');
                }
                else {
                    docs.push(' [' + param.name + ']');
                }
            }, this);
        }
        docs.push('</tt>
');

        docs.push(command.description ? command.description : '(No description)');
        docs.push('
');

        if (command.params && command.params.length > 0) {
            docs.push('
');
            command.params.forEach(function(param) {
                docs.push('
');
                docs.push('<tt>' + param.name + '</tt>: ');
                docs.push(param.description ? param.description : '(No description)');
                if (param.defaultValue === undefined) {
                    docs.push(' [Required]');
                }
                else if (param.defaultValue === null) {
                    docs.push(' [Optional]');
                }
                else {
                    docs.push(' [Default: ' + param.defaultValue + ']');
                }
                docs.push('
');
            }, this);
            docs.push('
');
        }

        return new Hint(Status.VALID, docs.join(''), arg);
    }

function
(
command
,
arg
)
{
var
docs
=
[
]
;
docs
.
push
(
'<tt> > '
)
;
docs
.
push
(
command
.
name
)
;
if
(
command
.
params
&&
command
.
params
.
length
>
0
)
{
command
.
params
.
forEach
(
function
(
param
)
{
if
(
param
.
defaultValue
===
undefined
)
{
docs
.
push
(
' ['
+
param
.
name
+
']'
)
;
}
else
{
docs
.
push
(
' ['
+
param
.
name
+
']'
)
;
}
}
,
this
)
;
}
docs
.
push
(
'</tt>
'
)
;
docs
.
push
(
command
.
description
command
.
description
:
'(No description)'
)
;
docs
.
push
(
'
'
)
;
if
(
command
.
params
&&
command
.
params
.
length
>
0
)
{
docs
.
push
(
'
'
)
;
command
.
params
.
forEach
(
function
(
param
)
{
docs
.
push
(
'
'
)
;
docs
.
push
(
'<tt>'
+
param
.
name
+
'</tt>: '
)
;
docs
.
push
(
param
.
description
param
.
description
:
'(No description)'
)
;
if
(
param
.
defaultValue
===
undefined
)
{
docs
.
push
(
' [Required]'
)
;
}
else
if
(
param
.
defaultValue
===
)
{
docs
.
push
(
' [Optional]'
)
;
}
else
{
docs
.
push
(
' [Default: '
+
param
.
defaultValue
+
']'
)
;
}
docs
.
push
(
'
'
)
;
}
,
this
)
;
docs
.
push
(
'
'
)
;
}
return
new
Hint
(
Status
.
VALID
,
docs
.
join
(
''
)
,
arg
)
;
}

Provide some documentation for a command.

Provide some documentation for a command .


function(assignment) {
        // This is all about re-creating Assignments
        if (assignment.param.name !== '__command') {
            return;
        }

        this._assignments = {};

        if (assignment.value) {
            assignment.value.params.forEach(function(param) {
                this._assignments[param.name] = new Assignment(param, this);
            }, this);
        }

        this.assignmentCount = Object.keys(this._assignments).length;
        this._dispatchEvent('commandChange', { command: assignment.value });
    }

When the command changes, we need to keep a bunch of stuff in sync

When the command changes we need to keep a bunch of stuff in sync


function(nameOrNumber) {
        var name = (typeof nameOrNumber === 'string') ?
            nameOrNumber :
            Object.keys(this._assignments)[nameOrNumber];
        return this._assignments[name];
    }

function ( nameOrNumber ) { var name = ( typeof nameOrNumber === 'string' ) ? nameOrNumber : Object . keys ( this . _assignments ) [ nameOrNumber ] ; return this . _assignments [ name ] ; }

Assignments have an order, so we need to store them in an array.
But we also need named access ...

Assignments have an order so we need to store them in an array . But we also need named access ...


function() {
        // TODO: work out when to clear this out for the plain Requisition case
        // this._hints = [];
        this.getAssignments(true).forEach(function(assignment) {
            this._hints.push(assignment.getHint());
        }, this);
        Hint.sort(this._hints);

        // We would like to put some initial help here, but for anyone but
        // a complete novice a 'type help' message is very annoying, so we
        // need to find a way to only display this message once, or for
        // until the user click a 'close' button or similar
        // TODO: Add special case for '' input
    }

Collect the statuses from the Assignments.
The hints returned are sorted by severity

Collect the statuses from the Assignments . The hints returned are sorted by severity


function() {
        var args = {};
        this.getAssignments().forEach(function(assignment) {
            args[assignment.param.name] = assignment.value;
        }, this);
        return args;
    }

function ( ) { var args = { } ; this . getAssignments ( ) . forEach ( function ( assignment ) { args [ assignment . param . name ] = assignment . value ; } , this ) ; return args ; }

Extract the names and values of all the assignments, and return as
an object.

Extract the names and values of all the assignments and return as an object .


function(includeCommand) {
        var args = [];
        if (includeCommand === true) {
            args.push(this.commandAssignment);
        }
        Object.keys(this._assignments).forEach(function(name) {
            args.push(this.getAssignment(name));
        }, this);
        return args;
    }

function ( includeCommand ) { var args = [ ] ; if ( includeCommand === true ) { args . push ( this . commandAssignment ) ; } Object . keys ( this . _assignments ) . forEach ( function ( name ) { args . push ( this . getAssignment ( name ) ) ; } , this ) ; return args ; }

Access the arguments as an array.
@param includeCommand By default only the parameter arguments are
returned unless (includeCommand === true), in which case the list is
prepended with commandAssignment.arg


function() {
        var line = [];
        line.push(this.commandAssignment.value.name);
        Object.keys(this._assignments).forEach(function(name) {
            var assignment = this._assignments[name];
            var type = assignment.param.type;
            // TODO: This will cause problems if there is a non-default value
            // after a default value. Also we need to decide when to use
            // named parameters in place of positional params. Both can wait.
            if (assignment.value !== assignment.param.defaultValue) {
                line.push(' ');
                line.push(type.stringify(assignment.value));
            }
        }, this);
        return line.join('');
    }

Extract a canonical version of the input


function CliView(cli, env) {
    cli.cliView = this;
    this.cli = cli;
    this.doc = document;
    this.win = dom.getParentWindow(this.doc);
    this.env = env;

    // TODO: we should have a better way to specify command lines???
    this.element = this.doc.getElementById('cockpitInput');
    if (!this.element) {
        // console.log('No element with an id of cockpit. Bailing on cli');
        return;
    }

    this.settings = env.settings;
    this.hintDirection = this.settings.getSetting('hintDirection');
    this.outputDirection = this.settings.getSetting('outputDirection');
    this.outputHeight = this.settings.getSetting('outputHeight');

    // If the requisition tells us something has changed, we use this to know
    // if we should ignore it
    this.isUpdating = false;

    this.createElements();
    this.update();
}

A class to handle the simplest UI implementation


function() {
        // Certain browsers have a bug such that scrollHeight is too small
        // when content does not fill the client area of the element
        var scrollHeight = Math.max(this.output.scrollHeight, this.output.clientHeight);
        this.output.scrollTop = scrollHeight - this.output.clientHeight;
    }

We need to see the output of the latest command entered


function() {
        var rect = this.element.getClientRects()[0];

        this.completer.style.top = rect.top + 'px';
        var height = rect.bottom - rect.top;
        this.completer.style.height = height + 'px';
        this.completer.style.lineHeight = height + 'px';
        this.completer.style.left = rect.left + 'px';
        var width = rect.right - rect.left;
        this.completer.style.width = width + 'px';

        if (this.hintDirection.get() === 'below') {
            this.hinter.style.top = rect.bottom + 'px';
            this.hinter.style.bottom = 'auto';
        }
        else {
            this.hinter.style.top = 'auto';
            this.hinter.style.bottom = (this.doc.documentElement.clientHeight - rect.top) + 'px';
        }
        this.hinter.style.left = (rect.left + 30) + 'px';
        this.hinter.style.maxWidth = (width - 110) + 'px';

        if (this.popupOutput) {
            if (this.outputDirection.get() === 'below') {
                this.output.style.top = rect.bottom + 'px';
                this.output.style.bottom = 'auto';
            }
            else {
                this.output.style.top = 'auto';
                this.output.style.bottom = (this.doc.documentElement.clientHeight - rect.top) + 'px';
            }
            this.output.style.left = rect.left + 'px';
            this.output.style.width = (width - 80) + 'px';
        }
    }

function ( ) { var rect = this . element . getClientRects ( ) [ 0 ] ; this . completer . style . top = rect . top + 'px' ; var height = rect . bottom - rect . top ; this . completer . style . height = height + 'px' ; this . completer . style . lineHeight = height + 'px' ; this . completer . style . left = rect . left + 'px' ; var width = rect . right - rect . left ; this . completer . style . width = width + 'px' ; if ( this . hintDirection . get ( ) === 'below' ) { this . hinter . style . top = rect . bottom + 'px' ; this . hinter . style . bottom = 'auto' ; } else { this . hinter . style . top = 'auto' ; this . hinter . style . bottom = ( this . doc . documentElement . clientHeight - rect . top ) + 'px' ; } this . hinter . style . left = ( rect . left + 30 ) + 'px' ; this . hinter . style . maxWidth = ( width - 110 ) + 'px' ; if ( this . popupOutput ) { if ( this . outputDirection . get ( ) === 'below' ) { this . output . style . top = rect . bottom + 'px' ; this . output . style . bottom = 'auto' ; } else { this . output . style . top = 'auto' ; this . output . style . bottom = ( this . doc . documentElement . clientHeight - rect . top ) + 'px' ; } this . output . style . left = rect . left + 'px' ; this . output . style . width = ( width - 80 ) + 'px' ; } }

To be called on window resize or any time we want to align the elements
with the input box.

To be called on window resize or any time we want to align the elements with the input box .


function(ev, hashId, keyCode) {
        var stopEvent;
        if (keyCode === keys.TAB ||
                keyCode === keys.UP ||
                keyCode === keys.DOWN) {
            stopEvent = true;
        } else if (hashId != 0 || keyCode != 0) {
            stopEvent = canon.execKeyCommand(this.env, 'cli', hashId, keyCode);
        }
        stopEvent && event.stopEvent(ev);
    }

function ( ev , hashId , keyCode ) { var stopEvent ; if ( keyCode === keys . TAB || keyCode === keys . UP || keyCode === keys . DOWN ) { stopEvent = true ; } else if ( hashId != 0 || keyCode != 0 ) { stopEvent = canon . execKeyCommand ( this . env , 'cli' , hashId , keyCode ) ; } stopEvent && event . stopEvent ( ev ) ; }

Ensure that TAB isn't handled by the browser

Ensure that TAB isn t handled by the browser


function(ev) {
        var handled;
        /*
        var handled = keyboardManager.processKeyEvent(ev, this, {
            isCommandLine: true, isKeyUp: true
        });
        */

        // RETURN does a special exec/highlight thing
        if (ev.keyCode === keys.RETURN) {
            var worst = this.cli.getWorstHint();
            // Deny RETURN unless the command might work
            if (worst.status === Status.VALID) {
                this.cli.exec();
                this.element.value = '';
            }
            else {
                // If we've denied RETURN because the command was not VALID,
                // select the part of the command line that is causing problems
                // TODO: if there are 2 errors are we picking the right one?
                dom.setSelectionStart(this.element, worst.start);
                dom.setSelectionEnd(this.element, worst.end);
            }
        }

        this.update();

        // Special actions which delegate to the assignment
        var current = this.cli.getAssignmentAt(dom.getSelectionStart(this.element));
        if (current) {
            // TAB does a special complete thing
            if (ev.keyCode === keys.TAB) {
                current.complete();
                this.update();
            }

            // UP/DOWN look for some history
            if (ev.keyCode === keys.UP) {
                current.increment();
                this.update();
            }
            if (ev.keyCode === keys.DOWN) {
                current.decrement();
                this.update();
            }
        }

        return handled;
    }


function() {
        this.isUpdating = true;
        var input = {
            typed: this.element.value,
            cursor: {
                start: dom.getSelectionStart(this.element),
                end: dom.getSelectionEnd(this.element.selectionEnd)
            }
        };
        this.cli.update(input);

        var display = this.cli.getAssignmentAt(input.cursor.start).getHint();

        // 1. Update the completer with prompt/error marker/TAB info
        dom.removeCssClass(this.completer, Status.VALID.toString());
        dom.removeCssClass(this.completer, Status.INCOMPLETE.toString());
        dom.removeCssClass(this.completer, Status.INVALID.toString());

        var completion = '> ';
        if (this.element.value.length > 0) {
            var scores = this.cli.getInputStatusMarkup();
            completion += this.markupStatusScore(scores);
        }

        // Display the "-> prediction" at the end of the completer
        if (this.element.value.length > 0 &&
                display.predictions && display.predictions.length > 0) {
            var tab = display.predictions[0];
            completion += '  ⇥ ' + (tab.name ? tab.name : tab);
        }
        this.completer.innerHTML = completion;
        dom.addCssClass(this.completer, this.cli.getWorstHint().status.toString());

        // 2. Update the hint element
        var hint = '';
        if (this.element.value.length !== 0) {
            hint += display.message;
            if (display.predictions && display.predictions.length > 0) {
                hint += ': [ ';
                display.predictions.forEach(function(prediction) {
                    hint += (prediction.name ? prediction.name : prediction);
                    hint += ' | ';
                }, this);
                hint = hint.replace(/\| $/, ']');
            }
        }

        this.hinter.innerHTML = hint;
        if (hint.length === 0) {
            dom.addCssClass(this.hinter, 'cptNoPopup');
        }
        else {
            dom.removeCssClass(this.hinter, 'cptNoPopup');
        }

        this.isUpdating = false;
    }

Actually parse the input and make sure we're all up to date

Actually parse the input and make sure we re all up to date


function(scores) {
        var completion = '';
        // Create mark-up
        var i = 0;
        var lastStatus = -1;
        while (true) {
            if (lastStatus !== scores[i]) {
                completion += '';
                lastStatus = scores[i];
            }
            completion += this.element.value[i];
            i++;
            if (i === this.element.value.length) {
                completion += '';
                break;
            }
            if (lastStatus !== scores[i]) {
                completion += '';
            }
        }

        return completion;
    }

function
(
scores
)
{
var
completion
=
''
;
// Create mark-up
var
i
=
0
;
var
lastStatus
=
1
;
while
(
true
)
{
if
(
lastStatus
!==
scores
[
i
]
)
{
completion
+=
''
;
lastStatus
=
scores
[
i
]
;
}
completion
+=
this
.
element
.
value
[
i
]
;
i
++
;
if
(
i
===
this
.
element
.
value
.
length
)
{
completion
+=
''
;
break
;
}
if
(
lastStatus
!==
scores
[
i
]
)
{
completion
+=
''
;
}
}
return
completion
;
}

Markup an array of Status values with spans


function(ev) {
        if (this.isUpdating) {
            return;
        }

        var prefix = this.element.value.substring(0, ev.argument.start);
        var suffix = this.element.value.substring(ev.argument.end);
        var insert = typeof ev.text === 'string' ? ev.text : ev.text.name;
        this.element.value = prefix + insert + suffix;
        // Fix the cursor.
        var insertEnd = (prefix + insert).length;
        this.element.selectionStart = insertEnd;
        this.element.selectionEnd = insertEnd;
    }

function
(
ev
)
{
if
(
this
.
isUpdating
)
{
return
;
}
var
prefix
=
this
.
element
.
value
.
substring
(
0
,
ev
.
argument
.
start
)
;
var
suffix
=
this
.
element
.
value
.
substring
(
ev
.
argument
.
end
)
;
var
insert
=
typeof
ev
.
text
===
'string'
ev
.
text
:
ev
.
text
.
name
;
this
.
element
.
value
=
prefix
+
insert
+
suffix
;
// Fix the cursor.
var
insertEnd
=
(
prefix
+
insert
)
.
length
;
this
.
element
.
selectionStart
=
insertEnd
;
this
.
element
.
selectionEnd
=
insertEnd
;
}

Update the input element to reflect the changed argument


function RequestView(request, cliView) {
    this.request = request;
    this.cliView = cliView;
    this.imageUrl = imageUrl;

    // Elements attached to this by the templater. For info only
    this.rowin = null;
    this.rowout = null;
    this.output = null;
    this.hide = null;
    this.show = null;
    this.duration = null;
    this.throb = null;

    new Templater().processNode(row.cloneNode(true), this);

    this.cliView.output.appendChild(this.rowin);
    this.cliView.output.appendChild(this.rowout);

    this.request.addEventListener('output', this.onRequestChange.bind(this));
}


function(ev) {
        this.cliView.cli.update({
            typed: this.request.typed,
            cursor: { start:0, end:0 }
        });
        this.cliView.cli.exec();
    }

function ( ev ) { this . cliView . cli . update ( { typed : this . request . typed , cursor : { start : 0 , end : 0 } } ) ; this . cliView . cli . exec ( ) ; }

A double click on an invocation line in the console executes the command


function(member, clone, ref) {
        ref.parentNode.insertBefore(clone, ref);
        data[paramName] = member;
        self.processNode(clone, data);
        delete data[paramName];
      }

function ( member , clone , ref ) { ref . parentNode . insertBefore ( clone , ref ) ; data [ paramName ] = member ; self . processNode ( clone , data ) ; delete data [ paramName ] ; }


function string(state) {
        return [
            {
            token : "string",
            regex : '".*?"'
        }, {
            token : "string", // multi line string start
            regex : '["].*$',
            next : state + "-qqstring"
        }, {
            token : "string",
            regex : "'.*?'"
        }, {
            token : "string", // multi line string start
            regex : "['].*$",
            next : state + "-qstring"
        }]
    }

function
string
(
state
)
{
return
[
{
token
:
"string"
,
regex
:
'".*?"'
}
,
{
token
:
"string"
,
// multi line string start
regex
:
'["].*$'
,
next
:
state
+
"-qqstring"
}
,
{
token
:
"string"
,
regex
:
"'.*?'"
}
,
{
token
:
"string"
,
// multi line string start
regex
:
"['].*$"
,
next
:
state
+
"-qstring"
}
]
}

regexp must not have capturing parentheses regexps are ordered -> the first match is used

regexp must not have capturing parentheses regexps are ordered - > the first match is used


function(data, hashId, key) {
        // If we pressed any command key but no other key, then ignore the input.
        // Otherwise "shift-" is added to the buffer, and later on "shift-g"
        // which results in "shift-shift-g" which doesn't make senese.
        if (hashId != 0 && (key == "" || String.fromCharCode(0))) {
            return null;
        }

        // Compute the current value of the keyboard input buffer.
        var r = this.$composeBuffer(data, hashId, key);
        var buffer = r.bufferToUse;
        var symbolicName = r.symbolicName;

        r = this.$find(data, buffer, symbolicName, hashId, key);
        if (DEBUG) {
            console.log("KeyboardStateMapper#match", buffer, symbolicName, r);
        }

        return r;
    }


function(model, req) {
    if(!model) return {}

    var fields = {}
        ,queryFieldSet

    if(req) {
        if(req.fieldSet) {
            queryFieldSet = {}
            try {
                queryFieldSet = JSON.parse(req.fieldSet)
            } catch(e) {queryFieldSet = null}
        } else if(req.urlparams && req.urlparams[1]) {
            queryFieldSet = {}
            var x = req.urlparams[1].split(',')
            for(var i=0;i<x.length;i++) queryFieldSet[x[i]] = 1
        }
    }

    for(var i in model.fields) if(model.fields[i] && model.fields[i].visable) {
        if(!queryFieldSet || queryFieldSet[model.fields[i].name]) fields[model.fields[i].name] = 1
    }
    return fields;
}

function ( model , req ) { if ( ! model ) return { } var fields = { } , queryFieldSet if ( req ) { if ( req . fieldSet ) { queryFieldSet = { } try { queryFieldSet = JSON . parse ( req . fieldSet ) } catch ( e ) { queryFieldSet = null } } else if ( req . urlparams && req . urlparams [ 1 ] ) { queryFieldSet = { } var x = req . urlparams [ 1 ] . split ( ',' ) for ( var i = 0 ; i < x . length ; i ++ ) queryFieldSet [ x [ i ] ] = 1 } } for ( var i in model . fields ) if ( model . fields [ i ] && model . fields [ i ] . visable ) { if ( ! queryFieldSet || queryFieldSet [ model . fields [ i ] . name ] ) fields [ model . fields [ i ] . name ] = 1 } return fields ; }


function(grid) {
        var me = this;

        if (grid.rendered) {
            me.grid = grid;
            grid.getView().on({
                render: function(v) {
                    me.view = v;
                    Ext.ux.dd.CellFieldDropZone.superclass.constructor.call(me, me.view.el);
                },
                single: true
            });
        } else {
            grid.on('render', me.init, me, {single: true});
        }
    }

function ( grid ) { var me = this ; if ( grid . rendered ) { me . grid = grid ; grid . getView ( ) . on ( { render : function ( v ) { me . view = v ; Ext . ux . dd . CellFieldDropZone . superclass . constructor . call ( me , me . view . el ) ; } , single : true } ) ; } else { grid . on ( 'render' , me . init , me , { single : true } ) ; } }

Call the DropZone constructor using the View's scrolling element only after the grid has been rendered.

Call the DropZone constructor using the View s scrolling element only after the grid has been rendered .


function(target, dd, e, dragData) {
        delete this.dropOK;
        if (!target) {
            return;
        }

//      Check that a field is being dragged.
        var f = dragData.field;
        if (!f) {
            return;
        }

//      Check whether the data type of the column being dropped on accepts the
//      dragged field type. If so, set dropOK flag, and highlight the target node.
        var type = target.record.fields.get(target.fieldName).type,
            types = Ext.data.Types;
        switch(type){
            case types.FLOAT:
            case types.INT:
                if (!f.isXType('numberfield')) {
                    return;
                }
                break;
            case types.DATE:
                if (!f.isXType('datefield')) {
                    return;
                }
                break;
            case types.BOOL:
                if (!f.isXType('checkbox')) {
                    return;
                }
        }
        this.dropOK = true;
        Ext.fly(target.node).addCls('x-drop-target-active');
    }

//      Check that a field is being dragged.

On Node enter, see if it is valid for us to drop the field on that type of column.

On Node enter see if it is valid for us to drop the field on that type of column .


function(target, dd, e, dragData) {
        if (this.dropOK) {
            var value = dragData.field.getValue();
            target.record.set(target.fieldName, value);
            this.onCellDrop(target.fieldName, value);
            return true;
        }
    }

function ( target , dd , e , dragData ) { if ( this . dropOK ) { var value = dragData . field . getValue ( ) ; target . record . set ( target . fieldName , value ) ; this . onCellDrop ( target . fieldName , value ) ; return true ; } }

Process the drop event if we have previously ascertained that a drop is OK.

Process the drop event if we have previously ascertained that a drop is OK .


function(cssText, id) {
            var ss,
                head = doc.getElementsByTagName("head")[0],
                styleEl = doc.createElement("style");

            styleEl.setAttribute("type", "text/css");
            if (id) {
               styleEl.setAttribute("id", id);
            }

            if (Ext.isIE) {
               head.appendChild(styleEl);
               ss = styleEl.styleSheet;
               ss.cssText = cssText;
            } else {
                try{
                    styleEl.appendChild(doc.createTextNode(cssText));
                } catch(e) {
                   styleEl.cssText = cssText;
                }
                head.appendChild(styleEl);
                ss = styleEl.styleSheet ? styleEl.styleSheet : (styleEl.sheet || doc.styleSheets[doc.styleSheets.length-1]);
            }
            CSS.cacheStyleSheet(ss);
            return ss;
        }

function ( cssText , id ) { var ss , head = doc . getElementsByTagName ( "head" ) [ 0 ] , styleEl = doc . createElement ( "style" ) ; styleEl . setAttribute ( "type" , "text/css" ) ; if ( id ) { styleEl . setAttribute ( "id" , id ) ; } if ( Ext . isIE ) { head . appendChild ( styleEl ) ; ss = styleEl . styleSheet ; ss . cssText = cssText ; } else { try { styleEl . appendChild ( doc . createTextNode ( cssText ) ) ; } catch ( e ) { styleEl . cssText = cssText ; } head . appendChild ( styleEl ) ; ss = styleEl . styleSheet ? styleEl . styleSheet : ( styleEl . sheet || doc . styleSheets [ doc . styleSheets . length - 1 ] ) ; } CSS . cacheStyleSheet ( ss ) ; return ss ; }

Creates a stylesheet from a text blob of rules.
These rules will be wrapped in a STYLE tag and appended to the HEAD of the document.
@param {String} cssText The text containing the css rules
@param {String} id An id to add to the stylesheet for later removal
@return {CSSStyleSheet}

Creates a stylesheet from a text blob of rules . These rules will be wrapped in a STYLE tag and appended to the HEAD of the document .


function(id) {
            var existing = doc.getElementById(id);
            if (existing) {
                existing.parentNode.removeChild(existing);
            }
        }

function ( id ) { var existing = doc . getElementById ( id ) ; if ( existing ) { existing . parentNode . removeChild ( existing ) ; } }

Removes a style or link tag by id
@param {String} id The id of the tag


function(id, url) {
            var ss;
            CSS.removeStyleSheet(id);
            ss = doc.createElement("link");
            ss.setAttribute("rel", "stylesheet");
            ss.setAttribute("type", "text/css");
            ss.setAttribute("id", id);
            ss.setAttribute("href", url);
            doc.getElementsByTagName("head")[0].appendChild(ss);
        }

function ( id , url ) { var ss ; CSS . removeStyleSheet ( id ) ; ss = doc . createElement ( "link" ) ; ss . setAttribute ( "rel" , "stylesheet" ) ; ss . setAttribute ( "type" , "text/css" ) ; ss . setAttribute ( "id" , id ) ; ss . setAttribute ( "href" , url ) ; doc . getElementsByTagName ( "head" ) [ 0 ] . appendChild ( ss ) ; }

Dynamically swaps an existing stylesheet reference for a new one
@param {String} id The id of an existing link tag to remove
@param {String} url The href of the new stylesheet to include


function(refreshCache) {
            var result = {},
                selector;

            if (rules === null || refreshCache) {
                CSS.refreshCache();
            }
            for (selector in rules) {
                result[selector] = rules[selector].cssRule;
            }
            return result;
        }

function ( refreshCache ) { var result = { } , selector ; if ( rules === null || refreshCache ) { CSS . refreshCache ( ) ; } for ( selector in rules ) { result [ selector ] = rules [ selector ] . cssRule ; } return result ; }

Gets all css rules for the document
@param {Boolean} refreshCache true to refresh the internal cache
@return {Object} An object (hash) of rules indexed by selector


function(styleSheet, selector, cssText) {
            var result,
                ruleSet = styleSheet.cssRules || styleSheet.rules,
                index = ruleSet.length;

            if (styleSheet.insertRule) {
                styleSheet.insertRule(selector + '{' + cssText + '}', index);
            } else {
                styleSheet.addRule(selector, cssText||' ');
            }
            CSS.cacheRule(result = ruleSet[index], styleSheet);
            return result;
        }

function
(
styleSheet
,
selector
,
cssText
)
{
var
result
,
ruleSet
=
styleSheet
.
cssRules
||
styleSheet
.
rules
,
index
=
ruleSet
.
length
;
if
(
styleSheet
.
insertRule
)
{
styleSheet
.
insertRule
(
selector
+
'{'
+
cssText
+
'}'
,
index
)
;
}
else
{
styleSheet
.
addRule
(
selector
,
cssText
||
' '
)
;
}
CSS
.
cacheRule
(
result
=
ruleSet
[
index
]
,
styleSheet
)
;
return
result
;
}

Creates a rule.
@param {CSSStyleSheet} styleSheet The StyleSheet to create the rule in as returned from {@link #createStyleSheet}.
@param {String} selector The selector to target the rule.
@param {String} property The cssText specification eg `"color:red;font-weight:bold;text-decoration:underline"`
@return {CSSStyleRule} The created rule


function cloneObject( obj ) {
  if ( obj === null || typeof obj !== 'object' ) {
    return obj;
  }
  var temp = obj.constructor( ); // give temp the original obj's constructor
  for ( var key in obj ) {
    temp[ key ] = cloneObject( obj[ key ] );
  }
  return temp;
}

recursive function to clone an object. If a non object parameter is passed in, that parameter is returned and no recursion occurs.

recursive function to clone an object . If a non object parameter is passed in that parameter is returned and no recursion occurs .


function(node, callback, scope, args) {
        var me = this,
            reader, dataRoot, data,
            callbackArgs;

        // Children are loaded go ahead with expand
        if (node.isLoaded()) {
            callbackArgs = [node.childNodes];
            if (args) {
                callbackArgs.push.apply(callbackArgs, args);
            }
            Ext.callback(callback, scope || node, callbackArgs);
        }
        // There are unloaded child nodes in the raw data because of the lazy configuration, load them then call back.
        else if (dataRoot = (data = (node.raw || node[node.persistenceProperty])[(reader = me.getProxy().getReader()).root])) {
            me.fillNode(node, reader.extractData(dataRoot));
            delete data[reader.root];
            callbackArgs = [node.childNodes];
            if (args) {
                callbackArgs.push.apply(callbackArgs, args);
            }
            Ext.callback(callback, scope || node, callbackArgs);
        }
        // The node is loading
        else if (node.isLoading()) {
            me.on('load', function() {
                callbackArgs = [node.childNodes];
                if (args) {
                    callbackArgs.push.apply(callbackArgs, args);
                }
                Ext.callback(callback, scope || node, callbackArgs);
            }, me, {single: true});
        }
        // Node needs loading
        else {
            me.read({
                node: node,
                callback: function() {
                    // Clear the callback, since if we're introducing a custom one,
                    // it may be re-used on reload
                    delete me.lastOptions.callback;
                    callbackArgs = [node.childNodes];
                    if (args) {
                        callbackArgs.push.apply(callbackArgs, args);
                    }
                    Ext.callback(callback, scope || node, callbackArgs);
                }
            });
        }
    }

Fired by the root node.

Called before a node is expanded.

This ensures that the child nodes are available before calling the passed callback.
@private
@param {Ext.data.NodeInterface} node The node being expanded.
@param {Function} callback The function to run after the expand finishes
@param {Object} scope The scope in which to run the callback function
@param {Array} args The extra args to pass to the callback after the new child nodes


function(node1, node2) {
        return node1[node1.persistenceProperty].index - node2[node2.persistenceProperty].index;
    }

function ( node1 , node2 ) { return node1 [ node1 . persistenceProperty ] . index - node2 [ node2 . persistenceProperty ] . index ; }

Sorter function for sorting records in index order
@private
@param {Ext.data.NodeInterface} node1
@param {Ext.data.NodeInterface} node2
@return {Number}


function init(tag, attrs, params) {  // {{{2
/**
 * View constructor
 *
 * @copyParams ose-html5.lib.wrap/constructor
 *
 * @method constructor
 */

  O.inherited(this)(tag || 'ul', attrs, params);

  this.updating = 0;

  this.hook();
  this.text('Loading ...');
}

Defines the layout which extends this view. Layouts are defined
in modules located in the "html5" subdirectory of the entry kind
directory.

@property layout
@type String
@abstract
 Public {{{1

Defines the layout which extends this view . Layouts are defined in modules located in the html5 subdirectory of the entry kind directory .


function(req, res, runMethod) {
    var form = new formidable.IncomingForm()
        ,files = {}
        ,fields = {}
        ,size = 0

    for(var i in formConfig) {
        form[i] = formConfig[i]
    }
    form.on('file', function(field, file) {
        size += file.size
        if(size > maxUploadSize) {
            return false;
        }
        if(files[field]) {
            if(!util.isArray(files[field])) files[field] = [files[field]]
            files[field].push(file)
        } else {
            files[field] = file;
        }
    })
    form.on('field', function(field, value) {
        if(fields[field]) {
            if(!util.isArray(fields[field])) fields[field] = [fields[field]]
            fields[field].push(value)
        } else {
            fields[field] = value;
        }
    })
    form.on('end', function() {
        fields.files = files
        runMethod(req, res, fields);
    });
    form.parse(req);
}

function ( req , res , runMethod ) { var form = new formidable . IncomingForm ( ) , files = { } , fields = { } , size = 0 for ( var i in formConfig ) { form [ i ] = formConfig [ i ] } form . on ( 'file' , function ( field , file ) { size += file . size if ( size > maxUploadSize ) { return false ; } if ( files [ field ] ) { if ( ! util . isArray ( files [ field ] ) ) files [ field ] = [ files [ field ] ] files [ field ] . push ( file ) } else { files [ field ] = file ; } } ) form . on ( 'field' , function ( field , value ) { if ( fields [ field ] ) { if ( ! util . isArray ( fields [ field ] ) ) fields [ field ] = [ fields [ field ] ] fields [ field ] . push ( value ) } else { fields [ field ] = value ; } } ) form . on ( 'end' , function ( ) { fields . files = files runMethod ( req , res , fields ) ; } ) ; form . parse ( req ) ; }

Create multipart parser to parse given request


function sortArgs(app, argv, options) {
  options = options || [];

  var first = options.first || [];
  var last = options.last || [];
  var cliKeys = [];

  if (app.cli && app.cli.keys) {
    cliKeys = app.cli.keys;
  }

  var keys = utils.union(first, cliKeys, Object.keys(argv));
  keys = utils.diff(keys, last);
  keys = utils.union(keys, last);

  var len = keys.length;
  var idx = -1;
  var res = {};

  while (++idx < len) {
    var key = keys[idx];
    if (argv.hasOwnProperty(key)) {
      res[key] = argv[key];
    }
  }
  return res;
}

function sortArgs ( app , argv , options ) { options = options || [ ] ; var first = options . first || [ ] ; var last = options . last || [ ] ; var cliKeys = [ ] ; if ( app . cli && app . cli . keys ) { cliKeys = app . cli . keys ; } var keys = utils . union ( first , cliKeys , Object . keys ( argv ) ) ; keys = utils . diff ( keys , last ) ; keys = utils . union ( keys , last ) ; var len = keys . length ; var idx = - 1 ; var res = { } ; while ( ++ idx < len ) { var key = keys [ idx ] ; if ( argv . hasOwnProperty ( key ) ) { res [ key ] = argv [ key ] ; } } return res ; }

Sort arguments so that `app.cli.process` executes commands
in the order specified.

@param {Object} `app` Application instance
@param {Object} `argv` The expanded argv object
@param {Object} `options`
@param {Array} `options.first` The keys to run first.
@param {Array} `options.last` The keys to run last.
@return {Object} Returns the `argv` object with sorted keys.

Sort arguments so that app . cli . process executes commands in the order specified .


function() {
        var me = this,
            picker = new Ext.tree.Panel({
                shrinkWrapDock: 2,
                store: me.store,
                floating: true,
                displayField: me.displayField,
                columns: me.columns,
                minHeight: me.minPickerHeight,
                maxHeight: me.maxPickerHeight,
                manageHeight: false,
                shadow: false,
                listeners: {
                    scope: me,
                    itemclick: me.onItemClick
                },
                viewConfig: {
                    listeners: {
                        scope: me,
                        render: me.onViewRender
                    }
                }
            }),
            view = picker.getView();

        if (Ext.isIE9 && Ext.isStrict) {
            // In IE9 strict mode, the tree view grows by the height of the horizontal scroll bar when the items are highlighted or unhighlighted.
            // Also when items are collapsed or expanded the height of the view is off. Forcing a repaint fixes the problem.
            view.on({
                scope: me,
                highlightitem: me.repaintPickerView,
                unhighlightitem: me.repaintPickerView,
                afteritemexpand: me.repaintPickerView,
                afteritemcollapse: me.repaintPickerView
            });
        }
        return picker;
    }

Creates and returns the tree panel to be used as this field's picker.

Creates and returns the tree panel to be used as this field s picker .


function() {
        var style = this.picker.getView().getEl().dom.style;

        // can't use Element.repaint because it contains a setTimeout, which results in a flicker effect
        style.display = style.display;
    }


function() {
        var me = this,
            picker;

        if (me.isExpanded) {
            picker = me.getPicker();
            if (me.matchFieldWidth) {
                // Auto the height (it will be constrained by max height)
                picker.setWidth(me.bodyEl.getWidth());
            }
            if (picker.isFloating()) {
                me.doAlign();
            }
        }
    }


function(e, el) {
        var key = e.getKey();

        if(key === e.ENTER || (key === e.TAB && this.selectOnTab)) {
            this.selectItem(this.picker.getSelectionModel().getSelection()[0]);
        }
    }

function ( e , el ) { var key = e . getKey ( ) ; if ( key === e . ENTER || ( key === e . TAB && this . selectOnTab ) ) { this . selectItem ( this . picker . getSelectionModel ( ) . getSelection ( ) [ 0 ] ) ; } }

Handles a keypress event on the picker element
@private
@param {Ext.EventObject} e
@param {HTMLElement} el


function(record) {
        var me = this;
        me.setValue(record.getId());
        me.picker.hide();
        me.inputEl.focus();
        me.fireEvent('select', me, record)

    }

function ( record ) { var me = this ; me . setValue ( record . getId ( ) ) ; me . picker . hide ( ) ; me . inputEl . focus ( ) ; me . fireEvent ( 'select' , me , record ) }

Changes the selection to a given record and closes the picker
@private
@param {Ext.data.Model} record


function() {
        var me = this,
            picker = me.picker,
            store = picker.store,
            value = me.value,
            node;

        if (value) {
            node = store.getNodeById(value);
        }

        if (!node) {
            node = store.getRootNode();
        }

        picker.selectPath(node.getPath());

        Ext.defer(function() {
            picker.getView().focus();
        }, 1);
    }

function ( ) { var me = this , picker = me . picker , store = picker . store , value = me . value , node ; if ( value ) { node = store . getNodeById ( value ) ; } if ( ! node ) { node = store . getRootNode ( ) ; } picker . selectPath ( node . getPath ( ) ) ; Ext . defer ( function ( ) { picker . getView ( ) . focus ( ) ; } , 1 ) ; }

Runs when the picker is expanded.  Selects the appropriate tree node based on the value of the input element,
and focuses the picker so that keyboard navigation will work.
@private

Runs when the picker is expanded . Selects the appropriate tree node based on the value of the input element and focuses the picker so that keyboard navigation will work .


function(value) {
        var me = this,
            record;

        me.value = value;

        if (me.store.loading) {
            // Called while the Store is loading. Ensure it is processed by the onLoad method.
            return me;
        }

        // try to find a record in the store that matches the value
        record = value ? me.store.getNodeById(value) : me.store.getRootNode();
        if (value === undefined) {
            record = me.store.getRootNode();
            me.value = record.getId();
        } else {
            record = me.store.getNodeById(value);
        }

        // set the raw value to the record's display field if a record was found
        me.setRawValue(record ? record.get(me.displayField) : '');

        return me;
    }

Sets the specified value into the field
@param {Mixed} value
@return {Ext.ux.TreePicker} this


function(key) {
    var pos = key.indexOf('[');
    if (pos === -1) return { type: 'string', val: key };
    return { type: 'array', val: key.substr(0, pos) };
  }

function ( key ) { var pos = key . indexOf ( '[' ) ; if ( pos === - 1 ) return { type : 'string' , val : key } ; return { type : 'array' , val : key . substr ( 0 , pos ) } ; }

for now we will only support string and arrays


function(direction) {
        var me = this;
        me.direction = direction ? direction.toUpperCase() : direction;
        me.updateSortFunction();
    }

function ( direction ) { var me = this ; me . direction = direction ? direction . toUpperCase ( ) : direction ; me . updateSortFunction ( ) ; }

Set the sorting direction for this sorter.
@param {String} direction The direction to sort in. Should be either 'ASC' or 'DESC'.

Set the sorting direction for this sorter .


function() {
        var me = this;
        me.direction = Ext.String.toggle(me.direction, "ASC", "DESC");
        me.updateSortFunction();
    }

function ( ) { var me = this ; me . direction = Ext . String . toggle ( me . direction , "ASC" , "DESC" ) ; me . updateSortFunction ( ) ; }

Toggles the sorting direction for this sorter.

Toggles the sorting direction for this sorter .


function(fn) {
        var me = this;
        fn = fn || me.sorterFn || me.defaultSorterFn;
        me.sort = me.createSortFunction(fn);
    }

function ( fn ) { var me = this ; fn = fn || me . sorterFn || me . defaultSorterFn ; me . sort = me . createSortFunction ( fn ) ; }

Update the sort function for this sorter.
@param {Function} [fn] A new sorter function for this sorter. If not specified it will use the default
sorting function.

Update the sort function for this sorter .


function Recurring(str) {

  var parts = str.split('/');

  if(str.charAt(0) != 'R' || parts.length != 3) {
    throw new Error('Invalid Recurring Date');
  }

  // We must have start and end. error if both aren't set
  if(!parts[1] || !parts[2]) {
    throw new Error('Recurring must have a start and end');
  }

  var countNum = parts[0].substr(1);

  // Validate count is a number if set
  if(countNum) {
    if(!(/^[0-9]+$/.test(countNum))) {
      throw new Error('Invalid recurrence count: not a number')
    }
    this.count = parseInt(countNum, 10);
    if(this.count < 0) throw new Error('Invalid recurrence count');
  }

  Range.call(this, parts[1]+'/'+parts[2]);

  // If we have a count, replace end with the actual end date or undefined.
  delete this.end;
  if(this.count) {
    this.end = this.getNth(this.count);
  }
}


function iopaStaticSend(context, path, opts) {
    opts = opts || {};

    return new Promise(function iopaStaticLoad(resolve, reject){
                       var root = opts.root ? normalize(pathResolve(opts.root)) : '';
                       var index = opts.index;
                       var maxage = opts.maxage || 0;
                       var hidden = opts.hidden || false;
                       var sync = opts.sync || false;
                       opts = null;

                       // normalize path
                       path = decode(path);
                       if (path =="")
                         path = "/";

                          var trailingSlash = '/' == path[path.length - 1];

                       if (-1 == path) return reject('failed to decode');

                       // null byte(s)
                       if (~path.indexOf('\0')) return reject('null bytes');

                       // index file support
                       if (index && trailingSlash) path += index;

                       // malicious path
                       if (!root && !isAbsolute(path)) return reject('relative paths require the .root option');
                       if (!root && ~path.indexOf('..')) return reject('malicious path');

                       // relative to root
                       path = normalize(join(root, path));

                       // out of bounds
                       if (root && 0 != path.indexOf(root)) return reject('malicious path');

                       // hidden file support, ignore
                       if (!hidden && leadingDot(path)) return resolve();
                       var stats;
                       try
                       {
                       stats = fs.statSync(path);
                       }
                       catch (err) {
                       return resolve(null);
                       }

                       if (stats.isDirectory())
                       {
                       return resolve(null);
                       }
                       var contentType =  mime.lookup(path) || 'application/octet-stream';

                       context.response.writeHead(200, {
                                               'Content-Type' : contentType,
                                               'Last-Modified' : stats.mtime.toUTCString(),
                                               'Content-Length': stats.size + '',
                                               'Cache-Control': 'max-age=' + (maxage / 1000 | 0)});

                       if (sync)
                       {
                       var bodyBuffer = fs.readFileSync(path);
                       context.response.end(bodyBuffer);
                       bodyBuffer = null;
                       context = null;
                       return resolve();
                       }
                       else
                       {

                       var stream = fs.createReadStream(path, { flags: 'r',
                                                        encoding: null,
                                                        autoClose: true
                                                        });

                       stream.on('error', function(err){
                                 console.log(err);
                                 stream = null;
                                 context = null;

                                 reject(err);

                                 });

                       stream.on('end', function(){
                                 context.response.end();
                                 stream = null;
                                 context = null;
                                 resolve();

                                 });

                       stream.pipe(context.response[IOPA.Body]);

                       return;
                       }
                       });
}

Send file at `path` with the
given `options` to the iopa context.

@param {Context} iopa context
@param {String} path
@param {Object} [opts]
@return {Function}
@api public

Send file at path with the given options to the iopa context .


function(ed) {
			var self = this, testKey = PLUGIN_NAME + '_test', testVal = "OK";

			self.key = PLUGIN_NAME + ed.id;

			// Loop though each storage engine type until we find one that works
			tinymce.each([
				function() {
					// Try HTML5 Local Storage
					if (localStorage) {
						localStorage.setItem(testKey, testVal);

						if (localStorage.getItem(testKey) === testVal) {
							localStorage.removeItem(testKey);

							return localStorage;
						}
					}
				},

				function() {
					// Try HTML5 Session Storage
					if (sessionStorage) {
						sessionStorage.setItem(testKey, testVal);

						if (sessionStorage.getItem(testKey) === testVal) {
							sessionStorage.removeItem(testKey);

							return sessionStorage;
						}
					}
				},

				function() {
					// Try IE userData
					if (tinymce.isIE) {
						ed.getElement().style.behavior = "url('#default#userData')";

						// Fake localStorage on old IE
						return {
							autoExpires : TRUE,

							setItem : function(key, value) {
								var userDataElement = ed.getElement();

								userDataElement.setAttribute(key, value);
								userDataElement.expires = self.getExpDate();

								try {
									userDataElement.save("TinyMCE");
								} catch (e) {
									// Ignore, saving might fail if "Userdata Persistence" is disabled in IE
								}
							},

							getItem : function(key) {
								var userDataElement = ed.getElement();

								try {
									userDataElement.load("TinyMCE");
									return userDataElement.getAttribute(key);
								} catch (e) {
									// Ignore, loading might fail if "Userdata Persistence" is disabled in IE
									return null;
								}
							},

							removeItem : function(key) {
								ed.getElement().removeAttribute(key);
							}
						};
					}
				},
			], function(setup) {
				// Try executing each function to find a suitable storage engine
				try {
					self.storage = setup();

					if (self.storage)
						return false;
				} catch (e) {
					// Ignore
				}
			});
		}

This method will setup the storage engine. If the browser has support for it.

@method setupStorage

This method will setup the storage engine . If the browser has support for it .


function() {
			var self = this, storage = self.storage, editor = self.editor, expires, content;

			// Is the contents dirty
			if (storage) {
				// If there is no existing key and the contents hasn't been changed since
				// it's original value then there is no point in saving a draft
				if (!storage.getItem(self.key) && !editor.isDirty())
					return;

				// Store contents if the contents if longer than the minlength of characters
				content = editor.getContent({draft: true});
				if (content.length > editor.settings.autosave_minlength) {
					expires = self.getExpDate();

					// Store expiration date if needed IE userData has auto expire built in
					if (!self.storage.autoExpires)
						self.storage.setItem(self.key + "_expires", expires);

					self.storage.setItem(self.key, content);
					self.onStoreDraft.dispatch(self, {
						expires : expires,
						content : content
					});
				}
			}
		}

This method will store the current contents in the the storage engine.

@method storeDraft

This method will store the current contents in the the storage engine .


function() {
			var self = this, storage = self.storage, content;

			if (storage) {
				content = storage.getItem(self.key);

				if (content) {
					self.editor.setContent(content);
					self.onRestoreDraft.dispatch(self, {
						content : content
					});
				}
			}
		}

function ( ) { var self = this , storage = self . storage , content ; if ( storage ) { content = storage . getItem ( self . key ) ; if ( content ) { self . editor . setContent ( content ) ; self . onRestoreDraft . dispatch ( self , { content : content } ) ; } } }

This method will restore the contents from the storage engine back to the editor.

@method restoreDraft

This method will restore the contents from the storage engine back to the editor .


function() {
			var self = this, storage = self.storage, key = self.key, content;

			if (storage) {
				// Get current contents and remove the existing draft
				content = storage.getItem(key);
				storage.removeItem(key);
				storage.removeItem(key + "_expires");

				// Dispatch remove event if we had any contents
				if (content) {
					self.onRemoveDraft.dispatch(self, {
						content : content
					});
				}
			}
		}

Removes the currently stored draft.

@method removeDraft


function(e) {
				var msg;

				tinymce.each(tinyMCE.editors, function(ed) {
					// Store a draft for each editor instance
					if (ed.plugins.autosave)
						ed.plugins.autosave.storeDraft();

					// Never ask in fullscreen mode
					if (ed.getParam("fullscreen_is_enabled"))
						return;

					// Setup a return message if the editor is dirty
					if (!msg && ed.isDirty() && ed.getParam("autosave_ask_before_unload"))
						msg = ed.getLang("autosave.unload_msg");
				});

				return msg;
			}

Internal unload handler will be called before the page is unloaded


function request(url){
  return new Promise(function(resolve, reject) {
    _request(url, function (error, response, body) {
      if(error) return reject(error);
      resolve({response, body})
    });
  });
}

function request ( url ) { return new Promise ( function ( resolve , reject ) { _request ( url , function ( error , response , body ) { if ( error ) return reject ( error ) ; resolve ( { response , body } ) } ) ; } ) ; }


function (grid, state) {
        var filters = {};
        this.filters.each(function (filter) {
            if (filter.active) {
                filters[filter.dataIndex] = filter.getValue();
            }
        });
        return (state.filters = filters);
    }

function ( grid , state ) { var filters = { } ; this . filters . each ( function ( filter ) { if ( filter . active ) { filters [ filter . dataIndex ] = filter . getValue ( ) ; } } ) ; return ( state . filters = filters ) ; }

Saves the state of all active filters
@param {Object} grid
@param {Object} state
@return {Boolean}


function(store) {
        var me = this;

        // Unbind from the old Store
        if (me.store && me.storeListeners) {
            me.store.un(me.storeListeners);
        }

        // Set up correct listeners
        if (store) {
            me.storeListeners = {
                scope: me
            };
            if (me.local) {
                me.storeListeners.load = me.onLoad;
            } else {
                me.storeListeners['before' + (store.buffered ? 'prefetch' : 'load')] = me.onBeforeLoad;
            }
            store.on(me.storeListeners);
        } else {
            delete me.storeListeners;
        }
        me.store = store;
    }

function
(
store
)
{
var
me
=
this
;
// Unbind from the old Store
if
(
me
.
store
&&
me
.
storeListeners
)
{
me
.
store
.
un
(
me
.
storeListeners
)
;
}
// Set up correct listeners
if
(
store
)
{
me
.
storeListeners
=
{
scope
:
me
}
;
if
(
me
.
local
)
{
me
.
storeListeners
.
load
=
me
.
onLoad
;
}
else
{
me
.
storeListeners
[
'before'
+
(
store
.
buffered
'prefetch'
:
'load'
)
]
=
me
.
onBeforeLoad
;
}
store
.
on
(
me
.
storeListeners
)
;
}
else
{
delete
me
.
storeListeners
;
}
me
.
store
=
store
;
}

Changes the data store bound to this view and refreshes it.
@param {Ext.data.Store} store The store to bind to this view

Changes the data store bound to this view and refreshes it .


function () {
        var me = this,
            headerCt = me.view.headerCt;
        if (headerCt) {
            headerCt.items.each(function(header) {
                var filter = me.getFilter(header.dataIndex);
                header[filter && filter.active ? 'addCls' : 'removeCls'](me.filterCls);
            });
        }
    }

function ( ) { var me = this , headerCt = me . view . headerCt ; if ( headerCt ) { headerCt . items . each ( function ( header ) { var filter = me . getFilter ( header . dataIndex ) ; header [ filter && filter . active ? 'addCls' : 'removeCls' ] ( me . filterCls ) ; } ) ; } }

Update the styles for the header row based on the active filters


function () {
        var f = [], len, i;
        this.filters.each(function (filter) {
            if (filter.active) {
                f.push(filter);
            }
        });

        len = f.length;
        return function (record) {
            for (i = 0; i < len; i++) {
                if (!f[i].validateRecord(record)) {
                    return false;
                }
            }
            return true;
        };
    }

function ( ) { var f = [ ] , len , i ; this . filters . each ( function ( filter ) { if ( filter . active ) { f . push ( filter ) ; } } ) ; len = f . length ; return function ( record ) { for ( i = 0 ; i < len ; i ++ ) { if ( ! f [ i ] . validateRecord ( record ) ) { return false ; } } return true ; } ; }

Method factory that generates a record validator for the filters active at the time
of invokation.
@private

Method factory that generates a record validator for the filters active at the time of invokation .


function (config) {
        var me = this,
            columns = me.getGridPanel().columns,
            i, columnsLength, column, filtersLength, filter;

        for (i = 0, columnsLength = columns.length; i < columnsLength; i++) {
            column = columns[i];
            if (column.dataIndex === config.dataIndex) {
                column.filter = config;
            }
        }

        if (me.view.headerCt.menu) {
            me.createFilters();
        } else {
            // Call getMenu() to ensure the menu is created, and so, also are the filters. We cannot call
            // createFilters() withouth having a menu because it will cause in a recursion to applyState()
            // that ends up to clear all the filter values. This is likely to happen when we reorder a column
            // and then add a new filter before the menu is recreated.
            me.view.headerCt.getMenu();
        }

        for (i = 0, filtersLength = me.filters.items.length; i < filtersLength; i++) {
            filter = me.filters.items[i];
            if (filter.dataIndex === config.dataIndex) {
                return filter;
            }
        }
    }

Adds a filter to the collection and observes it for state change.
@param {Object/Ext.ux.grid.filter.Filter} config A filter configuration or a filter object.
@return {Ext.ux.grid.filter.Filter} The existing or newly created filter object.

Adds a filter to the collection and observes it for state change .


function (filters) {
        if (filters) {
            var me = this,
                i, filtersLength;
            for (i = 0, filtersLength = filters.length; i < filtersLength; i++) {
                me.addFilter(filters[i]);
            }
        }
    }

function ( filters ) { if ( filters ) { var me = this , i , filtersLength ; for ( i = 0 , filtersLength = filters . length ; i < filtersLength ; i ++ ) { me . addFilter ( filters [ i ] ) ; } } }

Adds filters to the collection.
@param {Array} filters An Array of filter configuration objects.


function () {
        var items = this.getFilterItems(),
            filters = [],
            n, nlen, item, d, i, len;

        for (n = 0, nlen = items.length; n < nlen; n++) {
            item = items[n];
            if (item.active) {
                d = [].concat(item.serialize());
                for (i = 0, len = d.length; i < len; i++) {
                    filters.push({
                        field: item.dataIndex,
                        data: d[i]
                    });
                }
            }
        }
        return filters;
    }

function ( ) { var items = this . getFilterItems ( ) , filters = [ ] , n , nlen , item , d , i , len ; for ( n = 0 , nlen = items . length ; n < nlen ; n ++ ) { item = items [ n ] ; if ( item . active ) { d = [ ] . concat ( item . serialize ( ) ) ; for ( i = 0 , len = d . length ; i < len ; i ++ ) { filters . push ( { field : item . dataIndex , data : d [ i ] } ) ; } } } return filters ; }

Returns an Array of the currently active filters.
@return {Array} filters Array of the currently active filters.

Returns an Array of the currently active filters .


function (p) {
        // if encoding just delete the property
        if (this.encode) {
            delete p[this.paramPrefix];
        // otherwise scrub the object of filter data
        } else {
            var regex, key;
            regex = new RegExp('^' + this.paramPrefix + '\[[0-9]+\]');
            for (key in p) {
                if (regex.test(key)) {
                    delete p[key];
                }
            }
        }
    }

Removes filter related query parameters from the provided object.
@param {Object} p Query parameters that may contain filter related fields.

Removes filter related query parameters from the provided object .


function(record, columnHeader) {
        var me = this,
            grid = me.editingPlugin.grid,
            store = grid.store,
            view = grid.getView(),
            context = me.context = Ext.apply(me.editingPlugin.context, {
                view: view,
                store: store
            });

        if (!me.rendered) {
            me.render(view.el);
        }
        // make sure our row is selected before editing
        context.grid.getSelectionModel().select(record);

        // Reload the record data
        me.loadRecord(record);

        if (!me.isVisible()) {
            me.show();
        }
        me.reposition({
            callback: this.focusContextCell
        });
    }

Start editing the specified grid at the specified position.
@param {Ext.data.Model} record The Store data record which backs the row to be edited.
@param {Ext.data.Model} columnHeader The Column object defining the column to be edited.

Start editing the specified grid at the specified position .


function Approximate() {

  if(arguments.length > 0) {

    if(arguments[0].length < 1 || arguments[0].charAt(0) != 'A') {
      throw new Error('Invalid Approximate Date');
    }
    try {
      Simple.call(this, arguments[0].substr(1));
    } catch(e) {
      throw new Error(e.message+' in Approximate Date');
    }
  } else {
    Simple.call(this);
  }
}

function
Approximate
(
)
{
if
(
arguments
.
length
>
0
)
{
if
(
arguments
[
0
]
.
length
<
1
||
arguments
[
0
]
.
charAt
(
0
)
!=
'A'
)
{
throw
new
Error
(
'Invalid Approximate Date'
)
;
}
try
{
Simple
.
call
(
this
,
arguments
[
0
]
.
substr
(
1
)
)
;
}
catch
(
e
)
{
throw
new
Error
(
e
.
message
+
' in Approximate Date'
)
;
}
}
else
{
Simple
.
call
(
this
)
;
}
}

An approximate GedcomX Date.
Inherits from Simple.

An approximate GedcomX Date . Inherits from Simple .