Input: / * This file is part of the lps . js project released open source under the BSD 3 - Clause license . For more info please see https : // github . com / mauris / lps . js [CODESPLIT] function AstNode ( type , token ) { let _type = type ; let _token = token ; let _children = [ ] ; this . getType = function getType ( ) { return _type ; } ; this . getToken = function getToken ( ) { return _token ; } ; this . getChildren = function getChildren ( ) { return _children ; } ; this . setToken = function setToken ( t ) { _token = t ; } ; this . isLeaf = function isLeaf ( ) { return _children . length === 0 ; } ; this . addChild = function addChild ( childNode ) { _children . push ( childNode ) ; } ; this . print = function print ( nArg ) { let n = nArg ; if ( ! n ) { n = 0 ; } console . log ( ' ' . repeat ( n ) + String ( _type ) + ( _token ? ( ': ' + _token . value ) : '' ) ) ; n += 1 ; _children . forEach ( ( child ) => { child . print ( n ) ; } ) ; } ; }


Input: Construct the program arguments predicate [CODESPLIT] function ( programArgs ) { let _programArgs = programArgs ; if ( programArgs === undefined ) { _programArgs = [ ] ; } // map to values _programArgs = _programArgs . map ( arg => new Value ( arg ) ) ; let argsList = new List ( _programArgs ) ; let theta = { List : argsList } ; return programArgsPredicate . substitute ( theta ) ; }


Input: Create a function to update a given program with the given program arguments [CODESPLIT] function createProgramArgsUpdaterFunc ( programArgs ) { return ( program ) => { let programArgsFact = buildProgramArgsPredicate ( programArgs ) ; program . getFacts ( ) . add ( programArgsFact ) ; return Promise . resolve ( program ) ; } ; }


Input:
A list data representation [CODESPLIT] function List ( head , tail ) { let _head = head ; let _tail = tail ; let _variableHash = null ; if ( tail === undefined ) { // empty list for tail _tail = null ; } /**
   * Get the head of the list
   * @return {Array} Return the array representing the head of the list
   */ this . getHead = function getHead ( ) { return _head . concat ( ) ; } ; /**
   * Get the tail of the list
   * @return {Array|List|Variable} Return the tail representation of the list
   */ this . getTail = function getTail ( ) { return _tail ; } ; /**
   * Determine if the term is ground
   * @return {Boolean} Return true if the term is ground, false otherwise.
   */ this . isGround = function isGround ( ) { if ( _tail !== null ) { return _tail . isGround ( ) ; } for ( let i = 0 ; i < _head . length ; i += 1 ) { if ( ! _head [ i ] . isGround ( ) ) { return false ; } } return true ; } ; /**
   * Get all unique variables that occur in this term
   * @return {Array} Return the array of unique variables occuring in this term
   */ this . getVariables = function getVariables ( ) { return Object . keys ( this . getVariableHash ( ) ) ; } ; this . getVariableHash = function getVariableHash ( existingHash ) { let hash = existingHash ; if ( _variableHash !== null ) { if ( hash === undefined ) { return _variableHash ; } Object . keys ( _variableHash ) . forEach ( ( v ) => { hash [ v ] = true ; } ) ; return hash ; } // if we're writing into existing hash, don't store the hash if ( hash === undefined ) { hash = { } ; } let storedHash = { } ; const processArg = function processArg ( arg ) { arg . getVariableHash ( storedHash ) ; arg . getVariableHash ( hash ) ; } ; _head . forEach ( processArg ) ; if ( _tail instanceof List ) { processArg ( _tail ) ; } else if ( _tail instanceof Variable ) { storedHash [ _tail . evaluate ( ) ] = true ; hash [ _tail . evaluate ( ) ] = true ; } _variableHash = storedHash ; return hash ; } ; /**
   * Perform a substitution on this term.
   * @param  {Object} theta The substitution theta
   * @return {List}       Return the substituted list
   */ this . substitute = function substitute ( theta ) { let newHead = head . map ( ( element ) => { return element . substitute ( theta ) ; } ) ; let newTail = _tail ; if ( newTail instanceof List || newTail instanceof Variable ) { newTail = newTail . substitute ( theta ) ; } return new List ( newHead , newTail ) ; } ; /**
   * Create a flat representation of the list. If the tail of the list is a variable,
   * the empty list is assumed.
   * @return {Array} Return the flat array representation of the list
   */ this . flatten = function flatten ( ) { let result = [ ] ; if ( _head . length > 0 ) { result = result . concat ( _head ) ; if ( _tail instanceof List ) { result = result . concat ( _tail . flatten ( ) ) ; } } return result ; } ; /**
   * Determine if the list is empty
   * @return {Boolean} Return true if the list is empty, false otherwise.
   */ this . isEmpty = function isEmpty ( ) { return _head . length === 0 && ( _tail instanceof List && _tail . isEmpty ( ) ) ; } ; /**
   * Create a string representation of the term
   * @return {string} Return the string representation of the term
   */ this . toString = function toString ( ) { let result = '' ; result += '[' ; for ( let j = 0 ; j < _head . length ; j += 1 ) { result += _head [ j ] ; if ( j < _head . length - 1 ) { result += ', ' ; } } if ( _tail !== null && ( ! ( _tail instanceof List ) || ! _tail . isEmpty ( ) ) ) { result += '|' + _tail . toString ( ) ; } result += ']' ; return result ; } ; }


Input: eslint - disable - next - line no - unused - vars [CODESPLIT] function observeProcessor ( engine , program ) { let result = engine . query ( observeLiteral ) ; result . forEach ( ( r ) => { if ( r . theta . O === undefined || r . theta . ST === undefined || r . theta . ET === undefined ) { // ignoring those undefined ones return ; } let observation = r . theta . O ; let startTime = r . theta . ST ; let endTime = r . theta . ET ; if ( ! ( startTime instanceof Value ) ) { throw new Error ( stringLiterals ( [ 'declarationProcessors' , 'observe' , 'invalidStartTimeValue' ] ) ) ; } if ( ! ( endTime instanceof Value ) ) { throw new Error ( stringLiterals ( [ 'declarationProcessors' , 'observe' , 'invalidEndTimeValue' ] ) ) ; } let sTime = startTime . evaluate ( ) ; let eTime = endTime . evaluate ( ) ; if ( eTime < sTime ) { throw new Error ( stringLiterals ( [ 'declarationProcessors' , 'observe' , 'invalidTimeOrdering' ] ) ) ; } engine . scheduleObservation ( observation , sTime , eTime ) ; } ) ; }


Input: / * This file is part of the lps . js project released open source under the BSD 3 - Clause license . For more info please see https : // github . com / mauris / lps . js [CODESPLIT] function Manager ( ) { let _events = { } ; this . addListener = function addListener ( event , listener ) { if ( _events [ event ] === undefined ) { _events [ event ] = [ ] ; } _events [ event ] . push ( listener ) ; } ; this . clearListeners = function clearListeners ( event ) { delete _events [ event ] ; } ; this . notify = function notify ( event , sender ) { if ( _events [ event ] === undefined ) { return Promise . resolve ( ) ; } _events [ event ] . forEach ( ( listener ) => { listener ( sender ) ; } ) ; return Promise . resolve ( ) ; } ; }


Input: Process observations for the current cycle [CODESPLIT] function processCycleObservations ( ) { let activeObservations = new LiteralTreeMap ( ) ; if ( _observations [ _currentTime ] === undefined ) { // no observations for current time return activeObservations ; } let cloneProgram = _program . clone ( ) ; cloneProgram . setExecutedActions ( activeObservations ) ; const nextTime = _currentTime + 1 ; // process observations for the current time _observations [ _currentTime ] . forEach ( ( ob ) => { let action = ob . action ; let tempTreeMap = new LiteralTreeMap ( ) ; tempTreeMap . add ( action ) ; activeObservations . add ( action ) ; let postCloneProgram = cloneProgram . clone ( ) ; let postState = postCloneProgram . getState ( ) ; postCloneProgram . setExecutedActions ( new LiteralTreeMap ( ) ) ; updateStateWithFluentActors ( this , tempTreeMap , postState ) ; postCloneProgram . setState ( postState ) ; // perform pre-check and post-check if ( ! checkConstraintSatisfaction . call ( this , cloneProgram ) || ! checkConstraintSatisfaction . call ( this , postCloneProgram ) ) { // reject the observed event // to keep model true activeObservations . remove ( action ) ; // warning _engineEventManager . notify ( 'warning' , { type : 'observation.reject' , message : stringLiterals ( 'engine.rejectObservationWarning' , action , _currentTime , nextTime ) } ) ; } // if the given observation endTime has not ended // propagate to the next cycle's if ( ob . endTime > nextTime ) { if ( _observations [ nextTime ] === undefined ) { _observations [ nextTime ] = [ ] ; } _observations [ nextTime ] . push ( ob ) ; } } ) ; return activeObservations ; }


Input: Select the appropriate set of actions from the given goal trees such that constraints are not violated for the current cycle . [CODESPLIT] function actionsSelector ( goalTrees ) { const recursiveActionsSelector = ( actionsSoFar , programSoFar , l ) => { if ( l >= goalTrees . length ) { let actions = new LiteralTreeMap ( ) ; actionsSoFar . forEach ( ( map ) => { map . forEach ( ( literal ) => { actions . add ( literal ) ; } ) ; } ) ; return actions ; } let goalTree = goalTrees [ l ] ; let resultSet = null ; goalTree . forEachCandidateActions ( _currentTime , ( candidateActions ) => { let cloneProgram = programSoFar . clone ( ) ; let cloneExecutedActions = cloneProgram . getExecutedActions ( ) ; candidateActions . forEach ( ( a ) => { cloneExecutedActions . add ( a ) ; } ) ; // pre-condition check if ( ! checkConstraintSatisfaction . call ( this , cloneProgram ) ) { return false ; } // post condition checks let clonePostProgram = programSoFar . clone ( ) ; clonePostProgram . setExecutedActions ( new LiteralTreeMap ( ) ) ; let postState = clonePostProgram . getState ( ) ; updateStateWithFluentActors ( this , candidateActions , postState ) ; clonePostProgram . setState ( postState ) ; if ( ! checkConstraintSatisfaction . call ( this , clonePostProgram ) ) { return false ; } resultSet = recursiveActionsSelector ( actionsSoFar . concat ( [ candidateActions ] ) , cloneProgram , l + 1 ) ; return true ; } ) ; if ( resultSet !== null ) { return resultSet ; } return recursiveActionsSelector ( actionsSoFar , programSoFar , l + 1 ) ; } ; return recursiveActionsSelector ( [ ] , _program , 0 ) ; }


Input: Performs the state transition for a single cycle . [CODESPLIT] function performCycle ( ) { _currentTime += 1 ; let selectedAndExecutedActions = new LiteralTreeMap ( ) ; let executedObservations = new LiteralTreeMap ( ) ; // Step 0 - Updating database let updatedState = _program . getState ( ) . clone ( ) ; updateStateWithFluentActors ( this , _program . getExecutedActions ( ) , updatedState ) ; _program . setState ( updatedState ) ; _nextCycleObservations . forEach ( ( obs ) => { executedObservations . add ( obs ) ; } ) ; _nextCycleActions . forEach ( ( act ) => { selectedAndExecutedActions . add ( act ) ; } ) ; // Step 1 - Processing rules let newFiredGoals = processRules ( this , _program , _currentTime , _profiler ) ; _goals = _goals . concat ( newFiredGoals ) ; // Step 3 - Processing return evaluateGoalTrees ( _currentTime , _goals , _profiler ) . then ( ( newGoals ) => { _goals = newGoals ; // Start preparation for next cycle // reset the set of executed actions _program . setExecutedActions ( new LiteralTreeMap ( ) ) ; _goals . sort ( goalTreeSorter ( _currentTime ) ) ; // select actions from candidate actions return actionsSelector . call ( this , _goals ) ; } ) . then ( ( nextCycleActions ) => { _nextCycleActions = new LiteralTreeMap ( ) ; nextCycleActions . forEach ( ( l ) => { _nextCycleActions . add ( l ) ; } ) ; _nextCycleObservations = new LiteralTreeMap ( ) ; let cycleObservations = processCycleObservations . call ( this ) ; cycleObservations . forEach ( ( observation ) => { nextCycleActions . add ( observation ) ; _nextCycleObservations . add ( observation ) ; } ) ; _program . setExecutedActions ( nextCycleActions ) ; _lastCycleActions = selectedAndExecutedActions ; _lastCycleObservations = executedObservations ; // done with cycle return Promise . resolve ( ) ; } ) ; }


Input: converts native arguments object to an array and applies function [CODESPLIT] function applyArgs ( func , thisObj , args ) { return func . apply ( thisObj , Array . prototype . slice . call ( args ) ) ; }


Input: defines a flow given any number of functions as arguments [CODESPLIT] function define ( ) { var thisFlow = function ( ) { applyArgs ( thisFlow . exec , thisFlow , arguments ) ; } thisFlow . blocks = arguments ; thisFlow . exec = function ( ) { // The flowState is the actual object each step in the flow is applied to. It acts as a // callback to the next function. It also maintains the internal state of each execution // and acts as a place for users to save values between steps of the flow. var flowState = function ( ) { if ( flowState . __frozen ) return ; if ( flowState . __timeoutId ) { clearTimeout ( flowState . __timeoutId ) ; delete flowState . __timeoutId ; } var blockIdx = flowState . __nextBlockIdx ++ ; var block = thisFlow . blocks [ blockIdx ] ; if ( block === undefined ) { return ; } else { applyArgs ( block , flowState , arguments ) ; } } // __nextBlockIdx specifies which function is the next step in the flow. flowState . __nextBlockIdx = 0 ; // __multiCount is incremented every time MULTI is used to createa a multiplexed callback flowState . __multiCount = 0 ; // __multiOutputs accumulates the arguments of each call to callbacks generated by MULTI flowState . __multiOutputs = [ ] ; // REWIND signals that the next call to thisFlow should repeat this step. It allows you // to create serial loops. flowState . REWIND = function ( ) { flowState . __nextBlockIdx -= 1 ; } // MULTI can be used to generate callbacks that must ALL be called before the next step // in the flow is executed. Arguments to those callbacks are accumulated, and an array of // of those arguments objects is sent as the one argument to the next step in the flow. // @param {String} resultId An identifier to get the result of a multi call. flowState . MULTI = function ( resultId ) { flowState . __multiCount += 1 ; return function ( ) { flowState . __multiCount -= 1 ; flowState . __multiOutputs . push ( arguments ) ; if ( resultId ) { var result = arguments . length <= 1 ? arguments [ 0 ] : arguments flowState . __multiOutputs [ resultId ] = result ; } if ( flowState . __multiCount === 0 ) { var multiOutputs = flowState . __multiOutputs ; flowState . __multiOutputs = [ ] ; flowState ( multiOutputs ) ; } } } // TIMEOUT sets a timeout that freezes a flow and calls the provided callback. This // timeout is cleared if the next flow step happens first. flowState . TIMEOUT = function ( milliseconds , timeoutCallback ) { if ( flowState . __timeoutId !== undefined ) { throw new Error ( "timeout already set for this flow step" ) ; } flowState . __timeoutId = setTimeout ( function ( ) { flowState . __frozen = true ; timeoutCallback ( ) ; } , milliseconds ) ; } applyArgs ( flowState , this , arguments ) ; } return thisFlow ; }


Input: The flowState is the actual object each step in the flow is applied to . It acts as a callback to the next function . It also maintains the internal state of each execution and acts as a place for users to save values between steps of the flow . [CODESPLIT] function ( ) { if ( flowState . __frozen ) return ; if ( flowState . __timeoutId ) { clearTimeout ( flowState . __timeoutId ) ; delete flowState . __timeoutId ; } var blockIdx = flowState . __nextBlockIdx ++ ; var block = thisFlow . blocks [ blockIdx ] ; if ( block === undefined ) { return ; } else { applyArgs ( block , flowState , arguments ) ; } }


Input: defines a flow and evaluates it immediately . The first flow function won t receive any arguments . [CODESPLIT] function exec ( ) { var flow = typeof exports != 'undefined' ? exports : window . flow ; applyArgs ( flow . define , flow , arguments ) ( ) ; }


Input: helper methods [CODESPLIT] function anyError ( results ) { var r , _i , _len ; for ( _i = 0 , _len = results . length ; _i < _len ; _i ++ ) { r = results [ _i ] ; if ( r [ 0 ] ) { return r [ 0 ] ; } } return null ; }


Input: Pads supplied string with character to fill the desired length . [CODESPLIT] function padStart ( str , length , padChar ) { if ( str . length >= length ) { return str ; } else { return padChar . repeat ( length - str . length ) + str ; } }


Input: The SM2 elliptic curve [CODESPLIT] function SM2Curve ( params ) { if ( ! ( this instanceof SM2Curve ) ) { return new SM2Curve ( params ) ; } elliptic . curve . short . call ( this , params ) ; }


Input: Return a point on the curve . Will throw error if ( x y ) is not on curve . [CODESPLIT] function _sm2Point ( x , y , parity ) { if ( x == null ) { return SM2 . point ( ) ; } var pt ; if ( y != null ) { pt = SM2 . point ( x , y ) ; if ( ! SM2 . validate ( pt ) ) { throw 'point is not on curve' ; } } else { var px = new BN ( x , 16 ) . toRed ( SM2 . red ) ; var py = px . redSqr ( ) . redMul ( px ) ; py = py . redIAdd ( px . redMul ( SM2 . a ) ) . redIAdd ( SM2 . b ) . redSqrt ( ) ; if ( ( parity === 'odd' ) != py . fromRed ( ) . isOdd ( ) ) { py = py . redNeg ( ) ; } pt = SM2 . point ( px , py ) ; } return pt ; }


Input: SM2 public and private key pair [CODESPLIT] function SM2KeyPair ( pub , pri ) { if ( ! ( this instanceof SM2KeyPair ) ) { return new SM2KeyPair ( pub , pri ) ; } this . curve = SM2 ; // curve parameter this . pub = null ; // public key, should be a point on the curve this . pri = null ; // private key, should be a integer var validPub = false ; var validPri = false ; if ( pub != null ) { if ( typeof pub === 'string' ) { this . _pubFromString ( pub ) ; } else if ( Array . isArray ( pub ) ) { this . _pubFromBytes ( pub ) ; } else if ( 'x' in pub && pub . x instanceof BN && 'y' in pub && pub . y instanceof BN ) { // pub is already the Point object this . pub = pub ; validPub = true ; } else { throw 'invalid public key' ; } } if ( pri != null ) { if ( typeof pri === 'string' ) { this . pri = new BN ( pri , 16 ) ; } else if ( pri instanceof BN ) { this . pri = pri ; validPri = true ; } else { throw 'invalid private key' ; } // calculate public key if ( this . pub == null ) { this . pub = SM2 . g . mul ( this . pri ) ; } } if ( ! ( validPub && validPri ) && ! this . validate ( ) ) { throw 'invalid key' ; } }


Input: / * ------------------------------------------------------------------ Constructor : EnoceanUtils () ---------------------------------------------------------------- [CODESPLIT] function ( ) { this . _default_baud_rate = 57600 ; this . _baud_rate = 57600 ; this . _path = '' ; this . _devices = { } ; this . _port = null ; this . _telegram_buffer = null ; this . _gateway = null ; mEventEmitter . call ( this ) ; }


Input: plugin wrapper so streams can pipe to it . [CODESPLIT] function gulpStaticI18n ( options ) { return through . obj ( function ( target , encoding , cb ) { var stream = this ; var build = new StaticI18n ( target , options , stream ) ; build . translate ( cb ) ; } ) ; }


Input: Add an event to an object and optionally adjust it s scope [CODESPLIT] function ( obj , type , fn , scope ) { scope = scope || obj ; var wrappedFn = function ( e ) { fn . call ( scope , e ) ; } ; obj . addEventListener ( type , wrappedFn , false ) ; cache . push ( [ obj , type , fn , wrappedFn ] ) ; }


Input: Remove an event from an object [CODESPLIT] function ( obj , type , fn ) { var wrappedFn , item , len = cache . length , i ; for ( i = 0 ; i < len ; i ++ ) { item = cache [ i ] ; if ( item [ 0 ] === obj && item [ 1 ] === type && item [ 2 ] === fn ) { wrappedFn = item [ 3 ] ; if ( wrappedFn ) { obj . removeEventListener ( type , wrappedFn , false ) ; cache = cache . slice ( i ) ; return true ; } } } }


Input: Add an event to an object and optionally adjust it s scope ( IE ) [CODESPLIT] function ( obj , type , fn , scope ) { scope = scope || obj ; var wrappedFn = function ( ) { var e = window . event ; e . target = e . target || e . srcElement ; e . preventDefault = function ( ) { e . returnValue = false ; } ; fn . call ( scope , e ) ; } ; obj . attachEvent ( 'on' + type , wrappedFn ) ; cache . push ( [ obj , type , fn , wrappedFn ] ) ; }


Input: Remove an event from an object ( IE ) [CODESPLIT] function ( obj , type , fn ) { var wrappedFn , item , len = cache . length , i ; for ( i = 0 ; i < len ; i ++ ) { item = cache [ i ] ; if ( item [ 0 ] === obj && item [ 1 ] === type && item [ 2 ] === fn ) { wrappedFn = item [ 3 ] ; if ( wrappedFn ) { obj . detachEvent ( 'on' + type , wrappedFn ) ; cache = cache . slice ( i ) ; return true ; } } } }


Input: Creates a view model . [CODESPLIT] function View ( model ) { var wrapper ; this . el = wrapper = document . createElement ( 'div' ) ; this . model = model ; this . isShowing = false ; // HTML wrapper . id = config . name ; config . parent . appendChild ( wrapper ) ; // CSS css . inject ( document . getElementsByTagName ( 'head' ) [ 0 ] , config . styles ) ; // JavaScript events . add ( document , ( 'ontouchstart' in window ) ? 'touchstart' : 'click' , viewevents . click , this ) ; events . add ( document , 'keyup' , viewevents . keyup , this ) ; events . add ( document , 'readystatechange' , viewevents . readystatechange , this ) ; events . add ( window , 'pageshow' , viewevents . pageshow , this ) ; }


Input: Creates a new product . [CODESPLIT] function Product ( data ) { data . quantity = parser . quantity ( data . quantity ) ; data . amount = parser . amount ( data . amount ) ; data . href = parser . href ( data . href ) ; this . _data = data ; this . _options = null ; this . _discount = null ; this . _amount = null ; this . _total = null ; Pubsub . call ( this ) ; }


Input: Renders the Mini Cart to the page s DOM . [CODESPLIT] function Cart ( name , duration ) { var data , items , settings , len , i ; this . _items = [ ] ; this . _settings = { bn : constants . BN } ; Pubsub . call ( this ) ; Storage . call ( this , name , duration ) ; if ( ( data = this . load ( ) ) ) { items = data . items ; settings = data . settings ; if ( settings ) { this . _settings = settings ; } if ( items ) { for ( i = 0 , len = items . length ; i < len ; i ++ ) { this . add ( items [ i ] ) ; } } } }


Input: / * Builds the project with ant . Returns a promise . [CODESPLIT] function ( opts ) { // Without our custom_rules.xml, we need to clean before building. var ret = Q ( ) ; if ( ! hasCustomRules ( ) ) { // clean will call check_ant() for us. ret = this . clean ( opts ) ; } var args = this . getArgs ( opts . buildType == 'debug' ? 'debug' : 'release' , opts ) ; return check_reqs . check_ant ( ) . then ( function ( ) { console . log ( 'Executing: ant ' + args . join ( ' ' ) ) ; return spawn ( 'ant' , args ) ; } ) ; }


Input: / * Builds the project with gradle . Returns a promise . [CODESPLIT] function ( opts ) { var wrapper = path . join ( ROOT , 'gradlew' ) ; var args = this . getArgs ( opts . buildType == 'debug' ? 'debug' : 'release' , opts ) ; return Q ( ) . then ( function ( ) { console . log ( 'Running: ' + wrapper + ' ' + args . join ( ' ' ) ) ; return spawn ( wrapper , args ) ; } ) ; }


Input: on rejection either retry or throw the error [CODESPLIT] function onRejected ( error ) { attemts_left -= 1 ; if ( attemts_left < 1 ) { throw error ; } console . log ( "A retried call failed. Retrying " + attemts_left + " more time(s)." ) ; // retry call self again with the same arguments, except attemts_left is now lower var fullArguments = [ attemts_left , promiseFunction ] . concat ( promiseFunctionArguments ) ; return module . exports . retryPromise . apply ( undefined , fullArguments ) ; }


Input: this is the function for full tree / * function collectDependencies ( bowerJson ) { var dependencies = [] ; if ( bowerJson ! = null && bowerJson ! = undefined ) { if ( bowerJson . hasOwnProperty ( dependencies )) { var dependenciesJson = bowerJson . dependencies ; var dependencisKeys = Object . keys ( dependenciesJson ) ; var key ; for ( key in dependencisKeys ) { var dependecyJson = dependenciesJson [ dependencisKeys [ key ]] ; var dependency = createDependency ( dependecyJson ) ; if ( dependency ! = null ) { dependency . children = collectDependencies ( dependecyJson ) ; dependencies . push ( dependency ) ; } } } } return dependencies ; } [CODESPLIT] function collectDependencies ( bowerJson , dependencies ) { if ( bowerJson != null && bowerJson != undefined ) { if ( bowerJson . hasOwnProperty ( "dependencies" ) ) { var dependenciesJson = bowerJson . dependencies ; var dependencisKeys = Object . keys ( dependenciesJson ) ; var key ; for ( key in dependencisKeys ) { var dependecyJson = dependenciesJson [ dependencisKeys [ key ] ] ; var dependency = createDependency ( dependecyJson ) ; if ( dependency != null ) { dependencies . push ( dependency ) ; collectDependencies ( dependecyJson , dependencies ) ; } } } } }


Input: Create a tree with optional deep paths and create new blobs . Entries is an array of { mode path hash|content } Also deltas can be specified by setting entries . base to the hash of a tree in delta mode entries can be removed by specifying just { path } [CODESPLIT] function createTree ( entries , callback ) { if ( ! callback ) return createTree . bind ( repo , entries ) ; var toDelete = entries . base && entries . filter ( function ( entry ) { return ! entry . mode ; } ) . map ( function ( entry ) { return entry . path ; } ) ; var toCreate = entries . filter ( function ( entry ) { return bodec . isBinary ( entry . content ) ; } ) ; if ( ! toCreate . length ) return next ( ) ; var done = false ; var left = entries . length ; toCreate . forEach ( function ( entry ) { repo . saveAs ( "blob" , entry . content , function ( err , hash ) { if ( done ) return ; if ( err ) { done = true ; return callback ( err ) ; } delete entry . content ; entry . hash = hash ; left -- ; if ( ! left ) next ( ) ; } ) ; } ) ; function next ( err ) { if ( err ) return callback ( err ) ; if ( toDelete && toDelete . length ) { return slowUpdateTree ( entries , toDelete , callback ) ; } return fastUpdateTree ( entries , callback ) ; } }


Input: Github doesn t support deleting entries via the createTree API so we need to manually create those affected trees and modify the request . [CODESPLIT] function slowUpdateTree ( entries , toDelete , callback ) { callback = singleCall ( callback ) ; var root = entries . base ; var left = 0 ; // Calculate trees that need to be re-built and save any provided content. var parents = { } ; toDelete . forEach ( function ( path ) { var parentPath = path . substr ( 0 , path . lastIndexOf ( "/" ) ) ; var parent = parents [ parentPath ] || ( parents [ parentPath ] = { add : { } , del : [ ] } ) ; var name = path . substr ( path . lastIndexOf ( "/" ) + 1 ) ; parent . del . push ( name ) ; } ) ; var other = entries . filter ( function ( entry ) { if ( ! entry . mode ) return false ; var parentPath = entry . path . substr ( 0 , entry . path . lastIndexOf ( "/" ) ) ; var parent = parents [ parentPath ] ; if ( ! parent ) return true ; var name = entry . path . substr ( entry . path . lastIndexOf ( "/" ) + 1 ) ; if ( entry . hash ) { parent . add [ name ] = { mode : entry . mode , hash : entry . hash } ; return false ; } left ++ ; repo . saveAs ( "blob" , entry . content , function ( err , hash ) { if ( err ) return callback ( err ) ; parent . add [ name ] = { mode : entry . mode , hash : hash } ; if ( ! -- left ) onParents ( ) ; } ) ; return false ; } ) ; if ( ! left ) onParents ( ) ; function onParents ( ) { Object . keys ( parents ) . forEach ( function ( parentPath ) { left ++ ; // TODO: remove this dependency on pathToEntry repo . pathToEntry ( root , parentPath , function ( err , entry ) { if ( err ) return callback ( err ) ; var tree = entry . tree ; var commands = parents [ parentPath ] ; commands . del . forEach ( function ( name ) { delete tree [ name ] ; } ) ; for ( var name in commands . add ) { tree [ name ] = commands . add [ name ] ; } repo . saveAs ( "tree" , tree , function ( err , hash , tree ) { if ( err ) return callback ( err ) ; other . push ( { path : parentPath , hash : hash , mode : modes . tree } ) ; if ( ! -- left ) { other . base = entries . base ; if ( other . length === 1 && other [ 0 ] . path === "" ) { return callback ( null , hash , tree ) ; } fastUpdateTree ( other , callback ) ; } } ) ; } ) ; } ) ; } }


Input: GitHub has a nasty habit of stripping whitespace from messages and losing the timezone . This information is required to make our hashes match up so we guess it by mutating the value till the hash matches . If we re unable to match we will just force the hash when saving to the cache . [CODESPLIT] function fixDate ( type , value , hash ) { if ( type !== "commit" && type !== "tag" ) return ; // Add up to 3 extra newlines and try all 30-minutes timezone offsets. var clone = JSON . parse ( JSON . stringify ( value ) ) ; for ( var x = 0 ; x < 3 ; x ++ ) { for ( var i = - 720 ; i < 720 ; i += 30 ) { if ( type === "commit" ) { clone . author . date . offset = i ; clone . committer . date . offset = i ; } else if ( type === "tag" ) { clone . tagger . date . offset = i ; } if ( hash !== hashAs ( type , clone ) ) continue ; // Apply the changes and return. value . message = clone . message ; if ( type === "commit" ) { value . author . date . offset = clone . author . date . offset ; value . committer . date . offset = clone . committer . date . offset ; } else if ( type === "tag" ) { value . tagger . date . offset = clone . tagger . date . offset ; } return true ; } clone . message += "\n" ; } return false ; }


Input: Note on viewbox / width This methods only work when the pixels match the svg units . when the viewbox is changed or width is set they won t return the correct results Returns the global coordinates of a position given for a specific coordinate system [CODESPLIT] function toGlobalCoordinates ( svgdoc : any , elem : any , x : number , y : number ) { var offset = svgdoc . getBoundingClientRect ( ) ; var matrix = elem . getScreenCTM ( ) ; return { x : matrix . a * x + matrix . c * y + matrix . e - offset . left , y : matrix . b * x + matrix . d * y + matrix . f - offset . top } ; }


Input: Returns the angle ( degrees ) given a point . Assumes 0 0 as the center of the circle [CODESPLIT] function getAngleForPoint ( x : number , y : number ) { if ( x == 0 && y == 0 ) return 0 ; const angle = Math . atan ( x / y ) ; let angleDeg = angle * 180 / Math . PI ; //The final value depends on the quadrant const quadrant = getQuadrant ( x , y ) ; if ( quadrant === 1 ) { angleDeg = 90 - angleDeg ; } if ( quadrant === 2 ) { angleDeg = 90 - angleDeg ; } if ( quadrant === 3 ) { angleDeg = 270 - angleDeg ; } if ( quadrant === 4 ) { angleDeg = 270 - angleDeg ; } return angleDeg ; }


Input: Transforms the top / left variables of the rectangle returned by getBoundingClientRect to document based coordinates without the scroll . UPDATE [CODESPLIT] function transformBoundingClientRectToDocument ( box ) { var t ; const scrollX = ( ( ( t = document . documentElement ) || ( t = document . body . parentNode ) ) && typeof t . scrollLeft == "number" ? t : document . body ) . scrollLeft ; const scrollY = ( ( ( t = document . documentElement ) || ( t = document . body . parentNode ) ) && typeof t . scrollTop == "number" ? t : document . body ) . scrollTop ; //This assumes width == height const ttop = box . top - scrollY ; const tleft = box . left - scrollX ; //info needed to draw line from center to mousepos return { top : ttop , left : tleft , width : box . width , height : box . height } }


Input: / * This method must be called once during initialization . It sets the behaviour of the naked bar in case of one handle . [CODESPLIT] function ( position , handleWidth ) { if ( position === "stickToSides" ) { _naked_bar_deltas = { toEndWidth : handleWidth , toBeginLeft : 0 , toBeginWidth : handleWidth } ; } else if ( position === "middle" ) { // Position naked end of the bar at the middle value. _naked_bar_deltas = { toEndWidth : handleWidth / 2 , toBeginLeft : handleWidth / 2 , toBeginWidth : handleWidth / 2 } ; } else { throw new Error ( 'unknown position of setNakedBarDelta: ' + position ) ; } }


Input: / * Move slider grips to the specified position . This method is designed to run within the user interaction lifecycle . Only call this method if the user has interacted with the sliders actually ... [CODESPLIT] function ( nextLeftGripPositionPx , nextRightGripPositionPx ) { var $this = this ; var draggableAreaLengthPx = _methods . getSliderWidthPx . call ( $this ) - $this . data ( 'left_grip_width' ) ; // // Validate & Move // if ( nextRightGripPositionPx <= draggableAreaLengthPx && nextLeftGripPositionPx >= 0 && nextLeftGripPositionPx <= draggableAreaLengthPx && ( ! $this . data ( 'has_right_grip' ) || nextLeftGripPositionPx <= nextRightGripPositionPx ) ) { var prevMin = $this . data ( 'cur_min' ) , prevMax = $this . data ( 'cur_max' ) ; // note: also stores new cur_min, cur_max _methods . set_position_from_px . call ( $this , nextLeftGripPositionPx , nextRightGripPositionPx ) ; // set the style of the grips according to the highlighted range _methods . refresh_grips_style . call ( $this ) ; _methods . notify_changed_implicit . call ( $this , 'drag_move' , prevMin , prevMax ) ; } return $this ; }


Input: / * Update aria attributes of the slider based on the current configuration of the slider . [CODESPLIT] function ( ) { var $this = this , settings = $this . data ( 'settings' ) , $leftGrip = $this . find ( settings . left_grip_selector ) ; // // double grips sliders is probably the most common case... // ... also, the values to be set in the two cases are quite // different. // if ( $this . data ( 'has_right_grip' ) ) { var $rightGrip = $this . find ( settings . right_grip_selector ) ; // // grips are mutually binding their max/min values when 2 grips // are present. For example, we should imagine the left grip as // being constrained between [ rangeMin, valueMax ] // $leftGrip . attr ( 'aria-valuemin' , $this . data ( 'range_min' ) ) . attr ( 'aria-valuenow' , methods . get_current_min_value . call ( $this ) ) . attr ( 'aria-valuemax' , methods . get_current_max_value . call ( $this ) ) ; $rightGrip . attr ( 'aria-valuemin' , methods . get_current_min_value . call ( $this ) ) . attr ( 'aria-valuenow' , methods . get_current_max_value . call ( $this ) ) . attr ( 'aria-valuemax' , $this . data ( 'range_max' ) ) ; } else { $leftGrip . attr ( 'aria-valuemin' , $this . data ( 'range_min' ) ) . attr ( 'aria-valuenow' , methods . get_current_min_value . call ( $this ) ) . attr ( 'aria-valuemax' , $this . data ( 'range_max' ) ) ; } return $this ; }


Input: / * Return the position of the right Grip if it exists or return the current position if not . Even if the right grip doesn t exist its position should be defined as it determines the position of the bar . [CODESPLIT] function ( ) { var $this = this , settings = $this . data ( 'settings' ) ; if ( $this . data ( 'has_right_grip' ) ) { return _methods . getGripPositionPx . call ( $this , $this . find ( settings . right_grip_selector ) ) ; } // default var sliderWidthPx = _methods . getSliderWidthPx . call ( $this ) - $this . data ( 'left_grip_width' ) ; return _methods . rangemap_0_to_n . call ( $this , $this . data ( 'cur_max' ) , sliderWidthPx ) ; }


Input: / * Perform binary search to find searchElement into a generic array . It uses a customized compareFunc to perform the comparison between two elements of the array and a getElement function to pick the element from the array ( e . g . in case we want to pick a field of an array of objects ) [CODESPLIT] function ( array , searchElement , getElementFunc , compareFunc ) { var minIndex = 0 ; var maxIndex = array . length - 1 ; var currentIndex ; var currentElement ; while ( minIndex <= maxIndex ) { currentIndex = ( minIndex + maxIndex ) / 2 | 0 ; currentElement = getElementFunc ( array , currentIndex ) ; // lt = -1 (searchElement < currentElement) // eq = 0  // gt = 1  (searchElement > currentElement) var lt_eq_gt = compareFunc ( searchElement , array , currentIndex ) ; if ( lt_eq_gt > 0 ) { minIndex = currentIndex + 1 ; } else if ( lt_eq_gt < 0 ) { maxIndex = currentIndex - 1 ; } else { return currentIndex ; } } return - 1 ; }


Input: / * Returns true if this slider has limit false otherwise . There can be an upper limit and a lower limit for the sliders . The lower / upper limits are values that are out of the slider range but that can be selected by the user when he moves a slider all the way down the minimum and up to the maximum value . [CODESPLIT] function ( ) { var $this = this , lowerLimit = $this . data ( 'lower-limit' ) , upperLimit = $this . data ( 'upper-limit' ) , haveLimits = false ; if ( typeof lowerLimit !== 'undefined' && typeof upperLimit !== 'undefined' ) { haveLimits = true ; } return haveLimits ; }


Input: / * This method is called whenever the style of the grips needs to get updated . [CODESPLIT] function ( ) { var $this = this , settings = $this . data ( 'settings' ) ; // Skip refreshing grips style if no hihglight is specified in // construction if ( typeof settings . highlight === 'undefined' ) { return ; } var highlightedRangeMin = $this . data ( 'highlightedRangeMin' ) ; if ( typeof highlightedRangeMin === 'undefined' ) { return ; } var $leftGrip = $this . find ( settings . left_grip_selector ) , $rightGrip = $this . find ( settings . right_grip_selector ) , highlightedRangeMax = $this . data ( 'highlightedRangeMax' ) , curMin = $this . data ( 'cur_min' ) , curMax = $this . data ( 'cur_max' ) , highlightGripClass = settings . highlight . grip_class ; // curmin is within the highlighted range if ( curMin < highlightedRangeMin || curMin > highlightedRangeMax ) { // de-highlight grip $leftGrip . removeClass ( highlightGripClass ) ; } else { // highlight grip $leftGrip . addClass ( highlightGripClass ) ; } // time to highlight right grip if ( curMax < highlightedRangeMin || curMax > highlightedRangeMax ) { // de-highlight grip $rightGrip . removeClass ( highlightGripClass ) ; } else { // highlight grip $rightGrip . addClass ( highlightGripClass ) ; } }


Input: / * Set left and right handle at the right position on the screen ( pixels ) given the desired position in currency . [CODESPLIT] function ( cur_min , cur_max ) { var $this = this ; //  // We need to understand how much pixels cur_min and cur_max // correspond. // var range_min = $this . data ( 'range_min' ) , range_max = $this . data ( 'range_max' ) ; // // (safety) constrain the cur_min or the cur_max value between the // max/min ranges allowed for this slider. // if ( cur_min < range_min ) { cur_min = range_min ; } if ( cur_min > range_max ) { cur_min = range_max ; } if ( $this . data ( 'has_right_grip' ) ) { if ( cur_max > range_max ) { cur_max = range_max ; } if ( cur_max < range_min ) { cur_max = range_min ; } } else { cur_max = $this . data ( 'cur_max' ) ; } var leftPx = methods . value_to_px . call ( $this , cur_min ) , rightPx = methods . value_to_px . call ( $this , cur_max ) ; _methods . set_handles_at_px . call ( $this , leftPx , rightPx ) ; // save this position $this . data ( 'cur_min' , cur_min ) ; if ( $this . data ( 'has_right_grip' ) ) { $this . data ( 'cur_max' , cur_max ) ; } return $this ; }


Input: / * Set the position of the handles at the specified pixel points ( taking the whole slider width as a maximum point ) . [CODESPLIT] function ( leftPx , rightPx ) { var $this = this ; // // we need to find a value from the given value in pixels // // now set the position as requested... _methods . set_handles_at_px . call ( $this , leftPx , rightPx ) ; var valueLeftRight = _methods . getSliderValuesAtPositionPx . call ( $this , leftPx , rightPx ) , leftPxInValue = valueLeftRight [ 0 ] , rightPxInValue = valueLeftRight [ 1 ] ; // ... and save the one we've found. $this . data ( 'cur_min' , leftPxInValue ) ; if ( $this . data ( 'has_right_grip' ) ) { $this . data ( 'cur_max' , rightPxInValue ) ; } return $this ; }


Input: / * Updates the CSS of grips and bar so that the left grip appears at leftPx and the right grip appears at rightPx . Note : leftPx can be > rightPx . [CODESPLIT] function ( leftPx , rightPx ) { var $this = this ; var settings = $this . data ( 'settings' ) ; var left_grip_selector = settings . left_grip_selector , right_grip_selector = settings . right_grip_selector , value_bar_selector = settings . value_bar_selector ; var handleWidth = $this . data ( 'left_grip_width' ) ; // The left grip $this . find ( left_grip_selector ) . css ( 'left' , leftPx + 'px' ) ; // The right grip $this . find ( right_grip_selector ) . css ( 'left' , rightPx + 'px' ) ; // The value bar if ( $this . data ( 'has_right_grip' ) ) { // If both the grips are there, the value bar must stick to // beginning and the end of the grips.  $this . find ( value_bar_selector ) . css ( 'left' , leftPx + 'px' ) . css ( 'width' , ( rightPx - leftPx + handleWidth ) + 'px' ) ; } else { if ( ! _naked_bar_deltas ) { _methods . populateNakedBarDeltas . call ( $this , leftPx , rightPx , handleWidth ) ; } if ( rightPx > leftPx ) { // The naked end of the bar is on the right of the grip $this . find ( value_bar_selector ) . css ( 'left' , leftPx + 'px' ) . css ( 'width' , rightPx - leftPx + _naked_bar_deltas . toEndWidth + 'px' ) ; } else { // The naked end of the bar is on the left of the grip // NOTE: leftPx and rightPx are to be read swapped here. $this . find ( value_bar_selector ) . css ( 'left' , rightPx + _naked_bar_deltas . toBeginLeft + 'px' ) . css ( 'width' , ( leftPx - rightPx + _naked_bar_deltas . toBeginWidth ) + 'px' ) ; } } return $this ; }


Input: compare search element with current element < 0 search < current 0 equals > 0 search > current [CODESPLIT] function ( search , array , currentIdx ) { // first check if this is our element // this is our element if the search value is: if ( search < array [ currentIdx ] . range ) { // we can have a match or search in the left half if ( currentIdx > 0 ) { if ( search >= array [ currentIdx - 1 ] . range ) { return 0 ; } else { // go left return - 1 ; } } else { return 0 ; } } else { // we must search in the next half return 1 ; } }


Input: / * Calls the user mouseup callback with the right parameters . Relies on $data ( beforestart_min / max ) in addition to the isLeftGrip parameter . [CODESPLIT] function ( isLeftGrip ) { var $this = this , current_min_value = methods . get_current_min_value . call ( $this ) , current_max_value = methods . get_current_max_value . call ( $this ) , didValuesChange = false ; // check if we changed. if ( ( $this . data ( 'beforestart_min' ) !== current_min_value ) || ( $this . data ( 'beforestart_max' ) !== current_max_value ) ) { // values have changed! didValuesChange = true ; // save the new values $this . data ( 'beforestart_min' , current_min_value ) ; $this . data ( 'beforestart_max' , current_max_value ) ; } var settings = $this . data ( 'settings' ) ; settings . user_mouseup_callback . call ( $this , methods . get_current_min_value . call ( $this ) , methods . get_current_max_value . call ( $this ) , isLeftGrip , didValuesChange ) ; return $this ; }


Input: / * NOTE : this method may take the previous min / max value as input . if no arguments are provided the method blindly notifies . [CODESPLIT] function ( cause , prevMin , prevMax ) { var $this = this ; var force = false ; if ( cause === 'init' || cause === 'refresh' ) { force = true ; } var curMin = methods . get_current_min_value . call ( $this ) , curMax = methods . get_current_max_value . call ( $this ) ; if ( ! force ) { prevMin = methods . round_value_according_to_rounding . call ( $this , prevMin ) ; prevMax = methods . round_value_according_to_rounding . call ( $this , prevMax ) ; } if ( force || curMin !== prevMin || curMax !== prevMax ) { _methods . notify_changed_explicit . call ( $this , cause , prevMin , prevMax , curMin , curMax ) ; force = 1 ; } return force ; }


Input: / * Maps a value between [ minRange -- maxRange ] into [ 0 -- n ] . The target range will be an integer number . [CODESPLIT] function ( val , n ) { var $this = this ; var rangeMin = $this . data ( 'range_min' ) ; var rangeMax = $this . data ( 'range_max' ) ; if ( val <= rangeMin ) { return 0 ; } if ( val >= rangeMax ) { return n ; } return Math . floor ( ( n * val - n * rangeMin ) / ( rangeMax - rangeMin ) ) ; }


Input: / * Maps a value between [ 0 -- max ] back into [ minRange -- maxRange ] . The target range can be a floating point number . [CODESPLIT] function ( val , max ) { var $this = this ; var rangeMin = $this . data ( 'range_min' ) ; var rangeMax = $this . data ( 'range_max' ) ; if ( val <= 0 ) { return rangeMin ; } if ( val >= max ) { return rangeMax ; } // // To do this we first map 0 -- max relatively withing [minRange // and maxRange], that is between [0 and (maxRange-minRange)]. // var relativeMapping = ( rangeMax - rangeMin ) * val / max ; // ... then we bring this to the actual value by adding rangeMin. return relativeMapping + rangeMin ; }


Input: for test removed by Grunt [CODESPLIT] function ( ) { var $this = this ; // remove all data set with .data() $this . removeData ( ) ; // unbind the document as well $ ( document ) . unbind ( 'mousemove.nstSlider' ) . unbind ( 'mouseup.nstSlider' ) ; // unbind events bound to the container element $this . parent ( ) . unbind ( 'mousedown.nstSlider' ) . unbind ( 'touchstart.nstSlider' ) . unbind ( 'touchmove.nstSlider' ) . unbind ( 'touchend.nstSlider' ) ; // unbind events bound to the current element $this . unbind ( 'keydown.nstSlider' ) . unbind ( 'keyup.nstSlider' ) ; return $this ; }


Input: just call set_position on the current values [CODESPLIT] function ( ) { var $this = this ; // re-set the slider step if specified var lastStepHistogram = $this . data ( 'last_step_histogram' ) ; if ( typeof lastStepHistogram !== 'undefined' ) { methods . set_step_histogram . call ( $this , lastStepHistogram ) ; } // re-center given values _methods . set_position_from_val . call ( $this , methods . get_current_min_value . call ( $this ) , methods . get_current_max_value . call ( $this ) ) ; // re-highlight the range var highlightRangeMin = $this . data ( 'highlightedRangeMin' ) ; if ( typeof highlightRangeMin === 'number' ) { // a highlight range is present, we must update it var highlightRangeMax = $this . data ( 'highlightedRangeMax' ) ; methods . highlight_range . call ( $this , highlightRangeMin , highlightRangeMax ) ; } _methods . notify_changed_implicit . call ( $this , 'refresh' ) ; return $this ; }


Input: / * This one is the public method called externally . It sets the position and notifies in fact . [CODESPLIT] function ( min , max ) { var $this = this ; var prev_min = $this . data ( 'cur_min' ) , prev_max = $this . data ( 'cur_max' ) ; if ( min > max ) { _methods . set_position_from_val . call ( $this , max , min ) ; } else { _methods . set_position_from_val . call ( $this , min , max ) ; } // set the style of the grips according to the highlighted range _methods . refresh_grips_style . call ( $this ) ; _methods . notify_changed_implicit . call ( $this , 'set_position' , prev_min , prev_max ) ; // this is for the future, therefore "before the next // interaction starts" $this . data ( 'beforestart_min' , min ) ; $this . data ( 'beforestart_max' , max ) ; }


Input: / * This tells the slider to increment its step non linearly over the current range based on the histogram on where results are . [CODESPLIT] function ( histogram ) { var $this = this ; $this . data ( 'last_step_histogram' , histogram ) ; if ( typeof histogram === 'undefined' ) { $ . error ( 'got an undefined histogram in set_step_histogram' ) ; _methods . unset_step_histogram . call ( $this ) ; } var sliderWidthPx = _methods . getSliderWidthPx . call ( $this ) - $this . data ( 'left_grip_width' ) , nbuckets = histogram . length ; if ( sliderWidthPx <= 0 ) { // that means the slider is not visible... return ; } // // we need to transform this pdf into a cdf, and use it to obtain // two mappings: pixel to value and value to pixel. // // 1) normalize the pdf to sum to sliderWidthPx first var i ; var histogram_sum = 0 ; for ( i = 0 ; i < nbuckets ; i ++ ) { histogram_sum += histogram [ i ] ; } // // if the sum of the histogram is 0 it means that all is 0 in the  // histogram! (i.e, flat histogram). In this case we already know // what's going to be the answer... // if ( histogram_sum === 0 ) { // ... and the answer is: a linear scale between min_range and // max range! methods . unset_step_histogram . call ( $this ) ; return $this ; } // coefficient for normalization var coeff = parseFloat ( histogram_sum ) / sliderWidthPx ; // go normalize the histogram using this coefficient! for ( i = 0 ; i < nbuckets ; i ++ ) { histogram [ i ] = histogram [ i ] / coeff ; } // 2) now that the histogram is normalized, extract the cumulative // distribution function (CDF). This is an always increasing function // that ranges between 0 and sliderWidthPx; // // We also build the inverted cdf, just the cdf read the other way // around. // var cdf = [ histogram [ 0 ] ] ; // points to pixels for ( i = 1 ; i < nbuckets ; i ++ ) { var cdf_x = cdf [ i - 1 ] + histogram [ i ] ; cdf . push ( cdf_x ) ; } cdf . push ( sliderWidthPx ) ; // the first value here is always min_range as the cdf is supposed // to start from 0 (also first pixel = min_range) var pixel_to_value_lookup = [ $this . data ( 'range_min' ) ] ; var last_filled = 0 ; // we've already filled 0 // now stretch over the rest of the cdf var last_price_for_cdf_bucket = pixel_to_value_lookup [ 0 ] ; var cdf_bucket_count = 0 ; while ( last_filled <= sliderWidthPx ) { // do until all pixels are filled // get next item from cdf var fill_up_to_px = parseInt ( cdf . shift ( ) , 10 ) ; var price_for_cdf_bucket = _methods . inverse_rangemap_0_to_n . call ( $this , cdf_bucket_count + 1 , nbuckets + 1 ) ; cdf_bucket_count ++ ; // how many pixels do we have to fill var fill_tot = fill_up_to_px - last_filled ; // interpolate and fill var diff = price_for_cdf_bucket - last_price_for_cdf_bucket ; for ( i = last_filled ; i < fill_up_to_px ; i ++ ) { var next_price_for_cdf_bucket = last_price_for_cdf_bucket + ( diff * ( i - last_filled + 1 ) / fill_tot ) ; pixel_to_value_lookup . push ( next_price_for_cdf_bucket ) ; last_filled ++ ; last_price_for_cdf_bucket = next_price_for_cdf_bucket ; } if ( last_filled === sliderWidthPx ) { break ; } } pixel_to_value_lookup [ pixel_to_value_lookup . length - 1 ] = $this . data ( 'range_max' ) ; // 3) build lookup functions to extract pixels and values from the // cdf and the inverted cdf. // var pixel_to_value_mapping = function ( pixel ) { return pixel_to_value_lookup [ parseInt ( pixel , 10 ) ] ; } ; var value_to_pixel_mapping = function ( value ) { // // Binary search into the array of pixels, returns always the // rightmost pixel if there is no exact match. // var suggestedPixel = _methods . binarySearch . call ( $this , pixel_to_value_lookup , value , function ( a , i ) { return a [ i ] ; } , // access a value in the array _methods . binarySearchValueToPxCompareFunc ) ; // exact match if ( pixel_to_value_lookup [ suggestedPixel ] === value ) { return suggestedPixel ; } // approx match: we need to check if it's closer to the value // at suggestedPixel or the value at suggestedPixel-1 if ( Math . abs ( pixel_to_value_lookup [ suggestedPixel - 1 ] - value ) < Math . abs ( pixel_to_value_lookup [ suggestedPixel ] - value ) ) { return suggestedPixel - 1 ; } return suggestedPixel ; } ; // // these two functions will be stored and then used internally to // decide what value to display given a certain pixel, and what // pixel to put the slider on given a certain value. // $this . data ( 'pixel_to_value_mapping' , pixel_to_value_mapping ) ; $this . data ( 'value_to_pixel_mapping' , value_to_pixel_mapping ) ; return $this ; }


Input: / * This method highlights the range of the slider apart from the position of the slider grips . To work well the slider must have background color set to transparent in the CSS or not set . [CODESPLIT] function ( rangeMin , rangeMax ) { var $this = this ; var settings = $this . data ( 'settings' ) ; if ( typeof settings . highlight === "undefined" ) { $ . error ( 'you cannot call highlight_range if you haven\' specified the "highlight" parameter in construction!' ) ; } // avoid empty string if ( ! rangeMin ) { rangeMin = 0 ; } if ( ! rangeMax ) { rangeMax = 0 ; } // we need to map rangeMin and rangeMax into pixels. var leftPx = methods . value_to_px . call ( $this , rangeMin ) , rightPx = methods . value_to_px . call ( $this , rangeMax ) , barWidth = rightPx - leftPx + $this . data ( 'left_grip_width' ) ; // set position var $highlightPanel = $this . find ( settings . highlight . panel_selector ) ; $highlightPanel . css ( 'left' , leftPx + "px" ) ; $highlightPanel . css ( 'width' , barWidth + "px" ) ; // keep the latest highlighted range, because if set_range is called // we must be able to update the highlighting. $this . data ( 'highlightedRangeMin' , rangeMin ) ; $this . data ( 'highlightedRangeMax' , rangeMax ) ; // now decide wether the handler should be highlight _methods . refresh_grips_style . call ( $this ) ; return $this ; }


Input: / * Sets the increment rounding for the slider see input parameters section for more information . [CODESPLIT] function ( rounding ) { var $this = this ; if ( typeof rounding === 'string' && rounding . indexOf ( '{' ) > - 1 ) { // probably a json string rounding = $ . parseJSON ( rounding ) ; } $this . data ( 'rounding' , rounding ) ; // build an array of roundings and sort it by value to facilitate search // when the range is going to be set. var roundings_array = [ ] ; if ( typeof rounding === 'object' ) { // initial object has the form { value : range } var rounding_value ; for ( rounding_value in rounding ) { // skip_javascript_test if ( rounding . hasOwnProperty ( rounding_value ) ) { var rounding_range = rounding [ rounding_value ] ; roundings_array . push ( { 'range' : rounding_range , 'value' : rounding_value } ) ; } } // now sort it by rounding range roundings_array . sort ( function ( a , b ) { return a . range - b . range ; } ) ; $this . data ( 'rounding_ranges' , roundings_array ) ; } else { $this . removeData ( 'rounding_ranges' ) ; } return $this ; }


Input: / * This method rounds a given value to the closest integer defined according to the rounding . Examples : rounding : 10 v : 12 . 3 -- > 10 rounding : 1 v : 12 . 3 -- > 12 rounding : 10 v : 12 . 6 -- > 13 [CODESPLIT] function ( v ) { var $this = this ; var rounding = _methods . get_rounding_for_value . call ( $this , v ) ; if ( rounding > 0 ) { // We bring ourselves in a space of unitary roundings. You can // imagine now that sliders range between a certain minimum and  // maximum, and we always increase/decrease of one. var increment = v / rounding ; // This is the proposed value. var increment_int = parseInt ( increment , 10 ) ; // delta is a positive number between 0 and 1 that tells us how // close is the slider to integer + 1 (i.e., the next rounding). // 0 means the grip is exactly on integer // 1 means the grip is on integer + 1. var delta = increment - increment_int ; // now use delta to modify or not the current value. if ( delta > 0.5 ) { increment_int ++ ; } // we now move the  var rounded = increment_int * rounding ; return rounded ; } else { $ . error ( 'rounding must be > 0, got ' + rounding + ' instead' ) ; } return v ; }


Input: / * Utility function . Given a value within the range of the slider converts the value in pixels . If a value_to_pixel_mapping function is defined it will be used otherwise a linear mapping is used for the conversion . [CODESPLIT] function ( value ) { var $this = this , value_to_pixel_mapping_func = $this . data ( 'value_to_pixel_mapping' ) ; // try using non-linear mapping if it's there... if ( typeof value_to_pixel_mapping_func !== 'undefined' ) { return value_to_pixel_mapping_func ( value ) ; } // ... use linear mapping otherwise var w = _methods . getSliderWidthPx . call ( $this ) - $this . data ( 'left_grip_width' ) ; return _methods . rangemap_0_to_n . call ( $this , value , w ) ; }


Input: / * Internal method Example : params ( city { name : Aalst postalcode : 9300 } ) returns city . name = { name } appendToken city . postalcode = { postalcode } [CODESPLIT] function append ( fieldName , props , appendToken ) { var params = '' ; var notFirst = false ; fieldName += '.' ; for ( var key in props ) { var obj = props [ key ] ; if ( notFirst ) params += appendToken ; else notFirst = true ; params += fieldName + key + '={' + key + '}' ; } return params ; }


Input: / * Example : remove ( city [ name postalcode ] ) returns city . name city . postalcode [CODESPLIT] function remove ( fieldName , props ) { var removes = '' , notFirst = false , i = props . length ; fieldName += '.' ; while ( i -- ) { if ( notFirst ) { removes += ',' ; } else { notFirst = true ; } removes += fieldName + props [ i ] ; } return removes ; }


Input: Create a where and set string and a new object with unique propertynames Example : whereSetProperties ( user { userid : 123 firstname : foo } { firstname : bar } ) returns { where : user . userid = { xQ_1 } AND user . firstname = { xQ_2 } set : user . firstname = { xQ_3 } props { xQ_1 : 123 xQ_2 : foo xQ_2 : bar } } [CODESPLIT] function whereSetProperties ( fieldName , oldProps , newProps ) { var prefix = 'xQ_' , whereClause = '' , setClause = '' , notFirst = false , props = { } , i = 0 , obj ; fieldName += '.' ; // Build WHERE for ( var k in oldProps ) { obj = oldProps [ k ] ; if ( notFirst ) whereClause += ' AND ' ; else notFirst = true ; whereClause += fieldName + k + '={' + prefix + ( ++ i ) + '}' ; props [ prefix + i ] = obj ; } notFirst = false ; // Build SET for ( var key in newProps ) { obj = newProps [ key ] ; if ( notFirst ) setClause += ',' ; else notFirst = true ; // Create unique placeholder {xx1} {xx2} ... setClause += fieldName + key + '={' + prefix + ( ++ i ) + '}' ; // Build new properties object props [ prefix + i ] = obj ; } // Return stringified `where` and `set` clause and a new object with unique property names // So there are no name collisions return { where : whereClause , set : setClause , properties : props } ; }


Input: Example : labels ( [ User Student ] ) returns : User : Student [CODESPLIT] function labels ( array ) { var res = '' ; if ( typeof array === 'string' ) { return ':' + array ; } for ( var i = 0 ; i < array . length ; i ++ ) { res += ':' + array [ i ] ; } return res ; }


Input: / * Replace a Node s properties This will replace all existing properties on the node with the new set of attributes . [CODESPLIT] function ( node_id , node_data , callback ) { var that = this ; request . put ( that . url + '/db/data/node/' + node_id + '/properties' ) . set ( this . header ) . send ( that . stringifyValueObjects ( that . replaceNullWithString ( node_data ) ) ) . end ( function ( result ) { switch ( result . statusCode ) { case 204 : callback ( null , true ) ; break ; case 404 : callback ( null , false ) ; break ; default : callback ( new Error ( 'HTTP Error ' + result . statusCode + ' when updating a Node.' ) , null ) ; } } ) ; }


Input: / * CONSTRAINTS / * Create a uniqueness constraint on a property . Example : createUniquenessConstraint ( User email callback ) ; returns { label : User type : UNIQUENESS property - keys : [ email ] } [CODESPLIT] function ( label , property_key , callback ) { var that = this ; var val = new Validator ( ) ; val . label ( label ) . property ( property_key ) ; if ( val . hasErrors ) { return callback ( val . error ( ) , null ) ; } request . post ( that . url + '/db/data/schema/constraint/' + label + '/uniqueness' ) . set ( this . header ) . send ( { 'property_keys' : [ property_key ] } ) . end ( function ( result ) { switch ( result . statusCode ) { case 200 : callback ( null , result . body ) ; break ; case 409 : callback ( null , false ) ; // Constraint already exists break ; default : callback ( new Error ( 'HTTP Error ' + result . statusCode + ' when creating a uniqueness contraint.' ) , null ) ; } } ) ; }


Input: / * Get Relationships of a Node --------- [CODESPLIT] function ( node_id , options , callback ) { var that = this ; if ( typeof options === 'function' ) { callback = options ; } var url = that . url + '/db/data/node/' + node_id + '/relationships/' ; // Set direction of relationships to retrieve. if ( options . direction && ( options . direction === 'in' || options . direction === 'out' ) ) { url += options . direction ; } else { url += 'all' ; } // Set types of relationships to retrieve. if ( options . types && options . types . length >= 1 ) { url += '/' + encodeURIComponent ( options . types . join ( '&' ) ) ; } request . get ( url ) . set ( this . header ) . end ( function ( result ) { switch ( result . statusCode ) { case 200 : that . addRelationshipIdForArray ( result . body , callback ) ; break ; case 404 : callback ( null , false ) ; break ; default : callback ( new Error ( 'HTTP Error ' + result . statusCode + ' when retrieving relationships for node ' + node_id ) , null ) ; } } ) ; }