function(e) {
	        var stack = (e.stack + '\n').replace(/^\S[^\(]+?[\n$]/gm, '').
	          replace(/^\s+(at eval )?at\s+/gm, '').
	          replace(/^([^\(]+?)([\n$])/gm, '{anonymous}()@$1$2').
	          replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}()@$1').split('\n');
	        stack.pop();
	        return stack;
	    }

function
(
e
)
{
var
stack
=
(
e
.
stack
+
'\n'
)
.
replace
(
/
^\S[^\(]+?[\n$]
/
gm
,
''
)
.
replace
(
/
^\s+(at eval )?at\s+
/
gm
,
''
)
.
replace
(
/
^([^\(]+?)([\n$])
/
gm
,
'{anonymous}()@$1$2'
)
.
replace
(
/
^Object.<anonymous>\s*\(([^\)]+)\)
/
gm
,
'{anonymous}()@$1'
)
.
split
(
'\n'
)
;
stack
.
pop
(
)
;
return
stack
;
}

Given an Error object, return a formatted Array based on Chrome's stack string.

@param e - Error object to inspect
@return Array<String> of function calls, files and line numbers

Given an Error object return a formatted Array based on Chrome s stack string .


function(e) {
	        var lineRE = /^.*at (\w+) \(([^\)]+)\)$/gm;
	        return e.stack.replace(/at Anonymous function /gm, '{anonymous}()@')
	            .replace(/^(?=\w+Error\:).*$\n/m, '')
	            .replace(lineRE, '$1@$2')
	            .split('\n');
	    }

function
(
e
)
{
var
lineRE
=
/
^.*at (\w+) \(([^\)]+)\)$
/
gm
;
return
e
.
stack
.
replace
(
/
at Anonymous function
/
gm
,
'{anonymous}()@'
)
.
replace
(
/
^(?=\w+Error\:).*$\n
/
m
,
''
)
.
replace
(
lineRE
,
'$1@$2'
)
.
split
(
'\n'
)
;
}

Given an Error object, return a formatted Array based on IE's stack string.

@param e - Error object to inspect
@return Array<String> of function calls, files and line numbers

Given an Error object return a formatted Array based on IE s stack string .


function(e) {
	        // "  Line 43 of linked script file://localhost/G:/js/stacktrace.js\n"
	        // "  Line 7 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n"
	        var ANON = '{anonymous}', lineRE = /Line (\d+).*script (?:in )?(\S+)/i;
	        var lines = e.message.split('\n'), result = [];

	        for (var i = 2, len = lines.length; i < len; i += 2) {
	            var match = lineRE.exec(lines[i]);
	            if (match) {
	                result.push(ANON + '()@' + match[2] + ':' + match[1] + ' -- ' + lines[i + 1].replace(/^\s+/, ''));
	            }
	        }

	        return result;
	    }


function(url) {
	        // TODO reuse source from script tags?
	        if (!(url in this.sourceCache)) {
	            this.sourceCache[url] = this.ajax(url).split('\n');
	        }
	        return this.sourceCache[url];
	    }

function
(
url
)
{
// TODO reuse source from script tags?
if
(
!
(
url
in
this
.
sourceCache
)
)
{
this
.
sourceCache
[
url
]
=
this
.
ajax
(
url
)
.
split
(
'\n'
)
;
}
return
this
.
sourceCache
[
url
]
;
}

Get source code from given URL if in the same domain.

@param url <String> JS source URL
@return <Array> Array of source code lines

Get source code from given URL if in the same domain .


function recordAndTriggerHandlers(type, eventData) {
            this.history.push({type:type, data: eventData})
            this.handlers[type].forEach(function(handlerInfo) {
                try {
                    handlerInfo.handler.call(undefined, eventData)
                } catch(e) {

                    // throw error asynchronously because these error should be separate from the test exceptions
                    var throwErrorFn = options.throwAsyncException

                    if(handlerInfo.domain) {
                        throwErrorFn = handlerInfo.domain.bind(throwErrorFn)    // this domain bind is needed because emit is done inside deadunit's test domain, which isn't where we want to put errors caused by the event handlers
                    }

                    throwErrorFn(e)
                }
            })
        }


function(name, mainTester, parentTester) {
        if(!mainTester) mainTester = this

        this.id = groupid()
        this.mainTester = mainTester // the mainTester is used to easily figure out if the test results have been accessed (so early accesses can be detected)
        this.parentTester = parentTester // used to reset timeouts
        this.name = name

        this.doneTests = 0
        this.doneAsserts = 0
        this.runningTests = 0 // the number of subtests created synchronously
        this.doneCalled = false
        this.doSourcemappery = true // whether to do source mapping, if possible, within this test

        this.complete = new Future // resolved when done
    }

the prototype of objects used to write tests and contain the results of tests


function remove(array, item) {
        console.log("attempting to remove "+item)
        var index = array.indexOf(item)
        if(index !== -1)
            array.splice(index, 1) // no longer throwing Error("Item doesn't exist to remove") if there's nothing to remove - in the case that mainTester.timeouts gets set back to [] (when done), it won't be there

    }


function assert(that, success, actualValue, expectedValue, type, functionName/*="ok"*/, lineInfo/*=dynamic*/, stackIncrease/*=0*/) {
        if(!stackIncrease) stackIncrease = 1
        if(!functionName) functionName = "ok"
        if(!lineInfo)
            var lineInfoFuture = getLineInformation(functionName, stackIncrease, that.doSourcemappery, that.warningHandler)
        else
            var lineInfoFuture = Future(lineInfo)

        // reste timeouts up the chain
        var cur = that
        while(cur !== undefined) {
            setTesterTimeout(cur)
            cur = cur.parentTester
        }

        var emitData = lineInfoFuture.then(function(lineInfo) {
            var result = lineInfo
            result.type = 'assert'
            if(type !=='count') result.success = success === true

            if(actualValue !== undefined)     result.actual = actualValue
            if(expectedValue !== undefined)   result.expected = expectedValue

            result.parent = that.id
            result.time = now()

           return Future(result)
        })

        return that.manager.emit(type, emitData)
    }

function
assert
(
that
,
success
,
actualValue
,
expectedValue
,
type
,
functionName
/*="ok"*/
,
lineInfo
/*=dynamic*/
,
stackIncrease
/*=0*/
)
{
if
(
!
stackIncrease
)
stackIncrease
=
1
if
(
!
functionName
)
functionName
=
"ok"
if
(
!
lineInfo
)
var
lineInfoFuture
=
getLineInformation
(
functionName
,
stackIncrease
,
that
.
doSourcemappery
,
that
.
warningHandler
)
else
var
lineInfoFuture
=
Future
(
lineInfo
)
// reste timeouts up the chain
var
cur
=
that
while
(
cur
!==
undefined
)
{
setTesterTimeout
(
cur
)
cur
=
cur
.
parentTester
}
var
emitData
=
lineInfoFuture
.
then
(
function
(
lineInfo
)
{
var
result
=
lineInfo
result
.
type
=
'assert'
if
(
type
!==
'count'
)
result
.
success
=
success
===
true
if
(
actualValue
!==
undefined
)
result
.
actual
=
actualValue
if
(
expectedValue
!==
undefined
)
result
.
expected
=
expectedValue
result
.
parent
=
that
.
id
result
.
time
=
now
(
)
return
Future
(
result
)
}
)
return
that
.
manager
.
emit
(
type
,
emitData
)
}


function getMappedSourceInfo(sourceMapConsumer, originalFilePath, originalLine, originalColumn, originalFunctionName) {
        var sourceMapInfo = sourceMapConsumer.originalPositionFor({line:originalLine, column:originalColumn||0})       // the 0 is for browsers (like firefox) that don't output column numbers
        var line = sourceMapInfo.line
        var column = sourceMapInfo.column
        var fn = sourceMapInfo.name

        if(sourceMapInfo.source !== null) {
            var relative = isRelative(sourceMapInfo.source)

            /* I don't think this is needed any longer, and probably isn't correct - this was working around an issue in webpack: See https://github.com/webpack/webpack/issues/559 and https://github.com/webpack/webpack/issues/238
            if(sourceMapConsumer.sourceRoot !== null) {
                sourceMapInfo.source = sourceMapInfo.source.replace(sourceMapConsumer.sourceRoot, '') // remove sourceRoot
            }*/

            if(relative) {
                var file = Url.resolve(originalFilePath, path.basename(sourceMapInfo.source))
            } else {
                var file = sourceMapInfo.source
            }

            var originalFile = true
        } else {
            var file = originalFilePath
            var originalFile = false
        }

        if(fn === null || !originalFile) {
            fn = originalFunctionName
        }
        if(line === null || !originalFile) {
            line = originalLine
            column = originalColumn
        }
        if(column === null) {
            column = undefined
        }

        if(file != undefined && sourceMapConsumer.sourcesContent != undefined) { // intentional single !=
            var index = sourceMapConsumer.sources.indexOf(file)
            var sourceLines = sourceMapConsumer.sourcesContent[index]
            if(sourceLines !== undefined) sourceLines = sourceLines.split('\n')
        }

        return {
            file: file,
            function: fn,
            line: line,
            column: column,
            usingOriginalFile: originalFile,
            sourceLines: sourceLines
        }
    }

returns the line, column, and filename mapped from a source map appropriately handles cases where some information is missing

returns the line column and filename mapped from a source map appropriately handles cases where some information is missing


function getFunctionCallLines(sourcesContent, filePath, functionName, lineNumber, multiLineSearch, warningHandler) {
        if(sourcesContent !==  undefined) {
            var source = Future(sourcesContent)
        } else {
            var source = options.getScriptSourceLines(filePath)
        }
        return source.catch(function(e) {
            warningHandler(e)
            return Future(undefined)

        }).then(function(fileLines) {
            if(fileLines !== undefined) {

                var startLine = findStartLine(fileLines, functionName, lineNumber)
                if(startLine === 'lineOfCodeNotFound') {
                    return Future("<line of code not found (possibly an error?)> ")

                } else if(startLine !== 'sourceNotAvailable') {
                    if(multiLineSearch) {
                        return Future(findFullSourceLine(fileLines, startLine))
                    } else {
                        return Future(fileLines[startLine].trim())
                    }
                }
            }
            // else
            return Future("<source not available>")

        })
    }

gets the actual lines of the call if multiLineSearch is true, it finds

gets the actual lines of the call if multiLineSearch is true it finds


function mapException(exception, warningHandler) {
        try {
            if(exception instanceof Error) {
                var stacktrace;
                return options.getExceptionInfo(exception).then(function(trace){
                    stacktrace = trace

                    var smcFutures = []
                    for(var n=0; n<trace.length; n++) {
                        if(trace[n].file !== undefined) {
                            smcFutures.push(getSourceMapConsumer(trace[n].file, warningHandler))
                        } else {
                            smcFutures.push(Future(undefined))
                        }
                    }

                    return Future.all(smcFutures)
                }).then(function(sourceMapConsumers) {
                    var CustomMappedException = proto(MappedException, function() {
                        // set the name so it looks like the original exception when printed
                        // this subclasses MappedException so that name won't be an own-property
                        this.name = exception.name
                    })

                    try {
                        throw CustomMappedException(exception, stacktrace, sourceMapConsumers)  // IE doesn't give exceptions stack traces unless they're actually thrown
                    } catch(mappedExcetion) {
                        return Future(mappedExcetion)
                    }
                })
            } else {
                return Future(exception)
            }
        } catch(e) {
            var errorFuture = new Future
            errorFuture.throw(e)
            return errorFuture
        }
    }

takes an exception and returns a future exception that has a stacktrace with sourcemapped tracelines


function YearMonthForm({ date, localeUtils, onChange, fromMonth, toMonth }) {
    const months = localeUtils.getMonths();

    const years = [];
    for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) {
        years.push(i);
    }

    const handleChange = function handleChange(e) {
        const { year, month } = e.target.form;
        onChange(new Date(year.value, month.value));
    };

    return (
        <form className="DayPicker-Caption">
            <select name="month" onChange={handleChange} value={date.getMonth()}>
                {months.map((month, i) => <option key={i} value={i}>{month}</option>)}
            </select>
            <select name="year" onChange={handleChange} value={date.getFullYear()}>
                {years.map((year, i) =>
                    <option key={i} value={year}>
                        {year}
                    </option>
                )}
            </select>
        </form>
    );
}

function YearMonthForm ( { date , localeUtils , onChange , fromMonth , toMonth } ) { const months = localeUtils . getMonths ( ) ; const years = [ ] ; for ( let i = fromMonth . getFullYear ( ) ; i <= toMonth . getFullYear ( ) ; i += 1 ) { years . push ( i ) ; } const handleChange = function handleChange ( e ) { const { year , month } = e . target . form ; onChange ( new Date ( year . value , month . value ) ) ; } ; return ( < form className = "DayPicker-Caption" > < select name = "month" onChange = { handleChange } value = { date . getMonth ( ) } > { months . map ( ( month , i ) => < option key = { i } value = { i } > { month } < / option > ) } < / select > < select name = "year" onChange = { handleChange } value = { date . getFullYear ( ) } > { years . map ( ( year , i ) => < option key = { i } value = { year } > { year } < / option > ) } < / select > < / form > ) ; }

Component will receive date, locale and localeUtils props

Component will receive date locale and localeUtils props


function Floodgate (opts) {
  if (!(this instanceof Floodgate)) return new Floodgate(opts);

  opts = opts || {};
  Transform.call(this, opts);
  this._interval = opts.interval || 0;
}

function Floodgate ( opts ) { if ( ! ( this instanceof Floodgate ) ) return new Floodgate ( opts ) ; opts = opts || { } ; Transform . call ( this , opts ) ; this . _interval = opts . interval || 0 ; }

Creates a transform stream that will delay passing values through according to the given interval.

Note:
Passing and interval of 0 is useful in order to keep any streams in your pipe chain from blocking the
event loop.

@name Floodgate
@function
@param opts {Object} typical TransformStream options (like highWaterMark) and one additional:
- interval: the interval at which to time out passing through values
@return {TransformStream} stream that can be added to a pipe in order to delay values coming through

Creates a transform stream that will delay passing values through according to the given interval .


function remove(obj, path, i) {
	i = i || 0

	var key = path[i],
		last = i === path.length - 1

	if (!obj || typeof obj !== 'object') {
		throw new Error('Can\'t remove key ' + key + ' from non-object')
	}

	if (Array.isArray(obj)) {
		if (typeof key !== 'number') {
			obj.forEach(function (each) {
				remove(each, path, i)
			})
		} else if (key >= 0 && key < obj.length) {
			if (last) {
				obj.splice(key, 1)
			} else {
				remove(obj[key], path, i + 1)
			}
		} else {
			throw new Error('Can\'t remove index ' + key + ' from an array with ' + obj.length + ' elements')
		}
	} else {
		if (typeof key !== 'string') {
			throw new Error('Can\'t remove the numeric key ' + key + ' from an object')
		} else if (key in obj) {
			if (last) {
				delete obj[key]
			} else {
				remove(obj[key], path, i + 1)
			}
		} else {
			throw new Error('Can\'t remove key ' + key + ' from the object')
		}
	}
}

function
remove
(
obj
,
path
,
i
)
{
i
=
i
||
0
var
key
=
path
[
i
]
,
last
=
i
===
path
.
length
1
if
(
!
obj
||
typeof
obj
!==
'object'
)
{
throw
new
Error
(
'Can\'t remove key '
+
key
+
' from non-object'
)
}
if
(
Array
.
isArray
(
obj
)
)
{
if
(
typeof
key
!==
'number'
)
{
obj
.
forEach
(
function
(
each
)
{
remove
(
each
,
path
,
i
)
}
)
}
else
if
(
key
>=
0
&&
key
<
obj
.
length
)
{
if
(
last
)
{
obj
.
splice
(
key
,
1
)
}
else
{
remove
(
obj
[
key
]
,
path
,
i
+
1
)
}
}
else
{
throw
new
Error
(
'Can\'t remove index '
+
key
+
' from an array with '
+
obj
.
length
+
' elements'
)
}
}
else
{
if
(
typeof
key
!==
'string'
)
{
throw
new
Error
(
'Can\'t remove the numeric key '
+
key
+
' from an object'
)
}
else
if
(
key
in
obj
)
{
if
(
last
)
{
delete
obj
[
key
]
}
else
{
remove
(
obj
[
key
]
,
path
,
i
+
1
)
}
}
else
{
throw
new
Error
(
'Can\'t remove key '
+
key
+
' from the object'
)
}
}
}

Remove a path from an object
@param {Object} obj
@param {Array<string|number>} path
@param {number} [i]
@throws {Error}
@private


function(uuid_or_name, cb) {
        if (_.isObject(uuid_or_name)) { return cb(new Error('parameter must be a uuid or name')); }
        var self = this;
        client.getEntity({ type: self._usergrid.type, uuid: uuid_or_name }, translateSDKCallback(function (err, entity) {
          if (err) { return cb(err); }
          cb(null, wrap(self, entity));
        }));
      }

function
(
uuid_or_name
,
cb
)
{
if
(
_
.
isObject
(
uuid_or_name
)
)
{
return
cb
(
new
Error
(
'parameter must be a uuid or name'
)
)
;
}
var
self
=
this
;
client
.
getEntity
(
{
type
:
self
.
_usergrid
.
type
,
uuid
:
uuid_or_name
}
,
translateSDKCallback
(
function
(
err
,
entity
)
{
if
(
err
)
{
return
cb
(
err
)
;
}
cb
(
,
wrap
(
self
,
entity
)
)
;
}
)
)
;
}

retrieve a single entity by uuid or unique name


function(criteria, limit, cb) {
        if (_.isFunction(limit)) { cb = limit; limit = undefined; }
        var self = this;
        var query = buildQuery(criteria, limit);
        client.createCollection(options(self, query), translateSDKCallback(function (err, collection) {
          if (err) { return cb(err); }
          cb(null, wrapCollection(self, collection));
        }));
      }

function ( criteria , limit , cb ) { if ( _ . isFunction ( limit ) ) { cb = limit ; limit = undefined ; } var self = this ; var query = buildQuery ( criteria , limit ) ; client . createCollection ( options ( self , query ) , translateSDKCallback ( function ( err , collection ) { if ( err ) { return cb ( err ) ; } cb ( null , wrapCollection ( self , collection ) ) ; } ) ) ; }

query with attributes - returns an array of entities limit is optional


function(criteria, cb) {
        var self = this;
        this.first(criteria, function(err, entity) {
          if (err) { return cb(err); }
          if (entity) {
            cb(null, entity);
          } else {
            self.create(criteria, cb);
          }
        });
      }

function ( criteria , cb ) { var self = this ; this . first ( criteria , function ( err , entity ) { if ( err ) { return cb ( err ) ; } if ( entity ) { cb ( null , entity ) ; } else { self . create ( criteria , cb ) ; } } ) ; }

searches for a record with criteria, creates it with criteria if not found

searches for a record with criteria creates it with criteria if not found


function options(Class, hash) {
  var opts;
  var type = { type: Class._usergrid.type };
  if (hash) {
    opts = _.assign({}, hash, type);
  } else {
    opts = type;
  }
  return opts;
}

function options ( Class , hash ) { var opts ; var type = { type : Class . _usergrid . type } ; if ( hash ) { opts = _ . assign ( { } , hash , type ) ; } else { opts = type ; } return opts ; }

utility methods clones hash and adds type for usergrid context


function define(Class, constructor, type) {
  if (!client) { throw new Error('Usergrid not configured'); }
  if (typeof Class === 'function') {
    type = constructor;
    constructor = Class;
    Class = {};
  }
  Class._usergrid = {
    constructor: constructor,
    type: (type) ? type : constructor.name.toLowerCase()
  };
  _.mixin(Class, usergridStatics(client));
  return Class;
}

function
define
(
Class
,
constructor
,
type
)
{
if
(
!
client
)
{
throw
new
Error
(
'Usergrid not configured'
)
;
}
if
(
typeof
Class
===
'function'
)
{
type
=
constructor
;
constructor
=
Class
;
Class
=
{
}
;
}
Class
.
_usergrid
=
{
constructor
:
constructor
,
type
:
(
type
)
type
:
constructor
.
name
.
toLowerCase
(
)
}
;
_
.
mixin
(
Class
,
usergridStatics
(
client
)
)
;
return
Class
;
}

"Class" is optional. if omitted, a Class object will be created and returned. "type" is optional. if omitted, constructor name is used as the usergrid type.

Class is optional . if omitted a Class object will be created and returned . type is optional . if omitted constructor name is used as the usergrid type .


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

    if (parsed.args.length < 2) throw new SyntaxError('SAVESPRITE command requires 2 arguments');

    this.id = parsed.args[0];
    this.fileName = parsed.args[1];
}

Saves a sprite to a file

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


function defer(func) {
    return new (class {
        constructor(generator) {
            this.generator = generator;
        }
        [Symbol.iterator]() {
            return this.generator()[Symbol.iterator]();
        }
    })(func);
}

function defer ( func ) { return new ( class { constructor ( generator ) { this . generator = generator ; } [ Symbol . iterator ] ( ) { return this . generator ( ) [ Symbol . iterator ] ( ) ; } } ) ( func ) ; }

Wraps an iterable factory inside a class that allows it to be repeatedly iterated without state, same as how Arrays work

Wraps an iterable factory inside a class that allows it to be repeatedly iterated without state same as how Arrays work


function forward(event, source, target) {
    source.on(event, target.emit.bind(target, event));
}

function forward ( event , source , target ) { source . on ( event , target . emit . bind ( target , event ) ) ; }

Forward events of the specified type from source emitter to target.
@param {string} event
@param {EventEmitter} source
@param {EventEmitter} target

Forward events of the specified type from source emitter to target .


function (state, scope, secondaryScope) {
        if(!validators.isBlockStart(state)) return state.error(constants.unexpectedToken);
        state.next(); //Skip block start.

        utils.statementsInBlock(state, scope, secondaryScope);

        if(!validators.isBlockEnd(state)) return state.error(constants.unexpectedToken);
        state.next(); //Skip block end.
    }

function
(
state
,
scope
,
secondaryScope
)
{
if
(
!
validators
.
isBlockStart
(
state
)
)
return
state
.
error
(
constants
.
unexpectedToken
)
;
state
.
next
(
)
;
//Skip block start.
utils
.
statementsInBlock
(
state
,
scope
,
secondaryScope
)
;
if
(
!
validators
.
isBlockEnd
(
state
)
)
return
state
.
error
(
constants
.
unexpectedToken
)
;
state
.
next
(
)
;
//Skip block end.
}

Parses a Block Statement.
@param state The parser state.
@param [scope] {string} The scope to use when parsing the statements inside the block.
@returns {*}


function(state, scope, secondaryScope) {
        state.createLexicalEnvironment();

        state.levelDown(scope);
        if(secondaryScope) state.levelDown(secondaryScope);

        while(state.token && !validators.isBlockEnd(state)) {
            state.processor.token(state);
        }

        if(secondaryScope) state.levelUp();
        state.levelUp();

        state.finalizeLexicalEnvironment();
    }

function ( state , scope , secondaryScope ) { state . createLexicalEnvironment ( ) ; state . levelDown ( scope ) ; if ( secondaryScope ) state . levelDown ( secondaryScope ) ; while ( state . token && ! validators . isBlockEnd ( state ) ) { state . processor . token ( state ) ; } if ( secondaryScope ) state . levelUp ( ) ; state . levelUp ( ) ; state . finalizeLexicalEnvironment ( ) ; }

Parses statements until a block end is found.
@param state The parser state.
@param [scope] {string} The scope to use when parsing the statements inside the block.

Parses statements until a block end is found .


function(state, noError) {
        if(validators.isSemicolon(state)) {
            state.next();
        }
        else if(state.token && !validators.isBlockEnd(state)) {
            var lb = state.lookback();
            if(!lb || state.token.line === lb.line) {
                if(!noError) state.error(constants.unexpectedToken);
                return false;
            }
        }

        return true;
    }

function ( state , noError ) { if ( validators . isSemicolon ( state ) ) { state . next ( ) ; } else if ( state . token && ! validators . isBlockEnd ( state ) ) { var lb = state . lookback ( ) ; if ( ! lb || state . token . line === lb . line ) { if ( ! noError ) state . error ( constants . unexpectedToken ) ; return false ; } } return true ; }

Parses a semicolon or applies automatic semicolon insertion.
@param state The parser state.
@param [noError] {boolean} Whether a missing semicolon should cause an error.
@returns {boolean} Whether the parsing or the insertion was successful.

Parses a semicolon or applies automatic semicolon insertion .


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

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

Reads a pixel at a certain location

@param {String} args The arguments to the command


function(config) {
			if(!config) {
				return "";
			}

			var result = [];

			for(var key in config) {
				if(typeof config[key] == "undefined") {
					continue;
				}

				result.push(key + "=" + config[key]);
			}

			if(result.length > 0) {
				return "?" + result.join("&");
			}

			return "";
		}

function ( config ) { if ( ! config ) { return "" ; } var result = [ ] ; for ( var key in config ) { if ( typeof config [ key ] == "undefined" ) { continue ; } result . push ( key + "=" + config [ key ] ) ; } if ( result . length > 0 ) { return "?" + result . join ( "&" ) ; } return "" ; }

Function returns string in ?q1=v1&q2=v2 format
from passed config key-value pairs

@param {Object} config
@returns {undefined}

Function returns string in ?q1 = v1&q2 = v2 format from passed config key - value pairs


function(consumerKey, consumerSecret, applicationName, format, useCompression) {
		this.eventHandlers = {};
		this.consumerKey = consumerKey;
		this.consumerSecret = consumerSecret;
		this.useCompression = useCompression || true;
		this.format = format || "json";
	    this.acceptEncoding = this.useCompression ? 'gzip, deflate' : 'identity';
	    this.applicationName = applicationName ? (applicationName + "/") : "";

	    if(!this.consumerKey || !this.consumerSecret) {
	    	throw "ConsumerKey and ConsumerSecret should be specified in order to use SDK";
	    }

	    this.applicationName += this.tpl("JavaScript/{SDK_VERSION}/{format}", {
	    	SDK_VERSION: this.SDK_VERSION,
	    	format: this.format
	    });
	}

initializes the API

@param {Object} config
@returns {undefined}


function save(file, options) {
  var stream = fs.createWriteStream(file, options);
  function onSave() {
    stream.removeAllListeners();
    this.emit('save');
  }
  function onError(err) {
    stream.removeAllListeners();
    this.emit('error', err);
  }
  stream.on('finish', onSave.bind(this));
  stream.on('error', onError.bind(this));
  this.pipe(stream);
  return this;
}

function save ( file , options ) { var stream = fs . createWriteStream ( file , options ) ; function onSave ( ) { stream . removeAllListeners ( ) ; this . emit ( 'save' ) ; } function onError ( err ) { stream . removeAllListeners ( ) ; this . emit ( 'error' , err ) ; } stream . on ( 'finish' , onSave . bind ( this ) ) ; stream . on ( 'error' , onError . bind ( this ) ) ; this . pipe ( stream ) ; return this ; }

Pipe the output of this writer to a file.

Pipe the output of this writer to a file .


function findPath(request, paths) {
  if (paths.length == 1 && /^\.{2}/.test(request)) {
    paths[0] = path.dirname(paths[0])
    request = request.slice(1)
  }
  return originalFindPath(request, paths)
}

function findPath ( request , paths ) { if ( paths . length == 1 && / ^\.{2} / . test ( request ) ) { paths [ 0 ] = path . dirname ( paths [ 0 ] ) request = request . slice ( 1 ) } return originalFindPath ( request , paths ) }

monkey patch findPath to handle fake directories better

TODO: handle more types of request

@param  {String} request
@param  {Array[String]} paths
@return {String}


function run(js, path) {
  var m = new Module(path, module)
  Module._findPath = findPath
  m.paths = Module._nodeModulePaths(dirname(path))
  m.id = path
  m.filename = path
  js = 'module.return=eval(' + json(js) + ')'
  m._compile(js, path)
  Module._findPath = originalFindPath
  return m
}

function run ( js , path ) { var m = new Module ( path , module ) Module . _findPath = findPath m . paths = Module . _nodeModulePaths ( dirname ( path ) ) m . id = path m . filename = path js = 'module.return=eval(' + json ( js ) + ')' m . _compile ( js , path ) Module . _findPath = originalFindPath return m }

run `js` as if it were a module at `path`

@param {String} js
@param {String} path
@api private


function move_aspirate_forward(hash) {
    var asp = u.unasp2asp(hash.stemUlt);
    if (!asp) return;
    var stem = u.replaceEnd(hash.stem, hash.stemUlt, asp);
    if (!stem || stem == hash.stem) return;
    hash.stems = [stem];
    if (debug) log('mod: move_aspirate_forward', stem);
}

function
move_aspirate_forward
(
hash
)
{
var
asp
=
u
.
unasp2asp
(
hash
.
stemUlt
)
;
if
(
!
asp
)
return
;
var
stem
=
u
.
replaceEnd
(
hash
.
stem
,
hash
.
stemUlt
,
asp
)
;
if
(
!
stem
||
stem
==
hash
.
stem
)
return
;
hash
.
stems
=
[
stem
]
;
if
(
debug
)
log
(
'mod: move_aspirate_forward'
,
stem
)
;
}

t- and th-, when they are the second letter, become dh-

t - and th - when they are the second letter become dh -


function get (options, config) {
  options = options || found
  config = config || {}

  // Load options.
  var dir = options.dir || found.dir || 'config'
  var env = options.env || found.env || 'staging'
  var base = options.base || found.base || 'base'

  // Allow many "env" values.
  var key = env.toLowerCase()
    .replace(/^([gro]|ca)/, 'p')  // gamma, release, one, canary -> "production".
    .replace(/^(sa|[al])/, 'd')   // sandbox, alpha, local -> "development".
    .replace(/^[qtbcij]/, 's')[0] // qa, test, beta, ci, jenkins -> "staging".

  // Coerce to an expected environment.
  var environment = map[key] || map[key = 's']

  config.env = env
  config.environment = environment
  config.isDebug = /de?bu?g/i.test(env)
  config.isDevelopment = (key === 'd')
  config.isStaging = (key === 's')
  config.isProduction = (key === 'p')

  // Load files.
  hide(config, 'load', load)

  // Load configuration from files.
  config.load(dir, base)
  config.load(dir, environment)

  // Load any matching sub-environments.
  var subEnvironments = config.subEnvironments
  if (subEnvironments && subEnvironments.indexOf(env) > -1) {
    config.load(dir, env)
  }

  return config
}

Get a configuration based on options.

@param  {Object} options  An optional object with optional parameters:
- dir: defaults to "config".
- env: defaults to "staging".
- base: defaults to "base".
@param  {Object} config   An optional object to populate.
@return {Object}          A fully populated configuration object.


function decorate (object, values) {
  for (var key in values) {
    if (typeof object[key] === 'object') {
      decorate(object[key], values[key])
    } else {
      object[key] = values[key]
    }
  }
}

function decorate ( object , values ) { for ( var key in values ) { if ( typeof object [ key ] === 'object' ) { decorate ( object [ key ] , values [ key ] ) } else { object [ key ] = values [ key ] } } }

Decorate one configuration object with values from another.

@param  {Object} object  An existing config object.
@param  {Object} values  An overriding config object.

Decorate one configuration object with values from another .


function hide (object, name, value) {
  Object.defineProperty(object, name, {
    enumerable: false,
    value: value
  })
}

function hide ( object , name , value ) { Object . defineProperty ( object , name , { enumerable : false , value : value } ) }

Set a non-enumerable property value.

@param  {Object} object  An object.
@param  {Object} name    A property name.
@param  {Object} value   A property value.


function _instanceCopy(sourceRef, copyRef, rc, copier) {
    let origIndex = rc.xStack.indexOf(sourceRef);
    if (origIndex === -1) {
        rc.push(sourceRef, copyRef);
        forEach(sourceRef, function(value, key) {
            copier(copyRef, value, key);
        });
        rc.pop();
        return copyRef;
    }
    else
        return rc.yStack[origIndex];
}

function _instanceCopy ( sourceRef , copyRef , rc , copier ) { let origIndex = rc . xStack . indexOf ( sourceRef ) ; if ( origIndex === - 1 ) { rc . push ( sourceRef , copyRef ) ; forEach ( sourceRef , function ( value , key ) { copier ( copyRef , value , key ) ; } ) ; rc . pop ( ) ; return copyRef ; } else return rc . yStack [ origIndex ] ; }

The shared instance copier based on provided callback.

@param sourceRef A reference to the source.
@param copyRef A reference to the copy.
@param rc The current recurse and reference counter.
@param copier The callback used to make a copy of the property list from source to copy reference.
@returns {any} The reference to the copy.

The shared instance copier based on provided callback .


function _objectCopy(sourceRef, copyRef, rc) {
    let origIndex = rc.xStack.indexOf(sourceRef);
    if (origIndex === -1) {
        rc.push(sourceRef, copyRef);
        for (let [key, val] of _entries(sourceRef))
            copyRef[key] = _clone(val, rc);
        let symbols = Object.getOwnPropertySymbols(sourceRef);
        for (let symbol of symbols)
            copyRef[symbol] = _clone(sourceRef[symbol], rc);
        rc.pop();
        return copyRef;
    }
    else
        return rc.yStack[origIndex];
}

function _objectCopy ( sourceRef , copyRef , rc ) { let origIndex = rc . xStack . indexOf ( sourceRef ) ; if ( origIndex === - 1 ) { rc . push ( sourceRef , copyRef ) ; for ( let [ key , val ] of _entries ( sourceRef ) ) copyRef [ key ] = _clone ( val , rc ) ; let symbols = Object . getOwnPropertySymbols ( sourceRef ) ; for ( let symbol of symbols ) copyRef [ symbol ] = _clone ( sourceRef [ symbol ] , rc ) ; rc . pop ( ) ; return copyRef ; } else return rc . yStack [ origIndex ] ; }

Copies data from one object to another.

@param sourceRef A reference to the object source.
@param copyRef A reference to the object copy.
@param rc The current recurse and reference counter.
@returns {Object} The reference to the object copy.

Copies data from one object to another .


function _setCopy(sourceRef, copyRef, rc) {
    return _instanceCopy(sourceRef, copyRef, rc, (set, val) => {
        set.add(_clone(val, rc));
    });
}

function _setCopy ( sourceRef , copyRef , rc ) { return _instanceCopy ( sourceRef , copyRef , rc , ( set , val ) => { set . add ( _clone ( val , rc ) ) ; } ) ; }

Copies data from one set to another.

@param sourceRef A reference to the set source.
@param copyRef A reference to the set copy.
@param rc The current recurse and reference counter.
@returns {Set} The reference to the set copy.


function _mapCopy(sourceRef, copyRef, rc) {
    return _instanceCopy(sourceRef, copyRef, rc, (map, val, key) => {
        map.set(key, _clone(val, rc));
    });
}

function _mapCopy ( sourceRef , copyRef , rc ) { return _instanceCopy ( sourceRef , copyRef , rc , ( map , val , key ) => { map . set ( key , _clone ( val , rc ) ) ; } ) ; }

Copies data from one map to another.

@param sourceRef A reference to the map source.
@param copyRef A reference to the map copy.
@param rc The current recurse and reference counter.
@returns {Map} The reference to the map copy.


function _singleCopy(sourceRef, copyRef, rc) {
    return _instanceCopy(sourceRef, copyRef, rc, (item, val, key) => {
        copyRef[key] = _clone(val, rc);
    });
}

function _singleCopy ( sourceRef , copyRef , rc ) { return _instanceCopy ( sourceRef , copyRef , rc , ( item , val , key ) => { copyRef [ key ] = _clone ( val , rc ) ; } ) ; }

Copies data from one item to another.
Designed to a be a generic copy interface, where possible.

@param sourceRef A reference to the source.
@param copyRef A reference to the copy.
@param rc The current recurse and reference counter.
@returns {any} The reference to the copy.

Copies data from one item to another . Designed to a be a generic copy interface where possible .


function clone(origSource) {
    let origIndex = -1;
    let rc = new RecurseCounter(1000);
    return _clone.call(null, origSource, rc);
}

function clone ( origSource ) { let origIndex = - 1 ; let rc = new RecurseCounter ( 1000 ) ; return _clone . call ( null , origSource , rc ) ; }

Creates a deep clone of the provided source.

@param origSource The item to clone.
@returns {any} The cloned item.

Creates a deep clone of the provided source .


function _compareObject(x, y, rc) {
    if (x === y)
        return true;
    if (x.constructor && y.constructor && x.constructor !== y.constructor)
        return false;
    let xKeys = Object.keys(x);
    let yKeys = Object.keys(y);
    xKeys.sort();
    yKeys.sort();
    if (!_equals(xKeys, yKeys, rc))
        return false;
    rc.push(x, y);
    for (let k in x) {
        if (!_equals(x[k], y[k], rc))
            return false;
    }
    rc.pop();
    return true;
}

function _compareObject ( x , y , rc ) { if ( x === y ) return true ; if ( x . constructor && y . constructor && x . constructor !== y . constructor ) return false ; let xKeys = Object . keys ( x ) ; let yKeys = Object . keys ( y ) ; xKeys . sort ( ) ; yKeys . sort ( ) ; if ( ! _equals ( xKeys , yKeys , rc ) ) return false ; rc . push ( x , y ) ; for ( let k in x ) { if ( ! _equals ( x [ k ] , y [ k ] , rc ) ) return false ; } rc . pop ( ) ; return true ; }

Internal method for comparing the equivalence of objects, or object-like items.

@param x The first item to compare.
@param y The second item to compare.
@param rc The running counter for comparing circular references.
@returns {boolean} An indication as to whether or not x and y were equal.

Internal method for comparing the equivalence of objects or object - like items .


function equals(x, y) {
    let rc = new RecurseCounter(1000);
    return _equals.call(null, x, y, rc);
}

function equals ( x , y ) { let rc = new RecurseCounter ( 1000 ) ; return _equals . call ( null , x , y , rc ) ; }

Compares the equality of two items.

@param x The first item to compare.
@param y The second item to compare.
@returns {boolean} An indication as to whether or not x and y were equal.


function forEach(item, method, context) {
    let type = getType(item);
    switch(type) {
        case types.date:
        case types.function:
        case types.object:
        case types.regexp:
            if (!item[Symbol.iterator]) {
                for (let [key, value] of _entries(item)) {
                    if (item.hasOwnProperty(key))
                        method.call(context, value, key, item);
                }
            }
            else { // shenanigans
                for (let value of item) {
                    // do we want to check if value is array, and spread it across value/key?
                    method.call(context, value, undefined, item);
                }
            }
            break;
        case types.arguments:
        case types.array:
            for (let i = 0; i < item.length; i++)
                method.call(context, item[i], i, item);
            break;
        case types.map:
            for (let [key, value] of item)
                method.call(context, value, key, item);
            break;
        case types.set:
            for (let value of item) // treat keys and values as equivalent for sets
                method.call(context, value, value, item);
            break;
        default:
            // if unknown type, then check for Symbol.iterator
            if (item[Symbol.iterator]) {
                for (let value of item[Symbol.iterator]())
                    method.call(context, value, undefined, item);
            }
            else if (!typeset.has(type) && type && type.constructor) {
                for (let [ key, value ] of _entries(item)) {
                    if (item.hasOwnProperty(key)) // necessary with _entries?
                        method.call(context, value, key, item);
                }
            }
            break;
    }
    return item;
}

Generic interface for looping over an iterable,
and executing a provided method for each item.

@param {any} item The item over which to iterate.
@param {Function} method The callback to execute for each iterated value.
@param {any} context The optional context to pass to each callback.
@returns {any} A reference to the original item.

Generic interface for looping over an iterable and executing a provided method for each item .


function typeForExtend(val) {
    // treat unknown types (classes, hopefully?) and functions as objects
    let type = getType(val);
    if (type === types.function || !typeset.has(type) && type && type.constructor)
        type = types.object;
    return type;
}

Internal method determining which type
to utilize for a provided value when using extend.

This is to be used so types for classes
and functions can be considered as objects.

@param val The first item to compare.
@param y The second item to compare.
@param rc The running counter for comparing circular references.
@returns {boolean} An indication as to whether or not x and y were equal.

Internal method determining which type to utilize for a provided value when using extend .


function isExtendable(...args) {
    // this is a fairly expensive call. find a way to optimize further?
    if (args.length < 1)
        return false;

    let baseType = typeForExtend(args[0]);
    if (!(
               baseType === types.array
            || baseType === types.object
            || baseType === types.set
            || baseType === types.map
            || baseType === types.function)) {
        return false;
    }
    for (let i = 1; i < args.length; i++) {
        let targetType = typeForExtend(args[i]);
        if (targetType !== baseType)
            return false;
    }
    return true;
}

Internal method determining whether or not the provided arguments
can be smashed or extended together, based on types.

@param x The first item to compare.
@param y The second item to compare.
@param rc The running counter for comparing circular references.
@returns {boolean} An indication as to whether or not x and y were equal.

Internal method determining whether or not the provided arguments can be smashed or extended together based on types .


function _extend(a, b) {
    forEach(b, (bVal, key) => {
        let type = typeForExtend(a);
        switch(type) {
            case types.array:
            case types.object:
                if (a[key] === undefined || a[key] === null)
                    a[key] = b[key];
                else if (isExtendable(a[key], b[key]))
                    _extend(a[key], b[key]);
                break;
            case types.set:
                if (!a.has(bVal))
                    a.add(bVal);
                break;
            case types.map:
                if (!a.has(key))
                    a.set(key, bVal);
                else {
                    let aVal = a.get(key);
                    if (aVal === undefined || aVal === null)
                        a.set(key, bVal);
                    else if (isExtendable(aVal, bVal))
                        _extend(aVal, bVal);
                }
                break;
        }
    });
    return a;
}

function _extend ( a , b ) { forEach ( b , ( bVal , key ) => { let type = typeForExtend ( a ) ; switch ( type ) { case types . array : case types . object : if ( a [ key ] === undefined || a [ key ] === null ) a [ key ] = b [ key ] ; else if ( isExtendable ( a [ key ] , b [ key ] ) ) _extend ( a [ key ] , b [ key ] ) ; break ; case types . set : if ( ! a . has ( bVal ) ) a . add ( bVal ) ; break ; case types . map : if ( ! a . has ( key ) ) a . set ( key , bVal ) ; else { let aVal = a . get ( key ) ; if ( aVal === undefined || aVal === null ) a . set ( key , bVal ) ; else if ( isExtendable ( aVal , bVal ) ) _extend ( aVal , bVal ) ; } break ; } } ) ; return a ; }

Internal extend call.
Performance abstraction to bypass all the argument shenanigans,
as we know we will only be extending two items at a time internally.

@param {any} a The item on which to extend the second.
@param {any} b The item to extend onto the first.
@returns {any} The reference to the first item.

Internal extend call . Performance abstraction to bypass all the argument shenanigans as we know we will only be extending two items at a time internally .


function extend(a, ...rest) {
    rest.forEach(b => {
        if (isExtendable(a, b))
            _extend(a, b);
    });
    return a;
}

function extend ( a , ... rest ) { rest . forEach ( b => { if ( isExtendable ( a , b ) ) _extend ( a , b ) ; } ) ; return a ; }

Extends the properties on the provided arguments into the original item.
Any properties on the tail arguments will not overwrite any properties
on the first argument unless they are null or undefined,
and any non primitive references will be shallow.

@param {any} a The target to be extended.
@param {...any} rest The tail items to extend onto the target.
@returns {any} A reference to the extended target.

Extends the properties on the provided arguments into the original item . Any properties on the tail arguments will not overwrite any properties on the first argument unless they are null or undefined and any non primitive references will be shallow .


function _smash(a, b) {
    this.forEach(b, (val, key) => {
        if (this.isSmashable(a[key], b[key])) // find a way to move isSmashable internal
            this._smash(a[key], b[key]);
        else
            a[key] = this.deepCopy(b[key]);
    });
    return a;
}

Internal smash call.
Performance abstraction to bypass all the argument shenanigans,
as we know we will only be smashing two items at a time internally.

@param {any} a The item on which to smash the second.
@param {any} b The item to smash onto the first.
@returns {any} The reference to the first item.

Internal smash call . Performance abstraction to bypass all the argument shenanigans as we know we will only be smashing two items at a time internally .


function smash(a, ...rest) {
    rest.forEach(b => {
        if (this.isSmashable(a, b)) // find a way to move isSmashable internal
            this._smash(a, b);
    });
    return a;
}

Smashes the properties on the provided arguments into the first argument.
Any properties on the tail arguments will overwrite
any existing properties on the first argument.

@param {any} a The target to be smashed.
@param {...any} rest The tail items to smash onto the target.
@returns {any} A reference to the smashed target.

Smashes the properties on the provided arguments into the first argument . Any properties on the tail arguments will overwrite any existing properties on the first argument .


function File(name, file, parent) {
    this.name = name;
    this.file = file;
    this.parent = parent;
    this.readCursor = 0;
    this.eof = false;
}

function File ( name , file , parent ) { this . name = name ; this . file = file ; this . parent = parent ; this . readCursor = 0 ; this . eof = false ; }

Represents a file

@param {String} name The name of the file
@param {Array} file The file contents
@param {Drive} parent The parent drive


function(msg, code, errorStr, cb) {
                return function(error, data) {
                    if (error) {
                        error = json_rpc.newSysError(msg, code, errorStr,
                                                     error);
                    }
                    cb(error, data);
                };
            }

function ( msg , code , errorStr , cb ) { return function ( error , data ) { if ( error ) { error = json_rpc . newSysError ( msg , code , errorStr , error ) ; } cb ( error , data ) ; } ; }


function getTimeDifference(timestr1, timestr2) {
	if (typeof timestr1 !== 'string' || typeof timestr2 !== 'string') {
		throw new Error('pendel.time() expects string arguments');
	}

	// Check if we are getting the short timecode formats
	// like 1:32PM or 13:32. If Yes, convert it into a
	// generic datestring so that we can support the old API.
	var date1 = shortTimeToDateString(timestr1);
	var date2 = shortTimeToDateString(timestr2);

	if (!date1) {
		date1 = new Date(timestr1).toString();
	}

	if (!date2) {
		date2 = new Date(timestr2).toString();
	}

	var time1 = dateComponents(date1);
	var time2 = dateComponents(date2);

	var results = getTotalResultsFromEpochs(time1.epoch, time2.epoch);

	return {
		hours: Math.floor(results.totalSeconds / 60 / 60),
		minutes: Math.floor((results.totalSeconds / 60) % 60),
		seconds: Math.floor(results.totalSeconds % 60),
		totalMinutes: results.totalMinutes,
		totalSeconds: results.totalSeconds
	};
}

Get the time difference between two timestrings.

@param {string} timestr1 - a time string.
@param {string} timestr2 - a time string.
@returns {object}

Get the time difference between two timestrings .


function getDateDifference(timestr1, timestr2) {
	// Force into predictable date format
	var start = timestr1.toLocaleDateString ? timestr1 : new Date(timestr1);
	var end = timestr2.toLocaleDateString ? timestr2 : new Date(timestr2);

	if (start.toString() === 'Invalid Date' || end.toString() === 'Invalid Date') {
		throw new TypeError('pendel.date() expects two valid date strings');
	}

	var dr = moment.range(start, end);

	return {
		years: dr.diff('years'),
		months: dr.diff('months'),
		weeks: dr.diff('weeks'),
		days: dr.diff('days'),
		hours: dr.diff('hours'),
		minutes: dr.diff('minutes'),
		seconds: dr.diff('seconds')
	};
}

Get the time difference between two datestrings.

@param {string} timestr1 - a date string.
@param {string} timestr2 - a date string.
@returns {object}

Get the time difference between two datestrings .


function getTotalResultsFromEpochs(epoch1, epoch2) {
	var millisecs = Math.abs(epoch1 - epoch2);
	var seconds = millisecs / 1000;

	return {
		totalSeconds: seconds,
		totalMinutes: Math.floor(seconds / 60),
		totalHours: Math.floor(seconds / 60) * 60
	};
}

function getTotalResultsFromEpochs ( epoch1 , epoch2 ) { var millisecs = Math . abs ( epoch1 - epoch2 ) ; var seconds = millisecs / 1000 ; return { totalSeconds : seconds , totalMinutes : Math . floor ( seconds / 60 ) , totalHours : Math . floor ( seconds / 60 ) * 60 } ; }

Get total elapsed seconds, minutes and hours between
two epoch times.

@param {number} epoch1 - an epoch time.
@param {number} epoch2 - an epoch time.
@returns {object}

Get total elapsed seconds minutes and hours between two epoch times .


function InputCommand(args) {
    var parsed = new statements.ArgumentStatement(args);
    if (!parsed.args.length) throw new SyntaxError('INPUT requires at least one argument');

    var question = "", placeVar, file;
    if (parsed.args.length === 1) placeVar = parsed.args[0];
    else {
        if (parsed.args[0].child instanceof statements.PointerStatement) file = parsed.args[0];
        else question = parsed.args[0];

        placeVar = parsed.args[1];
    }

    if (!(placeVar.child instanceof statements.VariableStatement || placeVar.child instanceof statements.FunctionStatement))
        throw new SyntaxError('Expected variable');

    this.file = file;
    this.question = question;
    this.placeVar = placeVar;
}

function
InputCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
!
parsed
.
args
.
length
)
throw
new
SyntaxError
(
'INPUT requires at least one argument'
)
;
var
question
=
""
,
placeVar
,
file
;
if
(
parsed
.
args
.
length
===
1
)
placeVar
=
parsed
.
args
[
0
]
;
else
{
if
(
parsed
.
args
[
0
]
.
child
instanceof
statements
.
PointerStatement
)
file
=
parsed
.
args
[
0
]
;
else
question
=
parsed
.
args
[
0
]
;
placeVar
=
parsed
.
args
[
1
]
;
}
if
(
!
(
placeVar
.
child
instanceof
statements
.
VariableStatement
||
placeVar
.
child
instanceof
statements
.
FunctionStatement
)
)
throw
new
SyntaxError
(
'Expected variable'
)
;
this
.
file
=
file
;
this
.
question
=
question
;
this
.
placeVar
=
placeVar
;
}

Inputs a line from the user

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


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

    if (parsed.args.length < 8) throw new SyntaxError('PIECHART command requires 8 arguments');
    this.x = parsed.args[0];
    this.y = parsed.args[1];
    this.r = parsed.args[2];
    this.itemsLength = parsed.args[3];
    this.percentages = parsed.args[4];
    this.itemsRed = parsed.args[5];
    this.itemsGreen = parsed.args[6];
    this.itemsBlue = parsed.args[7];
}

function
PiechartCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
8
)
throw
new
SyntaxError
(
'PIECHART command requires 8 arguments'
)
;
this
.
x
=
parsed
.
args
[
0
]
;
this
.
y
=
parsed
.
args
[
1
]
;
this
.
r
=
parsed
.
args
[
2
]
;
this
.
itemsLength
=
parsed
.
args
[
3
]
;
this
.
percentages
=
parsed
.
args
[
4
]
;
this
.
itemsRed
=
parsed
.
args
[
5
]
;
this
.
itemsGreen
=
parsed
.
args
[
6
]
;
this
.
itemsBlue
=
parsed
.
args
[
7
]
;
}

Draws a piechart

@param {String} args The arguments to the command


function flatMap(mapper) {
    return function* (iterable) {
        let index = 0;
        for (const value of iterable) {
            const innerIterable = mapper(value, index);
            for (const inner of innerIterable) {
                yield inner;
            }
            index = index + 1;
        }
    };
}

function flatMap ( mapper ) { return function * ( iterable ) { let index = 0 ; for ( const value of iterable ) { const innerIterable = mapper ( value , index ) ; for ( const inner of innerIterable ) { yield inner ; } index = index + 1 ; } } ; }

Yield all items in every iterable returned by the mapper when applied to every item in the source iterable


function skipWhile(predicate) {
    return function* (iterable) {
        let i = 0;
        let canReturn = false;
        for (const item of iterable) {
            if (!canReturn) {
                canReturn = !predicate(item, i);
                if (canReturn) {
                    yield item;
                }
                i = i + 1;
            }
            else {
                yield item;
            }
        }
    };
}

function skipWhile ( predicate ) { return function * ( iterable ) { let i = 0 ; let canReturn = false ; for ( const item of iterable ) { if ( ! canReturn ) { canReturn = ! predicate ( item , i ) ; if ( canReturn ) { yield item ; } i = i + 1 ; } else { yield item ; } } } ; }

Skip items in an iterable until the passed predicate fails, then yioeld all items in the iterable

Skip items in an iterable until the passed predicate fails then yioeld all items in the iterable


function skipUntil(predicate) {
    return function* (iterable) {
        let i = 0;
        let canReturn = false;
        for (const item of iterable) {
            if (!canReturn) {
                canReturn = predicate(item, i);
                if (canReturn) {
                    yield item;
                }
                i = i + 1;
            }
            else {
                yield item;
            }
        }
    };
}

function skipUntil ( predicate ) { return function * ( iterable ) { let i = 0 ; let canReturn = false ; for ( const item of iterable ) { if ( ! canReturn ) { canReturn = predicate ( item , i ) ; if ( canReturn ) { yield item ; } i = i + 1 ; } else { yield item ; } } } ; }

Skip items in an iterable until the passed predicate matches, then yioeld all items in the iterable

Skip items in an iterable until the passed predicate matches then yioeld all items in the iterable


function distinctUntilKeyChanged(keySelector) {
    return function* (it) {
        let prev = undefined;
        for (const item of it) {
            const key = keySelector(item);
            if (key === prev) {
                continue;
            }
            prev = key;
            yield item;
        }
    };
}

function distinctUntilKeyChanged ( keySelector ) { return function * ( it ) { let prev = undefined ; for ( const item of it ) { const key = keySelector ( item ) ; if ( key === prev ) { continue ; } prev = key ; yield item ; } } ; }

Play items from a set, skipping ones that do not change

Play items from a set skipping ones that do not change


function orderBy(keySelector, comparison) {
    const trueKeySelector = keySelector || defaultKeySelector;
    const trueComparison = comparison || defaultComparison;
    return function* (item) {
        const keyedMapper = map((item, index) => ({ item, key: trueKeySelector(item, index) }));
        const keyed = keyedMapper(item);
        const keyedArray = Array.from(keyed);
        keyedArray.sort((a, b) => trueComparison(a.key, b.key));
        for (const { item } of keyedArray) {
            yield item;
        }
    };
}

function orderBy ( keySelector , comparison ) { const trueKeySelector = keySelector || defaultKeySelector ; const trueComparison = comparison || defaultComparison ; return function * ( item ) { const keyedMapper = map ( ( item , index ) => ( { item , key : trueKeySelector ( item , index ) } ) ) ; const keyed = keyedMapper ( item ) ; const keyedArray = Array . from ( keyed ) ; keyedArray . sort ( ( a , b ) => trueComparison ( a . key , b . key ) ) ; for ( const { item } of keyedArray ) { yield item ; } } ; }

Play the given Iterable ordered by a given key or itself


function repeat(times) {
    return function* (it) {
        const buffer = [];
        for (const item of it) {
            buffer.push(item);
            yield item;
        }
        for (let i = 0; i < times; ++i) {
            yield* buffer;
        }
    };
}

function repeat ( times ) { return function * ( it ) { const buffer = [ ] ; for ( const item of it ) { buffer . push ( item ) ; yield item ; } for ( let i = 0 ; i < times ; ++ i ) { yield * buffer ; } } ; }

Play the given Iterable, and then it N more times

Play the given Iterable and then it N more times


function shuffle(it, rand = () => Math.random()) {
    return map((x) => x[0])(orderBy((x) => x[1])(map((x) => [x, rand()])(it)));
}

function shuffle ( it , rand = ( ) => Math . random ( ) ) { return map ( ( x ) => x [ 0 ] ) ( orderBy ( ( x ) => x [ 1 ] ) ( map ( ( x ) => [ x , rand ( ) ] ) ( it ) ) ) ; }

Play the given Iterable in a random order


function(compressedData) {
    var inflatedData =  zlib.inflateSync( new Buffer(compressedData, 'base64'));
    var outputString = "[" + String.fromCharCode.apply(null,inflatedData) + "]";
    var outputArray = JSON.parse(outputString);
    return ArrayConverter.diffsToValues(outputArray);
  }

function ( compressedData ) { var inflatedData = zlib . inflateSync ( new Buffer ( compressedData , 'base64' ) ) ; var outputString = "[" + String . fromCharCode . apply ( null , inflatedData ) + "]" ; var outputArray = JSON . parse ( outputString ) ; return ArrayConverter . diffsToValues ( outputArray ) ; }

Decompress compressed string data

@param  {String} compressedData
@return {array<number>} decompressed data


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

    if (parsed.args.length < 3) throw new SyntaxError('SHAPE command requires 3 arguments');
    this.pointsLength = parsed.args[0];
    this.pointsX = parsed.args[1];
    this.pointsY = parsed.args[2];
    this.stroke = parsed.args.length > 3 ? parsed.args[3] : false;
}

function
ShapeCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
)
;
if
(
parsed
.
args
.
length
<
3
)
throw
new
SyntaxError
(
'SHAPE command requires 3 arguments'
)
;
this
.
pointsLength
=
parsed
.
args
[
0
]
;
this
.
pointsX
=
parsed
.
args
[
1
]
;
this
.
pointsY
=
parsed
.
args
[
2
]
;
this
.
stroke
=
parsed
.
args
.
length
>
3
parsed
.
args
[
3
]
:
false
;
}

Draws a custom shape

@param {String} args The arguments to the command


function scrollSpy() {
            var scrollTop = $window.scrollTop(),
                $anchors = $childMenu.find('a'),
                activeIndex;
            $anchors.each(function (index) {
                var $target = $($(this).attr('href').replace(/\./g, '\\.')),
                    offsetTop = $target.offset().top,
                    offsetBottom = offsetTop + $target.outerHeight(true);
                if (offsetTop <= scrollTop && scrollTop < offsetBottom) {
                    activeIndex = index;
                    return false;
                }
            });
            $childMenuItem.removeClass('kss-active');
            if (typeof activeIndex !== 'undefined') {
                $childMenuItem.eq(activeIndex).addClass('kss-active');
            }
        }

function scrollSpy ( ) { var scrollTop = $window . scrollTop ( ) , $anchors = $childMenu . find ( 'a' ) , activeIndex ; $anchors . each ( function ( index ) { var $target = $ ( $ ( this ) . attr ( 'href' ) . replace ( / \. / g , '\\.' ) ) , offsetTop = $target . offset ( ) . top , offsetBottom = offsetTop + $target . outerHeight ( true ) ; if ( offsetTop <= scrollTop && scrollTop < offsetBottom ) { activeIndex = index ; return false ; } } ) ; $childMenuItem . removeClass ( 'kss-active' ) ; if ( typeof activeIndex !== 'undefined' ) { $childMenuItem . eq ( activeIndex ) . addClass ( 'kss-active' ) ; } }


function fixSidebar() {
            if ($sidebarInner.outerHeight() < $content.outerHeight()) {
                $sidebar.addClass('kss-fixed');
                if ($sidebarInner.outerHeight() > $window.height()) {
                    $sidebar.height($window.height());
                    $window.on('scroll', scrollSidebar).trigger('scroll');
                }
                else {
                    $sidebar.height('auto');
                    $window.off('scroll', scrollSidebar);
                }
            }
            else {
                $sidebar.removeClass('kss-fixed');
                $sidebar.height('auto');
                $window.off('scroll', scrollSidebar);
            }
        }

function fixSidebar ( ) { if ( $sidebarInner . outerHeight ( ) < $content . outerHeight ( ) ) { $sidebar . addClass ( 'kss-fixed' ) ; if ( $sidebarInner . outerHeight ( ) > $window . height ( ) ) { $sidebar . height ( $window . height ( ) ) ; $window . on ( 'scroll' , scrollSidebar ) . trigger ( 'scroll' ) ; } else { $sidebar . height ( 'auto' ) ; $window . off ( 'scroll' , scrollSidebar ) ; } } else { $sidebar . removeClass ( 'kss-fixed' ) ; $sidebar . height ( 'auto' ) ; $window . off ( 'scroll' , scrollSidebar ) ; } }


function scrollSidebar(event) {
            if (event.handled !== true) {
                var scrollTop = $window.scrollTop(),
                    maxScrollTop = $document.height() - $window.height();
                if (scrollTop >= 0 && prevScrollTop >= 0 && scrollTop <= maxScrollTop && prevScrollTop <= maxScrollTop) {  // for Mac scrolling
                    $sidebar.scrollTop($sidebar.scrollTop() + (scrollTop - prevScrollTop));
                }
                prevScrollTop = scrollTop;
                event.handled = true;
            }
            else {
                return false;
            }
        }

function
scrollSidebar
(
event
)
{
if
(
event
.
handled
!==
true
)
{
var
scrollTop
=
$window
.
scrollTop
(
)
,
maxScrollTop
=
$document
.
height
(
)
$window
.
height
(
)
;
if
(
scrollTop
>=
0
&&
prevScrollTop
>=
0
&&
scrollTop
<=
maxScrollTop
&&
prevScrollTop
<=
maxScrollTop
)
{
// for Mac scrolling
$sidebar
.
scrollTop
(
$sidebar
.
scrollTop
(
)
+
(
scrollTop
prevScrollTop
)
)
;
}
prevScrollTop
=
scrollTop
;
event
.
handled
=
true
;
}
else
{
return
false
;
}
}


function forEach(declarations, reqName, callback) {
        var d;
        if (reqName === "*") {
            // Iterate over all declarations.
            for (d in declarations) {
                callback.call(this, d);
            }
        } else if (reqName.charAt(reqName.length - 1) === "*") {
            // Iterate over uncapped `*` declarations.
            var baseName = reqName.substring(0, reqName.length - 1);
            for (d in declarations) {
                if (d.indexOf(baseName) === 0) {
                    callback.call(this, d);
                }
            }
        } else {
            // A single dependency iteration.
            if (declarations[reqName]) {
                callback.call(this, reqName);
            } else {
                error("Invalid dependency '" + reqName + "'");
            }
        }
    }

Iterate over declarations, executing a callback function for each matched dependency.

Iterate over declarations executing a callback function for each matched dependency .


function mkdir(units, name) {
        if (name !== "") {
            var parts = name.split(".");
            var path = "";
            for (var i = 0, len = parts.length; i < len; i++) {
                var part = parts[i];
                path += part;
                if (units[part] == null) {
                    units[part] = {};
                } else if (typeof units[part] !== "object") {
                    error("Cann't init unit '" + name
                            + "' because path element '" + path
                            + "' isn't an object");
                }
                units = units[part];
                path += ".";
            }
        }
        return units;
    }

function
mkdir
(
units
,
name
)
{
if
(
name
!==
""
)
{
var
parts
=
name
.
split
(
"."
)
;
var
path
=
""
;
for
(
var
i
=
0
,
len
=
parts
.
length
;
i
<
len
;
i
++
)
{
var
part
=
parts
[
i
]
;
path
+=
part
;
if
(
units
[
part
]
==
)
{
units
[
part
]
=
{
}
;
}
else
if
(
typeof
units
[
part
]
!==
"object"
)
{
error
(
"Cann't init unit '"
+
name
+
"' because path element '"
+
path
+
"' isn't an object"
)
;
}
units
=
units
[
part
]
;
path
+=
"."
;
}
}
return
units
;
}

Creates a valid path to the unit in the namespace.

Creates a valid path to the unit in the namespace .


function pickUnit(srcDecls, destDecls, name, picked, stack) {
        var decl = srcDecls[name];
        if (!picked[name]) {
            if (stack[name]) {
                error("Recursive dependency '" + name + "'");
            }
            stack[name] = true;
            for (var i = 0, len = decl._dependencies.length; i < len; i++) {
                var reqName = decl._dependencies[i];
                forEach(srcDecls, reqName, function(depName) {
                    if (depName !== name) {
                        pickUnit(srcDecls, destDecls, depName, picked, stack);
                    }
                });
            }
            destDecls[name] = decl;
            picked[name] = true;
        }
    }

function
pickUnit
(
srcDecls
,
destDecls
,
name
,
picked
,
stack
)
{
var
decl
=
srcDecls
[
name
]
;
if
(
!
picked
[
name
]
)
{
if
(
stack
[
name
]
)
{
error
(
"Recursive dependency '"
+
name
+
"'"
)
;
}
stack
[
name
]
=
true
;
for
(
var
i
=
0
,
len
=
decl
.
_dependencies
.
length
;
i
<
len
;
i
++
)
{
var
reqName
=
decl
.
_dependencies
[
i
]
;
forEach
(
srcDecls
,
reqName
,
function
(
depName
)
{
if
(
depName
!==
name
)
{
pickUnit
(
srcDecls
,
destDecls
,
depName
,
picked
,
stack
)
;
}
}
)
;
}
destDecls
[
name
]
=
decl
;
picked
[
name
]
=
true
;
}
}

Copy unit declaration and its dependencies.

Copy unit declaration and its dependencies .


function pickUnits(dest, settings) {
        var units = settings.units;
        if (!isArray(units)) {
            error("Invalid units array in pick settings");
        }
        if (!(settings.namespace instanceof Gumup)) {
            error("Invalid namespace in pick settings");
        }
        var picked = {},
            srcDecls = settings.namespace._declarations;
        for (var i = 0, len = units.length; i < len; i++) {
            var reqName = units[i];
            if (!checkRequireName(reqName)) {
                error("Invalid unit name '" + reqName + "' in pick settings");
            }
            forEach(srcDecls, reqName, function(depName) {
                pickUnit(srcDecls, dest._declarations, depName, picked, {});
            });
        }
    }

function
pickUnits
(
dest
,
settings
)
{
var
units
=
settings
.
units
;
if
(
!
isArray
(
units
)
)
{
error
(
"Invalid units array in pick settings"
)
;
}
if
(
!
(
settings
.
namespace
instanceof
Gumup
)
)
{
error
(
"Invalid namespace in pick settings"
)
;
}
var
picked
=
{
}
,
srcDecls
=
settings
.
namespace
.
_declarations
;
for
(
var
i
=
0
,
len
=
units
.
length
;
i
<
len
;
i
++
)
{
var
reqName
=
units
[
i
]
;
if
(
!
checkRequireName
(
reqName
)
)
{
error
(
"Invalid unit name '"
+
reqName
+
"' in pick settings"
)
;
}
forEach
(
srcDecls
,
reqName
,
function
(
depName
)
{
pickUnit
(
srcDecls
,
dest
.
_declarations
,
depName
,
picked
,
{
}
)
;
}
)
;
}
}

Iterate over `settings.unit`, executing a `pickUnit` function for each item.

Iterate over settings . unit executing a pickUnit function for each item .


function initialize(dest, declarations, name, cache, inited) {
        var decl = declarations[name];
        if (!inited[name]) {
            // Create unit dependencies first.
            var len = cache.dependencies[name].length;
            for (var i = 0; i < len; i++) {
                initialize(dest, declarations,
                        cache.dependencies[name][i], cache, inited);
            }
            // Create unit.
            decl._init(dest, name);
            inited[name] = true;
        }
    }

function
initialize
(
dest
,
declarations
,
name
,
cache
,
inited
)
{
var
decl
=
declarations
[
name
]
;
if
(
!
inited
[
name
]
)
{
// Create unit dependencies first.
var
len
=
cache
.
dependencies
[
name
]
.
length
;
for
(
var
i
=
0
;
i
<
len
;
i
++
)
{
initialize
(
dest
,
declarations
,
cache
.
dependencies
[
name
]
[
i
]
,
cache
,
inited
)
;
}
// Create unit.
decl
.
_init
(
dest
,
name
)
;
inited
[
name
]
=
true
;
}
}


function getShaSalt() {
  var shaDeps = [__filename,
                 __dirname + '/protractor_api.dart'];
  return shaTextHexDigest.apply(shaDeps.map(utils.readTextFile));
}

function getShaSalt ( ) { var shaDeps = [ __filename , __dirname + '/protractor_api.dart' ] ; return shaTextHexDigest . apply ( shaDeps . map ( utils . readTextFile ) ) ; }

The generated JS files corresponding to the Dart files are also dependent on this codebase.  As an example, an earlier version fixed up some source map refs.  Another version introduced some bootstrap code, etc.  We make the SHA we use dependendant on our codebase by salting it with the SHA for our sourcecode.

The generated JS files corresponding to the Dart files are also dependent on this codebase . As an example an earlier version fixed up some source map refs . Another version introduced some bootstrap code etc . We make the SHA we use dependendant on our codebase by salting it with the SHA for our sourcecode .


function isBemDecl(node) {
    if (node.type !== 'CallExpression') {
        return false;
    }

    if (node.callee.type !== 'MemberExpression') {
        return false;
    }

    if (node.callee.property.type !== 'Identifier' || node.callee.property.name !== 'decl') {
        return false;
    }

    var obj = node.callee.object;
    if (obj.type === "Identifier") {
        return obj.name === "BEM";
    }

    if (obj.type === "MemberExpression") {
        if (obj.object.type !== "Identifier") {
            return false;
        }

        if (obj.object.name !== "BEM") {
            return false;
        }

        if (obj.property.type !== "Identifier") {
            return false;
        }

        return obj.property.name === "DOM";
    }
    return false;
}

function isBemDecl ( node ) { if ( node . type !== 'CallExpression' ) { return false ; } if ( node . callee . type !== 'MemberExpression' ) { return false ; } if ( node . callee . property . type !== 'Identifier' || node . callee . property . name !== 'decl' ) { return false ; } var obj = node . callee . object ; if ( obj . type === "Identifier" ) { return obj . name === "BEM" ; } if ( obj . type === "MemberExpression" ) { if ( obj . object . type !== "Identifier" ) { return false ; } if ( obj . object . name !== "BEM" ) { return false ; } if ( obj . property . type !== "Identifier" ) { return false ; } return obj . property . name === "DOM" ; } return false ; }

Checks if AST node is `BEM.decl` or `BEM.DOM.decl` call.

@param {Object} node Mozilla Parser API AST node

Checks if AST node is BEM . decl or BEM . DOM . decl call .


function getEntity(decl) {
    if (decl.type === "Literal") {
        return {block: decl.value};
    }

    if (decl.type === "ObjectExpression") {
        var base = getProperty(decl, 'baseBlock'),
            o = {
                block: getProperty(decl, 'block'),
                mod: getProperty(decl, 'modName'),
                val: getProperty(decl, 'modVal')
            };

        if (base) {
            o.base = base;
        }
        return o;
    }

}

function getEntity ( decl ) { if ( decl . type === "Literal" ) { return { block : decl . value } ; } if ( decl . type === "ObjectExpression" ) { var base = getProperty ( decl , 'baseBlock' ) , o = { block : getProperty ( decl , 'block' ) , mod : getProperty ( decl , 'modName' ) , val : getProperty ( decl , 'modVal' ) } ; if ( base ) { o . base = base ; } return o ; } }

Constructs a bem entity description
from first argument of `BEM.DOM.decl`

@param {Object} decl an AST node of a first argument of
BEM.DOM.decl
@returns {Object} bem entity description with `block`,
`mod`, and `val` keys

Constructs a bem entity description from first argument of BEM . DOM . decl


function getProperty(objNode, name) {
    for (var i=0; i<objNode.properties.length; i++) {
        if (getKey(objNode.properties[i]) === name) {
            return getValue(objNode.properties[i]);
        }
    }
}

function getProperty ( objNode , name ) { for ( var i = 0 ; i < objNode . properties . length ; i ++ ) { if ( getKey ( objNode . properties [ i ] ) === name ) { return getValue ( objNode . properties [ i ] ) ; } } }

Returns a value of property by name from
given object literal AST node

@param {Object} objNode an AST node of an object literal
(node.type is assumed to be equal to "ObjectExpression")
@param {String} name a name of a property to return


function getKey(propNode) {
    if (propNode.key.type === "Literal") {
        return propNode.key.value;
    }

    if (propNode.key.type === "Identifier") {
        return propNode.key.name;
    }
}

function getKey ( propNode ) { if ( propNode . key . type === "Literal" ) { return propNode . key . value ; } if ( propNode . key . type === "Identifier" ) { return propNode . key . name ; } }

Returns a key value of a property expression
@param {Object} propNode an AST node of a propery expression


function addDocletBemEntity(e) {
    var bemEntity = e.code.bemEntity;
    e.doclet.block = bemEntity.block;
    if (bemEntity.base) {
        e.doclet.baseBlock = bemEntity.base;
    }
    if (bemEntity.mod) {
        e.doclet.mod = {
            name: bemEntity.mod,
            value: bemEntity.val
        };
    }
}

function addDocletBemEntity ( e ) { var bemEntity = e . code . bemEntity ; e . doclet . block = bemEntity . block ; if ( bemEntity . base ) { e . doclet . baseBlock = bemEntity . base ; } if ( bemEntity . mod ) { e . doclet . mod = { name : bemEntity . mod , value : bemEntity . val } ; } }

Adds bem entity description to a doclet.
This method is called after doclet has
been constructed but before it sent to template.
Its required, because automatically inserted
`@block`, `@elem` and `@mod` keys does not
contain names.
@param {Object} e symbolFound event, generated from
`astNodeVisitor`. At this stage should already have
doclet property, which contains parsed docs.

Adds bem entity description to a doclet . This method is called after doclet has been constructed but before it sent to template . Its required because automatically inserted


function isStaticDecl(node) {
    var parent = node.parent;
    return hasStatic(parent) &&
        parent.arguments[2] === node;
}

function isStaticDecl ( node ) { var parent = node . parent ; return hasStatic ( parent ) && parent . arguments [ 2 ] === node ; }

Returns true if passed AST node is a static
methods declaration of BEM.DOM.decl
@param {Object} node an AST node of BEM.DOM.decl argument
@returns {Boolean}

Returns true if passed AST node is a static methods declaration of BEM . DOM . decl


function hasStatic(node) {
    var args = node.arguments;
    if (!args) {
        return false;
    }
    return args.length >= 3 &&
        args[1].type === "ObjectExpression" &&
        args[2].type === "ObjectExpression";
}

function hasStatic ( node ) { var args = node . arguments ; if ( ! args ) { return false ; } return args . length >= 3 && args [ 1 ] . type === "ObjectExpression" && args [ 2 ] . type === "ObjectExpression" ; }

Returns true if `BEM.DOM.decl` AST node has
static methods declaration.
@param {Object} node AST node of BEM.DOM.decl`
@return {Boolean}

Returns true if BEM . DOM . decl AST node has static methods declaration .


function getInputArguments(args) {
      var out = {};
      out.localServices = {};
      if (args.length > 0) {
         out.source = args[0];
         out.target = args[0];
         if (_.isPlainObject(args[0])) {
            var opts = args[0];
            out.target = opts.target;
            out.source = opts.source;
            out.instance = opts.instance;
         }
         // call(func, callback)
         if (args.length > 1) {
            var argsDefined = _.isString(args[0]) || _.isArray(args[0]);
            if (argsDefined) {
               if (_.isArray(args[0])) {
                  out.source = args[0];
               } else {
                  out.source = _.isString(args[0]) ? [args[0]] : args[0];
               }
               if (_.isFunction(args[1])) {
                  out.target = args[1];
               }
               if (_.isFunction(args[2])) {
                  out.target = args[2];
               }
            } else {

               if (_.isFunction(args[1])) {
                  out.callReady = args[1];
               }
               if (_.isPlainObject(args[1])) {
                  out.localServices = args[1];
               }
            }
         }
         if (args.length === 3) {
            if (_.isPlainObject(args[1])) {
               out.localServices = args[1];
            }
            if (_.isFunction(args[2])) {
               out.callReady = args[2];
            }
         }
      }
      out.target = out.target || function() {};
      out.source = out.source ? out.source : out.target;
      out.callReady = out.callReady || function() {};
      return out;
   }

function
getInputArguments
(
args
)
{
var
out
=
{
}
;
out
.
localServices
=
{
}
;
if
(
args
.
length
>
0
)
{
out
.
source
=
args
[
0
]
;
out
.
target
=
args
[
0
]
;
if
(
_
.
isPlainObject
(
args
[
0
]
)
)
{
var
opts
=
args
[
0
]
;
out
.
target
=
opts
.
target
;
out
.
source
=
opts
.
source
;
out
.
instance
=
opts
.
instance
;
}
// call(func, callback)
if
(
args
.
length
>
1
)
{
var
argsDefined
=
_
.
isString
(
args
[
0
]
)
||
_
.
isArray
(
args
[
0
]
)
;
if
(
argsDefined
)
{
if
(
_
.
isArray
(
args
[
0
]
)
)
{
out
.
source
=
args
[
0
]
;
}
else
{
out
.
source
=
_
.
isString
(
args
[
0
]
)
[
args
[
0
]
]
:
args
[
0
]
;
}
if
(
_
.
isFunction
(
args
[
1
]
)
)
{
out
.
target
=
args
[
1
]
;
}
if
(
_
.
isFunction
(
args
[
2
]
)
)
{
out
.
target
=
args
[
2
]
;
}
}
else
{
if
(
_
.
isFunction
(
args
[
1
]
)
)
{
out
.
callReady
=
args
[
1
]
;
}
if
(
_
.
isPlainObject
(
args
[
1
]
)
)
{
out
.
localServices
=
args
[
1
]
;
}
}
}
if
(
args
.
length
===
3
)
{
if
(
_
.
isPlainObject
(
args
[
1
]
)
)
{
out
.
localServices
=
args
[
1
]
;
}
if
(
_
.
isFunction
(
args
[
2
]
)
)
{
out
.
callReady
=
args
[
2
]
;
}
}
}
out
.
target
=
out
.
target
||
function
(
)
{
}
;
out
.
source
=
out
.
source
out
.
source
:
out
.
target
;
out
.
callReady
=
out
.
callReady
||
function
(
)
{
}
;
return
out
;
}

Extracts arguments and defined target for the require function


function findNext(data, items, index) {
    var currentIndex = data.length + 1, found = '';
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        var location = data.indexOf(item, index);
        if (location !== -1 && location < currentIndex) {
            currentIndex = location;
            found = item;
        }
    }
    if (currentIndex === data.length + 1) return { index: -1, found: '' };
    return {
        index: currentIndex,
        found: found
    };
}

function findNext ( data , items , index ) { var currentIndex = data . length + 1 , found = '' ; for ( var i = 0 ; i < items . length ; i ++ ) { var item = items [ i ] ; var location = data . indexOf ( item , index ) ; if ( location !== - 1 && location < currentIndex ) { currentIndex = location ; found = item ; } } if ( currentIndex === data . length + 1 ) return { index : - 1 , found : '' } ; return { index : currentIndex , found : found } ; }

Finds the next one of the items

@param {String} data The string to search
@param {Array<String>} items The items to find
@param {Number=0} index The start index
@returns {{index: Number, found: String}} The found index and the found item


function findLast(data, items, index) {
    var currentIndex = -1, found = '';
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        var location = data.lastIndexOf(item, index);
        if (location > currentIndex) {
            currentIndex = location;
            found = item;
        }
    }
    return {
        index: currentIndex,
        found: found
    };
}

function findLast ( data , items , index ) { var currentIndex = - 1 , found = '' ; for ( var i = 0 ; i < items . length ; i ++ ) { var item = items [ i ] ; var location = data . lastIndexOf ( item , index ) ; if ( location > currentIndex ) { currentIndex = location ; found = item ; } } return { index : currentIndex , found : found } ; }

Finds the last one of the items

@param {String} data The string to search
@param {Array<String>} items The items to find
@param {Number=0} index The end index
@returns {{index: number, found: string}} The found index and the found item


function findNextOutside(data, items, index, exclude) {
    var result, positionResult = {start: 0, end: index ? index - 1 : -1};

    do {
        result = findNext(data, items, positionResult.end + 1);
    } while (result.index !== -1 && (positionResult = inPosition(result.index, exclude)));
    return result;
}

function findNextOutside ( data , items , index , exclude ) { var result , positionResult = { start : 0 , end : index ? index - 1 : - 1 } ; do { result = findNext ( data , items , positionResult . end + 1 ) ; } while ( result . index !== - 1 && ( positionResult = inPosition ( result . index , exclude ) ) ) ; return result ; }

Finds the next one of the items outside of the given positions

@param {String} data The string to search
@param {Array<String>} items The items to find
@param {Number=0} index The start index
@param {Array<{start: Number, end: Number}>} exclude The boundaries to exclude
@returns {{index: Number, found: String}} The found index and the found item


function findLastOutside(data, items, index, exclude) {
    var result, positionResult = {start: index ? index + 1 : data.length + 1, end: 0};

    do {
        result = findLast(data, items, positionResult.start - 1);
    } while (result.index !== -1 && (positionResult = inPosition(result.index, exclude)));
    return result;
}

function findLastOutside ( data , items , index , exclude ) { var result , positionResult = { start : index ? index + 1 : data . length + 1 , end : 0 } ; do { result = findLast ( data , items , positionResult . start - 1 ) ; } while ( result . index !== - 1 && ( positionResult = inPosition ( result . index , exclude ) ) ) ; return result ; }

Finds the last one of the items outside of the given positions

@param {String} data The string to search
@param {Array<String>} items The items to find
@param {Number?} index The end index
@param {Array<{start: Number, end: Number}>} exclude The boundaries to exclude
@returns {{index: Number, found: String}} The found index and the found item


function indexOfOutside(data, item, index, exclude) {
    var result, positionResult = {start: 0, end: index ? index - 1 : -1};

    do {
        result = data.indexOf(item, positionResult.end + 1);
    } while (result !== -1 && (positionResult = inPosition(result, exclude)));
    return result;
}

function indexOfOutside ( data , item , index , exclude ) { var result , positionResult = { start : 0 , end : index ? index - 1 : - 1 } ; do { result = data . indexOf ( item , positionResult . end + 1 ) ; } while ( result !== - 1 && ( positionResult = inPosition ( result , exclude ) ) ) ; return result ; }

Finds the next index of the item outside of the given positions

@param {String} data The string to search
@param {String} item The item to find
@param {Number=0} index The start index
@param {Array<{start: Number, end: Number}>} exclude The boundaries to exclude
@returns {Number} The found index, or -1 if none found


function lastIndexOfOutside(data, item, index, exclude) {
    var result, positionResult = {start: index ? index + 1 : data.length + 1, end: 0};

    do {
        result = data.lastIndexOf(item, positionResult.start - 1);
    } while (result.index !== -1 && (positionResult = inPosition(result.index, exclude)));
    return result;
}

function lastIndexOfOutside ( data , item , index , exclude ) { var result , positionResult = { start : index ? index + 1 : data . length + 1 , end : 0 } ; do { result = data . lastIndexOf ( item , positionResult . start - 1 ) ; } while ( result . index !== - 1 && ( positionResult = inPosition ( result . index , exclude ) ) ) ; return result ; }

Finds the last index of the item outside of the given positions

@param {String} data The string to search
@param {String} item The item to find
@param {Number=data.length} index The end index
@param {Array<{start: Number, end: Number}>} exclude The boundaries to exclude
@returns {Number} The found index, or -1 if none found


function splitOutside(data, separator, exclude) {
    var result = [];

    var accumulator = "";
    for (var i = 0; i < data.length; i++) {
        accumulator += data[i];

        var isInExclusion = inPosition(i, exclude);
        if (!isInExclusion && endsWith(accumulator, separator)) {
            result.push(accumulator.substring(0, accumulator.length - separator.length));
            accumulator = '';
        }
    }
    result.push(accumulator);
    return result;
}

function splitOutside ( data , separator , exclude ) { var result = [ ] ; var accumulator = "" ; for ( var i = 0 ; i < data . length ; i ++ ) { accumulator += data [ i ] ; var isInExclusion = inPosition ( i , exclude ) ; if ( ! isInExclusion && endsWith ( accumulator , separator ) ) { result . push ( accumulator . substring ( 0 , accumulator . length - separator . length ) ) ; accumulator = '' ; } } result . push ( accumulator ) ; return result ; }

Splits data into an array by the separator, except if in the exclude regions

@param {String} data The string to split
@param {String} separator The separator
@param {Array<{start: Number, end: Number}>} exclude The boundaries to exclude
@returns {Array<String>} The separated array

Splits data into an array by the separator except if in the exclude regions


function inPosition(index, items) {
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (index >= item.start && index <= item.end) return item;
    }
    return false;
}

function inPosition ( index , items ) { for ( var i = 0 ; i < items . length ; i ++ ) { var item = items [ i ] ; if ( index >= item . start && index <= item . end ) return item ; } return false ; }

Finds if the index is inside one of the items
Items should be in the same format as returned from util.findPositions

@param {Number} index The index to check
@param {Array<{start: Number, end: Number}>} items The items to search
@returns {*} The start/end position if index is inside an item, else false

Finds if the index is inside one of the items Items should be in the same format as returned from util . findPositions


function endsWith(data, str) {
    if (data.length < str.length) return false;
    if (data === str) return true;
    return data.lastIndexOf(str) === data.length - str.length;
}

function endsWith ( data , str ) { if ( data . length < str . length ) return false ; if ( data === str ) return true ; return data . lastIndexOf ( str ) === data . length - str . length ; }

Finds if data ends with str

@param {String} data The text to search
@param {String} str The text to find
@returns {Boolean} whether data ends with str


function pad(data, length, pad) {
    data = String(data);
    pad = pad || ' ';
    while (data.length < length) data += pad;
    return data;
}

function
pad
(
data
,
length
,
pad
)
{
data
=
String
(
data
)
;
pad
=
pad
||
' '
;
while
(
data
.
length
<
length
)
data
+=
pad
;
return
data
;
}

Pads a string

@param {*} data The text to pad
@param {Number} length The padded length
@param {String?} pad The text to pad with, default is space
@returns {String}


function shallowClone(source, obj) {
    if (arguments.length < 2) {
        obj = source;
        source = {};
    }

    for (var key in obj) {
        if (!obj.hasOwnProperty(key)) continue;
        source[key] = obj[key];
    }
    return source;
}

function shallowClone ( source , obj ) { if ( arguments . length < 2 ) { obj = source ; source = { } ; } for ( var key in obj ) { if ( ! obj . hasOwnProperty ( key ) ) continue ; source [ key ] = obj [ key ] ; } return source ; }

Shallowly clones the object into the source object

@param {Object?} source The source object
@param {Object} obj The object to clone
@returns {Object} The source object


function() {
      var args = norma('path:s?', arguments);
      var _url = url.format(_.clone(this.url));
      var _path = (args.path || '').replace(/^\//, '');
      return url.resolve(_url, _path);
    }

function ( ) { var args = norma ( 'path:s?' , arguments ) ; var _url = url . format ( _ . clone ( this . url ) ) ; var _path = ( args . path || '' ) . replace ( / ^\/ / , '' ) ; return url . resolve ( _url , _path ) ; }


function nextLine(context, ast, prompt, oldPrompt, forceCursor, eval) {
    rl.question(prompt, function(answer) {
        eval(answer, context, ast, forceCursor === -1 ? ast.root.length : forceCursor, function(newPrompt, newCursor) {
            nextLine(context, ast, newPrompt || oldPrompt, oldPrompt, typeof newCursor === 'undefined' ? -1 : newCursor, eval);
        });
    });
}

function nextLine ( context , ast , prompt , oldPrompt , forceCursor , eval ) { rl . question ( prompt , function ( answer ) { eval ( answer , context , ast , forceCursor === - 1 ? ast . root . length : forceCursor , function ( newPrompt , newCursor ) { nextLine ( context , ast , newPrompt || oldPrompt , oldPrompt , typeof newCursor === 'undefined' ? - 1 : newCursor , eval ) ; } ) ; } ) ; }

Inputs and executes the next line

@param {ExecutionContext} context The current execution context
@param {AbstractSyntaxTree} ast The current abstract syntax tree
@param {String} prompt
@param {String} oldPrompt
@param {Number} forceCursor
@param {Function} eval The function to evaluate
@private


function initialize(done) {
    done = done || function() { };
    if (fileContents) done();

    fs.readFile(__dirname + '/../../data/filesystem.json', {
        encoding: 'utf8'
    }, function(err, data) {
        if (err) fileContents = {};
        else fileContents = JSON.parse(data);
        done();
    });
}

function initialize ( done ) { done = done || function ( ) { } ; if ( fileContents ) done ( ) ; fs . readFile ( __dirname + '/../../data/filesystem.json' , { encoding : 'utf8' } , function ( err , data ) { if ( err ) fileContents = { } ; else fileContents = JSON . parse ( data ) ; done ( ) ; } ) ; }

Initializes the file system

@param {Function?} done A callback for when initialization is complete


function save(done) {
    if (process.browser) return done();

    fs.writeFile(__dirname + '/../../data/filesystem.json', JSON.stringify(fileContents), function(err) {
        if (done) done(err);
    });
}

function save ( done ) { if ( process . browser ) return done ( ) ; fs . writeFile ( __dirname + '/../../data/filesystem.json' , JSON . stringify ( fileContents ) , function ( err ) { if ( done ) done ( err ) ; } ) ; }

Saves the filesystem

@param {Function?} done A function to call when complete


function (i, validate){
  // we offer a shortcut to get types when only one argument is provided
  if (arguments.length === 1) {
    return av.type(i);
  }

  // we store the value in private scope
  var _i;
  // our getter-setter-combo including validation
  var me = function (d){
    if (!arguments.length) {
      if (typeof _i === 'object'){
        var o = {};
        for (var prop in _i){
          o[prop] = _i[prop]();
        }
        return o;
      } else {
        return _i;
      }
    }
    _i = validate(d);
    // if _i is an object we expose the getter/setter methods of its attributes
    if (typeof _i === 'object'){
      for (var prop_object in _i){
        me[prop_object] = _i[prop_object];
      }
    }
  };
  // we initialize the getter-setter-combo with the provided value
  me(i);
  // return the getter-setter-combo (allows chaining, among other things)
  return me;
}

av's main function is a getter-setter-combo it expects a default value and a validation function the validation function should return the validated value or throw an exception it shouldn't return 'false' for non-validating values

av s main function is a getter - setter - combo it expects a default value and a validation function the validation function should return the validated value or throw an exception it shouldn t return false for non - validating values


function (d){
    if (!arguments.length) {
      if (typeof _i === 'object'){
        var o = {};
        for (var prop in _i){
          o[prop] = _i[prop]();
        }
        return o;
      } else {
        return _i;
      }
    }
    _i = validate(d);
    // if _i is an object we expose the getter/setter methods of its attributes
    if (typeof _i === 'object'){
      for (var prop_object in _i){
        me[prop_object] = _i[prop_object];
      }
    }
  }

our getter-setter-combo including validation

our getter - setter - combo including validation


function DimCommand(args) {
    var parsed = new statements.ArgumentStatement(args, {
        parseArgs: false
    });

    this.creates = [];

    for (var i = 0; i < parsed.args.length; i++) {
        var dimDef = parsed.args[i];
        var startBracket = dimDef.indexOf('(');
        var endBracket = dimDef.indexOf(')');

        if (startBracket === -1) throw new SyntaxError('Expected start bracket');
        if (endBracket === -1) throw new SyntaxError('Expected end bracket');

        var arrayName = dimDef.substring(0, startBracket).trim();
        var arrayLengthName = dimDef.substring(startBracket + 1, endBracket);
        var arrayLengthArg = new statements.ArgumentStatement(arrayLengthName);

        this.creates.push({
            name: arrayName,
            lengths: arrayLengthArg.args
        })
    }
}

function
DimCommand
(
args
)
{
var
parsed
=
new
statements
.
ArgumentStatement
(
args
,
{
parseArgs
:
false
}
)
;
this
.
creates
=
[
]
;
for
(
var
i
=
0
;
i
<
parsed
.
args
.
length
;
i
++
)
{
var
dimDef
=
parsed
.
args
[
i
]
;
var
startBracket
=
dimDef
.
indexOf
(
'('
)
;
var
endBracket
=
dimDef
.
indexOf
(
')'
)
;
if
(
startBracket
===
1
)
throw
new
SyntaxError
(
'Expected start bracket'
)
;
if
(
endBracket
===
1
)
throw
new
SyntaxError
(
'Expected end bracket'
)
;
var
arrayName
=
dimDef
.
substring
(
0
,
startBracket
)
.
trim
(
)
;
var
arrayLengthName
=
dimDef
.
substring
(
startBracket
+
1
,
endBracket
)
;
var
arrayLengthArg
=
new
statements
.
ArgumentStatement
(
arrayLengthName
)
;
this
.
creates
.
push
(
{
name
:
arrayName
,
lengths
:
arrayLengthArg
.
args
}
)
}
}

Declares one or more arrays

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


function genEntityDescription(data, kind, entityName) {
    return data({kind: kind, name: entityName}).select('description').join('\n\n');
}

function genEntityDescription ( data , kind , entityName ) { return data ( { kind : kind , name : entityName } ) . select ( 'description' ) . join ( '\n\n' ) ; }

Generates description for a bem entity by merging
doclets descriptions from all levels