id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
20,700
trustnote/trustnote-pow-common
pow/pow_service.js
connectToServer
function connectToServer( oOptions ) { let sUrl; let oWs; if ( 'object' !== typeof oOptions ) { throw new Error( 'call connectToServer with invalid oOptions' ); } if ( 'string' !== typeof oOptions.minerGateway || 0 === oOptions.minerGateway.length ) { throw new Error( 'call connectToServer with invalid oOptions.minerGateway' ); } if ( 'function' !== typeof oOptions.onOpen ) { throw new Error( 'call connectToServer with invalid oOptions.onOpen' ); } if ( 'function' !== typeof oOptions.onMessage ) { throw new Error( 'call connectToServer with invalid oOptions.onMessage' ); } if ( 'function' !== typeof oOptions.onError ) { throw new Error( 'call connectToServer with invalid oOptions.onError' ); } if ( 'function' !== typeof oOptions.onClose ) { throw new Error( 'call connectToServer with invalid oOptions.onClose' ); } // ... sUrl = oOptions.minerGateway; sUrl = sUrl.trim().toLowerCase(); oWs = new WebSocket( sUrl ); // // set max listeners for EventEmitter // oWs.on( 'open', () => { let oAnotherWsToTheSameServer; if ( ! oWs.url ) { throw new Error( "no url on ws" ); } // // browser implementation of Web Socket might add '/' // if ( oWs.url !== sUrl && oWs.url !== sUrl + "/" ) { throw new Error( `url is different: ${ oWs.url }` ); } // ... oAnotherWsToTheSameServer = _cacheGetHandleByUrl( sUrl ); if ( oAnotherWsToTheSameServer ) { // // duplicate driver. // May happen if we abondoned a driver attempt after timeout // but it still succeeded while we opened another driver // console.log( `already have a connection to ${ sUrl }, will keep the old one and close the duplicate` ); oWs.close( 1000, 'duplicate driver' ); // ... return oOptions.onOpen( null, oWs ); } // // almost done! // oWs.peer = sUrl; // peer oWs.host = _getHostByPeerUrl( sUrl ); // host oWs.bOutbound = true; // identify this driver as outbound driver oWs.last_ts = Date.now(); // record the last timestamp while we connected to this peer // ... console.log( `connected to ${ sUrl }, host ${ oWs.host }` ); // // cache new socket handle // _cacheAddHandle( oWs ); // ... return oOptions.onOpen( null, oWs ); }); oWs.on( 'message', ( sMessage ) => { oOptions.onMessage( oWs, sMessage ); }); oWs.on( 'close', () => { _cacheRemoveHandle( oWs ); oOptions.onClose( oWs, `socket was close` ); }); oWs.on( 'error', ( vError ) => { oOptions.onError( oWs, vError ); }); }
javascript
function connectToServer( oOptions ) { let sUrl; let oWs; if ( 'object' !== typeof oOptions ) { throw new Error( 'call connectToServer with invalid oOptions' ); } if ( 'string' !== typeof oOptions.minerGateway || 0 === oOptions.minerGateway.length ) { throw new Error( 'call connectToServer with invalid oOptions.minerGateway' ); } if ( 'function' !== typeof oOptions.onOpen ) { throw new Error( 'call connectToServer with invalid oOptions.onOpen' ); } if ( 'function' !== typeof oOptions.onMessage ) { throw new Error( 'call connectToServer with invalid oOptions.onMessage' ); } if ( 'function' !== typeof oOptions.onError ) { throw new Error( 'call connectToServer with invalid oOptions.onError' ); } if ( 'function' !== typeof oOptions.onClose ) { throw new Error( 'call connectToServer with invalid oOptions.onClose' ); } // ... sUrl = oOptions.minerGateway; sUrl = sUrl.trim().toLowerCase(); oWs = new WebSocket( sUrl ); // // set max listeners for EventEmitter // oWs.on( 'open', () => { let oAnotherWsToTheSameServer; if ( ! oWs.url ) { throw new Error( "no url on ws" ); } // // browser implementation of Web Socket might add '/' // if ( oWs.url !== sUrl && oWs.url !== sUrl + "/" ) { throw new Error( `url is different: ${ oWs.url }` ); } // ... oAnotherWsToTheSameServer = _cacheGetHandleByUrl( sUrl ); if ( oAnotherWsToTheSameServer ) { // // duplicate driver. // May happen if we abondoned a driver attempt after timeout // but it still succeeded while we opened another driver // console.log( `already have a connection to ${ sUrl }, will keep the old one and close the duplicate` ); oWs.close( 1000, 'duplicate driver' ); // ... return oOptions.onOpen( null, oWs ); } // // almost done! // oWs.peer = sUrl; // peer oWs.host = _getHostByPeerUrl( sUrl ); // host oWs.bOutbound = true; // identify this driver as outbound driver oWs.last_ts = Date.now(); // record the last timestamp while we connected to this peer // ... console.log( `connected to ${ sUrl }, host ${ oWs.host }` ); // // cache new socket handle // _cacheAddHandle( oWs ); // ... return oOptions.onOpen( null, oWs ); }); oWs.on( 'message', ( sMessage ) => { oOptions.onMessage( oWs, sMessage ); }); oWs.on( 'close', () => { _cacheRemoveHandle( oWs ); oOptions.onClose( oWs, `socket was close` ); }); oWs.on( 'error', ( vError ) => { oOptions.onError( oWs, vError ); }); }
[ "function", "connectToServer", "(", "oOptions", ")", "{", "let", "sUrl", ";", "let", "oWs", ";", "if", "(", "'object'", "!==", "typeof", "oOptions", ")", "{", "throw", "new", "Error", "(", "'call connectToServer with invalid oOptions'", ")", ";", "}", "if", "(", "'string'", "!==", "typeof", "oOptions", ".", "minerGateway", "||", "0", "===", "oOptions", ".", "minerGateway", ".", "length", ")", "{", "throw", "new", "Error", "(", "'call connectToServer with invalid oOptions.minerGateway'", ")", ";", "}", "if", "(", "'function'", "!==", "typeof", "oOptions", ".", "onOpen", ")", "{", "throw", "new", "Error", "(", "'call connectToServer with invalid oOptions.onOpen'", ")", ";", "}", "if", "(", "'function'", "!==", "typeof", "oOptions", ".", "onMessage", ")", "{", "throw", "new", "Error", "(", "'call connectToServer with invalid oOptions.onMessage'", ")", ";", "}", "if", "(", "'function'", "!==", "typeof", "oOptions", ".", "onError", ")", "{", "throw", "new", "Error", "(", "'call connectToServer with invalid oOptions.onError'", ")", ";", "}", "if", "(", "'function'", "!==", "typeof", "oOptions", ".", "onClose", ")", "{", "throw", "new", "Error", "(", "'call connectToServer with invalid oOptions.onClose'", ")", ";", "}", "//\t...", "sUrl", "=", "oOptions", ".", "minerGateway", ";", "sUrl", "=", "sUrl", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ";", "oWs", "=", "new", "WebSocket", "(", "sUrl", ")", ";", "//", "//\tset max listeners for EventEmitter", "//", "oWs", ".", "on", "(", "'open'", ",", "(", ")", "=>", "{", "let", "oAnotherWsToTheSameServer", ";", "if", "(", "!", "oWs", ".", "url", ")", "{", "throw", "new", "Error", "(", "\"no url on ws\"", ")", ";", "}", "//", "//\tbrowser implementation of Web Socket might add '/'", "//", "if", "(", "oWs", ".", "url", "!==", "sUrl", "&&", "oWs", ".", "url", "!==", "sUrl", "+", "\"/\"", ")", "{", "throw", "new", "Error", "(", "`", "${", "oWs", ".", "url", "}", "`", ")", ";", "}", "//\t...", "oAnotherWsToTheSameServer", "=", "_cacheGetHandleByUrl", "(", "sUrl", ")", ";", "if", "(", "oAnotherWsToTheSameServer", ")", "{", "//", "//\tduplicate driver.", "//\tMay happen if we abondoned a driver attempt after timeout", "// \t\tbut it still succeeded while we opened another driver", "//", "console", ".", "log", "(", "`", "${", "sUrl", "}", "`", ")", ";", "oWs", ".", "close", "(", "1000", ",", "'duplicate driver'", ")", ";", "//\t...", "return", "oOptions", ".", "onOpen", "(", "null", ",", "oWs", ")", ";", "}", "//", "//\talmost done!", "//", "oWs", ".", "peer", "=", "sUrl", ";", "//\tpeer", "oWs", ".", "host", "=", "_getHostByPeerUrl", "(", "sUrl", ")", ";", "//\thost", "oWs", ".", "bOutbound", "=", "true", ";", "//\tidentify this driver as outbound driver", "oWs", ".", "last_ts", "=", "Date", ".", "now", "(", ")", ";", "//\trecord the last timestamp while we connected to this peer", "//\t...", "console", ".", "log", "(", "`", "${", "sUrl", "}", "${", "oWs", ".", "host", "}", "`", ")", ";", "//", "//\tcache new socket handle", "//", "_cacheAddHandle", "(", "oWs", ")", ";", "//\t...", "return", "oOptions", ".", "onOpen", "(", "null", ",", "oWs", ")", ";", "}", ")", ";", "oWs", ".", "on", "(", "'message'", ",", "(", "sMessage", ")", "=>", "{", "oOptions", ".", "onMessage", "(", "oWs", ",", "sMessage", ")", ";", "}", ")", ";", "oWs", ".", "on", "(", "'close'", ",", "(", ")", "=>", "{", "_cacheRemoveHandle", "(", "oWs", ")", ";", "oOptions", ".", "onClose", "(", "oWs", ",", "`", "`", ")", ";", "}", ")", ";", "oWs", ".", "on", "(", "'error'", ",", "(", "vError", ")", "=>", "{", "oOptions", ".", "onError", "(", "oWs", ",", "vError", ")", ";", "}", ")", ";", "}" ]
CLIENT connect to server @public @param {object} oOptions @param {string} oOptions.minerGateway e.g. : wss://1.miner.trustnote.org @param {function} oOptions.onOpen( err, oWsClient ) @param {function} oOptions.onMessage( oWsClient, sMessage ) @param {function} oOptions.onError( oWsClient, vError ) @param {function} oOptions.onClose( oWsClient, sReason )
[ "CLIENT", "connect", "to", "server" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow_service.js#L199-L304
20,701
trustnote/trustnote-pow-common
pow/pow_service.js
sendMessageOnce
function sendMessageOnce( oWs, sCommand, jsonMessage ) { // ... sendMessage( oWs, sCommand, jsonMessage ); // ... let nCheckInterval = setInterval( () => { if ( 0 === oWs.bufferedAmount ) { // Im' not busy anymore - set a flag or something like that clearInterval( nCheckInterval ); nCheckInterval = null; // close socket oWs.close( 1000, 'done' ); } }, 50 ); }
javascript
function sendMessageOnce( oWs, sCommand, jsonMessage ) { // ... sendMessage( oWs, sCommand, jsonMessage ); // ... let nCheckInterval = setInterval( () => { if ( 0 === oWs.bufferedAmount ) { // Im' not busy anymore - set a flag or something like that clearInterval( nCheckInterval ); nCheckInterval = null; // close socket oWs.close( 1000, 'done' ); } }, 50 ); }
[ "function", "sendMessageOnce", "(", "oWs", ",", "sCommand", ",", "jsonMessage", ")", "{", "//\t...", "sendMessage", "(", "oWs", ",", "sCommand", ",", "jsonMessage", ")", ";", "//\t...", "let", "nCheckInterval", "=", "setInterval", "(", "(", ")", "=>", "{", "if", "(", "0", "===", "oWs", ".", "bufferedAmount", ")", "{", "//\tIm' not busy anymore - set a flag or something like that", "clearInterval", "(", "nCheckInterval", ")", ";", "nCheckInterval", "=", "null", ";", "//\tclose socket", "oWs", ".", "close", "(", "1000", ",", "'done'", ")", ";", "}", "}", ",", "50", ")", ";", "}" ]
send message and then close the socket @public @param {object} oWs @param {string} sCommand @param {object} jsonMessage @return {boolean}
[ "send", "message", "and", "then", "close", "the", "socket" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow_service.js#L363-L381
20,702
trustnote/trustnote-pow-common
pow/pow_service.js
_cacheGetHandleByUrl
function _cacheGetHandleByUrl( sUrl ) { let oRet; let arrResult; if ( 'string' !== typeof sUrl || 0 === sUrl.length ) { return null; } // ... oRet = null; sUrl = sUrl.trim().toLowerCase(); arrResult = m_arrCacheOutboundPeers.filter( oSocket => oSocket.peer === sUrl ); if ( Array.isArray( arrResult ) && 1 === arrResult.length ) { oRet = arrResult[ 0 ]; } return oRet; }
javascript
function _cacheGetHandleByUrl( sUrl ) { let oRet; let arrResult; if ( 'string' !== typeof sUrl || 0 === sUrl.length ) { return null; } // ... oRet = null; sUrl = sUrl.trim().toLowerCase(); arrResult = m_arrCacheOutboundPeers.filter( oSocket => oSocket.peer === sUrl ); if ( Array.isArray( arrResult ) && 1 === arrResult.length ) { oRet = arrResult[ 0 ]; } return oRet; }
[ "function", "_cacheGetHandleByUrl", "(", "sUrl", ")", "{", "let", "oRet", ";", "let", "arrResult", ";", "if", "(", "'string'", "!==", "typeof", "sUrl", "||", "0", "===", "sUrl", ".", "length", ")", "{", "return", "null", ";", "}", "//\t...", "oRet", "=", "null", ";", "sUrl", "=", "sUrl", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ";", "arrResult", "=", "m_arrCacheOutboundPeers", ".", "filter", "(", "oSocket", "=>", "oSocket", ".", "peer", "===", "sUrl", ")", ";", "if", "(", "Array", ".", "isArray", "(", "arrResult", ")", "&&", "1", "===", "arrResult", ".", "length", ")", "{", "oRet", "=", "arrResult", "[", "0", "]", ";", "}", "return", "oRet", ";", "}" ]
get socket handle by url @private @param {string} sUrl @returns {null}
[ "get", "socket", "handle", "by", "url" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow_service.js#L393-L413
20,703
trustnote/trustnote-pow-common
pow/pow_service.js
_cacheAddHandle
function _cacheAddHandle( oSocket ) { if ( ! oSocket ) { return false; } // ... _cacheRemoveHandle( oSocket ); m_arrCacheOutboundPeers.push( oSocket ); return true; }
javascript
function _cacheAddHandle( oSocket ) { if ( ! oSocket ) { return false; } // ... _cacheRemoveHandle( oSocket ); m_arrCacheOutboundPeers.push( oSocket ); return true; }
[ "function", "_cacheAddHandle", "(", "oSocket", ")", "{", "if", "(", "!", "oSocket", ")", "{", "return", "false", ";", "}", "//\t...", "_cacheRemoveHandle", "(", "oSocket", ")", ";", "m_arrCacheOutboundPeers", ".", "push", "(", "oSocket", ")", ";", "return", "true", ";", "}" ]
add new socket handle by url @private @param {object} oSocket @returns {boolean}
[ "add", "new", "socket", "handle", "by", "url" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow_service.js#L422-L433
20,704
trustnote/trustnote-pow-common
pow/pow_service.js
_cacheRemoveHandle
function _cacheRemoveHandle( oSocket ) { let bRet; let nIndex; if ( ! oSocket ) { return false; } // ... bRet = false; nIndex = m_arrCacheOutboundPeers.indexOf( oSocket ); if ( -1 !== nIndex ) { bRet = true; m_arrCacheOutboundPeers.splice( nIndex, 1 ); } return bRet; }
javascript
function _cacheRemoveHandle( oSocket ) { let bRet; let nIndex; if ( ! oSocket ) { return false; } // ... bRet = false; nIndex = m_arrCacheOutboundPeers.indexOf( oSocket ); if ( -1 !== nIndex ) { bRet = true; m_arrCacheOutboundPeers.splice( nIndex, 1 ); } return bRet; }
[ "function", "_cacheRemoveHandle", "(", "oSocket", ")", "{", "let", "bRet", ";", "let", "nIndex", ";", "if", "(", "!", "oSocket", ")", "{", "return", "false", ";", "}", "//\t...", "bRet", "=", "false", ";", "nIndex", "=", "m_arrCacheOutboundPeers", ".", "indexOf", "(", "oSocket", ")", ";", "if", "(", "-", "1", "!==", "nIndex", ")", "{", "bRet", "=", "true", ";", "m_arrCacheOutboundPeers", ".", "splice", "(", "nIndex", ",", "1", ")", ";", "}", "return", "bRet", ";", "}" ]
remove socket handle by url @private @param {object} oSocket @returns {boolean}
[ "remove", "socket", "handle", "by", "url" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow_service.js#L442-L462
20,705
trustnote/trustnote-pow-common
pow/pow_service.js
_getHostByPeerUrl
function _getHostByPeerUrl( sUrl ) { let arrMatches; // // this regex will match wss://xxx and ws://xxx // arrMatches = sUrl.match( /^wss?:\/\/(.*)$/i ); if ( Array.isArray( arrMatches ) && arrMatches.length >= 1 ) { sUrl = arrMatches[ 1 ]; } // ... arrMatches = sUrl.match( /^(.*?)[:\/]/ ); return ( Array.isArray( arrMatches ) && arrMatches.length >= 1 ) ? arrMatches[ 1 ] : sUrl; }
javascript
function _getHostByPeerUrl( sUrl ) { let arrMatches; // // this regex will match wss://xxx and ws://xxx // arrMatches = sUrl.match( /^wss?:\/\/(.*)$/i ); if ( Array.isArray( arrMatches ) && arrMatches.length >= 1 ) { sUrl = arrMatches[ 1 ]; } // ... arrMatches = sUrl.match( /^(.*?)[:\/]/ ); return ( Array.isArray( arrMatches ) && arrMatches.length >= 1 ) ? arrMatches[ 1 ] : sUrl; }
[ "function", "_getHostByPeerUrl", "(", "sUrl", ")", "{", "let", "arrMatches", ";", "//", "//\tthis regex will match wss://xxx and ws://xxx", "//", "arrMatches", "=", "sUrl", ".", "match", "(", "/", "^wss?:\\/\\/(.*)$", "/", "i", ")", ";", "if", "(", "Array", ".", "isArray", "(", "arrMatches", ")", "&&", "arrMatches", ".", "length", ">=", "1", ")", "{", "sUrl", "=", "arrMatches", "[", "1", "]", ";", "}", "//\t...", "arrMatches", "=", "sUrl", ".", "match", "(", "/", "^(.*?)[:\\/]", "/", ")", ";", "return", "(", "Array", ".", "isArray", "(", "arrMatches", ")", "&&", "arrMatches", ".", "length", ">=", "1", ")", "?", "arrMatches", "[", "1", "]", ":", "sUrl", ";", "}" ]
get host by peer url @private @param {string} sUrl @return {string}
[ "get", "host", "by", "peer", "url" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow_service.js#L472-L488
20,706
trustnote/trustnote-pow-common
pow/pow_service.js
_getRemoteAddress
function _getRemoteAddress( oSocket ) { let sRet; if ( 'object' !== typeof oSocket ) { return null; } // ... sRet = oSocket.upgradeReq.connection.remoteAddress; if ( sRet ) { // // check for proxy // ONLY VALID FOR 127.0.0.1 and resources addresses // if ( oSocket.upgradeReq.headers[ 'x-real-ip' ] && _isValidResourceAddress( sRet ) ) { // we are behind a proxy sRet = oSocket.upgradeReq.headers[ 'x-real-ip' ]; } } return sRet; }
javascript
function _getRemoteAddress( oSocket ) { let sRet; if ( 'object' !== typeof oSocket ) { return null; } // ... sRet = oSocket.upgradeReq.connection.remoteAddress; if ( sRet ) { // // check for proxy // ONLY VALID FOR 127.0.0.1 and resources addresses // if ( oSocket.upgradeReq.headers[ 'x-real-ip' ] && _isValidResourceAddress( sRet ) ) { // we are behind a proxy sRet = oSocket.upgradeReq.headers[ 'x-real-ip' ]; } } return sRet; }
[ "function", "_getRemoteAddress", "(", "oSocket", ")", "{", "let", "sRet", ";", "if", "(", "'object'", "!==", "typeof", "oSocket", ")", "{", "return", "null", ";", "}", "//\t...", "sRet", "=", "oSocket", ".", "upgradeReq", ".", "connection", ".", "remoteAddress", ";", "if", "(", "sRet", ")", "{", "//", "//\tcheck for proxy", "//\tONLY VALID FOR 127.0.0.1 and resources addresses", "//", "if", "(", "oSocket", ".", "upgradeReq", ".", "headers", "[", "'x-real-ip'", "]", "&&", "_isValidResourceAddress", "(", "sRet", ")", ")", "{", "//\twe are behind a proxy", "sRet", "=", "oSocket", ".", "upgradeReq", ".", "headers", "[", "'x-real-ip'", "]", ";", "}", "}", "return", "sRet", ";", "}" ]
get remote address @private @param {object} oSocket
[ "get", "remote", "address" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow_service.js#L497-L522
20,707
trustnote/trustnote-pow-common
witness/witness_pow_proof.js
validateUnit
function validateUnit( objUnit, bRequireDefinitionOrChange, cb2 ) { let bFound = false; _async.eachSeries ( objUnit.authors, function( author, cb3 ) { let sAddress = author.address; if ( -1 === arrFoundTrustMEAuthors.indexOf( sAddress ) ) { // not a witness - skip it return cb3(); } // // the latest definition chash of the witness // let definition_chash = assocDefinitionChashes[ sAddress ]; if ( ! definition_chash ) { throw Error( "definition chash not known for address " + sAddress ); } if ( author.definition ) { // // do transaction for the first time // if ( _object_hash.getChash160( author.definition ) !== definition_chash ) { return cb3( "definition doesn't hash to the expected value" ); } assocDefinitions[ definition_chash ] = author.definition; bFound = true; } function handleAuthor() { // FIX _validation.validateAuthorSignaturesWithoutReferences ( author, objUnit, assocDefinitions[ definition_chash ], // definition JSON function( err ) { if ( err ) { return cb3( err ); } // // okay, definition is valid // for ( let i = 0; i < objUnit.messages.length; i++ ) { let message = objUnit.messages[ i ]; if ( 'address_definition_change' === message.app && ( message.payload.address === sAddress || 1 === objUnit.authors.length && objUnit.authors[ 0 ].address === sAddress ) ) { assocDefinitionChashes[ sAddress ] = message.payload.definition_chash; bFound = true; } } // ... cb3(); } ); } if ( assocDefinitions[ definition_chash ] ) { return handleAuthor(); } // // only an address with money // there is no transaction any more // _storage.readDefinition( _db, definition_chash, { ifFound : function( arrDefinition ) { assocDefinitions[ definition_chash ] = arrDefinition; handleAuthor(); }, ifDefinitionNotFound : function( sDefinitionCHash ) { throw Error( "definition " + definition_chash + " not found, address " + sAddress ); } }); }, function( err ) { if ( err ) { return cb2( err ); } if ( bRequireDefinitionOrChange && ! bFound ) { // // bRequireDefinitionOrChange always be false // so, you will never arrive here so far // return cb2( "neither definition nor change" ); } // ... cb2(); } ); // each authors }
javascript
function validateUnit( objUnit, bRequireDefinitionOrChange, cb2 ) { let bFound = false; _async.eachSeries ( objUnit.authors, function( author, cb3 ) { let sAddress = author.address; if ( -1 === arrFoundTrustMEAuthors.indexOf( sAddress ) ) { // not a witness - skip it return cb3(); } // // the latest definition chash of the witness // let definition_chash = assocDefinitionChashes[ sAddress ]; if ( ! definition_chash ) { throw Error( "definition chash not known for address " + sAddress ); } if ( author.definition ) { // // do transaction for the first time // if ( _object_hash.getChash160( author.definition ) !== definition_chash ) { return cb3( "definition doesn't hash to the expected value" ); } assocDefinitions[ definition_chash ] = author.definition; bFound = true; } function handleAuthor() { // FIX _validation.validateAuthorSignaturesWithoutReferences ( author, objUnit, assocDefinitions[ definition_chash ], // definition JSON function( err ) { if ( err ) { return cb3( err ); } // // okay, definition is valid // for ( let i = 0; i < objUnit.messages.length; i++ ) { let message = objUnit.messages[ i ]; if ( 'address_definition_change' === message.app && ( message.payload.address === sAddress || 1 === objUnit.authors.length && objUnit.authors[ 0 ].address === sAddress ) ) { assocDefinitionChashes[ sAddress ] = message.payload.definition_chash; bFound = true; } } // ... cb3(); } ); } if ( assocDefinitions[ definition_chash ] ) { return handleAuthor(); } // // only an address with money // there is no transaction any more // _storage.readDefinition( _db, definition_chash, { ifFound : function( arrDefinition ) { assocDefinitions[ definition_chash ] = arrDefinition; handleAuthor(); }, ifDefinitionNotFound : function( sDefinitionCHash ) { throw Error( "definition " + definition_chash + " not found, address " + sAddress ); } }); }, function( err ) { if ( err ) { return cb2( err ); } if ( bRequireDefinitionOrChange && ! bFound ) { // // bRequireDefinitionOrChange always be false // so, you will never arrive here so far // return cb2( "neither definition nor change" ); } // ... cb2(); } ); // each authors }
[ "function", "validateUnit", "(", "objUnit", ",", "bRequireDefinitionOrChange", ",", "cb2", ")", "{", "let", "bFound", "=", "false", ";", "_async", ".", "eachSeries", "(", "objUnit", ".", "authors", ",", "function", "(", "author", ",", "cb3", ")", "{", "let", "sAddress", "=", "author", ".", "address", ";", "if", "(", "-", "1", "===", "arrFoundTrustMEAuthors", ".", "indexOf", "(", "sAddress", ")", ")", "{", "//\tnot a witness - skip it", "return", "cb3", "(", ")", ";", "}", "//", "//\tthe latest definition chash of the witness", "//", "let", "definition_chash", "=", "assocDefinitionChashes", "[", "sAddress", "]", ";", "if", "(", "!", "definition_chash", ")", "{", "throw", "Error", "(", "\"definition chash not known for address \"", "+", "sAddress", ")", ";", "}", "if", "(", "author", ".", "definition", ")", "{", "//", "//\tdo transaction for the first time", "//", "if", "(", "_object_hash", ".", "getChash160", "(", "author", ".", "definition", ")", "!==", "definition_chash", ")", "{", "return", "cb3", "(", "\"definition doesn't hash to the expected value\"", ")", ";", "}", "assocDefinitions", "[", "definition_chash", "]", "=", "author", ".", "definition", ";", "bFound", "=", "true", ";", "}", "function", "handleAuthor", "(", ")", "{", "//\tFIX", "_validation", ".", "validateAuthorSignaturesWithoutReferences", "(", "author", ",", "objUnit", ",", "assocDefinitions", "[", "definition_chash", "]", ",", "//\tdefinition JSON", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "cb3", "(", "err", ")", ";", "}", "//", "//\tokay, definition is valid", "//", "for", "(", "let", "i", "=", "0", ";", "i", "<", "objUnit", ".", "messages", ".", "length", ";", "i", "++", ")", "{", "let", "message", "=", "objUnit", ".", "messages", "[", "i", "]", ";", "if", "(", "'address_definition_change'", "===", "message", ".", "app", "&&", "(", "message", ".", "payload", ".", "address", "===", "sAddress", "||", "1", "===", "objUnit", ".", "authors", ".", "length", "&&", "objUnit", ".", "authors", "[", "0", "]", ".", "address", "===", "sAddress", ")", ")", "{", "assocDefinitionChashes", "[", "sAddress", "]", "=", "message", ".", "payload", ".", "definition_chash", ";", "bFound", "=", "true", ";", "}", "}", "//\t...", "cb3", "(", ")", ";", "}", ")", ";", "}", "if", "(", "assocDefinitions", "[", "definition_chash", "]", ")", "{", "return", "handleAuthor", "(", ")", ";", "}", "//", "//\tonly an address with money", "//\tthere is no transaction any more", "//", "_storage", ".", "readDefinition", "(", "_db", ",", "definition_chash", ",", "{", "ifFound", ":", "function", "(", "arrDefinition", ")", "{", "assocDefinitions", "[", "definition_chash", "]", "=", "arrDefinition", ";", "handleAuthor", "(", ")", ";", "}", ",", "ifDefinitionNotFound", ":", "function", "(", "sDefinitionCHash", ")", "{", "throw", "Error", "(", "\"definition \"", "+", "definition_chash", "+", "\" not found, address \"", "+", "sAddress", ")", ";", "}", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "cb2", "(", "err", ")", ";", "}", "if", "(", "bRequireDefinitionOrChange", "&&", "!", "bFound", ")", "{", "//", "//\tbRequireDefinitionOrChange always be false", "//\tso, you will never arrive here so far", "//", "return", "cb2", "(", "\"neither definition nor change\"", ")", ";", "}", "//\t...", "cb2", "(", ")", ";", "}", ")", ";", "// each authors", "}" ]
checks signatures and updates definitions
[ "checks", "signatures", "and", "updates", "definitions" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/witness/witness_pow_proof.js#L207-L324
20,708
trustnote/trustnote-pow-common
sc/deposit.js
isDepositDefinition
function isDepositDefinition(arrDefinition){ if (!validationUtils.isArrayOfLength(arrDefinition, 2)) return false; if (arrDefinition[0] !== 'or') return false; if (!validationUtils.isArrayOfLength(arrDefinition[1], 2)) return false; if (!validationUtils.isArrayOfLength(arrDefinition[1][0], 2)) return false; if (!validationUtils.isArrayOfLength(arrDefinition[1][1], 2)) return false; if (arrDefinition[1][0][1] !== constants.FOUNDATION_SAFE_ADDRESS) return false; if(!validationUtils.isValidAddress(arrDefinition[1][1][1])) return false; return true; }
javascript
function isDepositDefinition(arrDefinition){ if (!validationUtils.isArrayOfLength(arrDefinition, 2)) return false; if (arrDefinition[0] !== 'or') return false; if (!validationUtils.isArrayOfLength(arrDefinition[1], 2)) return false; if (!validationUtils.isArrayOfLength(arrDefinition[1][0], 2)) return false; if (!validationUtils.isArrayOfLength(arrDefinition[1][1], 2)) return false; if (arrDefinition[1][0][1] !== constants.FOUNDATION_SAFE_ADDRESS) return false; if(!validationUtils.isValidAddress(arrDefinition[1][1][1])) return false; return true; }
[ "function", "isDepositDefinition", "(", "arrDefinition", ")", "{", "if", "(", "!", "validationUtils", ".", "isArrayOfLength", "(", "arrDefinition", ",", "2", ")", ")", "return", "false", ";", "if", "(", "arrDefinition", "[", "0", "]", "!==", "'or'", ")", "return", "false", ";", "if", "(", "!", "validationUtils", ".", "isArrayOfLength", "(", "arrDefinition", "[", "1", "]", ",", "2", ")", ")", "return", "false", ";", "if", "(", "!", "validationUtils", ".", "isArrayOfLength", "(", "arrDefinition", "[", "1", "]", "[", "0", "]", ",", "2", ")", ")", "return", "false", ";", "if", "(", "!", "validationUtils", ".", "isArrayOfLength", "(", "arrDefinition", "[", "1", "]", "[", "1", "]", ",", "2", ")", ")", "return", "false", ";", "if", "(", "arrDefinition", "[", "1", "]", "[", "0", "]", "[", "1", "]", "!==", "constants", ".", "FOUNDATION_SAFE_ADDRESS", ")", "return", "false", ";", "if", "(", "!", "validationUtils", ".", "isValidAddress", "(", "arrDefinition", "[", "1", "]", "[", "1", "]", "[", "1", "]", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
verify if a deposit definition is valid. @param {Array} arrDefinition @return {boolean}
[ "verify", "if", "a", "deposit", "definition", "is", "valid", "." ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/sc/deposit.js#L18-L35
20,709
trustnote/trustnote-pow-common
sc/deposit.js
hasInvalidUnitsFromHistory
function hasInvalidUnitsFromHistory(conn, address, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(address)) return cb("param address is null or empty string"); if(!validationUtils.isValidAddress(address)) return cb("param address is not a valid address"); conn.query( "SELECT address FROM units JOIN unit_authors USING(unit) \n\ WHERE is_stable=1 AND sequence!='good' AND address=?", [address], function(rows){ cb(null, rows.length > 0 ? true : false); } ); }
javascript
function hasInvalidUnitsFromHistory(conn, address, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(address)) return cb("param address is null or empty string"); if(!validationUtils.isValidAddress(address)) return cb("param address is not a valid address"); conn.query( "SELECT address FROM units JOIN unit_authors USING(unit) \n\ WHERE is_stable=1 AND sequence!='good' AND address=?", [address], function(rows){ cb(null, rows.length > 0 ? true : false); } ); }
[ "function", "hasInvalidUnitsFromHistory", "(", "conn", ",", "address", ",", "cb", ")", "{", "var", "conn", "=", "conn", "||", "db", ";", "if", "(", "!", "validationUtils", ".", "isNonemptyString", "(", "address", ")", ")", "return", "cb", "(", "\"param address is null or empty string\"", ")", ";", "if", "(", "!", "validationUtils", ".", "isValidAddress", "(", "address", ")", ")", "return", "cb", "(", "\"param address is not a valid address\"", ")", ";", "conn", ".", "query", "(", "\"SELECT address FROM units JOIN unit_authors USING(unit) \\n\\\n WHERE is_stable=1 AND sequence!='good' AND address=?\"", ",", "[", "address", "]", ",", "function", "(", "rows", ")", "{", "cb", "(", "null", ",", "rows", ".", "length", ">", "0", "?", "true", ":", "false", ")", ";", "}", ")", ";", "}" ]
Check if an address has sent invalid unit. @param {obj} conn if conn is null, use db query, otherwise use conn. @param {string} address @param {function} cb( err, hasInvalidUnits ) callback function If there's error, err is the error message and hasInvalidUnits is null. If there's no error and there's invalid units, then hasInvalidUnits is true, otherwise false.
[ "Check", "if", "an", "address", "has", "sent", "invalid", "unit", "." ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/sc/deposit.js#L46-L60
20,710
trustnote/trustnote-pow-common
sc/deposit.js
getBalanceOfDepositContract
function getBalanceOfDepositContract(conn, depositAddress, roundIndex, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(depositAddress)) return cb("param depositAddress is null or empty string"); if(!validationUtils.isValidAddress(depositAddress)) return cb("param depositAddress is not a valid address"); if(!validationUtils.isPositiveInteger(roundIndex)) return cb("param roundIndex is not a positive integer"); if(roundIndex === 1) return cb(null, 0); //WHERE src_unit=? AND src_message_index=? AND src_output_index=? \n\ round.getMaxMciByRoundIndex(conn, roundIndex-1, function(lastRoundMaxMci){ var sumBanlance = 0; conn.query("SELECT src_unit, src_message_index, src_output_index AS count \n\ FROM inputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index>? AND address=?", [lastRoundMaxMci, depositAddress], function(rowsInputs) { conn.query("SELECT unit, is_spent, amount, message_index, output_index \n\ FROM outputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index<=? AND address=?", [lastRoundMaxMci, depositAddress], function(rowsOutputs) { if (rowsOutputs.length === 0) return cb(null, 0); for (var i=0; i<rowsOutputs.length; i++) { if(rowsOutputs[i].is_spent === 0) { sumBanlance += rowsOutputs[i].amount; } else { if(rowsInputs.length > 0) { for (var j=0; j<rowsInputs.length; j++) { if(rowsInputs[j].src_unit === rowsOutputs[i].unit && rowsInputs[j].src_message_index === rowsOutputs[i].message_index && rowsInputs[j].src_output_index === rowsOutputs[i].output_index ){ sumBanlance += rowsOutputs[i].amount; } } } } } cb(null, sumBanlance); }); }); }); }
javascript
function getBalanceOfDepositContract(conn, depositAddress, roundIndex, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(depositAddress)) return cb("param depositAddress is null or empty string"); if(!validationUtils.isValidAddress(depositAddress)) return cb("param depositAddress is not a valid address"); if(!validationUtils.isPositiveInteger(roundIndex)) return cb("param roundIndex is not a positive integer"); if(roundIndex === 1) return cb(null, 0); //WHERE src_unit=? AND src_message_index=? AND src_output_index=? \n\ round.getMaxMciByRoundIndex(conn, roundIndex-1, function(lastRoundMaxMci){ var sumBanlance = 0; conn.query("SELECT src_unit, src_message_index, src_output_index AS count \n\ FROM inputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index>? AND address=?", [lastRoundMaxMci, depositAddress], function(rowsInputs) { conn.query("SELECT unit, is_spent, amount, message_index, output_index \n\ FROM outputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index<=? AND address=?", [lastRoundMaxMci, depositAddress], function(rowsOutputs) { if (rowsOutputs.length === 0) return cb(null, 0); for (var i=0; i<rowsOutputs.length; i++) { if(rowsOutputs[i].is_spent === 0) { sumBanlance += rowsOutputs[i].amount; } else { if(rowsInputs.length > 0) { for (var j=0; j<rowsInputs.length; j++) { if(rowsInputs[j].src_unit === rowsOutputs[i].unit && rowsInputs[j].src_message_index === rowsOutputs[i].message_index && rowsInputs[j].src_output_index === rowsOutputs[i].output_index ){ sumBanlance += rowsOutputs[i].amount; } } } } } cb(null, sumBanlance); }); }); }); }
[ "function", "getBalanceOfDepositContract", "(", "conn", ",", "depositAddress", ",", "roundIndex", ",", "cb", ")", "{", "var", "conn", "=", "conn", "||", "db", ";", "if", "(", "!", "validationUtils", ".", "isNonemptyString", "(", "depositAddress", ")", ")", "return", "cb", "(", "\"param depositAddress is null or empty string\"", ")", ";", "if", "(", "!", "validationUtils", ".", "isValidAddress", "(", "depositAddress", ")", ")", "return", "cb", "(", "\"param depositAddress is not a valid address\"", ")", ";", "if", "(", "!", "validationUtils", ".", "isPositiveInteger", "(", "roundIndex", ")", ")", "return", "cb", "(", "\"param roundIndex is not a positive integer\"", ")", ";", "if", "(", "roundIndex", "===", "1", ")", "return", "cb", "(", "null", ",", "0", ")", ";", "//WHERE src_unit=? AND src_message_index=? AND src_output_index=? \\n\\", "round", ".", "getMaxMciByRoundIndex", "(", "conn", ",", "roundIndex", "-", "1", ",", "function", "(", "lastRoundMaxMci", ")", "{", "var", "sumBanlance", "=", "0", ";", "conn", ".", "query", "(", "\"SELECT src_unit, src_message_index, src_output_index AS count \\n\\\n FROM inputs JOIN units USING(unit) \\n\\\n WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index>? AND address=?\"", ",", "[", "lastRoundMaxMci", ",", "depositAddress", "]", ",", "function", "(", "rowsInputs", ")", "{", "conn", ".", "query", "(", "\"SELECT unit, is_spent, amount, message_index, output_index \\n\\\n FROM outputs JOIN units USING(unit) \\n\\\n WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index<=? AND address=?\"", ",", "[", "lastRoundMaxMci", ",", "depositAddress", "]", ",", "function", "(", "rowsOutputs", ")", "{", "if", "(", "rowsOutputs", ".", "length", "===", "0", ")", "return", "cb", "(", "null", ",", "0", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rowsOutputs", ".", "length", ";", "i", "++", ")", "{", "if", "(", "rowsOutputs", "[", "i", "]", ".", "is_spent", "===", "0", ")", "{", "sumBanlance", "+=", "rowsOutputs", "[", "i", "]", ".", "amount", ";", "}", "else", "{", "if", "(", "rowsInputs", ".", "length", ">", "0", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "rowsInputs", ".", "length", ";", "j", "++", ")", "{", "if", "(", "rowsInputs", "[", "j", "]", ".", "src_unit", "===", "rowsOutputs", "[", "i", "]", ".", "unit", "&&", "rowsInputs", "[", "j", "]", ".", "src_message_index", "===", "rowsOutputs", "[", "i", "]", ".", "message_index", "&&", "rowsInputs", "[", "j", "]", ".", "src_output_index", "===", "rowsOutputs", "[", "i", "]", ".", "output_index", ")", "{", "sumBanlance", "+=", "rowsOutputs", "[", "i", "]", ".", "amount", ";", "}", "}", "}", "}", "}", "cb", "(", "null", ",", "sumBanlance", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Returns deposit address stable balance, Before the roundIndex @param {obj} conn if conn is null, use db query, otherwise use conn. @param {String} depositAddress @param {String} roundIndex @param {function} cb( err, balance ) callback function If address is invalid, then returns err "invalid address". If address is not a deposit, then returns err "address is not a deposit". If can not find the address, then returns err "address not found". @return {"base":{"stable":{Integer},"pending":{Integer}}} balance
[ "Returns", "deposit", "address", "stable", "balance", "Before", "the", "roundIndex" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/sc/deposit.js#L74-L117
20,711
trustnote/trustnote-pow-common
sc/deposit.js
getBalanceOfAllDepositContract
function getBalanceOfAllDepositContract(conn, roundIndex, cb){ var conn = conn || db; if(!validationUtils.isPositiveInteger(roundIndex)) return cb("param roundIndex is not a positive integer"); round.getMaxMciByRoundIndex(conn, roundIndex, function(lastRoundMaxMci){ conn.query("SELECT deposit_address FROM supernode", function(rowsDepositAddress) { var arrDepositAddress = rowsDepositAddress.map(function(row){ return row.deposit_address; }); var strDepositAddress = arrDepositAddress.map(db.escape).join(', '); conn.query("SELECT sum(amount) AS sumBanlance \n\ FROM outputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index<=? \n\ AND address IN("+strDepositAddress+")", [lastRoundMaxMci], function(rowsOutputs) { if (rowsOutputs.length === 0) return cb(null, 0); cb(null, parseInt(rowsOutputs[0].sumBanlance)); }); }); }); }
javascript
function getBalanceOfAllDepositContract(conn, roundIndex, cb){ var conn = conn || db; if(!validationUtils.isPositiveInteger(roundIndex)) return cb("param roundIndex is not a positive integer"); round.getMaxMciByRoundIndex(conn, roundIndex, function(lastRoundMaxMci){ conn.query("SELECT deposit_address FROM supernode", function(rowsDepositAddress) { var arrDepositAddress = rowsDepositAddress.map(function(row){ return row.deposit_address; }); var strDepositAddress = arrDepositAddress.map(db.escape).join(', '); conn.query("SELECT sum(amount) AS sumBanlance \n\ FROM outputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index<=? \n\ AND address IN("+strDepositAddress+")", [lastRoundMaxMci], function(rowsOutputs) { if (rowsOutputs.length === 0) return cb(null, 0); cb(null, parseInt(rowsOutputs[0].sumBanlance)); }); }); }); }
[ "function", "getBalanceOfAllDepositContract", "(", "conn", ",", "roundIndex", ",", "cb", ")", "{", "var", "conn", "=", "conn", "||", "db", ";", "if", "(", "!", "validationUtils", ".", "isPositiveInteger", "(", "roundIndex", ")", ")", "return", "cb", "(", "\"param roundIndex is not a positive integer\"", ")", ";", "round", ".", "getMaxMciByRoundIndex", "(", "conn", ",", "roundIndex", ",", "function", "(", "lastRoundMaxMci", ")", "{", "conn", ".", "query", "(", "\"SELECT deposit_address FROM supernode\"", ",", "function", "(", "rowsDepositAddress", ")", "{", "var", "arrDepositAddress", "=", "rowsDepositAddress", ".", "map", "(", "function", "(", "row", ")", "{", "return", "row", ".", "deposit_address", ";", "}", ")", ";", "var", "strDepositAddress", "=", "arrDepositAddress", ".", "map", "(", "db", ".", "escape", ")", ".", "join", "(", "', '", ")", ";", "conn", ".", "query", "(", "\"SELECT sum(amount) AS sumBanlance \\n\\\n FROM outputs JOIN units USING(unit) \\n\\\n WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index<=? \\n\\\n AND address IN(\"", "+", "strDepositAddress", "+", "\")\"", ",", "[", "lastRoundMaxMci", "]", ",", "function", "(", "rowsOutputs", ")", "{", "if", "(", "rowsOutputs", ".", "length", "===", "0", ")", "return", "cb", "(", "null", ",", "0", ")", ";", "cb", "(", "null", ",", "parseInt", "(", "rowsOutputs", "[", "0", "]", ".", "sumBanlance", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get all deposit address stable balance, Before the roundIndex @param {obj} conn if conn is null, use db query, otherwise use conn. @param {String} roundIndex @param {function} cb( err, balance ) callback function @return {"base":{"stable":{Integer},"pending":{Integer}}} balance
[ "Get", "all", "deposit", "address", "stable", "balance", "Before", "the", "roundIndex" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/sc/deposit.js#L129-L151
20,712
trustnote/trustnote-pow-common
sc/deposit.js
getDepositAddressBySafeAddress
function getDepositAddressBySafeAddress(conn, safeAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(safeAddress)) return cb("param safeAddress is null or empty string"); if(!validationUtils.isValidAddress(safeAddress)) return cb("param safeAddress is not a valid address"); const arrDefinition = [ 'or', [ ['address', constants.FOUNDATION_SAFE_ADDRESS], ['address', safeAddress], ] ]; const depositAddress = objectHash.getChash160(arrDefinition); conn.query("SELECT definition FROM shared_addresses WHERE shared_address = ?", [depositAddress], function(rows) { if (rows.length !== 1 ) return cb("deposit Address is not found when getDepositAddressBySafeAddress " + safeAddress); cb(null, depositAddress); }); }
javascript
function getDepositAddressBySafeAddress(conn, safeAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(safeAddress)) return cb("param safeAddress is null or empty string"); if(!validationUtils.isValidAddress(safeAddress)) return cb("param safeAddress is not a valid address"); const arrDefinition = [ 'or', [ ['address', constants.FOUNDATION_SAFE_ADDRESS], ['address', safeAddress], ] ]; const depositAddress = objectHash.getChash160(arrDefinition); conn.query("SELECT definition FROM shared_addresses WHERE shared_address = ?", [depositAddress], function(rows) { if (rows.length !== 1 ) return cb("deposit Address is not found when getDepositAddressBySafeAddress " + safeAddress); cb(null, depositAddress); }); }
[ "function", "getDepositAddressBySafeAddress", "(", "conn", ",", "safeAddress", ",", "cb", ")", "{", "var", "conn", "=", "conn", "||", "db", ";", "if", "(", "!", "validationUtils", ".", "isNonemptyString", "(", "safeAddress", ")", ")", "return", "cb", "(", "\"param safeAddress is null or empty string\"", ")", ";", "if", "(", "!", "validationUtils", ".", "isValidAddress", "(", "safeAddress", ")", ")", "return", "cb", "(", "\"param safeAddress is not a valid address\"", ")", ";", "const", "arrDefinition", "=", "[", "'or'", ",", "[", "[", "'address'", ",", "constants", ".", "FOUNDATION_SAFE_ADDRESS", "]", ",", "[", "'address'", ",", "safeAddress", "]", ",", "]", "]", ";", "const", "depositAddress", "=", "objectHash", ".", "getChash160", "(", "arrDefinition", ")", ";", "conn", ".", "query", "(", "\"SELECT definition FROM shared_addresses WHERE shared_address = ?\"", ",", "[", "depositAddress", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "return", "cb", "(", "\"deposit Address is not found when getDepositAddressBySafeAddress \"", "+", "safeAddress", ")", ";", "cb", "(", "null", ",", "depositAddress", ")", ";", "}", ")", ";", "}" ]
Returns deposit address by supernode safe address. @param {obj} conn if conn is null, use db query, otherwise use conn. @param {String} safeAddress @param {function} cb( err, depositAddress ) callback function If address is invalid, then returns err "invalid address". If can not find the address, then returns err "depositAddress not found".
[ "Returns", "deposit", "address", "by", "supernode", "safe", "address", "." ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/sc/deposit.js#L162-L182
20,713
trustnote/trustnote-pow-common
sc/deposit.js
getDepositAddressBySupernodeAddress
function getDepositAddressBySupernodeAddress(conn, supernodeAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(supernodeAddress)) return cb("param supernodeAddress is null or empty string"); if(!validationUtils.isValidAddress(supernodeAddress)) return cb("param supernodeAddress is not a valid address"); conn.query("SELECT deposit_address FROM supernode WHERE address = ?", [supernodeAddress], function(rows) { if (rows.length !== 1 ) return cb("deposit address is not found when getDepositAddressBySupernodeAddress " + supernodeAddress); cb(null, rows[0].deposit_address); }); }
javascript
function getDepositAddressBySupernodeAddress(conn, supernodeAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(supernodeAddress)) return cb("param supernodeAddress is null or empty string"); if(!validationUtils.isValidAddress(supernodeAddress)) return cb("param supernodeAddress is not a valid address"); conn.query("SELECT deposit_address FROM supernode WHERE address = ?", [supernodeAddress], function(rows) { if (rows.length !== 1 ) return cb("deposit address is not found when getDepositAddressBySupernodeAddress " + supernodeAddress); cb(null, rows[0].deposit_address); }); }
[ "function", "getDepositAddressBySupernodeAddress", "(", "conn", ",", "supernodeAddress", ",", "cb", ")", "{", "var", "conn", "=", "conn", "||", "db", ";", "if", "(", "!", "validationUtils", ".", "isNonemptyString", "(", "supernodeAddress", ")", ")", "return", "cb", "(", "\"param supernodeAddress is null or empty string\"", ")", ";", "if", "(", "!", "validationUtils", ".", "isValidAddress", "(", "supernodeAddress", ")", ")", "return", "cb", "(", "\"param supernodeAddress is not a valid address\"", ")", ";", "conn", ".", "query", "(", "\"SELECT deposit_address FROM supernode WHERE address = ?\"", ",", "[", "supernodeAddress", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "return", "cb", "(", "\"deposit address is not found when getDepositAddressBySupernodeAddress \"", "+", "supernodeAddress", ")", ";", "cb", "(", "null", ",", "rows", "[", "0", "]", ".", "deposit_address", ")", ";", "}", ")", ";", "}" ]
Returns deposit address by supernode address. @param {obj} conn if conn is null, use db query, otherwise use conn. @param {String} supernodeAddress @param {function} cb( err, deposit_address ) callback function If depositAddress is invalid, then returns err "invalid address". If can not find the address, then returns err "deposit address not found".
[ "Returns", "deposit", "address", "by", "supernode", "address", "." ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/sc/deposit.js#L193-L206
20,714
trustnote/trustnote-pow-common
sc/deposit.js
getSupernodeByDepositAddress
function getSupernodeByDepositAddress(conn, depositAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(depositAddress)) return cb("param depostiAddress is null or empty string"); if(!validationUtils.isValidAddress(depositAddress)) return cb("param depostiAddress is not a valid address"); conn.query("SELECT address, safe_address FROM supernode WHERE deposit_address = ?", [depositAddress], function(rows) { if (rows.length !== 1 ) return cb("supernodeAddress is not found"); cb(null, rows); }); }
javascript
function getSupernodeByDepositAddress(conn, depositAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(depositAddress)) return cb("param depostiAddress is null or empty string"); if(!validationUtils.isValidAddress(depositAddress)) return cb("param depostiAddress is not a valid address"); conn.query("SELECT address, safe_address FROM supernode WHERE deposit_address = ?", [depositAddress], function(rows) { if (rows.length !== 1 ) return cb("supernodeAddress is not found"); cb(null, rows); }); }
[ "function", "getSupernodeByDepositAddress", "(", "conn", ",", "depositAddress", ",", "cb", ")", "{", "var", "conn", "=", "conn", "||", "db", ";", "if", "(", "!", "validationUtils", ".", "isNonemptyString", "(", "depositAddress", ")", ")", "return", "cb", "(", "\"param depostiAddress is null or empty string\"", ")", ";", "if", "(", "!", "validationUtils", ".", "isValidAddress", "(", "depositAddress", ")", ")", "return", "cb", "(", "\"param depostiAddress is not a valid address\"", ")", ";", "conn", ".", "query", "(", "\"SELECT address, safe_address FROM supernode WHERE deposit_address = ?\"", ",", "[", "depositAddress", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "return", "cb", "(", "\"supernodeAddress is not found\"", ")", ";", "cb", "(", "null", ",", "rows", ")", ";", "}", ")", ";", "}" ]
Returns supernode address by deposit address. @param {obj} conn if conn is null, use db query, otherwise use conn. @param {String} depositAddress @param {function} cb( err, supernodeAddress ) callback function If depositAddress is invalid, then returns err "invalid address". If can not find the address, then returns err "supernodeAddress not found".
[ "Returns", "supernode", "address", "by", "deposit", "address", "." ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/sc/deposit.js#L217-L230
20,715
trustnote/trustnote-pow-common
sc/deposit.js
createDepositAddress
function createDepositAddress(my_address, callback) { var arrDefinition = [ 'or', [ ['address', constants.FOUNDATION_SAFE_ADDRESS], ['address', my_address], ] ]; var shared_address = objectHash.getChash160(arrDefinition) if(isDepositDefinition(arrDefinition)){ return callback.ifOk(shared_address) } else { return callback.ifError(JSON.stringify(arrDefinition) + ' is not a valid deposit definiton') } }
javascript
function createDepositAddress(my_address, callback) { var arrDefinition = [ 'or', [ ['address', constants.FOUNDATION_SAFE_ADDRESS], ['address', my_address], ] ]; var shared_address = objectHash.getChash160(arrDefinition) if(isDepositDefinition(arrDefinition)){ return callback.ifOk(shared_address) } else { return callback.ifError(JSON.stringify(arrDefinition) + ' is not a valid deposit definiton') } }
[ "function", "createDepositAddress", "(", "my_address", ",", "callback", ")", "{", "var", "arrDefinition", "=", "[", "'or'", ",", "[", "[", "'address'", ",", "constants", ".", "FOUNDATION_SAFE_ADDRESS", "]", ",", "[", "'address'", ",", "my_address", "]", ",", "]", "]", ";", "var", "shared_address", "=", "objectHash", ".", "getChash160", "(", "arrDefinition", ")", "if", "(", "isDepositDefinition", "(", "arrDefinition", ")", ")", "{", "return", "callback", ".", "ifOk", "(", "shared_address", ")", "}", "else", "{", "return", "callback", ".", "ifError", "(", "JSON", ".", "stringify", "(", "arrDefinition", ")", "+", "' is not a valid deposit definiton'", ")", "}", "}" ]
Create Deposit Address @param {String} my_address - address that use to generate deposit address @param {Array} arrDefinition - definiton of miner shared address @param {Object} assocSignersByPath - address paths of shared address @param {Function} callback - callback(deposit_address)
[ "Create", "Deposit", "Address" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/sc/deposit.js#L239-L255
20,716
trustnote/trustnote-pow-common
validation/validation_byzantine.js
validateProposalJoint
function validateProposalJoint(objJoint, callbacks){ var objUnit = objJoint.unit; if (typeof objUnit !== "object" || objUnit === null) return callbacks.ifInvalid("no unit object"); console.log("\nvalidating joint identified by unit "+objJoint.unit.unit); if (!isStringOfLength(objUnit.unit, constants.HASH_LENGTH)) return callbacks.ifInvalid("wrong unit length"); // UnitError is linked to objUnit.unit, so we need to ensure objUnit.unit is true before we throw any UnitErrors if (objectHash.getProposalUnitHash(objUnit) !== objUnit.unit){ // console.log("888888888888888888888888--Proposal joint : " + JSON.stringify(objJoint)); return callbacks.ifInvalid("wrong proposal unit hash: "+objectHash.getProposalUnitHash(objUnit)+" != "+objUnit.unit); } if (hasFieldsExcept(objUnit, ["unit", "version", "alt" ,"round_index","pow_type","timestamp", "parent_units", "last_ball", "last_ball_unit", "messages", "hp"])) return callbacks.ifInvalid("unknown fields in nonserial unit"); if (objUnit.version !== constants.version) return callbacks.ifInvalid("wrong version"); if (objUnit.alt !== constants.alt) return callbacks.ifInvalid("wrong alt"); if (typeof objUnit.round_index !== "number") return callbacks.ifInvalid("no round index"); if (typeof objUnit.pow_type !== "number") return callbacks.ifInvalid("no pow_type type"); if (typeof objUnit.hp !== "number") return callbacks.ifInvalid("no hp type"); // pow_type type should be 2 for trustme if ( objUnit.pow_type !== constants.POW_TYPE_TRUSTME) return callbacks.ifInvalid("invalid unit type"); // unity round index should be in range of [1,4204800] if ( objUnit.round_index < 1 || objUnit.round_index > 4204800) return callbacks.ifInvalid("invalid unit round index"); if (!isNonemptyArray(objUnit.messages)) return callbacks.ifInvalid("missing or empty messages array"); // only one 'data_feed' message allowed in trust me units. if (objUnit.messages.length !== 1) return callbacks.ifInvalid("only one message allowed in proposal unit"); // Joint fields validation add last_ball_mci for only proposal joint, used for final trustme unit if (hasFieldsExcept(objJoint, ["unit", "proposer", "phase", "address","last_ball_mci", "idv","vp","isValid","sig"])) return callbacks.ifInvalid("unknown fields in joint unit " + json.stringify(objJoint)); if (typeof objJoint.phase !== "number" || objJoint.phase < 0 ) return callbacks.ifInvalid("joint phase invalid"); if(objJoint.proposer && objJoint.proposer.length !== 1) return callbacks.ifInvalid("multiple proposers are not allowed"); var conn = null; var objValidationState = { }; async.series( [ function(cb){ db.takeConnectionFromPool(function(new_conn){ conn = new_conn; conn.query("BEGIN", function(){cb();}); }); }, function(cb){ //validate roundIndex and hp (mci) to see if I am sync with proposer mci //if not, return -1 to let caller knows . round.getCurrentRoundIndex(conn, function(curRoundIndex){ if(objUnit.round_index < curRoundIndex) return cb("proposer's round_index is too old, curRoundIndex: " + curRoundIndex + " proposer round_index: " +objUnit.round_index ); if(objUnit.round_index > curRoundIndex) return cb({error_code: "unresolved_dependency", errorMessage:"propose round_index is ahead of me , curRoundIndex: " + curRoundIndex + " proposer round_index: " +objUnit.round_index }); storage.getMaxMci(conn,function(curMCI){ if(objUnit.hp < curMCI + 1) // recieve old proposal return cb("proposal hp is old, will discard it"); if(objUnit.hp > curMCI + 1 ) // propose mci is ahead of me return cb({error_code: "unresolved_dependency", errorMessage:"propose mci is ahead of me, will handle it once come up with it " }); cb(); }); }); }, function(cb){ validateParents(conn, objJoint, objValidationState, cb); }, // function(cb){ // profiler.stop('validation-parents'); // profiler.start(); // !objJoint.skiplist_units // ? cb() // : validateSkiplist(conn, objJoint.skiplist_units, cb); // }, function(cb){ // validate proposer ID byzantine.getCoordinators(conn, objUnit.hp, objJoint.phase, function(err, proposer, round_index, witnesses){ if(err) return cb("error occured when getCoordinators err:" + err); if(proposer !== objJoint.proposer[0].address) return cb("proposer incorrect,Expected: "+ proposer +" Actual :" + objJoint.proposer[0].address); if(round_index !== objUnit.round_index) return cb("proposer round_index incorrect ,Expected: "+ round_index +" Actual :" + objUnit.round_index); objValidationState.unit_hash_to_sign = objectHash.getProposalHashToSign(objUnit); //validate proposer signature validateProposer(conn, objJoint.proposer[0], objUnit, objValidationState, cb); }); }, function(cb){ // check timestamp is near to mine in data feed message validateDataFeedMessage(conn, objUnit.messages[0], objUnit, objValidationState, cb); }, ], function(err){ if(!err){ conn.query("COMMIT", function(){ conn.release(); callbacks.ifOk(); }); } else{ //Error occured here conn.query("ROLLBACK", function(){ conn.release(); if (typeof err === "object"){ if (err.error_code === "unresolved_dependency"){ console.log(err.errorMessage); callbacks.ifNeedWaiting(err.errorMessage); } else throw Error("unknown error code"); } else callbacks.ifInvalid(err); }); } } ); // async.series }
javascript
function validateProposalJoint(objJoint, callbacks){ var objUnit = objJoint.unit; if (typeof objUnit !== "object" || objUnit === null) return callbacks.ifInvalid("no unit object"); console.log("\nvalidating joint identified by unit "+objJoint.unit.unit); if (!isStringOfLength(objUnit.unit, constants.HASH_LENGTH)) return callbacks.ifInvalid("wrong unit length"); // UnitError is linked to objUnit.unit, so we need to ensure objUnit.unit is true before we throw any UnitErrors if (objectHash.getProposalUnitHash(objUnit) !== objUnit.unit){ // console.log("888888888888888888888888--Proposal joint : " + JSON.stringify(objJoint)); return callbacks.ifInvalid("wrong proposal unit hash: "+objectHash.getProposalUnitHash(objUnit)+" != "+objUnit.unit); } if (hasFieldsExcept(objUnit, ["unit", "version", "alt" ,"round_index","pow_type","timestamp", "parent_units", "last_ball", "last_ball_unit", "messages", "hp"])) return callbacks.ifInvalid("unknown fields in nonserial unit"); if (objUnit.version !== constants.version) return callbacks.ifInvalid("wrong version"); if (objUnit.alt !== constants.alt) return callbacks.ifInvalid("wrong alt"); if (typeof objUnit.round_index !== "number") return callbacks.ifInvalid("no round index"); if (typeof objUnit.pow_type !== "number") return callbacks.ifInvalid("no pow_type type"); if (typeof objUnit.hp !== "number") return callbacks.ifInvalid("no hp type"); // pow_type type should be 2 for trustme if ( objUnit.pow_type !== constants.POW_TYPE_TRUSTME) return callbacks.ifInvalid("invalid unit type"); // unity round index should be in range of [1,4204800] if ( objUnit.round_index < 1 || objUnit.round_index > 4204800) return callbacks.ifInvalid("invalid unit round index"); if (!isNonemptyArray(objUnit.messages)) return callbacks.ifInvalid("missing or empty messages array"); // only one 'data_feed' message allowed in trust me units. if (objUnit.messages.length !== 1) return callbacks.ifInvalid("only one message allowed in proposal unit"); // Joint fields validation add last_ball_mci for only proposal joint, used for final trustme unit if (hasFieldsExcept(objJoint, ["unit", "proposer", "phase", "address","last_ball_mci", "idv","vp","isValid","sig"])) return callbacks.ifInvalid("unknown fields in joint unit " + json.stringify(objJoint)); if (typeof objJoint.phase !== "number" || objJoint.phase < 0 ) return callbacks.ifInvalid("joint phase invalid"); if(objJoint.proposer && objJoint.proposer.length !== 1) return callbacks.ifInvalid("multiple proposers are not allowed"); var conn = null; var objValidationState = { }; async.series( [ function(cb){ db.takeConnectionFromPool(function(new_conn){ conn = new_conn; conn.query("BEGIN", function(){cb();}); }); }, function(cb){ //validate roundIndex and hp (mci) to see if I am sync with proposer mci //if not, return -1 to let caller knows . round.getCurrentRoundIndex(conn, function(curRoundIndex){ if(objUnit.round_index < curRoundIndex) return cb("proposer's round_index is too old, curRoundIndex: " + curRoundIndex + " proposer round_index: " +objUnit.round_index ); if(objUnit.round_index > curRoundIndex) return cb({error_code: "unresolved_dependency", errorMessage:"propose round_index is ahead of me , curRoundIndex: " + curRoundIndex + " proposer round_index: " +objUnit.round_index }); storage.getMaxMci(conn,function(curMCI){ if(objUnit.hp < curMCI + 1) // recieve old proposal return cb("proposal hp is old, will discard it"); if(objUnit.hp > curMCI + 1 ) // propose mci is ahead of me return cb({error_code: "unresolved_dependency", errorMessage:"propose mci is ahead of me, will handle it once come up with it " }); cb(); }); }); }, function(cb){ validateParents(conn, objJoint, objValidationState, cb); }, // function(cb){ // profiler.stop('validation-parents'); // profiler.start(); // !objJoint.skiplist_units // ? cb() // : validateSkiplist(conn, objJoint.skiplist_units, cb); // }, function(cb){ // validate proposer ID byzantine.getCoordinators(conn, objUnit.hp, objJoint.phase, function(err, proposer, round_index, witnesses){ if(err) return cb("error occured when getCoordinators err:" + err); if(proposer !== objJoint.proposer[0].address) return cb("proposer incorrect,Expected: "+ proposer +" Actual :" + objJoint.proposer[0].address); if(round_index !== objUnit.round_index) return cb("proposer round_index incorrect ,Expected: "+ round_index +" Actual :" + objUnit.round_index); objValidationState.unit_hash_to_sign = objectHash.getProposalHashToSign(objUnit); //validate proposer signature validateProposer(conn, objJoint.proposer[0], objUnit, objValidationState, cb); }); }, function(cb){ // check timestamp is near to mine in data feed message validateDataFeedMessage(conn, objUnit.messages[0], objUnit, objValidationState, cb); }, ], function(err){ if(!err){ conn.query("COMMIT", function(){ conn.release(); callbacks.ifOk(); }); } else{ //Error occured here conn.query("ROLLBACK", function(){ conn.release(); if (typeof err === "object"){ if (err.error_code === "unresolved_dependency"){ console.log(err.errorMessage); callbacks.ifNeedWaiting(err.errorMessage); } else throw Error("unknown error code"); } else callbacks.ifInvalid(err); }); } } ); // async.series }
[ "function", "validateProposalJoint", "(", "objJoint", ",", "callbacks", ")", "{", "var", "objUnit", "=", "objJoint", ".", "unit", ";", "if", "(", "typeof", "objUnit", "!==", "\"object\"", "||", "objUnit", "===", "null", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"no unit object\"", ")", ";", "console", ".", "log", "(", "\"\\nvalidating joint identified by unit \"", "+", "objJoint", ".", "unit", ".", "unit", ")", ";", "if", "(", "!", "isStringOfLength", "(", "objUnit", ".", "unit", ",", "constants", ".", "HASH_LENGTH", ")", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"wrong unit length\"", ")", ";", "// UnitError is linked to objUnit.unit, so we need to ensure objUnit.unit is true before we throw any UnitErrors", "if", "(", "objectHash", ".", "getProposalUnitHash", "(", "objUnit", ")", "!==", "objUnit", ".", "unit", ")", "{", "// console.log(\"888888888888888888888888--Proposal joint : \" + JSON.stringify(objJoint));", "return", "callbacks", ".", "ifInvalid", "(", "\"wrong proposal unit hash: \"", "+", "objectHash", ".", "getProposalUnitHash", "(", "objUnit", ")", "+", "\" != \"", "+", "objUnit", ".", "unit", ")", ";", "}", "if", "(", "hasFieldsExcept", "(", "objUnit", ",", "[", "\"unit\"", ",", "\"version\"", ",", "\"alt\"", ",", "\"round_index\"", ",", "\"pow_type\"", ",", "\"timestamp\"", ",", "\"parent_units\"", ",", "\"last_ball\"", ",", "\"last_ball_unit\"", ",", "\"messages\"", ",", "\"hp\"", "]", ")", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"unknown fields in nonserial unit\"", ")", ";", "if", "(", "objUnit", ".", "version", "!==", "constants", ".", "version", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"wrong version\"", ")", ";", "if", "(", "objUnit", ".", "alt", "!==", "constants", ".", "alt", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"wrong alt\"", ")", ";", "if", "(", "typeof", "objUnit", ".", "round_index", "!==", "\"number\"", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"no round index\"", ")", ";", "if", "(", "typeof", "objUnit", ".", "pow_type", "!==", "\"number\"", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"no pow_type type\"", ")", ";", "if", "(", "typeof", "objUnit", ".", "hp", "!==", "\"number\"", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"no hp type\"", ")", ";", "// pow_type type should be 2 for trustme ", "if", "(", "objUnit", ".", "pow_type", "!==", "constants", ".", "POW_TYPE_TRUSTME", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"invalid unit type\"", ")", ";", "// unity round index should be in range of [1,4204800]", "if", "(", "objUnit", ".", "round_index", "<", "1", "||", "objUnit", ".", "round_index", ">", "4204800", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"invalid unit round index\"", ")", ";", "if", "(", "!", "isNonemptyArray", "(", "objUnit", ".", "messages", ")", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"missing or empty messages array\"", ")", ";", "// only one 'data_feed' message allowed in trust me units.", "if", "(", "objUnit", ".", "messages", ".", "length", "!==", "1", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"only one message allowed in proposal unit\"", ")", ";", "// Joint fields validation add last_ball_mci for only proposal joint, used for final trustme unit", "if", "(", "hasFieldsExcept", "(", "objJoint", ",", "[", "\"unit\"", ",", "\"proposer\"", ",", "\"phase\"", ",", "\"address\"", ",", "\"last_ball_mci\"", ",", "\"idv\"", ",", "\"vp\"", ",", "\"isValid\"", ",", "\"sig\"", "]", ")", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"unknown fields in joint unit \"", "+", "json", ".", "stringify", "(", "objJoint", ")", ")", ";", "if", "(", "typeof", "objJoint", ".", "phase", "!==", "\"number\"", "||", "objJoint", ".", "phase", "<", "0", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"joint phase invalid\"", ")", ";", "if", "(", "objJoint", ".", "proposer", "&&", "objJoint", ".", "proposer", ".", "length", "!==", "1", ")", "return", "callbacks", ".", "ifInvalid", "(", "\"multiple proposers are not allowed\"", ")", ";", "var", "conn", "=", "null", ";", "var", "objValidationState", "=", "{", "}", ";", "async", ".", "series", "(", "[", "function", "(", "cb", ")", "{", "db", ".", "takeConnectionFromPool", "(", "function", "(", "new_conn", ")", "{", "conn", "=", "new_conn", ";", "conn", ".", "query", "(", "\"BEGIN\"", ",", "function", "(", ")", "{", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "function", "(", "cb", ")", "{", "//validate roundIndex and hp (mci) to see if I am sync with proposer mci", "//if not, return -1 to let caller knows .", "round", ".", "getCurrentRoundIndex", "(", "conn", ",", "function", "(", "curRoundIndex", ")", "{", "if", "(", "objUnit", ".", "round_index", "<", "curRoundIndex", ")", "return", "cb", "(", "\"proposer's round_index is too old, curRoundIndex: \"", "+", "curRoundIndex", "+", "\" proposer round_index: \"", "+", "objUnit", ".", "round_index", ")", ";", "if", "(", "objUnit", ".", "round_index", ">", "curRoundIndex", ")", "return", "cb", "(", "{", "error_code", ":", "\"unresolved_dependency\"", ",", "errorMessage", ":", "\"propose round_index is ahead of me , curRoundIndex: \"", "+", "curRoundIndex", "+", "\" proposer round_index: \"", "+", "objUnit", ".", "round_index", "}", ")", ";", "storage", ".", "getMaxMci", "(", "conn", ",", "function", "(", "curMCI", ")", "{", "if", "(", "objUnit", ".", "hp", "<", "curMCI", "+", "1", ")", "// recieve old proposal", "return", "cb", "(", "\"proposal hp is old, will discard it\"", ")", ";", "if", "(", "objUnit", ".", "hp", ">", "curMCI", "+", "1", ")", "// propose mci is ahead of me ", "return", "cb", "(", "{", "error_code", ":", "\"unresolved_dependency\"", ",", "errorMessage", ":", "\"propose mci is ahead of me, will handle it once come up with it \"", "}", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "function", "(", "cb", ")", "{", "validateParents", "(", "conn", ",", "objJoint", ",", "objValidationState", ",", "cb", ")", ";", "}", ",", "// function(cb){", "// \tprofiler.stop('validation-parents');", "// \tprofiler.start();", "// \t!objJoint.skiplist_units", "// \t\t? cb()", "// \t\t: validateSkiplist(conn, objJoint.skiplist_units, cb);", "// },", "function", "(", "cb", ")", "{", "// validate proposer ID", "byzantine", ".", "getCoordinators", "(", "conn", ",", "objUnit", ".", "hp", ",", "objJoint", ".", "phase", ",", "function", "(", "err", ",", "proposer", ",", "round_index", ",", "witnesses", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "\"error occured when getCoordinators err:\"", "+", "err", ")", ";", "if", "(", "proposer", "!==", "objJoint", ".", "proposer", "[", "0", "]", ".", "address", ")", "return", "cb", "(", "\"proposer incorrect,Expected: \"", "+", "proposer", "+", "\" Actual :\"", "+", "objJoint", ".", "proposer", "[", "0", "]", ".", "address", ")", ";", "if", "(", "round_index", "!==", "objUnit", ".", "round_index", ")", "return", "cb", "(", "\"proposer round_index incorrect ,Expected: \"", "+", "round_index", "+", "\" Actual :\"", "+", "objUnit", ".", "round_index", ")", ";", "objValidationState", ".", "unit_hash_to_sign", "=", "objectHash", ".", "getProposalHashToSign", "(", "objUnit", ")", ";", "//validate proposer signature", "validateProposer", "(", "conn", ",", "objJoint", ".", "proposer", "[", "0", "]", ",", "objUnit", ",", "objValidationState", ",", "cb", ")", ";", "}", ")", ";", "}", ",", "function", "(", "cb", ")", "{", "// check timestamp is near to mine in data feed message ", "validateDataFeedMessage", "(", "conn", ",", "objUnit", ".", "messages", "[", "0", "]", ",", "objUnit", ",", "objValidationState", ",", "cb", ")", ";", "}", ",", "]", ",", "function", "(", "err", ")", "{", "if", "(", "!", "err", ")", "{", "conn", ".", "query", "(", "\"COMMIT\"", ",", "function", "(", ")", "{", "conn", ".", "release", "(", ")", ";", "callbacks", ".", "ifOk", "(", ")", ";", "}", ")", ";", "}", "else", "{", "//Error occured here", "conn", ".", "query", "(", "\"ROLLBACK\"", ",", "function", "(", ")", "{", "conn", ".", "release", "(", ")", ";", "if", "(", "typeof", "err", "===", "\"object\"", ")", "{", "if", "(", "err", ".", "error_code", "===", "\"unresolved_dependency\"", ")", "{", "console", ".", "log", "(", "err", ".", "errorMessage", ")", ";", "callbacks", ".", "ifNeedWaiting", "(", "err", ".", "errorMessage", ")", ";", "}", "else", "throw", "Error", "(", "\"unknown error code\"", ")", ";", "}", "else", "callbacks", ".", "ifInvalid", "(", "err", ")", ";", "}", ")", ";", "}", "}", ")", ";", "// async.series", "}" ]
validate proposed value
[ "validate", "proposed", "value" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/validation/validation_byzantine.js#L272-L407
20,717
trustnote/trustnote-pow-common
pow/pow.js
obtainMiningInput
function obtainMiningInput( oConn, uRoundIndex, pfnCallback ) { if ( ! oConn ) { throw new Error( `call obtainMiningInput with invalid oConn.` ); } if ( 'number' !== typeof uRoundIndex ) { throw new Error( `call obtainMiningInput with invalid nRoundIndex.` ); } if ( 'function' !== typeof pfnCallback ) { // arguments.callee.name throw new Error( `call obtainMiningInput with invalid pfnCallback.` ); } let sCurrentFirstTrustMEBall = null; let uCurrentBitsValue = null; let sCurrentPublicSeed = null; let sSuperNodeAuthorAddress = null; let sDepositAddress = null; let fDepositBalance = null; _async.series ([ function( pfnNext ) { // // author address of this super node // _super_node.readSingleAddress( oConn, function( sAddress ) { sSuperNodeAuthorAddress = sAddress; return pfnNext(); }); }, function( pfnNext ) { // // get deposit address by super-node address // _deposit.getDepositAddressBySupernodeAddress( oConn, sSuperNodeAuthorAddress, ( err, sAddress ) => { if ( err ) { return pfnNext( err ); } sDepositAddress = sAddress; return pfnNext(); }); }, function( pfnNext ) { // // get deposit amount by deposit address // _deposit.getBalanceOfDepositContract( oConn, sDepositAddress, uRoundIndex, ( err, fBanlance ) => { if ( err ) { return pfnNext( err ); } fDepositBalance = fBanlance; return pfnNext(); }); }, function( pfnNext ) { // // round (N) // obtain ball address of the first TrustME unit from current round // _round.queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, uRoundIndex, function( err, sBall ) { if ( err ) { return pfnNext( err ); } sCurrentFirstTrustMEBall = sBall; return pfnNext(); }); }, function( pfnNext ) { // // round (N) // calculate public seed // _round.getRoundInfoByRoundIndex( oConn, uRoundIndex, function( round_index, min_wl, sSeed ) { sCurrentPublicSeed = sSeed; return pfnNext(); }); }, // function( pfnNext ) // { // // // // round (N) // // calculate bits value // // // _round.getDifficultydByRoundIndex( oConn, uRoundIndex, function( nBits ) // { // nCurrentBitsValue = nBits; // return pfnNext(); // }); // }, function( pfnNext ) { // // calculate bits value // calculateBitsValueByRoundIndexWithDeposit ( oConn, uRoundIndex, fDepositBalance, ( err, uSelfBits ) => { if ( err ) { return pfnCallback( err ); } // ... uCurrentBitsValue = uSelfBits; return pfnNext(); } ); } ], function( err ) { if ( err ) { return pfnCallback( err ); } let objInput = { roundIndex : uRoundIndex, firstTrustMEBall : sCurrentFirstTrustMEBall, bits : uCurrentBitsValue, deposit : fDepositBalance, publicSeed : sCurrentPublicSeed, superNodeAuthor : sSuperNodeAuthorAddress, }; pfnCallback( null, objInput ); }); return true; }
javascript
function obtainMiningInput( oConn, uRoundIndex, pfnCallback ) { if ( ! oConn ) { throw new Error( `call obtainMiningInput with invalid oConn.` ); } if ( 'number' !== typeof uRoundIndex ) { throw new Error( `call obtainMiningInput with invalid nRoundIndex.` ); } if ( 'function' !== typeof pfnCallback ) { // arguments.callee.name throw new Error( `call obtainMiningInput with invalid pfnCallback.` ); } let sCurrentFirstTrustMEBall = null; let uCurrentBitsValue = null; let sCurrentPublicSeed = null; let sSuperNodeAuthorAddress = null; let sDepositAddress = null; let fDepositBalance = null; _async.series ([ function( pfnNext ) { // // author address of this super node // _super_node.readSingleAddress( oConn, function( sAddress ) { sSuperNodeAuthorAddress = sAddress; return pfnNext(); }); }, function( pfnNext ) { // // get deposit address by super-node address // _deposit.getDepositAddressBySupernodeAddress( oConn, sSuperNodeAuthorAddress, ( err, sAddress ) => { if ( err ) { return pfnNext( err ); } sDepositAddress = sAddress; return pfnNext(); }); }, function( pfnNext ) { // // get deposit amount by deposit address // _deposit.getBalanceOfDepositContract( oConn, sDepositAddress, uRoundIndex, ( err, fBanlance ) => { if ( err ) { return pfnNext( err ); } fDepositBalance = fBanlance; return pfnNext(); }); }, function( pfnNext ) { // // round (N) // obtain ball address of the first TrustME unit from current round // _round.queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, uRoundIndex, function( err, sBall ) { if ( err ) { return pfnNext( err ); } sCurrentFirstTrustMEBall = sBall; return pfnNext(); }); }, function( pfnNext ) { // // round (N) // calculate public seed // _round.getRoundInfoByRoundIndex( oConn, uRoundIndex, function( round_index, min_wl, sSeed ) { sCurrentPublicSeed = sSeed; return pfnNext(); }); }, // function( pfnNext ) // { // // // // round (N) // // calculate bits value // // // _round.getDifficultydByRoundIndex( oConn, uRoundIndex, function( nBits ) // { // nCurrentBitsValue = nBits; // return pfnNext(); // }); // }, function( pfnNext ) { // // calculate bits value // calculateBitsValueByRoundIndexWithDeposit ( oConn, uRoundIndex, fDepositBalance, ( err, uSelfBits ) => { if ( err ) { return pfnCallback( err ); } // ... uCurrentBitsValue = uSelfBits; return pfnNext(); } ); } ], function( err ) { if ( err ) { return pfnCallback( err ); } let objInput = { roundIndex : uRoundIndex, firstTrustMEBall : sCurrentFirstTrustMEBall, bits : uCurrentBitsValue, deposit : fDepositBalance, publicSeed : sCurrentPublicSeed, superNodeAuthor : sSuperNodeAuthorAddress, }; pfnCallback( null, objInput ); }); return true; }
[ "function", "obtainMiningInput", "(", "oConn", ",", "uRoundIndex", ",", "pfnCallback", ")", "{", "if", "(", "!", "oConn", ")", "{", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "if", "(", "'number'", "!==", "typeof", "uRoundIndex", ")", "{", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "if", "(", "'function'", "!==", "typeof", "pfnCallback", ")", "{", "//\targuments.callee.name", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "let", "sCurrentFirstTrustMEBall", "=", "null", ";", "let", "uCurrentBitsValue", "=", "null", ";", "let", "sCurrentPublicSeed", "=", "null", ";", "let", "sSuperNodeAuthorAddress", "=", "null", ";", "let", "sDepositAddress", "=", "null", ";", "let", "fDepositBalance", "=", "null", ";", "_async", ".", "series", "(", "[", "function", "(", "pfnNext", ")", "{", "//", "//\tauthor address of this super node", "//", "_super_node", ".", "readSingleAddress", "(", "oConn", ",", "function", "(", "sAddress", ")", "{", "sSuperNodeAuthorAddress", "=", "sAddress", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "pfnNext", ")", "{", "//", "//\tget deposit address by super-node address", "//", "_deposit", ".", "getDepositAddressBySupernodeAddress", "(", "oConn", ",", "sSuperNodeAuthorAddress", ",", "(", "err", ",", "sAddress", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "pfnNext", "(", "err", ")", ";", "}", "sDepositAddress", "=", "sAddress", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "pfnNext", ")", "{", "//", "//\tget deposit amount by deposit address", "//", "_deposit", ".", "getBalanceOfDepositContract", "(", "oConn", ",", "sDepositAddress", ",", "uRoundIndex", ",", "(", "err", ",", "fBanlance", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "pfnNext", "(", "err", ")", ";", "}", "fDepositBalance", "=", "fBanlance", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "pfnNext", ")", "{", "//", "//\tround (N)", "//\tobtain ball address of the first TrustME unit from current round", "//", "_round", ".", "queryFirstTrustMEBallOnMainChainByRoundIndex", "(", "oConn", ",", "uRoundIndex", ",", "function", "(", "err", ",", "sBall", ")", "{", "if", "(", "err", ")", "{", "return", "pfnNext", "(", "err", ")", ";", "}", "sCurrentFirstTrustMEBall", "=", "sBall", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "pfnNext", ")", "{", "//", "//\tround (N)", "//\tcalculate public seed", "//", "_round", ".", "getRoundInfoByRoundIndex", "(", "oConn", ",", "uRoundIndex", ",", "function", "(", "round_index", ",", "min_wl", ",", "sSeed", ")", "{", "sCurrentPublicSeed", "=", "sSeed", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", ",", "// function( pfnNext )", "// {", "// \t//", "// \t//\tround (N)", "// \t//\tcalculate bits value", "// \t//", "// \t_round.getDifficultydByRoundIndex( oConn, uRoundIndex, function( nBits )", "// \t{", "// \t\tnCurrentBitsValue\t= nBits;", "// \t\treturn pfnNext();", "// \t});", "// },", "function", "(", "pfnNext", ")", "{", "//", "//\tcalculate bits value", "//", "calculateBitsValueByRoundIndexWithDeposit", "(", "oConn", ",", "uRoundIndex", ",", "fDepositBalance", ",", "(", "err", ",", "uSelfBits", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "pfnCallback", "(", "err", ")", ";", "}", "//\t...", "uCurrentBitsValue", "=", "uSelfBits", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "pfnCallback", "(", "err", ")", ";", "}", "let", "objInput", "=", "{", "roundIndex", ":", "uRoundIndex", ",", "firstTrustMEBall", ":", "sCurrentFirstTrustMEBall", ",", "bits", ":", "uCurrentBitsValue", ",", "deposit", ":", "fDepositBalance", ",", "publicSeed", ":", "sCurrentPublicSeed", ",", "superNodeAuthor", ":", "sSuperNodeAuthorAddress", ",", "}", ";", "pfnCallback", "(", "null", ",", "objInput", ")", ";", "}", ")", ";", "return", "true", ";", "}" ]
obtain mining input @param {handle} oConn @param {function} oConn.query @param {number} uRoundIndex @param {function} pfnCallback( err ) @return {boolean} @description start successfully pfnCallback( null, objInput ); failed to start pfnCallback( error );
[ "obtain", "mining", "input" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow.js#L235-L386
20,718
trustnote/trustnote-pow-common
pow/pow.js
startMiningWithInputs
function startMiningWithInputs( oInput, pfnCallback ) { console.log( `>***< will start mining with inputs : ${ JSON.stringify( oInput ) }` ); if ( _bBrowser && ! _bWallet ) { throw new Error( 'I am not be able to run in a Web Browser.' ); } if ( 'object' !== typeof oInput ) { throw new Error( 'call startMiningWithInputs with invalid oInput' ); } if ( 'number' !== typeof oInput.roundIndex ) { throw new Error( 'call startMiningWithInputs with invalid oInput.roundIndex' ); } if ( 'string' !== typeof oInput.firstTrustMEBall || 44 !== oInput.firstTrustMEBall.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.firstTrustMEBall' ); } if ( 'number' !== typeof oInput.bits || oInput.bits < 0 ) { throw new Error( 'call startMiningWithInputs with invalid oInput.bits' ); } if ( 'string' !== typeof oInput.publicSeed || 0 === oInput.publicSeed.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.publicSeed' ); } if ( 'string' !== typeof oInput.superNodeAuthor || 0 === oInput.superNodeAuthor.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.superNodeAuthor' ); } if ( 'function' !== typeof pfnCallback ) { throw new Error( `call startMiningWithInputs with invalid pfnCallback.` ); } if ( _bDebugModel && ! _bUnitTestEnv ) { return _startMiningWithInputs_debug( oInput, pfnCallback ); } /** * start here */ let _oOptions = { bufInputHeader : _createMiningInputBufferFromObject( oInput ), bits : oInput.bits, calcTimes : ( 'number' === typeof oInput.calcTimes ? oInput.calcTimes : 30 ), maxLoop : ( 'number' === typeof oInput.maxLoop ? oInput.maxLoop : 1000000 ), }; console.log( `))) stopMining.` ); _pow_miner.stopMining(); console.log( `))) startMining with options : `, _oOptions ); _pow_miner.startMining( _oOptions, function( err, oData ) { let objSolution = null; if ( null === err ) { console.log( `))) startMining, callback data( ${ typeof oData } ) : `, oData ); if ( oData && 'object' === typeof oData ) { if ( oData.hasOwnProperty( 'win' ) && oData.win ) { console.log( `pow-solution :: WINNER WINNER, CHICKEN DINNER!`, oData ); objSolution = { round : oInput.roundIndex, selfBits : oInput.bits, publicSeed : oInput.publicSeed, nonce : oData.nonce, hash : oData.hashHex }; } else if ( oData.hasOwnProperty( 'gameOver' ) && oData.gameOver ) { err = `pow-solution :: game over!`; } else { err = `pow-solution :: unknown error!`; } } else { err = `pow-solution :: invalid data!`; } } // ... _event_bus.emit( 'pow_mined_gift', err, objSolution ); }); pfnCallback( null ); return true; }
javascript
function startMiningWithInputs( oInput, pfnCallback ) { console.log( `>***< will start mining with inputs : ${ JSON.stringify( oInput ) }` ); if ( _bBrowser && ! _bWallet ) { throw new Error( 'I am not be able to run in a Web Browser.' ); } if ( 'object' !== typeof oInput ) { throw new Error( 'call startMiningWithInputs with invalid oInput' ); } if ( 'number' !== typeof oInput.roundIndex ) { throw new Error( 'call startMiningWithInputs with invalid oInput.roundIndex' ); } if ( 'string' !== typeof oInput.firstTrustMEBall || 44 !== oInput.firstTrustMEBall.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.firstTrustMEBall' ); } if ( 'number' !== typeof oInput.bits || oInput.bits < 0 ) { throw new Error( 'call startMiningWithInputs with invalid oInput.bits' ); } if ( 'string' !== typeof oInput.publicSeed || 0 === oInput.publicSeed.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.publicSeed' ); } if ( 'string' !== typeof oInput.superNodeAuthor || 0 === oInput.superNodeAuthor.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.superNodeAuthor' ); } if ( 'function' !== typeof pfnCallback ) { throw new Error( `call startMiningWithInputs with invalid pfnCallback.` ); } if ( _bDebugModel && ! _bUnitTestEnv ) { return _startMiningWithInputs_debug( oInput, pfnCallback ); } /** * start here */ let _oOptions = { bufInputHeader : _createMiningInputBufferFromObject( oInput ), bits : oInput.bits, calcTimes : ( 'number' === typeof oInput.calcTimes ? oInput.calcTimes : 30 ), maxLoop : ( 'number' === typeof oInput.maxLoop ? oInput.maxLoop : 1000000 ), }; console.log( `))) stopMining.` ); _pow_miner.stopMining(); console.log( `))) startMining with options : `, _oOptions ); _pow_miner.startMining( _oOptions, function( err, oData ) { let objSolution = null; if ( null === err ) { console.log( `))) startMining, callback data( ${ typeof oData } ) : `, oData ); if ( oData && 'object' === typeof oData ) { if ( oData.hasOwnProperty( 'win' ) && oData.win ) { console.log( `pow-solution :: WINNER WINNER, CHICKEN DINNER!`, oData ); objSolution = { round : oInput.roundIndex, selfBits : oInput.bits, publicSeed : oInput.publicSeed, nonce : oData.nonce, hash : oData.hashHex }; } else if ( oData.hasOwnProperty( 'gameOver' ) && oData.gameOver ) { err = `pow-solution :: game over!`; } else { err = `pow-solution :: unknown error!`; } } else { err = `pow-solution :: invalid data!`; } } // ... _event_bus.emit( 'pow_mined_gift', err, objSolution ); }); pfnCallback( null ); return true; }
[ "function", "startMiningWithInputs", "(", "oInput", ",", "pfnCallback", ")", "{", "console", ".", "log", "(", "`", "${", "JSON", ".", "stringify", "(", "oInput", ")", "}", "`", ")", ";", "if", "(", "_bBrowser", "&&", "!", "_bWallet", ")", "{", "throw", "new", "Error", "(", "'I am not be able to run in a Web Browser.'", ")", ";", "}", "if", "(", "'object'", "!==", "typeof", "oInput", ")", "{", "throw", "new", "Error", "(", "'call startMiningWithInputs with invalid oInput'", ")", ";", "}", "if", "(", "'number'", "!==", "typeof", "oInput", ".", "roundIndex", ")", "{", "throw", "new", "Error", "(", "'call startMiningWithInputs with invalid oInput.roundIndex'", ")", ";", "}", "if", "(", "'string'", "!==", "typeof", "oInput", ".", "firstTrustMEBall", "||", "44", "!==", "oInput", ".", "firstTrustMEBall", ".", "length", ")", "{", "throw", "new", "Error", "(", "'call startMiningWithInputs with invalid oInput.firstTrustMEBall'", ")", ";", "}", "if", "(", "'number'", "!==", "typeof", "oInput", ".", "bits", "||", "oInput", ".", "bits", "<", "0", ")", "{", "throw", "new", "Error", "(", "'call startMiningWithInputs with invalid oInput.bits'", ")", ";", "}", "if", "(", "'string'", "!==", "typeof", "oInput", ".", "publicSeed", "||", "0", "===", "oInput", ".", "publicSeed", ".", "length", ")", "{", "throw", "new", "Error", "(", "'call startMiningWithInputs with invalid oInput.publicSeed'", ")", ";", "}", "if", "(", "'string'", "!==", "typeof", "oInput", ".", "superNodeAuthor", "||", "0", "===", "oInput", ".", "superNodeAuthor", ".", "length", ")", "{", "throw", "new", "Error", "(", "'call startMiningWithInputs with invalid oInput.superNodeAuthor'", ")", ";", "}", "if", "(", "'function'", "!==", "typeof", "pfnCallback", ")", "{", "throw", "new", "Error", "(", "`", "`", ")", ";", "}", "if", "(", "_bDebugModel", "&&", "!", "_bUnitTestEnv", ")", "{", "return", "_startMiningWithInputs_debug", "(", "oInput", ",", "pfnCallback", ")", ";", "}", "/**\n\t *\tstart here\n\t */", "let", "_oOptions", "=", "{", "bufInputHeader", ":", "_createMiningInputBufferFromObject", "(", "oInput", ")", ",", "bits", ":", "oInput", ".", "bits", ",", "calcTimes", ":", "(", "'number'", "===", "typeof", "oInput", ".", "calcTimes", "?", "oInput", ".", "calcTimes", ":", "30", ")", ",", "maxLoop", ":", "(", "'number'", "===", "typeof", "oInput", ".", "maxLoop", "?", "oInput", ".", "maxLoop", ":", "1000000", ")", ",", "}", ";", "console", ".", "log", "(", "`", "`", ")", ";", "_pow_miner", ".", "stopMining", "(", ")", ";", "console", ".", "log", "(", "`", "`", ",", "_oOptions", ")", ";", "_pow_miner", ".", "startMining", "(", "_oOptions", ",", "function", "(", "err", ",", "oData", ")", "{", "let", "objSolution", "=", "null", ";", "if", "(", "null", "===", "err", ")", "{", "console", ".", "log", "(", "`", "${", "typeof", "oData", "}", "`", ",", "oData", ")", ";", "if", "(", "oData", "&&", "'object'", "===", "typeof", "oData", ")", "{", "if", "(", "oData", ".", "hasOwnProperty", "(", "'win'", ")", "&&", "oData", ".", "win", ")", "{", "console", ".", "log", "(", "`", "`", ",", "oData", ")", ";", "objSolution", "=", "{", "round", ":", "oInput", ".", "roundIndex", ",", "selfBits", ":", "oInput", ".", "bits", ",", "publicSeed", ":", "oInput", ".", "publicSeed", ",", "nonce", ":", "oData", ".", "nonce", ",", "hash", ":", "oData", ".", "hashHex", "}", ";", "}", "else", "if", "(", "oData", ".", "hasOwnProperty", "(", "'gameOver'", ")", "&&", "oData", ".", "gameOver", ")", "{", "err", "=", "`", "`", ";", "}", "else", "{", "err", "=", "`", "`", ";", "}", "}", "else", "{", "err", "=", "`", "`", ";", "}", "}", "//\t...", "_event_bus", ".", "emit", "(", "'pow_mined_gift'", ",", "err", ",", "objSolution", ")", ";", "}", ")", ";", "pfnCallback", "(", "null", ")", ";", "return", "true", ";", "}" ]
start calculation with inputs @param {object} oInput @param {number} oInput.roundIndex @param {string} oInput.firstTrustMEBall @param {string} oInput.bits @param {string} oInput.publicSeed @param {string} oInput.superNodeAuthor @param {function} pfnCallback( err ) will be called immediately while we start mining @return {boolean} @events 'pow_mined_gift' will post solution object through event bus while mining successfully [parameters] err - null if no error, otherwise a string contains error description, objSolution - solution object { round : oInput.roundIndex, bits : oInput.bits, publicSeed : oInput.publicSeed, nonce : oData.nonce, hash : oData.hashHex };
[ "start", "calculation", "with", "inputs" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow.js#L418-L515
20,719
trustnote/trustnote-pow-common
pow/pow.js
calculatePublicSeedByRoundIndex
function calculatePublicSeedByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call calculatePublicSeedByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex ) { return pfnCallback( `call calculatePublicSeedByRoundIndex with invalid nRoundIndex` ); } if ( nRoundIndex <= 1 ) { // // round 1 // hard code // return pfnCallback( null, _blakejs.blake2sHex( _constants.GENESIS_UNIT ) ); } let sPreviousPublicSeed = null; let arrPrePreviousCoinBase = null; let sPreviousTrustMEBall = null; _async.series ([ function( pfnNext ) { // public seed queryPublicSeedByRoundIndex( oConn, nRoundIndex - 1, function( err, sSeed ) { if ( err ) { return pfnNext( err ); } if ( 'string' !== typeof sSeed || 0 === sSeed.length ) { return pfnNext( `calculatePublicSeedByRoundIndex got invalid sSeed.` ); } sPreviousPublicSeed = sSeed; return pfnNext(); } ); }, function( pfnNext ) { // coin base if ( 2 === nRoundIndex ) { arrPrePreviousCoinBase = []; return pfnNext(); } // ... _round.queryCoinBaseListByRoundIndex( oConn, nRoundIndex - 1, function( err, arrCoinBaseList ) { if ( err ) { return pfnNext( err ); } if ( ! Array.isArray( arrCoinBaseList ) ) { return pfnNext( 'empty coin base list' ); } if ( _constants.COUNT_WITNESSES !== arrCoinBaseList.length ) { return pfnNext( 'no enough coin base units.' ); } arrPrePreviousCoinBase = arrCoinBaseList; return pfnNext(); } ); }, function( pfnNext ) { // first ball _round.queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, nRoundIndex - 1, function( err, sBall ) { if ( err ) { return pfnNext( err ); } if ( 'string' !== typeof sBall || 0 === sBall.length ) { return pfnNext( `calculatePublicSeedByRoundIndex got invalid sBall.` ); } sPreviousTrustMEBall = sBall; return pfnNext(); } ); } ], function( err ) { if ( err ) { return pfnCallback( err ); } // ... let sSource = "" + sPreviousPublicSeed + _crypto.createHash( 'sha512' ).update( JSON.stringify( arrPrePreviousCoinBase ), 'utf8' ).digest(); + _crypto.createHash( 'sha512' ).update( sPreviousTrustMEBall, 'utf8' ).digest(); pfnCallback( null, _blakejs.blake2sHex( sSource ) ); }); }
javascript
function calculatePublicSeedByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call calculatePublicSeedByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex ) { return pfnCallback( `call calculatePublicSeedByRoundIndex with invalid nRoundIndex` ); } if ( nRoundIndex <= 1 ) { // // round 1 // hard code // return pfnCallback( null, _blakejs.blake2sHex( _constants.GENESIS_UNIT ) ); } let sPreviousPublicSeed = null; let arrPrePreviousCoinBase = null; let sPreviousTrustMEBall = null; _async.series ([ function( pfnNext ) { // public seed queryPublicSeedByRoundIndex( oConn, nRoundIndex - 1, function( err, sSeed ) { if ( err ) { return pfnNext( err ); } if ( 'string' !== typeof sSeed || 0 === sSeed.length ) { return pfnNext( `calculatePublicSeedByRoundIndex got invalid sSeed.` ); } sPreviousPublicSeed = sSeed; return pfnNext(); } ); }, function( pfnNext ) { // coin base if ( 2 === nRoundIndex ) { arrPrePreviousCoinBase = []; return pfnNext(); } // ... _round.queryCoinBaseListByRoundIndex( oConn, nRoundIndex - 1, function( err, arrCoinBaseList ) { if ( err ) { return pfnNext( err ); } if ( ! Array.isArray( arrCoinBaseList ) ) { return pfnNext( 'empty coin base list' ); } if ( _constants.COUNT_WITNESSES !== arrCoinBaseList.length ) { return pfnNext( 'no enough coin base units.' ); } arrPrePreviousCoinBase = arrCoinBaseList; return pfnNext(); } ); }, function( pfnNext ) { // first ball _round.queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, nRoundIndex - 1, function( err, sBall ) { if ( err ) { return pfnNext( err ); } if ( 'string' !== typeof sBall || 0 === sBall.length ) { return pfnNext( `calculatePublicSeedByRoundIndex got invalid sBall.` ); } sPreviousTrustMEBall = sBall; return pfnNext(); } ); } ], function( err ) { if ( err ) { return pfnCallback( err ); } // ... let sSource = "" + sPreviousPublicSeed + _crypto.createHash( 'sha512' ).update( JSON.stringify( arrPrePreviousCoinBase ), 'utf8' ).digest(); + _crypto.createHash( 'sha512' ).update( sPreviousTrustMEBall, 'utf8' ).digest(); pfnCallback( null, _blakejs.blake2sHex( sSource ) ); }); }
[ "function", "calculatePublicSeedByRoundIndex", "(", "oConn", ",", "nRoundIndex", ",", "pfnCallback", ")", "{", "if", "(", "!", "oConn", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "if", "(", "'number'", "!==", "typeof", "nRoundIndex", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "if", "(", "nRoundIndex", "<=", "1", ")", "{", "//", "//\tround 1", "//\t\thard code", "//", "return", "pfnCallback", "(", "null", ",", "_blakejs", ".", "blake2sHex", "(", "_constants", ".", "GENESIS_UNIT", ")", ")", ";", "}", "let", "sPreviousPublicSeed", "=", "null", ";", "let", "arrPrePreviousCoinBase", "=", "null", ";", "let", "sPreviousTrustMEBall", "=", "null", ";", "_async", ".", "series", "(", "[", "function", "(", "pfnNext", ")", "{", "//\tpublic seed", "queryPublicSeedByRoundIndex", "(", "oConn", ",", "nRoundIndex", "-", "1", ",", "function", "(", "err", ",", "sSeed", ")", "{", "if", "(", "err", ")", "{", "return", "pfnNext", "(", "err", ")", ";", "}", "if", "(", "'string'", "!==", "typeof", "sSeed", "||", "0", "===", "sSeed", ".", "length", ")", "{", "return", "pfnNext", "(", "`", "`", ")", ";", "}", "sPreviousPublicSeed", "=", "sSeed", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "pfnNext", ")", "{", "//\tcoin base", "if", "(", "2", "===", "nRoundIndex", ")", "{", "arrPrePreviousCoinBase", "=", "[", "]", ";", "return", "pfnNext", "(", ")", ";", "}", "//\t...", "_round", ".", "queryCoinBaseListByRoundIndex", "(", "oConn", ",", "nRoundIndex", "-", "1", ",", "function", "(", "err", ",", "arrCoinBaseList", ")", "{", "if", "(", "err", ")", "{", "return", "pfnNext", "(", "err", ")", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "arrCoinBaseList", ")", ")", "{", "return", "pfnNext", "(", "'empty coin base list'", ")", ";", "}", "if", "(", "_constants", ".", "COUNT_WITNESSES", "!==", "arrCoinBaseList", ".", "length", ")", "{", "return", "pfnNext", "(", "'no enough coin base units.'", ")", ";", "}", "arrPrePreviousCoinBase", "=", "arrCoinBaseList", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "pfnNext", ")", "{", "//\tfirst ball", "_round", ".", "queryFirstTrustMEBallOnMainChainByRoundIndex", "(", "oConn", ",", "nRoundIndex", "-", "1", ",", "function", "(", "err", ",", "sBall", ")", "{", "if", "(", "err", ")", "{", "return", "pfnNext", "(", "err", ")", ";", "}", "if", "(", "'string'", "!==", "typeof", "sBall", "||", "0", "===", "sBall", ".", "length", ")", "{", "return", "pfnNext", "(", "`", "`", ")", ";", "}", "sPreviousTrustMEBall", "=", "sBall", ";", "return", "pfnNext", "(", ")", ";", "}", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "pfnCallback", "(", "err", ")", ";", "}", "//\t...", "let", "sSource", "=", "\"\"", "+", "sPreviousPublicSeed", "+", "_crypto", ".", "createHash", "(", "'sha512'", ")", ".", "update", "(", "JSON", ".", "stringify", "(", "arrPrePreviousCoinBase", ")", ",", "'utf8'", ")", ".", "digest", "(", ")", ";", "+", "_crypto", ".", "createHash", "(", "'sha512'", ")", ".", "update", "(", "sPreviousTrustMEBall", ",", "'utf8'", ")", ".", "digest", "(", ")", ";", "pfnCallback", "(", "null", ",", "_blakejs", ".", "blake2sHex", "(", "sSource", ")", ")", ";", "}", ")", ";", "}" ]
calculate public seed by round index @param {handle} oConn @param {function} oConn.query @param {number} nRoundIndex round 1 hard code round 2 previous seed [] TrustME Ball round 3 previous seed [] TrustME Ball @param {function} pfnCallback( err, sSeed ) @documentation https://github.com/trustnote/document/blob/master/TrustNote-TR-2018-02.md#PoW-Unit pubSeed(i) = blake2s256 ( pubSeed(i-1) + hash( Coin-base(i-2) ) + hash( FirstStableMCUnit(i-1) ) )
[ "calculate", "public", "seed", "by", "round", "index" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow.js#L675-L780
20,720
trustnote/trustnote-pow-common
pow/pow.js
queryPublicSeedByRoundIndex
function queryPublicSeedByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryPublicSeedByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex || nRoundIndex <= 0 ) { return pfnCallback( `call queryPublicSeedByRoundIndex with invalid nRoundIndex` ); } oConn.query ( "SELECT seed \ FROM round \ WHERE round_index = ?", [ nRoundIndex ], function( arrRows ) { if ( 0 === arrRows.length ) { return pfnCallback( `seed not found.` ); } return pfnCallback( null, arrRows[ 0 ][ 'seed' ] ); } ); }
javascript
function queryPublicSeedByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryPublicSeedByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex || nRoundIndex <= 0 ) { return pfnCallback( `call queryPublicSeedByRoundIndex with invalid nRoundIndex` ); } oConn.query ( "SELECT seed \ FROM round \ WHERE round_index = ?", [ nRoundIndex ], function( arrRows ) { if ( 0 === arrRows.length ) { return pfnCallback( `seed not found.` ); } return pfnCallback( null, arrRows[ 0 ][ 'seed' ] ); } ); }
[ "function", "queryPublicSeedByRoundIndex", "(", "oConn", ",", "nRoundIndex", ",", "pfnCallback", ")", "{", "if", "(", "!", "oConn", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "if", "(", "'number'", "!==", "typeof", "nRoundIndex", "||", "nRoundIndex", "<=", "0", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "oConn", ".", "query", "(", "\"SELECT seed \\\n\t\tFROM round \\\n\t\tWHERE round_index = ?\"", ",", "[", "nRoundIndex", "]", ",", "function", "(", "arrRows", ")", "{", "if", "(", "0", "===", "arrRows", ".", "length", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "return", "pfnCallback", "(", "null", ",", "arrRows", "[", "0", "]", "[", "'seed'", "]", ")", ";", "}", ")", ";", "}" ]
get public seed by round index @param {handle} oConn @param {function} oConn.query @param {number} nRoundIndex @param {function} pfnCallback( err, arrCoinBaseList )
[ "get", "public", "seed", "by", "round", "index" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow.js#L791-L820
20,721
trustnote/trustnote-pow-common
pow/pow.js
queryBitsValueByCycleIndex
function queryBitsValueByCycleIndex( oConn, uCycleIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryBitsValueByCycleIndex with invalid oConn` ); } if ( 'number' !== typeof uCycleIndex || uCycleIndex <= 0 ) { return pfnCallback( `call queryBitsValueByCycleIndex with invalid uCycleIndex` ); } oConn.query ( "SELECT bits \ FROM round_cycle \ WHERE cycle_id = ?", [ _round.getCycleIdByRoundIndex( uCycleIndex ) ], function( arrRows ) { if ( 0 === arrRows.length ) { return pfnCallback( `bits not found in table [round_cycle].` ); } return pfnCallback( null, parseInt( arrRows[ 0 ][ 'bits' ] ) ); } ); }
javascript
function queryBitsValueByCycleIndex( oConn, uCycleIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryBitsValueByCycleIndex with invalid oConn` ); } if ( 'number' !== typeof uCycleIndex || uCycleIndex <= 0 ) { return pfnCallback( `call queryBitsValueByCycleIndex with invalid uCycleIndex` ); } oConn.query ( "SELECT bits \ FROM round_cycle \ WHERE cycle_id = ?", [ _round.getCycleIdByRoundIndex( uCycleIndex ) ], function( arrRows ) { if ( 0 === arrRows.length ) { return pfnCallback( `bits not found in table [round_cycle].` ); } return pfnCallback( null, parseInt( arrRows[ 0 ][ 'bits' ] ) ); } ); }
[ "function", "queryBitsValueByCycleIndex", "(", "oConn", ",", "uCycleIndex", ",", "pfnCallback", ")", "{", "if", "(", "!", "oConn", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "if", "(", "'number'", "!==", "typeof", "uCycleIndex", "||", "uCycleIndex", "<=", "0", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "oConn", ".", "query", "(", "\"SELECT bits \\\n\t\tFROM round_cycle \\\n\t\tWHERE cycle_id = ?\"", ",", "[", "_round", ".", "getCycleIdByRoundIndex", "(", "uCycleIndex", ")", "]", ",", "function", "(", "arrRows", ")", "{", "if", "(", "0", "===", "arrRows", ".", "length", ")", "{", "return", "pfnCallback", "(", "`", "`", ")", ";", "}", "return", "pfnCallback", "(", "null", ",", "parseInt", "(", "arrRows", "[", "0", "]", "[", "'bits'", "]", ")", ")", ";", "}", ")", ";", "}" ]
query bits value by round index from database @param {handle} oConn @param {function} oConn.query @param {number} uCycleIndex @param {function} pfnCallback( err, nBitsValue )
[ "query", "bits", "value", "by", "round", "index", "from", "database" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow.js#L831-L860
20,722
trustnote/trustnote-pow-common
pow/pow.js
_createMiningInputBufferFromObject
function _createMiningInputBufferFromObject( objInput ) { let objInputCpy; let sInput; let bufSha512; let bufMd5; let bufRmd160; let bufSha384; if ( 'object' !== typeof objInput ) { return null; } // ... objInputCpy = { roundIndex : objInput.roundIndex, firstTrustMEBall : objInput.firstTrustMEBall, bits : objInput.bits, publicSeed : objInput.publicSeed, superNodeAuthor : objInput.superNodeAuthor, }; sInput = JSON.stringify( objInputCpy ); bufSha512 = _crypto.createHash( 'sha512' ).update( sInput, 'utf8' ).digest(); bufMd5 = _crypto.createHash( 'md5' ).update( sInput, 'utf8' ).digest(); bufRmd160 = _crypto.createHash( 'rmd160' ).update( sInput, 'utf8' ).digest(); bufSha384 = _crypto.createHash( 'sha384' ).update( sInput, 'utf8' ).digest(); return Buffer.concat( [ bufSha512, bufMd5, bufRmd160, bufSha384 ], 140 ); }
javascript
function _createMiningInputBufferFromObject( objInput ) { let objInputCpy; let sInput; let bufSha512; let bufMd5; let bufRmd160; let bufSha384; if ( 'object' !== typeof objInput ) { return null; } // ... objInputCpy = { roundIndex : objInput.roundIndex, firstTrustMEBall : objInput.firstTrustMEBall, bits : objInput.bits, publicSeed : objInput.publicSeed, superNodeAuthor : objInput.superNodeAuthor, }; sInput = JSON.stringify( objInputCpy ); bufSha512 = _crypto.createHash( 'sha512' ).update( sInput, 'utf8' ).digest(); bufMd5 = _crypto.createHash( 'md5' ).update( sInput, 'utf8' ).digest(); bufRmd160 = _crypto.createHash( 'rmd160' ).update( sInput, 'utf8' ).digest(); bufSha384 = _crypto.createHash( 'sha384' ).update( sInput, 'utf8' ).digest(); return Buffer.concat( [ bufSha512, bufMd5, bufRmd160, bufSha384 ], 140 ); }
[ "function", "_createMiningInputBufferFromObject", "(", "objInput", ")", "{", "let", "objInputCpy", ";", "let", "sInput", ";", "let", "bufSha512", ";", "let", "bufMd5", ";", "let", "bufRmd160", ";", "let", "bufSha384", ";", "if", "(", "'object'", "!==", "typeof", "objInput", ")", "{", "return", "null", ";", "}", "//\t...", "objInputCpy", "=", "{", "roundIndex", ":", "objInput", ".", "roundIndex", ",", "firstTrustMEBall", ":", "objInput", ".", "firstTrustMEBall", ",", "bits", ":", "objInput", ".", "bits", ",", "publicSeed", ":", "objInput", ".", "publicSeed", ",", "superNodeAuthor", ":", "objInput", ".", "superNodeAuthor", ",", "}", ";", "sInput", "=", "JSON", ".", "stringify", "(", "objInputCpy", ")", ";", "bufSha512", "=", "_crypto", ".", "createHash", "(", "'sha512'", ")", ".", "update", "(", "sInput", ",", "'utf8'", ")", ".", "digest", "(", ")", ";", "bufMd5", "=", "_crypto", ".", "createHash", "(", "'md5'", ")", ".", "update", "(", "sInput", ",", "'utf8'", ")", ".", "digest", "(", ")", ";", "bufRmd160", "=", "_crypto", ".", "createHash", "(", "'rmd160'", ")", ".", "update", "(", "sInput", ",", "'utf8'", ")", ".", "digest", "(", ")", ";", "bufSha384", "=", "_crypto", ".", "createHash", "(", "'sha384'", ")", ".", "update", "(", "sInput", ",", "'utf8'", ")", ".", "digest", "(", ")", ";", "return", "Buffer", ".", "concat", "(", "[", "bufSha512", ",", "bufMd5", ",", "bufRmd160", ",", "bufSha384", "]", ",", "140", ")", ";", "}" ]
create an input buffer with length of 140 from Js plain object @public @param {object} objInput @return {Buffer}
[ "create", "an", "input", "buffer", "with", "length", "of", "140", "from", "Js", "plain", "object" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow.js#L1226-L1255
20,723
trustnote/trustnote-pow-common
pow/pow.js
_generateRandomInteger
function _generateRandomInteger( nMin, nMax ) { return Math.floor( Math.random() * ( nMax + 1 - nMin ) ) + nMin; }
javascript
function _generateRandomInteger( nMin, nMax ) { return Math.floor( Math.random() * ( nMax + 1 - nMin ) ) + nMin; }
[ "function", "_generateRandomInteger", "(", "nMin", ",", "nMax", ")", "{", "return", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "(", "nMax", "+", "1", "-", "nMin", ")", ")", "+", "nMin", ";", "}" ]
generate random integer @private @param {number} nMin @param {number} nMax @returns {*}
[ "generate", "random", "integer" ]
582965aee4cf98ad15188bfa2392f01b86fe8683
https://github.com/trustnote/trustnote-pow-common/blob/582965aee4cf98ad15188bfa2392f01b86fe8683/pow/pow.js#L1266-L1269
20,724
ethereumjs/ethereumjs-block
header-from-rpc.js
blockHeaderFromRpc
function blockHeaderFromRpc (blockParams) { const blockHeader = new BlockHeader({ parentHash: blockParams.parentHash, uncleHash: blockParams.sha3Uncles, coinbase: blockParams.miner, stateRoot: blockParams.stateRoot, transactionsTrie: blockParams.transactionsRoot, receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || ethUtil.SHA3_NULL, bloom: blockParams.logsBloom, difficulty: blockParams.difficulty, number: blockParams.number, gasLimit: blockParams.gasLimit, gasUsed: blockParams.gasUsed, timestamp: blockParams.timestamp, extraData: blockParams.extraData, mixHash: blockParams.mixHash, nonce: blockParams.nonce }) // override hash incase something was missing blockHeader.hash = function () { return ethUtil.toBuffer(blockParams.hash) } return blockHeader }
javascript
function blockHeaderFromRpc (blockParams) { const blockHeader = new BlockHeader({ parentHash: blockParams.parentHash, uncleHash: blockParams.sha3Uncles, coinbase: blockParams.miner, stateRoot: blockParams.stateRoot, transactionsTrie: blockParams.transactionsRoot, receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || ethUtil.SHA3_NULL, bloom: blockParams.logsBloom, difficulty: blockParams.difficulty, number: blockParams.number, gasLimit: blockParams.gasLimit, gasUsed: blockParams.gasUsed, timestamp: blockParams.timestamp, extraData: blockParams.extraData, mixHash: blockParams.mixHash, nonce: blockParams.nonce }) // override hash incase something was missing blockHeader.hash = function () { return ethUtil.toBuffer(blockParams.hash) } return blockHeader }
[ "function", "blockHeaderFromRpc", "(", "blockParams", ")", "{", "const", "blockHeader", "=", "new", "BlockHeader", "(", "{", "parentHash", ":", "blockParams", ".", "parentHash", ",", "uncleHash", ":", "blockParams", ".", "sha3Uncles", ",", "coinbase", ":", "blockParams", ".", "miner", ",", "stateRoot", ":", "blockParams", ".", "stateRoot", ",", "transactionsTrie", ":", "blockParams", ".", "transactionsRoot", ",", "receiptTrie", ":", "blockParams", ".", "receiptRoot", "||", "blockParams", ".", "receiptsRoot", "||", "ethUtil", ".", "SHA3_NULL", ",", "bloom", ":", "blockParams", ".", "logsBloom", ",", "difficulty", ":", "blockParams", ".", "difficulty", ",", "number", ":", "blockParams", ".", "number", ",", "gasLimit", ":", "blockParams", ".", "gasLimit", ",", "gasUsed", ":", "blockParams", ".", "gasUsed", ",", "timestamp", ":", "blockParams", ".", "timestamp", ",", "extraData", ":", "blockParams", ".", "extraData", ",", "mixHash", ":", "blockParams", ".", "mixHash", ",", "nonce", ":", "blockParams", ".", "nonce", "}", ")", "// override hash incase something was missing", "blockHeader", ".", "hash", "=", "function", "(", ")", "{", "return", "ethUtil", ".", "toBuffer", "(", "blockParams", ".", "hash", ")", "}", "return", "blockHeader", "}" ]
Creates a new block header object from Ethereum JSON RPC. @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber)
[ "Creates", "a", "new", "block", "header", "object", "from", "Ethereum", "JSON", "RPC", "." ]
2c3908e5bbb6c9c94aeb5547a779295433f42545
https://github.com/ethereumjs/ethereumjs-block/blob/2c3908e5bbb6c9c94aeb5547a779295433f42545/header-from-rpc.js#L11-L36
20,725
ethereumjs/ethereumjs-block
from-rpc.js
blockFromRpc
function blockFromRpc (blockParams, uncles) { uncles = uncles || [] const block = new Block({ transactions: [], uncleHeaders: [] }) block.header = blockHeaderFromRpc(blockParams) block.transactions = (blockParams.transactions || []).map(function (_txParams) { const txParams = normalizeTxParams(_txParams) // override from address const fromAddress = ethUtil.toBuffer(txParams.from) delete txParams.from const tx = new Transaction(txParams) tx._from = fromAddress tx.getSenderAddress = function () { return fromAddress } // override hash const txHash = ethUtil.toBuffer(txParams.hash) tx.hash = function () { return txHash } return tx }) block.uncleHeaders = uncles.map(function (uncleParams) { return blockHeaderFromRpc(uncleParams) }) return block }
javascript
function blockFromRpc (blockParams, uncles) { uncles = uncles || [] const block = new Block({ transactions: [], uncleHeaders: [] }) block.header = blockHeaderFromRpc(blockParams) block.transactions = (blockParams.transactions || []).map(function (_txParams) { const txParams = normalizeTxParams(_txParams) // override from address const fromAddress = ethUtil.toBuffer(txParams.from) delete txParams.from const tx = new Transaction(txParams) tx._from = fromAddress tx.getSenderAddress = function () { return fromAddress } // override hash const txHash = ethUtil.toBuffer(txParams.hash) tx.hash = function () { return txHash } return tx }) block.uncleHeaders = uncles.map(function (uncleParams) { return blockHeaderFromRpc(uncleParams) }) return block }
[ "function", "blockFromRpc", "(", "blockParams", ",", "uncles", ")", "{", "uncles", "=", "uncles", "||", "[", "]", "const", "block", "=", "new", "Block", "(", "{", "transactions", ":", "[", "]", ",", "uncleHeaders", ":", "[", "]", "}", ")", "block", ".", "header", "=", "blockHeaderFromRpc", "(", "blockParams", ")", "block", ".", "transactions", "=", "(", "blockParams", ".", "transactions", "||", "[", "]", ")", ".", "map", "(", "function", "(", "_txParams", ")", "{", "const", "txParams", "=", "normalizeTxParams", "(", "_txParams", ")", "// override from address", "const", "fromAddress", "=", "ethUtil", ".", "toBuffer", "(", "txParams", ".", "from", ")", "delete", "txParams", ".", "from", "const", "tx", "=", "new", "Transaction", "(", "txParams", ")", "tx", ".", "_from", "=", "fromAddress", "tx", ".", "getSenderAddress", "=", "function", "(", ")", "{", "return", "fromAddress", "}", "// override hash", "const", "txHash", "=", "ethUtil", ".", "toBuffer", "(", "txParams", ".", "hash", ")", "tx", ".", "hash", "=", "function", "(", ")", "{", "return", "txHash", "}", "return", "tx", "}", ")", "block", ".", "uncleHeaders", "=", "uncles", ".", "map", "(", "function", "(", "uncleParams", ")", "{", "return", "blockHeaderFromRpc", "(", "uncleParams", ")", "}", ")", "return", "block", "}" ]
Creates a new block object from Ethereum JSON RPC. @param {Object} blockParams - Ethereum JSON RPC of block (eth_getBlockByNumber) @param {Array.<Object>} Optional list of Ethereum JSON RPC of uncles (eth_getUncleByBlockHashAndIndex)
[ "Creates", "a", "new", "block", "object", "from", "Ethereum", "JSON", "RPC", "." ]
2c3908e5bbb6c9c94aeb5547a779295433f42545
https://github.com/ethereumjs/ethereumjs-block/blob/2c3908e5bbb6c9c94aeb5547a779295433f42545/from-rpc.js#L14-L40
20,726
ethereumjs/ethereumjs-block
index.js
function (cb3) { blockChain.getDetails(uncle.hash(), function (err, blockInfo) { // TODO: remove uncles from BC if (blockInfo && blockInfo.isUncle) { cb3(err || 'uncle already included') } else { cb3() } }) }
javascript
function (cb3) { blockChain.getDetails(uncle.hash(), function (err, blockInfo) { // TODO: remove uncles from BC if (blockInfo && blockInfo.isUncle) { cb3(err || 'uncle already included') } else { cb3() } }) }
[ "function", "(", "cb3", ")", "{", "blockChain", ".", "getDetails", "(", "uncle", ".", "hash", "(", ")", ",", "function", "(", "err", ",", "blockInfo", ")", "{", "// TODO: remove uncles from BC", "if", "(", "blockInfo", "&&", "blockInfo", ".", "isUncle", ")", "{", "cb3", "(", "err", "||", "'uncle already included'", ")", "}", "else", "{", "cb3", "(", ")", "}", "}", ")", "}" ]
check to make sure the uncle is not already in the blockchain
[ "check", "to", "make", "sure", "the", "uncle", "is", "not", "already", "in", "the", "blockchain" ]
2c3908e5bbb6c9c94aeb5547a779295433f42545
https://github.com/ethereumjs/ethereumjs-block/blob/2c3908e5bbb6c9c94aeb5547a779295433f42545/index.js#L271-L280
20,727
kcartlidge/nodepub
src/index.js
replacements
function replacements(document, original) { var modified = moment().format('YYYY-MM-DD'); var result = original; result = tagReplace(result, 'EOL', '\n'); result = tagReplace(result, 'ID', document.metadata.id); result = tagReplace(result, 'TITLE', document.metadata.title); result = tagReplace(result, 'SERIES', document.metadata.series); result = tagReplace(result, 'SEQUENCE', document.metadata.sequence); result = tagReplace(result, 'COPYRIGHT', document.metadata.copyright); result = tagReplace(result, 'LANGUAGE', document.metadata.language); result = tagReplace(result, 'FILEAS', document.metadata.fileAs); result = tagReplace(result, 'AUTHOR', document.metadata.author); result = tagReplace(result, 'PUBLISHER', document.metadata.publisher); result = tagReplace(result, 'DESCRIPTION', document.metadata.description); result = tagReplace(result, 'PUBLISHED', document.metadata.published); result = tagReplace(result, 'GENRE', document.metadata.genre); result = tagReplace(result, 'TAGS', document.metadata.tags); result = tagReplace(result, 'CONTENTS', document.metadata.contents); result = tagReplace(result, 'SOURCE', document.metadata.source); result = tagReplace(result, 'MODIFIED', modified); return result; }
javascript
function replacements(document, original) { var modified = moment().format('YYYY-MM-DD'); var result = original; result = tagReplace(result, 'EOL', '\n'); result = tagReplace(result, 'ID', document.metadata.id); result = tagReplace(result, 'TITLE', document.metadata.title); result = tagReplace(result, 'SERIES', document.metadata.series); result = tagReplace(result, 'SEQUENCE', document.metadata.sequence); result = tagReplace(result, 'COPYRIGHT', document.metadata.copyright); result = tagReplace(result, 'LANGUAGE', document.metadata.language); result = tagReplace(result, 'FILEAS', document.metadata.fileAs); result = tagReplace(result, 'AUTHOR', document.metadata.author); result = tagReplace(result, 'PUBLISHER', document.metadata.publisher); result = tagReplace(result, 'DESCRIPTION', document.metadata.description); result = tagReplace(result, 'PUBLISHED', document.metadata.published); result = tagReplace(result, 'GENRE', document.metadata.genre); result = tagReplace(result, 'TAGS', document.metadata.tags); result = tagReplace(result, 'CONTENTS', document.metadata.contents); result = tagReplace(result, 'SOURCE', document.metadata.source); result = tagReplace(result, 'MODIFIED', modified); return result; }
[ "function", "replacements", "(", "document", ",", "original", ")", "{", "var", "modified", "=", "moment", "(", ")", ".", "format", "(", "'YYYY-MM-DD'", ")", ";", "var", "result", "=", "original", ";", "result", "=", "tagReplace", "(", "result", ",", "'EOL'", ",", "'\\n'", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'ID'", ",", "document", ".", "metadata", ".", "id", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'TITLE'", ",", "document", ".", "metadata", ".", "title", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'SERIES'", ",", "document", ".", "metadata", ".", "series", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'SEQUENCE'", ",", "document", ".", "metadata", ".", "sequence", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'COPYRIGHT'", ",", "document", ".", "metadata", ".", "copyright", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'LANGUAGE'", ",", "document", ".", "metadata", ".", "language", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'FILEAS'", ",", "document", ".", "metadata", ".", "fileAs", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'AUTHOR'", ",", "document", ".", "metadata", ".", "author", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'PUBLISHER'", ",", "document", ".", "metadata", ".", "publisher", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'DESCRIPTION'", ",", "document", ".", "metadata", ".", "description", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'PUBLISHED'", ",", "document", ".", "metadata", ".", "published", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'GENRE'", ",", "document", ".", "metadata", ".", "genre", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'TAGS'", ",", "document", ".", "metadata", ".", "tags", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'CONTENTS'", ",", "document", ".", "metadata", ".", "contents", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'SOURCE'", ",", "document", ".", "metadata", ".", "source", ")", ";", "result", "=", "tagReplace", "(", "result", ",", "'MODIFIED'", ",", "modified", ")", ";", "return", "result", ";", "}" ]
Do all in-line replacements needed.
[ "Do", "all", "in", "-", "line", "replacements", "needed", "." ]
4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258
https://github.com/kcartlidge/nodepub/blob/4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258/src/index.js#L178-L199
20,728
kcartlidge/nodepub
src/index.js
getContainer
function getContainer(document) { var content = structuralFiles.getContainer(document); return replacements(document, replacements(document, content)); }
javascript
function getContainer(document) { var content = structuralFiles.getContainer(document); return replacements(document, replacements(document, content)); }
[ "function", "getContainer", "(", "document", ")", "{", "var", "content", "=", "structuralFiles", ".", "getContainer", "(", "document", ")", ";", "return", "replacements", "(", "document", ",", "replacements", "(", "document", ",", "content", ")", ")", ";", "}" ]
Provide the contents of the container XML file.
[ "Provide", "the", "contents", "of", "the", "container", "XML", "file", "." ]
4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258
https://github.com/kcartlidge/nodepub/blob/4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258/src/index.js#L207-L210
20,729
kcartlidge/nodepub
src/index.js
getNCX
function getNCX(document) { var content = structuralFiles.getNCX(document); return replacements(document, replacements(document, content)); }
javascript
function getNCX(document) { var content = structuralFiles.getNCX(document); return replacements(document, replacements(document, content)); }
[ "function", "getNCX", "(", "document", ")", "{", "var", "content", "=", "structuralFiles", ".", "getNCX", "(", "document", ")", ";", "return", "replacements", "(", "document", ",", "replacements", "(", "document", ",", "content", ")", ")", ";", "}" ]
Provide the contents of the NCX file.
[ "Provide", "the", "contents", "of", "the", "NCX", "file", "." ]
4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258
https://github.com/kcartlidge/nodepub/blob/4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258/src/index.js#L219-L222
20,730
kcartlidge/nodepub
src/index.js
getTOC
function getTOC(document) { var content = ""; if (document.generateContentsCallback) { var callbackContent = document.generateContentsCallback(document.filesForTOC); content = markupFiles.getContents(document, callbackContent); } else { content = markupFiles.getContents(document); } return replacements(document, replacements(document, content)); }
javascript
function getTOC(document) { var content = ""; if (document.generateContentsCallback) { var callbackContent = document.generateContentsCallback(document.filesForTOC); content = markupFiles.getContents(document, callbackContent); } else { content = markupFiles.getContents(document); } return replacements(document, replacements(document, content)); }
[ "function", "getTOC", "(", "document", ")", "{", "var", "content", "=", "\"\"", ";", "if", "(", "document", ".", "generateContentsCallback", ")", "{", "var", "callbackContent", "=", "document", ".", "generateContentsCallback", "(", "document", ".", "filesForTOC", ")", ";", "content", "=", "markupFiles", ".", "getContents", "(", "document", ",", "callbackContent", ")", ";", "}", "else", "{", "content", "=", "markupFiles", ".", "getContents", "(", "document", ")", ";", "}", "return", "replacements", "(", "document", ",", "replacements", "(", "document", ",", "content", ")", ")", ";", "}" ]
Provide the contents of the TOC file.
[ "Provide", "the", "contents", "of", "the", "TOC", "file", "." ]
4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258
https://github.com/kcartlidge/nodepub/blob/4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258/src/index.js#L225-L234
20,731
kcartlidge/nodepub
src/index.js
getCover
function getCover(document) { var content = markupFiles.getCover(); return replacements(document, replacements(document, content)); }
javascript
function getCover(document) { var content = markupFiles.getCover(); return replacements(document, replacements(document, content)); }
[ "function", "getCover", "(", "document", ")", "{", "var", "content", "=", "markupFiles", ".", "getCover", "(", ")", ";", "return", "replacements", "(", "document", ",", "replacements", "(", "document", ",", "content", ")", ")", ";", "}" ]
Provide the contents of the cover HTML enclosure.
[ "Provide", "the", "contents", "of", "the", "cover", "HTML", "enclosure", "." ]
4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258
https://github.com/kcartlidge/nodepub/blob/4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258/src/index.js#L237-L240
20,732
kcartlidge/nodepub
src/index.js
getCSS
function getCSS(document) { var content = document.CSS; return replacements(document, replacements(document, content)); }
javascript
function getCSS(document) { var content = document.CSS; return replacements(document, replacements(document, content)); }
[ "function", "getCSS", "(", "document", ")", "{", "var", "content", "=", "document", ".", "CSS", ";", "return", "replacements", "(", "document", ",", "replacements", "(", "document", ",", "content", ")", ")", ";", "}" ]
Provide the contents of the CSS file.
[ "Provide", "the", "contents", "of", "the", "CSS", "file", "." ]
4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258
https://github.com/kcartlidge/nodepub/blob/4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258/src/index.js#L243-L246
20,733
kcartlidge/nodepub
src/index.js
getSection
function getSection(document, sectionNumber) { var content = markupFiles.getSection(document, sectionNumber); return replacements(document, replacements(document, content)); }
javascript
function getSection(document, sectionNumber) { var content = markupFiles.getSection(document, sectionNumber); return replacements(document, replacements(document, content)); }
[ "function", "getSection", "(", "document", ",", "sectionNumber", ")", "{", "var", "content", "=", "markupFiles", ".", "getSection", "(", "document", ",", "sectionNumber", ")", ";", "return", "replacements", "(", "document", ",", "replacements", "(", "document", ",", "content", ")", ")", ";", "}" ]
Provide the contents of a single section's HTML.
[ "Provide", "the", "contents", "of", "a", "single", "section", "s", "HTML", "." ]
4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258
https://github.com/kcartlidge/nodepub/blob/4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258/src/index.js#L249-L252
20,734
kcartlidge/nodepub
src/index.js
makeFolder
function makeFolder(path, cb) { if (cb) { fs.mkdir(path, function (err) { if (err && err.code != 'EEXIST') { throw err; } cb(); }); } }
javascript
function makeFolder(path, cb) { if (cb) { fs.mkdir(path, function (err) { if (err && err.code != 'EEXIST') { throw err; } cb(); }); } }
[ "function", "makeFolder", "(", "path", ",", "cb", ")", "{", "if", "(", "cb", ")", "{", "fs", ".", "mkdir", "(", "path", ",", "function", "(", "err", ")", "{", "if", "(", "err", "&&", "err", ".", "code", "!=", "'EEXIST'", ")", "{", "throw", "err", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}", "}" ]
Create a folder, throwing an error only if the error is not that the folder already exists. Effectively creates if not found.
[ "Create", "a", "folder", "throwing", "an", "error", "only", "if", "the", "error", "is", "not", "that", "the", "folder", "already", "exists", ".", "Effectively", "creates", "if", "not", "found", "." ]
4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258
https://github.com/kcartlidge/nodepub/blob/4c4b53a3c559f6a0e32f70d63c2b750b2eaa1258/src/index.js#L256-L265
20,735
royriojas/file-entry-cache
cache.js
function ( files ) { var me = this; files = files || [ ]; return me.normalizeEntries( files ).filter( function ( entry ) { return entry.changed; } ).map( function ( entry ) { return entry.key; } ); }
javascript
function ( files ) { var me = this; files = files || [ ]; return me.normalizeEntries( files ).filter( function ( entry ) { return entry.changed; } ).map( function ( entry ) { return entry.key; } ); }
[ "function", "(", "files", ")", "{", "var", "me", "=", "this", ";", "files", "=", "files", "||", "[", "]", ";", "return", "me", ".", "normalizeEntries", "(", "files", ")", ".", "filter", "(", "function", "(", "entry", ")", "{", "return", "entry", ".", "changed", ";", "}", ")", ".", "map", "(", "function", "(", "entry", ")", "{", "return", "entry", ".", "key", ";", "}", ")", ";", "}" ]
Return the list o the files that changed compared against the ones stored in the cache @method getUpdated @param files {Array} the array of files to compare against the ones in the cache @returns {Array}
[ "Return", "the", "list", "o", "the", "files", "that", "changed", "compared", "against", "the", "ones", "stored", "in", "the", "cache" ]
03f700c99b76133dc14648b465a1550ec2930e5c
https://github.com/royriojas/file-entry-cache/blob/03f700c99b76133dc14648b465a1550ec2930e5c/cache.js#L176-L185
20,736
royriojas/file-entry-cache
cache.js
function ( files ) { files = files || [ ]; var me = this; var nEntries = files.map( function ( file ) { return me.getFileDescriptor( file ); } ); //normalizeEntries = nEntries; return nEntries; }
javascript
function ( files ) { files = files || [ ]; var me = this; var nEntries = files.map( function ( file ) { return me.getFileDescriptor( file ); } ); //normalizeEntries = nEntries; return nEntries; }
[ "function", "(", "files", ")", "{", "files", "=", "files", "||", "[", "]", ";", "var", "me", "=", "this", ";", "var", "nEntries", "=", "files", ".", "map", "(", "function", "(", "file", ")", "{", "return", "me", ".", "getFileDescriptor", "(", "file", ")", ";", "}", ")", ";", "//normalizeEntries = nEntries;", "return", "nEntries", ";", "}" ]
return the list of files @method normalizeEntries @param files @returns {*}
[ "return", "the", "list", "of", "files" ]
03f700c99b76133dc14648b465a1550ec2930e5c
https://github.com/royriojas/file-entry-cache/blob/03f700c99b76133dc14648b465a1550ec2930e5c/cache.js#L193-L203
20,737
royriojas/file-entry-cache
cache.js
function ( noPrune ) { removeNotFoundFiles(); noPrune = typeof noPrune === 'undefined' ? true : noPrune; var entries = normalizedEntries; var keys = Object.keys( entries ); if ( keys.length === 0 ) { return; } var me = this; keys.forEach( function ( entryName ) { var cacheEntry = entries[ entryName ]; try { var meta = useChecksum ? me._getMetaForFileUsingCheckSum( cacheEntry ) : me._getMetaForFileUsingMtimeAndSize( cacheEntry ); cache.setKey( entryName, meta ); } catch (err) { // if the file does not exists we don't save it // other errors are just thrown if ( err.code !== 'ENOENT' ) { throw err; } } } ); cache.save( noPrune ); }
javascript
function ( noPrune ) { removeNotFoundFiles(); noPrune = typeof noPrune === 'undefined' ? true : noPrune; var entries = normalizedEntries; var keys = Object.keys( entries ); if ( keys.length === 0 ) { return; } var me = this; keys.forEach( function ( entryName ) { var cacheEntry = entries[ entryName ]; try { var meta = useChecksum ? me._getMetaForFileUsingCheckSum( cacheEntry ) : me._getMetaForFileUsingMtimeAndSize( cacheEntry ); cache.setKey( entryName, meta ); } catch (err) { // if the file does not exists we don't save it // other errors are just thrown if ( err.code !== 'ENOENT' ) { throw err; } } } ); cache.save( noPrune ); }
[ "function", "(", "noPrune", ")", "{", "removeNotFoundFiles", "(", ")", ";", "noPrune", "=", "typeof", "noPrune", "===", "'undefined'", "?", "true", ":", "noPrune", ";", "var", "entries", "=", "normalizedEntries", ";", "var", "keys", "=", "Object", ".", "keys", "(", "entries", ")", ";", "if", "(", "keys", ".", "length", "===", "0", ")", "{", "return", ";", "}", "var", "me", "=", "this", ";", "keys", ".", "forEach", "(", "function", "(", "entryName", ")", "{", "var", "cacheEntry", "=", "entries", "[", "entryName", "]", ";", "try", "{", "var", "meta", "=", "useChecksum", "?", "me", ".", "_getMetaForFileUsingCheckSum", "(", "cacheEntry", ")", ":", "me", ".", "_getMetaForFileUsingMtimeAndSize", "(", "cacheEntry", ")", ";", "cache", ".", "setKey", "(", "entryName", ",", "meta", ")", ";", "}", "catch", "(", "err", ")", "{", "// if the file does not exists we don't save it", "// other errors are just thrown", "if", "(", "err", ".", "code", "!==", "'ENOENT'", ")", "{", "throw", "err", ";", "}", "}", "}", ")", ";", "cache", ".", "save", "(", "noPrune", ")", ";", "}" ]
Sync the files and persist them to the cache @method reconcile
[ "Sync", "the", "files", "and", "persist", "them", "to", "the", "cache" ]
03f700c99b76133dc14648b465a1550ec2930e5c
https://github.com/royriojas/file-entry-cache/blob/03f700c99b76133dc14648b465a1550ec2930e5c/cache.js#L253-L283
20,738
aerospike/aerospike-client-nodejs
lib/filter.js
typeOf
function typeOf (value) { if (value === null) return 'null' var valueType = typeof value if (valueType === 'object') { valueType = value.constructor.name.toLowerCase() } return valueType }
javascript
function typeOf (value) { if (value === null) return 'null' var valueType = typeof value if (valueType === 'object') { valueType = value.constructor.name.toLowerCase() } return valueType }
[ "function", "typeOf", "(", "value", ")", "{", "if", "(", "value", "===", "null", ")", "return", "'null'", "var", "valueType", "=", "typeof", "value", "if", "(", "valueType", "===", "'object'", ")", "{", "valueType", "=", "value", ".", "constructor", ".", "name", ".", "toLowerCase", "(", ")", "}", "return", "valueType", "}" ]
Helper function to determine the type of a primitive or Object
[ "Helper", "function", "to", "determine", "the", "type", "of", "a", "primitive", "or", "Object" ]
2b9554d1158abda58c17cfbd0438d78f0212ef9e
https://github.com/aerospike/aerospike-client-nodejs/blob/2b9554d1158abda58c17cfbd0438d78f0212ef9e/lib/filter.js#L94-L101
20,739
aerospike/aerospike-client-nodejs
lib/info.js
parseKeyValue
function parseKeyValue (str, sep1, sep2) { var result = {} str.split(sep1).forEach(function (kv) { if (kv.length > 0) { kv = kv.split(sep2, 2) result[kv[0]] = parseValue(kv[1]) } }) return result }
javascript
function parseKeyValue (str, sep1, sep2) { var result = {} str.split(sep1).forEach(function (kv) { if (kv.length > 0) { kv = kv.split(sep2, 2) result[kv[0]] = parseValue(kv[1]) } }) return result }
[ "function", "parseKeyValue", "(", "str", ",", "sep1", ",", "sep2", ")", "{", "var", "result", "=", "{", "}", "str", ".", "split", "(", "sep1", ")", ".", "forEach", "(", "function", "(", "kv", ")", "{", "if", "(", "kv", ".", "length", ">", "0", ")", "{", "kv", "=", "kv", ".", "split", "(", "sep2", ",", "2", ")", "result", "[", "kv", "[", "0", "]", "]", "=", "parseValue", "(", "kv", "[", "1", "]", ")", "}", "}", ")", "return", "result", "}" ]
Parses a string value representing a key-value-map separated by sep1 and sep2 into an Object. Ex.: - parseKeyValue('a=1;b=2', ';', '=') => { a: 1, b: 2 } @private
[ "Parses", "a", "string", "value", "representing", "a", "key", "-", "value", "-", "map", "separated", "by", "sep1", "and", "sep2", "into", "an", "Object", "." ]
2b9554d1158abda58c17cfbd0438d78f0212ef9e
https://github.com/aerospike/aerospike-client-nodejs/blob/2b9554d1158abda58c17cfbd0438d78f0212ef9e/lib/info.js#L104-L113
20,740
aerospike/aerospike-client-nodejs
lib/info.js
smartParse
function smartParse (str, sep1, sep2) { sep1 = sep1 || ';' sep2 = sep2 || '=' if ((typeof str === 'string') && str.indexOf(sep1) >= 0) { if (str.indexOf(sep2) >= 0) { return parseKeyValue(str, sep1, sep2) } else { return str.split(sep1) } } return str }
javascript
function smartParse (str, sep1, sep2) { sep1 = sep1 || ';' sep2 = sep2 || '=' if ((typeof str === 'string') && str.indexOf(sep1) >= 0) { if (str.indexOf(sep2) >= 0) { return parseKeyValue(str, sep1, sep2) } else { return str.split(sep1) } } return str }
[ "function", "smartParse", "(", "str", ",", "sep1", ",", "sep2", ")", "{", "sep1", "=", "sep1", "||", "';'", "sep2", "=", "sep2", "||", "'='", "if", "(", "(", "typeof", "str", "===", "'string'", ")", "&&", "str", ".", "indexOf", "(", "sep1", ")", ">=", "0", ")", "{", "if", "(", "str", ".", "indexOf", "(", "sep2", ")", ">=", "0", ")", "{", "return", "parseKeyValue", "(", "str", ",", "sep1", ",", "sep2", ")", "}", "else", "{", "return", "str", ".", "split", "(", "sep1", ")", "}", "}", "return", "str", "}" ]
Split string into list or key-value-pairs depending on whether the given separator chars appear in the string. This is the logic used by the old parseInfo function and the default logic used by the new parse function unless a specific format is defined for an info key. Ex.: - smartParse('foo') => 'foo' - smartParse('foo;bar') => ['foo', 'bar'] - smartParse('foo=1;bar=2') => {foo: 1, bar: 2} @private
[ "Split", "string", "into", "list", "or", "key", "-", "value", "-", "pairs", "depending", "on", "whether", "the", "given", "separator", "chars", "appear", "in", "the", "string", ".", "This", "is", "the", "logic", "used", "by", "the", "old", "parseInfo", "function", "and", "the", "default", "logic", "used", "by", "the", "new", "parse", "function", "unless", "a", "specific", "format", "is", "defined", "for", "an", "info", "key", "." ]
2b9554d1158abda58c17cfbd0438d78f0212ef9e
https://github.com/aerospike/aerospike-client-nodejs/blob/2b9554d1158abda58c17cfbd0438d78f0212ef9e/lib/info.js#L128-L139
20,741
aerospike/aerospike-client-nodejs
lib/info.js
getSeparators
function getSeparators (key) { let pattern = Object.keys(separators).find(p => minimatch(key, p)) const seps = separators[pattern] || defaultSeparators return seps.slice() // return a copy of the array }
javascript
function getSeparators (key) { let pattern = Object.keys(separators).find(p => minimatch(key, p)) const seps = separators[pattern] || defaultSeparators return seps.slice() // return a copy of the array }
[ "function", "getSeparators", "(", "key", ")", "{", "let", "pattern", "=", "Object", ".", "keys", "(", "separators", ")", ".", "find", "(", "p", "=>", "minimatch", "(", "key", ",", "p", ")", ")", "const", "seps", "=", "separators", "[", "pattern", "]", "||", "defaultSeparators", "return", "seps", ".", "slice", "(", ")", "// return a copy of the array", "}" ]
Returns separators to use for the given info key. @private
[ "Returns", "separators", "to", "use", "for", "the", "given", "info", "key", "." ]
2b9554d1158abda58c17cfbd0438d78f0212ef9e
https://github.com/aerospike/aerospike-client-nodejs/blob/2b9554d1158abda58c17cfbd0438d78f0212ef9e/lib/info.js#L146-L150
20,742
aerospike/aerospike-client-nodejs
lib/info.js
deepSplitString
function deepSplitString (input, separators) { if (input === null || typeof input === 'undefined') { return input } if (separators.length === 0) { return input } const sep = separators.shift() let output = input if (typeof input === 'string') { output = splitString(input, sep) } else if (Array.isArray(input)) { output = input.map(i => splitString(i, sep)) } else if (typeof input === 'object') { output = {} Object.keys(input).forEach(key => { output[key] = splitString(input[key], sep) }) } if (separators.length > 0) { return deepSplitString(output, separators) } else { return output } }
javascript
function deepSplitString (input, separators) { if (input === null || typeof input === 'undefined') { return input } if (separators.length === 0) { return input } const sep = separators.shift() let output = input if (typeof input === 'string') { output = splitString(input, sep) } else if (Array.isArray(input)) { output = input.map(i => splitString(i, sep)) } else if (typeof input === 'object') { output = {} Object.keys(input).forEach(key => { output[key] = splitString(input[key], sep) }) } if (separators.length > 0) { return deepSplitString(output, separators) } else { return output } }
[ "function", "deepSplitString", "(", "input", ",", "separators", ")", "{", "if", "(", "input", "===", "null", "||", "typeof", "input", "===", "'undefined'", ")", "{", "return", "input", "}", "if", "(", "separators", ".", "length", "===", "0", ")", "{", "return", "input", "}", "const", "sep", "=", "separators", ".", "shift", "(", ")", "let", "output", "=", "input", "if", "(", "typeof", "input", "===", "'string'", ")", "{", "output", "=", "splitString", "(", "input", ",", "sep", ")", "}", "else", "if", "(", "Array", ".", "isArray", "(", "input", ")", ")", "{", "output", "=", "input", ".", "map", "(", "i", "=>", "splitString", "(", "i", ",", "sep", ")", ")", "}", "else", "if", "(", "typeof", "input", "===", "'object'", ")", "{", "output", "=", "{", "}", "Object", ".", "keys", "(", "input", ")", ".", "forEach", "(", "key", "=>", "{", "output", "[", "key", "]", "=", "splitString", "(", "input", "[", "key", "]", ",", "sep", ")", "}", ")", "}", "if", "(", "separators", ".", "length", ">", "0", ")", "{", "return", "deepSplitString", "(", "output", ",", "separators", ")", "}", "else", "{", "return", "output", "}", "}" ]
Splits a string into a, possibly nested, array or object using the given separators. @private
[ "Splits", "a", "string", "into", "a", "possibly", "nested", "array", "or", "object", "using", "the", "given", "separators", "." ]
2b9554d1158abda58c17cfbd0438d78f0212ef9e
https://github.com/aerospike/aerospike-client-nodejs/blob/2b9554d1158abda58c17cfbd0438d78f0212ef9e/lib/info.js#L158-L185
20,743
aerospike/aerospike-client-nodejs
benchmarks/main.js
workerProbe
function workerProbe () { Object.keys(cluster.workers).forEach(function (id) { cluster.workers[id].send(['trans']) }) }
javascript
function workerProbe () { Object.keys(cluster.workers).forEach(function (id) { cluster.workers[id].send(['trans']) }) }
[ "function", "workerProbe", "(", ")", "{", "Object", ".", "keys", "(", "cluster", ".", "workers", ")", ".", "forEach", "(", "function", "(", "id", ")", "{", "cluster", ".", "workers", "[", "id", "]", ".", "send", "(", "[", "'trans'", "]", ")", "}", ")", "}" ]
Signal all workers asking for data on transactions
[ "Signal", "all", "workers", "asking", "for", "data", "on", "transactions" ]
2b9554d1158abda58c17cfbd0438d78f0212ef9e
https://github.com/aerospike/aerospike-client-nodejs/blob/2b9554d1158abda58c17cfbd0438d78f0212ef9e/benchmarks/main.js#L127-L131
20,744
nebulasio/neb.js
lib/account.js
function (priv) { if (utils.isString(priv) || Buffer.isBuffer(priv)) { this.privKey = priv.length === 32 ? priv : Buffer(priv, 'hex'); this.pubKey = null; this.address = null; } }
javascript
function (priv) { if (utils.isString(priv) || Buffer.isBuffer(priv)) { this.privKey = priv.length === 32 ? priv : Buffer(priv, 'hex'); this.pubKey = null; this.address = null; } }
[ "function", "(", "priv", ")", "{", "if", "(", "utils", ".", "isString", "(", "priv", ")", "||", "Buffer", ".", "isBuffer", "(", "priv", ")", ")", "{", "this", ".", "privKey", "=", "priv", ".", "length", "===", "32", "?", "priv", ":", "Buffer", "(", "priv", ",", "'hex'", ")", ";", "this", ".", "pubKey", "=", "null", ";", "this", ".", "address", "=", "null", ";", "}", "}" ]
Private Key setter. @param {Hash} priv - Account private key. @example account.setPrivateKey("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6");
[ "Private", "Key", "setter", "." ]
ad307a4be2015e5dba165ecab9c6e87104875f37
https://github.com/nebulasio/neb.js/blob/ad307a4be2015e5dba165ecab9c6e87104875f37/lib/account.js#L188-L194
20,745
nebulasio/neb.js
lib/account.js
function () { if (utils.isNull(this.address)) { var pubKey = this.getPublicKey(); if (pubKey.length !== 64) { pubKey = cryptoUtils.secp256k1.publicKeyConvert(pubKey, false).slice(1); } // The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus // the concatenation of the binary representation of the X coordinate plus the binary // representation of the y coordinate of the public point. pubKey = Buffer.concat([cryptoUtils.toBuffer(4), pubKey]); // Only take the lower 160bits of the hash var content = cryptoUtils.sha3(pubKey); content = cryptoUtils.ripemd160(content); // content = AddressPrefix + NormalType + content(local address only use normal type) content = Buffer.concat([cryptoUtils.toBuffer(AddressPrefix), cryptoUtils.toBuffer(NormalType), content]); var checksum = cryptoUtils.sha3(content).slice(0, 4); this.address = Buffer.concat([content, checksum]); } return this.address; }
javascript
function () { if (utils.isNull(this.address)) { var pubKey = this.getPublicKey(); if (pubKey.length !== 64) { pubKey = cryptoUtils.secp256k1.publicKeyConvert(pubKey, false).slice(1); } // The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus // the concatenation of the binary representation of the X coordinate plus the binary // representation of the y coordinate of the public point. pubKey = Buffer.concat([cryptoUtils.toBuffer(4), pubKey]); // Only take the lower 160bits of the hash var content = cryptoUtils.sha3(pubKey); content = cryptoUtils.ripemd160(content); // content = AddressPrefix + NormalType + content(local address only use normal type) content = Buffer.concat([cryptoUtils.toBuffer(AddressPrefix), cryptoUtils.toBuffer(NormalType), content]); var checksum = cryptoUtils.sha3(content).slice(0, 4); this.address = Buffer.concat([content, checksum]); } return this.address; }
[ "function", "(", ")", "{", "if", "(", "utils", ".", "isNull", "(", "this", ".", "address", ")", ")", "{", "var", "pubKey", "=", "this", ".", "getPublicKey", "(", ")", ";", "if", "(", "pubKey", ".", "length", "!==", "64", ")", "{", "pubKey", "=", "cryptoUtils", ".", "secp256k1", ".", "publicKeyConvert", "(", "pubKey", ",", "false", ")", ".", "slice", "(", "1", ")", ";", "}", "// The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus", "// the concatenation of the binary representation of the X coordinate plus the binary", "// representation of the y coordinate of the public point.", "pubKey", "=", "Buffer", ".", "concat", "(", "[", "cryptoUtils", ".", "toBuffer", "(", "4", ")", ",", "pubKey", "]", ")", ";", "// Only take the lower 160bits of the hash", "var", "content", "=", "cryptoUtils", ".", "sha3", "(", "pubKey", ")", ";", "content", "=", "cryptoUtils", ".", "ripemd160", "(", "content", ")", ";", "// content = AddressPrefix + NormalType + content(local address only use normal type)", "content", "=", "Buffer", ".", "concat", "(", "[", "cryptoUtils", ".", "toBuffer", "(", "AddressPrefix", ")", ",", "cryptoUtils", ".", "toBuffer", "(", "NormalType", ")", ",", "content", "]", ")", ";", "var", "checksum", "=", "cryptoUtils", ".", "sha3", "(", "content", ")", ".", "slice", "(", "0", ",", "4", ")", ";", "this", ".", "address", "=", "Buffer", ".", "concat", "(", "[", "content", ",", "checksum", "]", ")", ";", "}", "return", "this", ".", "address", ";", "}" ]
Accaunt address getter. @return {Buffer} Account address. @example var publicKey = account.getAddress(); //<Buffer 7f 87 83 58 46 96 12 7d 1a c0 57 1a 42 87 c6 25 36 08 ff 32 61 36 51 7c>
[ "Accaunt", "address", "getter", "." ]
ad307a4be2015e5dba165ecab9c6e87104875f37
https://github.com/nebulasio/neb.js/blob/ad307a4be2015e5dba165ecab9c6e87104875f37/lib/account.js#L250-L272
20,746
nebulasio/neb.js
lib/account.js
function (password, opts) { /*jshint maxcomplexity:17 */ opts = opts || {}; var salt = opts.salt || cryptoUtils.crypto.randomBytes(32); var iv = opts.iv || cryptoUtils.crypto.randomBytes(16); var derivedKey; var kdf = opts.kdf || 'scrypt'; var kdfparams = { dklen: opts.dklen || 32, salt: salt.toString('hex') }; if (kdf === 'pbkdf2') { kdfparams.c = opts.c || 262144; kdfparams.prf = 'hmac-sha256'; derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256'); } else if (kdf === 'scrypt') { kdfparams.n = opts.n || 4096; kdfparams.r = opts.r || 8; kdfparams.p = opts.p || 1; derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else { throw new Error('Unsupported kdf'); } var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv); if (!cipher) { throw new Error('Unsupported cipher'); } var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]); // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')])); return { version: KeyCurrentVersion, id: cryptoUtils.uuid.v4({ random: opts.uuid || cryptoUtils.crypto.randomBytes(16) }), address: this.getAddressString(), crypto: { ciphertext: ciphertext.toString('hex'), cipherparams: { iv: iv.toString('hex') }, cipher: opts.cipher || 'aes-128-ctr', kdf: kdf, kdfparams: kdfparams, mac: mac.toString('hex'), machash: "sha3256" } }; }
javascript
function (password, opts) { /*jshint maxcomplexity:17 */ opts = opts || {}; var salt = opts.salt || cryptoUtils.crypto.randomBytes(32); var iv = opts.iv || cryptoUtils.crypto.randomBytes(16); var derivedKey; var kdf = opts.kdf || 'scrypt'; var kdfparams = { dklen: opts.dklen || 32, salt: salt.toString('hex') }; if (kdf === 'pbkdf2') { kdfparams.c = opts.c || 262144; kdfparams.prf = 'hmac-sha256'; derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256'); } else if (kdf === 'scrypt') { kdfparams.n = opts.n || 4096; kdfparams.r = opts.r || 8; kdfparams.p = opts.p || 1; derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else { throw new Error('Unsupported kdf'); } var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv); if (!cipher) { throw new Error('Unsupported cipher'); } var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]); // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')])); return { version: KeyCurrentVersion, id: cryptoUtils.uuid.v4({ random: opts.uuid || cryptoUtils.crypto.randomBytes(16) }), address: this.getAddressString(), crypto: { ciphertext: ciphertext.toString('hex'), cipherparams: { iv: iv.toString('hex') }, cipher: opts.cipher || 'aes-128-ctr', kdf: kdf, kdfparams: kdfparams, mac: mac.toString('hex'), machash: "sha3256" } }; }
[ "function", "(", "password", ",", "opts", ")", "{", "/*jshint maxcomplexity:17 */", "opts", "=", "opts", "||", "{", "}", ";", "var", "salt", "=", "opts", ".", "salt", "||", "cryptoUtils", ".", "crypto", ".", "randomBytes", "(", "32", ")", ";", "var", "iv", "=", "opts", ".", "iv", "||", "cryptoUtils", ".", "crypto", ".", "randomBytes", "(", "16", ")", ";", "var", "derivedKey", ";", "var", "kdf", "=", "opts", ".", "kdf", "||", "'scrypt'", ";", "var", "kdfparams", "=", "{", "dklen", ":", "opts", ".", "dklen", "||", "32", ",", "salt", ":", "salt", ".", "toString", "(", "'hex'", ")", "}", ";", "if", "(", "kdf", "===", "'pbkdf2'", ")", "{", "kdfparams", ".", "c", "=", "opts", ".", "c", "||", "262144", ";", "kdfparams", ".", "prf", "=", "'hmac-sha256'", ";", "derivedKey", "=", "cryptoUtils", ".", "crypto", ".", "pbkdf2Sync", "(", "new", "Buffer", "(", "password", ")", ",", "salt", ",", "kdfparams", ".", "c", ",", "kdfparams", ".", "dklen", ",", "'sha256'", ")", ";", "}", "else", "if", "(", "kdf", "===", "'scrypt'", ")", "{", "kdfparams", ".", "n", "=", "opts", ".", "n", "||", "4096", ";", "kdfparams", ".", "r", "=", "opts", ".", "r", "||", "8", ";", "kdfparams", ".", "p", "=", "opts", ".", "p", "||", "1", ";", "derivedKey", "=", "cryptoUtils", ".", "scrypt", "(", "new", "Buffer", "(", "password", ")", ",", "salt", ",", "kdfparams", ".", "n", ",", "kdfparams", ".", "r", ",", "kdfparams", ".", "p", ",", "kdfparams", ".", "dklen", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Unsupported kdf'", ")", ";", "}", "var", "cipher", "=", "cryptoUtils", ".", "crypto", ".", "createCipheriv", "(", "opts", ".", "cipher", "||", "'aes-128-ctr'", ",", "derivedKey", ".", "slice", "(", "0", ",", "16", ")", ",", "iv", ")", ";", "if", "(", "!", "cipher", ")", "{", "throw", "new", "Error", "(", "'Unsupported cipher'", ")", ";", "}", "var", "ciphertext", "=", "Buffer", ".", "concat", "(", "[", "cipher", ".", "update", "(", "this", ".", "privKey", ")", ",", "cipher", ".", "final", "(", ")", "]", ")", ";", "// var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated", "var", "mac", "=", "cryptoUtils", ".", "sha3", "(", "Buffer", ".", "concat", "(", "[", "derivedKey", ".", "slice", "(", "16", ",", "32", ")", ",", "new", "Buffer", "(", "ciphertext", ",", "'hex'", ")", ",", "iv", ",", "new", "Buffer", "(", "opts", ".", "cipher", "||", "'aes-128-ctr'", ")", "]", ")", ")", ";", "return", "{", "version", ":", "KeyCurrentVersion", ",", "id", ":", "cryptoUtils", ".", "uuid", ".", "v4", "(", "{", "random", ":", "opts", ".", "uuid", "||", "cryptoUtils", ".", "crypto", ".", "randomBytes", "(", "16", ")", "}", ")", ",", "address", ":", "this", ".", "getAddressString", "(", ")", ",", "crypto", ":", "{", "ciphertext", ":", "ciphertext", ".", "toString", "(", "'hex'", ")", ",", "cipherparams", ":", "{", "iv", ":", "iv", ".", "toString", "(", "'hex'", ")", "}", ",", "cipher", ":", "opts", ".", "cipher", "||", "'aes-128-ctr'", ",", "kdf", ":", "kdf", ",", "kdfparams", ":", "kdfparams", ",", "mac", ":", "mac", ".", "toString", "(", "'hex'", ")", ",", "machash", ":", "\"sha3256\"", "}", "}", ";", "}" ]
Generate key buy passphrase and options. @param {Password} password - Provided password. @param {KeyOptions} opts - Key options. @return {Key} Key Object. @example var key = account.toKey("passphrase");
[ "Generate", "key", "buy", "passphrase", "and", "options", "." ]
ad307a4be2015e5dba165ecab9c6e87104875f37
https://github.com/nebulasio/neb.js/blob/ad307a4be2015e5dba165ecab9c6e87104875f37/lib/account.js#L295-L344
20,747
nebulasio/neb.js
lib/account.js
function (input, password, nonStrict) { /*jshint maxcomplexity:10 */ var json = (typeof input === 'object') ? input : JSON.parse(nonStrict ? input.toLowerCase() : input); if (json.version !== KeyVersion3 && json.version !== KeyCurrentVersion) { throw new Error('Not supported wallet version'); } var derivedKey; var kdfparams; if (json.crypto.kdf === 'scrypt') { kdfparams = json.crypto.kdfparams; derivedKey = cryptoUtils.scrypt(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else if (json.crypto.kdf === 'pbkdf2') { kdfparams = json.crypto.kdfparams; if (kdfparams.prf !== 'hmac-sha256') { throw new Error('Unsupported parameters to PBKDF2'); } derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); } else { throw new Error('Unsupported key derivation scheme'); } var ciphertext = new Buffer(json.crypto.ciphertext, 'hex'); var mac; if (json.version === KeyCurrentVersion) { mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext, new Buffer(json.crypto.cipherparams.iv, 'hex'), new Buffer(json.crypto.cipher)])); } else { // KeyVersion3 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext])); } if (mac.toString('hex') !== json.crypto.mac) { throw new Error('Key derivation failed - possibly wrong passphrase'); } var decipher = cryptoUtils.crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex')); var seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]); while (seed.length < 32) { var nullBuff = new Buffer([0x00]); seed = Buffer.concat([nullBuff, seed]); } this.setPrivateKey(seed); return this; }
javascript
function (input, password, nonStrict) { /*jshint maxcomplexity:10 */ var json = (typeof input === 'object') ? input : JSON.parse(nonStrict ? input.toLowerCase() : input); if (json.version !== KeyVersion3 && json.version !== KeyCurrentVersion) { throw new Error('Not supported wallet version'); } var derivedKey; var kdfparams; if (json.crypto.kdf === 'scrypt') { kdfparams = json.crypto.kdfparams; derivedKey = cryptoUtils.scrypt(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else if (json.crypto.kdf === 'pbkdf2') { kdfparams = json.crypto.kdfparams; if (kdfparams.prf !== 'hmac-sha256') { throw new Error('Unsupported parameters to PBKDF2'); } derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); } else { throw new Error('Unsupported key derivation scheme'); } var ciphertext = new Buffer(json.crypto.ciphertext, 'hex'); var mac; if (json.version === KeyCurrentVersion) { mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext, new Buffer(json.crypto.cipherparams.iv, 'hex'), new Buffer(json.crypto.cipher)])); } else { // KeyVersion3 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext])); } if (mac.toString('hex') !== json.crypto.mac) { throw new Error('Key derivation failed - possibly wrong passphrase'); } var decipher = cryptoUtils.crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex')); var seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]); while (seed.length < 32) { var nullBuff = new Buffer([0x00]); seed = Buffer.concat([nullBuff, seed]); } this.setPrivateKey(seed); return this; }
[ "function", "(", "input", ",", "password", ",", "nonStrict", ")", "{", "/*jshint maxcomplexity:10 */", "var", "json", "=", "(", "typeof", "input", "===", "'object'", ")", "?", "input", ":", "JSON", ".", "parse", "(", "nonStrict", "?", "input", ".", "toLowerCase", "(", ")", ":", "input", ")", ";", "if", "(", "json", ".", "version", "!==", "KeyVersion3", "&&", "json", ".", "version", "!==", "KeyCurrentVersion", ")", "{", "throw", "new", "Error", "(", "'Not supported wallet version'", ")", ";", "}", "var", "derivedKey", ";", "var", "kdfparams", ";", "if", "(", "json", ".", "crypto", ".", "kdf", "===", "'scrypt'", ")", "{", "kdfparams", "=", "json", ".", "crypto", ".", "kdfparams", ";", "derivedKey", "=", "cryptoUtils", ".", "scrypt", "(", "new", "Buffer", "(", "password", ")", ",", "new", "Buffer", "(", "kdfparams", ".", "salt", ",", "'hex'", ")", ",", "kdfparams", ".", "n", ",", "kdfparams", ".", "r", ",", "kdfparams", ".", "p", ",", "kdfparams", ".", "dklen", ")", ";", "}", "else", "if", "(", "json", ".", "crypto", ".", "kdf", "===", "'pbkdf2'", ")", "{", "kdfparams", "=", "json", ".", "crypto", ".", "kdfparams", ";", "if", "(", "kdfparams", ".", "prf", "!==", "'hmac-sha256'", ")", "{", "throw", "new", "Error", "(", "'Unsupported parameters to PBKDF2'", ")", ";", "}", "derivedKey", "=", "cryptoUtils", ".", "crypto", ".", "pbkdf2Sync", "(", "new", "Buffer", "(", "password", ")", ",", "new", "Buffer", "(", "kdfparams", ".", "salt", ",", "'hex'", ")", ",", "kdfparams", ".", "c", ",", "kdfparams", ".", "dklen", ",", "'sha256'", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Unsupported key derivation scheme'", ")", ";", "}", "var", "ciphertext", "=", "new", "Buffer", "(", "json", ".", "crypto", ".", "ciphertext", ",", "'hex'", ")", ";", "var", "mac", ";", "if", "(", "json", ".", "version", "===", "KeyCurrentVersion", ")", "{", "mac", "=", "cryptoUtils", ".", "sha3", "(", "Buffer", ".", "concat", "(", "[", "derivedKey", ".", "slice", "(", "16", ",", "32", ")", ",", "ciphertext", ",", "new", "Buffer", "(", "json", ".", "crypto", ".", "cipherparams", ".", "iv", ",", "'hex'", ")", ",", "new", "Buffer", "(", "json", ".", "crypto", ".", "cipher", ")", "]", ")", ")", ";", "}", "else", "{", "// KeyVersion3", "mac", "=", "cryptoUtils", ".", "sha3", "(", "Buffer", ".", "concat", "(", "[", "derivedKey", ".", "slice", "(", "16", ",", "32", ")", ",", "ciphertext", "]", ")", ")", ";", "}", "if", "(", "mac", ".", "toString", "(", "'hex'", ")", "!==", "json", ".", "crypto", ".", "mac", ")", "{", "throw", "new", "Error", "(", "'Key derivation failed - possibly wrong passphrase'", ")", ";", "}", "var", "decipher", "=", "cryptoUtils", ".", "crypto", ".", "createDecipheriv", "(", "json", ".", "crypto", ".", "cipher", ",", "derivedKey", ".", "slice", "(", "0", ",", "16", ")", ",", "new", "Buffer", "(", "json", ".", "crypto", ".", "cipherparams", ".", "iv", ",", "'hex'", ")", ")", ";", "var", "seed", "=", "Buffer", ".", "concat", "(", "[", "decipher", ".", "update", "(", "ciphertext", ")", ",", "decipher", ".", "final", "(", ")", "]", ")", ";", "while", "(", "seed", ".", "length", "<", "32", ")", "{", "var", "nullBuff", "=", "new", "Buffer", "(", "[", "0x00", "]", ")", ";", "seed", "=", "Buffer", ".", "concat", "(", "[", "nullBuff", ",", "seed", "]", ")", ";", "}", "this", ".", "setPrivateKey", "(", "seed", ")", ";", "return", "this", ";", "}" ]
Restore account from key and passphrase. @param {Key} input - Key Object. @param {Password} password - Provided password. @param {Boolean} nonStrict - Strict сase sensitivity flag. @return {@link Account} - Instance of Account restored from key and passphrase.
[ "Restore", "account", "from", "key", "and", "passphrase", "." ]
ad307a4be2015e5dba165ecab9c6e87104875f37
https://github.com/nebulasio/neb.js/blob/ad307a4be2015e5dba165ecab9c6e87104875f37/lib/account.js#L368-L411
20,748
nebulasio/neb.js
lib/transaction.js
function (options) { if (arguments.length > 0) { options = utils.argumentsToObject(['chainID', 'from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments); this.chainID = options.chainID; this.from = account.fromAddress(options.from); this.to = account.fromAddress(options.to); this.value = utils.toBigNumber(options.value); if(!this.value.isInteger()) throw new Error("Invalid value! The minimum unit is wei (1^-18nas)"); this.nonce = parseInt(options.nonce); // An error will be thrown is nonce is string. Error: "nonce: integer|Long expected" this.timestamp = Math.floor(new Date().getTime()/1000); this.contract = options.contract; this.gasPrice = utils.toBigNumber(options.gasPrice); this.gasLimit = utils.toBigNumber(options.gasLimit); this.data = parseContract(this.contract); if (this.gasPrice.lessThanOrEqualTo(0)) { this.gasPrice = new BigNumber(1000000); } if (this.gasLimit.lessThanOrEqualTo(0)) { this.gasLimit = new BigNumber(20000); } } this.signErrorMessage = "You should sign transaction before this operation."; }
javascript
function (options) { if (arguments.length > 0) { options = utils.argumentsToObject(['chainID', 'from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments); this.chainID = options.chainID; this.from = account.fromAddress(options.from); this.to = account.fromAddress(options.to); this.value = utils.toBigNumber(options.value); if(!this.value.isInteger()) throw new Error("Invalid value! The minimum unit is wei (1^-18nas)"); this.nonce = parseInt(options.nonce); // An error will be thrown is nonce is string. Error: "nonce: integer|Long expected" this.timestamp = Math.floor(new Date().getTime()/1000); this.contract = options.contract; this.gasPrice = utils.toBigNumber(options.gasPrice); this.gasLimit = utils.toBigNumber(options.gasLimit); this.data = parseContract(this.contract); if (this.gasPrice.lessThanOrEqualTo(0)) { this.gasPrice = new BigNumber(1000000); } if (this.gasLimit.lessThanOrEqualTo(0)) { this.gasLimit = new BigNumber(20000); } } this.signErrorMessage = "You should sign transaction before this operation."; }
[ "function", "(", "options", ")", "{", "if", "(", "arguments", ".", "length", ">", "0", ")", "{", "options", "=", "utils", ".", "argumentsToObject", "(", "[", "'chainID'", ",", "'from'", ",", "'to'", ",", "'value'", ",", "'nonce'", ",", "'gasPrice'", ",", "'gasLimit'", ",", "'contract'", "]", ",", "arguments", ")", ";", "this", ".", "chainID", "=", "options", ".", "chainID", ";", "this", ".", "from", "=", "account", ".", "fromAddress", "(", "options", ".", "from", ")", ";", "this", ".", "to", "=", "account", ".", "fromAddress", "(", "options", ".", "to", ")", ";", "this", ".", "value", "=", "utils", ".", "toBigNumber", "(", "options", ".", "value", ")", ";", "if", "(", "!", "this", ".", "value", ".", "isInteger", "(", ")", ")", "throw", "new", "Error", "(", "\"Invalid value! The minimum unit is wei (1^-18nas)\"", ")", ";", "this", ".", "nonce", "=", "parseInt", "(", "options", ".", "nonce", ")", ";", "// An error will be thrown is nonce is string. Error: \"nonce: integer|Long expected\"", "this", ".", "timestamp", "=", "Math", ".", "floor", "(", "new", "Date", "(", ")", ".", "getTime", "(", ")", "/", "1000", ")", ";", "this", ".", "contract", "=", "options", ".", "contract", ";", "this", ".", "gasPrice", "=", "utils", ".", "toBigNumber", "(", "options", ".", "gasPrice", ")", ";", "this", ".", "gasLimit", "=", "utils", ".", "toBigNumber", "(", "options", ".", "gasLimit", ")", ";", "this", ".", "data", "=", "parseContract", "(", "this", ".", "contract", ")", ";", "if", "(", "this", ".", "gasPrice", ".", "lessThanOrEqualTo", "(", "0", ")", ")", "{", "this", ".", "gasPrice", "=", "new", "BigNumber", "(", "1000000", ")", ";", "}", "if", "(", "this", ".", "gasLimit", ".", "lessThanOrEqualTo", "(", "0", ")", ")", "{", "this", ".", "gasLimit", "=", "new", "BigNumber", "(", "20000", ")", ";", "}", "}", "this", ".", "signErrorMessage", "=", "\"You should sign transaction before this operation.\"", ";", "}" ]
Represent Transaction parameters @typedef {Object} TransactionOptions @property {Number} options.chainID - Transaction chain id. @property {HexString} options.from - Hex string of the sender account addresss.. @property {HexString} options.to - Hex string of the receiver account addresss.. @property {Number} options.value - Value of transaction. @property {Number} options.nonce - Transaction nonce. @property {Number} options.gasPrice - Gas price. The unit is 10^-18 NAS. @property {Number} options.gasLimit - Transaction gas limit. @property {Contract} [options.contract] @example { chainID: 1, from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5", to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 10, nonce: 12, gasPrice: 1000000, gasLimit: 2000000 } Transaction constructor. Class encapsulate main operation with transactions. @see [For more information about parameters, follow this link]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction} @constructor @param {TransactionOptions} options - Transaction options. @see [Transaction tutorial.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2002%20Transaction.md} @see [Create own smart contract in Nebulas.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md} @see [More about transaction parameters.]{@link https://github.com/nebulasio/wiki/blob/c3f5ce8908c80e9104e3b512a7fdfd75f16ac38c/rpc.md#sendtransaction} @example var acc = Account.NewAccount(); var tx = new Transaction({ chainID: 1, from: acc, to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 10, nonce: 12, gasPrice: 1000000, gasLimit: 2000000, contract: { function: "save", args: "[0]" } });
[ "Represent", "Transaction", "parameters" ]
ad307a4be2015e5dba165ecab9c6e87104875f37
https://github.com/nebulasio/neb.js/blob/ad307a4be2015e5dba165ecab9c6e87104875f37/lib/transaction.js#L128-L154
20,749
nebulasio/neb.js
lib/transaction.js
function () { var Data = root.lookup("corepb.Data"); var err = Data.verify(this.data); if (err) { throw new Error(err); } var data = Data.create(this.data); var dataBuffer = Data.encode(data).finish(); var hash = cryptoUtils.sha3( this.from.getAddress(), this.to.getAddress(), cryptoUtils.padToBigEndian(this.value, 128), cryptoUtils.padToBigEndian(this.nonce, 64), cryptoUtils.padToBigEndian(this.timestamp, 64), dataBuffer, cryptoUtils.padToBigEndian(this.chainID, 32), cryptoUtils.padToBigEndian(this.gasPrice, 128), cryptoUtils.padToBigEndian(this.gasLimit, 128) ); return hash; }
javascript
function () { var Data = root.lookup("corepb.Data"); var err = Data.verify(this.data); if (err) { throw new Error(err); } var data = Data.create(this.data); var dataBuffer = Data.encode(data).finish(); var hash = cryptoUtils.sha3( this.from.getAddress(), this.to.getAddress(), cryptoUtils.padToBigEndian(this.value, 128), cryptoUtils.padToBigEndian(this.nonce, 64), cryptoUtils.padToBigEndian(this.timestamp, 64), dataBuffer, cryptoUtils.padToBigEndian(this.chainID, 32), cryptoUtils.padToBigEndian(this.gasPrice, 128), cryptoUtils.padToBigEndian(this.gasLimit, 128) ); return hash; }
[ "function", "(", ")", "{", "var", "Data", "=", "root", ".", "lookup", "(", "\"corepb.Data\"", ")", ";", "var", "err", "=", "Data", ".", "verify", "(", "this", ".", "data", ")", ";", "if", "(", "err", ")", "{", "throw", "new", "Error", "(", "err", ")", ";", "}", "var", "data", "=", "Data", ".", "create", "(", "this", ".", "data", ")", ";", "var", "dataBuffer", "=", "Data", ".", "encode", "(", "data", ")", ".", "finish", "(", ")", ";", "var", "hash", "=", "cryptoUtils", ".", "sha3", "(", "this", ".", "from", ".", "getAddress", "(", ")", ",", "this", ".", "to", ".", "getAddress", "(", ")", ",", "cryptoUtils", ".", "padToBigEndian", "(", "this", ".", "value", ",", "128", ")", ",", "cryptoUtils", ".", "padToBigEndian", "(", "this", ".", "nonce", ",", "64", ")", ",", "cryptoUtils", ".", "padToBigEndian", "(", "this", ".", "timestamp", ",", "64", ")", ",", "dataBuffer", ",", "cryptoUtils", ".", "padToBigEndian", "(", "this", ".", "chainID", ",", "32", ")", ",", "cryptoUtils", ".", "padToBigEndian", "(", "this", ".", "gasPrice", ",", "128", ")", ",", "cryptoUtils", ".", "padToBigEndian", "(", "this", ".", "gasLimit", ",", "128", ")", ")", ";", "return", "hash", ";", "}" ]
Convert transaction to hash by SHA3-256 algorithm. @return {Hash} hash of Transaction. @example var acc = Account.NewAccount(); var tx = new Transaction({ chainID: 1, from: acc, to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 10, nonce: 12, gasPrice: 1000000, gasLimit: 2000000 }); var txHash = tx.hashTransaction(); //Uint8Array(32) [211, 213, 102, 103, 23, 231, 246, 141, 20, 202, 210, 25, 92, 142, 162, 242, 232, 95, 44, 239, 45, 57, 241, 61, 34, 2, 213, 160, 17, 207, 75, 40]
[ "Convert", "transaction", "to", "hash", "by", "SHA3", "-", "256", "algorithm", "." ]
ad307a4be2015e5dba165ecab9c6e87104875f37
https://github.com/nebulasio/neb.js/blob/ad307a4be2015e5dba165ecab9c6e87104875f37/lib/transaction.js#L254-L274
20,750
nebulasio/neb.js
lib/transaction.js
function () { if (this.from.getPrivateKey() !== null) { this.hash = this.hashTransaction(); this.alg = SECP256K1; this.sign = cryptoUtils.sign(this.hash, this.from.getPrivateKey()); } else { throw new Error("transaction from address's private key is invalid"); } }
javascript
function () { if (this.from.getPrivateKey() !== null) { this.hash = this.hashTransaction(); this.alg = SECP256K1; this.sign = cryptoUtils.sign(this.hash, this.from.getPrivateKey()); } else { throw new Error("transaction from address's private key is invalid"); } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "from", ".", "getPrivateKey", "(", ")", "!==", "null", ")", "{", "this", ".", "hash", "=", "this", ".", "hashTransaction", "(", ")", ";", "this", ".", "alg", "=", "SECP256K1", ";", "this", ".", "sign", "=", "cryptoUtils", ".", "sign", "(", "this", ".", "hash", ",", "this", ".", "from", ".", "getPrivateKey", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"transaction from address's private key is invalid\"", ")", ";", "}", "}" ]
Sign transaction with the specified algorithm. @example var acc = Account.NewAccount(); var tx = new Transaction({ chainID: 1, from: acc, to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 10, nonce: 12, gasPrice: 1000000, gasLimit: 2000000 }); tx.signTransaction();
[ "Sign", "transaction", "with", "the", "specified", "algorithm", "." ]
ad307a4be2015e5dba165ecab9c6e87104875f37
https://github.com/nebulasio/neb.js/blob/ad307a4be2015e5dba165ecab9c6e87104875f37/lib/transaction.js#L292-L300
20,751
nebulasio/neb.js
lib/transaction.js
function() { return { chainID: this.chainID, from: this.from.getAddressString(), to: this.to.getAddressString(), value: utils.isBigNumber(this.value) ? this.value.toNumber() : this.value, nonce: this.nonce, gasPrice: utils.isBigNumber(this.gasPrice) ? this.gasPrice.toNumber() : this.gasPrice, gasLimit: utils.isBigNumber(this.gasLimit) ? this.gasLimit.toNumber() : this.gasLimit, contract: this.contract }; }
javascript
function() { return { chainID: this.chainID, from: this.from.getAddressString(), to: this.to.getAddressString(), value: utils.isBigNumber(this.value) ? this.value.toNumber() : this.value, nonce: this.nonce, gasPrice: utils.isBigNumber(this.gasPrice) ? this.gasPrice.toNumber() : this.gasPrice, gasLimit: utils.isBigNumber(this.gasLimit) ? this.gasLimit.toNumber() : this.gasLimit, contract: this.contract }; }
[ "function", "(", ")", "{", "return", "{", "chainID", ":", "this", ".", "chainID", ",", "from", ":", "this", ".", "from", ".", "getAddressString", "(", ")", ",", "to", ":", "this", ".", "to", ".", "getAddressString", "(", ")", ",", "value", ":", "utils", ".", "isBigNumber", "(", "this", ".", "value", ")", "?", "this", ".", "value", ".", "toNumber", "(", ")", ":", "this", ".", "value", ",", "nonce", ":", "this", ".", "nonce", ",", "gasPrice", ":", "utils", ".", "isBigNumber", "(", "this", ".", "gasPrice", ")", "?", "this", ".", "gasPrice", ".", "toNumber", "(", ")", ":", "this", ".", "gasPrice", ",", "gasLimit", ":", "utils", ".", "isBigNumber", "(", "this", ".", "gasLimit", ")", "?", "this", ".", "gasLimit", ".", "toNumber", "(", ")", ":", "this", ".", "gasLimit", ",", "contract", ":", "this", ".", "contract", "}", ";", "}" ]
Conver transaction data to plain JavaScript object. @return {Object} Plain JavaScript object with Transaction fields. @example var acc = Account.NewAccount(); var tx = new Transaction({ chainID: 1, from: acc, to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 10, nonce: 12, gasPrice: 1000000, gasLimit: 2000000 }); txData = tx.toPlainObject(); // {chainID: 1001, from: "n1USdDKeZXQYubA44W2ZVUdW1cjiJuqswxp", to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 1000000000000000000, nonce: 1, …}
[ "Conver", "transaction", "data", "to", "plain", "JavaScript", "object", "." ]
ad307a4be2015e5dba165ecab9c6e87104875f37
https://github.com/nebulasio/neb.js/blob/ad307a4be2015e5dba165ecab9c6e87104875f37/lib/transaction.js#L319-L330
20,752
pillarjs/finalhandler
index.js
createHtmlDocument
function createHtmlDocument (message) { var body = escapeHtml(message) .replace(NEWLINE_REGEXP, '<br>') .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;') return '<!DOCTYPE html>\n' + '<html lang="en">\n' + '<head>\n' + '<meta charset="utf-8">\n' + '<title>Error</title>\n' + '</head>\n' + '<body>\n' + '<pre>' + body + '</pre>\n' + '</body>\n' + '</html>\n' }
javascript
function createHtmlDocument (message) { var body = escapeHtml(message) .replace(NEWLINE_REGEXP, '<br>') .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;') return '<!DOCTYPE html>\n' + '<html lang="en">\n' + '<head>\n' + '<meta charset="utf-8">\n' + '<title>Error</title>\n' + '</head>\n' + '<body>\n' + '<pre>' + body + '</pre>\n' + '</body>\n' + '</html>\n' }
[ "function", "createHtmlDocument", "(", "message", ")", "{", "var", "body", "=", "escapeHtml", "(", "message", ")", ".", "replace", "(", "NEWLINE_REGEXP", ",", "'<br>'", ")", ".", "replace", "(", "DOUBLE_SPACE_REGEXP", ",", "' &nbsp;'", ")", "return", "'<!DOCTYPE html>\\n'", "+", "'<html lang=\"en\">\\n'", "+", "'<head>\\n'", "+", "'<meta charset=\"utf-8\">\\n'", "+", "'<title>Error</title>\\n'", "+", "'</head>\\n'", "+", "'<body>\\n'", "+", "'<pre>'", "+", "body", "+", "'</pre>\\n'", "+", "'</body>\\n'", "+", "'</html>\\n'", "}" ]
Create a minimal HTML document. @param {string} message @private
[ "Create", "a", "minimal", "HTML", "document", "." ]
1b2c36949db50aa766d4691a5f38eb6639d01d66
https://github.com/pillarjs/finalhandler/blob/1b2c36949db50aa766d4691a5f38eb6639d01d66/index.js#L43-L58
20,753
pillarjs/finalhandler
index.js
finalhandler
function finalhandler (req, res, options) { var opts = options || {} // get environment var env = opts.env || process.env.NODE_ENV || 'development' // get error callback var onerror = opts.onerror return function (err) { var headers var msg var status // ignore 404 on in-flight response if (!err && headersSent(res)) { debug('cannot 404 after headers sent') return } // unhandled error if (err) { // respect status code from error status = getErrorStatusCode(err) if (status === undefined) { // fallback to status code on response status = getResponseStatusCode(res) } else { // respect headers from error headers = getErrorHeaders(err) } // get error message msg = getErrorMessage(err, status, env) } else { // not found status = 404 msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) } debug('default %s', status) // schedule onerror callback if (err && onerror) { defer(onerror, err, req, res) } // cannot actually respond if (headersSent(res)) { debug('cannot %d after headers sent', status) req.socket.destroy() return } // send response send(req, res, status, headers, msg) } }
javascript
function finalhandler (req, res, options) { var opts = options || {} // get environment var env = opts.env || process.env.NODE_ENV || 'development' // get error callback var onerror = opts.onerror return function (err) { var headers var msg var status // ignore 404 on in-flight response if (!err && headersSent(res)) { debug('cannot 404 after headers sent') return } // unhandled error if (err) { // respect status code from error status = getErrorStatusCode(err) if (status === undefined) { // fallback to status code on response status = getResponseStatusCode(res) } else { // respect headers from error headers = getErrorHeaders(err) } // get error message msg = getErrorMessage(err, status, env) } else { // not found status = 404 msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) } debug('default %s', status) // schedule onerror callback if (err && onerror) { defer(onerror, err, req, res) } // cannot actually respond if (headersSent(res)) { debug('cannot %d after headers sent', status) req.socket.destroy() return } // send response send(req, res, status, headers, msg) } }
[ "function", "finalhandler", "(", "req", ",", "res", ",", "options", ")", "{", "var", "opts", "=", "options", "||", "{", "}", "// get environment", "var", "env", "=", "opts", ".", "env", "||", "process", ".", "env", ".", "NODE_ENV", "||", "'development'", "// get error callback", "var", "onerror", "=", "opts", ".", "onerror", "return", "function", "(", "err", ")", "{", "var", "headers", "var", "msg", "var", "status", "// ignore 404 on in-flight response", "if", "(", "!", "err", "&&", "headersSent", "(", "res", ")", ")", "{", "debug", "(", "'cannot 404 after headers sent'", ")", "return", "}", "// unhandled error", "if", "(", "err", ")", "{", "// respect status code from error", "status", "=", "getErrorStatusCode", "(", "err", ")", "if", "(", "status", "===", "undefined", ")", "{", "// fallback to status code on response", "status", "=", "getResponseStatusCode", "(", "res", ")", "}", "else", "{", "// respect headers from error", "headers", "=", "getErrorHeaders", "(", "err", ")", "}", "// get error message", "msg", "=", "getErrorMessage", "(", "err", ",", "status", ",", "env", ")", "}", "else", "{", "// not found", "status", "=", "404", "msg", "=", "'Cannot '", "+", "req", ".", "method", "+", "' '", "+", "encodeUrl", "(", "getResourceName", "(", "req", ")", ")", "}", "debug", "(", "'default %s'", ",", "status", ")", "// schedule onerror callback", "if", "(", "err", "&&", "onerror", ")", "{", "defer", "(", "onerror", ",", "err", ",", "req", ",", "res", ")", "}", "// cannot actually respond", "if", "(", "headersSent", "(", "res", ")", ")", "{", "debug", "(", "'cannot %d after headers sent'", ",", "status", ")", "req", ".", "socket", ".", "destroy", "(", ")", "return", "}", "// send response", "send", "(", "req", ",", "res", ",", "status", ",", "headers", ",", "msg", ")", "}", "}" ]
Create a function to handle the final response. @param {Request} req @param {Response} res @param {Object} [options] @return {Function} @public
[ "Create", "a", "function", "to", "handle", "the", "final", "response", "." ]
1b2c36949db50aa766d4691a5f38eb6639d01d66
https://github.com/pillarjs/finalhandler/blob/1b2c36949db50aa766d4691a5f38eb6639d01d66/index.js#L77-L135
20,754
pillarjs/finalhandler
index.js
getErrorHeaders
function getErrorHeaders (err) { if (!err.headers || typeof err.headers !== 'object') { return undefined } var headers = Object.create(null) var keys = Object.keys(err.headers) for (var i = 0; i < keys.length; i++) { var key = keys[i] headers[key] = err.headers[key] } return headers }
javascript
function getErrorHeaders (err) { if (!err.headers || typeof err.headers !== 'object') { return undefined } var headers = Object.create(null) var keys = Object.keys(err.headers) for (var i = 0; i < keys.length; i++) { var key = keys[i] headers[key] = err.headers[key] } return headers }
[ "function", "getErrorHeaders", "(", "err", ")", "{", "if", "(", "!", "err", ".", "headers", "||", "typeof", "err", ".", "headers", "!==", "'object'", ")", "{", "return", "undefined", "}", "var", "headers", "=", "Object", ".", "create", "(", "null", ")", "var", "keys", "=", "Object", ".", "keys", "(", "err", ".", "headers", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", "headers", "[", "key", "]", "=", "err", ".", "headers", "[", "key", "]", "}", "return", "headers", "}" ]
Get headers from Error object. @param {Error} err @return {object} @private
[ "Get", "headers", "from", "Error", "object", "." ]
1b2c36949db50aa766d4691a5f38eb6639d01d66
https://github.com/pillarjs/finalhandler/blob/1b2c36949db50aa766d4691a5f38eb6639d01d66/index.js#L145-L159
20,755
pillarjs/finalhandler
index.js
getErrorMessage
function getErrorMessage (err, status, env) { var msg if (env !== 'production') { // use err.stack, which typically includes err.message msg = err.stack // fallback to err.toString() when possible if (!msg && typeof err.toString === 'function') { msg = err.toString() } } return msg || statuses[status] }
javascript
function getErrorMessage (err, status, env) { var msg if (env !== 'production') { // use err.stack, which typically includes err.message msg = err.stack // fallback to err.toString() when possible if (!msg && typeof err.toString === 'function') { msg = err.toString() } } return msg || statuses[status] }
[ "function", "getErrorMessage", "(", "err", ",", "status", ",", "env", ")", "{", "var", "msg", "if", "(", "env", "!==", "'production'", ")", "{", "// use err.stack, which typically includes err.message", "msg", "=", "err", ".", "stack", "// fallback to err.toString() when possible", "if", "(", "!", "msg", "&&", "typeof", "err", ".", "toString", "===", "'function'", ")", "{", "msg", "=", "err", ".", "toString", "(", ")", "}", "}", "return", "msg", "||", "statuses", "[", "status", "]", "}" ]
Get message from Error object, fallback to status message. @param {Error} err @param {number} status @param {string} env @return {string} @private
[ "Get", "message", "from", "Error", "object", "fallback", "to", "status", "message", "." ]
1b2c36949db50aa766d4691a5f38eb6639d01d66
https://github.com/pillarjs/finalhandler/blob/1b2c36949db50aa766d4691a5f38eb6639d01d66/index.js#L171-L185
20,756
pillarjs/finalhandler
index.js
getErrorStatusCode
function getErrorStatusCode (err) { // check err.status if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { return err.status } // check err.statusCode if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { return err.statusCode } return undefined }
javascript
function getErrorStatusCode (err) { // check err.status if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { return err.status } // check err.statusCode if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { return err.statusCode } return undefined }
[ "function", "getErrorStatusCode", "(", "err", ")", "{", "// check err.status", "if", "(", "typeof", "err", ".", "status", "===", "'number'", "&&", "err", ".", "status", ">=", "400", "&&", "err", ".", "status", "<", "600", ")", "{", "return", "err", ".", "status", "}", "// check err.statusCode", "if", "(", "typeof", "err", ".", "statusCode", "===", "'number'", "&&", "err", ".", "statusCode", ">=", "400", "&&", "err", ".", "statusCode", "<", "600", ")", "{", "return", "err", ".", "statusCode", "}", "return", "undefined", "}" ]
Get status code from Error object. @param {Error} err @return {number} @private
[ "Get", "status", "code", "from", "Error", "object", "." ]
1b2c36949db50aa766d4691a5f38eb6639d01d66
https://github.com/pillarjs/finalhandler/blob/1b2c36949db50aa766d4691a5f38eb6639d01d66/index.js#L195-L207
20,757
pillarjs/finalhandler
index.js
getResponseStatusCode
function getResponseStatusCode (res) { var status = res.statusCode // default status code to 500 if outside valid range if (typeof status !== 'number' || status < 400 || status > 599) { status = 500 } return status }
javascript
function getResponseStatusCode (res) { var status = res.statusCode // default status code to 500 if outside valid range if (typeof status !== 'number' || status < 400 || status > 599) { status = 500 } return status }
[ "function", "getResponseStatusCode", "(", "res", ")", "{", "var", "status", "=", "res", ".", "statusCode", "// default status code to 500 if outside valid range", "if", "(", "typeof", "status", "!==", "'number'", "||", "status", "<", "400", "||", "status", ">", "599", ")", "{", "status", "=", "500", "}", "return", "status", "}" ]
Get status code from response. @param {OutgoingMessage} res @return {number} @private
[ "Get", "status", "code", "from", "response", "." ]
1b2c36949db50aa766d4691a5f38eb6639d01d66
https://github.com/pillarjs/finalhandler/blob/1b2c36949db50aa766d4691a5f38eb6639d01d66/index.js#L236-L245
20,758
pillarjs/finalhandler
index.js
setHeaders
function setHeaders (res, headers) { if (!headers) { return } var keys = Object.keys(headers) for (var i = 0; i < keys.length; i++) { var key = keys[i] res.setHeader(key, headers[key]) } }
javascript
function setHeaders (res, headers) { if (!headers) { return } var keys = Object.keys(headers) for (var i = 0; i < keys.length; i++) { var key = keys[i] res.setHeader(key, headers[key]) } }
[ "function", "setHeaders", "(", "res", ",", "headers", ")", "{", "if", "(", "!", "headers", ")", "{", "return", "}", "var", "keys", "=", "Object", ".", "keys", "(", "headers", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "keys", "[", "i", "]", "res", ".", "setHeader", "(", "key", ",", "headers", "[", "key", "]", ")", "}", "}" ]
Set response headers from an object. @param {OutgoingMessage} res @param {object} headers @private
[ "Set", "response", "headers", "from", "an", "object", "." ]
1b2c36949db50aa766d4691a5f38eb6639d01d66
https://github.com/pillarjs/finalhandler/blob/1b2c36949db50aa766d4691a5f38eb6639d01d66/index.js#L321-L331
20,759
Peer5/videojs-contrib-hls.js
src/videojs.hlsjs.js
Html5HlsJS
function Html5HlsJS(source, tech) { var options = tech.options_; var el = tech.el(); var duration = null; var hls = this.hls = new Hls(options.hlsjsConfig); /** * creates an error handler function * @returns {Function} */ function errorHandlerFactory() { var _recoverDecodingErrorDate = null; var _recoverAudioCodecErrorDate = null; return function() { var now = Date.now(); if (!_recoverDecodingErrorDate || (now - _recoverDecodingErrorDate) > 2000) { _recoverDecodingErrorDate = now; hls.recoverMediaError(); } else if (!_recoverAudioCodecErrorDate || (now - _recoverAudioCodecErrorDate) > 2000) { _recoverAudioCodecErrorDate = now; hls.swapAudioCodec(); hls.recoverMediaError(); } else { console.error('Error loading media: File could not be played'); } }; } // create separate error handlers for hlsjs and the video tag var hlsjsErrorHandler = errorHandlerFactory(); var videoTagErrorHandler = errorHandlerFactory(); // listen to error events coming from the video tag el.addEventListener('error', function(e) { var mediaError = e.currentTarget.error; if (mediaError.code === mediaError.MEDIA_ERR_DECODE) { videoTagErrorHandler(); } else { console.error('Error loading media: File could not be played'); } }); /** * Destroys the Hls instance */ this.dispose = function() { hls.destroy(); }; /** * returns the duration of the stream, or Infinity if live video * @returns {Infinity|number} */ this.duration = function() { return duration || el.duration || 0; }; // update live status on level load hls.on(Hls.Events.LEVEL_LOADED, function(event, data) { duration = data.details.live ? Infinity : data.details.totalduration; }); // try to recover on fatal errors hls.on(Hls.Events.ERROR, function(event, data) { if (data.fatal) { switch (data.type) { case Hls.ErrorTypes.NETWORK_ERROR: hls.startLoad(); break; case Hls.ErrorTypes.MEDIA_ERROR: hlsjsErrorHandler(); break; default: console.error('Error loading media: File could not be played'); break; } } }); Object.keys(Hls.Events).forEach(function(key) { var eventName = Hls.Events[key]; hls.on(eventName, function(event, data) { tech.trigger(eventName, data); }); }); // Intercept native TextTrack calls and route to video.js directly only // if native text tracks are not supported on this browser. if (!tech.featuresNativeTextTracks) { Object.defineProperty(el, 'textTracks', { value: tech.textTracks, writable: false }); el.addTextTrack = function() { return tech.addTextTrack.apply(tech, arguments); }; } // attach hlsjs to videotag hls.attachMedia(el); hls.loadSource(source.src); }
javascript
function Html5HlsJS(source, tech) { var options = tech.options_; var el = tech.el(); var duration = null; var hls = this.hls = new Hls(options.hlsjsConfig); /** * creates an error handler function * @returns {Function} */ function errorHandlerFactory() { var _recoverDecodingErrorDate = null; var _recoverAudioCodecErrorDate = null; return function() { var now = Date.now(); if (!_recoverDecodingErrorDate || (now - _recoverDecodingErrorDate) > 2000) { _recoverDecodingErrorDate = now; hls.recoverMediaError(); } else if (!_recoverAudioCodecErrorDate || (now - _recoverAudioCodecErrorDate) > 2000) { _recoverAudioCodecErrorDate = now; hls.swapAudioCodec(); hls.recoverMediaError(); } else { console.error('Error loading media: File could not be played'); } }; } // create separate error handlers for hlsjs and the video tag var hlsjsErrorHandler = errorHandlerFactory(); var videoTagErrorHandler = errorHandlerFactory(); // listen to error events coming from the video tag el.addEventListener('error', function(e) { var mediaError = e.currentTarget.error; if (mediaError.code === mediaError.MEDIA_ERR_DECODE) { videoTagErrorHandler(); } else { console.error('Error loading media: File could not be played'); } }); /** * Destroys the Hls instance */ this.dispose = function() { hls.destroy(); }; /** * returns the duration of the stream, or Infinity if live video * @returns {Infinity|number} */ this.duration = function() { return duration || el.duration || 0; }; // update live status on level load hls.on(Hls.Events.LEVEL_LOADED, function(event, data) { duration = data.details.live ? Infinity : data.details.totalduration; }); // try to recover on fatal errors hls.on(Hls.Events.ERROR, function(event, data) { if (data.fatal) { switch (data.type) { case Hls.ErrorTypes.NETWORK_ERROR: hls.startLoad(); break; case Hls.ErrorTypes.MEDIA_ERROR: hlsjsErrorHandler(); break; default: console.error('Error loading media: File could not be played'); break; } } }); Object.keys(Hls.Events).forEach(function(key) { var eventName = Hls.Events[key]; hls.on(eventName, function(event, data) { tech.trigger(eventName, data); }); }); // Intercept native TextTrack calls and route to video.js directly only // if native text tracks are not supported on this browser. if (!tech.featuresNativeTextTracks) { Object.defineProperty(el, 'textTracks', { value: tech.textTracks, writable: false }); el.addTextTrack = function() { return tech.addTextTrack.apply(tech, arguments); }; } // attach hlsjs to videotag hls.attachMedia(el); hls.loadSource(source.src); }
[ "function", "Html5HlsJS", "(", "source", ",", "tech", ")", "{", "var", "options", "=", "tech", ".", "options_", ";", "var", "el", "=", "tech", ".", "el", "(", ")", ";", "var", "duration", "=", "null", ";", "var", "hls", "=", "this", ".", "hls", "=", "new", "Hls", "(", "options", ".", "hlsjsConfig", ")", ";", "/**\n * creates an error handler function\n * @returns {Function}\n */", "function", "errorHandlerFactory", "(", ")", "{", "var", "_recoverDecodingErrorDate", "=", "null", ";", "var", "_recoverAudioCodecErrorDate", "=", "null", ";", "return", "function", "(", ")", "{", "var", "now", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "!", "_recoverDecodingErrorDate", "||", "(", "now", "-", "_recoverDecodingErrorDate", ")", ">", "2000", ")", "{", "_recoverDecodingErrorDate", "=", "now", ";", "hls", ".", "recoverMediaError", "(", ")", ";", "}", "else", "if", "(", "!", "_recoverAudioCodecErrorDate", "||", "(", "now", "-", "_recoverAudioCodecErrorDate", ")", ">", "2000", ")", "{", "_recoverAudioCodecErrorDate", "=", "now", ";", "hls", ".", "swapAudioCodec", "(", ")", ";", "hls", ".", "recoverMediaError", "(", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'Error loading media: File could not be played'", ")", ";", "}", "}", ";", "}", "// create separate error handlers for hlsjs and the video tag", "var", "hlsjsErrorHandler", "=", "errorHandlerFactory", "(", ")", ";", "var", "videoTagErrorHandler", "=", "errorHandlerFactory", "(", ")", ";", "// listen to error events coming from the video tag", "el", ".", "addEventListener", "(", "'error'", ",", "function", "(", "e", ")", "{", "var", "mediaError", "=", "e", ".", "currentTarget", ".", "error", ";", "if", "(", "mediaError", ".", "code", "===", "mediaError", ".", "MEDIA_ERR_DECODE", ")", "{", "videoTagErrorHandler", "(", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'Error loading media: File could not be played'", ")", ";", "}", "}", ")", ";", "/**\n * Destroys the Hls instance\n */", "this", ".", "dispose", "=", "function", "(", ")", "{", "hls", ".", "destroy", "(", ")", ";", "}", ";", "/**\n * returns the duration of the stream, or Infinity if live video\n * @returns {Infinity|number}\n */", "this", ".", "duration", "=", "function", "(", ")", "{", "return", "duration", "||", "el", ".", "duration", "||", "0", ";", "}", ";", "// update live status on level load", "hls", ".", "on", "(", "Hls", ".", "Events", ".", "LEVEL_LOADED", ",", "function", "(", "event", ",", "data", ")", "{", "duration", "=", "data", ".", "details", ".", "live", "?", "Infinity", ":", "data", ".", "details", ".", "totalduration", ";", "}", ")", ";", "// try to recover on fatal errors", "hls", ".", "on", "(", "Hls", ".", "Events", ".", "ERROR", ",", "function", "(", "event", ",", "data", ")", "{", "if", "(", "data", ".", "fatal", ")", "{", "switch", "(", "data", ".", "type", ")", "{", "case", "Hls", ".", "ErrorTypes", ".", "NETWORK_ERROR", ":", "hls", ".", "startLoad", "(", ")", ";", "break", ";", "case", "Hls", ".", "ErrorTypes", ".", "MEDIA_ERROR", ":", "hlsjsErrorHandler", "(", ")", ";", "break", ";", "default", ":", "console", ".", "error", "(", "'Error loading media: File could not be played'", ")", ";", "break", ";", "}", "}", "}", ")", ";", "Object", ".", "keys", "(", "Hls", ".", "Events", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "eventName", "=", "Hls", ".", "Events", "[", "key", "]", ";", "hls", ".", "on", "(", "eventName", ",", "function", "(", "event", ",", "data", ")", "{", "tech", ".", "trigger", "(", "eventName", ",", "data", ")", ";", "}", ")", ";", "}", ")", ";", "// Intercept native TextTrack calls and route to video.js directly only", "// if native text tracks are not supported on this browser.", "if", "(", "!", "tech", ".", "featuresNativeTextTracks", ")", "{", "Object", ".", "defineProperty", "(", "el", ",", "'textTracks'", ",", "{", "value", ":", "tech", ".", "textTracks", ",", "writable", ":", "false", "}", ")", ";", "el", ".", "addTextTrack", "=", "function", "(", ")", "{", "return", "tech", ".", "addTextTrack", ".", "apply", "(", "tech", ",", "arguments", ")", ";", "}", ";", "}", "// attach hlsjs to videotag", "hls", ".", "attachMedia", "(", "el", ")", ";", "hls", ".", "loadSource", "(", "source", ".", "src", ")", ";", "}" ]
hls.js source handler @param source @param tech @constructor
[ "hls", ".", "js", "source", "handler" ]
9e1faddae5adbd27860b602376a705c793d5ff71
https://github.com/Peer5/videojs-contrib-hls.js/blob/9e1faddae5adbd27860b602376a705c793d5ff71/src/videojs.hlsjs.js#L15-L122
20,760
Peer5/videojs-contrib-hls.js
src/videojs.hlsjs.js
errorHandlerFactory
function errorHandlerFactory() { var _recoverDecodingErrorDate = null; var _recoverAudioCodecErrorDate = null; return function() { var now = Date.now(); if (!_recoverDecodingErrorDate || (now - _recoverDecodingErrorDate) > 2000) { _recoverDecodingErrorDate = now; hls.recoverMediaError(); } else if (!_recoverAudioCodecErrorDate || (now - _recoverAudioCodecErrorDate) > 2000) { _recoverAudioCodecErrorDate = now; hls.swapAudioCodec(); hls.recoverMediaError(); } else { console.error('Error loading media: File could not be played'); } }; }
javascript
function errorHandlerFactory() { var _recoverDecodingErrorDate = null; var _recoverAudioCodecErrorDate = null; return function() { var now = Date.now(); if (!_recoverDecodingErrorDate || (now - _recoverDecodingErrorDate) > 2000) { _recoverDecodingErrorDate = now; hls.recoverMediaError(); } else if (!_recoverAudioCodecErrorDate || (now - _recoverAudioCodecErrorDate) > 2000) { _recoverAudioCodecErrorDate = now; hls.swapAudioCodec(); hls.recoverMediaError(); } else { console.error('Error loading media: File could not be played'); } }; }
[ "function", "errorHandlerFactory", "(", ")", "{", "var", "_recoverDecodingErrorDate", "=", "null", ";", "var", "_recoverAudioCodecErrorDate", "=", "null", ";", "return", "function", "(", ")", "{", "var", "now", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "!", "_recoverDecodingErrorDate", "||", "(", "now", "-", "_recoverDecodingErrorDate", ")", ">", "2000", ")", "{", "_recoverDecodingErrorDate", "=", "now", ";", "hls", ".", "recoverMediaError", "(", ")", ";", "}", "else", "if", "(", "!", "_recoverAudioCodecErrorDate", "||", "(", "now", "-", "_recoverAudioCodecErrorDate", ")", ">", "2000", ")", "{", "_recoverAudioCodecErrorDate", "=", "now", ";", "hls", ".", "swapAudioCodec", "(", ")", ";", "hls", ".", "recoverMediaError", "(", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'Error loading media: File could not be played'", ")", ";", "}", "}", ";", "}" ]
creates an error handler function @returns {Function}
[ "creates", "an", "error", "handler", "function" ]
9e1faddae5adbd27860b602376a705c793d5ff71
https://github.com/Peer5/videojs-contrib-hls.js/blob/9e1faddae5adbd27860b602376a705c793d5ff71/src/videojs.hlsjs.js#L25-L45
20,761
gfranko/jquery.selectBoxIt.js
src/javascripts/modules/jquery.selectBoxIt.core.js
function() { // Used to make sure the dropdown becomes focused (fixes IE issue) self.dropdown.trigger("focus", true); // The `click` handler logic will only be applied if the dropdown list is enabled if (!self.originalElem.disabled) { // Triggers the `click` event on the original select box self.triggerEvent("click"); if(!nativeMousedown && !customShowHideEvent) { self.toggle(); } } }
javascript
function() { // Used to make sure the dropdown becomes focused (fixes IE issue) self.dropdown.trigger("focus", true); // The `click` handler logic will only be applied if the dropdown list is enabled if (!self.originalElem.disabled) { // Triggers the `click` event on the original select box self.triggerEvent("click"); if(!nativeMousedown && !customShowHideEvent) { self.toggle(); } } }
[ "function", "(", ")", "{", "// Used to make sure the dropdown becomes focused (fixes IE issue)", "self", ".", "dropdown", ".", "trigger", "(", "\"focus\"", ",", "true", ")", ";", "// The `click` handler logic will only be applied if the dropdown list is enabled", "if", "(", "!", "self", ".", "originalElem", ".", "disabled", ")", "{", "// Triggers the `click` event on the original select box", "self", ".", "triggerEvent", "(", "\"click\"", ")", ";", "if", "(", "!", "nativeMousedown", "&&", "!", "customShowHideEvent", ")", "{", "self", ".", "toggle", "(", ")", ";", "}", "}", "}" ]
`click` event with the `selectBoxIt` namespace
[ "click", "event", "with", "the", "selectBoxIt", "namespace" ]
31d714060aa94d980be57b2fc052eb7ae73f486e
https://github.com/gfranko/jquery.selectBoxIt.js/blob/31d714060aa94d980be57b2fc052eb7ae73f486e/src/javascripts/modules/jquery.selectBoxIt.core.js#L1135-L1154
20,762
gfranko/jquery.selectBoxIt.js
src/javascripts/modules/jquery.selectBoxIt.core.js
function(e) { // Stores the `keycode` value in a local variable var currentKey = self._keyMappings[e.keyCode], keydownMethod = self._keydownMethods()[currentKey]; if(keydownMethod) { keydownMethod(); if(self.options["keydownOpen"] && (currentKey === "up" || currentKey === "down")) { self.open(); } } if(keydownMethod && currentKey !== "tab") { e.preventDefault(); } }
javascript
function(e) { // Stores the `keycode` value in a local variable var currentKey = self._keyMappings[e.keyCode], keydownMethod = self._keydownMethods()[currentKey]; if(keydownMethod) { keydownMethod(); if(self.options["keydownOpen"] && (currentKey === "up" || currentKey === "down")) { self.open(); } } if(keydownMethod && currentKey !== "tab") { e.preventDefault(); } }
[ "function", "(", "e", ")", "{", "// Stores the `keycode` value in a local variable", "var", "currentKey", "=", "self", ".", "_keyMappings", "[", "e", ".", "keyCode", "]", ",", "keydownMethod", "=", "self", ".", "_keydownMethods", "(", ")", "[", "currentKey", "]", ";", "if", "(", "keydownMethod", ")", "{", "keydownMethod", "(", ")", ";", "if", "(", "self", ".", "options", "[", "\"keydownOpen\"", "]", "&&", "(", "currentKey", "===", "\"up\"", "||", "currentKey", "===", "\"down\"", ")", ")", "{", "self", ".", "open", "(", ")", ";", "}", "}", "if", "(", "keydownMethod", "&&", "currentKey", "!==", "\"tab\"", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "}", "}" ]
`keydown` event with the `selectBoxIt` namespace. Catches all user keyboard navigations
[ "keydown", "event", "with", "the", "selectBoxIt", "namespace", ".", "Catches", "all", "user", "keyboard", "navigations" ]
31d714060aa94d980be57b2fc052eb7ae73f486e
https://github.com/gfranko/jquery.selectBoxIt.js/blob/31d714060aa94d980be57b2fc052eb7ae73f486e/src/javascripts/modules/jquery.selectBoxIt.core.js#L1237-L1262
20,763
gfranko/jquery.selectBoxIt.js
src/javascripts/modules/jquery.selectBoxIt.core.js
function(e) { if (!self.originalElem.disabled) { // Sets the current key to the `keyCode` value if `charCode` does not exist. Used for cross // browser support since IE uses `keyCode` instead of `charCode`. var currentKey = e.charCode || e.keyCode, key = self._keyMappings[e.charCode || e.keyCode], // Converts unicode values to characters alphaNumericKey = String.fromCharCode(currentKey); // If the plugin options allow text searches if (self.search && (!key || (key && key === "space"))) { // Calls `search` and passes the character value of the user's text search self.search(alphaNumericKey, true, true); } if(key === "space") { e.preventDefault(); } } }
javascript
function(e) { if (!self.originalElem.disabled) { // Sets the current key to the `keyCode` value if `charCode` does not exist. Used for cross // browser support since IE uses `keyCode` instead of `charCode`. var currentKey = e.charCode || e.keyCode, key = self._keyMappings[e.charCode || e.keyCode], // Converts unicode values to characters alphaNumericKey = String.fromCharCode(currentKey); // If the plugin options allow text searches if (self.search && (!key || (key && key === "space"))) { // Calls `search` and passes the character value of the user's text search self.search(alphaNumericKey, true, true); } if(key === "space") { e.preventDefault(); } } }
[ "function", "(", "e", ")", "{", "if", "(", "!", "self", ".", "originalElem", ".", "disabled", ")", "{", "// Sets the current key to the `keyCode` value if `charCode` does not exist. Used for cross", "// browser support since IE uses `keyCode` instead of `charCode`.", "var", "currentKey", "=", "e", ".", "charCode", "||", "e", ".", "keyCode", ",", "key", "=", "self", ".", "_keyMappings", "[", "e", ".", "charCode", "||", "e", ".", "keyCode", "]", ",", "// Converts unicode values to characters", "alphaNumericKey", "=", "String", ".", "fromCharCode", "(", "currentKey", ")", ";", "// If the plugin options allow text searches", "if", "(", "self", ".", "search", "&&", "(", "!", "key", "||", "(", "key", "&&", "key", "===", "\"space\"", ")", ")", ")", "{", "// Calls `search` and passes the character value of the user's text search", "self", ".", "search", "(", "alphaNumericKey", ",", "true", ",", "true", ")", ";", "}", "if", "(", "key", "===", "\"space\"", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "}", "}", "}" ]
`keypress` event with the `selectBoxIt` namespace. Catches all user keyboard text searches since you can only reliably get character codes using the `keypress` event
[ "keypress", "event", "with", "the", "selectBoxIt", "namespace", ".", "Catches", "all", "user", "keyboard", "text", "searches", "since", "you", "can", "only", "reliably", "get", "character", "codes", "using", "the", "keypress", "event" ]
31d714060aa94d980be57b2fc052eb7ae73f486e
https://github.com/gfranko/jquery.selectBoxIt.js/blob/31d714060aa94d980be57b2fc052eb7ae73f486e/src/javascripts/modules/jquery.selectBoxIt.core.js#L1265-L1291
20,764
gfranko/jquery.selectBoxIt.js
src/javascripts/modules/jquery.selectBoxIt.core.js
function() { // Removes the hover class from the previous drop down option self.listItems.not($(this)).removeAttr("data-active"); $(this).attr("data-active", ""); var listIsHidden = self.list.is(":hidden"); if((self.options["searchWhenHidden"] && listIsHidden) || self.options["aggressiveChange"] || (listIsHidden && self.options["selectWhenHidden"])) { self._update($(this)); } // Adds the focus CSS class to the currently focused dropdown list option $(this).addClass(focusClass); }
javascript
function() { // Removes the hover class from the previous drop down option self.listItems.not($(this)).removeAttr("data-active"); $(this).attr("data-active", ""); var listIsHidden = self.list.is(":hidden"); if((self.options["searchWhenHidden"] && listIsHidden) || self.options["aggressiveChange"] || (listIsHidden && self.options["selectWhenHidden"])) { self._update($(this)); } // Adds the focus CSS class to the currently focused dropdown list option $(this).addClass(focusClass); }
[ "function", "(", ")", "{", "// Removes the hover class from the previous drop down option", "self", ".", "listItems", ".", "not", "(", "$", "(", "this", ")", ")", ".", "removeAttr", "(", "\"data-active\"", ")", ";", "$", "(", "this", ")", ".", "attr", "(", "\"data-active\"", ",", "\"\"", ")", ";", "var", "listIsHidden", "=", "self", ".", "list", ".", "is", "(", "\":hidden\"", ")", ";", "if", "(", "(", "self", ".", "options", "[", "\"searchWhenHidden\"", "]", "&&", "listIsHidden", ")", "||", "self", ".", "options", "[", "\"aggressiveChange\"", "]", "||", "(", "listIsHidden", "&&", "self", ".", "options", "[", "\"selectWhenHidden\"", "]", ")", ")", "{", "self", ".", "_update", "(", "$", "(", "this", ")", ")", ";", "}", "// Adds the focus CSS class to the currently focused dropdown list option", "$", "(", "this", ")", ".", "addClass", "(", "focusClass", ")", ";", "}" ]
Delegates the `focusin` event with the `selectBoxIt` namespace to the list items
[ "Delegates", "the", "focusin", "event", "with", "the", "selectBoxIt", "namespace", "to", "the", "list", "items" ]
31d714060aa94d980be57b2fc052eb7ae73f486e
https://github.com/gfranko/jquery.selectBoxIt.js/blob/31d714060aa94d980be57b2fc052eb7ae73f486e/src/javascripts/modules/jquery.selectBoxIt.core.js#L1367-L1385
20,765
gfranko/jquery.selectBoxIt.js
src/javascripts/modules/jquery.selectBoxIt.core.js
function() { if(nativeMousedown && !customShowHideEvent) { self._update($(this)); self.triggerEvent("option-mouseup"); // If the current drop down option is not disabled if ($(this).attr("data-disabled") === "false" && $(this).attr("data-preventclose") !== "true") { // Closes the drop down list self.close(); } } }
javascript
function() { if(nativeMousedown && !customShowHideEvent) { self._update($(this)); self.triggerEvent("option-mouseup"); // If the current drop down option is not disabled if ($(this).attr("data-disabled") === "false" && $(this).attr("data-preventclose") !== "true") { // Closes the drop down list self.close(); } } }
[ "function", "(", ")", "{", "if", "(", "nativeMousedown", "&&", "!", "customShowHideEvent", ")", "{", "self", ".", "_update", "(", "$", "(", "this", ")", ")", ";", "self", ".", "triggerEvent", "(", "\"option-mouseup\"", ")", ";", "// If the current drop down option is not disabled", "if", "(", "$", "(", "this", ")", ".", "attr", "(", "\"data-disabled\"", ")", "===", "\"false\"", "&&", "$", "(", "this", ")", ".", "attr", "(", "\"data-preventclose\"", ")", "!==", "\"true\"", ")", "{", "// Closes the drop down list", "self", ".", "close", "(", ")", ";", "}", "}", "}" ]
Delegates the `focus` event with the `selectBoxIt` namespace to the list items
[ "Delegates", "the", "focus", "event", "with", "the", "selectBoxIt", "namespace", "to", "the", "list", "items" ]
31d714060aa94d980be57b2fc052eb7ae73f486e
https://github.com/gfranko/jquery.selectBoxIt.js/blob/31d714060aa94d980be57b2fc052eb7ae73f486e/src/javascripts/modules/jquery.selectBoxIt.core.js#L1388-L1406
20,766
gfranko/jquery.selectBoxIt.js
src/javascripts/modules/jquery.selectBoxIt.core.js
function() { // If the currently moused over drop down option is not disabled if($(this).attr("data-disabled") === "false") { self.listItems.removeAttr("data-active"); $(this).addClass(focusClass).attr("data-active", ""); // Sets the dropdown list indropdownidual options back to the default state and sets the focus CSS class on the currently hovered option self.listItems.not($(this)).removeClass(focusClass); $(this).addClass(focusClass); self.currentFocus = +$(this).attr("data-id"); } }
javascript
function() { // If the currently moused over drop down option is not disabled if($(this).attr("data-disabled") === "false") { self.listItems.removeAttr("data-active"); $(this).addClass(focusClass).attr("data-active", ""); // Sets the dropdown list indropdownidual options back to the default state and sets the focus CSS class on the currently hovered option self.listItems.not($(this)).removeClass(focusClass); $(this).addClass(focusClass); self.currentFocus = +$(this).attr("data-id"); } }
[ "function", "(", ")", "{", "// If the currently moused over drop down option is not disabled", "if", "(", "$", "(", "this", ")", ".", "attr", "(", "\"data-disabled\"", ")", "===", "\"false\"", ")", "{", "self", ".", "listItems", ".", "removeAttr", "(", "\"data-active\"", ")", ";", "$", "(", "this", ")", ".", "addClass", "(", "focusClass", ")", ".", "attr", "(", "\"data-active\"", ",", "\"\"", ")", ";", "// Sets the dropdown list indropdownidual options back to the default state and sets the focus CSS class on the currently hovered option", "self", ".", "listItems", ".", "not", "(", "$", "(", "this", ")", ")", ".", "removeClass", "(", "focusClass", ")", ";", "$", "(", "this", ")", ".", "addClass", "(", "focusClass", ")", ";", "self", ".", "currentFocus", "=", "+", "$", "(", "this", ")", ".", "attr", "(", "\"data-id\"", ")", ";", "}", "}" ]
Delegates the `mouseenter` event with the `selectBoxIt` namespace to the list items
[ "Delegates", "the", "mouseenter", "event", "with", "the", "selectBoxIt", "namespace", "to", "the", "list", "items" ]
31d714060aa94d980be57b2fc052eb7ae73f486e
https://github.com/gfranko/jquery.selectBoxIt.js/blob/31d714060aa94d980be57b2fc052eb7ae73f486e/src/javascripts/modules/jquery.selectBoxIt.core.js#L1409-L1427
20,767
gfranko/jquery.selectBoxIt.js
src/javascripts/modules/jquery.selectBoxIt.core.js
function(event, internal) { var currentOption, currentDataSelectedText; // If the user called the change method if(!internal) { currentOption = self.list.find('li[data-val="' + self.originalElem.value + '"]'); // If there is a dropdown option with the same value as the original select box element if(currentOption.length) { self.listItems.eq(self.currentFocus).removeClass(self.focusClass); self.currentFocus = +currentOption.attr("data-id"); } } currentOption = self.listItems.eq(self.currentFocus); currentDataSelectedText = currentOption.attr("data-selectedtext"); currentDataText = currentOption.attr("data-text"); currentText = currentDataText ? currentDataText: currentOption.find("a").text(); // Sets the new dropdown list text to the value of the current option self._setText(self.dropdownText, currentDataSelectedText || currentText); self.dropdownText.attr("data-val", self.originalElem.value); if(currentOption.find("i").attr("class")) { self.dropdownImage.attr("class", currentOption.find("i").attr("class")).addClass("selectboxit-default-icon"); self.dropdownImage.attr("style", currentOption.find("i").attr("style")); } // Triggers a custom changed event on the original select box self.triggerEvent("changed"); }
javascript
function(event, internal) { var currentOption, currentDataSelectedText; // If the user called the change method if(!internal) { currentOption = self.list.find('li[data-val="' + self.originalElem.value + '"]'); // If there is a dropdown option with the same value as the original select box element if(currentOption.length) { self.listItems.eq(self.currentFocus).removeClass(self.focusClass); self.currentFocus = +currentOption.attr("data-id"); } } currentOption = self.listItems.eq(self.currentFocus); currentDataSelectedText = currentOption.attr("data-selectedtext"); currentDataText = currentOption.attr("data-text"); currentText = currentDataText ? currentDataText: currentOption.find("a").text(); // Sets the new dropdown list text to the value of the current option self._setText(self.dropdownText, currentDataSelectedText || currentText); self.dropdownText.attr("data-val", self.originalElem.value); if(currentOption.find("i").attr("class")) { self.dropdownImage.attr("class", currentOption.find("i").attr("class")).addClass("selectboxit-default-icon"); self.dropdownImage.attr("style", currentOption.find("i").attr("style")); } // Triggers a custom changed event on the original select box self.triggerEvent("changed"); }
[ "function", "(", "event", ",", "internal", ")", "{", "var", "currentOption", ",", "currentDataSelectedText", ";", "// If the user called the change method", "if", "(", "!", "internal", ")", "{", "currentOption", "=", "self", ".", "list", ".", "find", "(", "'li[data-val=\"'", "+", "self", ".", "originalElem", ".", "value", "+", "'\"]'", ")", ";", "// If there is a dropdown option with the same value as the original select box element", "if", "(", "currentOption", ".", "length", ")", "{", "self", ".", "listItems", ".", "eq", "(", "self", ".", "currentFocus", ")", ".", "removeClass", "(", "self", ".", "focusClass", ")", ";", "self", ".", "currentFocus", "=", "+", "currentOption", ".", "attr", "(", "\"data-id\"", ")", ";", "}", "}", "currentOption", "=", "self", ".", "listItems", ".", "eq", "(", "self", ".", "currentFocus", ")", ";", "currentDataSelectedText", "=", "currentOption", ".", "attr", "(", "\"data-selectedtext\"", ")", ";", "currentDataText", "=", "currentOption", ".", "attr", "(", "\"data-text\"", ")", ";", "currentText", "=", "currentDataText", "?", "currentDataText", ":", "currentOption", ".", "find", "(", "\"a\"", ")", ".", "text", "(", ")", ";", "// Sets the new dropdown list text to the value of the current option", "self", ".", "_setText", "(", "self", ".", "dropdownText", ",", "currentDataSelectedText", "||", "currentText", ")", ";", "self", ".", "dropdownText", ".", "attr", "(", "\"data-val\"", ",", "self", ".", "originalElem", ".", "value", ")", ";", "if", "(", "currentOption", ".", "find", "(", "\"i\"", ")", ".", "attr", "(", "\"class\"", ")", ")", "{", "self", ".", "dropdownImage", ".", "attr", "(", "\"class\"", ",", "currentOption", ".", "find", "(", "\"i\"", ")", ".", "attr", "(", "\"class\"", ")", ")", ".", "addClass", "(", "\"selectboxit-default-icon\"", ")", ";", "self", ".", "dropdownImage", ".", "attr", "(", "\"style\"", ",", "currentOption", ".", "find", "(", "\"i\"", ")", ".", "attr", "(", "\"style\"", ")", ")", ";", "}", "// Triggers a custom changed event on the original select box", "self", ".", "triggerEvent", "(", "\"changed\"", ")", ";", "}" ]
`change` event handler with the `selectBoxIt` namespace
[ "change", "event", "handler", "with", "the", "selectBoxIt", "namespace" ]
31d714060aa94d980be57b2fc052eb7ae73f486e
https://github.com/gfranko/jquery.selectBoxIt.js/blob/31d714060aa94d980be57b2fc052eb7ae73f486e/src/javascripts/modules/jquery.selectBoxIt.core.js#L1472-L1516
20,768
gfranko/jquery.selectBoxIt.js
src/javascripts/modules/jquery.selectBoxIt.core.js
function() { var currentElem = self.list.find("li[data-val='" + self.dropdownText.attr("data-val") + "']"), activeElem; // If no current element can be found, then select the first drop down option if(!currentElem.length) { // Sets the default value of the dropdown list to the first option that is not disabled currentElem = self.listItems.not("[data-disabled=true]").first(); } self.currentFocus = +currentElem.attr("data-id"); activeElem = self.listItems.eq(self.currentFocus); self.dropdown.addClass(openClass). // Removes the focus class from the dropdown list and adds the library focus class for both the dropdown list and the currently selected dropdown list option removeClass(hoverClass).addClass(focusClass); self.listItems.removeClass(self.selectedClass). removeAttr("data-active").not(activeElem).removeClass(focusClass); activeElem.addClass(self.selectedClass).addClass(focusClass); if(self.options.hideCurrent) { activeElem.hide().promise().done(function () { self.listItems.show(); }); } }
javascript
function() { var currentElem = self.list.find("li[data-val='" + self.dropdownText.attr("data-val") + "']"), activeElem; // If no current element can be found, then select the first drop down option if(!currentElem.length) { // Sets the default value of the dropdown list to the first option that is not disabled currentElem = self.listItems.not("[data-disabled=true]").first(); } self.currentFocus = +currentElem.attr("data-id"); activeElem = self.listItems.eq(self.currentFocus); self.dropdown.addClass(openClass). // Removes the focus class from the dropdown list and adds the library focus class for both the dropdown list and the currently selected dropdown list option removeClass(hoverClass).addClass(focusClass); self.listItems.removeClass(self.selectedClass). removeAttr("data-active").not(activeElem).removeClass(focusClass); activeElem.addClass(self.selectedClass).addClass(focusClass); if(self.options.hideCurrent) { activeElem.hide().promise().done(function () { self.listItems.show(); }); } }
[ "function", "(", ")", "{", "var", "currentElem", "=", "self", ".", "list", ".", "find", "(", "\"li[data-val='\"", "+", "self", ".", "dropdownText", ".", "attr", "(", "\"data-val\"", ")", "+", "\"']\"", ")", ",", "activeElem", ";", "// If no current element can be found, then select the first drop down option", "if", "(", "!", "currentElem", ".", "length", ")", "{", "// Sets the default value of the dropdown list to the first option that is not disabled", "currentElem", "=", "self", ".", "listItems", ".", "not", "(", "\"[data-disabled=true]\"", ")", ".", "first", "(", ")", ";", "}", "self", ".", "currentFocus", "=", "+", "currentElem", ".", "attr", "(", "\"data-id\"", ")", ";", "activeElem", "=", "self", ".", "listItems", ".", "eq", "(", "self", ".", "currentFocus", ")", ";", "self", ".", "dropdown", ".", "addClass", "(", "openClass", ")", ".", "// Removes the focus class from the dropdown list and adds the library focus class for both the dropdown list and the currently selected dropdown list option", "removeClass", "(", "hoverClass", ")", ".", "addClass", "(", "focusClass", ")", ";", "self", ".", "listItems", ".", "removeClass", "(", "self", ".", "selectedClass", ")", ".", "removeAttr", "(", "\"data-active\"", ")", ".", "not", "(", "activeElem", ")", ".", "removeClass", "(", "focusClass", ")", ";", "activeElem", ".", "addClass", "(", "self", ".", "selectedClass", ")", ".", "addClass", "(", "focusClass", ")", ";", "if", "(", "self", ".", "options", ".", "hideCurrent", ")", "{", "activeElem", ".", "hide", "(", ")", ".", "promise", "(", ")", ".", "done", "(", "function", "(", ")", "{", "self", ".", "listItems", ".", "show", "(", ")", ";", "}", ")", ";", "}", "}" ]
`open` event with the `selectBoxIt` namespace
[ "open", "event", "with", "the", "selectBoxIt", "namespace" ]
31d714060aa94d980be57b2fc052eb7ae73f486e
https://github.com/gfranko/jquery.selectBoxIt.js/blob/31d714060aa94d980be57b2fc052eb7ae73f486e/src/javascripts/modules/jquery.selectBoxIt.core.js#L1535-L1569
20,769
tj/node-querystring
index.js
compact
function compact(obj) { if ('object' != typeof obj) return obj; if (isArray(obj)) { var ret = []; for (var i in obj) { if (hasOwnProperty.call(obj, i)) { ret.push(obj[i]); } } return ret; } for (var key in obj) { obj[key] = compact(obj[key]); } return obj; }
javascript
function compact(obj) { if ('object' != typeof obj) return obj; if (isArray(obj)) { var ret = []; for (var i in obj) { if (hasOwnProperty.call(obj, i)) { ret.push(obj[i]); } } return ret; } for (var key in obj) { obj[key] = compact(obj[key]); } return obj; }
[ "function", "compact", "(", "obj", ")", "{", "if", "(", "'object'", "!=", "typeof", "obj", ")", "return", "obj", ";", "if", "(", "isArray", "(", "obj", ")", ")", "{", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "in", "obj", ")", "{", "if", "(", "hasOwnProperty", ".", "call", "(", "obj", ",", "i", ")", ")", "{", "ret", ".", "push", "(", "obj", "[", "i", "]", ")", ";", "}", "}", "return", "ret", ";", "}", "for", "(", "var", "key", "in", "obj", ")", "{", "obj", "[", "key", "]", "=", "compact", "(", "obj", "[", "key", "]", ")", ";", "}", "return", "obj", ";", "}" ]
Compact sparse arrays.
[ "Compact", "sparse", "arrays", "." ]
2769b6e3a09a9dc9887be26ccd1effe9fea639d8
https://github.com/tj/node-querystring/blob/2769b6e3a09a9dc9887be26ccd1effe9fea639d8/index.js#L155-L175
20,770
tj/node-querystring
index.js
parseObject
function parseObject(obj){ var ret = { base: {} }; forEach(objectKeys(obj), function(name){ merge(ret, name, obj[name]); }); return compact(ret.base); }
javascript
function parseObject(obj){ var ret = { base: {} }; forEach(objectKeys(obj), function(name){ merge(ret, name, obj[name]); }); return compact(ret.base); }
[ "function", "parseObject", "(", "obj", ")", "{", "var", "ret", "=", "{", "base", ":", "{", "}", "}", ";", "forEach", "(", "objectKeys", "(", "obj", ")", ",", "function", "(", "name", ")", "{", "merge", "(", "ret", ",", "name", ",", "obj", "[", "name", "]", ")", ";", "}", ")", ";", "return", "compact", "(", "ret", ".", "base", ")", ";", "}" ]
Parse the given obj.
[ "Parse", "the", "given", "obj", "." ]
2769b6e3a09a9dc9887be26ccd1effe9fea639d8
https://github.com/tj/node-querystring/blob/2769b6e3a09a9dc9887be26ccd1effe9fea639d8/index.js#L181-L189
20,771
tj/node-querystring
index.js
parseString
function parseString(str, options){ var ret = reduce(String(str).split(options.separator), function(ret, pair){ var eql = indexOf(pair, '=') , brace = lastBraceInKey(pair) , key = pair.substr(0, brace || eql) , val = pair.substr(brace || eql, pair.length) , val = val.substr(indexOf(val, '=') + 1, val.length); // ?foo if ('' == key) key = pair, val = ''; if ('' == key) return ret; return merge(ret, decode(key), decode(val)); }, { base: {} }).base; return compact(ret); }
javascript
function parseString(str, options){ var ret = reduce(String(str).split(options.separator), function(ret, pair){ var eql = indexOf(pair, '=') , brace = lastBraceInKey(pair) , key = pair.substr(0, brace || eql) , val = pair.substr(brace || eql, pair.length) , val = val.substr(indexOf(val, '=') + 1, val.length); // ?foo if ('' == key) key = pair, val = ''; if ('' == key) return ret; return merge(ret, decode(key), decode(val)); }, { base: {} }).base; return compact(ret); }
[ "function", "parseString", "(", "str", ",", "options", ")", "{", "var", "ret", "=", "reduce", "(", "String", "(", "str", ")", ".", "split", "(", "options", ".", "separator", ")", ",", "function", "(", "ret", ",", "pair", ")", "{", "var", "eql", "=", "indexOf", "(", "pair", ",", "'='", ")", ",", "brace", "=", "lastBraceInKey", "(", "pair", ")", ",", "key", "=", "pair", ".", "substr", "(", "0", ",", "brace", "||", "eql", ")", ",", "val", "=", "pair", ".", "substr", "(", "brace", "||", "eql", ",", "pair", ".", "length", ")", ",", "val", "=", "val", ".", "substr", "(", "indexOf", "(", "val", ",", "'='", ")", "+", "1", ",", "val", ".", "length", ")", ";", "// ?foo", "if", "(", "''", "==", "key", ")", "key", "=", "pair", ",", "val", "=", "''", ";", "if", "(", "''", "==", "key", ")", "return", "ret", ";", "return", "merge", "(", "ret", ",", "decode", "(", "key", ")", ",", "decode", "(", "val", ")", ")", ";", "}", ",", "{", "base", ":", "{", "}", "}", ")", ".", "base", ";", "return", "compact", "(", "ret", ")", ";", "}" ]
Parse the given str.
[ "Parse", "the", "given", "str", "." ]
2769b6e3a09a9dc9887be26ccd1effe9fea639d8
https://github.com/tj/node-querystring/blob/2769b6e3a09a9dc9887be26ccd1effe9fea639d8/index.js#L195-L211
20,772
AudithSoftworks/Uniform
src/js/jquery.uniform.js
bindMany
function bindMany($el, options, events) { var name, namespaced; for (name in events) { if (events.hasOwnProperty(name)) { namespaced = name.replace(/ |$/g, options.eventNamespace); $el.bind(namespaced, events[name]); } } }
javascript
function bindMany($el, options, events) { var name, namespaced; for (name in events) { if (events.hasOwnProperty(name)) { namespaced = name.replace(/ |$/g, options.eventNamespace); $el.bind(namespaced, events[name]); } } }
[ "function", "bindMany", "(", "$el", ",", "options", ",", "events", ")", "{", "var", "name", ",", "namespaced", ";", "for", "(", "name", "in", "events", ")", "{", "if", "(", "events", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "namespaced", "=", "name", ".", "replace", "(", "/", " |$", "/", "g", ",", "options", ".", "eventNamespace", ")", ";", "$el", ".", "bind", "(", "namespaced", ",", "events", "[", "name", "]", ")", ";", "}", "}", "}" ]
For backwards compatibility with older jQuery libraries, only bind one thing at a time. Also, this function adds our namespace to events in one consistent location, shrinking the minified code. The properties on the events object are the names of the events that we are supposed to add to. It can be a space separated list. The namespace will be added automatically. @param {jQuery} $el @param {Object} options Uniform options for this element @param {Object} events Events to bind, properties are event names
[ "For", "backwards", "compatibility", "with", "older", "jQuery", "libraries", "only", "bind", "one", "thing", "at", "a", "time", ".", "Also", "this", "function", "adds", "our", "namespace", "to", "events", "in", "one", "consistent", "location", "shrinking", "the", "minified", "code", "." ]
e1c0583a4fe06493e9fb35c8fadc46b6f1de0423
https://github.com/AudithSoftworks/Uniform/blob/e1c0583a4fe06493e9fb35c8fadc46b6f1de0423/src/js/jquery.uniform.js#L49-L58
20,773
AudithSoftworks/Uniform
src/js/jquery.uniform.js
bindUi
function bindUi($el, $target, options) { bindMany($el, options, { focus: function () { $target.addClass(options.focusClass); }, blur: function () { $target.removeClass(options.focusClass); $target.removeClass(options.activeClass); }, mouseenter: function () { $target.addClass(options.hoverClass); }, mouseleave: function () { $target.removeClass(options.hoverClass); $target.removeClass(options.activeClass); }, "mousedown touchbegin": function () { if (!$el.is(":disabled")) { $target.addClass(options.activeClass); } }, "mouseup touchend": function () { $target.removeClass(options.activeClass); } }); }
javascript
function bindUi($el, $target, options) { bindMany($el, options, { focus: function () { $target.addClass(options.focusClass); }, blur: function () { $target.removeClass(options.focusClass); $target.removeClass(options.activeClass); }, mouseenter: function () { $target.addClass(options.hoverClass); }, mouseleave: function () { $target.removeClass(options.hoverClass); $target.removeClass(options.activeClass); }, "mousedown touchbegin": function () { if (!$el.is(":disabled")) { $target.addClass(options.activeClass); } }, "mouseup touchend": function () { $target.removeClass(options.activeClass); } }); }
[ "function", "bindUi", "(", "$el", ",", "$target", ",", "options", ")", "{", "bindMany", "(", "$el", ",", "options", ",", "{", "focus", ":", "function", "(", ")", "{", "$target", ".", "addClass", "(", "options", ".", "focusClass", ")", ";", "}", ",", "blur", ":", "function", "(", ")", "{", "$target", ".", "removeClass", "(", "options", ".", "focusClass", ")", ";", "$target", ".", "removeClass", "(", "options", ".", "activeClass", ")", ";", "}", ",", "mouseenter", ":", "function", "(", ")", "{", "$target", ".", "addClass", "(", "options", ".", "hoverClass", ")", ";", "}", ",", "mouseleave", ":", "function", "(", ")", "{", "$target", ".", "removeClass", "(", "options", ".", "hoverClass", ")", ";", "$target", ".", "removeClass", "(", "options", ".", "activeClass", ")", ";", "}", ",", "\"mousedown touchbegin\"", ":", "function", "(", ")", "{", "if", "(", "!", "$el", ".", "is", "(", "\":disabled\"", ")", ")", "{", "$target", ".", "addClass", "(", "options", ".", "activeClass", ")", ";", "}", "}", ",", "\"mouseup touchend\"", ":", "function", "(", ")", "{", "$target", ".", "removeClass", "(", "options", ".", "activeClass", ")", ";", "}", "}", ")", ";", "}" ]
Bind the hover, active, focus, and blur UI updates @param {jQuery} $el Original element @param {jQuery} $target Target for the events (our div/span) @param {Object} options Uniform options for the element $target
[ "Bind", "the", "hover", "active", "focus", "and", "blur", "UI", "updates" ]
e1c0583a4fe06493e9fb35c8fadc46b6f1de0423
https://github.com/AudithSoftworks/Uniform/blob/e1c0583a4fe06493e9fb35c8fadc46b6f1de0423/src/js/jquery.uniform.js#L67-L92
20,774
AudithSoftworks/Uniform
src/js/jquery.uniform.js
divSpanWrap
function divSpanWrap($el, $container, method) { switch (method) { case "after": // Result: <element /> <container /> $el.after($container); return $el.next(); case "before": // Result: <container /> <element /> $el.before($container); return $el.prev(); case "wrap": // Result: <container> <element /> </container> $el.wrap($container); return $el.parent(); } return null; }
javascript
function divSpanWrap($el, $container, method) { switch (method) { case "after": // Result: <element /> <container /> $el.after($container); return $el.next(); case "before": // Result: <container /> <element /> $el.before($container); return $el.prev(); case "wrap": // Result: <container> <element /> </container> $el.wrap($container); return $el.parent(); } return null; }
[ "function", "divSpanWrap", "(", "$el", ",", "$container", ",", "method", ")", "{", "switch", "(", "method", ")", "{", "case", "\"after\"", ":", "// Result: <element /> <container />", "$el", ".", "after", "(", "$container", ")", ";", "return", "$el", ".", "next", "(", ")", ";", "case", "\"before\"", ":", "// Result: <container /> <element />", "$el", ".", "before", "(", "$container", ")", ";", "return", "$el", ".", "prev", "(", ")", ";", "case", "\"wrap\"", ":", "// Result: <container> <element /> </container>", "$el", ".", "wrap", "(", "$container", ")", ";", "return", "$el", ".", "parent", "(", ")", ";", "}", "return", "null", ";", "}" ]
Wrap an element inside of a container or put the container next to the element. See the code for examples of the different methods. Returns the container that was added to the HTML. @param {jQuery} $el Element to wrap @param {jQuery} $container Add this new container around/near $el @param {String} method One of "after", "before" or "wrap" @return {jQuery} $container after it has been cloned for adding to $el
[ "Wrap", "an", "element", "inside", "of", "a", "container", "or", "put", "the", "container", "next", "to", "the", "element", ".", "See", "the", "code", "for", "examples", "of", "the", "different", "methods", "." ]
e1c0583a4fe06493e9fb35c8fadc46b6f1de0423
https://github.com/AudithSoftworks/Uniform/blob/e1c0583a4fe06493e9fb35c8fadc46b6f1de0423/src/js/jquery.uniform.js#L176-L193
20,775
AudithSoftworks/Uniform
src/js/jquery.uniform.js
highContrast
function highContrast() { var c, $div, el, rgb; // High contrast mode deals with white and black rgb = 'rgb(120,2,153)'; $div = $('<div style="width:0;height:0;color:' + rgb + '">'); $('body').append($div); el = $div.get(0); // $div.css() will get the style definition, not // the actually displaying style if (wind.getComputedStyle) { c = wind.getComputedStyle(el, '').color; } else { c = (el.currentStyle || el.style || {}).color; } $div.remove(); return c.replace(/ /g, '') !== rgb; }
javascript
function highContrast() { var c, $div, el, rgb; // High contrast mode deals with white and black rgb = 'rgb(120,2,153)'; $div = $('<div style="width:0;height:0;color:' + rgb + '">'); $('body').append($div); el = $div.get(0); // $div.css() will get the style definition, not // the actually displaying style if (wind.getComputedStyle) { c = wind.getComputedStyle(el, '').color; } else { c = (el.currentStyle || el.style || {}).color; } $div.remove(); return c.replace(/ /g, '') !== rgb; }
[ "function", "highContrast", "(", ")", "{", "var", "c", ",", "$div", ",", "el", ",", "rgb", ";", "// High contrast mode deals with white and black", "rgb", "=", "'rgb(120,2,153)'", ";", "$div", "=", "$", "(", "'<div style=\"width:0;height:0;color:'", "+", "rgb", "+", "'\">'", ")", ";", "$", "(", "'body'", ")", ".", "append", "(", "$div", ")", ";", "el", "=", "$div", ".", "get", "(", "0", ")", ";", "// $div.css() will get the style definition, not", "// the actually displaying style", "if", "(", "wind", ".", "getComputedStyle", ")", "{", "c", "=", "wind", ".", "getComputedStyle", "(", "el", ",", "''", ")", ".", "color", ";", "}", "else", "{", "c", "=", "(", "el", ".", "currentStyle", "||", "el", ".", "style", "||", "{", "}", ")", ".", "color", ";", "}", "$div", ".", "remove", "(", ")", ";", "return", "c", ".", "replace", "(", "/", " ", "/", "g", ",", "''", ")", "!==", "rgb", ";", "}" ]
Test if high contrast mode is enabled. In high contrast mode, background images can not be set and they are always returned as 'none'. @return {Boolean} True if in high contrast mode
[ "Test", "if", "high", "contrast", "mode", "is", "enabled", "." ]
e1c0583a4fe06493e9fb35c8fadc46b6f1de0423
https://github.com/AudithSoftworks/Uniform/blob/e1c0583a4fe06493e9fb35c8fadc46b6f1de0423/src/js/jquery.uniform.js#L286-L305
20,776
AudithSoftworks/Uniform
src/js/jquery.uniform.js
setFilename
function setFilename($el, $filenameTag, options) { var filenames = $.map($el[0].files, function (file) {return file.name}).join(', '); if (filenames === "") { filenames = options.fileDefaultHtml; } else { filenames = filenames.split(/[\/\\]+/); filenames = filenames[(filenames.length - 1)]; } $filenameTag.text(filenames); }
javascript
function setFilename($el, $filenameTag, options) { var filenames = $.map($el[0].files, function (file) {return file.name}).join(', '); if (filenames === "") { filenames = options.fileDefaultHtml; } else { filenames = filenames.split(/[\/\\]+/); filenames = filenames[(filenames.length - 1)]; } $filenameTag.text(filenames); }
[ "function", "setFilename", "(", "$el", ",", "$filenameTag", ",", "options", ")", "{", "var", "filenames", "=", "$", ".", "map", "(", "$el", "[", "0", "]", ".", "files", ",", "function", "(", "file", ")", "{", "return", "file", ".", "name", "}", ")", ".", "join", "(", "', '", ")", ";", "if", "(", "filenames", "===", "\"\"", ")", "{", "filenames", "=", "options", ".", "fileDefaultHtml", ";", "}", "else", "{", "filenames", "=", "filenames", ".", "split", "(", "/", "[\\/\\\\]+", "/", ")", ";", "filenames", "=", "filenames", "[", "(", "filenames", ".", "length", "-", "1", ")", "]", ";", "}", "$filenameTag", ".", "text", "(", "filenames", ")", ";", "}" ]
Updates the filename tag based on the value of the real input element. @param {jQuery} $el Actual form element @param {jQuery} $filenameTag Span/div to update @param {Object} options Uniform options for this element
[ "Updates", "the", "filename", "tag", "based", "on", "the", "value", "of", "the", "real", "input", "element", "." ]
e1c0583a4fe06493e9fb35c8fadc46b6f1de0423
https://github.com/AudithSoftworks/Uniform/blob/e1c0583a4fe06493e9fb35c8fadc46b6f1de0423/src/js/jquery.uniform.js#L396-L407
20,777
AudithSoftworks/Uniform
src/js/jquery.uniform.js
swap
function swap($elements, newCss, callback) { var restore, item; restore = []; $elements.each(function () { var name; for (name in newCss) { if (Object.prototype.hasOwnProperty.call(newCss, name)) { restore.push({ el: this, name: name, old: this.style[name] }); this.style[name] = newCss[name]; } } }); callback(); while (restore.length) { item = restore.pop(); item.el.style[item.name] = item.old; } }
javascript
function swap($elements, newCss, callback) { var restore, item; restore = []; $elements.each(function () { var name; for (name in newCss) { if (Object.prototype.hasOwnProperty.call(newCss, name)) { restore.push({ el: this, name: name, old: this.style[name] }); this.style[name] = newCss[name]; } } }); callback(); while (restore.length) { item = restore.pop(); item.el.style[item.name] = item.old; } }
[ "function", "swap", "(", "$elements", ",", "newCss", ",", "callback", ")", "{", "var", "restore", ",", "item", ";", "restore", "=", "[", "]", ";", "$elements", ".", "each", "(", "function", "(", ")", "{", "var", "name", ";", "for", "(", "name", "in", "newCss", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "newCss", ",", "name", ")", ")", "{", "restore", ".", "push", "(", "{", "el", ":", "this", ",", "name", ":", "name", ",", "old", ":", "this", ".", "style", "[", "name", "]", "}", ")", ";", "this", ".", "style", "[", "name", "]", "=", "newCss", "[", "name", "]", ";", "}", "}", "}", ")", ";", "callback", "(", ")", ";", "while", "(", "restore", ".", "length", ")", "{", "item", "=", "restore", ".", "pop", "(", ")", ";", "item", ".", "el", ".", "style", "[", "item", ".", "name", "]", "=", "item", ".", "old", ";", "}", "}" ]
Function from jQuery to swap some CSS values, run a callback, then restore the CSS. Modified to pass JSLint and handle undefined values with 'use strict'. @param {jQuery} $elements Element @param {Object} newCss CSS values to swap out @param {Function} callback Function to run
[ "Function", "from", "jQuery", "to", "swap", "some", "CSS", "values", "run", "a", "callback", "then", "restore", "the", "CSS", ".", "Modified", "to", "pass", "JSLint", "and", "handle", "undefined", "values", "with", "use", "strict", "." ]
e1c0583a4fe06493e9fb35c8fadc46b6f1de0423
https://github.com/AudithSoftworks/Uniform/blob/e1c0583a4fe06493e9fb35c8fadc46b6f1de0423/src/js/jquery.uniform.js#L418-L445
20,778
AudithSoftworks/Uniform
src/js/jquery.uniform.js
sizingInvisible
function sizingInvisible($el, callback) { var targets; // We wish to target ourselves and any parents as long as // they are not visible targets = $el.parents(); targets.push($el[0]); targets = targets.not(':visible'); swap(targets, { visibility: "hidden", display: "block", position: "absolute" }, callback); }
javascript
function sizingInvisible($el, callback) { var targets; // We wish to target ourselves and any parents as long as // they are not visible targets = $el.parents(); targets.push($el[0]); targets = targets.not(':visible'); swap(targets, { visibility: "hidden", display: "block", position: "absolute" }, callback); }
[ "function", "sizingInvisible", "(", "$el", ",", "callback", ")", "{", "var", "targets", ";", "// We wish to target ourselves and any parents as long as", "// they are not visible", "targets", "=", "$el", ".", "parents", "(", ")", ";", "targets", ".", "push", "(", "$el", "[", "0", "]", ")", ";", "targets", "=", "targets", ".", "not", "(", "':visible'", ")", ";", "swap", "(", "targets", ",", "{", "visibility", ":", "\"hidden\"", ",", "display", ":", "\"block\"", ",", "position", ":", "\"absolute\"", "}", ",", "callback", ")", ";", "}" ]
The browser doesn't provide sizes of elements that are not visible. This will clone an element and add it to the DOM for calculations. @param {jQuery} $el @param {Function} callback
[ "The", "browser", "doesn", "t", "provide", "sizes", "of", "elements", "that", "are", "not", "visible", ".", "This", "will", "clone", "an", "element", "and", "add", "it", "to", "the", "DOM", "for", "calculations", "." ]
e1c0583a4fe06493e9fb35c8fadc46b6f1de0423
https://github.com/AudithSoftworks/Uniform/blob/e1c0583a4fe06493e9fb35c8fadc46b6f1de0423/src/js/jquery.uniform.js#L454-L467
20,779
shakilsiraj/json-object-mapper
dist/ObjectMapper.js
function (typeName) { switch (typeName) { case Constants.STRING_TYPE: return true; case Constants.NUMBER_TYPE: return true; case Constants.BOOLEAN_TYPE: return true; case Constants.DATE_TYPE: return true; case Constants.STRING_TYPE_LOWERCASE: return true; case Constants.NUMBER_TYPE_LOWERCASE: return true; case Constants.BOOLEAN_TYPE_LOWERCASE: return true; case Constants.DATE_TYPE_LOWERCASE: return true; default: return false; } }
javascript
function (typeName) { switch (typeName) { case Constants.STRING_TYPE: return true; case Constants.NUMBER_TYPE: return true; case Constants.BOOLEAN_TYPE: return true; case Constants.DATE_TYPE: return true; case Constants.STRING_TYPE_LOWERCASE: return true; case Constants.NUMBER_TYPE_LOWERCASE: return true; case Constants.BOOLEAN_TYPE_LOWERCASE: return true; case Constants.DATE_TYPE_LOWERCASE: return true; default: return false; } }
[ "function", "(", "typeName", ")", "{", "switch", "(", "typeName", ")", "{", "case", "Constants", ".", "STRING_TYPE", ":", "return", "true", ";", "case", "Constants", ".", "NUMBER_TYPE", ":", "return", "true", ";", "case", "Constants", ".", "BOOLEAN_TYPE", ":", "return", "true", ";", "case", "Constants", ".", "DATE_TYPE", ":", "return", "true", ";", "case", "Constants", ".", "STRING_TYPE_LOWERCASE", ":", "return", "true", ";", "case", "Constants", ".", "NUMBER_TYPE_LOWERCASE", ":", "return", "true", ";", "case", "Constants", ".", "BOOLEAN_TYPE_LOWERCASE", ":", "return", "true", ";", "case", "Constants", ".", "DATE_TYPE_LOWERCASE", ":", "return", "true", ";", "default", ":", "return", "false", ";", "}", "}" ]
Checks to see if the specified type is a standard JS object type.
[ "Checks", "to", "see", "if", "the", "specified", "type", "is", "a", "standard", "JS", "object", "type", "." ]
718c8f8697080bdf7eb44701e34065b87be08e9c
https://github.com/shakilsiraj/json-object-mapper/blob/718c8f8697080bdf7eb44701e34065b87be08e9c/dist/ObjectMapper.js#L61-L73
20,780
shakilsiraj/json-object-mapper
dist/ObjectMapper.js
function (metadata) { if (typeof metadata === 'string') { return getJsonPropertyDecorator({ name: metadata, required: false, access: exports.AccessType.BOTH }); } else { return getJsonPropertyDecorator(metadata); } }
javascript
function (metadata) { if (typeof metadata === 'string') { return getJsonPropertyDecorator({ name: metadata, required: false, access: exports.AccessType.BOTH }); } else { return getJsonPropertyDecorator(metadata); } }
[ "function", "(", "metadata", ")", "{", "if", "(", "typeof", "metadata", "===", "'string'", ")", "{", "return", "getJsonPropertyDecorator", "(", "{", "name", ":", "metadata", ",", "required", ":", "false", ",", "access", ":", "exports", ".", "AccessType", ".", "BOTH", "}", ")", ";", "}", "else", "{", "return", "getJsonPropertyDecorator", "(", "metadata", ")", ";", "}", "}" ]
JsonProperty Decorator function.
[ "JsonProperty", "Decorator", "function", "." ]
718c8f8697080bdf7eb44701e34065b87be08e9c
https://github.com/shakilsiraj/json-object-mapper/blob/718c8f8697080bdf7eb44701e34065b87be08e9c/dist/ObjectMapper.js#L132-L139
20,781
shakilsiraj/json-object-mapper
dist/ObjectMapper.js
function (instance, instanceKey, type, json, jsonKey) { var jsonObject = (jsonKey !== undefined) ? (json[jsonKey] || []) : json; var jsonArraySize = jsonObject.length; var conversionFunctionsList = []; var arrayInstance = []; instance[instanceKey] = arrayInstance; if (jsonArraySize > 0) { for (var i = 0; i < jsonArraySize; i++) { if (jsonObject[i]) { var typeName = getTypeNameFromInstance(type); if (!isSimpleType(typeName)) { var typeInstance = new type(); conversionFunctionsList.push({ functionName: Constants.OBJECT_TYPE, instance: typeInstance, json: jsonObject[i] }); arrayInstance.push(typeInstance); } else { arrayInstance.push(conversionFunctions[Constants.FROM_ARRAY](jsonObject[i], typeName)); } } } } return conversionFunctionsList; }
javascript
function (instance, instanceKey, type, json, jsonKey) { var jsonObject = (jsonKey !== undefined) ? (json[jsonKey] || []) : json; var jsonArraySize = jsonObject.length; var conversionFunctionsList = []; var arrayInstance = []; instance[instanceKey] = arrayInstance; if (jsonArraySize > 0) { for (var i = 0; i < jsonArraySize; i++) { if (jsonObject[i]) { var typeName = getTypeNameFromInstance(type); if (!isSimpleType(typeName)) { var typeInstance = new type(); conversionFunctionsList.push({ functionName: Constants.OBJECT_TYPE, instance: typeInstance, json: jsonObject[i] }); arrayInstance.push(typeInstance); } else { arrayInstance.push(conversionFunctions[Constants.FROM_ARRAY](jsonObject[i], typeName)); } } } } return conversionFunctionsList; }
[ "function", "(", "instance", ",", "instanceKey", ",", "type", ",", "json", ",", "jsonKey", ")", "{", "var", "jsonObject", "=", "(", "jsonKey", "!==", "undefined", ")", "?", "(", "json", "[", "jsonKey", "]", "||", "[", "]", ")", ":", "json", ";", "var", "jsonArraySize", "=", "jsonObject", ".", "length", ";", "var", "conversionFunctionsList", "=", "[", "]", ";", "var", "arrayInstance", "=", "[", "]", ";", "instance", "[", "instanceKey", "]", "=", "arrayInstance", ";", "if", "(", "jsonArraySize", ">", "0", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "jsonArraySize", ";", "i", "++", ")", "{", "if", "(", "jsonObject", "[", "i", "]", ")", "{", "var", "typeName", "=", "getTypeNameFromInstance", "(", "type", ")", ";", "if", "(", "!", "isSimpleType", "(", "typeName", ")", ")", "{", "var", "typeInstance", "=", "new", "type", "(", ")", ";", "conversionFunctionsList", ".", "push", "(", "{", "functionName", ":", "Constants", ".", "OBJECT_TYPE", ",", "instance", ":", "typeInstance", ",", "json", ":", "jsonObject", "[", "i", "]", "}", ")", ";", "arrayInstance", ".", "push", "(", "typeInstance", ")", ";", "}", "else", "{", "arrayInstance", ".", "push", "(", "conversionFunctions", "[", "Constants", ".", "FROM_ARRAY", "]", "(", "jsonObject", "[", "i", "]", ",", "typeName", ")", ")", ";", "}", "}", "}", "}", "return", "conversionFunctionsList", ";", "}" ]
Deserializes a JS array type from json.
[ "Deserializes", "a", "JS", "array", "type", "from", "json", "." ]
718c8f8697080bdf7eb44701e34065b87be08e9c
https://github.com/shakilsiraj/json-object-mapper/blob/718c8f8697080bdf7eb44701e34065b87be08e9c/dist/ObjectMapper.js#L205-L227
20,782
shakilsiraj/json-object-mapper
dist/ObjectMapper.js
function (key, instance, serializer) { var value = serializer.serialize(instance); if (key !== undefined) { return "\"" + key + "\":" + value; } else { return value; } }
javascript
function (key, instance, serializer) { var value = serializer.serialize(instance); if (key !== undefined) { return "\"" + key + "\":" + value; } else { return value; } }
[ "function", "(", "key", ",", "instance", ",", "serializer", ")", "{", "var", "value", "=", "serializer", ".", "serialize", "(", "instance", ")", ";", "if", "(", "key", "!==", "undefined", ")", "{", "return", "\"\\\"\"", "+", "key", "+", "\"\\\":\"", "+", "value", ";", "}", "else", "{", "return", "value", ";", "}", "}" ]
Serialize any type with key value pairs
[ "Serialize", "any", "type", "with", "key", "value", "pairs" ]
718c8f8697080bdf7eb44701e34065b87be08e9c
https://github.com/shakilsiraj/json-object-mapper/blob/718c8f8697080bdf7eb44701e34065b87be08e9c/dist/ObjectMapper.js#L462-L470
20,783
klaascuvelier/gulp-copy
lib/gulp-copy.js
gulpCopy
function gulpCopy(destination, opts) { const throughOptions = { objectMode: true }; // Make sure a destination was verified if (typeof destination !== 'string') { throw new PluginError('gulp-copy', 'No valid destination specified'); } // Default options if (opts === undefined) { opts = opts || {}; } else if (typeof opts !== 'object' || opts === null) { throw new PluginError('gulp-copy', 'No valid options specified'); } return through(throughOptions, transform); /** * Transform method, copies the file to its new destination * @param {object} file * @param {string} encoding * @param {function} cb */ function transform(file, encoding, cb) { let rel = null; let fileDestination = null; if (file.isStream()) { cb(new PluginError('gulp-copy', 'Streaming not supported')); } if (file.isNull()) { cb(null, file); } else { rel = path.relative(file.cwd, file.path).replace(/\\/g, separator); // Strip path prefixes if (opts.prefix) { let p = opts.prefix; while (p-- > 0) { rel = rel.substring(rel.indexOf(separator) + 1); } } fileDestination = path.join(destination, rel); // Make sure destination exists if (!doesPathExist(fileDestination)) { createDestination(fileDestination.substr(0, fileDestination.lastIndexOf(separator))); } // Copy the file copyFile(file.path, fileDestination, function copyFileCallback(error) { if (error) { throw new PluginError('gulp-copy', `Could not copy file <${file.path}>: ${error.message}`); } // Update path for file so this path is used later on file.path = fileDestination; cb(null, file); }); } } }
javascript
function gulpCopy(destination, opts) { const throughOptions = { objectMode: true }; // Make sure a destination was verified if (typeof destination !== 'string') { throw new PluginError('gulp-copy', 'No valid destination specified'); } // Default options if (opts === undefined) { opts = opts || {}; } else if (typeof opts !== 'object' || opts === null) { throw new PluginError('gulp-copy', 'No valid options specified'); } return through(throughOptions, transform); /** * Transform method, copies the file to its new destination * @param {object} file * @param {string} encoding * @param {function} cb */ function transform(file, encoding, cb) { let rel = null; let fileDestination = null; if (file.isStream()) { cb(new PluginError('gulp-copy', 'Streaming not supported')); } if (file.isNull()) { cb(null, file); } else { rel = path.relative(file.cwd, file.path).replace(/\\/g, separator); // Strip path prefixes if (opts.prefix) { let p = opts.prefix; while (p-- > 0) { rel = rel.substring(rel.indexOf(separator) + 1); } } fileDestination = path.join(destination, rel); // Make sure destination exists if (!doesPathExist(fileDestination)) { createDestination(fileDestination.substr(0, fileDestination.lastIndexOf(separator))); } // Copy the file copyFile(file.path, fileDestination, function copyFileCallback(error) { if (error) { throw new PluginError('gulp-copy', `Could not copy file <${file.path}>: ${error.message}`); } // Update path for file so this path is used later on file.path = fileDestination; cb(null, file); }); } } }
[ "function", "gulpCopy", "(", "destination", ",", "opts", ")", "{", "const", "throughOptions", "=", "{", "objectMode", ":", "true", "}", ";", "// Make sure a destination was verified", "if", "(", "typeof", "destination", "!==", "'string'", ")", "{", "throw", "new", "PluginError", "(", "'gulp-copy'", ",", "'No valid destination specified'", ")", ";", "}", "// Default options", "if", "(", "opts", "===", "undefined", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "}", "else", "if", "(", "typeof", "opts", "!==", "'object'", "||", "opts", "===", "null", ")", "{", "throw", "new", "PluginError", "(", "'gulp-copy'", ",", "'No valid options specified'", ")", ";", "}", "return", "through", "(", "throughOptions", ",", "transform", ")", ";", "/**\n * Transform method, copies the file to its new destination\n * @param {object} file\n * @param {string} encoding\n * @param {function} cb\n */", "function", "transform", "(", "file", ",", "encoding", ",", "cb", ")", "{", "let", "rel", "=", "null", ";", "let", "fileDestination", "=", "null", ";", "if", "(", "file", ".", "isStream", "(", ")", ")", "{", "cb", "(", "new", "PluginError", "(", "'gulp-copy'", ",", "'Streaming not supported'", ")", ")", ";", "}", "if", "(", "file", ".", "isNull", "(", ")", ")", "{", "cb", "(", "null", ",", "file", ")", ";", "}", "else", "{", "rel", "=", "path", ".", "relative", "(", "file", ".", "cwd", ",", "file", ".", "path", ")", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "separator", ")", ";", "// Strip path prefixes", "if", "(", "opts", ".", "prefix", ")", "{", "let", "p", "=", "opts", ".", "prefix", ";", "while", "(", "p", "--", ">", "0", ")", "{", "rel", "=", "rel", ".", "substring", "(", "rel", ".", "indexOf", "(", "separator", ")", "+", "1", ")", ";", "}", "}", "fileDestination", "=", "path", ".", "join", "(", "destination", ",", "rel", ")", ";", "// Make sure destination exists", "if", "(", "!", "doesPathExist", "(", "fileDestination", ")", ")", "{", "createDestination", "(", "fileDestination", ".", "substr", "(", "0", ",", "fileDestination", ".", "lastIndexOf", "(", "separator", ")", ")", ")", ";", "}", "// Copy the file", "copyFile", "(", "file", ".", "path", ",", "fileDestination", ",", "function", "copyFileCallback", "(", "error", ")", "{", "if", "(", "error", ")", "{", "throw", "new", "PluginError", "(", "'gulp-copy'", ",", "`", "${", "file", ".", "path", "}", "${", "error", ".", "message", "}", "`", ")", ";", "}", "// Update path for file so this path is used later on", "file", ".", "path", "=", "fileDestination", ";", "cb", "(", "null", ",", "file", ")", ";", "}", ")", ";", "}", "}", "}" ]
gulp copy method @param {string} destination @param {object} opts @returns {object}
[ "gulp", "copy", "method" ]
4b4c3391b3704f14c7edb9f2fc149e4f801d26b1
https://github.com/klaascuvelier/gulp-copy/blob/4b4c3391b3704f14c7edb9f2fc149e4f801d26b1/lib/gulp-copy.js#L14-L77
20,784
klaascuvelier/gulp-copy
lib/gulp-copy.js
createDestination
function createDestination(destination) { const folders = destination.split(separator); const pathParts = []; const l = folders.length; // for absolute paths if (folders[0] === '') { pathParts.push(separator); folders.shift(); } for (let i = 0; i < l; i++) { pathParts.push(folders[i]); if (folders[i] !== '' && !doesPathExist(pathParts.join(separator))) { try { fs.mkdirSync(pathParts.join(separator)); } catch (error) { throw new PluginError('gulp-copy', `Could not create destination <${destination}>: ${error.message}`); } } } }
javascript
function createDestination(destination) { const folders = destination.split(separator); const pathParts = []; const l = folders.length; // for absolute paths if (folders[0] === '') { pathParts.push(separator); folders.shift(); } for (let i = 0; i < l; i++) { pathParts.push(folders[i]); if (folders[i] !== '' && !doesPathExist(pathParts.join(separator))) { try { fs.mkdirSync(pathParts.join(separator)); } catch (error) { throw new PluginError('gulp-copy', `Could not create destination <${destination}>: ${error.message}`); } } } }
[ "function", "createDestination", "(", "destination", ")", "{", "const", "folders", "=", "destination", ".", "split", "(", "separator", ")", ";", "const", "pathParts", "=", "[", "]", ";", "const", "l", "=", "folders", ".", "length", ";", "// for absolute paths", "if", "(", "folders", "[", "0", "]", "===", "''", ")", "{", "pathParts", ".", "push", "(", "separator", ")", ";", "folders", ".", "shift", "(", ")", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "pathParts", ".", "push", "(", "folders", "[", "i", "]", ")", ";", "if", "(", "folders", "[", "i", "]", "!==", "''", "&&", "!", "doesPathExist", "(", "pathParts", ".", "join", "(", "separator", ")", ")", ")", "{", "try", "{", "fs", ".", "mkdirSync", "(", "pathParts", ".", "join", "(", "separator", ")", ")", ";", "}", "catch", "(", "error", ")", "{", "throw", "new", "PluginError", "(", "'gulp-copy'", ",", "`", "${", "destination", "}", "${", "error", ".", "message", "}", "`", ")", ";", "}", "}", "}", "}" ]
Recursively creates the path @param {string} destination
[ "Recursively", "creates", "the", "path" ]
4b4c3391b3704f14c7edb9f2fc149e4f801d26b1
https://github.com/klaascuvelier/gulp-copy/blob/4b4c3391b3704f14c7edb9f2fc149e4f801d26b1/lib/gulp-copy.js#L83-L105
20,785
klaascuvelier/gulp-copy
lib/gulp-copy.js
doesPathExist
function doesPathExist(pathToVerify) { let pathExists = true; try { fs.accessSync(pathToVerify); } catch (error) { pathExists = false; } return pathExists; }
javascript
function doesPathExist(pathToVerify) { let pathExists = true; try { fs.accessSync(pathToVerify); } catch (error) { pathExists = false; } return pathExists; }
[ "function", "doesPathExist", "(", "pathToVerify", ")", "{", "let", "pathExists", "=", "true", ";", "try", "{", "fs", ".", "accessSync", "(", "pathToVerify", ")", ";", "}", "catch", "(", "error", ")", "{", "pathExists", "=", "false", ";", "}", "return", "pathExists", ";", "}" ]
Check if the path exists @param path @returns {boolean}
[ "Check", "if", "the", "path", "exists" ]
4b4c3391b3704f14c7edb9f2fc149e4f801d26b1
https://github.com/klaascuvelier/gulp-copy/blob/4b4c3391b3704f14c7edb9f2fc149e4f801d26b1/lib/gulp-copy.js#L112-L122
20,786
klaascuvelier/gulp-copy
lib/gulp-copy.js
copyFile
function copyFile(source, target, copyCallback) { const readStream = fs.createReadStream(source); const writeStream = fs.createWriteStream(target); let done = false; readStream.on('error', copyDone); writeStream.on('error', copyDone); writeStream.on('close', function onWriteCb() { copyDone(null); }); readStream.pipe(writeStream); /** * Finish copying. Reports error when needed * @param [error] optional error */ function copyDone(error) { if (!done) { done = true; copyCallback(error); } } }
javascript
function copyFile(source, target, copyCallback) { const readStream = fs.createReadStream(source); const writeStream = fs.createWriteStream(target); let done = false; readStream.on('error', copyDone); writeStream.on('error', copyDone); writeStream.on('close', function onWriteCb() { copyDone(null); }); readStream.pipe(writeStream); /** * Finish copying. Reports error when needed * @param [error] optional error */ function copyDone(error) { if (!done) { done = true; copyCallback(error); } } }
[ "function", "copyFile", "(", "source", ",", "target", ",", "copyCallback", ")", "{", "const", "readStream", "=", "fs", ".", "createReadStream", "(", "source", ")", ";", "const", "writeStream", "=", "fs", ".", "createWriteStream", "(", "target", ")", ";", "let", "done", "=", "false", ";", "readStream", ".", "on", "(", "'error'", ",", "copyDone", ")", ";", "writeStream", ".", "on", "(", "'error'", ",", "copyDone", ")", ";", "writeStream", ".", "on", "(", "'close'", ",", "function", "onWriteCb", "(", ")", "{", "copyDone", "(", "null", ")", ";", "}", ")", ";", "readStream", ".", "pipe", "(", "writeStream", ")", ";", "/**\n * Finish copying. Reports error when needed\n * @param [error] optional error\n */", "function", "copyDone", "(", "error", ")", "{", "if", "(", "!", "done", ")", "{", "done", "=", "true", ";", "copyCallback", "(", "error", ")", ";", "}", "}", "}" ]
Copy a file to its new destination @param {string} source @param {string} target @param {function} copyCallback
[ "Copy", "a", "file", "to", "its", "new", "destination" ]
4b4c3391b3704f14c7edb9f2fc149e4f801d26b1
https://github.com/klaascuvelier/gulp-copy/blob/4b4c3391b3704f14c7edb9f2fc149e4f801d26b1/lib/gulp-copy.js#L130-L154
20,787
eslint/eslint-scope
lib/index.js
defaultOptions
function defaultOptions() { return { optimistic: false, directive: false, nodejsScope: false, impliedStrict: false, sourceType: "script", // one of ['script', 'module'] ecmaVersion: 5, childVisitorKeys: null, fallback: "iteration" }; }
javascript
function defaultOptions() { return { optimistic: false, directive: false, nodejsScope: false, impliedStrict: false, sourceType: "script", // one of ['script', 'module'] ecmaVersion: 5, childVisitorKeys: null, fallback: "iteration" }; }
[ "function", "defaultOptions", "(", ")", "{", "return", "{", "optimistic", ":", "false", ",", "directive", ":", "false", ",", "nodejsScope", ":", "false", ",", "impliedStrict", ":", "false", ",", "sourceType", ":", "\"script\"", ",", "// one of ['script', 'module']", "ecmaVersion", ":", "5", ",", "childVisitorKeys", ":", "null", ",", "fallback", ":", "\"iteration\"", "}", ";", "}" ]
Set the default options @returns {Object} options
[ "Set", "the", "default", "options" ]
5d2ec4fa322095067bd5a262b0c218d1bdf9270c
https://github.com/eslint/eslint-scope/blob/5d2ec4fa322095067bd5a262b0c218d1bdf9270c/lib/index.js#L65-L76
20,788
eslint/eslint-scope
lib/index.js
updateDeeply
function updateDeeply(target, override) { /** * Is hash object * @param {Object} value - Test value * @returns {boolean} Result */ function isHashObject(value) { return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); } for (const key in override) { if (override.hasOwnProperty(key)) { const val = override[key]; if (isHashObject(val)) { if (isHashObject(target[key])) { updateDeeply(target[key], val); } else { target[key] = updateDeeply({}, val); } } else { target[key] = val; } } } return target; }
javascript
function updateDeeply(target, override) { /** * Is hash object * @param {Object} value - Test value * @returns {boolean} Result */ function isHashObject(value) { return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); } for (const key in override) { if (override.hasOwnProperty(key)) { const val = override[key]; if (isHashObject(val)) { if (isHashObject(target[key])) { updateDeeply(target[key], val); } else { target[key] = updateDeeply({}, val); } } else { target[key] = val; } } } return target; }
[ "function", "updateDeeply", "(", "target", ",", "override", ")", "{", "/**\n * Is hash object\n * @param {Object} value - Test value\n * @returns {boolean} Result\n */", "function", "isHashObject", "(", "value", ")", "{", "return", "typeof", "value", "===", "\"object\"", "&&", "value", "instanceof", "Object", "&&", "!", "(", "value", "instanceof", "Array", ")", "&&", "!", "(", "value", "instanceof", "RegExp", ")", ";", "}", "for", "(", "const", "key", "in", "override", ")", "{", "if", "(", "override", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "const", "val", "=", "override", "[", "key", "]", ";", "if", "(", "isHashObject", "(", "val", ")", ")", "{", "if", "(", "isHashObject", "(", "target", "[", "key", "]", ")", ")", "{", "updateDeeply", "(", "target", "[", "key", "]", ",", "val", ")", ";", "}", "else", "{", "target", "[", "key", "]", "=", "updateDeeply", "(", "{", "}", ",", "val", ")", ";", "}", "}", "else", "{", "target", "[", "key", "]", "=", "val", ";", "}", "}", "}", "return", "target", ";", "}" ]
Preform deep update on option object @param {Object} target - Options @param {Object} override - Updates @returns {Object} Updated options
[ "Preform", "deep", "update", "on", "option", "object" ]
5d2ec4fa322095067bd5a262b0c218d1bdf9270c
https://github.com/eslint/eslint-scope/blob/5d2ec4fa322095067bd5a262b0c218d1bdf9270c/lib/index.js#L84-L111
20,789
aws/awsmobile-cli
lib/utils/directory-file-ops.js
getDirContentMTime
function getDirContentMTime(dirPath, ignoredDirs, ignoredFiles){ let mtime if(fs.existsSync(dirPath)){ _ignoredDirs.push.apply(_ignoredDirs, ignoredDirs) _ignoredFiles.push.apply(_ignoredFiles, ignoredFiles) mtime = recursiveGetDirContentMTime(dirPath) } return mtime }
javascript
function getDirContentMTime(dirPath, ignoredDirs, ignoredFiles){ let mtime if(fs.existsSync(dirPath)){ _ignoredDirs.push.apply(_ignoredDirs, ignoredDirs) _ignoredFiles.push.apply(_ignoredFiles, ignoredFiles) mtime = recursiveGetDirContentMTime(dirPath) } return mtime }
[ "function", "getDirContentMTime", "(", "dirPath", ",", "ignoredDirs", ",", "ignoredFiles", ")", "{", "let", "mtime", "if", "(", "fs", ".", "existsSync", "(", "dirPath", ")", ")", "{", "_ignoredDirs", ".", "push", ".", "apply", "(", "_ignoredDirs", ",", "ignoredDirs", ")", "_ignoredFiles", ".", "push", ".", "apply", "(", "_ignoredFiles", ",", "ignoredFiles", ")", "mtime", "=", "recursiveGetDirContentMTime", "(", "dirPath", ")", "}", "return", "mtime", "}" ]
get the last modification time of the directory including its files and subdirectories
[ "get", "the", "last", "modification", "time", "of", "the", "directory", "including", "its", "files", "and", "subdirectories" ]
dc17aeb3975f5f3a039ed2d8a24bb2ba5ff373be
https://github.com/aws/awsmobile-cli/blob/dc17aeb3975f5f3a039ed2d8a24bb2ba5ff373be/lib/utils/directory-file-ops.js#L21-L29
20,790
aws/awsmobile-cli
lib/backend-operations/backend-spec-manager.js
onClearBackend
function onClearBackend(projectInfo){ let backendProject = getBackendProjectObject(projectInfo) if(backendProject){ backendProject.name = '' setBackendProjectObject(backendProject, projectInfo) } }
javascript
function onClearBackend(projectInfo){ let backendProject = getBackendProjectObject(projectInfo) if(backendProject){ backendProject.name = '' setBackendProjectObject(backendProject, projectInfo) } }
[ "function", "onClearBackend", "(", "projectInfo", ")", "{", "let", "backendProject", "=", "getBackendProjectObject", "(", "projectInfo", ")", "if", "(", "backendProject", ")", "{", "backendProject", ".", "name", "=", "''", "setBackendProjectObject", "(", "backendProject", ",", "projectInfo", ")", "}", "}" ]
happens with delete or detach backend project
[ "happens", "with", "delete", "or", "detach", "backend", "project" ]
dc17aeb3975f5f3a039ed2d8a24bb2ba5ff373be
https://github.com/aws/awsmobile-cli/blob/dc17aeb3975f5f3a039ed2d8a24bb2ba5ff373be/lib/backend-operations/backend-spec-manager.js#L183-L189
20,791
angular/router
src/ngRoute_shim.js
routeObjToRouteName
function routeObjToRouteName(route, path) { var name = route.controllerAs; var controller = route.controller; if (!name && controller) { if (angular.isArray(controller)) { controller = controller[controller.length - 1]; } name = controller.name; } if (!name) { var segments = path.split('/'); name = segments[segments.length - 1]; } if (name) { name = name + 'AutoCmp'; } return name; }
javascript
function routeObjToRouteName(route, path) { var name = route.controllerAs; var controller = route.controller; if (!name && controller) { if (angular.isArray(controller)) { controller = controller[controller.length - 1]; } name = controller.name; } if (!name) { var segments = path.split('/'); name = segments[segments.length - 1]; } if (name) { name = name + 'AutoCmp'; } return name; }
[ "function", "routeObjToRouteName", "(", "route", ",", "path", ")", "{", "var", "name", "=", "route", ".", "controllerAs", ";", "var", "controller", "=", "route", ".", "controller", ";", "if", "(", "!", "name", "&&", "controller", ")", "{", "if", "(", "angular", ".", "isArray", "(", "controller", ")", ")", "{", "controller", "=", "controller", "[", "controller", ".", "length", "-", "1", "]", ";", "}", "name", "=", "controller", ".", "name", ";", "}", "if", "(", "!", "name", ")", "{", "var", "segments", "=", "path", ".", "split", "(", "'/'", ")", ";", "name", "=", "segments", "[", "segments", ".", "length", "-", "1", "]", ";", "}", "if", "(", "name", ")", "{", "name", "=", "name", "+", "'AutoCmp'", ";", "}", "return", "name", ";", "}" ]
Given a route object, attempts to find a unique directive name. @param route – route config object passed to $routeProvider.when @param path – route configuration path @returns {string|name} – a normalized (camelCase) directive name
[ "Given", "a", "route", "object", "attempts", "to", "find", "a", "unique", "directive", "name", "." ]
f642b4caad6501609182487ce5e7107d9876d912
https://github.com/angular/router/blob/f642b4caad6501609182487ce5e7107d9876d912/src/ngRoute_shim.js#L300-L321
20,792
nikku/node-xsd-schema-validator
lib/validator.js
Validator
function Validator(options) { options = options || {}; this.cwd = options.cwd || process.cwd(); this.debug = !!options.debug; }
javascript
function Validator(options) { options = options || {}; this.cwd = options.cwd || process.cwd(); this.debug = !!options.debug; }
[ "function", "Validator", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "cwd", "=", "options", ".", "cwd", "||", "process", ".", "cwd", "(", ")", ";", "this", ".", "debug", "=", "!", "!", "options", ".", "debug", ";", "}" ]
Pass the current working directory as an argument @param {Object} [options] directory to search for schema resources and includes.
[ "Pass", "the", "current", "working", "directory", "as", "an", "argument" ]
fac2fb3f9ee6d1c8bbc993a2ba857a01d44b1f79
https://github.com/nikku/node-xsd-schema-validator/blob/fac2fb3f9ee6d1c8bbc993a2ba857a01d44b1f79/lib/validator.js#L48-L53
20,793
fonini/ckeditor-youtube-plugin
youtube/plugin.js
hmsToSeconds
function hmsToSeconds(time) { var arr = time.split(':'), s = 0, m = 1; while (arr.length > 0) { s += m * parseInt(arr.pop(), 10); m *= 60; } return s; }
javascript
function hmsToSeconds(time) { var arr = time.split(':'), s = 0, m = 1; while (arr.length > 0) { s += m * parseInt(arr.pop(), 10); m *= 60; } return s; }
[ "function", "hmsToSeconds", "(", "time", ")", "{", "var", "arr", "=", "time", ".", "split", "(", "':'", ")", ",", "s", "=", "0", ",", "m", "=", "1", ";", "while", "(", "arr", ".", "length", ">", "0", ")", "{", "s", "+=", "m", "*", "parseInt", "(", "arr", ".", "pop", "(", ")", ",", "10", ")", ";", "m", "*=", "60", ";", "}", "return", "s", ";", "}" ]
Converts time in hms format to seconds only
[ "Converts", "time", "in", "hms", "format", "to", "seconds", "only" ]
74d69adfc32be83378adcf02b603095a380c92e2
https://github.com/fonini/ckeditor-youtube-plugin/blob/74d69adfc32be83378adcf02b603095a380c92e2/youtube/plugin.js#L381-L390
20,794
fonini/ckeditor-youtube-plugin
youtube/plugin.js
secondsToHms
function secondsToHms(seconds) { var h = Math.floor(seconds / 3600); var m = Math.floor((seconds / 60) % 60); var s = seconds % 60; var pad = function (n) { n = String(n); return n.length >= 2 ? n : "0" + n; }; if (h > 0) { return pad(h) + ':' + pad(m) + ':' + pad(s); } else { return pad(m) + ':' + pad(s); } }
javascript
function secondsToHms(seconds) { var h = Math.floor(seconds / 3600); var m = Math.floor((seconds / 60) % 60); var s = seconds % 60; var pad = function (n) { n = String(n); return n.length >= 2 ? n : "0" + n; }; if (h > 0) { return pad(h) + ':' + pad(m) + ':' + pad(s); } else { return pad(m) + ':' + pad(s); } }
[ "function", "secondsToHms", "(", "seconds", ")", "{", "var", "h", "=", "Math", ".", "floor", "(", "seconds", "/", "3600", ")", ";", "var", "m", "=", "Math", ".", "floor", "(", "(", "seconds", "/", "60", ")", "%", "60", ")", ";", "var", "s", "=", "seconds", "%", "60", ";", "var", "pad", "=", "function", "(", "n", ")", "{", "n", "=", "String", "(", "n", ")", ";", "return", "n", ".", "length", ">=", "2", "?", "n", ":", "\"0\"", "+", "n", ";", "}", ";", "if", "(", "h", ">", "0", ")", "{", "return", "pad", "(", "h", ")", "+", "':'", "+", "pad", "(", "m", ")", "+", "':'", "+", "pad", "(", "s", ")", ";", "}", "else", "{", "return", "pad", "(", "m", ")", "+", "':'", "+", "pad", "(", "s", ")", ";", "}", "}" ]
Converts seconds to hms format
[ "Converts", "seconds", "to", "hms", "format" ]
74d69adfc32be83378adcf02b603095a380c92e2
https://github.com/fonini/ckeditor-youtube-plugin/blob/74d69adfc32be83378adcf02b603095a380c92e2/youtube/plugin.js#L395-L411
20,795
fonini/ckeditor-youtube-plugin
youtube/plugin.js
timeParamToSeconds
function timeParamToSeconds(param) { var componentValue = function (si) { var regex = new RegExp('(\\d+)' + si); return param.match(regex) ? parseInt(RegExp.$1, 10) : 0; }; return componentValue('h') * 3600 + componentValue('m') * 60 + componentValue('s'); }
javascript
function timeParamToSeconds(param) { var componentValue = function (si) { var regex = new RegExp('(\\d+)' + si); return param.match(regex) ? parseInt(RegExp.$1, 10) : 0; }; return componentValue('h') * 3600 + componentValue('m') * 60 + componentValue('s'); }
[ "function", "timeParamToSeconds", "(", "param", ")", "{", "var", "componentValue", "=", "function", "(", "si", ")", "{", "var", "regex", "=", "new", "RegExp", "(", "'(\\\\d+)'", "+", "si", ")", ";", "return", "param", ".", "match", "(", "regex", ")", "?", "parseInt", "(", "RegExp", ".", "$1", ",", "10", ")", ":", "0", ";", "}", ";", "return", "componentValue", "(", "'h'", ")", "*", "3600", "+", "componentValue", "(", "'m'", ")", "*", "60", "+", "componentValue", "(", "'s'", ")", ";", "}" ]
Converts time in youtube t-param format to seconds
[ "Converts", "time", "in", "youtube", "t", "-", "param", "format", "to", "seconds" ]
74d69adfc32be83378adcf02b603095a380c92e2
https://github.com/fonini/ckeditor-youtube-plugin/blob/74d69adfc32be83378adcf02b603095a380c92e2/youtube/plugin.js#L416-L425
20,796
brantwills/Angular-Paging
dist/paging.js
internalAction
function internalAction(scope, page) { // Block clicks we try to load the active page if (scope.page == page) { return; } // Block if we are forcing disabled if(scope.isDisabled) { return; } // Update the page in scope scope.page = page; // Pass our parameters to the paging action scope.pagingAction({ page: scope.page, pageSize: scope.pageSize, total: scope.total }); // If allowed scroll up to the top of the page if (scope.scrollTop) { scrollTo(0, 0); } }
javascript
function internalAction(scope, page) { // Block clicks we try to load the active page if (scope.page == page) { return; } // Block if we are forcing disabled if(scope.isDisabled) { return; } // Update the page in scope scope.page = page; // Pass our parameters to the paging action scope.pagingAction({ page: scope.page, pageSize: scope.pageSize, total: scope.total }); // If allowed scroll up to the top of the page if (scope.scrollTop) { scrollTo(0, 0); } }
[ "function", "internalAction", "(", "scope", ",", "page", ")", "{", "// Block clicks we try to load the active page", "if", "(", "scope", ".", "page", "==", "page", ")", "{", "return", ";", "}", "// Block if we are forcing disabled ", "if", "(", "scope", ".", "isDisabled", ")", "{", "return", ";", "}", "// Update the page in scope", "scope", ".", "page", "=", "page", ";", "// Pass our parameters to the paging action", "scope", ".", "pagingAction", "(", "{", "page", ":", "scope", ".", "page", ",", "pageSize", ":", "scope", ".", "pageSize", ",", "total", ":", "scope", ".", "total", "}", ")", ";", "// If allowed scroll up to the top of the page", "if", "(", "scope", ".", "scrollTop", ")", "{", "scrollTo", "(", "0", ",", "0", ")", ";", "}", "}" ]
Assign the method action to take when a page is clicked @param {Object} scope - The local directive scope object @param {int} page - The current page of interest
[ "Assign", "the", "method", "action", "to", "take", "when", "a", "page", "is", "clicked" ]
0c1bf95cdbe9ba66a6e767092ffb73136f9f789f
https://github.com/brantwills/Angular-Paging/blob/0c1bf95cdbe9ba66a6e767092ffb73136f9f789f/dist/paging.js#L208-L235
20,797
brantwills/Angular-Paging
dist/paging.js
addRange
function addRange(start, finish, scope) { // Add our items where i is the page number var i = 0; for (i = start; i <= finish; i++) { var pgHref = scope.pgHref.replace(regex, i); var liClass = scope.page == i ? scope.activeClass : ''; // Handle items that are affected by disabled if(scope.isDisabled){ pgHref = ''; liClass = scope.disabledClass; } scope.List.push({ value: i, title: scope.textTitlePage.replace(regex, i), liClass: liClass, pgHref: pgHref, action: function () { internalAction(scope, this.value); } }); } }
javascript
function addRange(start, finish, scope) { // Add our items where i is the page number var i = 0; for (i = start; i <= finish; i++) { var pgHref = scope.pgHref.replace(regex, i); var liClass = scope.page == i ? scope.activeClass : ''; // Handle items that are affected by disabled if(scope.isDisabled){ pgHref = ''; liClass = scope.disabledClass; } scope.List.push({ value: i, title: scope.textTitlePage.replace(regex, i), liClass: liClass, pgHref: pgHref, action: function () { internalAction(scope, this.value); } }); } }
[ "function", "addRange", "(", "start", ",", "finish", ",", "scope", ")", "{", "// Add our items where i is the page number", "var", "i", "=", "0", ";", "for", "(", "i", "=", "start", ";", "i", "<=", "finish", ";", "i", "++", ")", "{", "var", "pgHref", "=", "scope", ".", "pgHref", ".", "replace", "(", "regex", ",", "i", ")", ";", "var", "liClass", "=", "scope", ".", "page", "==", "i", "?", "scope", ".", "activeClass", ":", "''", ";", "// Handle items that are affected by disabled", "if", "(", "scope", ".", "isDisabled", ")", "{", "pgHref", "=", "''", ";", "liClass", "=", "scope", ".", "disabledClass", ";", "}", "scope", ".", "List", ".", "push", "(", "{", "value", ":", "i", ",", "title", ":", "scope", ".", "textTitlePage", ".", "replace", "(", "regex", ",", "i", ")", ",", "liClass", ":", "liClass", ",", "pgHref", ":", "pgHref", ",", "action", ":", "function", "(", ")", "{", "internalAction", "(", "scope", ",", "this", ".", "value", ")", ";", "}", "}", ")", ";", "}", "}" ]
Adds a range of numbers to our list The range is dependent on the start and finish parameters @param {int} start - The start of the range to add to the paging list @param {int} finish - The end of the range to add to the paging list @param {Object} scope - The local directive scope object
[ "Adds", "a", "range", "of", "numbers", "to", "our", "list", "The", "range", "is", "dependent", "on", "the", "start", "and", "finish", "parameters" ]
0c1bf95cdbe9ba66a6e767092ffb73136f9f789f
https://github.com/brantwills/Angular-Paging/blob/0c1bf95cdbe9ba66a6e767092ffb73136f9f789f/dist/paging.js#L352-L378
20,798
haydenbbickerton/vue-charts
dist/vue-charts.common.js
buildDataTable
function buildDataTable() { var self = this; var dataTable = new google.visualization.DataTable(); _.each(self.columns, function (value) { dataTable.addColumn(value); }); if (!_.isEmpty(self.rows)) { dataTable.addRows(self.rows); } return dataTable; }
javascript
function buildDataTable() { var self = this; var dataTable = new google.visualization.DataTable(); _.each(self.columns, function (value) { dataTable.addColumn(value); }); if (!_.isEmpty(self.rows)) { dataTable.addRows(self.rows); } return dataTable; }
[ "function", "buildDataTable", "(", ")", "{", "var", "self", "=", "this", ";", "var", "dataTable", "=", "new", "google", ".", "visualization", ".", "DataTable", "(", ")", ";", "_", ".", "each", "(", "self", ".", "columns", ",", "function", "(", "value", ")", "{", "dataTable", ".", "addColumn", "(", "value", ")", ";", "}", ")", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "self", ".", "rows", ")", ")", "{", "dataTable", ".", "addRows", "(", "self", ".", "rows", ")", ";", "}", "return", "dataTable", ";", "}" ]
Initialize the datatable and add the initial data. @link https://developers.google.com/chart/interactive/docs/reference#DataTable @return object
[ "Initialize", "the", "datatable", "and", "add", "the", "initial", "data", "." ]
f8bb783dd2476d854389678d0abe45b35ad8014b
https://github.com/haydenbbickerton/vue-charts/blob/f8bb783dd2476d854389678d0abe45b35ad8014b/dist/vue-charts.common.js#L243-L257
20,799
haydenbbickerton/vue-charts
dist/vue-charts.common.js
updateDataTable
function updateDataTable() { var self = this; // Remove all data from the datatable. self.dataTable.removeRows(0, self.dataTable.getNumberOfRows()); self.dataTable.removeColumns(0, self.dataTable.getNumberOfColumns()); // Add _.each(self.columns, function (value) { self.dataTable.addColumn(value); }); if (!_.isEmpty(self.rows)) { self.dataTable.addRows(self.rows); } }
javascript
function updateDataTable() { var self = this; // Remove all data from the datatable. self.dataTable.removeRows(0, self.dataTable.getNumberOfRows()); self.dataTable.removeColumns(0, self.dataTable.getNumberOfColumns()); // Add _.each(self.columns, function (value) { self.dataTable.addColumn(value); }); if (!_.isEmpty(self.rows)) { self.dataTable.addRows(self.rows); } }
[ "function", "updateDataTable", "(", ")", "{", "var", "self", "=", "this", ";", "// Remove all data from the datatable.", "self", ".", "dataTable", ".", "removeRows", "(", "0", ",", "self", ".", "dataTable", ".", "getNumberOfRows", "(", ")", ")", ";", "self", ".", "dataTable", ".", "removeColumns", "(", "0", ",", "self", ".", "dataTable", ".", "getNumberOfColumns", "(", ")", ")", ";", "// Add", "_", ".", "each", "(", "self", ".", "columns", ",", "function", "(", "value", ")", "{", "self", ".", "dataTable", ".", "addColumn", "(", "value", ")", ";", "}", ")", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "self", ".", "rows", ")", ")", "{", "self", ".", "dataTable", ".", "addRows", "(", "self", ".", "rows", ")", ";", "}", "}" ]
Update the datatable. @return void
[ "Update", "the", "datatable", "." ]
f8bb783dd2476d854389678d0abe45b35ad8014b
https://github.com/haydenbbickerton/vue-charts/blob/f8bb783dd2476d854389678d0abe45b35ad8014b/dist/vue-charts.common.js#L265-L280