Input: function brushExtents () { var extents = {} ; d3 . keys ( __ . dimensions ) . forEach ( function ( d ) { var brush = brushes [ d ] ; if ( brush ! == undefined && !brush . empty () ) { var extent = brush . extent () ; extents [ d ] = extent ; } } ) ; return extents ; } [CODESPLIT] function brushFor ( axis ) { var brush = d3 . svg . multibrush ( ) ; brush . y ( __ . dimensions [ axis ] . yscale ) . on ( "brushstart" , function ( ) { if ( d3 . event . sourceEvent !== null ) { events . brushstart . call ( pc , __ . brushed ) ; d3 . event . sourceEvent . stopPropagation ( ) ; } } ) . on ( "brush" , function ( ) { brushUpdated ( selected ( ) ) ; } ) . on ( "brushend" , function ( ) { // d3.svg.multibrush clears extents just before calling 'brushend' // so we have to update here again. // This fixes issue #103 for now, but should be changed in d3.svg.multibrush // to avoid unnecessary computation. brushUpdated ( selected ( ) ) ; events . brushend . call ( pc , __ . brushed ) ; } ) . extentAdaption ( function ( selection ) { selection . style ( "visibility" , null ) . attr ( "x" , - 15 ) . attr ( "width" , 30 ) . style ( "fill" , "rgba(255,255,255,0.25)" ) . style ( "stroke" , "rgba(0,0,0,0.6)" ) ; } ) . resizeAdaption ( function ( selection ) { selection . selectAll ( "rect" ) . attr ( "x" , - 15 ) . attr ( "width" , 30 ) . style ( "visibility" , null ) . style ( "fill" , "rgba(0,0,0,0.1)" ) ; } ) ; brushes [ axis ] = brush ; return brush ; }


Input: [ 0 2 * PI ] - > [ - PI / 2 PI / 2 ] [CODESPLIT] function ( angle ) { var ret = angle ; if ( angle > Math . PI ) { ret = angle - 1.5 * Math . PI ; ret = angle - 1.5 * Math . PI ; } else { ret = angle - 0.5 * Math . PI ; ret = angle - 0.5 * Math . PI ; } return - ret ; }


Input: current iteration [CODESPLIT] function ( data ) { if ( data ) rq . data ( data ) ; rq . invalidate ( ) ; _clear ( ) ; rq . render ( ) ; }


Input: Logically converts a property and its value based on the flow direction context [CODESPLIT] function convertProperty ( originalKey , originalValue , isRtl ) { const key = getPropertyDoppelganger ( originalKey , isRtl ) const value = getValueDoppelganger ( key , originalValue , isRtl ) return { key , value } }


Input: Logically gets the direction of the given property based on the flow direction context [CODESPLIT] function getPropertyDoppelganger ( property , isRtl ) { const convertedProperty = isRtl ? propertiesToConvert . rtl [ property ] : propertiesToConvert . ltr [ property ] return convertedProperty || property }


Input: let s try to keep the complexity down ... If we have to do this much more let s break this up / * eslint - disable complexity Logically converts the given value to the correct version based on the key and flow direction context [CODESPLIT] function getValueDoppelganger ( key , originalValue , isRtl ) { if ( isNullOrUndefined ( originalValue ) ) { return originalValue } const flowDirection = isRtl ? 'rtl' : 'ltr' if ( isObject ( originalValue ) ) { return convert ( originalValue , flowDirection ) // recurssion 🌀 } const { isLogical , logicallessValue , isImportant , importantlessValue , } = analyzeOriginalValue ( originalValue ) if ( canHaveLogical . includes ( key ) && ! isLogical ) { return originalValue } const isFourDirectionalShorthand = includes ( [ 'margin' , 'padding' , 'borderColor' , 'borderRadius' , 'borderStyle' , 'borderWidth' , ] , key , ) if ( isLogical && ! isRtl && ! isFourDirectionalShorthand && ! key . match ( / (background)|((t|T)ransformOrigin) / ) ) { return logicallessValue } const conversionMap = valuesToConvert [ flowDirection ] // The logical props and values changes the default way you write four-directional shorhands // so that the order of values is `block-start`, `inline-start`, `block-end` and `inline-end`, which, // for the `inline-*` sides, is the opposite of how they are written without the `logical` keyword if ( isLogical && isFourDirectionalShorthand ) { return isRtl ? logicallessValue : convertValues ( key , importantlessValue , conversionMap , isImportant , // Reversing `isRtl` like this is crooked, but for the time being, it is the easiest way to // address how values of four-directional shorthand properties with the `logical` keyword // should be handled according to the spec. ! isRtl , ) } return convertValues ( key , importantlessValue , conversionMap , isImportant , isRtl , ) }


Input: / * eslint - enable complexity [CODESPLIT] function analyzeOriginalValue ( originalValue ) { const isNum = isNumber ( originalValue ) const logicallessValue = isNum ? originalValue : originalValue . replace ( / ^\s*logical\s* / i , '' ) const isLogical = ! isNum && logicallessValue . length !== originalValue . length const importantlessValue = isNum ? logicallessValue : logicallessValue . replace ( / \s*!important.*?$ / , '' ) const isImportant = ! isNum && importantlessValue . length !== logicallessValue . length return { isLogical , logicallessValue , isImportant , importantlessValue } }


Input: DirWatcher code adapted from Jeffrey Lin s original implementation : https : // github . com / jeffreylin / jsx_transformer_fun / blob / master / dirWatcher . js [CODESPLIT] function DirWatcher ( inputPath , persistent ) { assert . ok ( this instanceof DirWatcher ) ; var self = this ; var absPath = path . resolve ( inputPath ) ; if ( ! fs . statSync ( absPath ) . isDirectory ( ) ) { throw new Error ( inputPath + "is not a directory!" ) ; } EventEmitter . call ( self ) ; self . ready = false ; self . on ( "ready" , function ( ) { self . ready = true ; } ) ; Object . defineProperties ( self , { // Map of absDirPaths to fs.FSWatcher objects from fs.watch(). watchers : { value : { } } , dirContents : { value : { } } , rootPath : { value : absPath } , persistent : { value : ! ! persistent } } ) ; process . nextTick ( function ( ) { self . add ( absPath ) ; self . emit ( "ready" ) ; } ) ; }


Input: The Content constructor takes an options object which * must * have either a body or data property and * may * have a type property indicating the media type . If there is no type attribute a default will be inferred . [CODESPLIT] function ( options ) { this . body = options . body ; this . data = options . data ; this . type = options . type ; }


Input:
initialize the routes that the Express Application will serve [CODESPLIT] function init ( app , context , swagger ) { logger . log ( 'debug' , '%s|adding|routes|context=%s' + ( swagger ? "|SWAGGER" : "" ) , meta . module , context , meta ) ; if ( swagger ) { describeModels ( swagger ) ; swagger . addGET ( { 'spec' : { "description" : "Text To Speech REST API" , "path" : context + format + '/play/{voice}/{text}' , "notes" : "The REST API /play/ transform a text phrase into a spoken audio stream playable through an HTML5 <audio> element. You can pre-generate the audio by calling the REST API /generate/ before calling this one, to have the audio start playing as soon as you call the /play/ API." , "method" : "GET" , "summary" : "Transform a text phrase into an Audio Stream." , "nickname" : "play" , "responseClass" : "BinaryAudioStream" , "produces" : [ "audio/mp4" , "application/json" ] , "params" : [ swagger . params . path ( "voice" , "A 'human' voice to use, to speak the phrase" , "string" , { "values" : voices , "valueType" : "LIST" } , "Alex" ) , swagger . params . path ( "text" , "The text phrase to be spoken." , "string" ) ] , "errorResponses" : [ fix ( swagger . errors . notFound ( 'voice' ) ) , fix ( swagger . errors . notFound ( 'text' ) ) , fix ( swagger . errors . invalid ( 'voice' ) ) ] } , 'action' : function ( req , res ) { logger . log ( 'debug' , '%s|say|voice=%s|text=%s' , meta . module , req . params . voice , req . params . text , meta ) ; if ( voices . indexOf ( req . params . voice ) < 0 ) { swagger . stopWithError ( res , { code : 400 , reason : 'The voice ' + req . params . voice + ' is not supported' } ) ; return ; } tts . play ( req . param ( 'text' , 'No text passed' ) , req . param ( 'voice' , voice ) , function ( err , data ) { if ( err ) { if ( ! err . code || ! err . reason ) err = { code : 500 , reason : util . inspect ( err ) } ; swagger . stopWithError ( res , err ) ; } else { res . writeHead ( 200 , { 'Content-Type' : 'audio/mp4' } ) ; res . end ( data ) ; } } ) ; } } ) . addPost ( { 'spec' : { "description" : "Text To Speech REST API" , "path" : context + format + '/generate' , "notes" : "To avoid latency, when using the REST API /play/, you can pre-generate the audio on the server by calling this API." , "method" : "POST" , "summary" : "Generate the audio on the server." , "nickname" : "generate" , "responseClass" : "Status" , "params" : [ swagger . params . body ( "params" , "The text phrase to be pre-generated on the server" , 'TextToSpeech' , '{"voice" : "Alex", "text":"Hello world", "async" : true}' ) ] , "errorResponses" : [ fix ( swagger . errors . notFound ( 'voice' ) ) , fix ( swagger . errors . notFound ( 'text' ) ) , fix ( swagger . errors . invalid ( 'voice' ) ) , fix ( swagger . errors . invalid ( 'async' ) ) ] } , 'action' : function ( req , res ) { if ( ! req . body ) { swagger . stopWithError ( res , { code : 400 , reason : 'The BODY of the request is empty' } ) ; return ; } logger . log ( 'debug' , '%s|generate|voice=%s|text=%s|async=%s' , meta . module , req . body . voice , req . body . text , req . body . async , meta ) ; if ( voices . indexOf ( req . body . voice ) < 0 ) { swagger . stopWithError ( res , { code : 400 , reason : 'The voice ' + req . params . voice + ' is not supported' } ) ; return ; } var async ; if ( typeof req . body . async != 'undefined' ) { if ( req . body . async === true || req . body . async === 'true' ) { async = true ; } else if ( req . body . async === false || req . body . async === 'false' ) { async = false ; } else { swagger . stopWithError ( res , { code : 400 , reason : 'The async must be true or false' } ) ; return ; } } else async = false ; tts . play ( req . param ( 'text' , 'No text passed' ) , req . param ( 'voice' , voice ) , function ( err ) { if ( async === false ) { if ( err ) { if ( ! err . code || ! err . reason ) err = { code : 500 , reason : util . inspect ( err ) } ; swagger . stopWithError ( res , err ) ; } else { res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{"result":"OK","async":false}' ) ; } } } ) ; if ( async ) { res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{"result":"OK","async":true}' ) ; } } } ) ; } else { router . add ( app , context + '/tts.json/play' , 'GET' , function ( req , res ) { tts . play ( req . param ( 'text' , 'No text passed' ) , req . param ( 'voice' , voice ) , function ( err , data ) { if ( err ) { res . writeHead ( 404 , { "Content-Type" : "text/html" } ) ; res . end ( '
Unable to generate tts
\n' + err + '
' ) ; } else { res . writeHead ( 200 , { 'Content-Type' : 'audio/mp4' } ) ; res . end ( data ) ; } } ) ; } ) ; router . add ( app , context + '/tts.json/generate' , 'POST' , function ( req , res ) { var async = req . param ( 'async' , 'true' ) === 'true' ? true : false ; tts . play ( req . param ( 'text' , 'No text passed' ) , req . param ( 'voice' , voice ) , function ( err ) { if ( async === false ) { if ( err ) { res . writeHead ( 404 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{"result":"FAILED","async":false,"error":' + JSON . stringify ( err ) + '}' ) ; } else { res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{"result":"OK","async":false}' ) ; } } } ) ; if ( async ) { res . writeHead ( 200 , { 'Content-Type' : 'application/json' } ) ; res . end ( '{"result":"OK","async":true}' ) ; } } ) ; } tts . init ( ) ; }


Input: ReadFileCache is an EventEmitter subclass that caches file contents in memory so that subsequent calls to readFileP return the same contents regardless of any changes in the underlying file . [CODESPLIT] function ReadFileCache ( sourceDir , charset ) { assert . ok ( this instanceof ReadFileCache ) ; assert . strictEqual ( typeof sourceDir , "string" ) ; this . charset = charset ; EventEmitter . call ( this ) ; Object . defineProperties ( this , { sourceDir : { value : sourceDir } , sourceCache : { value : { } } } ) ; }


Input: Fetch the resource and call done when it is fetched [CODESPLIT] function done ( err , resource ) { totalRequestElapsed += ( ( new Date ( ) . getTime ( ) ) - started ) ; ++ totalRequests ; stats . avgFetchTime = parseInt ( totalRequestElapsed / totalRequests ) ; if ( err || verbose ) util . log ( 'cache|execute|done|err=' + err + '|result=' + ( resource ? 'found' : 'null' ) ) ; if ( err ) { ++ stats . failed ; } if ( ! err && defaultCacheTTL ) { // ttl ===  0 --> expire imediatly. if ( stats . inCache >= defaultCacheSize ) { weedOutCache ( ) ; } var now = new Date ( ) . getTime ( ) ; resourceCache [ key ] = { 'key' : key , 'epoch' : now , 'access' : now , 'expire' : defaultCacheTTL , 'hits' : 0 , 'data' : resource } ; ++ stats . inCache ; } var pendingRequests = requestQueue [ key ] ; delete requestQueue [ key ] ; for ( var i = 0 , size = pendingRequests . length ; i < size ; ++ i ) { if ( debug ) util . log ( 'cache|calling=' + i + '|err=' + err + '|resource=' + ( resource ? 'found' : 'null' ) ) ; if ( ! err && defaultCacheTTL ) { ++ resourceCache [ key ] . hits ; } pendingRequests [ i ] . call ( this , err , resource , resourceCache [ key ] ) ; -- stats . waiting ; } -- stats . fetching ; if ( stats . fetching === 0 && stats . waiting === 0 ) { self . emit ( 'stats' , stats ) ; } else { bufferedEmitter . call ( self , 'stats' , stats ) ; } }


Input: ///////////////////////// PUBLIC CLASS ////////////////////////////////// [CODESPLIT] function Cache ( size , ttl ) { defaultCacheSize = size || defaultCacheSize ; defaultCacheTTL = ttl || defaultCacheTTL ; if ( verbose ) util . log ( 'Cache|defaultCacheSize=' + defaultCacheSize + '|defaultCacheTTL=' + defaultCacheTTL ) ; if ( defaultCacheSize > 10000 ) { util . log ( 'Cache|WARNING|Weeding out a BIG (' + defaultCacheSize + ') cache when it is full can degrade the NODE server performance since it is not async' ) ; } }


Input:
Represents an instance of a gogs api [CODESPLIT] function API ( apiUrl , requester ) { var _this = this ; _this . apiUrl = apiUrl ; // Dependency injection. Allow a custom request module. var request = requester ? requester ( apiUrl ) : Requester ( apiUrl ) ; /**
   * Creates a new user account
   * @param user {object} the user to be created. Requires username, email, password
   * @param authUser {object} the user authenticating this request. Requires token or username and password
   * @param notify {boolean} send notification email to user
   * @return {Promise<object>} the newly created user
   */ _this . createUser = function ( user , authUser , notify ) { user . send_notify = notify ; return request ( 'admin/users' , authUser , user ) . then ( stat . checkCreatedResponse ) ; } ; /**
   * Edits the details on an existing user account
   * @param user {object} the user who's information will be updated. Requires username (note: the username cannot be changed)
   * @param authUser {object} the user authenticating this request. Requires token or username and password
   * @returns {Promise<object>} the updated user object
     */ _this . editUser = function ( user , authUser ) { return request ( 'admin/users/' + user . username , authUser , user , 'PATCH' ) . then ( stat . checkStandardResponse ) ; } ; /**
   * Deletes a user
   * @param user {object} the user to delete. Requires username
   * @param authUser {object} the user authenticating this request. Users cannot delete themselves. Requires token or username and password
   * @returns {Promise} resolves if successful
   */ _this . deleteUser = function ( user , authUser ) { if ( user . username === authUser . username ) { return Promise . reject ( 'Users cannot delete themselves!' ) ; } return request ( 'admin/users/' + user . username , authUser , null , 'DELETE' ) . then ( stat . checkNoContentResponse ) ; } ; /**
   * Searches for users that match the query
   * @param query {string}
   * @param limit {int} the maximum number of results to return
   * @param authUser {object} the user authenticating this request. If null the email fields will be empty in the result. Requires token or username and password
   * @returns {Promise<array>} an array of user objects
   */ _this . searchUsers = function ( query , limit , authUser ) { limit = limit || 10 ; // no zero limit allowed return request ( 'users/search?q=' + query + '&limit=' + limit , authUser ) . then ( stat . checkOkResponse ) ; } ; /**
   * Retrieves a user
   * @param user {object} the user to retrieve. Requires username
   * @param authUser {object} the user to authenticate as. If null the email field in the response will be empty. Requires token or username and password
   * @returns {Promise<object>} the found user object
   */ _this . getUser = function ( user , authUser ) { return request ( 'users/' + user . username , authUser ) . then ( stat . checkStandardResponse ) ; } ; /**
   * Searches for public repositories that match the query
   * @param query {string}
   * @param uid {int} the id of the user whose repositories will be searched. 0 will search all
   * @param limit {int} the maximum number of results to return
   * @returns {Promise<array>} an array of repository objects
   */ _this . searchRepos = function ( query , uid , limit ) { uid = uid || 0 ; limit = limit || 10 ; return request ( 'repos/search?q=' + query + '&uid=' + uid + '&limit=' + limit ) . then ( stat . checkOkResponse ) ; } ; /**
   * Creates a new repository for the user
   * @param repo {object} the repository being created. Requires name, description, private
   * @param user {object} the user creating the repository. Requires token or username and password
   * @returns {Promise<object>} the new repository object
     */ _this . createRepo = function ( repo , user ) { return request ( 'user/repos' , user , { name : repo . name , description : repo . description , private : repo . private } , null ) . then ( stat . checkCreatedResponse ) ; } ; /**
   * Returns information about a single repository
   * @param repo {object} the repository that will be retrieved. Requires full_name
   * @param authUser {object} the user authenticating this request. Requires username, password or token
   * @returns {Promise<object>} the repository object
   */ _this . getRepo = function ( repo , authUser ) { return request ( 'repos/' + repo . full_name , authUser ) . then ( stat . checkStandardResponse ) ; } ; /**
   * Returns an array of repositories this user has access to
   * @param user {object} the user who's repositories will be listed. Requires token or username and password
   * @returns {Promise<array>} an array of repository objects
   */ _this . listRepos = function ( user ) { return request ( 'user/repos' , user ) . then ( stat . checkStandardResponse ) ; } ; /**
   * Deletes a repository from the user
   * @param repo {object} the repository to delete. Requires name
   * @param user {object} the user that owns the repository. Requires token or username and password
   * @returns {Promise} resolves if successful
   */ _this . deleteRepo = function ( repo , user ) { return request ( 'repos/' + user . username + '/' + repo . name , user , null , 'DELETE' ) . then ( stat . checkNoContentResponse ) ; } ; /**
   * Creates an authentication token for the user
   * @param token {object} the token to be created. Requires name
   * @param user {object} the user creating the token. Requires username, token or password
   * @returns {Promise<object>} the new token object
   */ _this . createToken = function ( token , user ) { return request ( 'users/' + user . username + '/tokens' , user , { name : token . name } ) . then ( stat . checkCreatedResponse ) ; } ; /**
   * Returns an array of tokens the user has
   * @param user {object} the user who's tokens will be listed. Requires username, password
   * @returns {Promise<array>} an array of token objects
   */ _this . listTokens = function ( user ) { return request ( 'users/' + user . username + '/tokens' , user ) . then ( stat . checkStandardResponse ) ; } ; /**
   * Creates a public key for the user
   * @param key {object} the key to be created. Requires title, key
   * @param user {object} the user creating the key. Requires token or username and password
   * @returns {Promise<object>} the new public key object
   */ _this . createPublicKey = function ( key , user ) { return request ( 'user/keys' , user , { title : key . title , key : key . key } ) . then ( stat . checkCreatedResponse ) ; } ; /**
   * Returns an array of public keys that belong to the user
   * @param user {object} the user who's public keys will be listed. Requires username, token or password
   * @returns {Promise<array>} an array of public key objects
   */ _this . listPublicKeys = function ( user ) { return request ( 'users/' + user . username + '/keys' , user ) . then ( stat . checkStandardResponse ) ; } ; /**
   * Returns the full details for a public key
   * @param key {object} the key that will be retrieved. Requires id
   * @param user {object} the user who's key will be retrieved. Requires token or username and password
   * @returns {Promise<object>} the public key object
   */ _this . getPublicKey = function ( key , user ) { return request ( 'user/keys/' + key . id , user ) . then ( stat . checkStandardResponse ) ; } ; /**
   * Deletes a public key from the user
   * @param key {object} the key to be deleted. Requires id
   * @param user {object} the user who's key will be deleted. Requires token or username and password
   * @returns {Promise} resolves if successful
     */ _this . deletePublicKey = function ( key , user ) { return request ( 'user/keys/' + key . id , user , null , 'DELETE' ) . then ( stat . checkNoContentResponse ) ; } ; return _this ; }


Input: Helper that sorts by length giving priority to ones that start with ATG / AUG [CODESPLIT] function sortReadingFrames ( a , b ) { var aSort = a . length var bSort = b . length if ( bSort - aSort === 0 ) { var aStartCodon = a . slice ( 0 , 3 ) . toUpperCase ( ) . replace ( 'T' , 'U' ) var bStartCodon = b . slice ( 0 , 3 ) . toUpperCase ( ) . replace ( 'T' , 'U' ) if ( aStartCodon === 'AUG' ) { aSort ++ } if ( bStartCodon === 'AUG' ) { bSort ++ } } return bSort - aSort }


Input: Shred takes some options including a logger and request defaults . [CODESPLIT] function ( options ) { options = ( options || { } ) ; this . agent = options . agent ; this . defaults = options . defaults || { } ; this . log = options . logger || ( new Ax ( { level : "info" } ) ) ; this . _sharedCookieJar = new CookieJar ( ) ; this . logCurl = options . logCurl || false ; }


Input: this is a quick - and - dirty logger . there are other nicer loggers out there but the ones i found were also somewhat involved . this one has a Ruby logger type interface we can easily replace this provide the info debug etc . methods are the same . or we can change Haiku to use a more standard node . js interface [CODESPLIT] function ( level , message ) { var debug = ( level == "debug" || level == "error" ) ; if ( ! message ) { return message . toString ( ) ; } if ( typeof ( message ) == "object" ) { if ( message instanceof Error && debug ) { return message . stack ; } else { return inspect ( message ) ; } } else { return message . toString ( ) ; } }


Input: The Shred object itself constructs the Request object . You should rarely need to do this directly . [CODESPLIT] function ( options ) { this . log = options . logger ; this . cookieJar = options . cookieJar ; this . encoding = options . encoding ; this . logCurl = options . logCurl ; processOptions ( this , options || { } ) ; createRequest ( this ) ; }


Input: in milliseconds [CODESPLIT] function ( timeout ) { var request = this , milliseconds = 0 ; ; if ( ! timeout ) return this ; if ( typeof timeout === "number" ) { milliseconds = timeout ; } else { milliseconds = ( timeout . milliseconds || 0 ) + ( 1000 * ( ( timeout . seconds || 0 ) + ( 60 * ( ( timeout . minutes || 0 ) + ( 60 * ( timeout . hours || 0 ) ) ) ) ) ) ; } this . _timeout = milliseconds ; return this ; }


Input: processOptions is called from the constructor to handle all the work associated with making sure we do our best to ensure we have a valid request . [CODESPLIT] function ( request , options ) { request . log . debug ( "Processing request options .." ) ; // We'll use `request.emitter` to manage the `on` event handlers. request . emitter = ( new Emitter ) ; request . agent = options . agent ; // Set up the handlers ... if ( options . on ) { for ( var key in options . on ) { if ( options . on . hasOwnProperty ( key ) ) { request . emitter . on ( key , options . on [ key ] ) ; } } } // Make sure we were give a URL or a host if ( ! options . url && ! options . host ) { request . emitter . emit ( "request_error" , new Error ( "No url or url options (host, port, etc.)" ) ) ; return ; } // Allow for the [use of a proxy](http://www.jmarshall.com/easy/http/#proxies). if ( options . url ) { if ( options . proxy ) { request . url = options . proxy ; request . path = options . url ; } else { request . url = options . url ; } } // Set the remaining options. request . query = options . query || options . parameters || request . query ; request . method = options . method ; request . setHeader ( "user-agent" , options . agent || "Shred" ) ; request . setHeaders ( options . headers ) ; if ( request . cookieJar ) { var cookies = request . cookieJar . getCookies ( CookieAccessInfo ( request . host , request . path ) ) ; if ( cookies . length ) { var cookieString = request . getHeader ( 'cookie' ) || '' ; for ( var cookieIndex = 0 ; cookieIndex < cookies . length ; ++ cookieIndex ) { if ( cookieString . length && cookieString [ cookieString . length - 1 ] != ';' ) { cookieString += ';' ; } cookieString += cookies [ cookieIndex ] . name + '=' + cookies [ cookieIndex ] . value + ';' ; } request . setHeader ( "cookie" , cookieString ) ; } } // The content entity can be set either using the `body` or `content` attributes. if ( options . body || options . content ) { request . content = options . body || options . content ; } request . timeout = options . timeout ; }


Input: createRequest is also called by the constructor after processOptions . This actually makes the request and processes the response so createRequest is a bit of a misnomer . [CODESPLIT] function ( request ) { var timeout ; request . log . debug ( "Creating request .." ) ; request . log . debug ( request ) ; var reqParams = { host : request . host , port : request . port , method : request . method , path : request . path + ( request . query ? '?' + request . query : "" ) , headers : request . getHeaders ( ) , // Node's HTTP/S modules will ignore this, but we are using the // browserify-http module in the browser for both HTTP and HTTPS, and this // is how you differentiate the two. scheme : request . scheme , // Use a provided agent.  'Undefined' is the default, which uses a global // agent. agent : request . agent } ; if ( request . logCurl ) { logCurl ( request ) ; } var http = request . scheme == "http" ? HTTP : HTTPS ; // Set up the real request using the selected library. The request won't be // sent until we call `.end()`. request . _raw = http . request ( reqParams , function ( response ) { request . log . debug ( "Received response .." ) ; // We haven't timed out and we have a response, so make sure we clear the // timeout so it doesn't fire while we're processing the response. clearTimeout ( timeout ) ; // Construct a Shred `Response` object from the response. This will stream // the response, thus the need for the callback. We can access the response // entity safely once we're in the callback. response = new Response ( response , request , function ( response ) { // Set up some event magic. The precedence is given first to // status-specific handlers, then to responses for a given event, and then // finally to the more general `response` handler. In the last case, we // need to first make sure we're not dealing with a a redirect. var emit = function ( event ) { var emitter = request . emitter ; var textStatus = STATUS_CODES [ response . status ] ? STATUS_CODES [ response . status ] . toLowerCase ( ) : null ; if ( emitter . listeners ( response . status ) . length > 0 || emitter . listeners ( textStatus ) . length > 0 ) { emitter . emit ( response . status , response ) ; emitter . emit ( textStatus , response ) ; } else { if ( emitter . listeners ( event ) . length > 0 ) { emitter . emit ( event , response ) ; } else if ( ! response . isRedirect ) { emitter . emit ( "response" , response ) ; //console.warn("Request has no event listener for status code " + response.status); } } } ; // Next, check for a redirect. We simply repeat the request with the URL // given in the `Location` header. We fire a `redirect` event. if ( response . isRedirect ) { request . log . debug ( "Redirecting to " + response . getHeader ( "Location" ) ) ; request . url = response . getHeader ( "Location" ) ; emit ( "redirect" ) ; createRequest ( request ) ; // Okay, it's not a redirect. Is it an error of some kind? } else if ( response . isError ) { emit ( "error" ) ; } else { // It looks like we're good shape. Trigger the `success` event. emit ( "success" ) ; } } ) ; } ) ; // We're still setting up the request. Next, we're going to handle error cases // where we have no response. We don't emit an error event because that event // takes a response. We don't response handlers to have to check for a null // value. However, we [should introduce a different event // type](https://github.com/spire-io/shred/issues/3) for this type of error. request . _raw . on ( "error" , function ( error ) { request . emitter . emit ( "request_error" , error ) ; } ) ; request . _raw . on ( "socket" , function ( socket ) { request . emitter . emit ( "socket" , socket ) ; } ) ; // TCP timeouts should also trigger the "response_error" event. request . _raw . on ( 'socket' , function ( ) { request . _raw . socket . on ( 'timeout' , function ( ) { // This should trigger the "error" event on the raw request, which will // trigger the "response_error" on the shred request. request . _raw . abort ( ) ; } ) ; } ) ; // We're almost there. Next, we need to write the request entity to the // underlying request object. if ( request . content ) { request . log . debug ( "Streaming body: '" + request . content . data . slice ( 0 , 59 ) + "' ... " ) ; request . _raw . write ( request . content . data ) ; } // Finally, we need to set up the timeout. We do this last so that we don't // start the clock ticking until the last possible moment. if ( request . timeout ) { timeout = setTimeout ( function ( ) { request . log . debug ( "Timeout fired, aborting request ..." ) ; request . _raw . abort ( ) ; request . emitter . emit ( "timeout" , request ) ; } , request . timeout ) ; } // The `.end()` method will cause the request to fire. Technically, it might // have already sent the headers and body. request . log . debug ( "Sending request ..." ) ; request . _raw . end ( ) ; }


Input: Set up some event magic . The precedence is given first to status - specific handlers then to responses for a given event and then finally to the more general response handler . In the last case we need to first make sure we re not dealing with a a redirect . [CODESPLIT] function ( event ) { var emitter = request . emitter ; var textStatus = STATUS_CODES [ response . status ] ? STATUS_CODES [ response . status ] . toLowerCase ( ) : null ; if ( emitter . listeners ( response . status ) . length > 0 || emitter . listeners ( textStatus ) . length > 0 ) { emitter . emit ( response . status , response ) ; emitter . emit ( textStatus , response ) ; } else { if ( emitter . listeners ( event ) . length > 0 ) { emitter . emit ( event , response ) ; } else if ( ! response . isRedirect ) { emitter . emit ( "response" , response ) ; //console.warn("Request has no event listener for status code " + response.status); } } }


Input: Logs the curl command for the request . [CODESPLIT] function ( req ) { var headers = req . getHeaders ( ) ; var headerString = "" ; for ( var key in headers ) { headerString += '-H "' + key + ": " + headers [ key ] + '" ' ; } var bodyString = "" if ( req . content ) { bodyString += "-d '" + req . content . body + "' " ; } var query = req . query ? '?' + req . query : "" ; console . log ( "curl " + "-X " + req . method . toUpperCase ( ) + " " + req . scheme + "://" + req . host + ":" + req . port + req . path + query + " " + headerString + bodyString ) ; }


Input: Construct a Response object . You should never have to do this directly . The Request object handles this getting the raw response object and passing it in here along with the request . The callback allows us to stream the response and then use the callback to let the request know when it s ready . [CODESPLIT] function ( raw , request , callback ) { var response = this ; this . _raw = raw ; // The `._setHeaders` method is "private"; you can't otherwise set headers on // the response. this . _setHeaders . call ( this , raw . headers ) ; // store any cookies if ( request . cookieJar && this . getHeader ( 'set-cookie' ) ) { var cookieStrings = this . getHeader ( 'set-cookie' ) ; var cookieObjs = [ ] , cookie ; for ( var i = 0 ; i < cookieStrings . length ; i ++ ) { var cookieString = cookieStrings [ i ] ; if ( ! cookieString ) { continue ; } if ( ! cookieString . match ( / domain\= / i ) ) { cookieString += '; domain=' + request . host ; } if ( ! cookieString . match ( / path\= / i ) ) { cookieString += '; path=' + request . path ; } try { cookie = new Cookie ( cookieString ) ; if ( cookie ) { cookieObjs . push ( cookie ) ; } } catch ( e ) { console . warn ( "Tried to set bad cookie: " + cookieString ) ; } } request . cookieJar . setCookies ( cookieObjs ) ; } this . request = request ; this . client = request . client ; this . log = this . request . log ; // Stream the response content entity and fire the callback when we're done. // Store the incoming data in a array of Buffers which we concatinate into one // buffer at the end.  We need to use buffers instead of strings here in order // to preserve binary data. var chunkBuffers = [ ] ; var dataLength = 0 ; raw . on ( "data" , function ( chunk ) { chunkBuffers . push ( chunk ) ; dataLength += chunk . length ; } ) ; raw . on ( "end" , function ( ) { var body ; if ( typeof Buffer === 'undefined' ) { // Just concatinate into a string body = chunkBuffers . join ( '' ) ; } else { // Initialize new buffer and add the chunks one-at-a-time. body = new Buffer ( dataLength ) ; for ( var i = 0 , pos = 0 ; i < chunkBuffers . length ; i ++ ) { chunkBuffers [ i ] . copy ( body , pos ) ; pos += chunkBuffers [ i ] . length ; } } var setBodyAndFinish = function ( body ) { response . _body = new Content ( { body : body , type : response . getHeader ( "Content-Type" ) } ) ; callback ( response ) ; } if ( zlib && response . getHeader ( "Content-Encoding" ) === 'gzip' ) { zlib . gunzip ( body , function ( err , gunzippedBody ) { if ( Iconv && response . request . encoding ) { body = Iconv . fromEncoding ( gunzippedBody , response . request . encoding ) ; } else { body = gunzippedBody . toString ( ) ; } setBodyAndFinish ( body ) ; } ) } else { if ( response . request . encoding ) { body = Iconv . fromEncoding ( body , response . request . encoding ) ; } setBodyAndFinish ( body ) ; } } ) ; }


Input: The real getHeader function : get one or more headers or all of them if you don t ask for any specifics . [CODESPLIT] function ( object , names ) { var keys = ( names && names . length > 0 ) ? names : Object . keys ( $H ( object ) ) ; var hash = keys . reduce ( function ( hash , key ) { hash [ key ] = getHeader ( object , key ) ; return hash ; } , { } ) ; // Freeze the resulting hash so you don't mistakenly think you're modifying // the real headers. Object . freeze ( hash ) ; return hash ; }


Input: Add getters . [CODESPLIT] function ( constructor ) { constructor . prototype . getHeader = function ( name ) { return getHeader ( this , name ) ; } ; constructor . prototype . getHeaders = function ( ) { return getHeaders ( this , arguments ) ; } ; }


Input: Add setters but as private methods . [CODESPLIT] function ( constructor ) { constructor . prototype . _setHeader = function ( key , value ) { return setHeader ( this , key , value ) ; } ; constructor . prototype . _setHeaders = function ( hash ) { return setHeaders ( this , hash ) ; } ; }


Input: Add setters . [CODESPLIT] function ( constructor ) { constructor . prototype . setHeader = function ( key , value ) { return setHeader ( this , key , value ) ; } ; constructor . prototype . setHeaders = function ( hash ) { return setHeaders ( this , hash ) ; } ; }


Input: Add both getters and setters . [CODESPLIT] function ( constructor ) { constructor . prototype . getHeader = function ( name ) { return getHeader ( this , name ) ; } ; constructor . prototype . getHeaders = function ( ) { return getHeaders ( this , arguments ) ; } ; constructor . prototype . setHeader = function ( key , value ) { return setHeader ( this , key , value ) ; } ; constructor . prototype . setHeaders = function ( hash ) { return setHeaders ( this , hash ) ; } ; }


Input: Get correct codec for given encoding . [CODESPLIT] function ( encoding ) { var enc = encoding || "utf8" ; var codecOptions = undefined ; while ( 1 ) { if ( getType ( enc ) === "String" ) enc = enc . replace ( / [- ] / g , "" ) . toLowerCase ( ) ; var codec = iconv . encodings [ enc ] ; var type = getType ( codec ) ; if ( type === "String" ) { // Link to other encoding. codecOptions = { originalEncoding : enc } ; enc = codec ; } else if ( type === "Object" && codec . type != undefined ) { // Options for other encoding. codecOptions = codec ; enc = codec . type ; } else if ( type === "Function" ) // Codec itself. return codec ( codecOptions ) ; else throw new Error ( "Encoding not recognized: '" + encoding + "' (searched as: '" + enc + "')" ) ; } }


Input: Codepage single - byte encodings . [CODESPLIT] function ( options ) { // Prepare chars if needed if ( ! options . chars || ( options . chars . length !== 128 && options . chars . length !== 256 ) ) throw new Error ( "Encoding '" + options . type + "' has incorrect 'chars' (must be of len 128 or 256)" ) ; if ( options . chars . length === 128 ) options . chars = asciiString + options . chars ; if ( ! options . charsBuf ) { options . charsBuf = new Buffer ( options . chars , 'ucs2' ) ; } if ( ! options . revCharsBuf ) { options . revCharsBuf = new Buffer ( 65536 ) ; var defChar = iconv . defaultCharSingleByte . charCodeAt ( 0 ) ; for ( var i = 0 ; i < options . revCharsBuf . length ; i ++ ) options . revCharsBuf [ i ] = defChar ; for ( var i = 0 ; i < options . chars . length ; i ++ ) options . revCharsBuf [ options . chars . charCodeAt ( i ) ] = i ; } return { toEncoding : function ( str ) { str = ensureString ( str ) ; var buf = new Buffer ( str . length ) ; var revCharsBuf = options . revCharsBuf ; for ( var i = 0 ; i < str . length ; i ++ ) buf [ i ] = revCharsBuf [ str . charCodeAt ( i ) ] ; return buf ; } , fromEncoding : function ( buf ) { buf = ensureBuffer ( buf ) ; // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. var charsBuf = options . charsBuf ; var newBuf = new Buffer ( buf . length * 2 ) ; var idx1 = 0 , idx2 = 0 ; for ( var i = 0 , _len = buf . length ; i < _len ; i ++ ) { idx1 = buf [ i ] * 2 ; idx2 = i * 2 ; newBuf [ idx2 ] = charsBuf [ idx1 ] ; newBuf [ idx2 + 1 ] = charsBuf [ idx1 + 1 ] ; } return newBuf . toString ( 'ucs2' ) ; } } ; }


Input: Codepage double - byte encodings . [CODESPLIT] function ( options ) { var table = options . table , key , revCharsTable = options . revCharsTable ; if ( ! table ) { throw new Error ( "Encoding '" + options . type + "' has incorect 'table' option" ) ; } if ( ! revCharsTable ) { revCharsTable = options . revCharsTable = { } ; for ( key in table ) { revCharsTable [ table [ key ] ] = parseInt ( key ) ; } } return { toEncoding : function ( str ) { str = ensureString ( str ) ; var strLen = str . length ; var bufLen = strLen ; for ( var i = 0 ; i < strLen ; i ++ ) if ( str . charCodeAt ( i ) >> 7 ) bufLen ++ ; var newBuf = new Buffer ( bufLen ) , gbkcode , unicode , defaultChar = revCharsTable [ iconv . defaultCharUnicode . charCodeAt ( 0 ) ] ; for ( var i = 0 , j = 0 ; i < strLen ; i ++ ) { unicode = str . charCodeAt ( i ) ; if ( unicode >> 7 ) { gbkcode = revCharsTable [ unicode ] || defaultChar ; newBuf [ j ++ ] = gbkcode >> 8 ; //high byte; newBuf [ j ++ ] = gbkcode & 0xFF ; //low byte } else { //ascii newBuf [ j ++ ] = unicode ; } } return newBuf ; } , fromEncoding : function ( buf ) { buf = ensureBuffer ( buf ) ; var bufLen = buf . length , strLen = 0 ; for ( var i = 0 ; i < bufLen ; i ++ ) { strLen ++ ; if ( buf [ i ] & 0x80 ) //the high bit is 1, so this byte is gbkcode's high byte.skip next byte i ++ ; } var newBuf = new Buffer ( strLen * 2 ) , unicode , gbkcode , defaultChar = iconv . defaultCharUnicode . charCodeAt ( 0 ) ; for ( var i = 0 , j = 0 ; i < bufLen ; i ++ , j += 2 ) { gbkcode = buf [ i ] ; if ( gbkcode & 0x80 ) { gbkcode = ( gbkcode << 8 ) + buf [ ++ i ] ; unicode = table [ gbkcode ] || defaultChar ; } else { unicode = gbkcode ; } newBuf [ j ] = unicode & 0xFF ; //low byte newBuf [ j + 1 ] = unicode >> 8 ; //high byte } return newBuf . toString ( 'ucs2' ) ; } } }


Input: Refactor into module ------------------------------------------ [CODESPLIT] function copyFile ( opts ) { var importStr , ext ; if ( ! opts ) return console . log ( 'incomplete options' ) ; ext = opts . ext ; if ( typeof ext === 'string' ) { ext = [ ext ] ; // turn string ext into array } // itterate through each file and process it ext . forEach ( function ( extension ) { var filename ; filename = opts . filename ; // handle sass paritals by prepending underscore if ( extension === '.scss' ) { importStr = "@import '../pages/" + opts . pageName + "/" + filename + "';\n" fs . appendFileSync ( 'client/styles/_pages.scss' , importStr ) filename = "_" + filename ; } // copy from default folder to destination folder and rename any // variables that may be in each file fs . copy ( opts . from + filename + extension , opts . to + filename + extension , function ( err ) { handleError ( err ) ; replace ( opts . to + filename + extension , function ( data ) { var res , repl ; if ( opts . replaceWith ) { repl = opts . replaceWith ; res = data . replace ( / compName / g , changeCase . camelCase ( repl ) ) ; return res . replace ( / comp-name / g , changeCase . paramCase ( repl ) ) ; } else { res = data . replace ( / compName / g , nameCase . camel ) ; return res . replace ( / comp-name / g , nameCase . hyphen ) ; } } ) ; console . log ( '    Created:' , opts . to + opts . filename + extension ) ; } ) ; } ) ; }


Input: Generates the authentication parameter for the user Preference will be given to the token if it exists [CODESPLIT] function encodeUserAuth ( user ) { if ( ! user ) { return null ; } var token = user . token ; if ( token ) { var sha1 = typeof token === 'object' ? token . sha1 : token ; return 'token ' + sha1 ; } return 'Basic ' + base64 . encode ( user . username + ':' + user . password ) }


Input: add a route to an express application [CODESPLIT] function addRoute ( app , route , method , destination ) { if ( method === 'GET' ) { app . get ( route , destination ) ; } else if ( method === 'POST' ) { app . post ( route , destination ) ; } else if ( method === 'PUT' ) { app . put ( route , destination ) ; } else if ( method === 'DELETE' ) { app . delete ( route , destination ) ; } else { throw new Error ( meta . module + '|addRoute|EXCEPTION|unknown method:"' + method + '"|expecter=GET,POST,PUT,DELETE' ) ; } logger . log ( 'debug' , '%s|add|method=%s|route=%s' , meta . module , method , route , meta ) ; }


Input: add a route to an express application [CODESPLIT] function add ( app , route , method , destination ) { var methods ; if ( typeof ( method ) === 'string' ) { methods = method . split ( ',' ) ; } else if ( typeof ( method ) === 'object' ) { // array methods = method ; } else { throw new Error ( meta . module + '|add|EXCEPTION|unknown method:"' + typeof ( method ) + '"|expecter=string,object(array)' ) ; } for ( var i = 0 ; i < methods . length ; ++ i ) { addRoute ( app , route , methods [ i ] , destination ) ; } }


Input: Public : Copy the boilerplate in the templates init folder to the user s root project folder . Creates a router and client folder . The project name is used for removing original boilerplate . Examples : require ( . / init ) . init ( myProjectName ) ; projectName - the { String } name of the user s meteor project [CODESPLIT] function ( projectName ) { var self = this ; this . projectName = projectName ; this . projDir = './' + projectName + '/' ; this . packages = this . projDir + '.meteor/packages' ; this . _runTerminalCommand ( 'meteor create ' + projectName , function ( ) { // after command is finished router . create ( self . projDir ) ; self . _copyTemplate ( ) ; self . _removeOriginalMeteorFiles ( projectName ) ; self . _removeUnwantedPackages ( ) ; self . _addPackagesToPackagesFile ( ) ; puts ( '\n-------------------------------------------' ) ; puts ( '  type cd %s to navigate to project' , projectName ) ; puts ( '  then the meteor command to start a server' ) ; puts ( '-------------------------------------------\n' ) ; } ) ; }


Input: Private : Run a command on the command line . command - the { String } command to run callback - a { Function } to call when complete [CODESPLIT] function ( command , callback ) { var exec = require ( 'child_process' ) . exec ; exec ( command , function ( err ) { if ( err ) puts ( 'exec error: ' + err ) ; callback . call ( this ) ; } ) ; }


Input: Private : Copy the boilerplate from templates directory and place it in the user s project root directory . Remove . gitkeep when done [CODESPLIT] function ( ) { fs . copySync ( this . initSource , this . projDir ) ; fs . removeSync ( this . projDir + 'client/.gitkeep' ) ; fs . removeSync ( this . projDir + 'server/.gitkeep' ) ; puts ( '    Created: .jshintrc' ) ; puts ( '    Created: .jshintignore' ) ; puts ( '    Created: makefile' ) ; }


Input: Private : Removes the original foo . html foo . js and foo . css files that Meteor creates after a meteor create foo command [CODESPLIT] function ( ) { fs . removeSync ( this . projDir + this . projectName + '.js' ) ; fs . removeSync ( this . projDir + this . projectName + '.html' ) ; fs . removeSync ( this . projDir + this . projectName + '.css' ) ; puts ( '    Removed: original boilerplate' ) ; }


Input: Private : Look at packages file and remove package if present . Stream packages file replace then overwrite original file . packageName - The { String } name of the package [CODESPLIT] function ( packageName ) { var oldPackages , newPackages ; oldPackages = fs . readFileSync ( this . packages , { encoding : 'utf-8' } ) ; newPackages = oldPackages . replace ( packageName + '\n' , '' ) ; fs . writeFileSync ( this . packages , newPackages ) ; }


Input: Public : Copy routes . js from templates folder into users both / folder . If file already exists it will not be overwritten . [CODESPLIT] function ( projPath ) { // handle calling create outside of project and inside var rootPath = ( projPath ) ? projPath : './' ; // create both folder if it doesn't already exisit fs . mkdirsSync ( rootPath ) ; // bail if router already exists if ( fs . existsSync ( rootPath + 'both/routes.js' ) ) return ; // copy router.js from templates/ to project/both/controllers fs . copySync ( this . routeSrc , rootPath + 'both/routes.js' ) ; console . log ( '    Created: both/routes.js' ) ; }


Input: Public : Append the correct route into routes . js . The routes file is examined for the end - routes marker and it is removed . The new route is inserted onto the end of the file and the marker is re - appended . resName - The { String } name of the controller action eg index show [CODESPLIT] function ( resName , action ) { var route , newContent , oldFileStr , newFileStr , res ; resName = resName || '' ; res = require ( './parse_name' ) ( resName ) // set correct route for the required action // TODO Pascal case namespaces, camelcase routes switch ( action ) { case 'index' : route = "  this.route('" + res . camelPlural + "',     { path: '/" + resName + "',          controller: " + res . pascalPlural + "Controller.Index });" ; break ; case 'new' : route = "  this.route('" + res . camelPlural + "New',  { path: '/" + resName + "/new',      controller: " + res . pascalPlural + "Controller.New });" ; break ; case 'show' : route = "  this.route('" + res . camelPlural + "Show', { path: '/" + resName + "/:id',      controller: " + res . pascalPlural + "Controller.Show });" ; break ; case 'edit' : route = "  this.route('" + res . camelPlural + "Edit', { path: '/" + resName + "/edit/:id', controller: " + res . pascalPlural + "Controller.Edit });" ; break ; case 'comment_line' : route = "  // " + resName + " routes" ; break ; case 'blank_line' : route = "" ; break ; default : route = "  this.route('UNKNOWN', { path: '/', controller: UNKNOWN.index });" ; break ; } // read routes.js from users folder and save to string // concat new route together oldFileStr = fs . readFileSync ( this . routeDest , { encoding : 'utf-8' } ) ; newContent = route + "\n" + this . terminateRoute ; // insert new content into current routes.js string // write new content to file `routes/controllers/resource_name.js` newFileStr = oldFileStr . replace ( this . beforeEndOfRouter , newContent ) ; fs . writeFileSync ( this . routeDest , newFileStr ) ; }


Input: Public : Creates a controller file & appends any type of controller needed . If no options are passed in it will create all router and CRUD controllers resName - The { String } name of the resource passed in from command line opts - The options generated from a Commander command entry . [CODESPLIT] function ( resName , opts ) { // TODO ensure resName is always snake case this . contrFile = this . controllerPath + resName + '.js' ; this . resName = resName ; this . opts = opts ; // if no args passed in, created all routes if ( ! opts . index && ! opts . new && ! opts . show && ! opts . edit && ! opts . create && ! opts . update && ! opts . destroy ) { this . opts . all = true ; } this . _createBaseController ( ) ; // add a comment line before adding new routes require ( './router' ) . appendRoute ( resName , 'comment_line' ) ; // print 'created' if file doesn't exist yet (created on first append) if ( ! fs . existsSync ( this . contrFile ) ) { console . log ( '    Created: ' + this . contrFile ) ; } // Append Iron Router Controllers if ( opts . index || opts . all ) { this . _appendController ( 'index' ) ; require ( './page' ) . run ( this . resName , { index : true } ) ; } if ( opts . new || opts . all ) { this . _appendController ( 'new' ) ; require ( './page' ) . run ( resName , { 'new' : true } ) ; } if ( opts . show || opts . all ) { this . _appendController ( 'show' ) ; require ( './page' ) . run ( resName , { show : true } ) ; } if ( opts . edit || opts . all ) { this . _appendController ( 'edit' ) ; require ( './page' ) . run ( resName , { edit : true } ) ; } // Append data Controllers if ( opts . create || opts . all ) { this . _appendController ( 'create' ) ; } if ( opts . update || opts . all ) { this . _appendController ( 'update' ) ; } if ( opts . destroy || opts . all ) { this . _appendController ( 'destroy' ) ; } // add blank line to routes.js after controller routes require ( './router' ) . appendRoute ( null , 'blank_line' ) ; // instantiate and add namespace for this resource if needed new ( require ( './namespace' ) ) ( ) . add ( resName ) ; }


Input: Private : Streams controller template from templates folder renames any template variables with lib / rename . js and appends the new processed template into user s controller folder both / controller / posts . js . If this file does not exist it will be created . A route is appended to routes . js . action - The { String } name of the controller action eg index show [CODESPLIT] function ( action ) { var templateStr = fs . readFileSync ( this . contrTemplates + action + '.js' , { encoding : 'utf-8' } ) ; // rename template variables and append to controller file templateStr = require ( './rename' ) ( this . resName , templateStr ) ; fs . appendFileSync ( this . contrFile , templateStr ) ; // add a route for new controller if ( action !== 'create' && action !== 'update' && action !== 'destroy' ) { require ( './router' ) . appendRoute ( this . resName , action ) ; console . log ( '    Added Route: ' + this . resName + " " + action ) ; } }


Input: Private : Copy base app controller from templates dir to user project folder both / controllers / app . js Will not overwrite existing file . [CODESPLIT] function ( ) { if ( fs . existsSync ( this . controllerPath + '_app.js' ) ) return ; fs . copySync ( this . contrTemplates + '_app.js' , this . controllerPath + '_app.js' ) ; console . log ( '    Created: ' + this . controllerPath + '_app.js' ) ; }


Input: Instantiates a Vec4 object . [CODESPLIT] function Vec4 ( ) { switch ( arguments . length ) { case 1 : // array or VecN argument var argument = arguments [ 0 ] ; this . x = argument . x || argument [ 0 ] || 0.0 ; this . y = argument . y || argument [ 1 ] || 0.0 ; this . z = argument . z || argument [ 2 ] || 0.0 ; this . w = argument . w || argument [ 3 ] || 0.0 ; break ; case 4 : // individual component arguments this . x = arguments [ 0 ] ; this . y = arguments [ 1 ] ; this . z = arguments [ 2 ] ; this . w = arguments [ 3 ] || 0.0 ; break ; default : this . x = 0.0 ; this . y = 0.0 ; this . z = 0.0 ; this . w = 0.0 ; break ; } }


Input: Create a new EConstructor with the formatted format as a first argument . [CODESPLIT] function create ( EConstructor ) { FormattedError . displayName = EConstructor . displayName || EConstructor . name return FormattedError function FormattedError ( format ) { if ( format ) { format = formatter . apply ( null , arguments ) } return new EConstructor ( format ) } }


Input: Instantiates a Mat44 object . [CODESPLIT] function Mat44 ( that ) { that = that || [ 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 1 ] ; if ( that instanceof Array ) { this . data = that ; } else { this . data = new Array ( 16 ) ; this . data [ 0 ] = that . data [ 0 ] ; this . data [ 1 ] = that . data [ 1 ] ; this . data [ 2 ] = that . data [ 2 ] ; this . data [ 3 ] = that . data [ 3 ] ; this . data [ 4 ] = that . data [ 4 ] ; this . data [ 5 ] = that . data [ 5 ] ; this . data [ 6 ] = that . data [ 6 ] ; this . data [ 7 ] = that . data [ 7 ] ; this . data [ 8 ] = that . data [ 8 ] ; this . data [ 9 ] = that . data [ 9 ] ; this . data [ 10 ] = that . data [ 10 ] ; this . data [ 11 ] = that . data [ 11 ] ; this . data [ 12 ] = that . data [ 12 ] ; this . data [ 13 ] = that . data [ 13 ] ; this . data [ 14 ] = that . data [ 14 ] ; this . data [ 15 ] = that . data [ 15 ] ; } }


Input: Creates a Discovery object . The options object is optional . Supported options are : - port - Set the port the service listens on for announcements default : 44201 - bindAddr - bind to an address - dgramType - Either udp4 or udp6 default : udp4 . - timeOutInt - duration of time between timeout checks in ms . Default 1000 . [CODESPLIT] function Discovery ( options ) { var self = this ; if ( options && ! is . obj ( options ) ) debug ( 'Dicovery constructor bad options argument: ' + inspect ( options ) ) ; // Create a dgram socket and bind it self . dgramType = ( options && options . dgramType ) ? options . dgramType . toLowerCase ( ) : DEFAULT_DGRAM_TYPE ; self . reuseaddr = ( options && options . reuseaddr ) ? options . reuseaddr : DEFAULT_REUSE_ADDR ; self . socket = dgram . createSocket ( { type : self . dgramType , reuseAddr : self . reuseaddr } ) ; self . port = ( options && options . port ) ? options . port : DEFAULT_UDP_PORT ; self . bindAddr = ( options && options . bindAddr ) ? options . bindAddr : undefined ; self . socket . bind ( self . port , self . bindAddr ) ; // create an interval task to check for announcements that have timed out self . timeOutInt = ( options && options . timeOutInt ) ? options . timeOutInt : DEFAULT_TIMEOUT ; self . timeOutId = setInterval ( function ( ) { self . handleTimeOut ( ) ; } , self . timeOutInt ) ; // listen and listen for multicast packets self . socket . on ( 'listening' , function ( ) { self . socket . addMembership ( MULTICAST_ADDRESS ) ; } ) ; // handle any announcements, here we just do the formatting self . socket . on ( 'message' , function ( message , rinfo ) { if ( message ) { var obj = objToJson . jsonParse ( message . toString ( ) ) ; if ( ! obj ) { debug ( 'bad announcement: ' + message . toString ( ) ) ; return ; } // the received message was either an event or an announcement if ( obj . eventName ) self . emit ( GLOBAL_EVENT_NAME , obj . eventName , obj . data ) ; else self . handleAnnouncement ( obj , rinfo ) ; } } ) ; }


Input: 编译 [CODESPLIT] function plugin ( options , callback ) { options = options || { } ; return function ( style ) { if ( options . resolveUrl !== false ) { style . define ( 'url' , stylus . resolver ( ) ) ; } style . use ( rider ( { implicit : options . implicit } ) ) ; style . on ( 'end' , postprocessor ( options , callback ) ) ; if ( options . husl ) { // define husl & huslp style . define ( 'husl' , function ( H , S , L , A ) { var rgb = husl . _rgbPrepare ( husl . _conv . husl . rgb ( [ H . val , S . val , L . val ] ) ) ; var a = ( A !== undefined ? A . val : 1 ) ; return new stylus . nodes . RGBA ( rgb [ 0 ] , rgb [ 1 ] , rgb [ 2 ] , a ) ; } ) ; style . define ( 'huslp' , function ( H , S , L , A ) { var rgb = husl . _rgbPrepare ( husl . _conv . huslp . rgb ( [ H . val , S . val , L . val ] ) ) ; var a = ( A !== undefined ? A . val : 1 ) ; return new stylus . nodes . RGBA ( rgb [ 0 ] , rgb [ 1 ] , rgb [ 2 ] , a ) ; } ) ; } if ( options . use ) { style . use ( options . use ) ; } } ; }


Input: Instantiates a Vec2 object . [CODESPLIT] function Vec2 ( ) { switch ( arguments . length ) { case 1 : // array or VecN argument var argument = arguments [ 0 ] ; this . x = argument . x || argument [ 0 ] || 0.0 ; this . y = argument . y || argument [ 1 ] || 0.0 ; break ; case 2 : // individual component arguments this . x = arguments [ 0 ] ; this . y = arguments [ 1 ] ; break ; default : this . x = 0 ; this . y = 0 ; break ; } }


Input: Instantiates a Quaternion object . [CODESPLIT] function Quaternion ( ) { switch ( arguments . length ) { case 1 : // array or Quaternion argument var argument = arguments [ 0 ] ; if ( argument . w !== undefined ) { this . w = argument . w ; } else if ( argument [ 0 ] !== undefined ) { this . w = argument [ 0 ] ; } else { this . w = 1.0 ; } this . x = argument . x || argument [ 1 ] || 0.0 ; this . y = argument . y || argument [ 2 ] || 0.0 ; this . z = argument . z || argument [ 3 ] || 0.0 ; break ; case 4 : // individual component arguments this . w = arguments [ 0 ] ; this . x = arguments [ 1 ] ; this . y = arguments [ 2 ] ; this . z = arguments [ 3 ] ; break ; default : this . w = 1 ; this . x = 0 ; this . y = 0 ; this . z = 0 ; break ; } }


Input: / * Wrapper around Node which adds the current node ( and parent if available ) to the message . [CODESPLIT] function wrap ( fn ) { return wrapped function wrapped ( node , parent ) { try { fn ( node , parent ) } catch ( error ) { if ( ! error [ ID ] ) { error [ ID ] = true error . message += ': `' + view ( node ) + '`' if ( parent ) { error . message += ' in `' + view ( parent ) + '`' } } throw error } } }


Input: / * Assert . [CODESPLIT] function unist ( node ) { var type var children var value var key var index var length assert . ok ( object ( node ) , 'node should be an object' ) type = node . type children = node . children value = node . value assert . ok ( 'type' in node , 'node should have a type' ) assert . strictEqual ( typeof type , 'string' , '`type` should be a string' ) assert . notStrictEqual ( type , '' , '`type` should not be empty' ) if ( value != null ) { assert . strictEqual ( typeof value , 'string' , '`value` should be a string' ) } location ( node . position ) for ( key in node ) { if ( defined . indexOf ( key ) === - 1 ) { vanilla ( key , node [ key ] ) } } if ( children != null ) { assert . ok ( array ( children ) , '`children` should be an array' ) index = - 1 length = children . length while ( ++ index < length ) { exports ( children [ index ] , node ) } } }


Input: / * Assert value ( which lives at key ) can be stringified and re - parsed to the same ( deep ) value . [CODESPLIT] function vanilla ( key , value ) { try { assert . deepStrictEqual ( value , JSON . parse ( JSON . stringify ( value ) ) ) } catch ( error ) { assert . fail ( 'non-specced property `' + key + '` should be JSON' ) } }


Input: / * Stringify a value to inspect it . Tries JSON . stringify () and if that fails uses String () instead . If stringify () works . [CODESPLIT] function view ( value ) { try { /* eslint-disable no-else-return */ /* istanbul ignore else - Browser. */ if ( inspect ) { return inspect ( value , { colors : false } ) } else { return JSON . stringify ( value ) } } catch ( error ) { /* istanbul ignore next - Cyclical. */ return String ( value ) } }


Input: / * Assert node is a parent node . [CODESPLIT] function parent ( node ) { unist ( node ) assert . strictEqual ( 'value' in node , false , 'parent should not have `value`' ) assert . ok ( 'children' in node , 'parent should have `children`' ) }


Input: / * Assert node is a text node . [CODESPLIT] function text ( node ) { unist ( node ) assert . strictEqual ( 'children' in node , false , 'text should not have `children`' ) assert . ok ( 'value' in node , 'text should have `value`' ) }


Input: / * Assert node is a Unist node but neither parent nor text . [CODESPLIT] function empty ( node ) { unist ( node ) assert . strictEqual ( 'value' in node , false , 'void should not have `value`' ) assert . strictEqual ( 'children' in node , false , 'void should not have `children`' ) }


Input: / * Assert location is a Unist Location . [CODESPLIT] function location ( location ) { if ( location != null ) { assert . ok ( object ( location ) , '`position` should be an object' ) position ( location . start , 'position.start' ) position ( location . end , 'position.end' ) } }


Input: / * Assert location is a Unist Location . [CODESPLIT] function position ( position , name ) { if ( position != null ) { assert . ok ( object ( position ) , '`' + name + '` should be an object' ) if ( position . line != null ) { assert . ok ( 'line' in position , '`' + name + '` should have numeric `line`' ) assert . ok ( position . line >= 1 , '`' + name + '.line` should be gte `1`' ) } if ( position . column != null ) { assert . ok ( 'column' in position , '`' + name + '` should have numeric `column`' ) assert . ok ( position . column >= 1 , '`' + name + '.column` should be gte `1`' ) } } }


Input: Instantiates a Vec3 object . [CODESPLIT] function Vec3 ( ) { switch ( arguments . length ) { case 1 : // array or VecN argument var argument = arguments [ 0 ] ; this . x = argument . x || argument [ 0 ] || 0.0 ; this . y = argument . y || argument [ 1 ] || 0.0 ; this . z = argument . z || argument [ 2 ] || 0.0 ; break ; case 3 : // individual component arguments this . x = arguments [ 0 ] ; this . y = arguments [ 1 ] ; this . z = arguments [ 2 ] ; break ; default : this . x = 0.0 ; this . y = 0.0 ; this . z = 0.0 ; break ; } }


Input: Constructor [CODESPLIT] function Snackbar ( data , options , callback ) { if ( data !== "" ) { this . options = this . activateOptions ( options ) ; this . data = data ; this . callback = callback ; this . start ( ) ; this . snackbar ( ) ; } else { console . warn ( "SnackbarLight: You can not create a empty snackbar please give it a string." ) ; } }


Input: Create container for the snackbar [CODESPLIT] function ( ) { if ( ! document . getElementById ( "snackbar-container" ) ) { var snackbarContainer = document . createElement ( "div" ) ; snackbarContainer . setAttribute ( "id" , "snackbar-container" ) ; document . body . appendChild ( snackbarContainer ) ; } }


Input: Timer [CODESPLIT] function ( callback , delay ) { var remaining = delay ; this . timer = { // Create random timer id timerId : Math . round ( Math . random ( ) * 1000 ) , pause : function ( ) { // Clear the timeout window . clearTimeout ( this . timerId ) ; // Set the remaining to what time remains remaining -= new Date ( ) - start ; } , resume : function ( ) { start = new Date ( ) ; // Clear the timeout window . clearTimeout ( this . timerId ) ; // Set the timeout again this . timerId = window . setTimeout ( callback , remaining ) ; } , } ; // Start the timer this . timer . resume ( ) ; }


Input: snackbar [CODESPLIT] function ( ) { var __self = this , snackbar = document . createElement ( "div" ) ; // Put the snackbar inside the snackbar container document . getElementById ( "snackbar-container" ) . appendChild ( snackbar ) ; // Set the html inside the snackbar snackbar . innerHTML = this . getData ( ) ; // Set the class of the snackbar snackbar . setAttribute ( "class" , "snackbar" ) ; // Wait to set the active class so animations will be activated setTimeout ( function ( ) { snackbar . setAttribute ( "class" , "snackbar " + __self . options . activeClass ) ; } , 50 ) ; // If the timeout is false the snackbar will not be destroyed after some time // only when the user clicks on it if ( this . options . timeout !== false ) { // Start the timer this . timer ( function ( ) { snackbar . setAttribute ( "class" , "snackbar" ) ; __self . destroy ( snackbar ) ; } , this . options . timeout ) ; } // Add the event listeners this . listeners ( snackbar ) ; }


Input: Activate the listeners [CODESPLIT] function ( element ) { var __self = this ; // Adding event listener for when user clicks on the snackbar to remove it element . addEventListener ( "click" , function ( ) { if ( typeof __self . callback == "function" ) { __self . callback ( ) ; } element . setAttribute ( "class" , "snackbar" ) ; __self . destroy ( element ) ; } ) ; // Stopping the timer when user hovers on the snackbar element . addEventListener ( "mouseenter" , function ( ) { __self . timer . pause ( ) ; } ) ; element . addEventListener ( "mouseout" , function ( ) { __self . timer . resume ( ) ; } ) ; }


Input: Compare the options to the default ones . [CODESPLIT] function ( newOptions ) { var __self = this , options = newOptions || { } ; for ( var opt in this . options ) { if ( __self . options . hasOwnProperty ( opt ) && ! options . hasOwnProperty ( opt ) ) { options [ opt ] = __self . options [ opt ] ; } } return options ; }


Input: Install function for Vue [CODESPLIT] function ( Vue ) { var __self = this ; Vue . prototype . $snackbar = { } ; Vue . prototype . $snackbar . create = function ( data , options , callback ) { __self . create ( data , options , callback ) ; } ; }


Input: / * Converts a private key to WIF format [CODESPLIT] function privKeyToWIF ( privKey ) { var toCompressed = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : false ; var wif = arguments . length > 2 && arguments [ 2 ] !== undefined ? arguments [ 2 ] : zconfig . mainnet . wif ; if ( toCompressed ) privKey = privKey + '01' ; return bs58check . encode ( Buffer . from ( wif + privKey , 'hex' ) ) ; }


Input: / * Returns private key s public Key [CODESPLIT] function privKeyToPubKey ( privKey ) { var toCompressed = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : false ; var pkBuffer = Buffer . from ( privKey , 'hex' ) ; var publicKey = secp256k1 . publicKeyCreate ( pkBuffer , toCompressed ) ; return publicKey . toString ( 'hex' ) ; }


Input: / * Given a WIF format pk convert it back to the original pk [CODESPLIT] function WIFToPrivKey ( wifPk ) { var og = bs58check . decode ( wifPk , 'hex' ) . toString ( 'hex' ) ; og = og . substr ( 2 , og . length ) ; // remove WIF format ('80') // remove the '01' at the end to 'compress it' during WIF conversion if ( og . length > 64 ) { og = og . substr ( 0 , 64 ) ; } return og ; }


Input: / * Given a list of public keys create a M - of - N redeemscript [CODESPLIT] function mkMultiSigRedeemScript ( pubKeys , M , N ) { // https://github.com/ZencashOfficial/zen/blob/b7a7c4c4199f5e9f49868631fe5f2f6de6ba4f9a/src/script/standard.cpp#L411 if ( M > N && M <= 1 ) throw new Error ( 'Invalid Multi Sig Type' ) ; var OP_1 = Buffer . from ( zopcodes . OP_1 , 'hex' ) ; var OP_START = ( OP_1 . readInt8 ( 0 ) + ( M - 1 ) ) . toString ( 16 ) ; var OP_END = ( OP_1 . readInt8 ( 0 ) + ( N - 1 ) ) . toString ( 16 ) ; return OP_START + pubKeys . map ( function ( x ) { return zbufferutils . getPushDataLength ( x ) + x ; } ) . join ( '' ) + OP_END + zopcodes . OP_CHECKMULTISIG ; }


Input: / * Reference : http : // www . soroushjp . com / 2014 / 12 / 20 / bitcoin - multisig - the - hard - way - understanding - raw - multisignature - bitcoin - transactions / Given the multi sig redeem script return the corresponding address [CODESPLIT] function multiSigRSToAddress ( redeemScript ) { var scriptHash = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : zconfig . mainnet . scriptHash ; // Protocol: RIPEMD160(SHA256(script)) var s256 = zcrypto . sha256 ( Buffer . from ( redeemScript , 'hex' ) ) ; var r160 = zcrypto . ripemd160 ( Buffer . from ( s256 , 'hex' ) ) ; return bs58check . encode ( Buffer . from ( scriptHash + r160 , 'hex' ) ) ; }


Input: Instantiates a Transform object . [CODESPLIT] function Transform ( that ) { that = that || { } ; if ( that . data instanceof Array ) { // Mat33 or Mat44, extract transform components that = that . decompose ( ) ; this . rotation = that . rotation ; this . translation = that . translation || new Vec3 ( ) ; this . scale = that . scale ; } else { // set individual components, by value this . rotation = that . rotation ? new Quaternion ( that . rotation ) : new Quaternion ( ) ; this . translation = that . translation ? new Vec3 ( that . translation ) : new Vec3 ( ) ; if ( typeof that . scale === 'number' ) { this . scale = new Vec3 ( that . scale , that . scale , that . scale ) ; } else { this . scale = that . scale ? new Vec3 ( that . scale ) : new Vec3 ( 1 , 1 , 1 ) ; } } }


Input: 打包组件成js和css文件 [CODESPLIT] function vuePack ( file , encoding , callback ) { if ( ! file ) { throw new PluginError ( 'gulp-vue-pack' , 'file不存在');   } if ( file . isStream ( ) ) { throw new PluginError ( 'gulp-vue-pack' , '只支持.vue文件');   } if ( ! file . contents ) { //非文件,是目录 callback ( ) ; return ; } let fileName = path . basename ( file . path , ".vue" ) ; let fileContent = file . contents . toString ( encoding ) ; let contents = parseVueToContents ( fileContent , fileName , path . dirname ( file . path ) ) ; let fpath = path . dirname ( file . path ) ; this . push ( createFile ( file . base , file . cwd , fpath , fileName + ".js" , contents . js ) ) ; //如果css文件无内容，则不生成css文件 if ( contents . css . length > 0 ) { this . push ( createFile ( file . base , file . cwd , fpath , fileName + ".css" , contents . css ) ) ; } callback ( ) ; }


Input: 将vue文件中的内容，进行转换，生成多页引用的vue [CODESPLIT] function convertToJSContent ( script , template , style , fileName , filePath ) { if ( ! script ) { return "" ; } //兼容 windows filePath = filePath . replace ( / \\ / g , "/" ) ; let jsFileContent = ` ` ; if ( style && style . length > 0 ) { jsFileContent += ` ` + fileName + ` \n ` ; } jsFileContent += processJavascript ( fileName , script , processTemplate ( template ) , style , filePath ) ; jsFileContent += "\n\nglobal." + fileName + " = " + fileName + ";\n\n" ; //伪造ES6格式的VUE组件 jsFileContent += "global.__FORGE_ES6_VUE_COMPONENTS__['" + filePath + "/" + fileName + ".vue']=" + fileName + ";\n" ; jsFileContent += "Vue.component('vue" + fileName . replace ( / ([A-Z]) / g , "-$1" ) . toLowerCase ( ) + "', " + fileName + ");\n\n" ; jsFileContent += "\n}(window, Vue));" ; return jsFileContent ; }


Input: 处理js 将es6写的带export的部分转换成普通的组件定义 [CODESPLIT] function processJavascript ( fileName , script , processedTemplate , style , filePath ) { script = script . replace ( VUE_COMPONENT_IMPORT_REG , function ( matchedLine , variableName , vuePath , index , contents ) { return "var " + variableName + " = global.__FORGE_ES6_VUE_COMPONENTS__['" + path . resolve ( filePath , vuePath ) . replace ( / \\ / g , "/" ) + "']" ; } ) ; script = script . replace ( SCRIPT_REPLACER_REG , "var " + fileName + " = Vue.extend(" ) ; script += ");\n" ; script += fileName + ".options.template = " + processedTemplate ; // script = script.replace(/__gvptemplate/m, processedTemplate); return script ; }


Input: Instantiates a Triangle object . [CODESPLIT] function Triangle ( ) { switch ( arguments . length ) { case 1 : // array or object argument var arg = arguments [ 0 ] ; this . a = new Vec3 ( arg [ 0 ] || arg . a ) ; this . b = new Vec3 ( arg [ 1 ] || arg . b ) ; this . c = new Vec3 ( arg [ 2 ] || arg . c ) ; break ; case 3 : // individual vector arguments this . a = new Vec3 ( arguments [ 0 ] ) ; this . b = new Vec3 ( arguments [ 1 ] ) ; this . c = new Vec3 ( arguments [ 2 ] ) ; break ; default : this . a = new Vec3 ( 0 , 0 , 0 ) ; this . b = new Vec3 ( 1 , 0 , 0 ) ; this . c = new Vec3 ( 1 , 1 , 0 ) ; break ; } }


Input: / * More info : https : // github . com / ZencashOfficial / zen / blob / master / src / script / standard . cpp#L377 Given an address generates a pubkeyhash replay type script needed for the transaction [CODESPLIT] function mkPubkeyHashReplayScript ( address , blockHeight , blockHash ) { var pubKeyHash = arguments . length > 3 && arguments [ 3 ] !== undefined ? arguments [ 3 ] : zconfig . mainnet . pubKeyHash ; // Get lengh of pubKeyHash (so we know where to substr later on) var addrHex = bs58check . decode ( address ) . toString ( 'hex' ) ; // Cut out pubKeyHash var subAddrHex = addrHex . substring ( pubKeyHash . length , addrHex . length ) ; // Minimal encoding var blockHeightBuffer = Buffer . alloc ( 4 ) ; blockHeightBuffer . writeUInt32LE ( blockHeight , 0 ) ; if ( blockHeightBuffer [ 3 ] === 0x00 ) { blockHeightBuffer = blockHeightBuffer . slice ( 0 , 3 ) ; } var blockHeightHex = blockHeightBuffer . toString ( 'hex' ) ; // block hash is encoded in little indian var blockHashHex = Buffer . from ( blockHash , 'hex' ) . reverse ( ) . toString ( 'hex' ) ; // '14' is the length of the subAddrHex (in bytes) return zopcodes . OP_DUP + zopcodes . OP_HASH160 + zbufferutils . getPushDataLength ( subAddrHex ) + subAddrHex + zopcodes . OP_EQUALVERIFY + zopcodes . OP_CHECKSIG + zbufferutils . getPushDataLength ( blockHashHex ) + blockHashHex + zbufferutils . getPushDataLength ( blockHeightHex ) + blockHeightHex + zopcodes . OP_CHECKBLOCKATHEIGHT ; }


Input: / * Given an address generates a script hash replay type script needed for the transaction [CODESPLIT] function mkScriptHashReplayScript ( address , blockHeight , blockHash ) { var addrHex = bs58check . decode ( address ) . toString ( 'hex' ) ; var subAddrHex = addrHex . substring ( 4 , addrHex . length ) ; // Cut out the '00' (we also only want 14 bytes instead of 16) var blockHeightBuffer = Buffer . alloc ( 4 ) ; blockHeightBuffer . writeUInt32LE ( blockHeight , 0 ) ; if ( blockHeightBuffer [ 3 ] === 0x00 ) { blockHeightBuffer = blockHeightBuffer . slice ( 0 , 3 ) ; } var blockHeightHex = blockHeightBuffer . toString ( 'hex' ) ; // Need to reverse it var blockHashHex = Buffer . from ( blockHash , 'hex' ) . reverse ( ) . toString ( 'hex' ) ; return zopcodes . OP_HASH160 + zbufferutils . getPushDataLength ( subAddrHex ) + subAddrHex + zopcodes . OP_EQUAL + zbufferutils . getPushDataLength ( blockHashHex ) + blockHashHex + zbufferutils . getPushDataLength ( blockHeightHex ) + blockHeightHex + zopcodes . OP_CHECKBLOCKATHEIGHT ; }


Input: / * Given an address generates an output script [CODESPLIT] function addressToScript ( address , blockHeight , blockHash ) { // P2SH replay starts with a 's', or 'r' if ( address [ 1 ] === 's' || address [ 1 ] === 'r' ) { return mkScriptHashReplayScript ( address , blockHeight , blockHash ) ; } // P2PKH-replay is a replacement for P2PKH return mkPubkeyHashReplayScript ( address , blockHeight , blockHash ) ; }


Input: / * Serializes a TXOBJ into hex string [CODESPLIT] function serializeTx ( txObj ) { var serializedTx = '' ; var _buf16 = Buffer . alloc ( 4 ) ; // Version _buf16 . writeUInt16LE ( txObj . version , 0 ) ; serializedTx += _buf16 . toString ( 'hex' ) ; // History serializedTx += zbufferutils . numToVarInt ( txObj . ins . length ) ; txObj . ins . map ( function ( i ) { // Txids and vouts _buf16 . writeUInt16LE ( i . output . vout , 0 ) ; serializedTx += Buffer . from ( i . output . hash , 'hex' ) . reverse ( ) . toString ( 'hex' ) ; serializedTx += _buf16 . toString ( 'hex' ) ; // Script Signature // Doesn't work for length > 253 .... serializedTx += zbufferutils . getPushDataLength ( i . script ) ; serializedTx += i . script ; // Sequence serializedTx += i . sequence ; } ) ; // Outputs serializedTx += zbufferutils . numToVarInt ( txObj . outs . length ) ; txObj . outs . map ( function ( o ) { // Write 64bit buffers // JS only supports 56 bit // https://github.com/bitcoinjs/bitcoinjs-lib/blob/master/src/bufferutils.js#L25 var _buf32 = Buffer . alloc ( 8 ) ; // Satohis _buf32 . writeInt32LE ( o . satoshis & - 1 , 0 ) ; _buf32 . writeUInt32LE ( Math . floor ( o . satoshis / 0x100000000 ) , 4 ) ; // ScriptPubKey serializedTx += _buf32 . toString ( 'hex' ) ; serializedTx += zbufferutils . getPushDataLength ( o . script ) ; serializedTx += o . script ; } ) ; // Locktime _buf16 . writeUInt16LE ( txObj . locktime , 0 ) ; serializedTx += _buf16 . toString ( 'hex' ) ; return serializedTx ; }


Input: / * Creates a raw transaction [CODESPLIT] function createRawTx ( history , recipients , blockHeight , blockHash ) { var txObj = { locktime : 0 , version : 1 , ins : [ ] , outs : [ ] } ; txObj . ins = history . map ( function ( h ) { return { output : { hash : h . txid , vout : h . vout } , script : '' , prevScriptPubKey : h . scriptPubKey , sequence : 'ffffffff' } ; } ) ; txObj . outs = recipients . map ( function ( o ) { return { script : addressToScript ( o . address , blockHeight , blockHash ) , satoshis : o . satoshis } ; } ) ; return txObj ; }


Input: / * Gets signature for the vin script [CODESPLIT] function getScriptSignature ( privKey , signingTx , hashcode ) { // Buffer var _buf16 = Buffer . alloc ( 4 ) ; _buf16 . writeUInt16LE ( hashcode , 0 ) ; var signingTxHex = serializeTx ( signingTx ) ; var signingTxWithHashcode = signingTxHex + _buf16 . toString ( 'hex' ) ; // Sha256 it twice, according to spec var msg = zcrypto . sha256x2 ( Buffer . from ( signingTxWithHashcode , 'hex' ) ) ; // Signing it var rawsig = secp256k1 . sign ( Buffer . from ( msg , 'hex' ) , Buffer . from ( privKey , 'hex' ) , { canonical : true } ) ; // Convert it to DER format // Appending 01 to it cause // ScriptSig = <varint of total sig length> <SIG from code, including appended 01 SIGNHASH> <length of pubkey (0x21 or 0x41)> <pubkey> // https://bitcoin.stackexchange.com/a/36481 var signatureDER = Buffer . from ( rawsig . toDER ( ) ) . toString ( 'hex' ) + '01' ; return signatureDER ; }


Input: / * Signs the raw transaction [CODESPLIT] function signTx ( _txObj , i , privKey ) { var compressPubKey = arguments . length > 3 && arguments [ 3 ] !== undefined ? arguments [ 3 ] : false ; var hashcode = arguments . length > 4 && arguments [ 4 ] !== undefined ? arguments [ 4 ] : zconstants . SIGHASH_ALL ; // Make a copy var txObj = JSON . parse ( JSON . stringify ( _txObj ) ) ; // Prepare our signature // Get script from the current tx input var script = txObj . ins [ i ] . prevScriptPubKey ; // Populate current tx in with the prevScriptPubKey var signingTx = signatureForm ( txObj , i , script , hashcode ) ; // Get script signature var scriptSig = getScriptSignature ( privKey , signingTx , hashcode ) ; // Chuck it back into txObj and add pubkey // Protocol: // PUSHDATA // signature data and SIGHASH_ALL // PUSHDATA // public key data var pubKey = zaddress . privKeyToPubKey ( privKey , compressPubKey ) ; txObj . ins [ i ] . script = zbufferutils . getPushDataLength ( scriptSig ) + scriptSig + zbufferutils . getPushDataLength ( pubKey ) + pubKey ; return txObj ; }


Input: / * Gets signatures needed for multi - sign tx [CODESPLIT] function multiSign ( _txObj , i , privKey , redeemScript ) { var hashcode = arguments . length > 4 && arguments [ 4 ] !== undefined ? arguments [ 4 ] : zconstants . SIGHASH_ALL ; // Make a copy var txObj = JSON . parse ( JSON . stringify ( _txObj ) ) ; // Populate current tx.ins[i] with the redeemScript var signingTx = signatureForm ( txObj , i , redeemScript , hashcode ) ; return getScriptSignature ( privKey , signingTx , hashcode ) ; }


Input: / * Applies the signatures to the transaction object NOTE : You NEED to supply the signatures in order . E . g . You made sigAddr1 with priv1 priv3 priv2 You can provide signatures of ( priv1 priv2 ) ( priv3 priv2 ) ... But not ( priv2 priv1 ) [CODESPLIT] function applyMultiSignatures ( _txObj , i , signatures , redeemScript ) { // Make a copy var txObj = JSON . parse ( JSON . stringify ( _txObj ) ) ; var redeemScriptPushDataLength = zbufferutils . getPushDataLength ( redeemScript ) ; // Lmao no idea, just following the source code if ( redeemScriptPushDataLength . length > 2 ) { if ( redeemScriptPushDataLength . length === 6 ) { redeemScriptPushDataLength = redeemScriptPushDataLength . slice ( 2 , 4 ) ; } } // http://www.soroushjp.com/2014/12/20/bitcoin-multisig-the-hard-way-understanding-raw-multisignature-bitcoin-transactions/ txObj . ins [ i ] . script = zopcodes . OP_0 + signatures . map ( function ( x ) { return zbufferutils . getPushDataLength ( x ) + x ; } ) . join ( '' ) + zopcodes . OP_PUSHDATA1 + redeemScriptPushDataLength + redeemScript ; return txObj ; }


Input: Returns true if str matches the given pattern . [CODESPLIT] function bash ( str , pattern , options ) { if ( typeof str !== 'string' ) { throw new TypeError ( 'expected a string' ) ; } if ( typeof pattern !== 'string' ) { throw new TypeError ( 'expected a string' ) ; } if ( isWindows ( ) ) { throw new Error ( 'bash-match does not work on windows' ) ; } try { var opts = createOptions ( pattern , options ) ; var res = spawn . sync ( getBashPath ( ) , cmd ( str , pattern , opts ) , opts ) ; var err = toString ( res . stderr ) ; if ( err ) { return handleError ( err , opts ) ; } return ! ! toString ( res . stdout ) ; } catch ( err ) { return handleError ( err , opts ) ; } }


Input: Create the command to use [CODESPLIT] function cmd ( str , pattern , options ) { var valid = [ 'dotglob' , 'extglob' , 'failglob' , 'globstar' , 'nocaseglob' , 'nullglob' ] ; var args = [ ] ; for ( var key in options ) { if ( options . hasOwnProperty ( key ) && valid . indexOf ( key ) !== - 1 ) { args . push ( '-O' , key ) ; } } args . push ( '-c' , 'IFS=$"\n"; if [[ "' + str + '" = ' + pattern + ' ]]; then echo true; fi' ) ; return args ; }


Input: Shallow clone and create options [CODESPLIT] function createOptions ( pattern , options ) { if ( options && options . normalized === true ) return options ; var opts = extend ( { cwd : process . cwd ( ) } , options ) ; if ( opts . nocase === true ) opts . nocaseglob = true ; if ( opts . nonull === true ) opts . nullglob = true ; if ( opts . dot === true ) opts . dotglob = true ; if ( ! opts . hasOwnProperty ( 'globstar' ) && pattern . indexOf ( '**' ) !== - 1 ) { opts . globstar = true ; } if ( ! opts . hasOwnProperty ( 'extglob' ) && isExtglob ( pattern ) ) { opts . extglob = true ; } opts . normalized = true ; return opts ; }


Input: Get bash path [CODESPLIT] function getBashPath ( ) { if ( bashPath ) return bashPath ; if ( fs . existsSync ( '/usr/local/bin/bash' ) ) { bashPath = '/usr/local/bin/bash' ; } else if ( fs . existsSync ( '/bin/bash' ) ) { bashPath = '/bin/bash' ; } else { bashPath = 'bash' ; } return bashPath ; }


Input: Returns true if ( left < = p < = right ) . False otherwise . [CODESPLIT] function isBetween ( p , left , right ) { if ( p >= left && p <= right ) return true ; return false ; }


Input: / * Copyright ( c ) 2014 Jan Blaha [CODESPLIT] function ( reporter , definition ) { this . reporter = reporter this . definition = definition this . reporter . beforeRenderListeners . add ( definition . name , this , Statistics . prototype . handleBeforeRender ) this . reporter . afterRenderListeners . add ( definition . name , this , Statistics . prototype . handleAfterRender ) this . _defineEntities ( ) }


Input: / * Converts a Z secret key to a transmission key [CODESPLIT] function zSecretKeyToTransmissionKey ( a_sk ) { var sk_enc = prf . PRF_addr_sk_enc ( Buffer . from ( a_sk , 'hex' ) ) ; // Curve 25519 clamping sk_enc [ 0 ] &= 248 ; sk_enc [ 32 ] &= 127 ; sk_enc [ 31 ] |= 64 ; return Buffer . from ( sodium . crypto_scalarmult_base ( sk_enc ) ) . toString ( 'hex' ) ; }


Input: ----------------------------------- [CODESPLIT] function changeEvent ( event ) { var srcPattern = new RegExp ( '/.*(?=/' + config . source + ')/' ) ; log ( 'File ' + event . path . replace ( srcPattern , '' ) + ' ' + event . type ) ; }


Input: Provides in memory storage and regular flush to disk . [CODESPLIT] function Memory ( options ) { options = options || { } ; var self = this ; self . flush = options . db . _db . _memory . flush || false ; self . flushInterval = options . db . _db . _memory . flushInterval || 10000 ; self . flushFile = options . file ; self . memoryTable = [ ] ; console . log ( 'Data will be handled using \'Memory\' driver' ) ; // :S yeah we need to load it synchronously otherwise it might be loaded after the first insert var content = util . fileSystem . readSync ( self . flushFile ) ; self . set ( content ) ; if ( self . flush ) { console . log ( '\'Memory\' driver will flush data every %sms' , self . flushInterval ) ; // set interval to flush setInterval ( function flushToDisk ( ) { util . fileSystem . lock ( self . flushFile , function afterLock ( err ) { if ( err ) { throw err ; } self . get ( function afterGet ( err , inMemoryContent ) { if ( err ) { util . fileSystem . unlock ( self . flushFile ) ; throw err ; } util . fileSystem . write ( self . flushFile , inMemoryContent , function afterWrite ( err ) { util . fileSystem . unlock ( self . flushFile ) ; if ( err ) { throw err ; } } ) ; } ) ; } ) ; } , self . flushInterval ) ; } }


Input:
START : Module logic start [CODESPLIT] function VarStreamWriter ( callback , options ) { this . lastContext = '' ; this . callback = callback ; // Output stream callback
 this . options = options ; this . imbricatedArrayEntries = new Array ( ) ; this . scopes = new Array ( ) ; this . contexts = new Array ( ) ; this . previousContext = '' ; }


Input: removes the items from craftable if result is picked up [CODESPLIT] function deductcost ( ) { var cost = [ ] ; if ( ! giving . have || giving . have . length < 1 ) return ; // flatten var cost = [ ] ; for ( var i = 0 ; i < giving . have . length ; i ++ ) { for ( var j = 0 ; j < giving . have [ i ] . length ; j ++ ) { cost . push ( giving . have [ i ] [ j ] ) ; } } if ( typeof cost [ 0 ] === 'string' ) cost = [ cost ] ; function deduct ( from , amt ) { var current = parseInt ( from . getAttribute ( 'data-quantity' ) ) ; current -= amt ; from . setAttribute ( 'data-quantity' , current ) ; updateAmounts ( from ) ; if ( current < 1 ) { from . setAttribute ( 'data-type' , 'none' ) ; from . innerHTML = '' ; } } [ ] . forEach . call ( craftable . querySelectorAll ( 'li' ) , function ( li , i ) { var row = Math . floor ( i / 3 ) ; var has = ( li . getAttribute ( 'data-type' ) || 'none' ) . toLowerCase ( ) ; for ( var c = 0 ; c < cost . length ; c ++ ) { if ( cost [ c ] [ 0 ] . toLowerCase ( ) === has ) { var price = cost [ c ] [ 1 ] ; cost . splice ( c , 1 ) ; deduct ( li , price ) ; return false ; } } } ) ; }


Input: Provides the most common I / O operations . [CODESPLIT] function DataHandler ( options ) { options = options || { } ; var dataHandler = options . db . _db . _driver || 'disk' ; switch ( dataHandler ) { // load the driver to be used just once case 'memory' : this . dataHandlerDriver = new Memory ( options ) ; break ; case 'disk' : default : this . dataHandlerDriver = new Disk ( options ) ; } }


Input:
START : Module logic start Constructor [CODESPLIT] function VarStreamReader ( scope , prop , options ) { // Keep a ref to the root scope
 this . rootScope = { root : scope , prop : prop } ; // Save the options
 this . options = options ; // Store current scopes for backward references
 this . previousNodes = [ ] ; // The parse state
 this . state = PARSE_NEWLINE ; // The current values
 this . leftValue = '' ; this . rightValue = '' ; this . operator = '' ; this . escaped = ESC_NONE ; }


Input:
Constructor [CODESPLIT] function VarStream ( rootObject , rootProperty , options ) { var self = this ; // Ensure new were used
 if ( ! ( this instanceof VarStream ) ) { return new VarStream ( rootObject , rootProperty , options ) ; } // Ensure we had root object and property
 if ( ! ( rootObject instanceof Object ) ) { throw new Error ( 'No root object provided.' ) ; } if ( 'string' !== typeof rootProperty || ootProperty  =  ')
 throw new Error ( 'No root property name given.' ) ; } // Parent constructor
 DuplexStream . call ( this ) ; this . _varstreamReader = new VarStreamReader ( rootObject , rootProperty , options ? options & VarStreamReader . OPTIONS : 0 ) ; this . _varstreamWriter = new VarStreamWriter ( function ( str ) { self . push ( new Buffer ( str , 'utf8' ) ) ; } , options ? options & VarStreamWriter . OPTIONS : 0 ) ; // Parse input
 this . _write = function _write ( chunk , encoding , done ) { this . _varstreamReader . read ( chunk . toString ( encoding !== 'buffer' ? encoding : 'utf8' ) ) ; done ( ) ; } ; // Output data
 this . _read = function _read ( ) { this . _varstreamWriter . write ( rootObject [ rootProperty ] ) ; this . push ( null ) ; } ; }


Input: descend a specific node or descend all [CODESPLIT] function ( sub_node ) { if ( sub_node ) { walk ( sub_node , depth + 1 ) ; } else if ( node . pages ) { node . pages . forEach ( function ( sub_node , name ) { walk ( sub_node , depth + 1 ) ; } ) ; } }


Input: / * :: export type NodejsVersion = { version : string ; date : string ; files : string [] ; modules : string ; lts : boolean | string ; } ; [CODESPLIT] function find ( list /* : NodejsVersion[] */ , version /* : string */ ) /* : NodejsVersion */ { for ( let v = 0 , vLength = list . length ; v < vLength ; v += 1 ) { const candidate = list [ v ] if ( candidate . version === version ) { return candidate } } throw new Error ( ` ${ version } ` ) }


Input: Constructor [CODESPLIT] function Duplexer ( options , writableStream , readableStream ) { const _this = this ; // Ensure new were used if ( ! ( this instanceof Duplexer ) ) { return new ( Duplexer . bind . apply ( Duplexer , // eslint-disable-line [ Duplexer ] . concat ( [ ] . slice . call ( arguments , 0 ) ) ) ) ( ) ; } // Mapping args if ( isStream ( options ) ) { readableStream = writableStream ; writableStream = options ; options = { } ; } else { options = options || { } ; } this . _reemitErrors = 'boolean' === typeof options . reemitErrors ? options . reemitErrors : true ; delete options . reemitErrors ; // Checking arguments if ( ! isStream ( writableStream , 'Writable' , 'Duplex' ) ) { throw new Error ( 'The writable stream must be an instanceof Writable or Duplex.' ) ; } if ( ! isStream ( readableStream , 'Readable' ) ) { throw new Error ( 'The readable stream must be an instanceof Readable.' ) ; } // Parent constructor Stream . Duplex . call ( this , options ) ; // Save streams refs this . _writable = writableStream ; this . _readable = readableStream ; // Internal state this . _waitDatas = false ; this . _hasDatas = false ; if ( 'undefined' == typeof this . _readable . _readableState ) { this . _readable = new Stream . Readable ( { objectMode : options . objectMode || false , } ) . wrap ( this . _readable ) ; } if ( this . _reemitErrors ) { this . _writable . on ( 'error' , err => { _this . emit ( 'error' , err ) ; } ) ; this . _readable . on ( 'error' , err => { _this . emit ( 'error' , err ) ; } ) ; } this . _writable . on ( 'drain' , ( ) => { _this . emit ( 'drain' ) ; } ) ; this . once ( 'finish' , ( ) => { _this . _writable . end ( ) ; } ) ; this . _writable . once ( 'finish' , ( ) => { _this . end ( ) ; } ) ; this . _readable . on ( 'readable' , ( ) => { _this . _hasDatas = true ; if ( _this . _waitDatas ) { _this . _pushAll ( ) ; } } ) ; this . _readable . once ( 'end' , ( ) => { _this . push ( null ) ; } ) ; }


Input: Registers dependencies that can be provided to the function [CODESPLIT] function ( provides ) { if ( _ . isArray ( provides ) ) { this . _arguments = this . _provides = ( ! this . _provides ) ? provides : this . _provides . concat ( provides ) ; } else { this . _provides = _ . extend ( { } , this . _provides , provides ) ; this . _arguments = _ . map ( this . deps , function ( key ) { return this . _provides [ key ] ; } , this ) ; } return this ; }


Input: Calls the function [CODESPLIT] function ( context , callback ) { if ( arguments . length === 1 ) { callback = context ; context = this . _context ; } if ( this . isAsync ) { // clone the arguments so this.call can be reused with different callbacks var asyncArgs = this . _arguments . slice ( ) ; // push the callback onto the new arguments array asyncArgs . push ( callback ) ; // call the function this . fn . apply ( context , asyncArgs ) ; } else { // if the function isn't async, allow it to be called with or without a callback if ( callback ) { // If a callback is provided, it must use the error-first arguments pattern. // The return value of the function will be the second argument. try { callback ( null , this . fn . apply ( context , this . _arguments ) ) ; } catch ( e ) { callback ( e ) ; } } else { // If no callback is provided simply return the result of the function return this . fn . apply ( context , this . _arguments ) ; } } }


Input: Applies the function iterator to each item in arr in parallel . [CODESPLIT] function each ( arr , callback ) { var wrapper = this ; if ( this . isAsync ) { return async . each ( arr , function ( item , cb ) { wrapper . call ( item , cb ) ; } , callback ) ; } else { arr . each ( function ( item ) { wrapper . call ( item ) ; } ) ; if ( callback ) { callback ( ) ; } } }


Input: Returns the results of interating the function on each item in an array . [CODESPLIT] function map ( arr , callback ) { var wrapper = this ; if ( this . isAsync ) { async . map ( arr , function ( item , cb ) { wrapper . call ( item , cb ) ; } , callback ) ; } else { callback ( null , arr . map ( function ( item ) { return wrapper . call ( item ) ; } ) ) ; } }


Input: force wrap to true defining events callback [CODESPLIT] function ( selectedDates , dateStr , instance ) { that . setProperty ( "dateValue" , selectedDates , true ) ; that . fireOnChange ( { selectedDates : selectedDates , dateStr : dateStr , instance : instance } ) ; }


Input: ////////////////////////////////////////////////// EVENTS HANDLING ////////////////////////////////////////////////// [CODESPLIT] function ( selectedDates , dateStr , instance ) { this . fireOnChange ( { selectedDates : selectedDates , dateStr : dateStr , instance : instance } ) ; }


Input: XOR128 pseudo - random number generator . This is based off of algorithm found on the XORSHIFT wiki here : http : // en . wikipedia . org / wiki / Xorshift . Also the code ensures all numbers are handled as unsigned 32bit integers and is consistent with the C ++ example provided xor128 . cpp [CODESPLIT] function XOR128 ( x , y , z , w ) { if ( ( x && x < 1 ) || ( y && y < 1 ) || ( z && z < 1 ) || ( w && w < 1 ) ) { throw new Error ( 'Invalid Seed' ) ; } this . x = x ? x : Math . random ( ) * 4294967296 ; this . y = y ? y : Math . random ( ) * 4294967296 ; this . z = z ? z : Math . random ( ) * 4294967296 ; this . w = w ? w : Math . random ( ) * 4294967296 ; }


Input: init options [CODESPLIT] function initOptions ( options ) { var defaultOptions = { root : process . cwd ( ) , port : '3333' , style : path . resolve ( __dirname , '../public/screen.css' ) , dtpl : path . resolve ( __dirname , '../public/dir_template.html' ) , ftpl : path . resolve ( __dirname , '../public/file_template.html' ) , view : 'details' , silent : false } ; return merge ( defaultOptions , options ) ; }


Input: start server with provided options [CODESPLIT] function startServer ( options ) { options = initOptions ( options ) ; var app = connect ( ) , root = options . root , TEST = process . env . TEST , isSilent = options . silent || TEST ; if ( ! isSilent ) { app . use ( log ) ; } var smOpts = { } ; var smOptMap = { ftpl : 'template' , style : 'style' } ; Object . keys ( smOptMap ) . forEach ( function ( key ) { if ( options [ key ] !== undefined ) smOpts [ smOptMap [ key ] ] = options [ key ] ; } ) ; // serve markdown file app . use ( serveMarkdown ( root , smOpts ) ) ; // common files app . use ( serveStatic ( root , { index : [ 'index.html' ] } ) ) ; // serve directory app . use ( serveIndex ( root , { icon : true , template : options . dtpl , stylesheet : options . style , view : options . view } ) ) ; debug ( 'server run in ' + ( process . env . TEST ? 'TEST' : 'PRODUCTION' ) + ' mode' ) if ( ! TEST ) { app . listen ( options . port ) ; showSuccessInfo ( options ) ; } return app ; }


Input: show server starting information [CODESPLIT] function showSuccessInfo ( options ) { // server start success if ( options . silent ) return ; console . log ( chalk . blue ( 'serve start Success: ' ) + '\n' + chalk . green ( '\t url   ' ) + chalk . grey ( 'http://127.0.0.1:' ) + chalk . red ( options . port ) + chalk . grey ( '/' ) + '\n' + chalk . green ( '\t serve ' ) + chalk . grey ( options . root ) ) ; }


Input: simple log middleware output the access log [CODESPLIT] function log ( req , res , next ) { console . log ( '[' + chalk . grey ( ts ( ) ) + '] ' + chalk . white ( decodeURI ( req . url ) ) ) ; next ( ) ; }


Input: type = get | set [CODESPLIT] function ( valueToSet , type , iface , propertyKeys ) { type = type . toLowerCase ( ) ; propertyKeys . forEach ( function ( propertyKey ) { if ( type == 'get' ) valueToSet [ 'Get' + propertyKey ] = function ( callback ) { iface . getProperty ( propertyKey , callback ) ; } else valueToSet [ 'Set' + propertyKey ] = function ( value , callback ) { iface . setProperty ( propertyKey , value , callback ) ; } } ) ; }


Input: MD5 [CODESPLIT] function md5 ( data ) { var md5sum = crypto . createHash ( 'md5' ) ; md5sum . update ( data ) ; return md5sum . digest ( 'hex' ) ; }


Input: Sendpulse API initialization [CODESPLIT] function init ( user_id , secret , storage ) { API_USER_ID = user_id ; API_SECRET = secret ; TOKEN_STORAGE = storage ; var hashName = md5 ( API_USER_ID + '::' + API_SECRET ) ; if ( fs . existsSync ( TOKEN_STORAGE + hashName ) ) { TOKEN = fs . readFileSync ( TOKEN_STORAGE + hashName , { encoding : 'utf8' } ) ; } if ( ! TOKEN . length ) { getToken ( ) ; } }