Input: startSingleModule is the method that will initialize the module . When start is called the module instance will be created and the init method is called . If bSingle is true and the module is started the module will be stopped before instance it again . This avoid execute the same listeners more than one time . [CODESPLIT] function startSingleModule ( oWrapper , sModuleId , sIdInstance , oData , bSingle ) { const oModules = getModules ( ) ; var oModule ; oModule = oModules [ sModuleId ] ; if ( ( bSingle && isModuleStarted ( sModuleId ) ) || isModuleStarted ( sModuleId , sIdInstance ) ) { oWrapper . stop ( sModuleId , sIdInstance ) ; } if ( ! isTypeOf ( oModule , sNotDefined ) ) { createInstance ( sModuleId , undefined , function ( oInstance ) { oModule . instances [ sIdInstance ] = oInstance ; oInstance . __instance_id__ = sIdInstance ; beforeInit ( oInstance , oData , bSingle ) ; if ( ! isTypeOf ( oData , sNotDefined ) ) { oInstance . init ( oData ) ; } else { oInstance . init ( ) ; } } ) ; } else { const ErrorHandler = errorHandler ( ) ; ErrorHandler . error ( new Error ( ) , fpThrowErrorModuleNotRegistered ( sModuleId ) ) ; } }


Input: Start only one module . [CODESPLIT] function _singleModuleStart ( oInstance , sModuleId , sIdInstance , oData , bSingle ) { if ( ! isTypeOf ( sIdInstance , 'string' ) ) { bSingle = oData ; oData = sIdInstance ; sIdInstance = generateUniqueKey ( ) ; } startSingleModule ( oInstance , sModuleId , sIdInstance , oData , bSingle ) ; }


Input: start is the method that initialize the module / s If you use array instead of arrays you can start more than one module even adding the instance the data and if it must be executed as single module start . [CODESPLIT] function start ( oModuleId , oIdInstance , oData , oSingle ) { var bStartMultipleModules = isArray ( oModuleId ) ; if ( bStartMultipleModules ) { _multiModuleStart ( this , copyArray ( oModuleId ) , oIdInstance , oData , oSingle ) ; } else { _singleModuleStart ( this , oModuleId , oIdInstance , oData , oSingle ) ; } }


Input: createInstance is the method that will create the module instance and wrap the method if needed . [CODESPLIT] function createInstance ( sModuleId , aDependencies , fpCallback ) { const oModules = getModules ( ) ; if ( isTypeOf ( oModules [ sModuleId ] , sNotDefined ) ) { fpThrowErrorModuleNotRegistered ( sModuleId , true ) ; } addPropertiesAndMethodsToModule ( sModuleId , aDependencies , function ( oInstance ) { if ( ! getDebug ( ) ) { iterateObject ( oInstance , function ( oItem , sName ) { if ( isFunction ( oItem ) ) { wrapMethod ( oInstance , sName , sModuleId , oInstance [ sName ] ) ; } } ) ; } fpCallback ( oInstance ) ; } ) ; }


Input: Sets properties and methods from a template object . [CODESPLIT] function getCallbackToSetObjectFromTemplate ( oMethodsObject , oPropertiesObject ) { return function ( oValue , sKey ) { if ( typeof oValue === 'function' ) { oMethodsObject [ sKey ] = getSimpleFunction ( oValue ) ; } else if ( isArray ( oValue ) ) { oPropertiesObject [ sKey ] = copyArray ( oValue ) ; } else if ( typeof oValue === 'object' && oValue !== null ) { oPropertiesObject [ sKey ] = simpleMerge ( { } , oValue ) ; } else if ( isInstanceOf ( oValue , Date ) ) { oPropertiesObject [ sKey ] = new Date ( ) ; oPropertiesObject [ sKey ] . setTime ( oValue . getTime ( ) ) ; } else { oPropertiesObject [ sKey ] = oValue ; } } ; }


Input: startAll is the method that will initialize all the registered modules . [CODESPLIT] function startAll ( ) { const oModules = getModules ( ) ; iterateObject ( oModules , function ( _oModule , sModuleId ) { if ( ! isTypeOf ( _oModule , sNotDefined ) ) { start ( sModuleId , generateUniqueKey ( ) ) ; } } ) ; }


Input: stop is the method that will finish the module if it was registered and started . When stop is called the module will call the destroy method and will nullify the instance . [CODESPLIT] function stop ( sModuleId , sInstanceId ) { const oModules = getModules ( ) ; var oModule ; oModule = oModules [ sModuleId ] ; if ( isTypeOf ( oModule , sNotDefined ) ) { return false ; } if ( ! isTypeOf ( sInstanceId , sNotDefined ) ) { _singleModuleStop ( oModule , sInstanceId ) ; } else { _multiModuleStop ( oModule ) ; } return true ; }


Input: stop more than one module at the same time . [CODESPLIT] function _multiModuleStop ( oModule ) { iterateObject ( oModule . instances , function ( oInstance ) { if ( ! isTypeOf ( oModule , sNotDefined ) && ! isTypeOf ( oInstance , sNotDefined ) ) { oInstance . destroy ( ) ; } } ) ; oModule . instances = { } ; }


Input: Stop only one module . [CODESPLIT] function _singleModuleStop ( oModule , sInstanceId ) { var oInstance = oModule . instances [ sInstanceId ] ; if ( ! isTypeOf ( oModule , sNotDefined ) && ! isTypeOf ( oInstance , sNotDefined ) ) { oInstance . destroy ( ) ; delete oModule . instances [ sInstanceId ] ; } }


Input: stopAll is the method that will finish all the registered and started modules . [CODESPLIT] function stopAll ( ) { const oModules = getModules ( ) ; iterateObject ( oModules , function ( _oModule , sModuleId ) { if ( ! isTypeOf ( _oModule , sNotDefined ) ) { _stopOneByOne ( _oModule , sModuleId ) ; } } ) ; }


Input: Loops over instances of modules to stop them . [CODESPLIT] function _stopOneByOne ( oModule , sModuleId ) { iterateObject ( oModule . instances , function ( oItem , sInstanceId ) { stop ( sModuleId , sInstanceId ) ; } ) ; }


Input: remove is the method that will remove the full module from the oModules object [CODESPLIT] function remove ( sModuleId ) { const oModules = getModules ( ) ; var oModule = oModules [ sModuleId ] ; if ( isTypeOf ( oModule , sNotDefined ) ) { return null ; } if ( ! isTypeOf ( oModule , sNotDefined ) ) { try { return Module ; } finally { _delete ( sModuleId ) ; createMapping ( getMappingMaps ( ) , 'hm_' , oModules ) ; } } return null ; }


Input: _delete is a wrapper method that will call the native delete javascript function It s important to test the full code . [CODESPLIT] function _delete ( sModuleId ) { const oModules = getModules ( ) ; if ( ! isTypeOf ( oModules [ sModuleId ] , sNotDefined ) ) { delete oModules [ sModuleId ] ; return true ; } return false ; }


Input: Entry point . [CODESPLIT] function main ( ) { return __awaiter ( this , void 0 , void 0 , function ( ) { var outputDataSize , interval , dataFrame , dateFormat , api ; return __generator ( this , function ( _a ) { switch ( _a . label ) { case 0 : outputDataSize = "compact" ; if ( argv . outputDataSize ) { outputDataSize = argv . outputDataSize ; } interval = '60min' ; if ( argv . interval ) { interval = argv . interval ; } api = new index_1 . AlphaVantageAPI ( argv . apiKey , outputDataSize , argv . verbose ) ; if ( ! ( argv . type === 'daily' ) ) return [ 3 /*break*/ , 2 ] ; return [ 4 /*yield*/ , api . getDailyDataFrame ( argv . symbol ) ] ; case 1 : dataFrame = _a . sent ( ) ; dateFormat = 'YYYY-MM-DD' ; return [ 3 /*break*/ , 5 ] ; case 2 : if ( ! ( argv . type === 'intraday' ) ) return [ 3 /*break*/ , 4 ] ; return [ 4 /*yield*/ , api . getIntradayDataFrame ( argv . symbol , interval ) ] ; case 3 : dataFrame = _a . sent ( ) ; dateFormat = "YYYY-MM-DD HH:mm:ss" ; return [ 3 /*break*/ , 5 ] ; case 4 : throw new Error ( "Unexpected data type: " + argv . type + ", expected it to be either 'daily' or 'intrday'" ) ; case 5 : if ( ! argv . verbose ) { console . log ( '>> ' + argv . out ) ; } dataFrame . transformSeries ( { Timestamp : function ( t ) { return moment ( t ) . format ( dateFormat ) ; } , } ) . asCSV ( ) . writeFileSync ( argv . out ) ; return [ 2 /*return*/ ] ; } } ) ; } ) ; }


Input: instance identifier for bind / unbind events [CODESPLIT] function ( name , opts ) { //triggers an event bound to the element opts = opts || { } ; this . element . trigger ( $ . extend ( { type : name , pickerInstance : this } , opts ) ) ; //console.log(name + ' triggered for instance #' + this._id); }


Input: Sets the internal item value and updates everything excepting the input or element . For doing so call setSourceValue () or update () instead [CODESPLIT] function ( val ) { // sanitize first var _val = this . getValid ( val ) ; if ( _val !== false ) { this . pickerValue = _val ; this . _trigger ( 'pickerSetValue' , { pickerValue : _val } ) ; return this . pickerValue ; } else { this . _trigger ( 'pickerInvalid' , { pickerValue : val } ) ; return false ; } }


Input: Returns the formatted item value [CODESPLIT] function ( val ) { // here you may parse your format when you build your plugin var valueInPicker = this . options . itemProperty ? this . pickerValue [ this . options . itemProperty ] : this . pickerValue ; return ( val ? val : valueInPicker ) ; }


Input: Calls setValue and if it s a valid item value sets the input or element value [CODESPLIT] function ( val ) { val = this . setValue ( val ) ; if ( ( val !== false ) && ( val !== '' ) ) { if ( this . hasInput ( ) ) { this . input . val ( this . getValue ( ) ) ; } else { this . element . data ( 'pickerValue' , this . getValue ( ) ) ; } this . _trigger ( 'pickerSetSourceValue' , { pickerValue : val } ) ; } return val ; }


Input: Returns the input or element item value without formatting or defaultValue if it s empty string undefined false or null [CODESPLIT] function ( defaultValue ) { // returns the input or element value, as string defaultValue = defaultValue || this . options . defaultValue ; var val = defaultValue ; if ( this . hasInput ( ) ) { val = this . input . val ( ) ; } else { val = this . element . data ( 'pickerValue' ) ; val = this . options . itemProperty ? val [ this . options . itemProperty ] : val ; } if ( ( val === undefined ) || ( val === '' ) || ( val === null ) || ( val === false ) ) { // if not defined or empty, return default val = defaultValue ; } return val ; }


Input: based on from https : // github . com / inuyaksa / jquery . nicescroll / blob / master / jquery . nicescroll . js [CODESPLIT] function ( e , p ) { if ( ! e ) return false ; var el = e . target || e . srcElement || e || false ; while ( el && el != p ) { el = el . parentNode || false ; } return ( el !== false ) ; }


Input: SelectFx function [CODESPLIT] function ( el , options ) { events . EventEmitter . call ( this ) ; this . el = el ; this . options = extend ( { } , this . options ) ; this . options = extend ( this . options , options ) ; this . _init ( ) ; }


Input:
Helpers [CODESPLIT] function findUuidIndex ( array , uuid ) { for ( let i = 0 , len = array . length ; i < len ; i ++ ) { if ( array [ i ] . uuid == uuid ) { // eslint-disable-line
 return i ; } } return - 1 ; }


Input: createMarkdownSerializer create a snapshot serializer . [CODESPLIT] function createMarkdownSerializer ( indentCodeBlocks ) { return { serialize : ( name , suite ) => snapshotToMarkdown ( name , suite , indentCodeBlocks ) , deserialize : markdownToSnapshot , } ; }


Input: markdownToSnapshot converts snapshot from markdown format into native . [CODESPLIT] function markdownToSnapshot ( content ) { const tree = mdParser . parse ( content ) ; const state = { name : null , suite : null , suiteStack : [ ] , currentSuite : null , currentSnapshotList : null , depth : 0 } ; const children = tree . children ; for ( let i = 0 ; i < children . length ; i ++ ) { const c = children [ i ] ; switch ( c . type ) { case 'heading' : if ( c . depth === 1 ) { enterRootSuite ( state , c ) ; } else if ( c . depth === 2 ) { tryExit ( state , suiteDepth ( c ) ) ; enterSuite ( state , c ) ; } else if ( c . depth === 4 ) { enterSnapshot ( state , c ) ; } break ; case 'code' : pushSnapshotCode ( state , c ) ; break ; } } return { name : state . name , suite : state . suite } ; }


Input: tryExit tries to pop state until it has correct depth . [CODESPLIT] function tryExit ( state , depth ) { while ( state . depth >= depth ) { state . suiteStack . pop ( ) ; state . currentSuite = state . suiteStack [ state . suiteStack . length - 1 ] ; state . currentSnapshotList = null ; state . depth -- ; } }


Input: enterRootSuite pushes root suite into the current state . [CODESPLIT] function enterRootSuite ( state , node ) { const inlineCode = node . children [ 0 ] ; const name = inlineCode . value ; const suite = { children : { } , snapshots : { } } state . name = name ; state . suite = suite ; state . suiteStack . push ( suite ) ; state . currentSuite = suite ; state . currentSnapshotList = null ; state . depth = 0 ; }


Input: enterSnapshot pushes snapshot into the current state . [CODESPLIT] function enterSnapshot ( state , node ) { const inlineCode = node . children [ 0 ] ; const name = inlineCode . value ; const snapshotList = [ ] ; state . currentSuite . snapshots [ name ] = snapshotList ; state . currentSnapshotList = snapshotList ; }


Input: pushSnapshotCode adds snapshot to the current snapshot . [CODESPLIT] function pushSnapshotCode ( state , node ) { state . currentSnapshotList . push ( { lang : node . lang , code : normalizeNewlines ( node . value ) } ) ; }


Input: transformSuite converts suite from native into markdown format . [CODESPLIT] function transformSuite ( name , suite , depth , indentCodeBlocks ) { const children = suite . children ; const snapshots = suite . snapshots ; const nextDepth = depth + 1 ; let result = suiteHeader ( name , depth ) ; let keys , i ; keys = Object . keys ( snapshots ) ; for ( i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; const snapshotList = snapshots [ key ] ; result += transformSnapshotList ( key , snapshotList , nextDepth , indentCodeBlocks ) ; } keys = Object . keys ( children ) ; for ( i = 0 ; i < keys . length ; i ++ ) { const key = keys [ i ] ; result += transformSuite ( key , children [ key ] , nextDepth , indentCodeBlocks ) ; } return result ; }


Input: transformSnapshotList converts snapshot list from native into markdown format . [CODESPLIT] function transformSnapshotList ( name , snapshotList , depth , indentCodeBlocks ) { let result = snapshotHeader ( name , depth ) ; for ( let i = 0 ; i < snapshotList . length ; i ++ ) { if ( i > 0 && indentCodeBlocks ) { result += '---\n\n' ; } const snapshot = snapshotList [ i ] ; const lang = snapshot . lang ; const code = snapshot . code ; const delimiter = safeDelimiter ( code ) ; if ( indentCodeBlocks ) { const lines = code . split ( '\n' ) ; for ( let i = 0 ; i < lines . length ; i ++ ) { result += '    ' + lines [ i ] + '\n' ; } } else { result += delimiter ; if ( lang ) { result += lang ; } result += '\n' + code + '\n' + delimiter + '\n' ; } result += '\n' ; } return result ; }


Input: suiteHeader serializes suite header . [CODESPLIT] function suiteHeader ( name , depth ) { if ( depth === - 1 ) { return "# " + serializeName ( name ) + "\n\n" ; } return "## " + indent ( depth ) + serializeName ( name ) + "\n\n" ; }


Input: safeDelimiter tries to find a safe delimiter by appending backticks until it finally finds it . [CODESPLIT] function safeDelimiter ( s , delimiter ) { if ( delimiter === undefined ) { delimiter = '```' ; } while ( s . indexOf ( delimiter ) !== - 1 ) { delimiter += '`' ; } return delimiter ; }


Input: defaultPathResolver is a default path resolver for snapshot files . [CODESPLIT] function defaultPathResolver ( basePath , suiteName ) { const suiteSourcePath = path . join ( basePath , suiteName ) ; const suiteSourceDir = path . dirname ( suiteSourcePath ) ; const sourceFileName = path . basename ( suiteName ) ; return path . join ( suiteSourceDir , "__snapshots__" , sourceFileName + ".md" ) ; }


Input: Renders a list of snapshots up to specified limit of lines [CODESPLIT] function formatSnapshotList ( list , limit ) { limit = ( typeof limit != 'undefined' ) ? limit : - 1 ; const limitedList = limit > 0 ? list . slice ( 0 , limit ) : list ; const hasMore = list . length > limitedList . length ; const buildList = ( snapshots ) => snapshots . map ( ( s ) => s . join ( ' > ' ) ) . join ( '\n' ) ; if ( hasMore ) { return buildList ( limitedList . slice ( 0 , - 1 ) ) + ` \n ${ list . length - limitedList . length + 1 } ` ; } return buildList ( limitedList ) ; }


Input: Renders the message for unused snapshots warning [CODESPLIT] function formatUnusedSnapshotsWarning ( list , limit ) { if ( limit == 0 ) { return ` ${ list . length } ` ; } const prunedList = formatSnapshotList ( list , limit ) ; return ` ${ list . length } \n ${ prunedList } ` ; }


Input: snapshotFramework [CODESPLIT] function snapshotFramework ( files , config , emitter , loggerFactory ) { const logger = loggerFactory . create ( 'framework.snapshot' ) ; const snapshotConfig = Object . assign ( { update : false , prune : false , format : "md" , checkSourceFile : false , pathResolver : defaultPathResolver , limitUnusedSnapshotsInWarning : - 1 } , config . snapshot ) ; if ( typeof snapshotConfig . format === "string" ) { switch ( snapshotConfig . format ) { case "indented-md" : snapshotSerializer = createMarkdownSerializer ( true ) ; break ; case "md" : default : snapshotSerializer = createMarkdownSerializer ( false ) ; } } else { snapshotSerializer = snapshotConfig . format ; } // it should be in a files list after `adapter.js` if ( snapshotConfig . update ) { files . unshift ( filePattern ( path . join ( __dirname , 'snapshot-state-update.js' ) ) ) ; } // inject snapshot adapter files . unshift ( filePattern ( path . join ( __dirname , 'adapter.js' ) ) ) ; emitter . on ( 'browser_complete' , ( clientInfo , data ) => { const lastResult = clientInfo . lastResult ; if ( ! lastResult . disconnected ) { if ( data && data . snapshot ) { let rootSuite = data . snapshot ; let dirty = rootSuite . dirty ; // prune dead snapshots if ( ! lastResult . error && lastResult . failed === 0 && lastResult . skipped === 0 ) { const prunedSnapshots = prune . pruneSnapshots ( rootSuite ) ; if ( prunedSnapshots . pruned . length > 0 ) { if ( snapshotConfig . prune ) { const prunedList = formatSnapshotList ( prunedSnapshots . pruned ) logger . warn ( ` ${ prunedSnapshots . pruned . length } \n ${ prunedList } ` ) ; rootSuite = prunedSnapshots . suite ; prune . pruneFiles ( snapshotConfig . pathResolver , config . basePath , prunedSnapshots . prunedFiles ) ; dirty = true ; } else { logger . warn ( formatUnusedSnapshotsWarning ( prunedSnapshots . pruned , snapshotConfig . limitUnusedSnapshotsInWarning ) ) ; } } } if ( dirty ) { Object . keys ( rootSuite . children ) . forEach ( ( suiteName ) => { const suite = rootSuite . children [ suiteName ] ; if ( suite . dirty ) { if ( snapshotConfig . checkSourceFile ) { const suiteSourceFilePath = path . join ( config . basePath , suiteName ) ; if ( ! fs . existsSync ( suiteSourceFilePath ) ) { logger . error ( 'Failed to save snapshot file. ' + 'Source file "' + suiteSourceFilePath + '" does not exist.' ) ; return ; } } const snapshotPath = snapshotConfig . pathResolver ( config . basePath , suiteName ) ; const snapshotDir = path . dirname ( snapshotPath ) ; if ( ! fs . existsSync ( snapshotDir ) ) { mkdirp . sync ( snapshotDir ) ; } fs . writeFileSync ( snapshotPath , snapshotSerializer . serialize ( suiteName , suite ) ) ; } } ) ; } } } else { logger . warn ( 'Snapshot data is unavailable' ) ; } } ) ; }


Input: Snapshot preprocessor . [CODESPLIT] function snapshotPreprocessor ( basePath , loggerFactory ) { const logger = loggerFactory . create ( 'preprocessor.snapshot' ) ; return function ( content , file , done ) { const root = snapshotSerializer . deserialize ( content ) ; done ( iifeWrapper ( 'window.__snapshot__.addSuite("' + root . name + '",' + JSON . stringify ( root . suite ) + ');' ) ) ; } ; }


Input:
Single Line Plugin [CODESPLIT] function singleLinePlugin ( options = { } ) { options = Object . assign ( { } , defaultOptions , options ) return { /**
     * Return a compatible blockRenderMap
     *
     * NOTE: Needs to be explicitly applied, the plugin system doesn’t do
     * anything with this at the moment.
     *
     * @type {ImmutableMap}
     */ blockRenderMap : Map ( { 'unstyled' : { element : 'div' , } , } ) , /**
     * onChange
     *
     * Condense multiple blocks into a single block and (optionally) strip all
     * entities from the content of that block.
     *
     * @param  {EditorState} editorState The current state of the editor
     * @return {EditorState} A new editor state
     */ onChange ( editorState ) { const blocks = editorState . getCurrentContent ( ) . getBlocksAsArray ( ) // If we have more than one block, compress them if ( blocks . length > 1 ) { editorState = condenseBlocks ( editorState , blocks , options ) } else { // We only have one content block let contentBlock = blocks [ 0 ] let text = contentBlock . getText ( ) let characterList = contentBlock . getCharacterList ( ) let hasEntitiesToStrip = options . stripEntities && characterListhasEntities ( characterList ) if ( NEWLINE_REGEX . test ( text ) || hasEntitiesToStrip ) { // Replace the text stripped of its newlines. Note that we replace // one '\n' with one ' ' so we don't need to modify the characterList text = replaceNewlines ( text ) // Strip entities? if ( options . stripEntities ) { characterList = characterList . map ( stripEntityFromCharacterMetadata ) } // Create a new content block based on the old one contentBlock = new ContentBlock ( { key : genKey ( ) , text : text , type : 'unstyled' , characterList : characterList , depth : 0 , } ) // Update the editor state with the compressed version // const selection = editorState.getSelection() const newContentState = ContentState . createFromBlockArray ( [ contentBlock ] ) // Create the new state as an undoable action editorState = EditorState . push ( editorState , newContentState , 'insert-characters' ) } } return editorState } , /**
     * Stop new lines being inserted by always handling the return
     *
     * @param  {KeyboardEvent} e Synthetic keyboard event from draftjs
     * @return {String} Did we handle the return or not? (pro-trip: yes, we did)
     */ handleReturn ( e ) { return 'handled' } , } }


Input: Replace newline characters with the passed string [CODESPLIT] function replaceNewlines ( str ) { var replacement = arguments . length <= 1 || arguments [ 1 ] === undefined ? ' ' : arguments [ 1 ] ; return str . replace ( NEWLINE_REGEX , replacement ) ; }


Input: Condense an array of content blocks into a single block [CODESPLIT] function condenseBlocks ( editorState , blocks , options ) { blocks = blocks || editorState . getCurrentContent ( ) . getBlocksAsArray ( ) ; var text = ( 0 , _immutable . List ) ( ) ; var characterList = ( 0 , _immutable . List ) ( ) ; // Gather all the text/characterList and concat them blocks . forEach ( function ( block ) { // Atomic blocks should be ignored (stripped) if ( block . getType ( ) !== 'atomic' ) { text = text . push ( replaceNewlines ( block . getText ( ) ) ) ; characterList = characterList . concat ( block . getCharacterList ( ) ) ; } } ) ; // Strip entities? if ( options . stripEntities ) { characterList = characterList . map ( stripEntityFromCharacterMetadata ) ; } // Create a new content block var contentBlock = new _draftJs . ContentBlock ( { key : ( 0 , _draftJs . genKey ) ( ) , text : text . join ( '' ) , type : 'unstyled' , characterList : characterList , depth : 0 } ) ; // Update the editor state with the compressed version var newContentState = _draftJs . ContentState . createFromBlockArray ( [ contentBlock ] ) ; // Create the new state as an undoable action editorState = _draftJs . EditorState . push ( editorState , newContentState , 'remove-range' ) ; // Move the selection to the end return _draftJs . EditorState . moveFocusToEnd ( editorState ) ; }


Input: Check if a CharacterList contains entities [CODESPLIT] function characterListhasEntities ( characterList ) { var hasEntities = false ; characterList . forEach ( function ( characterMeta ) { if ( characterMeta . get ( 'entity' ) !== null ) { hasEntities = true ; } } ) ; return hasEntities ; }


Input: eslint - disable - line node / prefer - global / process [CODESPLIT] function getClosestVersion ( ) { if ( ! process . versions . v8 ) { // Assume compatibility with Node.js 8.9.4 return 'v8-6.1' ; } const v8 = parseFloat ( process . versions . v8 ) ; if ( v8 >= 6.6 ) { return 'v8-6.6' ; } if ( v8 >= 6.2 ) { return 'v8-6.2' ; } return 'v8-6.1' ; }


Input:
/ * ! [CODESPLIT] function GstLaunch ( ) { const gst_launch_executable = 'gst-launch-1.0' ; const gst_launch_versionarg = '--version' ; const SpawnSync = require ( 'child_process' ) . spawnSync ; const Spawn = require ( 'child_process' ) . spawn ; const Assert = require ( 'assert' ) ; const Path = require ( 'path' ) ; const OS = require ( 'os' ) ; const FS = require ( 'fs' ) ; /**
   * @fn getPath
   * @brief Returns path to gst-launch or undefined on error
   */ var getPath = function ( ) { var detected_path = undefined ; if ( OS . platform ( ) == 'win32' ) { // On Windows, GStreamer MSI installer defines the following // environment variables. const detected_path_x64 = process . env . GSTREAMER_1_0_ROOT_X86_64 ; const detected_path_x32 = process . env . GSTREAMER_1_0_ROOT_X86 ; if ( detected_path_x64 || detected_path_x32 ) { // If both variables are present, favor the architecture // of GStreamer which is the same as Node.js runtime. if ( detected_path_x64 && detected_path_x32 ) { if ( process . arch == 'x64' ) detected_path = detected_path_x64 ; else if ( process . arch == 'x32' ) detected_path = detected_path_x32 ; } else { detected_path = detected_path_x64 || detected_path_x32 ; } } if ( detected_path ) { detected_path = Path . join ( detected_path , 'bin' , ( gst_launch_executable + '.exe' ) ) ; try { FS . accessSync ( detected_path , FS . F_OK ) ; } catch ( e ) { detected_path = undefined ; } } else { // Look for GStreamer on PATH var path_dirs = process . env . PATH . split ( ';' ) ; for ( var index = 0 ; index < path_dirs . length ; ++ index ) { try { var base = Path . normalize ( path_dirs [ index ] ) ; var bin = Path . join ( base , ( gst_launch_executable + '.exe' ) ) ; FS . accessSync ( bin , FS . F_OK ) ; detected_path = bin ; } catch ( e ) { /* no-op */ } } } } else if ( OS . platform ( ) == 'linux' ) { // Look for GStreamer on PATH var path_dirs = process . env . PATH . split ( ':' ) ; for ( var index = 0 ; index < path_dirs . length ; ++ index ) { try { var base = Path . normalize ( path_dirs [ index ] ) ; var bin = Path . join ( base , gst_launch_executable ) ; FS . accessSync ( bin , FS . F_OK ) ; detected_path = bin ; } catch ( e ) { /* no-op */ } } } else if ( OS . platform ( ) == 'darwin' ) { try { var bin = '/usr/local/bin/gst-launch-1.0' FS . accessSync ( bin , FS . F_OK ) ; detected_path = bin ; } catch ( e ) { /* no-op */ } } return detected_path ; } /**
   * @fn getVersion
   * @brief Returns version string of GStreamer on this machine by
   * invoking the gst-launch executable or 'undefined' on failure.
   */ var getVersion = function ( ) { var version_str = undefined ; try { var gst_launch_path = getPath ( ) ; Assert . ok ( typeof ( gst_launch_path ) , 'string' ) ; var output = SpawnSync ( gst_launch_path , [ gst_launch_versionarg ] , { 'timeout' : 1000 } ) . stdout ; if ( output && output . toString ( ) . includes ( 'GStreamer' ) ) { version_str = output . toString ( ) . match ( / GStreamer\s+.+ / g ) [ 0 ] . replace ( / GStreamer\s+ / , '' ) ; } } catch ( ex ) { version_str = undefined ; } return version_str ; } /*!
   * @fn isAvailable
   * @brief Answers true if gst-launch executable is available
   */ var isAvailable = function ( ) { return getVersion ( ) != undefined ; } /*!
   * @fn spawnPipeline
   * @brief Spawns a GStreamer pipeline using gst-launch
   * @return A Node <child-process> of the launched pipeline
   * @see To construct a correct pipeline arg, consult the link below:
   * https://gstreamer.freedesktop.org/data/doc/gstreamer/head/manual/html/chapter-programs.html
   * @usage spawnPipeline('videotestsrc ! autovideosink')
   */ var spawnPipeline = function ( pipeline ) { Assert . ok ( typeof ( pipeline ) , 'string' ) ; Assert . ok ( isAvailable ( ) , "gst-launch is not available." ) ; var gst_launch_path = getPath ( ) ; Assert . ok ( typeof ( gst_launch_path ) , 'string' ) ; return Spawn ( gst_launch_path , pipeline . split ( ' ' ) ) ; } return { 'getPath' : getPath , 'getVersion' : getVersion , 'isAvailable' : isAvailable , 'spawnPipeline' : spawnPipeline } }


Input: / * ! [CODESPLIT] function ( pipeline ) { Assert . ok ( typeof ( pipeline ) , 'string' ) ; Assert . ok ( isAvailable ( ) , "gst-launch is not available." ) ; var gst_launch_path = getPath ( ) ; Assert . ok ( typeof ( gst_launch_path ) , 'string' ) ; return Spawn ( gst_launch_path , pipeline . split ( ' ' ) ) ; }


Input:
/ * ! [CODESPLIT] function GstLiveCamServer ( config ) { const Assert = require ( 'assert' ) ; const OS = require ( 'os' ) ; Assert . ok ( [ 'win32' , 'linux' , 'darwin' ] . indexOf ( OS . platform ( ) ) > - 1 , "livecam module supports Windows, Linux, and Mac OSX for broadcasting." ) ; config = config || { } ; Assert . ok ( typeof ( config ) , 'object' ) ; const fake = config . fake || false ; const width = config . width || 800 ; const height = config . height || 600 ; const framerate = config . framerate || 30 ; const grayscale = config . grayscale || false ; const deviceIndex = config . deviceIndex || - 1 ; Assert . ok ( typeof ( fake ) , 'boolean' ) ; Assert . ok ( typeof ( width ) , 'number' ) ; Assert . ok ( typeof ( height ) , 'number' ) ; Assert . ok ( typeof ( framerate ) , 'number' ) ; Assert . ok ( typeof ( grayscale ) , 'boolean' ) ; var gst_multipart_boundary = '--videoboundary' ; var gst_video_src = '' ; if ( ! fake ) { if ( OS . platform ( ) == 'win32' ) gst_video_src = 'ksvideosrc device-index=' + deviceIndex + ' ! decodebin' ; else if ( OS . platform ( ) == 'linux' ) gst_video_src = 'v4l2src ! decodebin' ; else if ( OS . platform ( ) == 'darwin' ) gst_video_src = 'avfvideosrc device-index=' + deviceIndex ; else Assert . ok ( false , 'unsupported platform' ) } else { gst_video_src = 'videotestsrc' ; } if ( width > 0 || height > 0 ) { gst_video_src += ' ! videoscale ! video/x-raw,width=' + parseInt ( width ) + ',height=' + parseInt ( height ) ; } if ( framerate > 0 ) { gst_video_src += ' ! videorate ! video/x-raw,framerate=' + parseInt ( framerate ) + '/1' ; } if ( grayscale ) { gst_video_src += ' ! videobalance saturation=0.0 ! videoconvert' ; } /*!
   * @fn start
   * @brief Starts a GStreamer pipeline that broadcasts the default
   * webcam over the given TCP address and port.
   * @return A Node <child-process> of the launched pipeline
   */ var start = function ( tcp_addr , tcp_port ) { Assert . ok ( typeof ( tcp_addr ) , 'string' ) ; Assert . ok ( typeof ( tcp_port ) , 'number' ) ; const cam_pipeline = gst_video_src + ' ! jpegenc ! multipartmux  boundary="' + gst_multipart_boundary + '" ! tcpserversink host=' + tcp_addr + ' port=' + tcp_port ; var gst_launch = new GstLaunch ( ) ; if ( gst_launch . isAvailable ( ) ) { console . log ( 'GstLaunch found: ' + gst_launch . getPath ( ) ) ; console . log ( 'GStreamer version: ' + gst_launch . getVersion ( ) ) ; console . log ( 'GStreamer pipeline: ' + cam_pipeline ) ; return gst_launch . spawnPipeline ( cam_pipeline ) ; } else { throw new Error ( 'GstLaunch not found.' ) ; } } return { 'start' : start } }


Input: / * ! [CODESPLIT] function ( tcp_addr , tcp_port ) { Assert . ok ( typeof ( tcp_addr ) , 'string' ) ; Assert . ok ( typeof ( tcp_port ) , 'number' ) ; const cam_pipeline = gst_video_src + ' ! jpegenc ! multipartmux  boundary="' + gst_multipart_boundary + '" ! tcpserversink host=' + tcp_addr + ' port=' + tcp_port ; var gst_launch = new GstLaunch ( ) ; if ( gst_launch . isAvailable ( ) ) { console . log ( 'GstLaunch found: ' + gst_launch . getPath ( ) ) ; console . log ( 'GStreamer version: ' + gst_launch . getVersion ( ) ) ; console . log ( 'GStreamer pipeline: ' + cam_pipeline ) ; return gst_launch . spawnPipeline ( cam_pipeline ) ; } else { throw new Error ( 'GstLaunch not found.' ) ; } }


Input:
/ * ! [CODESPLIT] function SocketCamWrapper ( gst_tcp_addr , gst_tcp_port , broadcast_tcp_addr , broadcast_tcp_port ) { const Net = require ( 'net' ) ; const Http = require ( 'http' ) ; const Dicer = require ( 'dicer' ) ; const Assert = require ( 'assert' ) ; const SocketIO = require ( 'socket.io' ) ; const gst_multipart_boundary = '--videoboundary' ; /*!
   * @fn wrap
   * @brief wraps a TCP server previously started by GstLiveCamServer.
   */ var wrap = function ( gst_tcp_addr , gst_tcp_port , broadcast_tcp_addr , broadcast_tcp_port ) { Assert . ok ( typeof ( gst_tcp_addr ) , 'string' ) ; Assert . ok ( typeof ( gst_tcp_port ) , 'number' ) ; Assert . ok ( typeof ( broadcast_tcp_addr ) , 'string' ) ; Assert . ok ( typeof ( broadcast_tcp_port ) , 'number' ) ; var socket = Net . Socket ( ) ; socket . connect ( gst_tcp_port , gst_tcp_addr , function ( ) { var io = SocketIO . listen ( Http . createServer ( ) . listen ( broadcast_tcp_port , broadcast_tcp_addr ) ) ; var dicer = new Dicer ( { boundary : gst_multipart_boundary } ) ; dicer . on ( 'part' , function ( part ) { var frameEncoded = '' ; part . setEncoding ( 'base64' ) ; part . on ( 'data' , function ( data ) { frameEncoded += data ; } ) ; part . on ( 'end' , function ( ) { io . sockets . emit ( 'image' , frameEncoded ) ; } ) ; } ) ; dicer . on ( 'finish' , function ( ) { console . log ( 'Dicer finished: ' + broadcast_tcp_addr + ':' + broadcast_tcp_port ) ; } ) ; socket . on ( 'close' , function ( ) { console . log ( 'Socket closed: ' + broadcast_tcp_addr + ':' + broadcast_tcp_port ) ; } ) ; socket . pipe ( dicer ) ; } ) ; } return { 'wrap' : wrap } }


Input:
/ * ! [CODESPLIT] function LiveCamUI ( ) { const Http = require ( 'http' ) ; const Assert = require ( 'assert' ) ; const template = ( function ( ) { /*
    	<!doctype html>

    			<meta charset="utf-8">
    			<title>livecam UI</title>

    			<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">

    	*/ } ) . toString ( ) . match ( / \/\*\s*([\s\S]*?)\s*\*\/ / m ) [ 1 ] ; var server = undefined ; var serve = function ( ui_addr , ui_port , webcam_addr , webcam_port ) { Assert . ok ( typeof ( ui_addr ) , 'object' ) ; Assert . ok ( typeof ( ui_port ) , 'number' ) ; Assert . ok ( typeof ( webcam_addr ) , 'object' ) ; Assert . ok ( typeof ( webcam_port ) , 'number' ) ; close ( ) ; server = Http . createServer ( function ( request , response ) { response . writeHead ( 200 , { "Content-Type" : "text/html" } ) ; response . write ( template . replace ( '@WEBCAM_ADDR@' , webcam_addr ) . replace ( '@WEBCAM_PORT@' , webcam_port ) ) ; response . end ( ) ; } ) ; server . listen ( ui_port , ui_addr ) ; console . log ( 'Open http://' + ui_addr + ':' + ui_port + '/ in your browser!' ) ; } var close = function ( ) { if ( server ) { server . close ( ) ; server = undefined ; } } return { 'serve' : serve , 'close' : close } }


Input: / * ! [CODESPLIT] function LiveCam ( config ) { const Assert = require ( 'assert' ) ; config = config || { } ; Assert . ok ( typeof ( config ) , 'object' ) ; const gst_tcp_addr = config . gst_addr || "127.0.0.1" ; const gst_tcp_port = config . gst_port || 10000 ; const ui_addr = config . ui_addr || "127.0.0.1" ; const ui_port = config . ui_port || 11000 ; const broadcast_addr = config . broadcast_addr || "127.0.0.1" ; const broadcast_port = config . broadcast_port || 12000 ; const start = config . start ; const webcam = config . webcam || { } ; if ( start ) Assert . ok ( typeof ( start ) , 'function' ) ; if ( broadcast_port ) Assert . ok ( typeof ( broadcast_port ) , 'number' ) ; if ( broadcast_addr ) Assert . ok ( typeof ( broadcast_addr ) , 'string' ) ; if ( ui_port ) Assert . ok ( typeof ( ui_port ) , 'number' ) ; if ( ui_addr ) Assert . ok ( typeof ( ui_addr ) , 'string' ) ; if ( gst_tcp_port ) Assert . ok ( typeof ( gst_tcp_port ) , 'number' ) ; if ( gst_tcp_addr ) Assert . ok ( typeof ( gst_tcp_addr ) , 'string' ) ; if ( webcam ) Assert . ok ( typeof ( webcam ) , 'object' ) ; if ( ! ( new GstLaunch ( ) ) . isAvailable ( ) ) { console . log ( "==================================================" ) ; console . log ( "Unable to locate gst-launch executable." ) ; console . log ( "Look at https://github.com/sepehr-laal/livecam" ) ; console . log ( "You are most likely missing the GStreamer runtime." ) ; console . log ( "==================================================" ) ; throw new Error ( 'Unable to broadcast.' ) ; } console . log ( "LiveCam parameters:" , { 'broadcast_addr' : broadcast_addr , 'broadcast_port' : broadcast_port , 'ui_addr' : ui_addr , 'ui_port' : ui_port , 'gst_tcp_addr' : gst_tcp_addr , 'gst_tcp_port' : gst_tcp_port } ) ; var broadcast = function ( ) { var gst_cam_ui = new LiveCamUI ( ) ; var gst_cam_wrap = new SocketCamWrapper ( ) ; var gst_cam_server = new GstLiveCamServer ( webcam ) ; var gst_cam_process = gst_cam_server . start ( gst_tcp_addr , gst_tcp_port ) ; gst_cam_process . stdout . on ( 'data' , function ( data ) { console . log ( data . toString ( ) ) ; // This catches GStreamer when pipeline goes into PLAYING state if ( data . toString ( ) . includes ( 'Setting pipeline to PLAYING' ) > 0 ) { gst_cam_wrap . wrap ( gst_tcp_addr , gst_tcp_port , broadcast_addr , broadcast_port ) ; gst_cam_ui . serve ( ui_addr , ui_port , broadcast_addr , broadcast_port ) ; gst_cam_ui . close ( ) ; if ( start ) start ( ) ; } } ) ; gst_cam_process . stderr . on ( 'data' , function ( data ) { console . log ( data . toString ( ) ) ; gst_cam_ui . close ( ) ; } ) ; gst_cam_process . on ( 'error' , function ( err ) { console . log ( "Webcam server error: " + err ) ; gst_cam_ui . close ( ) ; } ) ; gst_cam_process . on ( 'exit' , function ( code ) { console . log ( "Webcam server exited: " + code ) ; gst_cam_ui . close ( ) ; } ) ; } return { 'broadcast' : broadcast } }


Input: Hex to RGB converter [CODESPLIT] function hexRgb ( hex ) { let shorthandCheck = / ^([a-f\d])([a-f\d])([a-f\d])$ / i , rgbRegex = / ^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$ / i , rgb ; hex = hex . replace ( shorthandCheck , function ( m , r , g , b ) { return r + r + g + g + b + b ; } ) ; rgb = hex . replace ( / ^\s+|\s+$ / g , '' ) . match ( rgbRegex ) ; // Convert it return rgb ? [ parseInt ( rgb [ 1 ] , 16 ) , parseInt ( rgb [ 2 ] , 16 ) , parseInt ( rgb [ 3 ] , 16 ) ] : false ; }


Input: CSS rule handler [CODESPLIT] function ruleHandler ( decl , result ) { let input = decl . value ; // Get the raw hex values and replace them let output = input . replace ( / rgba\(#(.*?), / g , ( match , hex ) => { let rgb = hexRgb ( hex ) , matchHex = new RegExp ( '#' + hex ) ; // If conversion fails, emit a warning if ( ! rgb ) { result . warn ( 'not a valid hex' , { node : decl } ) ; return match ; } rgb = rgb . toString ( ) ; return match . replace ( matchHex , rgb ) ; } ) ; decl . replaceWith ( { prop : decl . prop , value : output , important : decl . important } ) ; }


Input: Segment service [CODESPLIT] function Segment ( config ) { this . config = config ; // Checks condition before calling Segment method this . factory = function ( method ) { var _this = this ; return function ( ) { // If a condition has been set, only call the Segment method if it returns true if ( _this . config . condition && ! _this . config . condition ( method , arguments ) ) { _this . debug ( 'Not calling method, condition returned false.' , { method : method , arguments : arguments , } ) ; return ; } //  No condition set, call the Segment method _this . debug ( 'Calling method ' + method + ' with arguments:' , arguments ) ; return window . analytics [ method ] . apply ( analytics , arguments ) ; } ; } ; }


Input: Creates analytics . js method stubs [CODESPLIT] function ( ) { for ( var i = 0 ; i < this . config . methods . length ; i ++ ) { var key = this . config . methods [ i ] ; // Only create analytics stub if it doesn't already exist if ( ! analytics [ key ] ) { analytics [ key ] = analytics . factory ( key ) ; } this [ key ] = this . factory ( key ) ; } }


Input: Segment provider available during . config () Angular app phase . Inherits from Segment prototype . [CODESPLIT] function SegmentProvider ( segmentDefaultConfig ) { this . config = angular . copy ( segmentDefaultConfig ) ; // Stores any analytics.js method calls this . queue = [ ] ; // Overwrite Segment factory to queue up calls if condition has been set this . factory = function ( method ) { var queue = this . queue ; return function ( ) { // Defer calling analytics.js methods until the service is instantiated queue . push ( { method : method , arguments : arguments } ) ; } ; } ; // Create method stubs using overridden factory this . init ( ) ; this . setKey = function ( apiKey ) { this . config . apiKey = apiKey ; this . validate ( 'apiKey' ) ; return this ; } ; this . setLoadDelay = function ( milliseconds ) { this . config . loadDelay = milliseconds ; this . validate ( 'loadDelay' ) ; return this ; } ; this . setCondition = function ( callback ) { this . config . condition = callback ; this . validate ( 'condition' ) ; return this ; } ; this . setEvents = function ( events ) { this . events = events ; return this ; } ; this . setConfig = function ( config ) { if ( ! angular . isObject ( config ) ) { throw new Error ( this . config . tag + 'Config must be an object.' ) ; } angular . extend ( this . config , config ) ; // Validate new settings var _this = this ; Object . keys ( config ) . forEach ( function ( key ) { _this . validate ( key ) ; } ) ; return this ; } ; this . setAutoload = function ( bool ) { this . config . autoload = ! ! bool ; return this ; } ; this . setDebug = function ( bool ) { this . config . debug = ! ! bool ; return this ; } ; var validations = { apiKey : function ( config ) { if ( ! angular . isString ( config . apiKey ) || ! config . apiKey ) { throw new Error ( config . tag + 'API key must be a valid string.' ) ; } } , loadDelay : function ( config ) { if ( ! angular . isNumber ( config . loadDelay ) ) { throw new Error ( config . tag + 'Load delay must be a number.' ) ; } } , condition : function ( config ) { if ( ! angular . isFunction ( config . condition ) && ! ( angular . isArray ( config . condition ) && angular . isFunction ( config . condition [ config . condition . length - 1 ] ) ) ) { throw new Error ( config . tag + 'Condition callback must be a function or array.' ) ; } } , } ; // Allows validating a specific property after set[Prop] // or all config after provider/constant config this . validate = function ( property ) { if ( typeof validations [ property ] === 'function' ) { validations [ property ] ( this . config ) ; } } ; this . createService = function ( $injector , segmentLoader ) { // Apply user-provided config constant if it exists if ( $injector . has ( 'segmentConfig' ) ) { var constant = $injector . get ( 'segmentConfig' ) ; if ( ! angular . isObject ( constant ) ) { throw new Error ( this . config . tag + 'Config constant must be an object.' ) ; } angular . extend ( this . config , constant ) ; this . debug ( 'Found segment config constant' ) ; // Validate settings passed in by constant var _this = this ; Object . keys ( constant ) . forEach ( function ( key ) { _this . validate ( key ) ; } ) ; } // Autoload Segment on service instantiation if an API key has been set via the provider if ( this . config . autoload ) { this . debug ( 'Autoloading Analytics.js' ) ; if ( this . config . apiKey ) { segmentLoader . load ( this . config . apiKey , this . config . loadDelay ) ; } else { this . debug ( this . config . tag + ' Warning: API key is not set and autoload is not disabled.' ) ; } } // Create dependency-injected condition if ( typeof this . config . condition === 'function' || ( typeof this . config . condition === 'array' && typeof this . config . condition [ this . config . condition - 1 ] === 'function' ) ) { var condition = this . config . condition ; this . config . condition = function ( method , params ) { return $injector . invoke ( condition , condition , { method : method , params : params } ) ; } ; } // Pass any provider-set configuration down to the service var segment = new Segment ( angular . copy ( this . config ) ) ; // Transfer events if set if ( this . events ) { segment . events = angular . copy ( this . events ) ; } // Set up service method stubs segment . init ( ) ; // Play back any segment calls that were made against the provider now that the // condition callback has been injected with dependencies this . queue . forEach ( function ( item ) { segment [ item . method ] . apply ( segment , item . arguments ) ; } ) ; return segment ; } ; // Returns segment service and creates dependency-injected condition callback, if provided this . $get = [ '$injector' , 'segmentLoader' , this . createService ] ; }


Input: In hindsight we can do without most of ES6 ( str obj ) - > transformStream [CODESPLIT] function es2020 ( filename , options ) { if ( / \.json$ / i . test ( filename ) ) return through ( ) const bufs = [ ] const transformStream = through ( write , end ) return transformStream function write ( buf , enc , next ) { bufs . push ( buf ) next ( ) } function end ( ) { const src = Buffer . concat ( bufs ) . toString ( 'utf8' ) try { var res = babel . transform ( src , { plugins : preset . plugins , sourceMaps : options . _flags . debug ? 'inline' : false , filename : filename , compact : false } ) } catch ( err ) { this . emit ( 'error' , err ) return } this . push ( res . code ) this . push ( null ) } }


Input: For each small multiple… [CODESPLIT] function bulvar ( g ) { g . each ( function ( d , i ) { var rangez = ranges . call ( this , d , i ) . slice ( ) . sort ( d3Descending ) , markerz = markers . call ( this , d , i ) . slice ( ) . sort ( d3Descending ) , measurez = measures . call ( this , d , i ) . slice ( ) . sort ( d3Descending ) , g2 = d3Select ( this ) , extentX , extentY ; var wrap = g2 . select ( "g.wrap" ) ; if ( wrap . empty ( ) ) wrap = g2 . append ( "g" ) . attr ( "class" , "wrap" ) ; if ( vertical ) { extentX = height , extentY = width ; wrap . attr ( "transform" , "rotate(90)translate(0," + - width + ")" ) ; } else { extentX = width , extentY = height ; wrap . attr ( "transform" , null ) ; } // Compute the new x-scale. var x1 = d3ScaleLinear ( ) . domain ( [ 0 , Math . max ( rangez [ 0 ] , markerz [ 0 ] , measurez [ 0 ] ) ] ) . range ( reverse ? [ extentX , 0 ] : [ 0 , extentX ] ) ; // Retrieve the old x-scale, if this is an update. var x0 = this . __chart__ || d3ScaleLinear ( ) . domain ( [ 0 , Infinity ] ) . range ( x1 . range ( ) ) ; // Stash the new scale. this . __chart__ = x1 ; // Derive width-scales from the x-scales. var w0 = bulvarWidth ( x0 ) , w1 = bulvarWidth ( x1 ) ; // Update the range rects. var range = wrap . selectAll ( "rect.range" ) . data ( rangez ) ; range . enter ( ) . append ( "rect" ) . attr ( "class" , function ( _d , i2 ) { return "range s" + i2 ; } ) . attr ( "width" , w0 ) . attr ( "height" , extentY ) . attr ( "x" , reverse ? x0 : 0 ) . merge ( range ) . transition ( range ) . attr ( "x" , reverse ? x1 : 0 ) . attr ( "width" , w1 ) . attr ( "height" , extentY ) ; // Update the measure rects. var measure = wrap . selectAll ( "rect.measure" ) . data ( measurez ) ; measure . enter ( ) . append ( "rect" ) . attr ( "class" , function ( _d , i2 ) { return "measure s" + i2 ; } ) . attr ( "width" , w0 ) . attr ( "height" , extentY / 3 ) . attr ( "x" , reverse ? x0 : 0 ) . attr ( "y" , extentY / 3 ) . merge ( measure ) . transition ( measure ) . attr ( "width" , w1 ) . attr ( "height" , extentY / 3 ) . attr ( "x" , reverse ? x1 : 0 ) . attr ( "y" , extentY / 3 ) ; // Update the marker lines. var marker = wrap . selectAll ( "line.marker" ) . data ( markerz ) ; marker . enter ( ) . append ( "line" ) . attr ( "class" , "marker" ) . attr ( "x1" , x0 ) . attr ( "x2" , x0 ) . attr ( "y1" , extentY / 6 ) . attr ( "y2" , extentY * 5 / 6 ) . merge ( marker ) . transition ( marker ) . attr ( "x1" , x1 ) . attr ( "x2" , x1 ) . attr ( "y1" , extentY / 6 ) . attr ( "y2" , extentY * 5 / 6 ) ; var axis = g2 . selectAll ( "g.axis" ) . data ( [ 0 ] ) ; axis . enter ( ) . append ( "g" ) . attr ( "class" , "axis" ) ; axis . attr ( "transform" , vertical ? null : "translate(0," + extentY + ")" ) . call ( xAxis . scale ( x1 ) ) ; } ) ; d3TimerFlush ( ) ; }


Input: Generates the Name - Based UUID hashes v3 and v5 according to RFC - 4122 https : // tools . ietf . org / html / rfc4122#section - 4 . 3 [CODESPLIT] function generateUuid ( target , namespace , version ) { if ( typeof target !== 'string' ) { throw TypeError ( 'Value must be string' ) ; } if ( typeof namespace === 'number' ) { return generateUuid ( target , undefined , namespace ) ; } if ( version == null ) { return generateUuid ( target , namespace , 5 ) ; } if ( version !== 3 && version !== 5 ) { throw TypeError ( 'Version of UUID can be only 3 or 5' ) ; } // Parsing target chars var charBuffer = lib . stringToCharBuffer ( target ) ; // TODO: Test namespace for uuid and parse to buffer var namespaceCharBuffer = typeof namespace === 'string' ? lib . stringToCharBuffer ( namespace ) : EMPTY_UINT8_ARRAY ; // Concatenation two buffers of strings to one var buffer = lib . concatBuffers ( namespaceCharBuffer , charBuffer ) ; // Getting hash var hash = version === 3 ? lib . md5Hash ( buffer ) : lib . sha1Hash ( buffer ) ; return lib . hashToUuid ( hash , version ) ; }


Input: Get color for value [CODESPLIT] function getColorGrad ( pct , col , maxBri ) { var no , inc , colors , percentage , rval , gval , bval , lower , upper , range , rangePct , pctLower , pctUpper , color , pow ; no = col . length ; if ( no === 1 ) return col [ 0 ] ; inc = 1 / ( no - 1 ) ; colors = [ ] ; for ( var i = 0 ; i < col . length ; i ++ ) { if ( typeof col [ i ] === 'object' ) { percentage = col [ i ] . pct ? col [ i ] . pct : inc * i ; pow = col [ i ] . pow || 1 ; rval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 0 , 2 ) , 16 ) ; gval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 2 , 4 ) , 16 ) ; bval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 4 , 6 ) , 16 ) ; } else { percentage = inc * i ; pow = 1 ; rval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 0 , 2 ) , 16 ) ; gval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 2 , 4 ) , 16 ) ; bval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 4 , 6 ) , 16 ) ; } colors [ i ] = { pct : percentage , pow : pow , color : { r : rval , g : gval , b : bval } } ; } if ( pct === 0 ) { return 'rgb(' + [ colors [ 0 ] . color . r , colors [ 0 ] . color . g , colors [ 0 ] . color . b ] . join ( ',' ) + ')' ; } for ( var j = 0 ; j < colors . length ; j ++ ) { if ( pct <= colors [ j ] . pct ) { var colorMax = Math . max ( colors [ j ] . color . r , colors [ j ] . color . g , colors [ j ] . color . b ) ; lower = colors [ j - 1 ] ; upper = colors [ j ] ; range = upper . pct - lower . pct ; rangePct = Math . pow ( ( pct - lower . pct ) / range , colors [ j ] . pow / colors [ j - 1 ] . pow ) ; pctLower = 1 - rangePct ; pctUpper = rangePct ; color = { r : Math . floor ( lower . color . r * pctLower + upper . color . r * pctUpper ) , g : Math . floor ( lower . color . g * pctLower + upper . color . g * pctUpper ) , b : Math . floor ( lower . color . b * pctLower + upper . color . b * pctUpper ) } ; if ( maxBri ) { var colorMax2 = Math . max ( color . r , color . g , color . b ) ; return 'rgb(' + [ Math . floor ( color . r / colorMax2 * colorMax ) , Math . floor ( color . g / colorMax2 * colorMax ) , Math . floor ( color . b / colorMax2 * colorMax ) ] . join ( ',' ) + ')' ; } else { return 'rgb(' + [ color . r , color . g , color . b ] . join ( ',' ) + ')' ; } } } }


Input: tiny helper function to lookup value of a key from two hash tables if none found return defaultvalue key : string tablea : object tableb : DOMStringMap|object defval : string|integer|float|null datatype : return datatype delimiter : delimiter to be used in conjunction with datatype formatting [CODESPLIT] function kvLookup ( key , tablea , tableb , defval , datatype , delimiter ) { var val = defval ; var canConvert = false ; if ( ! ( key === null || key === undefined ) ) { if ( tableb !== null && tableb !== undefined && typeof tableb === "object" && key in tableb ) { val = tableb [ key ] ; canConvert = true ; } else if ( tablea !== null && tablea !== undefined && typeof tablea === "object" && key in tablea ) { val = tablea [ key ] ; canConvert = true ; } else { val = defval ; } if ( canConvert === true ) { if ( datatype !== null && datatype !== undefined ) { switch ( datatype ) { case 'int' : val = parseInt ( val , 10 ) ; break ; case 'float' : val = parseFloat ( val ) ; break ; default : break ; } } } } return val ; }


Input: Get color for value [CODESPLIT] function getColor ( val , pct , col , noGradient , custSec , fullBri ) { var no , inc , colors , percentage , rval , gval , bval , lower , upper , range , rangePct , pctLower , pctUpper , color , pow ; var noGradient = noGradient || custSec . length > 0 ; if ( custSec . length > 0 ) { for ( var i = 0 ; i < custSec . length ; i ++ ) { if ( val >= custSec [ i ] . lo && val <= custSec [ i ] . hi ) { return custSec [ i ] . color ; } } } no = col . length ; if ( no === 1 ) return col [ 0 ] ; inc = ( noGradient ) ? ( 1 / no ) : ( 1 / ( no - 1 ) ) ; colors = [ ] ; for ( i = 0 ; i < col . length ; i ++ ) { if ( typeof col [ i ] === 'object' ) { percentage = col [ i ] . pct ? col [ i ] . pct : ( ( noGradient ) ? ( inc * ( i + 1 ) ) : ( inc * i ) ) ; pow = col [ i ] . pow || 1 ; rval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 0 , 2 ) , 16 ) ; gval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 2 , 4 ) , 16 ) ; bval = parseInt ( ( cutHex ( col [ i ] . color ) ) . substring ( 4 , 6 ) , 16 ) ; } else { percentage = ( noGradient ) ? ( inc * ( i + 1 ) ) : ( inc * i ) ; pow = 1 ; rval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 0 , 2 ) , 16 ) ; gval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 2 , 4 ) , 16 ) ; bval = parseInt ( ( cutHex ( col [ i ] ) ) . substring ( 4 , 6 ) , 16 ) ; } colors [ i ] = { pct : percentage , pow : pow , color : { r : rval , g : gval , b : bval } } ; } if ( pct === 0 ) { return 'rgb(' + [ colors [ 0 ] . color . r , colors [ 0 ] . color . g , colors [ 0 ] . color . b ] . join ( ',' ) + ')' ; } for ( var j = 0 ; j < colors . length ; j ++ ) { if ( pct <= colors [ j ] . pct ) { var colorMax = Math . max ( colors [ j ] . color . r , colors [ j ] . color . g , colors [ j ] . color . b ) ; if ( noGradient ) { return 'rgb(' + [ colors [ j ] . color . r , colors [ j ] . color . g , colors [ j ] . color . b ] . join ( ',' ) + ')' ; } else { lower = colors [ j - 1 ] ; upper = colors [ j ] ; range = upper . pct - lower . pct ; rangePct = Math . pow ( ( pct - lower . pct ) / range , colors [ j ] . pow / colors [ j - 1 ] . pow ) ; pctLower = 1 - rangePct ; pctUpper = rangePct ; color = { r : Math . floor ( lower . color . r * pctLower + upper . color . r * pctUpper ) , g : Math . floor ( lower . color . g * pctLower + upper . color . g * pctUpper ) , b : Math . floor ( lower . color . b * pctLower + upper . color . b * pctUpper ) } ; if ( fullBri ) { colorMax2 = Math . max ( color . r , color . g , color . b ) ; return 'rgb(' + [ Math . floor ( color . r / colorMax2 * colorMax ) , Math . floor ( color . g / colorMax2 * colorMax ) , Math . floor ( color . b / colorMax2 * colorMax ) ] . join ( ',' ) + ')' ; } else { return 'rgb(' + [ color . r , color . g , color . b ] . join ( ',' ) + ')' ; } } } } }


Input: Fix Raphael display : none tspan dy attribute bug [CODESPLIT] function setDy ( elem , fontSize , txtYpos ) { if ( ( ! ie || ie > 9 ) && elem . node . firstChild . attributes . dy ) { elem . node . firstChild . attributes . dy . value = 0 ; } }


Input: Human friendly number suffix - From : http : // stackoverflow . com / questions / 2692323 / code - golf - friendly - number - abbreviator [CODESPLIT] function humanFriendlyNumber ( n , d ) { var p , d2 , i , s ; p = Math . pow ; d2 = p ( 10 , d ) ; i = 7 ; while ( i ) { s = p ( 10 , i -- * 3 ) ; if ( s <= n ) { n = Math . round ( n * d2 / s ) / d2 + "KMGTPE" [ i ] ; } } return n ; }


Input: Format numbers with commas - From : http : // stackoverflow . com / questions / 2901102 / how - to - print - a - number - with - commas - as - thousands - separators - in - javascript [CODESPLIT] function formatNumber ( x ) { var parts = x . toString ( ) . split ( "." ) ; parts [ 0 ] = parts [ 0 ] . replace ( / \B(?=(\d{3})+(?!\d)) / g , "," ) ; return parts . join ( "." ) ; }


Input: Short format for ms . [CODESPLIT] function fmtShort ( ms ) { if ( ms >= d$1 ) { return Math . round ( ms / d$1 ) + 'd' } if ( ms >= h ) { return Math . round ( ms / h ) + 'h' } if ( ms >= m ) { return Math . round ( ms / m ) + 'm' } if ( ms >= s ) { return Math . round ( ms / s ) + 's' } return ms + 'ms' }


Input: Long format for ms . [CODESPLIT] function fmtLong ( ms ) { return plural ( ms , d$1 , 'day' ) || plural ( ms , h , 'hour' ) || plural ( ms , m , 'minute' ) || plural ( ms , s , 'second' ) || ms + ' ms' }


Input: Create a debugger with the given namespace . [CODESPLIT] function debug ( namespace ) { // define the `disabled` version function disabled ( ) { } disabled . enabled = false ; // define the `enabled` version function enabled ( ) { var self = enabled ; // set `diff` timestamp var curr = + new Date ( ) ; var ms = curr - ( prevTime || curr ) ; self . diff = ms ; self . prev = prevTime ; self . curr = curr ; prevTime = curr ; // add the `color` if not set if ( null == self . useColors ) self . useColors = exports . useColors ( ) ; if ( null == self . color && self . useColors ) self . color = selectColor ( ) ; var args = new Array ( arguments . length ) ; for ( var i = 0 ; i < args . length ; i ++ ) { args [ i ] = arguments [ i ] ; } args [ 0 ] = exports . coerce ( args [ 0 ] ) ; if ( 'string' !== typeof args [ 0 ] ) { // anything else let's inspect with %o args = [ '%o' ] . concat ( args ) ; } // apply any `formatters` transformations var index = 0 ; args [ 0 ] = args [ 0 ] . replace ( / %([a-z%]) / g , function ( match , format ) { // if we encounter an escaped % then don't increase the array index if ( match === '%%' ) return match ; index ++ ; var formatter = exports . formatters [ format ] ; if ( 'function' === typeof formatter ) { var val = args [ index ] ; match = formatter . call ( self , val ) ; // now we need to remove `args[index]` since it's inlined in the `format` args . splice ( index , 1 ) ; index -- ; } return match ; } ) ; // apply env-specific formatting args = exports . formatArgs . apply ( self , args ) ; var logFn = enabled . log || exports . log || console . log . bind ( console ) ; logFn . apply ( self , args ) ; } enabled . enabled = true ; var fn = exports . enabled ( namespace ) ? enabled : disabled ; fn . namespace = namespace ; return fn ; }


Input: Enables a debug mode by namespaces . This can include modes separated by a colon and wildcards . [CODESPLIT] function enable ( namespaces ) { exports . save ( namespaces ) ; var split = ( namespaces || '' ) . split ( / [\s,]+ / ) ; var len = split . length ; for ( var i = 0 ; i < len ; i ++ ) { if ( ! split [ i ] ) continue ; // ignore empty strings namespaces = split [ i ] . replace ( / [\\^$+?.()|[\]{}] / g , '\\$&' ) . replace ( / \* / g , '.*?' ) ; if ( namespaces [ 0 ] === '-' ) { exports . skips . push ( new RegExp ( '^' + namespaces . substr ( 1 ) + '$' ) ) ; } else { exports . names . push ( new RegExp ( '^' + namespaces + '$' ) ) ; } } }


Input: Parse or format the given val . [CODESPLIT] function ( val , options ) { options = options || { } ; if ( 'string' == typeof val ) return parse$1 ( val ) ; return options . long ? long ( val ) : short ( val ) ; }


Input: Parse the given str and return milliseconds . [CODESPLIT] function parse$1 ( str ) { str = '' + str ; if ( str . length > 10000 ) return ; var match = / ^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$ / i . exec ( str ) ; if ( ! match ) return ; var n = parseFloat ( match [ 1 ] ) ; var type = ( match [ 2 ] || 'ms' ) . toLowerCase ( ) ; switch ( type ) { case 'years' : case 'year' : case 'yrs' : case 'yr' : case 'y' : return n * y$1 ; case 'days' : case 'day' : case 'd' : return n * d$2 ; case 'hours' : case 'hour' : case 'hrs' : case 'hr' : case 'h' : return n * h$1 ; case 'minutes' : case 'minute' : case 'mins' : case 'min' : case 'm' : return n * m$1 ; case 'seconds' : case 'second' : case 'secs' : case 'sec' : case 's' : return n * s$1 ; case 'milliseconds' : case 'millisecond' : case 'msecs' : case 'msec' : case 'ms' : return n ; } }


Input: Short format for ms . [CODESPLIT] function short ( ms ) { if ( ms >= d$2 ) return Math . round ( ms / d$2 ) + 'd' ; if ( ms >= h$1 ) return Math . round ( ms / h$1 ) + 'h' ; if ( ms >= m$1 ) return Math . round ( ms / m$1 ) + 'm' ; if ( ms >= s$1 ) return Math . round ( ms / s$1 ) + 's' ; return ms + 'ms' ; }


Input: Long format for ms . [CODESPLIT] function long ( ms ) { return plural$1 ( ms , d$2 , 'day' ) || plural$1 ( ms , h$1 , 'hour' ) || plural$1 ( ms , m$1 , 'minute' ) || plural$1 ( ms , s$1 , 'second' ) || ms + ' ms' ; }


Input: Pluralization helper . [CODESPLIT] function plural$1 ( ms , n , name ) { if ( ms < n ) return ; if ( ms < n * 1.5 ) return Math . floor ( ms / n ) + ' ' + name ; return Math . ceil ( ms / n ) + ' ' + name + 's' ; }


Input: Returns true if obj is a buffer or an arraybuffer . [CODESPLIT] function isBuf$1 ( obj ) { return ( commonjsGlobal . Buffer && commonjsGlobal . Buffer . isBuffer ( obj ) ) || ( commonjsGlobal . ArrayBuffer && obj instanceof ArrayBuffer ) ; }


Input: Return a string representing the specified number . [CODESPLIT] function encode$1 ( num ) { var encoded = '' ; do { encoded = alphabet [ num % length ] + encoded ; num = Math . floor ( num / length ) ; } while ( num > 0 ) ; return encoded ; }


Input: Return the integer value specified by the given string . [CODESPLIT] function decode$1 ( str ) { var decoded = 0 ; for ( i = 0 ; i < str . length ; i ++ ) { decoded = decoded * length + map [ str . charAt ( i ) ] ; } return decoded ; }


Input: Yeast : A tiny growing id generator . [CODESPLIT] function yeast$1 ( ) { var now = encode$1 ( + new Date ( ) ) ; if ( now !== prev ) return seed = 0 , prev = now ; return now + '.' + encode$1 ( seed ++ ) ; }


Input: Parse or format the given val . [CODESPLIT] function ( val , options ) { options = options || { } ; var type = typeof val ; if ( type === 'string' && val . length > 0 ) { return parse$2 ( val ) } else if ( type === 'number' && isNaN ( val ) === false ) { return options . long ? fmtLong$1 ( val ) : fmtShort$1 ( val ) } throw new Error ( 'val is not a non-empty string or a valid number. val=' + JSON . stringify ( val ) ) }


Input: Parse the given str and return milliseconds . [CODESPLIT] function parse$2 ( str ) { str = String ( str ) ; if ( str . length > 10000 ) { return } var match = / ^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$ / i . exec ( str ) ; if ( ! match ) { return } var n = parseFloat ( match [ 1 ] ) ; var type = ( match [ 2 ] || 'ms' ) . toLowerCase ( ) ; switch ( type ) { case 'years' : case 'year' : case 'yrs' : case 'yr' : case 'y' : return n * y$2 case 'days' : case 'day' : case 'd' : return n * d$3 case 'hours' : case 'hour' : case 'hrs' : case 'hr' : case 'h' : return n * h$2 case 'minutes' : case 'minute' : case 'mins' : case 'min' : case 'm' : return n * m$2 case 'seconds' : case 'second' : case 'secs' : case 'sec' : case 's' : return n * s$2 case 'milliseconds' : case 'millisecond' : case 'msecs' : case 'msec' : case 'ms' : return n default : return undefined } }


Input: Short format for ms . [CODESPLIT] function fmtShort$1 ( ms ) { if ( ms >= d$3 ) { return Math . round ( ms / d$3 ) + 'd' } if ( ms >= h$2 ) { return Math . round ( ms / h$2 ) + 'h' } if ( ms >= m$2 ) { return Math . round ( ms / m$2 ) + 'm' } if ( ms >= s$2 ) { return Math . round ( ms / s$2 ) + 's' } return ms + 'ms' }


Input: Long format for ms . [CODESPLIT] function fmtLong$1 ( ms ) { return plural$2 ( ms , d$3 , 'day' ) || plural$2 ( ms , h$2 , 'hour' ) || plural$2 ( ms , m$2 , 'minute' ) || plural$2 ( ms , s$2 , 'second' ) || ms + ' ms' }


Input: Pluralization helper . [CODESPLIT] function plural$2 ( ms , n , name ) { if ( ms < n ) { return } if ( ms < n * 1.5 ) { return Math . floor ( ms / n ) + ' ' + name } return Math . ceil ( ms / n ) + ' ' + name + 's' }


Input: Polling interface . [CODESPLIT] function Polling$1 ( opts ) { var forceBase64 = ( opts && opts . forceBase64 ) ; if ( ! hasXHR2 || forceBase64 ) { this . supportsBinary = false ; } Transport . call ( this , opts ) ; }


Input: JSONP Polling constructor . [CODESPLIT] function JSONPPolling ( opts ) { Polling$2 . call ( this , opts ) ; this . query = this . query || { } ; // define global callbacks array if not present // we do this here (lazily) to avoid unneeded global pollution if ( ! callbacks ) { // we need to consider multiple engines in the same page if ( ! commonjsGlobal . ___eio ) commonjsGlobal . ___eio = [ ] ; callbacks = commonjsGlobal . ___eio ; } // callback identifier this . index = callbacks . length ; // add callback to jsonp global var self = this ; callbacks . push ( function ( msg ) { self . onData ( msg ) ; } ) ; // append to query string this . query . j = this . index ; // prevent spurious errors from being emitted when the window is unloaded if ( commonjsGlobal . document && commonjsGlobal . addEventListener ) { commonjsGlobal . addEventListener ( 'beforeunload' , function ( ) { if ( self . script ) self . script . onerror = empty$1 ; } , false ) ; } }


Input: When the socket is upgraded while we re probing [CODESPLIT] function onupgrade ( to ) { if ( transport$$1 && to . name !== transport$$1 . name ) { debug$2 ( '"%s" works - aborting "%s"' , to . name , transport$$1 . name ) ; freezeTransport ( ) ; } }


Input: Remove all listeners on the transport and on self [CODESPLIT] function cleanup ( ) { transport$$1 . removeListener ( 'open' , onTransportOpen ) ; transport$$1 . removeListener ( 'error' , onerror ) ; transport$$1 . removeListener ( 'close' , onTransportClose ) ; self . removeListener ( 'close' , onclose ) ; self . removeListener ( 'upgrading' , onupgrade ) ; }


Input: Initialize backoff timer with opts . [CODESPLIT] function Backoff$1 ( opts ) { opts = opts || { } ; this . ms = opts . min || 100 ; this . max = opts . max || 10000 ; this . factor = opts . factor || 2 ; this . jitter = opts . jitter > 0 && opts . jitter <= 1 ? opts . jitter : 0 ; this . attempts = 0 ; }


Input: Parse or format the given val . [CODESPLIT] function ( val , options ) { options = options || { } ; var type = typeof val ; if ( type === 'string' && val . length > 0 ) { return parse$3 ( val ) ; } else if ( type === 'number' && isNaN ( val ) === false ) { return options . long ? fmtLong$2 ( val ) : fmtShort$2 ( val ) ; } throw new Error ( 'val is not a non-empty string or a valid number. val=' + JSON . stringify ( val ) ) ; }


Input: Parse the given str and return milliseconds . [CODESPLIT] function parse$3 ( str ) { str = String ( str ) ; if ( str . length > 100 ) { return ; } var match = / ^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$ / i . exec ( str ) ; if ( ! match ) { return ; } var n = parseFloat ( match [ 1 ] ) ; var type = ( match [ 2 ] || 'ms' ) . toLowerCase ( ) ; switch ( type ) { case 'years' : case 'year' : case 'yrs' : case 'yr' : case 'y' : return n * y$3 ; case 'days' : case 'day' : case 'd' : return n * d$4 ; case 'hours' : case 'hour' : case 'hrs' : case 'hr' : case 'h' : return n * h$3 ; case 'minutes' : case 'minute' : case 'mins' : case 'min' : case 'm' : return n * m$3 ; case 'seconds' : case 'second' : case 'secs' : case 'sec' : case 's' : return n * s$3 ; case 'milliseconds' : case 'millisecond' : case 'msecs' : case 'msec' : case 'ms' : return n ; default : return undefined ; } }


Input: Short format for ms . [CODESPLIT] function fmtShort$2 ( ms ) { if ( ms >= d$4 ) { return Math . round ( ms / d$4 ) + 'd' ; } if ( ms >= h$3 ) { return Math . round ( ms / h$3 ) + 'h' ; } if ( ms >= m$3 ) { return Math . round ( ms / m$3 ) + 'm' ; } if ( ms >= s$3 ) { return Math . round ( ms / s$3 ) + 's' ; } return ms + 'ms' ; }


Input: Long format for ms . [CODESPLIT] function fmtLong$2 ( ms ) { return plural$3 ( ms , d$4 , 'day' ) || plural$3 ( ms , h$3 , 'hour' ) || plural$3 ( ms , m$3 , 'minute' ) || plural$3 ( ms , s$3 , 'second' ) || ms + ' ms' ; }


Input: Pluralization helper . [CODESPLIT] function plural$3 ( ms , n , name ) { if ( ms < n ) { return ; } if ( ms < n * 1.5 ) { return Math . floor ( ms / n ) + ' ' + name ; } return Math . ceil ( ms / n ) + ' ' + name + 's' ; }


Input: Extract code comments from the given string . [CODESPLIT] function extract ( str , options ) { const res = babylon . parse ( str , options ) ; return res . comments ; }


Input: Extends the API returned by noUiSlider with the $on function which wraps the on function to use Angular . [CODESPLIT] function extendApi ( api ) { api . $on = ( eventName , callback ) => { const wrappedCallback = ( ) => { $timeout ( ( ) => { callback ( api . get ( ) ) ; } ) ; } ; api . on ( eventName , wrappedCallback ) ; return ( ) => { api . off ( eventName , wrappedCallback ) ; } ; } ; return api ; }


Input: Creates a watcher that looks for changes in the slider - options directive attribute . When a change is detected the options for the noUiSlider instance are updated . Note that only the margin limit step range animate and snap options can be updated this way ( as documented in https : // refreshless . com / nouislider / more / #section - update ) . All other option updates require you to destroy the current instance and create a new one . [CODESPLIT] function setOptionsWatcher ( api ) { scope . $watch ( 'options' , ( newOptions , oldOptions ) => { if ( angular . equals ( newOptions , oldOptions ) ) { return ; } options = angular . copy ( scope . options ) ; api . updateOptions ( options ) ; } ) ; }


Input: Add ngModel controls to the directive . This allows the use of ngModel to set and get the value in the slider . It uses the noUiSlider API s get and set functions so no custom formatters need to be defined for ngModel . The ngModelOptions can be used . [CODESPLIT] function bindNgModelControls ( api ) { ngModel . $render = ( ) => { api . set ( ngModel . $modelValue ) ; } ; api . on ( 'update' , ( ) => { const positions = api . get ( ) ; ngModel . $setViewValue ( positions ) ; } ) ; }


Input: A utility function that returns a promise which resolves when ngModel is correctly loaded using $timeout . [CODESPLIT] function initializeNgModel ( ) { if ( ngModel === null ) { return $q . resolve ( null ) ; } return $q ( ( resolve ) => { $timeout ( ( ) => { if ( ! ( angular . isArray ( ngModel . $modelValue ) || angular . isNumber ( ngModel . $modelValue ) ) ) { throw new Error ( ` ${ ngModel . $modelValue } ` ) ; } resolve ( ngModel . $modelValue ) ; } ) ; } ) ; }


Input: Creates a noUiSlider instance . [CODESPLIT] function createInstance ( ) { const api = extendApi ( noUiSlider . create ( htmlElement , options ) ) ; setCreatedWatcher ( api ) ; setOptionsWatcher ( api ) ; if ( ngModel !== null ) { bindNgModelControls ( api ) ; } }


Input: suffix fixes [CODESPLIT] function postprocess ( arr ) { //trim whitespace arr = arr . map ( function ( w ) { return w . trim ( ) ; } ) ; arr = arr . filter ( function ( w ) { return w !== '' ; } ) ; // if (arr.length > 2) { //   return arr; // } let l = arr . length ; if ( l > 1 ) { let suffix = arr [ l - 2 ] + arr [ l - 1 ] ; for ( let i = 0 ; i < ones . length ; i ++ ) { if ( suffix . match ( ones [ i ] ) ) { arr [ l - 2 ] = arr [ l - 2 ] + arr [ l - 1 ] ; arr . pop ( ) ; } } } // since the open syllable detection is overzealous, // sometimes need to rejoin incorrect splits if ( arr . length > 1 ) { let first_is_open = ( arr [ 0 ] . length === 1 || arr [ 0 ] . match ( starts_with_consonant_vowel ) ) && arr [ 0 ] . match ( ends_with_vowel ) ; let second_is_joining = arr [ 1 ] . match ( joining_consonant_vowel ) ; if ( first_is_open && second_is_joining ) { let possible_combination = arr [ 0 ] + arr [ 1 ] ; let probably_separate_syllables = possible_combination . match ( cvcv_same_consonant ) || possible_combination . match ( cvcv_same_vowel ) || possible_combination . match ( cvcv_known_consonants ) ; if ( ! probably_separate_syllables ) { arr [ 0 ] = arr [ 0 ] + arr [ 1 ] ; arr . splice ( 1 , 1 ) ; } } } if ( arr . length > 1 ) { let second_to_last_is_open = arr [ arr . length - 2 ] . match ( starts_with_consonant_vowel ) && arr [ arr . length - 2 ] . match ( ends_with_vowel ) ; let last_is_joining = arr [ arr . length - 1 ] . match ( joining_consonant_vowel ) && ones . every ( re => ! arr [ arr . length - 1 ] . match ( re ) ) ; if ( second_to_last_is_open && last_is_joining ) { let possible_combination = arr [ arr . length - 2 ] + arr [ arr . length - 1 ] ; let probably_separate_syllables = possible_combination . match ( cvcv_same_consonant ) || possible_combination . match ( cvcv_same_vowel ) || possible_combination . match ( cvcv_known_consonants ) ; if ( ! probably_separate_syllables ) { arr [ arr . length - 2 ] = arr [ arr . length - 2 ] + arr [ arr . length - 1 ] ; arr . splice ( arr . length - 1 , 1 ) ; } } } if ( arr . length > 1 ) { let single = arr [ 0 ] + arr [ 1 ] ; if ( single . match ( starts_with_single_vowel_combos ) ) { arr [ 0 ] = single ; arr . splice ( 1 , 1 ) ; } } if ( arr . length > 1 ) { if ( arr [ arr . length - 1 ] . match ( only_one_or_more_c ) ) { arr [ arr . length - 2 ] = arr [ arr . length - 2 ] + arr [ arr . length - 1 ] ; arr . splice ( arr . length - 1 , 1 ) ; } } return arr ; }


Input: method is nested because it s called recursively [CODESPLIT] function ( w ) { let vow = / [aeiouy]$ / ; let chars = w . split ( '' ) ; let before = '' ; let after = '' ; let current = '' ; for ( let i = 0 ; i < chars . length ; i ++ ) { before = chars . slice ( 0 , i ) . join ( '' ) ; current = chars [ i ] ; after = chars . slice ( i + 1 , chars . length ) . join ( '' ) ; let candidate = before + chars [ i ] ; //it's a consonant that comes after a vowel if ( before . match ( ends_with_vowel ) && ! current . match ( ends_with_vowel ) ) { if ( after . match ( starts_with_e_then_specials ) ) { candidate += 'e' ; after = after . replace ( starts_with_e , '' ) ; } all . push ( candidate ) ; return doer ( after ) ; } //unblended vowels ('noisy' vowel combinations) if ( candidate . match ( ends_with_noisy_vowel_combos ) ) { //'io' is noisy, not in 'ion' all . push ( before ) ; all . push ( current ) ; return doer ( after ) ; //recursion } // if candidate is followed by a CV, assume consecutive open syllables if ( candidate . match ( ends_with_vowel ) && after . match ( starts_with_consonant_vowel ) ) { all . push ( candidate ) ; return doer ( after ) ; } } //if still running, end last syllable if ( str . match ( aiouy ) || str . match ( ends_with_ee ) ) { //allow silent trailing e all . push ( w ) ; } else { all [ all . length - 1 ] = ( all [ all . length - 1 ] || '' ) + w ; //append it to the last one } return null ; }


Input: Used by ProxyDomain - derived classes to create an API method called apiName ; the API can have methods send and reply which are bound to self ; a promise is created in api . replied which is satisfied after the reply method has been called [CODESPLIT] function addApi ( self , apiName , api ) { for ( var name in api ) { var fn = api [ name ] ; if ( typeof fn === "function" ) api [ name ] = api [ name ] . bind ( self ) ; } var tmp = null ; api . replied = new Promise ( ( resolve , reject ) => { tmp = { resolve , reject } ; } ) ; api . replied . resolve = tmp . resolve ; api . replied . reject = tmp . reject ; self [ apiName ] = api ; }


Input: Gets JSON from the remote server [CODESPLIT] function getJson ( path ) { return httpGet ( { hostname : t . options . remoteClientHostname , port : t . options . remoteClientPort , path : path , method : 'GET' } ) . then ( ( obj ) => { var contentType = getContentType ( obj . response ) ; if ( contentType !== "application/json" ) LOG . warn ( "Expecting JSON from " + path + " but found wrong content type: " + contentType ) ; try { return JSON . parse ( obj . data ) ; } catch ( ex ) { LOG . warn ( "Cannot parse JSON returned from " + path ) ; return null ; } } ) ; }


Input: Splits a string into domain and method [CODESPLIT] function splitName ( method ) { var pos = method . indexOf ( '.' ) ; if ( pos < 0 ) return [ null , method ] ; var domainName = method . substring ( 0 , pos ) ; var methodName = method . substring ( pos + 1 ) ; return [ domainName , methodName ] ; }


Input: Gets data from the remote server and copies it to the client [CODESPLIT] function copyToClient ( req , res ) { return httpGet ( { hostname : t . options . remoteClientHostname , port : t . options . remoteClientPort , path : req . originalUrl , method : 'GET' } ) . then ( function ( obj ) { var contentType = getContentType ( obj . response ) ; if ( contentType ) res . set ( "Content-Type" , contentType ) ; res . send ( obj . data ) ; } ) ; }


Input: Simple promisify [CODESPLIT] function promisify ( fn ) { return new Promise ( function ( resolve , reject ) { fn ( function ( err , value ) { if ( err ) reject ( err ) ; else resolve ( value ) ; } ) ; } ) ; }


Input: helpers ------- [CODESPLIT] function toFixed ( value , precision ) { var power = Math . pow ( 10 , precision ) ; return ( Math . round ( value * power ) / power ) . toFixed ( precision ) ; }


Input: Build a result object and pass it ( among other things ) into the done function . [CODESPLIT] function ( code , stdout , stderr ) { // Remove trailing whitespace (newline) stdout = _ . rtrim ( stdout ) ; stderr = _ . rtrim ( stderr ) ; // Create the result object. var result = { stdout : stdout , stderr : stderr , code : code , toString : function ( ) { if ( code === 0 ) { return stdout ; } else if ( 'fallback' in opts ) { return opts . fallback ; } else if ( opts . grunt ) { // grunt.log.error uses standard out, to be fixed in 0.5. return stderr || stdout ; } return stderr ; } } ; // On error (and no fallback) pass an error object, otherwise pass null. done ( code === 0 || 'fallback' in opts ? null : new Error ( stderr ) , result , code ) ; }


Input: Get native stack [CODESPLIT] function ( ) { // Save original Error.prepareStackTrace const origPrepareStackTrace = Error . prepareStackTrace // Override with function that just returns `stack` Error . prepareStackTrace = ( _ , stack ) => stack // Create a new `Error`, which automatically gets `stack` const err = new Error ( ) // Evaluate `err.stack`, which calls our new `Error.prepareStackTrace` const stack = err . stack // Restore original `Error.prepareStackTrace` Error . prepareStackTrace = origPrepareStackTrace // Remove superfluous function call on stack stack . shift ( ) // getStack --> Error return stack }


Input: / * Public Executes the provided function with the output on the provided streams . Accepts options to silence the output going to the console . [CODESPLIT] function capture ( streams , opts , exec ) { var args = _shift ( opts , exec ) ; opts = args [ 0 ] ; exec = args [ 1 ] ; if ( ! Array . isArray ( streams ) ) { streams = [ streams ] ; } var outputs = [ ] ; streams . forEach ( function ( stream , index ) { outputs [ index ] = '' ; startCapture ( stream , opts , function ( output ) { outputs [ index ] += output ; } ) ; } ) ; exec ( ) ; streams . forEach ( stopCapture ) ; return outputs ; }


Input: Captures stdout and stderr into an object for the provided execution scope . [CODESPLIT] function captureStdio ( opts , exec ) { var streams = [ process . stdout , process . stderr ] ; var outputs = capture ( streams , opts , exec ) ; return { stdout : outputs . shift ( ) , stderr : outputs . shift ( ) } ; }


Input: Listens to a provided stream and executes the provided function for every write call . Accepts options to silence the output going to the console . [CODESPLIT] function hook ( stream , opts , exec ) { var args = _shift ( opts , exec ) ; opts = args [ 0 ] ; exec = args [ 1 ] ; var old_write = stream . write ; stream . write = ( function override ( stream , writer ) { return function write ( string , encoding , fd ) { exec ( string , encoding , fd ) ; if ( ! opts [ 'quiet' ] ) { writer . apply ( stream , [ string , encoding , fd ] ) ; } } } ) ( stream , stream . write ) ; return function unhook ( ) { stream . write = old_write ; return true ; } }


Input: Starts a capture on the provided stream using the provided options and stream execution . [CODESPLIT] function startCapture ( stream , opts , exec ) { var unhook = hook ( stream , opts , exec ) ; var str_id = random . generate ( ) ; unhooks [ str_id ] = unhook ; stream . _id = str_id ; return true ; }


Input: Wraps capturing functions with quiet flags to allow for interception . [CODESPLIT] function _wrapIntercept ( func , stream , opts , exec ) { var idex = Number ( arguments . length > 3 ) ; var args = _shift ( arguments [ idex + 1 ] , arguments [ idex + 2 ] ) ; opts = args [ 0 ] ; exec = args [ 1 ] ; opts . quiet = true ; return idex ? func ( stream , opts , exec ) : func ( opts , exec ) ; }


Input: function to find nearest value in select options [CODESPLIT] function getNearest ( $select , value ) { var delta = { } ; $select . children ( 'option' ) . each ( function ( i , opt ) { var optValue = $ ( opt ) . attr ( 'value' ) , distance ; if ( optValue === '' ) return ; distance = Math . abs ( optValue - value ) ; if ( typeof delta . distance === 'undefined' || distance < delta . distance ) { delta = { value : optValue , distance : distance } ; } } ) ; return delta . value ; }


Input: Round x to the nearest integer choosing the even integer if it lies halfway between two . [CODESPLIT] function evenRound ( x ) { // There are four cases for numbers with fractional part being .5: // // case |     x     | floor(x) | round(x) | expected | x <> 0 | x % 1 | x & 1 |   example //   1  |  2n + 0.5 |  2n      |  2n + 1  |  2n      |   >    |  0.5  |   0   |  0.5 ->  0 //   2  |  2n + 1.5 |  2n + 1  |  2n + 2  |  2n + 2  |   >    |  0.5  |   1   |  1.5 ->  2 //   3  | -2n - 0.5 | -2n - 1  | -2n      | -2n      |   <    | -0.5  |   0   | -0.5 ->  0 //   4  | -2n - 1.5 | -2n - 2  | -2n - 1  | -2n - 2  |   <    | -0.5  |   1   | -1.5 -> -2 // (where n is a non-negative integer) // // Branch here for cases 1 and 4 if ( ( x > 0 && ( x % 1 ) === + 0.5 && ( x & 1 ) === 0 ) || ( x < 0 && ( x % 1 ) === - 0.5 && ( x & 1 ) === 1 ) ) { return censorNegativeZero ( Math . floor ( x ) ) ; } return censorNegativeZero ( Math . round ( x ) ) ; }


Input: delay only used for debugging [CODESPLIT] function addFrameAt ( time , value , delay , array ) { array . push ( { time : time , value : value , delay : delay } ) ; }


Input: / * Insert extra keyframe to preserve frame - by - frame ( keyframing ) effect because CSS is spec ed to attempt tweening on all properties even those that cannot be undesirably resulting in changes occuring immediately instead of on the following keyframe [CODESPLIT] function addPreservationFrameAt ( time , value , delay , array ) { addFrameAt ( time , value , delay , array ) ; }


Input: / * FROM OLD CODE -- here in case it s ever needed [CODESPLIT] function relateTime ( time , extendedDur , resolution ) { // Relative to sibling animations time = new Decimal ( time ) . dividedBy ( extendedDur ) ; // Clean up any repeating decimals time = applyResolution ( time , resolution ) ; return time ; }


Input: / * See test / special / css - delay / looping - multiple . svg See test / special / css - delay / repeatCount - loop - with - syncbases . svg [CODESPLIT] function delay ( data , definedLoop ) { var preDelay = data . sequence [ 0 ] [ definedLoop ? "begin" : "beginStatic" ] ; data . sequence . forEach ( function ( value , i ) { data . sequence [ i ] . begin = value . begin - preDelay ; } ) ; return preDelay ; }


Input: / * Check if supported animation elements exist [CODESPLIT] function isCompatible ( instance ) { var supported = instance . $root . find ( definitions . selectors . supported ) ; var unsupported = instance . $root . find ( definitions . selectors . unsupported ) ; if ( unsupported . length ) { // See test/erroneous/unsupported-elements.svg error . incompatible ( "Unsupported animation elements detected" , "https://github.com/stevenvachon/smil2css/wiki/Current-Status#animation-elements" , instance ) ; } else if ( ! supported . length ) { // See test/erroneous/non-animating.svg error . unnecessary ( "No animation elements detected" , null , instance ) ; } return true ; }


Input: / * Usage : instance = new smil2css () ; instance . convert () ; [CODESPLIT] function smil2css ( options ) { var defaults = { compress : true , force : false , targetBrowsers : null // use autoprefixer defaults } ; this . options = Object . assign ( defaults , options || { } ) ; }


Input: Patch polarity and valence properties on nodes with a value and word - nodes . Then patch the same properties on their parents . [CODESPLIT] function sentiment ( options ) { return transformer function transformer ( node ) { var concatenate = concatenateFactory ( ) visit ( node , any ( options ) ) visit ( node , concatenate ) concatenate . done ( ) } }


Input: Factory to gather parents and patch them based on their childrens directionality . [CODESPLIT] function concatenateFactory ( ) { var queue = [ ] concatenate . done = done return concatenate // Gather a parent if not already gathered. function concatenate ( node , index , parent ) { if ( parent && parent . type !== 'WordNode' && queue . indexOf ( parent ) === - 1 ) { queue . push ( parent ) } } // Patch all words in `parent`. function one ( node ) { var children = node . children var length = children . length var polarity = 0 var index = - 1 var child var hasNegation while ( ++ index < length ) { child = children [ index ] if ( child . data && child . data . polarity ) { polarity += ( hasNegation ? - 1 : 1 ) * child . data . polarity } // If the value is a word, remove any present negation.  Otherwise, add // negation if the node contains it. if ( child . type === 'WordNode' ) { if ( hasNegation ) { hasNegation = false } else if ( isNegation ( child ) ) { hasNegation = true } } } patch ( node , polarity ) } // Patch all parents. function done ( ) { var length = queue . length var index = - 1 queue . reverse ( ) while ( ++ index < length ) { one ( queue [ index ] ) } } }


Input: Patch all words in parent . [CODESPLIT] function one ( node ) { var children = node . children var length = children . length var polarity = 0 var index = - 1 var child var hasNegation while ( ++ index < length ) { child = children [ index ] if ( child . data && child . data . polarity ) { polarity += ( hasNegation ? - 1 : 1 ) * child . data . polarity } // If the value is a word, remove any present negation.  Otherwise, add // negation if the node contains it. if ( child . type === 'WordNode' ) { if ( hasNegation ) { hasNegation = false } else if ( isNegation ( child ) ) { hasNegation = true } } } patch ( node , polarity ) }


Input: Patch all parents . [CODESPLIT] function done ( ) { var length = queue . length var index = - 1 queue . reverse ( ) while ( ++ index < length ) { one ( queue [ index ] ) } }


Input: Factory to patch based on the bound config . [CODESPLIT] function any ( config ) { return setter // Patch data-properties on `node`s with a value and words. function setter ( node ) { var value var polarity if ( 'value' in node || node . type === 'WordNode' ) { value = nlcstToString ( node ) if ( config && own . call ( config , value ) ) { polarity = config [ value ] } else if ( own . call ( polarities , value ) ) { polarity = polarities [ value ] } if ( polarity ) { patch ( node , polarity ) } } } }


Input: Patch a polarity and valence property on node s . [CODESPLIT] function patch ( node , polarity ) { var data = node . data || { } data . polarity = polarity || 0 data . valence = classify ( polarity ) node . data = data }


Input: Detect if a value is used to negate something . [CODESPLIT] function isNegation ( node ) { var value value = nlcstToString ( node ) . toLowerCase ( ) if ( value === 'not' || value === 'neither' || value === 'nor' || / n['’]t/. t e st(v a lue)  ) { return true } return false }


Input: Fire a listener on a target [CODESPLIT] function fire ( event , target , listener ) { var returned , oldData ; if ( listener . d !== null ) { oldData = event . data ; event . data = listener . d ; returned = listener . h . call ( target , event , target ) ; event . data = oldData ; } else { returned = listener . h . call ( target , event , target ) ; } return returned ; }


Input: Internal function proxied by Delegate#on [CODESPLIT] function handle ( listenerList , root , event ) { var listener , returned , specificList , target ; if ( event [ EVENT_IGNORE ] === true ) { return ; } target = event . target ; if ( target . nodeType === Node . TEXT_NODE ) { target = target . parentNode ; } specificList = listenerList [ event . type ] ; // If the fire function actually causes the specific list to be destroyed, // Need check that the specific list is still populated while ( target && specificList . length > 0 ) { listener = specificList . first ; do { // Check for match and fire the event if there's one // TODO:MCG:20120117: Need a way to check if event#stopImmediateProgagation was called. If so, break both loops. if ( listener . m . call ( target , listener . p , target ) ) { returned = fire ( event , target , listener ) ; } // Stop propagation to subsequent callbacks if the callback returned false if ( returned === false ) { event [ EVENT_IGNORE ] = true ; return ; } listener = listener . next ; // If the fire function actually causes the specific list object to be destroyed, // need a way of getting out of here so check listener is set } while ( listener !== specificList . first && listener ) ; // TODO:MCG:20120117: Need a way to check if event#stopProgagation was called. If so, break looping through the DOM. // Stop if the delegation root has been reached if ( target === root ) { break ; } target = target . parentElement ; } }


Input: Internal function proxied by Delegate#on [CODESPLIT] function on ( that , listenerList , root , eventType , selector , eventData , handler ) { var matcher , matcherParam ; if ( ! eventType ) { throw new TypeError ( 'Invalid event type: ' + eventType ) ; } if ( ! selector ) { throw new TypeError ( 'Invalid selector: ' + selector ) ; } // Support a separated list of event types if ( eventType . indexOf ( SEPARATOR ) !== - 1 ) { eventType . split ( SEPARATOR ) . forEach ( function ( eventType ) { on . call ( that , that , listenerList , root , eventType , selector , eventData , handler ) ; } ) ; return ; } if ( handler === undefined ) { handler = eventData ; eventData = null ; // Normalise undefined eventData to null } else if ( eventData === undefined ) { eventData = null ; } if ( typeof handler !== 'function' ) { throw new TypeError ( "Handler must be a type of Function" ) ; } // Add master handler for type if not created yet if ( ! listenerList [ eventType ] ) { root . addEventListener ( eventType , that . handle , ( eventType === 'error' ) ) ; listenerList [ eventType ] = new CircularList ( ) ; } // Compile a matcher for the given selector if ( / ^[a-z]+$ / i . test ( selector ) ) { if ( ! tagsCaseSensitive ) { matcherParam = selector . toUpperCase ( ) ; } else { matcherParam = selector ; } matcher = matchesTag ; } else if ( / ^#[a-z0-9\-_]+$ / i . test ( selector ) ) { matcherParam = selector . slice ( 1 ) ; matcher = matchesId ; } else { matcherParam = selector ; matcher = matches ; } // Add to the list of listeners listenerList [ eventType ] . append ( { s : selector , d : eventData , h : handler , m : matcher , p : matcherParam } ) ; }


Input: Internal function proxied by Delegate#off [CODESPLIT] function off ( that , listenerList , root , eventType , selector , handler ) { var listener , nextListener , firstListener , specificList , singleEventType ; if ( ! eventType ) { for ( singleEventType in listenerList ) { if ( listenerList . hasOwnProperty ( singleEventType ) ) { off . call ( that , that , listenerList , root , singleEventType , selector , handler ) ; } } return ; } specificList = listenerList [ eventType ] ; if ( ! specificList ) { return ; } // Support a separated list of event types if ( eventType . indexOf ( SEPARATOR ) !== - 1 ) { eventType . split ( SEPARATOR ) . forEach ( function ( eventType ) { off . call ( that , that , listenerList , root , eventType , selector , handler ) ; } ) ; return ; } // Remove only parameter matches if specified listener = firstListener = specificList . first ; do { if ( ( ! selector || selector === listener . s ) && ( ! handler || handler === listener . h ) ) { // listener.next will be undefined after listener is removed, so save a reference here nextListener = listener . next ; specificList . remove ( listener ) ; listener = nextListener ; } else { listener = listener . next ; } } while ( listener && listener !== firstListener ) ; // All listeners removed if ( ! specificList . length ) { delete listenerList [ eventType ] ; // Remove the main handler root . removeEventListener ( eventType , that . handle , false ) ; } }


Input:
DOM event delegator [CODESPLIT] function Delegate ( root ) { var /**
			 * Keep a reference to the current instance
			 *
			 * @internal
			 * @type Delegate
			 */ that = this , /**
			 * Maintain a list of listeners, indexed by event name
			 *
			 * @internal
			 * @type Object
			 */ listenerList = { } ; if ( typeof root === 'string' ) { root = document . querySelector ( root ) ; } if ( ! root || ! root . addEventListener ) { throw new TypeError ( 'Root node not specified' ) ; } /**
		 * Attach a handler to one event for all elements that match the selector, now or in the future
		 *
		 * The handler function receives three arguments: the DOM event object, the node that matched the selector while the event was bubbling
		 * and a reference to itself. Within the handler, 'this' is equal to the second argument.
		 * The node that actually received the event can be accessed via 'event.target'.
		 *
		 * @param {string} eventType Listen for these events (in a space-separated list)
		 * @param {string} selector Only handle events on elements matching this selector
		 * @param {Object} [eventData] If this parameter is not specified, the third parameter must be the handler
		 * @param {function()} handler Handler function - event data passed here will be in event.data
		 * @returns {Delegate} This method is chainable
		 */ this . on = function ( ) { Array . prototype . unshift . call ( arguments , that , listenerList , root ) ; on . apply ( that , arguments ) ; return this ; } ; /**
		 * Remove an event handler for elements that match the selector, forever
		 *
		 * @param {string} eventType Remove handlers for events matching this type, considering the other parameters
		 * @param {string} [selector] If this parameter is omitted, only handlers which match the other two will be removed
		 * @param {function()} [handler] If this parameter is omitted, only handlers which match the previous two will be removed
		 * @returns {Delegate} This method is chainable
		 */ this . off = function ( ) { Array . prototype . unshift . call ( arguments , that , listenerList , root ) ; off . apply ( that , arguments ) ; return this ; } ; /**
		 * Handle an arbitrary event
		 *
		 * @private
		 * @param {Event} event
		 */ this . handle = function ( event ) { handle . call ( that , listenerList , root , event ) ; } ; }


Input: Methods [CODESPLIT] function setArticle ( id ) { database . getAsync ( id , function ( article ) { orange . model . set ( article ) ; orange . render ( ) . setup ( ) ; } ) ; }


Input: Module constructor [CODESPLIT] function Module ( options ) { // Shallow clone the options options = mixin ( { } , options ) ; // Various config steps this . _configure ( options ) ; this . _add ( options . children ) ; // Fire before initialize event hook this . fireStatic ( 'before initialize' , options ) ; // Run initialize hooks if ( this . initialize ) this . initialize ( options ) ; // Fire initialize event hook this . fireStatic ( 'initialize' , options ) ; }


Input: Shortcut method for creating lazy views . [CODESPLIT] function fm ( options ) { var Module = fm . modules [ options . module ] ; if ( Module ) { return new Module ( options ) ; } throw new Error ( "Unable to find module '" + options . module + "'" ) ; }


Input:
！！！非常关键的配置信息 当前模块配置 表配置：变量放到顶部，代码重用只需要更改头部的配置代码 [CODESPLIT] function Service ( oodbc , _config ) { this . instanceConfig = _config ; this . databaseConfig = _config . database || "MySQL" ; //数据源
 this . oodbc = oodbc ; }


Input: 常规SQL的方式 [CODESPLIT] function service ( oodbc , _config ) { if ( _config === undefined ) { throw new TypeError ( 'Expected object for argument _config' ) } if ( ! ( this instanceof Service ) ) { return new Service ( oodbc , _config ) } throw new TypeError ( 'Expected object for argument _config' ) ; }


Input:
数据库实例对象 [CODESPLIT] function Service ( oodbc , _database , _instance ) { //数据库标签识别，如果没有标识默认使用MYSQL
 var database = _database || "MYSQL" ; database = database . toUpperCase ( ) ; this . database = database ; var source = oodbc [ database ] ; //判断数据库识别
 if ( source ) { //实例识别
 var dbsource = source [ _instance . toUpperCase ( ) ] ; if ( dbsource ) { //识别正确，返回数据源实例对象，读写分离的实例一起返回
 this . db = dbsource ; } else { console . log ( '数据源实例配置节点识别错误，请检查' + _instance.toUpperCase() + '节点是否 在 );
         throw new TypeError ( '数据源实例配置节点识别错误，请检查' + _instance.toUpperCase() + '节点是否 在 );
         } } else { console . log ( '数据库类型节点配置识别错误，请检查' + this.database.toUpperCase() + ' 点 否存在' ) ;
         throw new TypeError ( '数据库类型节点配置识别错误，请检查' + this.database.toUpperCase() + ' 点 否存在' ) ;
         } }


Input:
数据库实例命令执行（高频执行） 读写实例走这一个对象 [CODESPLIT] function ( instance , sql , parameters ) { return new Promise ( function ( resolve , reject ) { //执行对数据库的访问
 console . time ( '【onela】执行SQL时间');
   //console.log('执行sql', sql, '参数', parameters);
 if ( instance ) { instance . query ( sql , parameters , function ( err , doc ) { console . timeEnd ( '【onela】执行SQL时间');
   if ( err ) { reject ( err ) ; } else { resolve ( doc ) ; } } ) ; } else { reject ( "数据库instance实例未正确指向，请检查oodbc数据实例配置和表结构配置（onelaInstanceConfig.json）的实例对照是否正确");
   } } ) ; }


Input: Converts an object into a persistent or temporary directory structure . [CODESPLIT] function ( structure = [ ] ) { return new Promise ( ( resolve , reject ) => { if ( Array . isArray ( structure ) === false ) { throw new Error ( ` ` ) } parseStructure ( structure , opts . cwd ) . then ( ( parsedStructure ) => writeStructure ( parsedStructure ) ) . then ( ( parsedStructure ) => binStructure ( parsedStructure , bin , opts . persistent ) ) . then ( resolve , reject ) } ) }


Input: Appends WHERE conditions to query builder based on given date parameters [CODESPLIT] function addAndWhereDate ( queryBuilder , column , from , to ) { if ( from && to ) { queryBuilder . whereBetween ( column , [ from , to ] ) ; } else if ( from ) { queryBuilder . andWhere ( column , '>=' , from ) ; } else if ( to ) { queryBuilder . andWhere ( column , '<=' , to ) ; } }