Input: Resizes the image to fit the specified width / height . If crop is specified image will also be cropped to the exact dimensions . [CODESPLIT] function ( options ) { var self = this ; var orientation ; var scale ; var srcRect = { x : 0 , y : 0 , width : self . width , height : self . height } ; var opts = Basic . extendIf ( { width : self . width , height : self . height , type : self . type || 'image/jpeg' , quality : 90 , crop : false , fit : true , preserveHeaders : true , resample : 'default' , multipass : true } , options ) ; try { if ( ! self . size ) { // only preloaded image objects can be used as source throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } // no way to reliably intercept the crash due to high resolution, so we simply avoid it if ( self . width > Image . MAX_RESIZE_WIDTH || self . height > Image . MAX_RESIZE_HEIGHT ) { throw new x . ImageError ( x . ImageError . MAX_RESOLUTION_ERR ) ; } // take into account orientation tag orientation = ( self . meta && self . meta . tiff && self . meta . tiff . Orientation ) || 1 ; if ( Basic . inArray ( orientation , [ 5 , 6 , 7 , 8 ] ) !== - 1 ) { // values that require 90 degree rotation var tmp = opts . width ; opts . width = opts . height ; opts . height = tmp ; } if ( opts . crop ) { scale = Math . max ( opts . width / self . width , opts . height / self . height ) ; if ( options . fit ) { // first scale it up or down to fit the original image srcRect . width = Math . min ( Math . ceil ( opts . width / scale ) , self . width ) ; srcRect . height = Math . min ( Math . ceil ( opts . height / scale ) , self . height ) ; // recalculate the scale for adapted dimensions scale = opts . width / srcRect . width ; } else { srcRect . width = Math . min ( opts . width , self . width ) ; srcRect . height = Math . min ( opts . height , self . height ) ; // now we do not need to scale it any further scale = 1 ; } if ( typeof ( opts . crop ) === 'boolean' ) { opts . crop = 'cc' ; } switch ( opts . crop . toLowerCase ( ) . replace ( / _ / , '-' ) ) { case 'rb' : case 'right-bottom' : srcRect . x = self . width - srcRect . width ; srcRect . y = self . height - srcRect . height ; break ; case 'cb' : case 'center-bottom' : srcRect . x = Math . floor ( ( self . width - srcRect . width ) / 2 ) ; srcRect . y = self . height - srcRect . height ; break ; case 'lb' : case 'left-bottom' : srcRect . x = 0 ; srcRect . y = self . height - srcRect . height ; break ; case 'lt' : case 'left-top' : srcRect . x = 0 ; srcRect . y = 0 ; break ; case 'ct' : case 'center-top' : srcRect . x = Math . floor ( ( self . width - srcRect . width ) / 2 ) ; srcRect . y = 0 ; break ; case 'rt' : case 'right-top' : srcRect . x = self . width - srcRect . width ; srcRect . y = 0 ; break ; case 'rc' : case 'right-center' : case 'right-middle' : srcRect . x = self . width - srcRect . width ; srcRect . y = Math . floor ( ( self . height - srcRect . height ) / 2 ) ; break ; case 'lc' : case 'left-center' : case 'left-middle' : srcRect . x = 0 ; srcRect . y = Math . floor ( ( self . height - srcRect . height ) / 2 ) ; break ; case 'cc' : case 'center-center' : case 'center-middle' : default : srcRect . x = Math . floor ( ( self . width - srcRect . width ) / 2 ) ; srcRect . y = Math . floor ( ( self . height - srcRect . height ) / 2 ) ; } // original image might be smaller than requested crop, so - avoid negative values srcRect . x = Math . max ( srcRect . x , 0 ) ; srcRect . y = Math . max ( srcRect . y , 0 ) ; } else { scale = Math . min ( opts . width / self . width , opts . height / self . height ) ; // do not upscale if we were asked to not fit it if ( scale > 1 && ! opts . fit ) { scale = 1 ; } } this . exec ( 'Image' , 'resize' , srcRect , scale , opts ) ; } catch ( ex ) { // for now simply trigger error event self . trigger ( 'error' , ex . code ) ; } }


Input: Downsizes the image to fit the specified width / height . If crop is supplied image will be cropped to exact dimensions . [CODESPLIT] function ( options ) { var defaults = { width : this . width , height : this . height , type : this . type || 'image/jpeg' , quality : 90 , crop : false , fit : false , preserveHeaders : true , resample : 'default' } , opts ; if ( typeof ( options ) === 'object' ) { opts = Basic . extend ( defaults , options ) ; } else { // for backward compatibility opts = Basic . extend ( defaults , { width : arguments [ 0 ] , height : arguments [ 1 ] , crop : arguments [ 2 ] , preserveHeaders : arguments [ 3 ] } ) ; } this . resize ( opts ) ; }


Input: Retrieves image in it s current state as moxie . file . Blob object . Cannot be run on empty or image in progress ( throws DOMException . INVALID_STATE_ERR ) . [CODESPLIT] function ( type , quality ) { if ( ! this . size ) { throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } return this . exec ( 'Image' , 'getAsBlob' , type || 'image/jpeg' , quality || 90 ) ; }


Input: Retrieves image in it s current state as binary string . Cannot be run on empty or image in progress ( throws DOMException . INVALID_STATE_ERR ) . [CODESPLIT] function ( type , quality ) { var dataUrl = this . getAsDataURL ( type , quality ) ; return Encode . atob ( dataUrl . substring ( dataUrl . indexOf ( 'base64,' ) + 7 ) ) ; }


Input:
Embeds a visual representation of the image into the specified node . Depending on the runtime it might be a canvas an img node or a thrid party shim object ( Flash or SilverLight - very rare can be used in legacy browsers that do not have canvas or proper dataURI support ) . [CODESPLIT] function ( el , options ) { var self = this , runtime // this has to be outside of all the closures to contain proper runtime ; var opts = Basic . extend ( { width : this . width , height : this . height , type : this . type || 'image/jpeg' , quality : 90 , fit : true , resample : 'nearest' } , options ) ; function render ( type , quality ) { var img = this ; // if possible, embed a canvas element directly if ( Env . can ( 'create_canvas' ) ) { var canvas = img . getAsCanvas ( ) ; if ( canvas ) { el . appendChild ( canvas ) ; canvas = null ; img . destroy ( ) ; self . trigger ( 'embedded' ) ; return ; } } var dataUrl = img . getAsDataURL ( type , quality ) ; if ( ! dataUrl ) { throw new x . ImageError ( x . ImageError . WRONG_FORMAT ) ; } if ( Env . can ( 'use_data_uri_of' , dataUrl . length ) ) { el . innerHTML = '<img src="' + dataUrl + '" width="' + img . width + '" height="' + img . height + '" alt="" />' ; img . destroy ( ) ; self . trigger ( 'embedded' ) ; } else { var tr = new Transporter ( ) ; tr . bind ( "TransportingComplete" , function ( ) { runtime = self . connectRuntime ( this . result . ruid ) ; self . bind ( "Embedded" , function ( ) { // position and size properly Basic . extend ( runtime . getShimContainer ( ) . style , { //position: 'relative', top : '0px' , left : '0px' , width : img . width + 'px' , height : img . height + 'px' } ) ; // some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's // position type changes (in Gecko), but since we basically need this only in IEs 6/7 and // sometimes 8 and they do not have this problem, we can comment this for now /*tr.bind("RuntimeInit", function(e, runtime) {
									tr.destroy();
									runtime.destroy();
									onResize.call(self); // re-feed our image data
								});*/ runtime = null ; // release } , 999 ) ; runtime . exec . call ( self , "ImageView" , "display" , this . result . uid , width , height ) ; img . destroy ( ) ; } ) ; tr . transport ( Encode . atob ( dataUrl . substring ( dataUrl . indexOf ( 'base64,' ) + 7 ) ) , type , { required_caps : { display_media : true } , runtime_order : 'flash,silverlight' , container : el } ) ; } } try { if ( ! ( el = Dom . get ( el ) ) ) { throw new x . DOMException ( x . DOMException . INVALID_NODE_TYPE_ERR ) ; } if ( ! this . size ) { // only preloaded image objects can be used as source throw new x . DOMException ( x . DOMException . INVALID_STATE_ERR ) ; } // high-resolution images cannot be consistently handled across the runtimes if ( this . width > Image . MAX_RESIZE_WIDTH || this . height > Image . MAX_RESIZE_HEIGHT ) { //throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } var imgCopy = new Image ( ) ; imgCopy . bind ( "Resize" , function ( ) { render . call ( this , opts . type , opts . quality ) ; } ) ; imgCopy . bind ( "Load" , function ( ) { this . downsize ( opts ) ; } ) ; // if embedded thumb data is available and dimensions are big enough, use it if ( this . meta . thumb && this . meta . thumb . width >= opts . width && this . meta . thumb . height >= opts . height ) { imgCopy . load ( this . meta . thumb . data ) ; } else { imgCopy . clone ( this , false ) ; } return imgCopy ; } catch ( ex ) { // for now simply trigger error event this . trigger ( 'error' , ex . code ) ; } }


Input: Properly destroys the image and frees resources in use . If any . Recommended way to dispose moxie . image . Image object . [CODESPLIT] function ( ) { if ( this . ruid ) { this . getRuntime ( ) . exec . call ( this , 'Image' , 'destroy' ) ; this . disconnectRuntime ( ) ; } if ( this . meta && this . meta . thumb ) { // thumb is blob, make sure we destroy it first this . meta . thumb . data . destroy ( ) ; } this . unbindAll ( ) ; }


Input: Defines property with specified descriptor on an object [CODESPLIT] function ( obj , prop , desc ) { if ( o . typeOf ( desc ) === 'object' ) { defineGSetter . call ( obj , prop , desc , 'get' ) ; if ( ! Object . defineProperty ) { // additionally call it for setter defineGSetter . call ( obj , prop , desc , 'set' ) ; } } }


Input: Defines getter or setter depending on a type param [CODESPLIT] function ( prop , desc , type ) { var defaults = { enumerable : true , configurable : true } , fn , camelType , self = this ; type = type . toLowerCase ( ) ; camelType = type . replace ( / ^[gs] / , function ( $1 ) { return $1 . toUpperCase ( ) ; } ) ; // define function object for fallback if ( o . typeOf ( desc ) === 'function' ) { fn = desc ; desc = { } ; desc [ type ] = fn ; } else if ( o . typeOf ( desc [ type ] ) === 'function' ) { fn = desc [ type ] ; } else { return ; } if ( Env . can ( 'define_property' ) ) { if ( Object . defineProperty ) { return Object . defineProperty ( this , prop , o . extend ( { } , defaults , desc ) ) ; } else { return self [ '__define' + camelType + 'ter__' ] ( prop , fn ) ; } } }


Input: / * Watch files and repeat drill Add a watcher call main wrapper to repeat cycle [CODESPLIT] function initializeWatchers ( ) { var watcher = chokidar . watch ( '**/*.js' , { ignored : 'node_modules' } ) ; watcher . on ( 'change' , main ) . on ( 'unlink' , main ) ; watchersInitialized = true ; console . log ( 'Watchers initialized' ) ; }


Input: SyntaxError Holds information about bad syntax found in a message pattern [CODESPLIT] function SyntaxError ( message /*: string */ , expected /*: ?string */ , found /*: ?string */ , offset /*: number */ , line /*: number */ , column /*: number */ ) { Error . call ( this , message ) this . name = 'SyntaxError' this . message = message this . expected = expected this . found = found this . offset = offset this . line = line this . column = column }


Input: / * ! Intl . MessageFormat prollyfill Copyright ( c ) 2015 Andy VanWagoner MIT licensed [CODESPLIT] function MessageFormat ( pattern /*: string */ , locales /*:: ?: string | string[] */ , options /*:: ?: Options */ ) { if ( ! ( this instanceof MessageFormat ) || internals . has ( this ) ) { throw new TypeError ( 'calling MessageFormat constructor without new is invalid' ) } var ast = parse ( pattern ) internals . set ( this , { ast : ast , format : interpret ( ast , locales , options && options . types ) , locale : MessageFormat . supportedLocalesOf ( locales ) [ 0 ] || 'en' , locales : locales , options : options } ) }


Input: The twist of the 8 corners 0 < = twist < 3^7 . The orientation of the DRB corner is fully determined by the orientation of the other corners . [CODESPLIT] function ( twist ) { var i , m , o , ori , parity , v ; if ( twist != null ) { parity = 0 ; for ( i = m = 6 ; m >= 0 ; i = -- m ) { ori = twist % 3 ; twist = ( twist / 3 ) | 0 ; this . co [ i ] = ori ; parity += ori ; } this . co [ 7 ] = ( 3 - parity % 3 ) % 3 ; return this ; } else { v = 0 ; for ( i = o = 0 ; o <= 6 ; i = ++ o ) { v = 3 * v + this . co [ i ] ; } return v ; } }


Input: The flip of the 12 edges 0 < = flip < 2^11 . The orientation of the BR edge is fully determined by the orientation of the other edges . [CODESPLIT] function ( flip ) { var i , m , o , ori , parity , v ; if ( flip != null ) { parity = 0 ; for ( i = m = 10 ; m >= 0 ; i = -- m ) { ori = flip % 2 ; flip = flip / 2 | 0 ; this . eo [ i ] = ori ; parity += ori ; } this . eo [ 11 ] = ( 2 - parity % 2 ) % 2 ; return this ; } else { v = 0 ; for ( i = o = 0 ; o <= 10 ; i = ++ o ) { v = 2 * v + this . eo [ i ] ; } return v ; } }


Input: Parity of the corner permutation [CODESPLIT] function ( ) { var i , j , m , o , ref , ref1 , ref2 , ref3 , s ; s = 0 ; for ( i = m = ref = DRB , ref1 = URF + 1 ; ( ref <= ref1 ? m <= ref1 : m >= ref1 ) ; i = ref <= ref1 ? ++ m : -- m ) { for ( j = o = ref2 = i - 1 , ref3 = URF ; ( ref2 <= ref3 ? o <= ref3 : o >= ref3 ) ; j = ref2 <= ref3 ? ++ o : -- o ) { if ( this . cp [ j ] > this . cp [ i ] ) { s ++ ; } } } return s % 2 ; }


Input: Parity of the edges permutation . Parity of corners and edges are the same if the cube is solvable . [CODESPLIT] function ( ) { var i , j , m , o , ref , ref1 , ref2 , ref3 , s ; s = 0 ; for ( i = m = ref = BR , ref1 = UR + 1 ; ( ref <= ref1 ? m <= ref1 : m >= ref1 ) ; i = ref <= ref1 ? ++ m : -- m ) { for ( j = o = ref2 = i - 1 , ref3 = UR ; ( ref2 <= ref3 ? o <= ref3 : o >= ref3 ) ; j = ref2 <= ref3 ? ++ o : -- o ) { if ( this . ep [ j ] > this . ep [ i ] ) { s ++ ; } } } return s % 2 ; }


Input: see [ ChartConfig#parser ] ( #chartconfig / parser ) [CODESPLIT] function parseXY ( config , _chartProps , callback , parseOpts ) { // Build chart settings from defaults or provided settings parseOpts = parseOpts || { } ; // clone so that we aren't modifying original // this can probably be avoided by applying new settings differently var chartProps = JSON . parse ( JSON . stringify ( _chartProps ) ) ; var bySeries = dataBySeries ( chartProps . input . raw , { checkForDate : true , type : chartProps . input . type } ) ; var labels = chartProps . _annotations . labels ; var allColumn = true ; // check if either scale contains columns, as we'll need to zero the axis var _primaryColumn = false ; var _secondaryColumn = false ; var _scaleComputed = { } ; each ( scaleNames , function ( name ) { _scaleComputed [ name ] = { data : [ ] , hasColumn : false , count : 0 } ; } ) ; var chartSettings = map ( bySeries . series , function ( dataSeries , i ) { var settings ; if ( chartProps . chartSettings [ i ] ) { settings = chartProps . chartSettings [ i ] ; } else { settings = clone ( config . defaultProps . chartProps . chartSettings [ 0 ] ) ; settings . colorIndex = i ; } if ( parseOpts . columnsChanged ) { settings . label = dataSeries . name ; } else { settings . label = settings . label || dataSeries . name ; } var values = map ( dataSeries . values , function ( d ) { return + d . value ; } ) ; // add data points to relevant scale if ( settings . altAxis === false ) { var _computed = _scaleComputed . primaryScale ; _computed . data = _computed . data . concat ( values ) ; _computed . count += 1 ; if ( settings . type == "column" ) { _computed . hasColumn = true ; } } else { var _computed = _scaleComputed . secondaryScale ; _computed . data = _computed . data . concat ( values ) ; _computed . count += 1 ; if ( settings . type == "column" ) { _computed . hasColumn = true ; } } return settings ; } ) ; labels . values = map ( bySeries . series , function ( dataSeries , i ) { if ( labels . values [ i ] ) { return assign ( { } , { name : chartSettings [ i ] . label } , labels . values [ i ] ) ; } else { return { name : dataSeries . name } ; } } ) ; var maxPrecision = 5 ; var factor = Math . pow ( 10 , maxPrecision ) ; var scale = { } ; var mobileScale = { } ; // Calculate domain and tick values for any scales that exist each ( scaleNames , function ( name ) { var _computed = _scaleComputed [ name ] ; if ( _computed . count > 0 ) { var currScale = chartProps . scale [ name ] || clone ( config . defaultProps . chartProps . scale . primaryScale ) ; var domain = help . computeScaleDomain ( currScale , _computed . data , { nice : true , minZero : _computed . hasColumn } ) ; assign ( currScale , domain ) ; var ticks ; if ( name === "primaryScale" ) { ticks = currScale . ticks ; } else { ticks = scale . primaryScale . ticks ; } currScale . tickValues = help . exactTicks ( currScale . domain , ticks ) ; each ( currScale . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currScale . precision ) { currScale . precision = tickPrecision ; } } ) ; scale [ name ] = currScale ; if ( chartProps . mobile ) { if ( chartProps . mobile . scale ) { var currMobile = chartProps . mobile . scale [ name ] ; if ( currMobile ) { var domain = help . computeScaleDomain ( currMobile , _computed . data , { nice : true , minZero : _computed . hasColumn } ) ; assign ( currMobile , domain ) ; var ticks = ( name == "primaryScale" ) ? currMobile . ticks : scale . primaryScale . ticks ; currMobile . tickValues = help . exactTicks ( currMobile . domain , ticks ) ; each ( currMobile . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currMobile . precision ) { currMobile . precision = tickPrecision ; } } ) ; } } } else { chartProps . mobile = { } ; } } } ) ; // If there is only one primary and >0 secondary, color the left axis if ( _scaleComputed . primaryScale . count === 1 && _scaleComputed . secondaryScale . count > 0 ) { scale . primaryScale . colorIndex = filter ( chartSettings , function ( series ) { return ( series . altAxis === false ) ; } ) [ 0 ] . colorIndex ; } else { scale . primaryScale . colorIndex = null ; } // If there is only one secondary and >0 primary, color the right axis if ( _scaleComputed . secondaryScale . count === 1 && _scaleComputed . primaryScale . count > 0 ) { scale . secondaryScale . colorIndex = filter ( chartSettings , function ( series ) { return ( series . altAxis === true ) ; } ) [ 0 ] . colorIndex ; } else if ( _scaleComputed . secondaryScale . count > 0 ) { scale . secondaryScale . colorIndex = null ; } // create the data structure for the renederer based on input if ( bySeries . hasDate ) { scale . hasDate = bySeries . hasDate ; scale . dateSettings = chartProps . scale . dateSettings || clone ( config . defaultProps . chartProps . scale . dateSettings ) ; scale . dateSettings . inputTZ = scale . dateSettings . inputTZ || SessionStore . get ( "nowOffset" ) } if ( bySeries . isNumeric ) { scale . isNumeric = bySeries . isNumeric ; _computed = { //TODO look at entries for all series not just the first data : bySeries . series [ 0 ] . values . map ( function ( d ) { return + d . entry } ) , hasColumn : false , count : 0 } ; var currScale = chartProps . scale . numericSettings || clone ( config . defaultProps . chartProps . scale . numericSettings ) ; var domain = help . computeScaleDomain ( currScale , _computed . data , { nice : true , minZero : false } ) ; assign ( currScale , domain ) ; currScale . ticks = currScale . ticks || help . suggestTickNum ( currScale . domain ) ; var ticks = currScale . ticks ; currScale . tickValues = help . exactTicks ( currScale . domain , ticks ) ; each ( currScale . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currScale . precision ) { currScale . precision = tickPrecision ; } } ) ; scale . numericSettings = currScale ; if ( chartProps . mobile ) { if ( chartProps . mobile . scale ) { var currMobile = chartProps . mobile . scale . numericSettings ; if ( currMobile ) { var domain = help . computeScaleDomain ( currMobile , _computed . data , { nice : true , minZero : false } ) ; assign ( currMobile , domain ) ; var ticks = currMobile . ticks ; currMobile . tickValues = help . exactTicks ( currMobile . domain , ticks ) ; each ( currMobile . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currMobile . precision ) { currMobile . precision = tickPrecision ; } } ) ; } chartProps . mobile . scale . numericSettings = currMobile ; } } else { chartProps . mobile = { } ; } } var newChartProps = assign ( chartProps , { chartSettings : chartSettings , scale : scale , input : bySeries . input , data : bySeries . series , _numSecondaryAxis : _scaleComputed . secondaryScale . count } ) ; if ( callback ) { callback ( newChartProps ) ; } else { return newChartProps ; } }


Input: see [ ChartConfig#parser ] ( #chartconfig / parser ) [CODESPLIT] function parseChartgrid ( config , _chartProps , callback , parseOpts ) { // Build chart settings from defaults or provided settings var chartProps = JSON . parse ( JSON . stringify ( _chartProps ) ) ; var chartgrid_defaults = config . defaultProps . chartProps ; var primaryScale = chartProps . scale . primaryScale || clone ( config . defaultProps . chartProps . scale . primaryScale ) ; var scaleData = [ ] ; var domain ; var height ; var isColumnOrBar ; parseOpts = parseOpts || { } ; // dont check for date column if grid type is bar var checkForDate = chartProps . _grid . type !== "bar" ; var bySeries = dataBySeries ( chartProps . input . raw , { checkForDate : checkForDate , type : chartProps . input . type } ) ; var gridSettings = { rows : + chartProps . _grid . rows || chartgrid_defaults . _grid . rows , cols : + chartProps . _grid . cols || bySeries . series . length } ; var chartSettings = map ( bySeries . series , function ( dataSeries , i ) { var settings ; // add data points to relevant scale scaleData = scaleData . concat ( map ( dataSeries . values , function ( d ) { return + d . value ; } ) ) ; if ( chartProps . chartSettings [ i ] ) { settings = chartProps . chartSettings [ i ] ; } else { settings = clone ( chartgrid_defaults . chartSettings [ 0 ] ) ; settings . colorIndex = i ; } if ( parseOpts . columnsChanged ) { settings . label = dataSeries . name ; } else { settings . label = settings . label || dataSeries . name ; } return settings ; } ) ; chartProps . scale . hasDate = bySeries . hasDate ; chartProps . scale . isNumeric = bySeries . isNumeric ; if ( bySeries . hasDate ) { chartProps . scale . dateSettings = chartProps . scale . dateSettings || clone ( config . defaultProps . chartProps . scale . dateSettings ) ; chartProps . scale . dateSettings . inputTZ = chartProps . scale . dateSettings . inputTZ || SessionStore . get ( "nowOffset" ) // for dates, default type should be line gridSettings . type = _chartProps . _grid . type || "line" ; isColumnOrBar = ( gridSettings . type === "column" || gridSettings . type === "bar" ) ; domain = help . computeScaleDomain ( primaryScale , scaleData , { nice : true , minZero : isColumnOrBar } ) ; assign ( primaryScale , domain ) ; } else if ( bySeries . isNumeric ) { var maxPrecision = 5 ; var factor = Math . pow ( 10 , maxPrecision ) ; gridSettings . type = _chartProps . _grid . type || "line" ; _computed = { //TODO look at entries for all series not just the first data : bySeries . series [ 0 ] . values . map ( function ( d ) { return + d . entry } ) , hasColumn : false , count : 0 } ; var currScale = chartProps . scale . numericSettings || clone ( config . defaultProps . chartProps . scale . numericSettings ) ; var domain = help . computeScaleDomain ( currScale , _computed . data , { nice : true , minZero : false } ) ; assign ( currScale , domain ) ; var ticks = currScale . ticks ; currScale . tickValues = help . exactTicks ( currScale . domain , ticks ) ; each ( currScale . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currScale . precision ) { currScale . precision = tickPrecision ; } } ) ; chartProps . scale . numericSettings = currScale ; if ( chartProps . mobile ) { if ( chartProps . mobile . scale ) { var currMobile = chartProps . mobile . scale . numericSettings ; if ( currMobile ) { var domain = help . computeScaleDomain ( currMobile , _computed . data , { nice : true , minZero : false } ) ; assign ( currMobile , domain ) ; var ticks = currMobile . ticks ; currMobile . tickValues = help . exactTicks ( currMobile . domain , ticks ) ; each ( currMobile . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > currMobile . precision ) { currMobile . precision = tickPrecision ; } } ) ; } chartProps . mobile . scale . numericSettings = currMobile } } else { chartProps . mobile = { } ; } } else { // ordinals default type should be bar gridSettings . type = _chartProps . _grid . type || "bar" ; isColumnOrBar = ( gridSettings . type == "column" || gridSettings . type == "bar" ) ; domain = help . computeScaleDomain ( primaryScale , scaleData , { minZero : isColumnOrBar } ) ; assign ( primaryScale , domain ) ; } chartProps . scale . primaryScale = primaryScale ; if ( ! chartProps . mobile ) { chartProps . mobile = { } ; } if ( chartProps . mobile . scale ) { chartProps . mobile . scale . hasDate = bySeries . hasDate ; } if ( gridSettings . type != "bar" ) { // TODO: this function is used in several places and should be factored out primaryScale . ticks = primaryScale . ticks || 5 ; primaryScale . precision = primaryScale . precision || 0 ; primaryScale . tickValues = help . exactTicks ( primaryScale . domain , primaryScale . ticks ) ; each ( primaryScale . tickValues , function ( v ) { var tickPrecision = help . precision ( Math . round ( v * factor ) / factor ) ; if ( tickPrecision > primaryScale . precision ) { primaryScale . precision = tickPrecision ; } } ) ; } var newChartProps = assign ( chartProps , { chartSettings : chartSettings , scale : chartProps . scale , input : bySeries . input , _grid : gridSettings , data : bySeries . series } ) ; if ( callback ) { callback ( newChartProps ) ; } else { return newChartProps ; } }


Input: make_mults [CODESPLIT] function make_mults ( Outer , outerProps , data , gridScales , renderDataFunc ) { var colDomain = gridScales . cols . domain ( ) ; var numCols = colDomain [ colDomain . length - 1 ] + 1 ; // only render number of grid blocks that are selected var numCharts = gridScales . cols . domain ( ) . length * gridScales . rows . domain ( ) . length ; var grid_dimensions = { width : gridScales . cols . rangeBand ( ) , height : gridScales . rows . rangeBand ( ) } ; return map ( data . slice ( 0 , numCharts ) , function ( d , i ) { var pos = { col : i % numCols , row : ( i === 0 ) ? 0 : Math . floor ( i / numCols ) } ; var gridProps = assign ( { } , outerProps , { key : i , translate : [ gridScales . cols ( pos . col ) , gridScales . rows ( pos . row ) ] , dimensions : grid_dimensions } ) ; return Outer ( gridProps , renderDataFunc ( d , i ) ) ; } ) ; }


Input: Determine if all tickValues are modulo some interval value [CODESPLIT] function all_modulo ( tickValues , interval ) { // we can't modulo-check decimals so we need to multiply by 10^Ndecimals var maxDecimals = reduce ( tickValues , function ( prevMax , tick ) { if ( ( tick % 1 ) !== 0 ) { return Math . max ( prevMax , tick . toString ( ) . split ( "." ) [ 1 ] . length ) ; } else { return prevMax ; } } , 0 ) ; var decimalOffset = Math . pow ( 10 , maxDecimals ) ; interval = interval * decimalOffset ; return reduce ( tickValues , function ( prev , curr ) { return prev && ( ( curr * decimalOffset ) % interval === 0 ) ; } , true ) ; }


Input: Detect delimiter of input algorithm : if numtabs > = numrows then TSV else CSV [CODESPLIT] function detectDelimiter ( input ) { var numRows = input . split ( / \r\n|\r|\n / ) . length ; var numTabs = input . replace ( tabRegex , "" ) . length ; if ( numTabs >= numRows - 1 ) { return "\t" ; } else { return "," ; } }


Input: Automatically calculate date frequency if not selected [CODESPLIT] function autoDateFormatAndFrequency ( minDate , maxDate , dateFormat , availableWidth ) { var timespan = Math . abs ( maxDate - minDate ) ; var years = timespan / 31536000000 ; var months = timespan / 2628000000 ; var days = timespan / 86400000 ; var yearGap ; var hourGap ; var interval ; var targetPixelGap = 64 ; var maximum_ticks = Math . max ( Math . floor ( availableWidth / targetPixelGap ) , 1 ) ; var time_gap = timespan / maximum_ticks ; if ( dateFormat == "auto" ) { //lets go small to large if ( days <= 2 ) { dateFormat = "h" ; } else if ( days <= 91 ) { dateFormat = "M1d" ; } else if ( months < 36 ) { dateFormat = "M" ; } else { dateFormat = "yy" ; } } var gapInYears = humanReadableNumber ( Math . floor ( time_gap / 31536000000 ) ) ; var gapInMonths = Math . ceil ( time_gap / 2628000000 ) ; var gapInDays = humanReadableNumber ( time_gap / 86400000 ) ; var gapInHours = humanReadableNumber ( time_gap / 3600000 ) ; //make sure that the interval include the maxDate in the interval list maxDate . addMilliseconds ( 0.1 ) ; switch ( dateFormat ) { case "yy" : // Add a day to the max date for years to make inclusive of max date // irrespective of time zone / DST maxDate = d3 . time . day . offset ( maxDate , 1 ) ; interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case "yyyy" : // See above maxDate = d3 . time . day . offset ( maxDate , 1 ) ; interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case "MM" : interval = d3 . time . month . range ( minDate , maxDate , gapInMonths ) ; break ; case "M" : interval = d3 . time . month . range ( minDate , maxDate , gapInMonths ) ; break ; case "Mdd" : interval = d3 . time . day . range ( minDate , maxDate , gapInDays ) ; break ; case "M1d" : interval = d3 . time . day . range ( minDate , maxDate , gapInDays ) ; break ; case "YY" : interval = d3 . time . year . range ( minDate , maxDate , gapInYears ) ; break ; case "QJan" : interval = d3 . time . month . range ( minDate , maxDate , 4 ) ; break ; case "QJul" : interval = d3 . time . month . range ( minDate , maxDate , 4 ) ; break ; case "h" : interval = d3 . time . hour . range ( minDate , maxDate , gapInHours ) ; break ; default : interval = d3 . time . year . range ( minDate , maxDate , 1 ) ; } interval = cleanInterval ( interval ) ; return { "format" : dateFormat , "frequency" : interval } ; }


Input: Test whether a string is a valid Chartbuilder model [CODESPLIT] function validate_chart_model ( modelStr ) { var parsed ; try { parsed = JSON . parse ( modelStr ) ; } catch ( e ) { throw new TypeError ( "Chart model is not valid JSON" ) ; } var isValidChartModel = ( parsed . hasOwnProperty ( "chartProps" ) && parsed . hasOwnProperty ( "metadata" ) ) ; if ( isValidChartModel ) { return parsed ; } else { throw new TypeError ( "Not a valid Chartbuilder model" ) ; } }


Input: see [ ChartConfig#calculateDimensions ] ( #chartconfig / calculatedimensions ) [CODESPLIT] function chartGridDimensions ( width , opts ) { var height ; var metadata = opts . metadata ; var grid = opts . grid ; if ( metadata . size == "auto" || opts . enableResponsive ) { // use current width } else { width = chartSizes [ metadata . size ] . width ; } if ( grid . type == "bar" ) { var numDataPoints = opts . data [ 0 ] . values . length ; height = calculate_bar_height ( numDataPoints , grid , opts . displayConfig ) ; } else { height = calculate_cartesian_height ( width , grid , opts . displayConfig ) ; } if ( ! opts . showMetadata ) { height -= opts . displayConfig . padding . bottom ; } return { width : width , height : height } ; }


Input:
/ * Respond to actions coming from the dispatcher [CODESPLIT] function registeredCallback ( payload ) { var action = payload . action ; var data ; switch ( action . eventName ) { /*
		* New chart model is received. Respond by first waiting for
		* `ChartProptiesStore`
		*/ case "receive-model" : Dispatcher . waitFor ( [ ChartPropertiesStore . dispatchToken ] ) ; _metadata = action . model . metadata ; data = ChartPropertiesStore . get ( "data" ) ; _metadata . title = defaultTitle ( data ) ; ChartMetadataStore . emitChange ( ) ; break ; /* Metadata alone is being updated */ case "update-metadata" : _metadata [ action . key ] = action . value ; // if title is edited, set dirty to true and dont generate default anymore // TODO: we don't need to do this every time if ( action . key == "title" ) { titleDirty = true ; } ChartMetadataStore . emitChange ( ) ; break ; case "update-and-reparse" : if ( ! titleDirty ) { data = ChartPropertiesStore . get ( "data" ) ; _metadata . title = defaultTitle ( data ) ; ChartMetadataStore . emitChange ( ) ; } break ; case "update-data-input" : if ( ! titleDirty ) { data = ChartPropertiesStore . get ( "data" ) ; _metadata . title = defaultTitle ( data ) ; ChartMetadataStore . emitChange ( ) ; } break ; default : // do nothing } return true ; }


Input: Generate an exact number of ticks given a domain [CODESPLIT] function exact_ticks ( domain , numticks ) { numticks -= 1 ; var ticks = [ ] ; var delta = domain [ 1 ] - domain [ 0 ] ; var i ; for ( i = 0 ; i < numticks ; i ++ ) { ticks . push ( domain [ 0 ] + ( delta / numticks ) * i ) ; } ticks . push ( domain [ 1 ] ) ; if ( domain [ 1 ] * domain [ 0 ] < 0 ) { //if the domain crosses zero, make sure there is a zero line var hasZero = false ; for ( i = ticks . length - 1 ; i >= 0 ; i -- ) { //check if there is already a zero line if ( ticks [ i ] === 0 ) { hasZero = true ; } } if ( ! hasZero ) { ticks . push ( 0 ) ; } } return ticks ; }


Input: compute_scale_domain [CODESPLIT] function compute_scale_domain ( scaleObj , data , opts ) { // Compute the domain (`[min, max]`) of a scale based on its data points. // `data` is a flat array of all values used in this scale, and is // created by `input-parsers/parse-<chart>.js` opts = opts || { } ; var scaleDomain = scaleObj . domain || [ ] ; var _domain ; var defaultMin ; var defaultMax ; if ( ! isArray ( data ) ) { throw new TypeError ( "data passed to compute_scale_domain must be an array" ) ; } var extent = d3 . extent ( data ) ; var niced = d3 . scale . linear ( ) . domain ( extent ) . nice ( ) . domain ( ) ; if ( ! scaleObj . domain || ! scaleObj . custom ) { if ( opts . nice ) { _domain = niced ; } else { _domain = extent ; } defaultMin = true ; defaultMax = true ; } else { _domain = ( opts . nice ) ? niced : extent ; defaultMin = ( _domain [ 0 ] === scaleDomain [ 0 ] || isUndefined ( scaleDomain [ 0 ] ) ) ; defaultMax = ( _domain [ 1 ] === scaleDomain [ 1 ] || isUndefined ( scaleDomain [ 1 ] ) ) ; _domain = scaleDomain ; } if ( opts . minZero ) { _domain [ 0 ] = Math . min ( _domain [ 0 ] , 0 ) ; } return { domain : _domain , custom : ( ! defaultMin || ! defaultMax ) } ; }


Input: round_to_precision Round a number to N decimal places [CODESPLIT] function round_to_precision ( num , precision , supress_thou_sep ) { //zero should always be "0" if ( num === 0 ) return "0" ; var s = Math . round ( num * Math . pow ( 10 , precision ) ) / Math . pow ( 10 , precision ) ; s = s + "" ; s = s . split ( "." ) ; if ( s . length == 1 ) { s [ 1 ] = "" ; } if ( s [ 1 ] . length < precision ) { s [ 1 ] += Array ( precision - s [ 1 ] . length + 1 ) . join ( "0" ) ; } if ( ! supress_thou_sep ) { s [ 0 ] = d3 . format ( "," ) ( parseInt ( s [ 0 ] ) ) ; } if ( precision === 0 ) { return s [ 0 ] ; } return s . join ( "." ) ; }


Input: combine_margin_pading [CODESPLIT] function combine_margin_pading ( m , p ) { return { top : m . top + p . top , right : m . right + p . right , bottom : m . bottom + p . bottom , left : m . left + p . left } ; }


Input: precision [CODESPLIT] function precision ( a ) { // http://stackoverflow.com/a/27865285/1181761 // guard for NaN if ( a === a ) { var e = 1 ; while ( Math . round ( a * e ) / e !== a ) e *= 10 ; return Math . round ( Math . log ( e ) / Math . LN10 ) ; } else { return 0 ; } }


Input: transform_coords [CODESPLIT] function transform_coords ( transformString ) { // Split on both space and comma because IE10 likes spaces? var s = transformString . split ( / \s|, / ) ; return [ s [ 0 ] . split ( "(" ) [ 1 ] , s [ 1 ] . split ( ")" ) [ 0 ] ] . map ( parseFloat ) ; }


Input: Given a defaults object and a source object copy the value from the source if it contains the same key otherwise return the default . Skip keys that only exist in the source object . [CODESPLIT] function merge_or_apply ( defaults , source ) { var defaultKeys = keys ( defaults ) ; var sourceKeys = keys ( source ) ; return reduce ( defaultKeys , function ( result , key ) { if ( sourceKeys . indexOf ( key ) > - 1 ) { result [ key ] = source [ key ] ; return result ; } else { result [ key ] = defaults [ key ] ; return result ; } } , { } ) ; }


Input: Given a the domain of a scale suggest the most numerous number of round number ticks that it cold be divided into while still containing values evenly divisible by 1 2 2 . 5 5 10 or 25 . [CODESPLIT] function suggest_tick_num ( domain ) { var MAX_TICKS = 10 ; var INTERVAL_BASE_VALS = [ 1 , 2 , 2.5 , 5 , 10 , 25 ] ; var range = Math . abs ( domain [ 0 ] - domain [ 1 ] ) var minimum = range / MAX_TICKS ; var digits = Math . floor ( range ) . toString ( ) . length ; var multiplier = Math . pow ( 10 , ( digits - 2 ) ) ; var acceptable_intervals = reduce ( INTERVAL_BASE_VALS , function ( prev , curr ) { var mult = curr * multiplier ; if ( mult >= minimum ) { prev = prev . concat ( [ mult ] ) ; } return prev ; } , [ ] ) ; for ( var i = 0 ; i < acceptable_intervals . length ; i ++ ) { var interval = acceptable_intervals [ i ] if ( range % interval == 0 ) { return ( range / interval ) + 1 } } ; return 11 ; }


Input: Given a timezone offset in an hour : minute format and return the equivalent number of minutes as a number only exist in the source object . [CODESPLIT] function tz_offset_to_minutes ( offset ) { if ( offset == "Z" ) { return 0 } var offset = offset . split ( ":" ) if ( offset . length == 1 ) { offset = offset [ 0 ] split_loc = offset . length - 2 offset = [ offset . substring ( 0 , split_loc ) , offset . substring ( split_loc ) ] } sign = offset [ 0 ] . indexOf ( "-" ) > - 1 ? - 1 : 1 offset = offset . map ( parseFloat ) return ( offset [ 0 ] * 60 ) + ( sign * offset [ 1 ] ) }


Input:
### Chart config Set up a configuration object for a given chart type [CODESPLIT] function ChartConfig ( settings ) { this . displayName = settings . displayName ; /**
	 * Func that parses input and settings to return newly parsed `chartProps`
	 * @param {object} config - The parsed configuration for this chart type
	 * @param {object} _chartProps - Previous `chartProps`
	 * @param {function} callback - Function to pass new `chartProps` to upon parse completion
	 * @param {object} parseOpts - Additional parse options
	 *
	 * @return {Object} chartProps - Updated `chartProps`
	 * @memberof ChartConfig
	 * @instance
	 */ this . parser = settings . parser ; /**
	 * Func that returns an object of `{width: N, height: N}` that will determine
	 * dimensions of a chart
	 * @param {number} width - Width of container or area that will contain the chart
	 * @param {object} model - The `chartProps` and `metadata` of the current chart
	 * @param {object} chartConfig - Parsed chart configuration
	 * @param {boolean} enableResponsive - Should we make dimensions relative to
	 * container or use preset sizes
	 * @param {number} extraHeight - Additional height we need to account for, eg
	 * from wrapped text at the footer
	 *
	 * @return {Object} dimensions - Dimensions returned by calculation
	 * @return {number} dimensions.width
	 * @return {number} dimension.height
	 * @memberof ChartConfig
	 * @instance
	 */ this . calculateDimensions = settings . calculateDimensions ; this . display = settings . display ; this . defaultProps = settings . defaultProps ; }


Input: Parse data by series . Options : checkForDate : bool | tell parser to return dates if key column is date / time / year [CODESPLIT] function dataBySeries ( input , opts ) { var series ; opts = opts || { } ; var parsedInput = parseDelimInput ( input , { checkForDate : opts . checkForDate , type : opts . type } ) ; var columnNames = parsedInput . columnNames ; var keyColumn = columnNames . shift ( ) ; if ( columnNames . length === 0 ) { series = [ { name : keyColumn , values : parsedInput . data . map ( function ( d ) { return { name : keyColumn , value : d [ keyColumn ] } ; } ) } ] ; } else { series = columnNames . map ( function ( header , i ) { return { name : header , values : parsedInput . data . map ( function ( d ) { return { name : header , entry : d [ keyColumn ] , value : d [ header ] } ; } ) } ; } ) ; } return { series : series , input : { raw : input , type : opts . type } , hasDate : parsedInput . hasDate && ( ! opts . type || opts . type == "date" ) , isNumeric : parsedInput . isNumeric && ( ! opts . type || opts . type == "numeric" ) } ; }


Input: generateScale [CODESPLIT] function generate_scale ( type , scaleOptions , data , range , additionalOpts ) { if ( ! scaleOptions ) return { } ; return scale_types [ type ] ( scaleOptions , data , range , additionalOpts ) ; }


Input: TODO : make this keyed funcs that accept a type param ( like ordinal time linear ) so that we dont have to check every time [CODESPLIT] function _ordinalAdjust ( scale , value ) { var isOrdinal = scale . hasOwnProperty ( "bandwidth" ) ; if ( isOrdinal ) { return scale ( value ) + scale . bandwidth ( ) / 2 ; } else { return scale ( value ) ; } }


Input: get_tick_widths [CODESPLIT] function get_tick_widths ( scaleOptions , font ) { if ( ! scaleOptions ) return { width : [ ] , max : 0 } ; var numTicks = scaleOptions . tickValues . length - 1 ; var formattedTicks = reduce ( scaleOptions . tickValues , function ( prev , tick , i ) { if ( i === numTicks ) { return prev . concat ( [ scaleOptions . prefix , help . roundToPrecision ( tick , scaleOptions . precision ) , scaleOptions . suffix ] . join ( "" ) ) ; } else { return prev . concat ( help . roundToPrecision ( tick , scaleOptions . precision ) ) ; } } , [ ] ) ; var widths = map ( formattedTicks , function ( text ) { return help . computeTextWidth ( text , font ) ; } ) ; return { widths : widths , max : d3 . max ( widths . slice ( 0 , - 1 ) ) // ignore the top tick } ; }


Input: Get thousands and decimal separators based on locale [CODESPLIT] function detectNumberSeparators ( ) { var n = 1000.50 ; var l = n . toLocaleString ( ) ; var s = n . toString ( ) ; var o = { decimal : l . substring ( 5 , 6 ) , thousands : l . substring ( 1 , 2 ) } ; if ( l . substring ( 5 , 6 ) == s . substring ( 5 , 6 ) ) { o . decimal = "." ; } if ( l . substring ( 1 , 2 ) == s . substring ( 1 , 2 ) ) { o . thousands = "," ; } return o ; }


Input: Max 400k for chartProps [CODESPLIT] function validateDataInput ( chartProps ) { var input = chartProps . input . raw ; var series = chartProps . data ; var hasDate = chartProps . scale . hasDate ; var isNumeric = chartProps . scale . isNumeric ; var type = chartProps . input . type ; var scale = chartProps . scale ; var inputErrors = [ ] ; // Check whether we have input if ( input . length === 0 ) { inputErrors . push ( "EMPTY" ) ; return inputErrors ; } if ( series . length && ! series [ 0 ] . values [ 0 ] . entry ) { // Check that we have at least 1 value col (i.e. minimum header + 1 data col) inputErrors . push ( "TOO_FEW_SERIES" ) ; } else if ( series . length > 12 ) { // Check whether there are too many series inputErrors . push ( "TOO_MANY_SERIES" ) ; } // Whether a column has a different number of values var unevenSeries = dataPointTest ( series , function ( val ) { return val . value !== null ? ( val . value === undefined || val . value . length === 0 ) : false ; } , function ( empty , vals ) { return empty . length !== vals [ 0 ] . length ; } ) ; if ( unevenSeries ) { inputErrors . push ( "UNEVEN_SERIES" ) ; } // Whether a column has something that is NaN but is not nothing (blank) or `null` var nanSeries = somePointTest ( series , function ( val ) { return ( isNaN ( val . value ) && val . value !== undefined && val . value !== "" ) ; } ) ; if ( nanSeries ) { inputErrors . push ( "NAN_VALUES" ) ; } // Are there multiple types of axis entries var entryTypes = unique ( series [ 0 ] . values . map ( function ( d ) { return typeof d . entry ; } ) ) ; if ( entryTypes . length > 1 && ! chartProps . input . type ) { inputErrors . push ( "CANT_AUTO_TYPE" ) ; } //Whether an entry column that is supposed to be a Number is not in fact a number if ( isNumeric || chartProps . input . type == "numeric" ) { var badNumSeries = somePointTest ( series , function ( val ) { return isNaN ( val . entry ) ; } ) ; if ( badNumSeries ) { inputErrors . push ( "NAN_VALUES" ) ; } } // Whether an entry column that is supposed to be a date is not in fact a date if ( hasDate || chartProps . input . type == "date" ) { var badDateSeries = somePointTest ( series , function ( val ) { return ! val . entry . getTime || isNaN ( val . entry . getTime ( ) ) ; } ) ; if ( badDateSeries ) { inputErrors . push ( "NOT_DATES" ) ; } var tz_pattern = / ([+-]\d\d:*\d\d) / gi ; var found_timezones = input . match ( tz_pattern ) ; if ( found_timezones && found_timezones . length != series [ 0 ] . values . length ) { inputErrors . push ( "UNEVEN_TZ" ) ; } } // Whether a column has numbers that should be divided var largeNumbers = somePointTest ( series , function ( val ) { return Math . floor ( val . value ) . toString ( ) . length > 4 ; } , function ( largeNums , vals ) { return largeNums . length > 0 ; } ) ; if ( largeNumbers ) { inputErrors . push ( "LARGE_NUMBERS" ) ; } // Whether the number of bytes in chartProps exceeds our defined maximum if ( catchChartMistakes . tooMuchData ( chartProps ) ) { inputErrors . push ( "TOO_MUCH_DATA" ) ; } // Whether axis ticks divide evenly if ( ! catchChartMistakes . axisTicksEven ( scale . primaryScale ) ) { inputErrors . push ( "UNEVEN_TICKS" ) ; } // Whether axis is missing pref and suf if ( catchChartMistakes . noPrefixSuffix ( scale . primaryScale ) ) { inputErrors . push ( "NO_PREFIX_SUFFIX" ) ; } return inputErrors ; }


Input:
/ * Respond to actions coming from the dispatcher [CODESPLIT] function registeredCallback ( payload ) { var action = payload . action ; var chartProps ; var error_messages ; var input_errors ; switch ( action . eventName ) { /* *
		* Data input updated or reparse called
		* */ case "update-data-input" : case "update-and-reparse" : Dispatcher . waitFor ( [ ChartPropertiesStore . dispatchToken ] ) ; chartProps = ChartPropertiesStore . getAll ( ) ; error_messages = [ ] ; input_errors = validateDataInput ( chartProps ) ; error_messages = error_messages . concat ( input_errors ) ; _errors . messages = error_messages . map ( function ( err_name ) { return errorNames [ err_name ] ; } ) ; var isInvalid = some ( _errors . messages , { type : "error" } ) ; _errors . valid = ! isInvalid ; ErrorStore . emitChange ( ) ; break ; default : // do nothing } return true ; }


Input: TODO : jsDocify this if it works see [ ChartConfig#calculateDimensions ] ( #chartconfig / calculatedimensions ) [CODESPLIT] function calculate_xy_dimensions ( width , opts ) { var height ; var aspectRatio = opts . displayConfig . aspectRatio ; var metadata = opts . metadata ; if ( metadata . size == "auto" || opts . enableResponsive ) { // use current width } else { width = chartSizes [ metadata . size ] . width ; } switch ( metadata . size ) { case "auto" : height = width * aspectRatio . wide ; break ; case 'medium' : height = width * aspectRatio . wide ; break ; case "spotLong" : height = width * aspectRatio . longSpot ; break ; case "spotSmall" : height = width * aspectRatio . smallSpot ; break ; default : height = width * aspectRatio . wide ; } return { width : width , height : height } ; }


Input: / * eslint - disable no - console [CODESPLIT] function getErrorMessage ( key , action ) { var actionType = action && action . type ; var actionName = actionType && ` ${ actionType . toString ( ) } ` || 'an action' ; return ( ` ${ key } ${ actionName } ` + ` ` ) ; }


Input: Completer for the CLI ( multiple files and support to add more ) . [CODESPLIT] function cliCompleter ( set , done ) { var exposed = { } set . valueOf ( ) . forEach ( expose ) set . valueOf ( ) . forEach ( checkFactory ( exposed ) ) done ( ) function expose ( file ) { var landmarks = file . data [ landmarkId ] if ( landmarks ) { xtend ( exposed , landmarks ) } } }


Input: Factory to create a transformer based on the given info and set . [CODESPLIT] function transformerFactory ( fileSet , info ) { return transformer // Transformer. Adds references files to the set. function transformer ( ast , file ) { var filePath = file . path var space = file . data var links = [ ] var landmarks = { } var references var current var link var pathname /* istanbul ignore if - stdin */ if ( ! filePath ) { return } references = gatherReferences ( file , ast , info , fileSet ) current = getPathname ( filePath ) for ( link in references ) { pathname = getPathname ( link ) if ( fileSet && pathname !== current && getHash ( link ) && links . indexOf ( pathname ) === - 1 ) { links . push ( pathname ) fileSet . add ( pathname ) } } landmarks [ filePath ] = true slugs . reset ( ) visit ( ast , mark ) space [ referenceId ] = references space [ landmarkId ] = landmarks function mark ( node ) { var data = node . data || { } var props = data . hProperties || { } var id = props . name || props . id || data . id if ( ! id && node . type === 'heading' ) { id = slugs . slug ( toString ( node ) ) } if ( id ) { landmarks [ filePath + '#' + id ] = true } } } }


Input: Check if file references headings or files not in exposed . [CODESPLIT] function validate ( exposed , file ) { var references = file . data [ referenceId ] var filePath = file . path var reference var nodes var real var hash var pathname var warning var suggestion var ruleId for ( reference in references ) { nodes = references [ reference ] real = exposed [ reference ] hash = getHash ( reference ) // Check if files without `hash` can be linked to.  Because there’s no need // to inspect those files for headings they are not added to remark.  This // is especially useful because they might be non-markdown files. Here we // check if they exist. if ( ( real === undefined || real === null ) && ! hash && fs ) { real = fs . existsSync ( path . join ( file . cwd , decodeURI ( reference ) ) ) references [ reference ] = real } if ( ! real ) { if ( hash ) { pathname = getPathname ( reference ) warning = 'Link to unknown heading' ruleId = headingRuleId if ( pathname !== filePath ) { warning += ' in `' + pathname + '`' ruleId = headingInFileRuleId } warning += ': `' + hash + '`' } else { warning = 'Link to unknown file: `' + decodeURI ( reference ) + '`' ruleId = fileRuleId } suggestion = getClosest ( reference , exposed ) if ( suggestion ) { warning += '. Did you mean `' + suggestion + '`' } warnAll ( file , nodes , warning , ruleId ) } } }


Input: Gather references : a map of file - paths references to be one or more nodes . [CODESPLIT] function gatherReferences ( file , tree , info , fileSet ) { var cache = { } var getDefinition = definitions ( tree ) var prefix = '' var headingPrefix = '#' var lines if ( info && info . type in viewPaths ) { prefix = '/' + info . path ( ) + '/' + viewPaths [ info . type ] + '/' } if ( info && info . type in headingPrefixes ) { headingPrefix = headingPrefixes [ info . type ] } lines = info && info . type in lineLinks ? lineLinks [ info . type ] : false visit ( tree , [ 'link' , 'image' , 'linkReference' , 'imageReference' ] , onresource ) return cache // Handle resources. function onresource ( node ) { var link = node . url var definition var index var uri var pathname var hash // Handle references. if ( node . identifier ) { definition = getDefinition ( node . identifier ) link = definition && definition . url } // Ignore definitions without url. if ( ! link ) { return } uri = parse ( link ) // Drop `?search` uri . search = '' link = format ( uri ) if ( ! fileSet && ( uri . hostname || uri . pathname ) ) { return } if ( ! uri . hostname ) { if ( lines && lineExpression . test ( uri . hash ) ) { uri . hash = '' } // Handle hashes, or relative files. if ( ! uri . pathname && uri . hash ) { link = file . path + uri . hash uri = parse ( link ) } else { link = urljoin ( file . dirname , link ) if ( uri . hash ) { link += uri . hash } uri = parse ( link ) } } // Handle full links. if ( uri . hostname ) { if ( ! prefix || ! fileSet ) { return } if ( uri . hostname !== info . domain || uri . pathname . slice ( 0 , prefix . length ) !== prefix ) { return } link = uri . pathname . slice ( prefix . length ) + ( uri . hash || '' ) // Things get interesting here: branches: `foo/bar/baz` could be `baz` on // the `foo/bar` branch, or, `baz` in the `bar` directory on the `foo` // branch. //  Currently, we’re ignoring this and just not supporting branches. link = link . slice ( link . indexOf ( '/' ) + 1 ) } // Handle file links, or combinations of files and hashes. index = link . indexOf ( headingPrefix ) if ( index === - 1 ) { pathname = link hash = null } else { pathname = link . slice ( 0 , index ) hash = link . slice ( index + headingPrefix . length ) if ( lines && lineExpression . test ( hash ) ) { hash = null } } if ( ! cache [ pathname ] ) { cache [ pathname ] = [ ] } cache [ pathname ] . push ( node ) if ( hash ) { link = pathname + '#' + hash if ( ! cache [ link ] ) { cache [ link ] = [ ] } cache [ link ] . push ( node ) } } }


Input: Handle resources . [CODESPLIT] function onresource ( node ) { var link = node . url var definition var index var uri var pathname var hash // Handle references. if ( node . identifier ) { definition = getDefinition ( node . identifier ) link = definition && definition . url } // Ignore definitions without url. if ( ! link ) { return } uri = parse ( link ) // Drop `?search` uri . search = '' link = format ( uri ) if ( ! fileSet && ( uri . hostname || uri . pathname ) ) { return } if ( ! uri . hostname ) { if ( lines && lineExpression . test ( uri . hash ) ) { uri . hash = '' } // Handle hashes, or relative files. if ( ! uri . pathname && uri . hash ) { link = file . path + uri . hash uri = parse ( link ) } else { link = urljoin ( file . dirname , link ) if ( uri . hash ) { link += uri . hash } uri = parse ( link ) } } // Handle full links. if ( uri . hostname ) { if ( ! prefix || ! fileSet ) { return } if ( uri . hostname !== info . domain || uri . pathname . slice ( 0 , prefix . length ) !== prefix ) { return } link = uri . pathname . slice ( prefix . length ) + ( uri . hash || '' ) // Things get interesting here: branches: `foo/bar/baz` could be `baz` on // the `foo/bar` branch, or, `baz` in the `bar` directory on the `foo` // branch. //  Currently, we’re ignoring this and just not supporting branches. link = link . slice ( link . indexOf ( '/' ) + 1 ) } // Handle file links, or combinations of files and hashes. index = link . indexOf ( headingPrefix ) if ( index === - 1 ) { pathname = link hash = null } else { pathname = link . slice ( 0 , index ) hash = link . slice ( index + headingPrefix . length ) if ( lines && lineExpression . test ( hash ) ) { hash = null } } if ( ! cache [ pathname ] ) { cache [ pathname ] = [ ] } cache [ pathname ] . push ( node ) if ( hash ) { link = pathname + '#' + hash if ( ! cache [ link ] ) { cache [ link ] = [ ] } cache [ link ] . push ( node ) } }


Input: Utility to warn reason for each node in nodes on file . [CODESPLIT] function warnAll ( file , nodes , reason , ruleId ) { nodes . forEach ( one ) function one ( node ) { file . message ( reason , node , [ sourceId , ruleId ] . join ( ':' ) ) } }


Input: Suggest a possible similar reference . [CODESPLIT] function getClosest ( pathname , references ) { var hash = getHash ( pathname ) var base = getPathname ( pathname ) var dictionary = [ ] var reference var subhash var subbase for ( reference in references ) { subbase = getPathname ( reference ) subhash = getHash ( reference ) if ( getPathname ( reference ) === base ) { if ( subhash && hash ) { dictionary . push ( subhash ) } } else if ( ! subhash && ! hash ) { dictionary . push ( subbase ) } } return propose ( hash ? hash : base , dictionary , { threshold : 0.7 } ) }


Input: Get the hash of uri if applicable . [CODESPLIT] function getHash ( uri ) { var hash = parse ( uri ) . hash return hash ? hash . slice ( 1 ) : null }


Input: Returns an input map contents if a custom map path was specified [CODESPLIT] function getPrevMap ( from ) { if ( typeof options . map . prev === 'string' ) { var mapPath = options . map . prev + path . basename ( from ) + '.map' ; if ( grunt . file . exists ( mapPath ) ) { return grunt . file . read ( mapPath ) ; } } }


Input: to add back in logging comment this line out [CODESPLIT] function ( req , res , next ) { if ( req . url . indexOf ( '.' ) === - 1 && req . url . indexOf ( startDir ) > - 1 ) { req . url = startPath ; } return next ( ) ; }


Input: / * One node . [CODESPLIT] function one ( node ) { var type = node && node . type if ( type in map ) { node = map [ type ] ( node ) } if ( 'length' in node ) { node = all ( node ) } if ( node . children ) { node . children = all ( node . children ) } return node }


Input: / --- API [CODESPLIT] function Server ( options ) { if ( typeof ( options ) !== 'object' ) throw new TypeError ( 'options (object) is required' ) ; this . _log = options . log . child ( { component : 'agent' } , true ) ; this . _name = options . name || "named" ; this . _socket = null ; }


Input: turns a dotted - decimal address into a UInt32 [CODESPLIT] function parseIPv4 ( addr ) { if ( typeof ( addr ) !== 'string' ) throw new TypeError ( 'addr (string) is required' ) ; var octets = addr . split ( / \. / ) . map ( function ( octet ) { return ( parseInt ( octet , 10 ) ) ; } ) ; if ( octets . length !== 4 ) throw new TypeError ( 'valid IP address required' ) ; var uint32 = ( ( octets [ 0 ] * Math . pow ( 256 , 3 ) ) + ( octets [ 1 ] * Math . pow ( 256 , 2 ) ) + ( octets [ 2 ] * 256 ) + octets [ 3 ] ) ; return ( uint32 ) ; }


Input: Iterator used to walk down a nested object . [CODESPLIT] function getNested ( obj , prop ) { var service = obj [ prop ] ; if ( service === undefined && Bottle . config . strict ) { throw new Error ( 'Bottle was unable to resolve a service.  `' + prop + '` is undefined.' ) ; } return service ; }


Input: Get a nested bottle . Will set and return if not set . [CODESPLIT] function getNestedBottle ( name ) { var bottle ; if ( ! this . nested [ name ] ) { bottle = Bottle . pop ( ) ; this . nested [ name ] = bottle ; this . factory ( name , function SubProviderFactory ( ) { return bottle . container ; } ) ; } return this . nested [ name ] ; }


Input: Function used by provider to set up middleware for each request . [CODESPLIT] function applyMiddleware ( middleware , name , instance , container ) { var descriptor = { configurable : true , enumerable : true } ; if ( middleware . length ) { descriptor . get = function getWithMiddlewear ( ) { var index = 0 ; var next = function nextMiddleware ( err ) { if ( err ) { throw err ; } if ( middleware [ index ] ) { middleware [ index ++ ] ( instance , next ) ; } } ; next ( ) ; return instance ; } ; } else { descriptor . value = instance ; descriptor . writable = true ; } Object . defineProperty ( container , name , descriptor ) ; return container [ name ] ; }


Input: Register middleware . [CODESPLIT] function middleware ( fullname , func ) { var parts , name ; if ( typeof fullname === FUNCTION_TYPE ) { func = fullname ; fullname = GLOBAL_NAME ; } parts = fullname . split ( DELIMITER ) ; name = parts . shift ( ) ; if ( parts . length ) { getNestedBottle . call ( this , name ) . middleware ( parts . join ( DELIMITER ) , func ) ; } else { if ( ! this . middlewares [ name ] ) { this . middlewares [ name ] = [ ] ; } this . middlewares [ name ] . push ( func ) ; } return this ; }


Input: Create the provider properties on the container [CODESPLIT] function createProvider ( name , Provider ) { var providerName , properties , container , id , decorators , middlewares ; id = this . id ; container = this . container ; decorators = this . decorators ; middlewares = this . middlewares ; providerName = name + PROVIDER_SUFFIX ; properties = Object . create ( null ) ; properties [ providerName ] = { configurable : true , enumerable : true , get : function getProvider ( ) { var instance = new Provider ( ) ; delete container [ providerName ] ; container [ providerName ] = instance ; return instance ; } } ; properties [ name ] = { configurable : true , enumerable : true , get : function getService ( ) { var provider = container [ providerName ] ; var instance ; if ( provider ) { // filter through decorators instance = getWithGlobal ( decorators , name ) . reduce ( reducer , provider . $get ( container ) ) ; delete container [ providerName ] ; delete container [ name ] ; } return instance === undefined ? instance : applyMiddleware ( getWithGlobal ( middlewares , name ) , name , instance , container ) ; } } ; Object . defineProperties ( container , properties ) ; return this ; }


Input: Register a provider . [CODESPLIT] function provider ( fullname , Provider ) { var parts , name ; parts = fullname . split ( DELIMITER ) ; if ( this . providerMap [ fullname ] && parts . length === 1 && ! this . container [ fullname + PROVIDER_SUFFIX ] ) { return console . error ( fullname + ' provider already instantiated.' ) ; } this . originalProviders [ fullname ] = Provider ; this . providerMap [ fullname ] = true ; name = parts . shift ( ) ; if ( parts . length ) { getNestedBottle . call ( this , name ) . provider ( parts . join ( DELIMITER ) , Provider ) ; return this ; } return createProvider . call ( this , name , Provider ) ; }


Input: Private helper for creating service and service factories . [CODESPLIT] function createService ( name , Service , isClass ) { var deps = arguments . length > 3 ? slice . call ( arguments , 3 ) : [ ] ; var bottle = this ; return factory . call ( this , name , function GenericFactory ( ) { var serviceFactory = Service ; // alias for jshint var args = deps . map ( getNestedService , bottle . container ) ; if ( ! isClass ) { return serviceFactory . apply ( null , args ) ; } return new ( Service . bind . apply ( Service , [ null ] . concat ( args ) ) ) ( ) ; } ) ; }


Input: Register a class service [CODESPLIT] function service ( name , Service ) { return createService . apply ( this , [ name , Service , true ] . concat ( slice . call ( arguments , 2 ) ) ) ; }


Input: Register a function service [CODESPLIT] function serviceFactory ( name , factoryService ) { return createService . apply ( this , [ name , factoryService , false ] . concat ( slice . call ( arguments , 2 ) ) ) ; }


Input: Define a mutable property on the container . [CODESPLIT] function defineValue ( name , val ) { Object . defineProperty ( this , name , { configurable : true , enumerable : true , value : val , writable : true } ) ; }


Input: Iterator for setting a plain object literal via defineValue [CODESPLIT] function setValueObject ( container , name ) { var nestedContainer = container [ name ] ; if ( ! nestedContainer ) { nestedContainer = { } ; defineValue . call ( container , name , nestedContainer ) ; } return nestedContainer ; }


Input: Register a value [CODESPLIT] function value ( name , val ) { var parts ; parts = name . split ( DELIMITER ) ; name = parts . pop ( ) ; defineValue . call ( parts . reduce ( setValueObject , this . container ) , name , val ) ; return this ; }


Input: Register a constant [CODESPLIT] function constant ( name , value ) { var parts = name . split ( DELIMITER ) ; name = parts . pop ( ) ; defineConstant . call ( parts . reduce ( setValueObject , this . container ) , name , value ) ; return this ; }


Input: Register decorator . [CODESPLIT] function decorator ( fullname , func ) { var parts , name ; if ( typeof fullname === FUNCTION_TYPE ) { func = fullname ; fullname = GLOBAL_NAME ; } parts = fullname . split ( DELIMITER ) ; name = parts . shift ( ) ; if ( parts . length ) { getNestedBottle . call ( this , name ) . decorator ( parts . join ( DELIMITER ) , func ) ; } else { if ( ! this . decorators [ name ] ) { this . decorators [ name ] = [ ] ; } this . decorators [ name ] . push ( func ) ; } return this ; }


Input: Register an instance factory inside a generic factory . [CODESPLIT] function instanceFactory ( name , Factory ) { return factory . call ( this , name , function GenericInstanceFactory ( container ) { return { instance : Factory . bind ( Factory , container ) } ; } ) ; }


Input: Get an instance of bottle . [CODESPLIT] function pop ( name ) { var instance ; if ( typeof name === STRING_TYPE ) { instance = bottles [ name ] ; if ( ! instance ) { bottles [ name ] = instance = new Bottle ( ) ; instance . constant ( 'BOTTLE_NAME' , name ) ; } return instance ; } return new Bottle ( ) ; }


Input: Register a service factory provider or value based on properties on the object . [CODESPLIT] function register ( Obj ) { var value = Obj . $value === undefined ? Obj : Obj . $value ; return this [ Obj . $type || 'service' ] . apply ( this , [ Obj . $name , value ] . concat ( Obj . $inject || [ ] ) ) ; }


Input: Resets providers on a bottle instance . If names array is provided only the named providers will be reset . [CODESPLIT] function resetProviders ( names ) { var tempProviders = this . originalProviders ; var shouldFilter = Array . isArray ( names ) ; Object . keys ( this . originalProviders ) . forEach ( function resetProvider ( originalProviderName ) { if ( shouldFilter && names . indexOf ( originalProviderName ) === - 1 ) { return ; } var parts = originalProviderName . split ( DELIMITER ) ; if ( parts . length > 1 ) { parts . forEach ( removeProviderMap , getNestedBottle . call ( this , parts [ 0 ] ) ) ; } removeProviderMap . call ( this , originalProviderName ) ; this . provider ( originalProviderName , tempProviders [ originalProviderName ] ) ; } , this ) ; }


Input: Determine the coefficient of determination ( r^2 ) of a fit from the observations and predictions . [CODESPLIT] function determinationCoefficient ( data , results ) { const predictions = [ ] ; const observations = [ ] ; data . forEach ( ( d , i ) => { if ( d [ 1 ] !== null ) { observations . push ( d ) ; predictions . push ( results [ i ] ) ; } } ) ; const sum = observations . reduce ( ( a , observation ) => a + observation [ 1 ] , 0 ) ; const mean = sum / observations . length ; const ssyy = observations . reduce ( ( a , observation ) => { const difference = observation [ 1 ] - mean ; return a + ( difference * difference ) ; } , 0 ) ; const sse = observations . reduce ( ( accum , observation , index ) => { const prediction = predictions [ index ] ; const residual = observation [ 1 ] - prediction [ 1 ] ; return accum + ( residual * residual ) ; } , 0 ) ; return 1 - ( sse / ssyy ) ; }


Input: Determine the solution of a system of linear equations A * x = b using Gaussian elimination . [CODESPLIT] function gaussianElimination ( input , order ) { const matrix = input ; const n = input . length - 1 ; const coefficients = [ order ] ; for ( let i = 0 ; i < n ; i ++ ) { let maxrow = i ; for ( let j = i + 1 ; j < n ; j ++ ) { if ( Math . abs ( matrix [ i ] [ j ] ) > Math . abs ( matrix [ i ] [ maxrow ] ) ) { maxrow = j ; } } for ( let k = i ; k < n + 1 ; k ++ ) { const tmp = matrix [ k ] [ i ] ; matrix [ k ] [ i ] = matrix [ k ] [ maxrow ] ; matrix [ k ] [ maxrow ] = tmp ; } for ( let j = i + 1 ; j < n ; j ++ ) { for ( let k = n ; k >= i ; k -- ) { matrix [ k ] [ j ] -= ( matrix [ k ] [ i ] * matrix [ i ] [ j ] ) / matrix [ i ] [ i ] ; } } } for ( let j = n - 1 ; j >= 0 ; j -- ) { let total = 0 ; for ( let k = j + 1 ; k < n ; k ++ ) { total += matrix [ k ] [ j ] * coefficients [ k ] ; } coefficients [ j ] = ( matrix [ n ] [ j ] - total ) / matrix [ j ] [ j ] ; } return coefficients ; }


Input: For internal use . Throws if is passed an invalid AST node else does nothing . [CODESPLIT] function throwIfInvalidNode ( node , functionName ) { if ( ! exports . isASTNode ( node ) ) { throw new Error ( functionName + "(): " + util . inspect ( node ) + " is not a valid AST node." ) ; } }


Input: While entering nodes register all events and all call expressions that are not part of emit statement While exiting determine which of the registered call expressions is an event trigger and flag them NOTE : This rule currently doesn t flag issues where event declaration & non - emit ted event trigger reside in different contracts which are linked through inheritance . [CODESPLIT] function create ( context ) { const events = [ ] , callExpressions = [ ] , sourceCode = context . getSourceCode ( ) ; // Determines whether the given call name refers to an event declaration using scope resolution. function isEvent ( expr , eventDeclarations ) { for ( let { node , enclosingContract } of eventDeclarations ) { if ( expr . callee . name === node . name && sourceCode . isAChildOf ( expr , enclosingContract ) ) { return true ; } } return false ; } // Stores each declared event in the file and its corresponding parent contract function registerEventName ( emitted ) { const { node } = emitted ; ( ! emitted . exit ) && events . push ( { node , enclosingContract : sourceCode . getParent ( node ) } ) ; } function registerNonEmittedCallExpression ( emitted ) { const { node } = emitted ; if ( ! emitted . exit && sourceCode . getParent ( node ) . type !== "EmitStatement" ) { callExpressions . push ( node ) ; } } function reportBadEventTriggers ( emitted ) { if ( ! emitted . exit ) { return ; } callExpressions . forEach ( node => { isEvent ( node , events ) && context . report ( { node , fix ( fixer ) { return fixer . insertTextBefore ( node , "emit " ) ; } , message : "Use emit statements for triggering events." } ) ; } ) ; } return { EventDeclaration : registerEventName , CallExpression : registerNonEmittedCallExpression , Program : reportBadEventTriggers } ; }


Input: Determines whether the given call name refers to an event declaration using scope resolution . [CODESPLIT] function isEvent ( expr , eventDeclarations ) { for ( let { node , enclosingContract } of eventDeclarations ) { if ( expr . callee . name === node . name && sourceCode . isAChildOf ( expr , enclosingContract ) ) { return true ; } } return false ; }


Input: Stores each declared event in the file and its corresponding parent contract [CODESPLIT] function registerEventName ( emitted ) { const { node } = emitted ; ( ! emitted . exit ) && events . push ( { node , enclosingContract : sourceCode . getParent ( node ) } ) ; }


Input: collect all variable declarations from VariableDeclarators and DeclarativeExpressions [CODESPLIT] function inspectVariableDeclarator ( emitted ) { let node = emitted . node ; if ( ! emitted . exit ) { allVariableDeclarations [ node . id . name ] = node ; } }


Input: While exiting Progam Node all the vars that haven t been used still exist inside VariableDeclarations . Report them [CODESPLIT] function inspectProgram ( emitted ) { if ( emitted . exit ) { Object . keys ( allVariableDeclarations ) . forEach ( function ( name ) { context . report ( { node : allVariableDeclarations [ name ] , message : "Variable '" + name + "' is declared but never used." } ) ; } ) ; } }


Input: As soon as the first use of a variable is encountered delete that variable s node from allVariableDeclarations [CODESPLIT] function inspectIdentifier ( emitted ) { if ( ! emitted . exit ) { let node = emitted . node , sourceCode = context . getSourceCode ( ) ; if ( allVariableDeclarations [ node . name ] && sourceCode . getParent ( node ) . type !== "VariableDeclarator" ) { delete allVariableDeclarations [ node . name ] ; } } }


Input: Set cursor to point to first visibility in order of vis . array . For each function Fi inside contract if Fi s vis is same as that pointed by cursor ignore func . If not check the pos in the order of Fi s vis . If ahead simply move cursor forward to Fi s vis . s position in array . If behind report func . [CODESPLIT] function inspectFunctionsOfContract ( emitted ) { if ( emitted . exit ) { return ; } const { node } = emitted , { body } = node ; let cursor = 0 ; // Filter out non-function nodes body . filter ( child => { return [ "FunctionDeclaration" , "ConstructorDeclaration" ] . includes ( child . type ) ; } ) . forEach ( funcNode => { // Return if the function is ignored or in the correct order. if ( ( context . options && isIgnored ( funcNode , node , context . options [ 0 ] . ignore ) ) || isFunctionVisibility ( node , funcNode , functionOrder [ cursor ] ) ) { return ; } const funcPosInOrder = findFuncPosInOrder ( node , funcNode ) ; if ( funcPosInOrder > cursor ) { cursor = funcPosInOrder ; return ; } context . report ( { node : funcNode , message : errorMessage } ) ; } ) ; }


Input: The InformalParameter nodes ( params ) in modifier declaration should follow the same spacing rules as function declarations [CODESPLIT] function inspectModifierDeclaration ( emitted ) { let node = emitted . node ; if ( emitted . exit ) { return ; } //If parameters are specified, ensure appropriate spacing surrounding commas let params = node . params ; if ( params && params . length > 1 ) { params . slice ( 0 , - 1 ) . forEach ( function ( arg ) { sourceCode . getNextChar ( arg ) !== "," && context . report ( { node : arg , location : { column : sourceCode . getEndingColumn ( arg ) + 1 } , message : "All arguments (except the last one) must be immediately followed by a comma." } ) ; } ) ; } }


Input: same could potentially be applied to FunctionDeclaration [CODESPLIT] function inspectCallExpression ( emitted ) { let node = emitted . node , callArgs = node . arguments ; if ( emitted . exit ) { return ; } let nodeCode = sourceCode . getText ( node ) ; //for a 0-argument call, ensure that name is followed by '()' if ( ! callArgs . length ) { for ( let i = nodeCode . length ; i > 0 ; i -- ) { if ( nodeCode [ i ] === ")" && nodeCode [ i - 1 ] === "(" ) { return ; } if ( / [\s\(\)] / . test ( nodeCode [ i ] ) ) { break ; } } return context . report ( { node : node , message : "\"" + nodeCode + "\": " + "A call without arguments should have brackets without any whitespace between them, like 'functionName ()'." } ) ; } let lastCallArg = callArgs . slice ( - 1 ) [ 0 ] ; //if call spans over multiple lines (due to too many arguments), below rules don't apply if ( sourceCode . getLine ( node ) !== sourceCode . getEndingLine ( lastCallArg ) ) { return ; } let charBeforeFirstArg = sourceCode . getPrevChar ( callArgs [ 0 ] ) , charAfterLastCallArg = sourceCode . getNextChar ( lastCallArg ) ; ( callArgs [ 0 ] . type !== "NameValueAssignment" && charBeforeFirstArg !== "(" ) && context . report ( { node : callArgs [ 0 ] , location : { column : sourceCode . getColumn ( callArgs [ 0 ] ) - 1 } , message : "'" + node . callee . name + "': The first argument must not be preceded by any whitespace or comments (only '(')." } ) ; ( lastCallArg . type !== "NameValueAssignment" && charAfterLastCallArg !== ")" ) && context . report ( { node : callArgs [ 0 ] , location : { column : sourceCode . getEndingColumn ( lastCallArg ) + 1 } , message : "'" + node . callee . name + "': The last argument must not be succeeded by any whitespace or comments (only ')')." } ) ; }


Input: This executes only when we re leaving the Program node . At that time we check whether the missing pragma on top error has already been reported or not . If not we proceed to report it here . This happens when there are no pragma statements in the entire file . If there is one ( but not on top of file ) it gets reported by inspectPragmaStatement () . NOTE : A Pragma dir must exist at absolute top even before pragma experimental . [CODESPLIT] function inspectProgram ( emitted ) { let node = emitted . node , body = node . body ; if ( ! emitted . exit || missingNodeOnTopErrorReported ) { return ; } ( body . length > 0 ) && ( body [ 0 ] . type !== "PragmaStatement" ) && context . report ( { node : node , message : "No Pragma directive found at the top of file." } ) ; }


Input: Experimental pragmas if they exist must be above everything EXCEPT pragma solidity & other experimental pragmas . [CODESPLIT] function inspectExperimentalPragmaStatement ( emitted ) { if ( emitted . exit ) { return ; } const { node } = emitted , nodesAllowedAbove = [ "ExperimentalPragmaStatement" , "PragmaStatement" ] , programNode = context . getSourceCode ( ) . getParent ( node ) ; for ( let childNode of programNode . body ) { // If we've reached this exp. pragma while traversing body, it means its position is fine. if ( node . start === childNode . start ) { return ; } // We found the first node not allowed above experimental pragma, report and exit. const pragmaCode = context . getSourceCode ( ) . getText ( node ) ; if ( nodesAllowedAbove . indexOf ( childNode . type ) < 0 ) { const errObject = { node , fix ( fixer ) { return [ fixer . remove ( node ) , fixer . insertTextBefore ( childNode , ` ${ pragmaCode } ${ EOL } ` ) ] ; } , message : "Experimental Pragma must precede everything except Solidity Pragma." } ; return context . report ( errObject ) ; } } }


Input: Apply fixes to source code depending on whichever errors can be fixed . [CODESPLIT] function ( sourceCode , errorMessages ) { let fixedSourceCode = "" , fixes = [ ] , fixesApplied = [ ] , remainingMessages = [ ] ; let cursor = Number . NEGATIVE_INFINITY ; function attemptFix ( fix ) { let start = fix . range [ 0 ] , end = fix . range [ 1 ] ; // If this fix overlaps with the previous one or has negaive range, return. // Note that when cursor === start, its NOT an overlap since when source code in range // [i, j] is being edited, the code covered is actually from i to j-1. if ( cursor > start || start > end ) { return false ; } fixedSourceCode += sourceCode . slice ( Math . max ( 0 , cursor ) , Math . max ( 0 , start ) ) ; fixedSourceCode += fix . text ; cursor = end ; return true ; } // Segregate errors that can be fixed from those that can't for sure. errorMessages . forEach ( function ( msg ) { if ( msg . fix ) { // If msg.fix is an Array of fix packets, merge them into a single fix packet. try { msg . fix = mergeFixes ( msg . fix , sourceCode ) ; } catch ( e ) { throw new Error ( "An error occured while applying fix of rule \"" + msg . ruleName + "\" for error \"" + msg . message + "\": " + e . message ) ; } return fixes . push ( msg ) ; } remainingMessages . push ( msg ) ; } ) ; // Fixes will be applied in top-down approach. The fix that arrives first (line-wise, followed by column-wise) // gets applied first. But if current fix is applied successfully & the next one overlaps the current one, // then the next one is simply skipped. Hence, it is NOT guranteed that all fixes will be applied. fixes . sort ( compareMessagesByFixRange ) . forEach ( function ( msg ) { if ( attemptFix ( msg . fix ) ) { return fixesApplied . push ( msg ) ; } remainingMessages . push ( msg ) ; } ) ; fixedSourceCode += sourceCode . slice ( Math . max ( 0 , cursor ) ) ; remainingMessages . sort ( compareMessagesByLocation ) ; return { fixesApplied : fixesApplied , fixedSourceCode : fixedSourceCode , remainingErrorMessages : remainingMessages } ; }


Input: This func will receive either empty str ( len = 0 ) str with N Spaces ( N > = 1 ) or N Tabs ( N > = 1 ) [CODESPLIT] function getIndentDescription ( indentStyle , level ) { // If either user has specified 0 indent or we're at level 0 (start), totalIndent becomes 0. const totalIndent = indentStyle . length * level , s = totalIndent > 1 ? "s" : "" ; // If style is that there should be no indent for any level OR we're at base level if ( totalIndent === 0 ) { return "0 whitespace" ; } if ( indentStyle [ 0 ] === " " ) { return ` ${ totalIndent } ${ s } ` ; } // If above 2 are bypassed, indent style must be tab(s) return ` ${ totalIndent } ${ s } ` ; }


Input: Ensure NO indentation exists before top - level declarations ( contract library ) [CODESPLIT] function inspectProgram ( emitted ) { let node = emitted . node ; if ( emitted . exit ) { return ; } function inspectProgramChild ( programChild ) { //if node's code starts at index 0, getPrevChar() returns null (meaning no errors), so change it to '\n' let prevChar = sourceCode . getPrevChar ( programChild ) || "\n" , childEndingLine = sourceCode . getEndingLine ( programChild ) , childEndingLineText = sourceCode . getTextOnLine ( childEndingLine ) ; function report ( messageText ) { context . report ( { node : programChild , message : ( programChild . type . replace ( "Statement" , "" ) . toLowerCase ( ) + ( programChild . name ? ( " '" + programChild . name + "'" ) : " statement" ) + ": " + messageText ) } ) ; } if ( prevChar !== "\n" ) { //either indentation exists, or some other character - both are not allowed if ( / \s / . test ( prevChar ) ) { report ( "There should be no indentation before top-level declaration." ) ; } else { report ( "There should be no character(s) before top-level declaration." ) ; } } //if node starts and ends on different lines and its last line starts with a whitespace or multiline/natspec comment, report if ( sourceCode . getLine ( programChild ) !== childEndingLine && / ^(\s+)|(\/\*[^*\/]*\*\/) / . test ( childEndingLineText ) ) { context . report ( { node : programChild , location : { line : childEndingLine , column : 0 } , message : "Line shouln't have any indentation or comments at the beginning." } ) ; } } node . body . forEach ( inspectProgramChild ) ; }


Input: Ensure level 1 indentation before all immediate children of top - level declarations [CODESPLIT] function inspectTopLevelDeclaration ( emitted ) { let body = emitted . node . body || [ ] , levelOneIndentRegExp = new RegExp ( "^\\n" + BASE_INDENTATION_STYLE + "$" ) , endingLineRegExp = new RegExp ( "^" + BASE_INDENTATION_STYLE + "(\\S| \\*)$" ) , //either a non-whitespace character or 1 extra whitespace followed by * (closing of multi-line comment) endingLineExtraIndentRegExp = new RegExp ( "^" + BASE_INDENTATION_STYLE . repeat ( 2 ) + "(\\S| \\*)$" ) ; if ( emitted . exit ) { return ; } function inspectChild ( child ) { let prevChars = sourceCode . getPrevChars ( child , BASE_INDENTATION_STYLE . length + 1 ) , endingLineNum = sourceCode . getEndingLine ( child ) ; //if the start of node doesn't follow correct indentation if ( ! levelOneIndentRegExp . test ( prevChars ) ) { context . report ( { node : child , message : ` ${ BASE_INDENTATION_STYLE_DESC } ` } ) ; } // If the node starts & ends on same line, exit. if ( sourceCode . getLine ( child ) === endingLineNum ) { return ; } // If node starts & ends on diff lines, the ending line must also follow correct indentation. // Exception to this is an abstract function whose declaration spans over multiple lines. Eg- // function foo() //     payable //     returns (uint, string); if ( child . type === "FunctionDeclaration" && child . is_abstract ) { if ( ! endingLineExtraIndentRegExp . test ( sourceCode . getTextOnLine ( endingLineNum ) . slice ( 0 , BASE_INDENTATION_STYLE . repeat ( 2 ) . length + 1 ) ) ) { context . report ( { node : child , location : { line : endingLineNum , column : 0 } , message : ` ${ BASE_INDENTATION_STYLE_DESC } ` } ) ; } return ; } if ( ! endingLineRegExp . test ( sourceCode . getTextOnLine ( endingLineNum ) . slice ( 0 , BASE_INDENTATION_STYLE . length + 1 ) ) ) { context . report ( { node : child , location : { line : endingLineNum , column : 0 } , message : ` ${ BASE_INDENTATION_STYLE_DESC } ` } ) ; } } body . forEach ( inspectChild ) ; }


Input:
Ensure 1 extra indentation inside Block than before it [CODESPLIT] function inspectBlockStatement ( emitted ) { let node = emitted . node ; //if the complete block resides on the same line, no need to check for indentation if ( emitted . exit || ( sourceCode . getLine ( node ) === sourceCode . getEndingLine ( node ) ) ) { return ; } let parent = sourceCode . getParent ( node ) , parentDeclarationLine = sourceCode . getLine ( parent ) , parentDeclarationLineText = sourceCode . getTextOnLine ( parentDeclarationLine ) , currentIndent , currentIndentLevel ; function inspectBlockItem ( blockIndent , blockIndentDesc , blockItem ) { let prevChars = sourceCode . getPrevChars ( blockItem , blockIndent . length + 1 ) , endingLineNum = sourceCode . getEndingLine ( blockItem ) , endingLineRegExp = new RegExp ( "^" + blockIndent + "(" + BASE_INDENTATION_STYLE + ")?\\S.*$" ) ; if ( prevChars !== ( "\n" + blockIndent ) ) { context . report ( { node : blockItem , message : ` ${ blockIndentDesc } ` } ) ; } /**
				 * If the block item spans over multiple lines, make sure the ending line also follows the indent rule
				 * An exception to this is the if-else statements when they don't have BlockStatement as their body
				 * eg-
				 * if (a)
				 *     foo();
				 * else
				 *     bar();
				 *
				 * Another exception is chaining.
				 * eg-
				 * function() {
				 *   myObject
				 *     .funcA()
				 *     .funcB()
				 *     [0];
				 * }
				 * Ending line has 1 extra indentation but this is acceptable.
				 */ if ( blockItem . type !== "IfStatement" && sourceCode . getLine ( blockItem ) !== endingLineNum && ! endingLineRegExp . test ( sourceCode . getTextOnLine ( endingLineNum ) ) ) { context . report ( { node : blockItem , location : { line : endingLineNum , column : 0 } , message : ` ${ blockIndentDesc } ` } ) ; } } currentIndent = parentDeclarationLineText . slice ( 0 , parentDeclarationLineText . indexOf ( parentDeclarationLineText . trim ( ) ) ) ; //in case of no match, match() returns null. Return [] instead to avoid crash currentIndentLevel = ( currentIndent . match ( BASE_INDENTATION_STYLE_REGEXP_GLOBAL ) || [ ] ) . length ; //ensure that there is only whitespace of correct level before the block's parent's code if ( getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel ) !== currentIndent ) { return ; //exit now, we can' proceed further unless this is fixed } //indentation of items inside block should be 1 level greater than that of parent const blockIndent = getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; const blockIndentDesc = getIndentDescription ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; node . body . forEach ( inspectBlockItem . bind ( null , blockIndent , blockIndentDesc ) ) ; }


Input: function params ( if on multiple lines ) [CODESPLIT] function inspectFunctionDeclaration ( emitted ) { let node = emitted . node , params = node . params || [ ] ; let startLine = sourceCode . getLine ( node ) , lastArgLine = params . length ? sourceCode . getEndingLine ( params . slice ( - 1 ) [ 0 ] ) : startLine , functionDeclarationLineText , currentIndent , currentIndentLevel ; function inspectParam ( paramIndent , paramIndentDesc , param ) { let indentRegExp = new RegExp ( "^" + paramIndent + "[^\\s(\/\*)]" ) , paramLineText = sourceCode . getTextOnLine ( sourceCode . getLine ( param ) ) ; //parameter declaration must be preceded by only correct level of indentation & no comments ! indentRegExp . test ( paramLineText ) && context . report ( { node : param , message : ` ${ paramIndentDesc } ` } ) ; } // If declaration args start & end on same line, exit now if ( emitted . exit || startLine === lastArgLine ) { return ; } functionDeclarationLineText = sourceCode . getTextOnLine ( startLine ) ; currentIndent = functionDeclarationLineText . slice ( 0 , functionDeclarationLineText . indexOf ( functionDeclarationLineText . trim ( ) ) ) ; currentIndentLevel = ( currentIndent . match ( BASE_INDENTATION_STYLE_REGEXP_GLOBAL ) || [ ] ) . length ; //ensure that there is only whitespace of correct level on the line containing parameter if ( getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel ) !== currentIndent ) { return ; //exit now, we can' proceed further unless this is fixed } const paramIndent = getIndentString ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; const paramIndentDesc = getIndentDescription ( BASE_INDENTATION_STYLE , currentIndentLevel + 1 ) ; params . forEach ( inspectParam . bind ( null , paramIndent , paramIndentDesc ) ) ; }


Input: Recursive function . -- elopio - 20180421 [CODESPLIT] function checkNodes ( nodes ) { if ( ! Array . isArray ( nodes ) ) { nodes = [ nodes ] ; } nodes . forEach ( node => { let lineNumber = sourceCode . getLine ( node ) - 1 ; if ( lineNumber > lastLine && lines [ lineNumber ] . length > maxLineLength ) { context . report ( { node , message : ` ${ maxLineLength } ` } ) ; lastLine = lineNumber ; } checkNodes ( node . body || [ ] ) ; } ) ; }


Input: Function to retrieve the source code text being linted . Returns the complete source code if no node specified [CODESPLIT] function ( node , beforeCount , afterCount ) { let sourceCodeText = this . text ; if ( node ) { if ( astUtils . isASTNode ( node ) ) { return this . text . slice ( Math . max ( 0 , node . start - ( Math . abs ( beforeCount ) || 0 ) ) , node . end + ( Math . abs ( afterCount ) || 0 ) ) ; } throw new Error ( "Invalid Node object" ) ; } return sourceCodeText ; }


Input: Get the entire string between 2 nodes - ranging from prevNode . end to currentNode . start ( exclusive ) [CODESPLIT] function ( prevNode , currentNode ) { if ( prevNode && astUtils . isASTNode ( prevNode ) && currentNode && astUtils . isASTNode ( currentNode ) && prevNode . start <= currentNode . start ) { return this . text . slice ( prevNode . end , currentNode . start ) ; } throw new Error ( "Invalid argument for one or both nodes" ) ; }


Input: Get the complete text on line lineNumber ( excluding the EOL ) [CODESPLIT] function ( lineNumber ) { // Call getLines() just to ensure that this.sourceCodeTextLines property is set this . getLines ( ) ; if ( lineNumber && typeof lineNumber === "number" && parseInt ( lineNumber ) === lineNumber && //ensure that argument is an INTEGER lineNumber >= 1 && lineNumber <= this . sourceCodeTextLines . length ) { return this . sourceCodeTextLines [ lineNumber - 1 ] ; } throw new Error ( ` ${ lineNumber } ` ) ; }


Input: statement like var x = 10 doesn t come under AssignmentExpression so needs to be checked separately [CODESPLIT] function inspectVariableDeclaration ( emitted ) { let node = emitted . node , code = sourceCode . getText ( node ) ; if ( emitted . exit ) { return ; } //if a particular character is '=', check its left and right for single space for ( let i = 2 ; i < code . length ; i ++ ) { if ( code [ i ] === "=" ) { ( ! / ^[^\/\s] $ / . test ( code . slice ( i - 2 , i ) ) ) && context . report ( { node : node , message : "There should be only a single space between assignment operator '=' and its left side." } ) ; ( ! / ^ [^\/\s]$ / . test ( code . slice ( i + 1 , i + 3 ) ) ) && context . report ( { node : node , message : "There should be only a single space between assignment operator '=' and its right side." } ) ; } } }


Input:
context object Constructor to set read - only properties and provide additional functionality to the rules using it [CODESPLIT] function RuleContext ( ruleName , ruleDesc , ruleMeta , Solium ) { let contextObject = this ; // Set contect attribute 'options' iff options were provided. ruleDesc . options && Object . assign ( contextObject , { options : ruleDesc . options } ) ; //set read-only properties of the context object Object . defineProperties ( contextObject , { name : { value : ruleName , writable : false //though the default is false anyway, I think its better to express your intention clearly } , meta : { value : ruleDesc , writable : false } } ) ; //inherit all Solium methods which are of relevance to the rule INHERITABLE_METHODS . forEach ( function ( methodName ) { contextObject [ methodName ] = function ( s , z , a , b , o ) { //every method will receive 5 arguments tops return Solium [ methodName ] . call ( Solium , s , z , a , b , o ) ; } ; } ) ; /**
     * wrapper around Solium.report () which adds some additional information to the error object
     * @param {Object} error An object describing the lint error, sent by the rule currently running
     */ contextObject . report = function ( error ) { if ( ! isErrObjectValid ( error ) ) { throw new Error ( ` ${ ruleName } ${ EOL } ${ util . inspect ( isErrObjectValid . errors ) } ` ) ; } Object . assign ( error , { ruleName : ruleName , ruleMeta : ruleMeta , type : contextObject . meta . type } ) ; Solium . report ( error ) ; } ; }


Input: Given a ruleset name determine whether its a core set or a sharable config and load the rule config accordingly . [CODESPLIT] function resolveUpstream ( upstream ) { let coreRulesetRegExp = / ^solium:[a-z_]+$ / ; // Determine whether upstream is a solium core ruleset or a sharable config. if ( coreRulesetRegExp . test ( upstream ) ) { try { return require ( "../../config/rulesets/solium-" + upstream . split ( ":" ) [ 1 ] ) . rules ; } catch ( e ) { throw new Error ( "\"" + upstream + "\" is not a core ruleset." ) ; } } // If flow reaches here, it means upstream is a sharable config. let configName = constants . SOLIUM_SHARABLE_CONFIG_PREFIX + upstream , config ; try { config = require ( configName ) ; } catch ( e ) { if ( e . code === "MODULE_NOT_FOUND" ) { throw new Error ( "The sharable config \"" + configName + "\" is not installed. " + "If Solium is installed globally, install the config globally using " + "\"npm install -g " + configName + "\". Else install locally using " + "\"npm install --save-dev " + configName + "\"." ) ; } throw new Error ( "The sharable config \"" + configName + "\" could not be loaded: " + e . message ) ; } if ( isAValidSharableConfig ( config ) ) { return config . rules ; } throw new Error ( "Invalid sharable config \"" + configName + "\". AJV message:\n" + util . inspect ( isAValidSharableConfig . errors ) ) ; }


Input: Create provided plugin s default rule configuration [CODESPLIT] function resolvePluginConfig ( name , plugin ) { let config = { } ; Object . keys ( plugin . rules ) . forEach ( function ( ruleName ) { config [ name + "/" + ruleName ] = plugin . rules [ ruleName ] . meta . docs . type ; } ) ; return config ; }


Input: Load rule definitions ( rule objects ) from Solium s core rule directory & from pre - installed linter plugins . [CODESPLIT] function load ( listOfRules ) { let ruleDefs = { } ; listOfRules . forEach ( function ( name ) { // If the rule is part of a plugin, first load the plugin assuming that it has already been installed // in the same scope as Solium (global/project). Then return the appropriate rule from that plugin. if ( name . indexOf ( "/" ) > - 1 ) { let parts = name . split ( "/" ) , pluginName = constants . SOLIUM_PLUGIN_PREFIX + parts [ 0 ] , ruleName = parts [ 1 ] , plugin ; try { plugin = require ( pluginName ) ; } catch ( e ) { throw new Error ( "Unable to load Plugin \"" + pluginName + "\"." ) ; } // No need to verify whether this rule's implementation exists & is valid or not. // That is done at a later stage in solium.js itself using rule-inspector. // TODO: Examine "peerDependencies" of the plugin to ensure its compatible with current version of Solium. return ruleDefs [ name ] = plugin . rules [ ruleName ] ; } // If we're here, it means the rule is just a regular core rule :) let ruleFile = path . join ( constants . SOLIUM_CORE_RULES_DIRPATH , name ) ; try { ruleDefs [ name ] = require ( ruleFile ) ; } catch ( e ) { throw new Error ( "Unable to read " + ruleFile ) ; } } ) ; return ruleDefs ; }


Input: Synchronously write the passed configuration to the file whose absolute path is SOLIUMRC_FILENAME_ABSOLUTE [CODESPLIT] function writeConfigFile ( config ) { try { fs . writeFileSync ( SOLIUMRC_FILENAME_ABSOLUTE , JSON . stringify ( config , null , 2 ) ) ; } catch ( e ) { errorReporter . reportFatal ( ` ${ SOLIUMRC_FILENAME_ABSOLUTE } ${ EOL } ${ e . message } ` ) ; process . exit ( errorCodes . WRITE_FAILED ) ; } }


Input: Copy data from cli - utils / . default - solium - ignore to ( newly created ) . soliumignore in user s root directory [CODESPLIT] function createDefaultSoliumIgnore ( ) { try { fs . writeFileSync ( SOLIUMIGNORE_FILENAME_ABSOLUTE , fs . readFileSync ( DEFAULT_SOLIUMIGNORE_PATH ) ) ; } catch ( e ) { errorReporter . reportFatal ( ` ${ SOLIUMIGNORE_FILENAME_ABSOLUTE } ${ EOL } ${ e . message } ` ) ; process . exit ( errorCodes . WRITE_FAILED ) ; } }


Input: Lint a source code string based on user settings . If autofix is enabled write the fixed code back to file . [CODESPLIT] function lintString ( sourceCode , userConfig , errorReporter , fileName ) { let lintErrors , fixesApplied ; try { if ( userConfig . options . autofix || userConfig . options . autofixDryrun ) { let result = solium . lintAndFix ( sourceCode , userConfig ) ; lintErrors = result . errorMessages ; if ( userConfig . options . autofix ) { applyFixes ( fileName , result ) ; fixesApplied = result . fixesApplied ; } else { errorReporter . reportDiff ( fileName , sourceCode , result . fixedSourceCode , result . fixesApplied . length ) ; } } else { lintErrors = solium . lint ( sourceCode , userConfig ) ; } } catch ( e ) { // Don't abort in case of a parse error, just report it as a normal lint issue. if ( e . name !== "SyntaxError" ) { const messageOrStackrace = userConfig . options . debug ? e . stack : e . message ; errorReporter . reportFatal ( ` ${ fileName } ${ EOL } ${ messageOrStackrace } ` ) ; process . exit ( errorCodes . ERRORS_FOUND ) ; } lintErrors = [ { ruleName : "" , type : "error" , message : ` ${ e . found } ` , line : e . location . start . line , column : e . location . start . column } ] ; } // If any lint/internal errors/warnings exist, report them lintErrors . length && errorReporter . report ( fileName , sourceCode , lintErrors , fixesApplied ) ; return lintErrors . reduce ( function ( numOfErrors , err ) { return err . type === "error" ? numOfErrors + 1 : numOfErrors ; } , 0 ) ; }


Input: Lint a file based on user settings [CODESPLIT] function lintFile ( fileName , userConfig , errorReporter ) { let sourceCode ; try { sourceCode = fs . readFileSync ( fileName , "utf8" ) ; } catch ( e ) { errorReporter . reportFatal ( "Unable to read " + fileName + ": " + e . message ) ; process . exit ( errorCodes . FILE_NOT_FOUND ) ; } return lintString ( sourceCode , userConfig , errorReporter , fileName ) ; }