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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
cloudkick/whiskey
lib/common.js
function(callback) { var errName; try { if (self._covered) { // If coverage is request, we want the testModule to reference the // code instrumented by istanbul in lib-cov/ instead of any local code in lib/. // This passage looks for variables assigned to by require('lib/*') // and sets a value for the variable which is the equivalent module in lib-cov. var fullModuleName = path.resolve(testModule); if (!fullModuleName.match(/\.js$/)) { fullModuleName = fullModuleName + '.js'; } var requirements = requiredAs(fullModuleName); // for every requirement in lib/, rewrite to lib-cov/ var newRequirements = underscore.map(requirements, function(req) { if (req.source.match(/node_modules/) || !req.source.match(/lib\//)) { return undefined; } req.source = path.resolve(path.dirname(fullModuleName), req.source); req.source = req.source.replace(/lib\//, 'lib-cov/'); return req; }); exportedFunctions = rewire(fullModuleName); underscore.each(newRequirements.filter(function(i) { return i; }), function(nr) { exportedFunctions.__set__(nr.name, require(nr.source)); }); } else { exportedFunctions = require(testModule); } } catch (err) { if (err.message.indexOf(testModule) !== -1 && err.message.match(/cannot find module/i)) { errName = 'file_does_not_exist'; } else { errName = 'uncaught_exception'; } test = new Test(errName, null); test._markAsFailed(err); self._reportTestResult(test.getResultObject()); callback(err); return; } exportedFunctionsNames = Object.keys(exportedFunctions); exportedFunctionsNames = exportedFunctionsNames.filter(isValidTestFunctionName); testsLen = exportedFunctionsNames.length; initializeFunc = exportedFunctions[constants.TEST_FILE_INITIALIZE_FUNCTION_NAME]; finalizeFunc = exportedFunctions[constants.TEST_FILE_FINALIZE_FUNCTION_NAME]; setUpFunc = exportedFunctions[constants.SETUP_FUNCTION_NAME]; tearDownFunc = exportedFunctions[constants.TEARDOWN_FUNCTION_NAME]; callback(); }
javascript
function(callback) { var errName; try { if (self._covered) { // If coverage is request, we want the testModule to reference the // code instrumented by istanbul in lib-cov/ instead of any local code in lib/. // This passage looks for variables assigned to by require('lib/*') // and sets a value for the variable which is the equivalent module in lib-cov. var fullModuleName = path.resolve(testModule); if (!fullModuleName.match(/\.js$/)) { fullModuleName = fullModuleName + '.js'; } var requirements = requiredAs(fullModuleName); // for every requirement in lib/, rewrite to lib-cov/ var newRequirements = underscore.map(requirements, function(req) { if (req.source.match(/node_modules/) || !req.source.match(/lib\//)) { return undefined; } req.source = path.resolve(path.dirname(fullModuleName), req.source); req.source = req.source.replace(/lib\//, 'lib-cov/'); return req; }); exportedFunctions = rewire(fullModuleName); underscore.each(newRequirements.filter(function(i) { return i; }), function(nr) { exportedFunctions.__set__(nr.name, require(nr.source)); }); } else { exportedFunctions = require(testModule); } } catch (err) { if (err.message.indexOf(testModule) !== -1 && err.message.match(/cannot find module/i)) { errName = 'file_does_not_exist'; } else { errName = 'uncaught_exception'; } test = new Test(errName, null); test._markAsFailed(err); self._reportTestResult(test.getResultObject()); callback(err); return; } exportedFunctionsNames = Object.keys(exportedFunctions); exportedFunctionsNames = exportedFunctionsNames.filter(isValidTestFunctionName); testsLen = exportedFunctionsNames.length; initializeFunc = exportedFunctions[constants.TEST_FILE_INITIALIZE_FUNCTION_NAME]; finalizeFunc = exportedFunctions[constants.TEST_FILE_FINALIZE_FUNCTION_NAME]; setUpFunc = exportedFunctions[constants.SETUP_FUNCTION_NAME]; tearDownFunc = exportedFunctions[constants.TEARDOWN_FUNCTION_NAME]; callback(); }
[ "function", "(", "callback", ")", "{", "var", "errName", ";", "try", "{", "if", "(", "self", ".", "_covered", ")", "{", "var", "fullModuleName", "=", "path", ".", "resolve", "(", "testModule", ")", ";", "if", "(", "!", "fullModuleName", ".", "match", "(", "/", "\\.js$", "/", ")", ")", "{", "fullModuleName", "=", "fullModuleName", "+", "'.js'", ";", "}", "var", "requirements", "=", "requiredAs", "(", "fullModuleName", ")", ";", "var", "newRequirements", "=", "underscore", ".", "map", "(", "requirements", ",", "function", "(", "req", ")", "{", "if", "(", "req", ".", "source", ".", "match", "(", "/", "node_modules", "/", ")", "||", "!", "req", ".", "source", ".", "match", "(", "/", "lib\\/", "/", ")", ")", "{", "return", "undefined", ";", "}", "req", ".", "source", "=", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "fullModuleName", ")", ",", "req", ".", "source", ")", ";", "req", ".", "source", "=", "req", ".", "source", ".", "replace", "(", "/", "lib\\/", "/", ",", "'lib-cov/'", ")", ";", "return", "req", ";", "}", ")", ";", "exportedFunctions", "=", "rewire", "(", "fullModuleName", ")", ";", "underscore", ".", "each", "(", "newRequirements", ".", "filter", "(", "function", "(", "i", ")", "{", "return", "i", ";", "}", ")", ",", "function", "(", "nr", ")", "{", "exportedFunctions", ".", "__set__", "(", "nr", ".", "name", ",", "require", "(", "nr", ".", "source", ")", ")", ";", "}", ")", ";", "}", "else", "{", "exportedFunctions", "=", "require", "(", "testModule", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "if", "(", "err", ".", "message", ".", "indexOf", "(", "testModule", ")", "!==", "-", "1", "&&", "err", ".", "message", ".", "match", "(", "/", "cannot find module", "/", "i", ")", ")", "{", "errName", "=", "'file_does_not_exist'", ";", "}", "else", "{", "errName", "=", "'uncaught_exception'", ";", "}", "test", "=", "new", "Test", "(", "errName", ",", "null", ")", ";", "test", ".", "_markAsFailed", "(", "err", ")", ";", "self", ".", "_reportTestResult", "(", "test", ".", "getResultObject", "(", ")", ")", ";", "callback", "(", "err", ")", ";", "return", ";", "}", "exportedFunctionsNames", "=", "Object", ".", "keys", "(", "exportedFunctions", ")", ";", "exportedFunctionsNames", "=", "exportedFunctionsNames", ".", "filter", "(", "isValidTestFunctionName", ")", ";", "testsLen", "=", "exportedFunctionsNames", ".", "length", ";", "initializeFunc", "=", "exportedFunctions", "[", "constants", ".", "TEST_FILE_INITIALIZE_FUNCTION_NAME", "]", ";", "finalizeFunc", "=", "exportedFunctions", "[", "constants", ".", "TEST_FILE_FINALIZE_FUNCTION_NAME", "]", ";", "setUpFunc", "=", "exportedFunctions", "[", "constants", ".", "SETUP_FUNCTION_NAME", "]", ";", "tearDownFunc", "=", "exportedFunctions", "[", "constants", ".", "TEARDOWN_FUNCTION_NAME", "]", ";", "callback", "(", ")", ";", "}" ]
Require the test file
[ "Require", "the", "test", "file" ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/common.js#L357-L417
train
cloudkick/whiskey
lib/common.js
function(callback) { var queue; if (exportedFunctionsNames.length === 0) { callback(); return; } function taskFunc(task, callback) { var setUpFunc = task.setUpFunc, tearDownFunc = task.tearDownFunc; async.waterfall([ function runSetUp(callback) { if (!setUpFunc) { callback(); return; } var test = new Test(constants.SETUP_FUNCTION_NAME, setUpFunc, self._scopeLeaks); test.run(onTestDone.bind(null, test, callback)); }, function runTest(callback) { var test = task.test; self._runningTest = test; test.run(onTestDone.bind(null, test, callback)); }, function runTearDown(callback) { if (!tearDownFunc) { callback(); return; } var test = new Test(constants.TEARDOWN_FUNCTION_NAME, tearDownFunc, self._scopeLeaks); test.run(onTestDone.bind(null, test, callback)); } ], callback); } function onDrain() { callback(); } queue = async.queue(taskFunc, self._concurrency); queue.drain = onDrain; for (i = 0; i < testsLen; i++) { testName = exportedFunctionsNames[i]; testFunc = exportedFunctions[testName]; if (!gex(self._pattern).on(testName)) { continue; } test = new Test(testName, testFunc, self._scopeLeaks); queue.push({'test': test, 'setUpFunc': setUpFunc, 'tearDownFunc': tearDownFunc}); } if (queue.length() === 0) { // No test matched the provided pattern callback(); } }
javascript
function(callback) { var queue; if (exportedFunctionsNames.length === 0) { callback(); return; } function taskFunc(task, callback) { var setUpFunc = task.setUpFunc, tearDownFunc = task.tearDownFunc; async.waterfall([ function runSetUp(callback) { if (!setUpFunc) { callback(); return; } var test = new Test(constants.SETUP_FUNCTION_NAME, setUpFunc, self._scopeLeaks); test.run(onTestDone.bind(null, test, callback)); }, function runTest(callback) { var test = task.test; self._runningTest = test; test.run(onTestDone.bind(null, test, callback)); }, function runTearDown(callback) { if (!tearDownFunc) { callback(); return; } var test = new Test(constants.TEARDOWN_FUNCTION_NAME, tearDownFunc, self._scopeLeaks); test.run(onTestDone.bind(null, test, callback)); } ], callback); } function onDrain() { callback(); } queue = async.queue(taskFunc, self._concurrency); queue.drain = onDrain; for (i = 0; i < testsLen; i++) { testName = exportedFunctionsNames[i]; testFunc = exportedFunctions[testName]; if (!gex(self._pattern).on(testName)) { continue; } test = new Test(testName, testFunc, self._scopeLeaks); queue.push({'test': test, 'setUpFunc': setUpFunc, 'tearDownFunc': tearDownFunc}); } if (queue.length() === 0) { // No test matched the provided pattern callback(); } }
[ "function", "(", "callback", ")", "{", "var", "queue", ";", "if", "(", "exportedFunctionsNames", ".", "length", "===", "0", ")", "{", "callback", "(", ")", ";", "return", ";", "}", "function", "taskFunc", "(", "task", ",", "callback", ")", "{", "var", "setUpFunc", "=", "task", ".", "setUpFunc", ",", "tearDownFunc", "=", "task", ".", "tearDownFunc", ";", "async", ".", "waterfall", "(", "[", "function", "runSetUp", "(", "callback", ")", "{", "if", "(", "!", "setUpFunc", ")", "{", "callback", "(", ")", ";", "return", ";", "}", "var", "test", "=", "new", "Test", "(", "constants", ".", "SETUP_FUNCTION_NAME", ",", "setUpFunc", ",", "self", ".", "_scopeLeaks", ")", ";", "test", ".", "run", "(", "onTestDone", ".", "bind", "(", "null", ",", "test", ",", "callback", ")", ")", ";", "}", ",", "function", "runTest", "(", "callback", ")", "{", "var", "test", "=", "task", ".", "test", ";", "self", ".", "_runningTest", "=", "test", ";", "test", ".", "run", "(", "onTestDone", ".", "bind", "(", "null", ",", "test", ",", "callback", ")", ")", ";", "}", ",", "function", "runTearDown", "(", "callback", ")", "{", "if", "(", "!", "tearDownFunc", ")", "{", "callback", "(", ")", ";", "return", ";", "}", "var", "test", "=", "new", "Test", "(", "constants", ".", "TEARDOWN_FUNCTION_NAME", ",", "tearDownFunc", ",", "self", ".", "_scopeLeaks", ")", ";", "test", ".", "run", "(", "onTestDone", ".", "bind", "(", "null", ",", "test", ",", "callback", ")", ")", ";", "}", "]", ",", "callback", ")", ";", "}", "function", "onDrain", "(", ")", "{", "callback", "(", ")", ";", "}", "queue", "=", "async", ".", "queue", "(", "taskFunc", ",", "self", ".", "_concurrency", ")", ";", "queue", ".", "drain", "=", "onDrain", ";", "for", "(", "i", "=", "0", ";", "i", "<", "testsLen", ";", "i", "++", ")", "{", "testName", "=", "exportedFunctionsNames", "[", "i", "]", ";", "testFunc", "=", "exportedFunctions", "[", "testName", "]", ";", "if", "(", "!", "gex", "(", "self", ".", "_pattern", ")", ".", "on", "(", "testName", ")", ")", "{", "continue", ";", "}", "test", "=", "new", "Test", "(", "testName", ",", "testFunc", ",", "self", ".", "_scopeLeaks", ")", ";", "queue", ".", "push", "(", "{", "'test'", ":", "test", ",", "'setUpFunc'", ":", "setUpFunc", ",", "'tearDownFunc'", ":", "tearDownFunc", "}", ")", ";", "}", "if", "(", "queue", ".", "length", "(", ")", "===", "0", ")", "{", "callback", "(", ")", ";", "}", "}" ]
Run the tests
[ "Run", "the", "tests" ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/common.js#L432-L497
train
cloudkick/whiskey
lib/common.js
function (actualArgs, expectedArgs) { var i; if (actualArgs.length !== expectedArgs.length) { return false; } for (i = 0; i < expectedArgs.length; i++) { if (actualArgs[i] !== expectedArgs[i]) { return false; } } return true; }
javascript
function (actualArgs, expectedArgs) { var i; if (actualArgs.length !== expectedArgs.length) { return false; } for (i = 0; i < expectedArgs.length; i++) { if (actualArgs[i] !== expectedArgs[i]) { return false; } } return true; }
[ "function", "(", "actualArgs", ",", "expectedArgs", ")", "{", "var", "i", ";", "if", "(", "actualArgs", ".", "length", "!==", "expectedArgs", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "expectedArgs", ".", "length", ";", "i", "++", ")", "{", "if", "(", "actualArgs", "[", "i", "]", "!==", "expectedArgs", "[", "i", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
checks the actual args match the expected args
[ "checks", "the", "actual", "args", "match", "the", "expected", "args" ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/common.js#L714-L725
train
basisjs/basisjs-tools-build
lib/build/js/makePackages.js
buildDep
function buildDep(file, pkg){ var files = []; if (file.processed || file.package != pkg) return files; file.processed = true; for (var i = 0, depFile; depFile = file.deps[i++];) files.push.apply(files, buildDep(depFile, file.package)); files.push(file); return files; }
javascript
function buildDep(file, pkg){ var files = []; if (file.processed || file.package != pkg) return files; file.processed = true; for (var i = 0, depFile; depFile = file.deps[i++];) files.push.apply(files, buildDep(depFile, file.package)); files.push(file); return files; }
[ "function", "buildDep", "(", "file", ",", "pkg", ")", "{", "var", "files", "=", "[", "]", ";", "if", "(", "file", ".", "processed", "||", "file", ".", "package", "!=", "pkg", ")", "return", "files", ";", "file", ".", "processed", "=", "true", ";", "for", "(", "var", "i", "=", "0", ",", "depFile", ";", "depFile", "=", "file", ".", "deps", "[", "i", "++", "]", ";", ")", "files", ".", "push", ".", "apply", "(", "files", ",", "buildDep", "(", "depFile", ",", "file", ".", "package", ")", ")", ";", "files", ".", "push", "(", "file", ")", ";", "return", "files", ";", "}" ]
make require file list
[ "make", "require", "file", "list" ]
177018ab31b225cddb6a184693fe4746512e7af1
https://github.com/basisjs/basisjs-tools-build/blob/177018ab31b225cddb6a184693fe4746512e7af1/lib/build/js/makePackages.js#L41-L55
train
somesocks/vet
dist/utils/assert.js
assert
function assert (validator, message) { message = messageBuilder(message || 'vet/utils/assert error!'); if (isFunction(validator)) { return function() { var args = arguments; if (validator.apply(this, args)) { return true; } else { throw new Error(message.apply(this, args)); } }; } else if (!validator) { throw new Error(message.apply(this)); } else { return true; } }
javascript
function assert (validator, message) { message = messageBuilder(message || 'vet/utils/assert error!'); if (isFunction(validator)) { return function() { var args = arguments; if (validator.apply(this, args)) { return true; } else { throw new Error(message.apply(this, args)); } }; } else if (!validator) { throw new Error(message.apply(this)); } else { return true; } }
[ "function", "assert", "(", "validator", ",", "message", ")", "{", "message", "=", "messageBuilder", "(", "message", "||", "'vet/utils/assert error!'", ")", ";", "if", "(", "isFunction", "(", "validator", ")", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "if", "(", "validator", ".", "apply", "(", "this", ",", "args", ")", ")", "{", "return", "true", ";", "}", "else", "{", "throw", "new", "Error", "(", "message", ".", "apply", "(", "this", ",", "args", ")", ")", ";", "}", "}", ";", "}", "else", "if", "(", "!", "validator", ")", "{", "throw", "new", "Error", "(", "message", ".", "apply", "(", "this", ")", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Wraps a validator, and throws an error if it returns false. This is useful for some code that expects assertion-style validation. @param validator - the validator to wrap @param message - an optional message string to pass into the error @returns a function that returns null if the arguments pass validation, or throws an error if they do not @memberof vet.utils
[ "Wraps", "a", "validator", "and", "throws", "an", "error", "if", "it", "returns", "false", "." ]
4557abeb6a8b470cb4a5823a2cc802c825ef29ef
https://github.com/somesocks/vet/blob/4557abeb6a8b470cb4a5823a2cc802c825ef29ef/dist/utils/assert.js#L20-L38
train
cloudkick/whiskey
lib/coverage.js
coverage
function coverage(data, type) { var comparisionFunc; var n = 0; function isCovered(val) { return (val > 0); } function isMissed(val) { return !isCovered(val); } if (type === 'covered') { comparisionFunc = isCovered; } else if (type === 'missed') { comparisionFunc = isMissed; } else { throw new Error('Invalid type: ' + type); } var len = Object.keys(data.lines).length; for (var i = 0; i < len; ++i) { if (data.lines[i] !== null && comparisionFunc(data.lines[i])) { ++n; } } return n; }
javascript
function coverage(data, type) { var comparisionFunc; var n = 0; function isCovered(val) { return (val > 0); } function isMissed(val) { return !isCovered(val); } if (type === 'covered') { comparisionFunc = isCovered; } else if (type === 'missed') { comparisionFunc = isMissed; } else { throw new Error('Invalid type: ' + type); } var len = Object.keys(data.lines).length; for (var i = 0; i < len; ++i) { if (data.lines[i] !== null && comparisionFunc(data.lines[i])) { ++n; } } return n; }
[ "function", "coverage", "(", "data", ",", "type", ")", "{", "var", "comparisionFunc", ";", "var", "n", "=", "0", ";", "function", "isCovered", "(", "val", ")", "{", "return", "(", "val", ">", "0", ")", ";", "}", "function", "isMissed", "(", "val", ")", "{", "return", "!", "isCovered", "(", "val", ")", ";", "}", "if", "(", "type", "===", "'covered'", ")", "{", "comparisionFunc", "=", "isCovered", ";", "}", "else", "if", "(", "type", "===", "'missed'", ")", "{", "comparisionFunc", "=", "isMissed", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid type: '", "+", "type", ")", ";", "}", "var", "len", "=", "Object", ".", "keys", "(", "data", ".", "lines", ")", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "++", "i", ")", "{", "if", "(", "data", ".", "lines", "[", "i", "]", "!==", "null", "&&", "comparisionFunc", "(", "data", ".", "lines", "[", "i", "]", ")", ")", "{", "++", "n", ";", "}", "}", "return", "n", ";", "}" ]
Total coverage for the given file data. @param {Array} data @return {Type}
[ "Total", "coverage", "for", "the", "given", "file", "data", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/coverage.js#L90-L121
train
cloudkick/whiskey
lib/coverage.js
aggregateCoverage
function aggregateCoverage(files) { var i, len, file, content, results; var resultsObj = getEmptyResultObject(); for (i = 0, len = files.length; i < len; i++) { file = files[i]; content = JSON.parse(fs.readFileSync(file).toString()); resultsObj = populateCoverage(resultsObj, content); } return resultsObj; }
javascript
function aggregateCoverage(files) { var i, len, file, content, results; var resultsObj = getEmptyResultObject(); for (i = 0, len = files.length; i < len; i++) { file = files[i]; content = JSON.parse(fs.readFileSync(file).toString()); resultsObj = populateCoverage(resultsObj, content); } return resultsObj; }
[ "function", "aggregateCoverage", "(", "files", ")", "{", "var", "i", ",", "len", ",", "file", ",", "content", ",", "results", ";", "var", "resultsObj", "=", "getEmptyResultObject", "(", ")", ";", "for", "(", "i", "=", "0", ",", "len", "=", "files", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "file", "=", "files", "[", "i", "]", ";", "content", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "file", ")", ".", "toString", "(", ")", ")", ";", "resultsObj", "=", "populateCoverage", "(", "resultsObj", ",", "content", ")", ";", "}", "return", "resultsObj", ";", "}" ]
Read multiple coverage files and return aggregated coverage.
[ "Read", "multiple", "coverage", "files", "and", "return", "aggregated", "coverage", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/coverage.js#L218-L229
train
GMOD/bgzf-filehandle
src/unzip.js
pakoUnzip
async function pakoUnzip(inputData) { let strm let pos = 0 let i = 0 const chunks = [] let inflator do { const remainingInput = inputData.slice(pos) inflator = new Inflate() strm = inflator.strm inflator.push(remainingInput, Z_SYNC_FLUSH) if (inflator.err) throw new Error(inflator.msg) pos += strm.next_in chunks[i] = Buffer.from(inflator.result) i += 1 } while (strm.avail_in) const result = Buffer.concat(chunks) return result }
javascript
async function pakoUnzip(inputData) { let strm let pos = 0 let i = 0 const chunks = [] let inflator do { const remainingInput = inputData.slice(pos) inflator = new Inflate() strm = inflator.strm inflator.push(remainingInput, Z_SYNC_FLUSH) if (inflator.err) throw new Error(inflator.msg) pos += strm.next_in chunks[i] = Buffer.from(inflator.result) i += 1 } while (strm.avail_in) const result = Buffer.concat(chunks) return result }
[ "async", "function", "pakoUnzip", "(", "inputData", ")", "{", "let", "strm", "let", "pos", "=", "0", "let", "i", "=", "0", "const", "chunks", "=", "[", "]", "let", "inflator", "do", "{", "const", "remainingInput", "=", "inputData", ".", "slice", "(", "pos", ")", "inflator", "=", "new", "Inflate", "(", ")", "strm", "=", "inflator", ".", "strm", "inflator", ".", "push", "(", "remainingInput", ",", "Z_SYNC_FLUSH", ")", "if", "(", "inflator", ".", "err", ")", "throw", "new", "Error", "(", "inflator", ".", "msg", ")", "pos", "+=", "strm", ".", "next_in", "chunks", "[", "i", "]", "=", "Buffer", ".", "from", "(", "inflator", ".", "result", ")", "i", "+=", "1", "}", "while", "(", "strm", ".", "avail_in", ")", "const", "result", "=", "Buffer", ".", "concat", "(", "chunks", ")", "return", "result", "}" ]
browserify-zlib, which is the zlib shim used by default in webpacked code, does not properly uncompress bgzf chunks that contain more than one bgzf block, so export an unzip function that uses pako directly if we are running in a browser.
[ "browserify", "-", "zlib", "which", "is", "the", "zlib", "shim", "used", "by", "default", "in", "webpacked", "code", "does", "not", "properly", "uncompress", "bgzf", "chunks", "that", "contain", "more", "than", "one", "bgzf", "block", "so", "export", "an", "unzip", "function", "that", "uses", "pako", "directly", "if", "we", "are", "running", "in", "a", "browser", "." ]
a43ddc0bc00b5610472de6ac5214ae50602be12e
https://github.com/GMOD/bgzf-filehandle/blob/a43ddc0bc00b5610472de6ac5214ae50602be12e/src/unzip.js#L12-L32
train
cloudkick/whiskey
lib/process_runner/runner.js
sink
function sink(modulename, level, message, obj) { term.puts(sprintf('[green]%s[/green]: %s', modulename, message)); }
javascript
function sink(modulename, level, message, obj) { term.puts(sprintf('[green]%s[/green]: %s', modulename, message)); }
[ "function", "sink", "(", "modulename", ",", "level", ",", "message", ",", "obj", ")", "{", "term", ".", "puts", "(", "sprintf", "(", "'[green]%s[/green]: %s'", ",", "modulename", ",", "message", ")", ")", ";", "}" ]
Set up logging
[ "Set", "up", "logging" ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/process_runner/runner.js#L34-L36
train
Ivshti/name-to-imdb
providers/cinemeta.js
indexEntry
function indexEntry(entry) { if (entry.year) entry.year = parseInt(entry.year.toString().split("-")[0]); // first year for series var n = helpers.simplifyName(entry); if (!meta[n]) meta[n] = []; meta[n].push(entry); byImdb[entry.imdb_id] = entry; }
javascript
function indexEntry(entry) { if (entry.year) entry.year = parseInt(entry.year.toString().split("-")[0]); // first year for series var n = helpers.simplifyName(entry); if (!meta[n]) meta[n] = []; meta[n].push(entry); byImdb[entry.imdb_id] = entry; }
[ "function", "indexEntry", "(", "entry", ")", "{", "if", "(", "entry", ".", "year", ")", "entry", ".", "year", "=", "parseInt", "(", "entry", ".", "year", ".", "toString", "(", ")", ".", "split", "(", "\"-\"", ")", "[", "0", "]", ")", ";", "var", "n", "=", "helpers", ".", "simplifyName", "(", "entry", ")", ";", "if", "(", "!", "meta", "[", "n", "]", ")", "meta", "[", "n", "]", "=", "[", "]", ";", "meta", "[", "n", "]", ".", "push", "(", "entry", ")", ";", "byImdb", "[", "entry", ".", "imdb_id", "]", "=", "entry", ";", "}" ]
Index entry in our in-mem index
[ "Index", "entry", "in", "our", "in", "-", "mem", "index" ]
529bcdf7ac034915991f4d2bac677f01f12cb647
https://github.com/Ivshti/name-to-imdb/blob/529bcdf7ac034915991f4d2bac677f01f12cb647/providers/cinemeta.js#L11-L17
train
warehouseai/cdnup
file.js
File
function File(retries, cdn, options) { options = options || {}; this.backoff = new Backoff({ min: 100, max: 20000 }); this.mime = options.mime || {}; this.retries = retries || 5; this.client = cdn.client; this.cdn = cdn; }
javascript
function File(retries, cdn, options) { options = options || {}; this.backoff = new Backoff({ min: 100, max: 20000 }); this.mime = options.mime || {}; this.retries = retries || 5; this.client = cdn.client; this.cdn = cdn; }
[ "function", "File", "(", "retries", ",", "cdn", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "backoff", "=", "new", "Backoff", "(", "{", "min", ":", "100", ",", "max", ":", "20000", "}", ")", ";", "this", ".", "mime", "=", "options", ".", "mime", "||", "{", "}", ";", "this", ".", "retries", "=", "retries", "||", "5", ";", "this", ".", "client", "=", "cdn", ".", "client", ";", "this", ".", "cdn", "=", "cdn", ";", "}" ]
Representation of a single file operation for the CDN. @constructor @param {Number} retries Amount of retries. @param {CDNUp} cdn CDN reference. @param {Object} options Additional configuration. @api private
[ "Representation", "of", "a", "single", "file", "operation", "for", "the", "CDN", "." ]
208e90b8236fdd52d8f90685522ef56047a30fc4
https://github.com/warehouseai/cdnup/blob/208e90b8236fdd52d8f90685522ef56047a30fc4/file.js#L21-L29
train
jonschlinkert/map-schema
lib/field.js
Field
function Field(type, config) { if (utils.typeOf(type) === 'object') { config = type; type = null; } if (!utils.isObject(config)) { throw new TypeError('expected config to be an object'); } this.types = type || config.type || config.types || []; this.types = typeof this.types === 'string' ? this.types.split(/\W/) : this.types; if (typeof this.types === 'undefined' || this.types.length === 0) { throw new TypeError('expected type to be a string or array of JavaScript native types'); } for (var key in config) { this[key] = config[key]; } if (!config.hasOwnProperty('required')) { this.required = false; } if (!config.hasOwnProperty('optional')) { this.optional = true; } if (this.required === true) { this.optional = false; } if (this.optional === false) { this.required = true; } }
javascript
function Field(type, config) { if (utils.typeOf(type) === 'object') { config = type; type = null; } if (!utils.isObject(config)) { throw new TypeError('expected config to be an object'); } this.types = type || config.type || config.types || []; this.types = typeof this.types === 'string' ? this.types.split(/\W/) : this.types; if (typeof this.types === 'undefined' || this.types.length === 0) { throw new TypeError('expected type to be a string or array of JavaScript native types'); } for (var key in config) { this[key] = config[key]; } if (!config.hasOwnProperty('required')) { this.required = false; } if (!config.hasOwnProperty('optional')) { this.optional = true; } if (this.required === true) { this.optional = false; } if (this.optional === false) { this.required = true; } }
[ "function", "Field", "(", "type", ",", "config", ")", "{", "if", "(", "utils", ".", "typeOf", "(", "type", ")", "===", "'object'", ")", "{", "config", "=", "type", ";", "type", "=", "null", ";", "}", "if", "(", "!", "utils", ".", "isObject", "(", "config", ")", ")", "{", "throw", "new", "TypeError", "(", "'expected config to be an object'", ")", ";", "}", "this", ".", "types", "=", "type", "||", "config", ".", "type", "||", "config", ".", "types", "||", "[", "]", ";", "this", ".", "types", "=", "typeof", "this", ".", "types", "===", "'string'", "?", "this", ".", "types", ".", "split", "(", "/", "\\W", "/", ")", ":", "this", ".", "types", ";", "if", "(", "typeof", "this", ".", "types", "===", "'undefined'", "||", "this", ".", "types", ".", "length", "===", "0", ")", "{", "throw", "new", "TypeError", "(", "'expected type to be a string or array of JavaScript native types'", ")", ";", "}", "for", "(", "var", "key", "in", "config", ")", "{", "this", "[", "key", "]", "=", "config", "[", "key", "]", ";", "}", "if", "(", "!", "config", ".", "hasOwnProperty", "(", "'required'", ")", ")", "{", "this", ".", "required", "=", "false", ";", "}", "if", "(", "!", "config", ".", "hasOwnProperty", "(", "'optional'", ")", ")", "{", "this", ".", "optional", "=", "true", ";", "}", "if", "(", "this", ".", "required", "===", "true", ")", "{", "this", ".", "optional", "=", "false", ";", "}", "if", "(", "this", ".", "optional", "===", "false", ")", "{", "this", ".", "required", "=", "true", ";", "}", "}" ]
Create a new `Field` of the given `type` to validate against, and optional `config` object. ```js var field = new Field('string', { normalize: function(val) { // do stuff to `val` return val; } }); ``` @param {String|Array} `type` One more JavaScript native types to use for validation. @param {Object} `config` @api public
[ "Create", "a", "new", "Field", "of", "the", "given", "type", "to", "validate", "against", "and", "optional", "config", "object", "." ]
08e11847e83ab91aa7460f6ee2249a64967a5d29
https://github.com/jonschlinkert/map-schema/blob/08e11847e83ab91aa7460f6ee2249a64967a5d29/lib/field.js#L28-L63
train
rrharvey/grunt-file-blocks
lib/block.js
function (obj, other) { var notIn = {}; for (var key in obj) { if (other[key] === undefined) { notIn[key] = true; } } return _.keys(notIn); }
javascript
function (obj, other) { var notIn = {}; for (var key in obj) { if (other[key] === undefined) { notIn[key] = true; } } return _.keys(notIn); }
[ "function", "(", "obj", ",", "other", ")", "{", "var", "notIn", "=", "{", "}", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "other", "[", "key", "]", "===", "undefined", ")", "{", "notIn", "[", "key", "]", "=", "true", ";", "}", "}", "return", "_", ".", "keys", "(", "notIn", ")", ";", "}" ]
Find keys that exist in the specified object that don't exist in the other object.
[ "Find", "keys", "that", "exist", "in", "the", "specified", "object", "that", "don", "t", "exist", "in", "the", "other", "object", "." ]
c1e3bfcb33df76ca820de580da3864085bfaed44
https://github.com/rrharvey/grunt-file-blocks/blob/c1e3bfcb33df76ca820de580da3864085bfaed44/lib/block.js#L8-L16
train
somesocks/vet
dist/numbers/isBetween.js
isBetween
function isBetween(lower, upper) { return function (val) { return isNumber(val) && val > lower && val < upper; } }
javascript
function isBetween(lower, upper) { return function (val) { return isNumber(val) && val > lower && val < upper; } }
[ "function", "isBetween", "(", "lower", ",", "upper", ")", "{", "return", "function", "(", "val", ")", "{", "return", "isNumber", "(", "val", ")", "&&", "val", ">", "lower", "&&", "val", "<", "upper", ";", "}", "}" ]
Checks to see if a value is a negative number @param {number} lower - the lower boundary value to check against @param {number} upper - the upper boundary value to check against @returns {function} - a validator function @memberof vet.numbers
[ "Checks", "to", "see", "if", "a", "value", "is", "a", "negative", "number" ]
4557abeb6a8b470cb4a5823a2cc802c825ef29ef
https://github.com/somesocks/vet/blob/4557abeb6a8b470cb4a5823a2cc802c825ef29ef/dist/numbers/isBetween.js#L11-L15
train
taskcluster/dockerode-process
docker_process.js
DockerProc
function DockerProc(docker, config) { EventEmitter.call(this); this.docker = docker; this._createConfig = config.create; this._startConfig = config.start; this.stdout = new streams.PassThrough(); this.stderr = new streams.PassThrough(); }
javascript
function DockerProc(docker, config) { EventEmitter.call(this); this.docker = docker; this._createConfig = config.create; this._startConfig = config.start; this.stdout = new streams.PassThrough(); this.stderr = new streams.PassThrough(); }
[ "function", "DockerProc", "(", "docker", ",", "config", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "docker", "=", "docker", ";", "this", ".", "_createConfig", "=", "config", ".", "create", ";", "this", ".", "_startConfig", "=", "config", ".", "start", ";", "this", ".", "stdout", "=", "new", "streams", ".", "PassThrough", "(", ")", ";", "this", ".", "stderr", "=", "new", "streams", ".", "PassThrough", "(", ")", ";", "}" ]
Loosely modeled on node's own child_process object thought the interface to get the child process is different.
[ "Loosely", "modeled", "on", "node", "s", "own", "child_process", "object", "thought", "the", "interface", "to", "get", "the", "child", "process", "is", "different", "." ]
f0ac2d8215f7c3ac513425a92a8f1d9edacc4f4e
https://github.com/taskcluster/dockerode-process/blob/f0ac2d8215f7c3ac513425a92a8f1d9edacc4f4e/docker_process.js#L27-L36
train
taskcluster/dockerode-process
docker_process.js
function(options) { options = options || {}; if (!('pull' in options)) options.pull = true; // no pull means no extra stream processing... if (!options.pull) return this._run(); return new Promise(function(accept, reject) { // pull the image (or use on in the cache and output status in stdout) var pullStream = utils.pullImageIfMissing(this.docker, this._createConfig.Image); // pipe the pull stream into stdout but don't end pullStream.pipe(this.stdout, { end: false }); pullStream.once('error', reject); pullStream.once('end', function() { pullStream.removeListener('error', reject); this._run().then(accept, reject); }.bind(this)); }.bind(this)); }
javascript
function(options) { options = options || {}; if (!('pull' in options)) options.pull = true; // no pull means no extra stream processing... if (!options.pull) return this._run(); return new Promise(function(accept, reject) { // pull the image (or use on in the cache and output status in stdout) var pullStream = utils.pullImageIfMissing(this.docker, this._createConfig.Image); // pipe the pull stream into stdout but don't end pullStream.pipe(this.stdout, { end: false }); pullStream.once('error', reject); pullStream.once('end', function() { pullStream.removeListener('error', reject); this._run().then(accept, reject); }.bind(this)); }.bind(this)); }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "(", "'pull'", "in", "options", ")", ")", "options", ".", "pull", "=", "true", ";", "if", "(", "!", "options", ".", "pull", ")", "return", "this", ".", "_run", "(", ")", ";", "return", "new", "Promise", "(", "function", "(", "accept", ",", "reject", ")", "{", "var", "pullStream", "=", "utils", ".", "pullImageIfMissing", "(", "this", ".", "docker", ",", "this", ".", "_createConfig", ".", "Image", ")", ";", "pullStream", ".", "pipe", "(", "this", ".", "stdout", ",", "{", "end", ":", "false", "}", ")", ";", "pullStream", ".", "once", "(", "'error'", ",", "reject", ")", ";", "pullStream", ".", "once", "(", "'end'", ",", "function", "(", ")", "{", "pullStream", ".", "removeListener", "(", "'error'", ",", "reject", ")", ";", "this", ".", "_run", "(", ")", ".", "then", "(", "accept", ",", "reject", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Run the docker process and resolve the promise on complete. @param {Object} options for running the container. @param {Boolean} [options.pull=true] when true pull the image and prepend the download details to stdout.
[ "Run", "the", "docker", "process", "and", "resolve", "the", "promise", "on", "complete", "." ]
f0ac2d8215f7c3ac513425a92a8f1d9edacc4f4e
https://github.com/taskcluster/dockerode-process/blob/f0ac2d8215f7c3ac513425a92a8f1d9edacc4f4e/docker_process.js#L130-L151
train
taskcluster/dockerode-process
docker_process.js
function() { var that = this; this.killed = true; if (this.started) { this.container.kill(); } else { this.once('container start', function() { that.container.kill(); }); } }
javascript
function() { var that = this; this.killed = true; if (this.started) { this.container.kill(); } else { this.once('container start', function() { that.container.kill(); }); } }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "this", ".", "killed", "=", "true", ";", "if", "(", "this", ".", "started", ")", "{", "this", ".", "container", ".", "kill", "(", ")", ";", "}", "else", "{", "this", ".", "once", "(", "'container start'", ",", "function", "(", ")", "{", "that", ".", "container", ".", "kill", "(", ")", ";", "}", ")", ";", "}", "}" ]
Kill docker container
[ "Kill", "docker", "container" ]
f0ac2d8215f7c3ac513425a92a8f1d9edacc4f4e
https://github.com/taskcluster/dockerode-process/blob/f0ac2d8215f7c3ac513425a92a8f1d9edacc4f4e/docker_process.js#L154-L164
train
somesocks/vet
dist/utils/returns.js
returns
function returns(func, validator, message) { message = messageBuilder(message || 'vet/utils/returns error!'); return function _returnsInstance() { var args = arguments; var result = func.apply(this, arguments); if (validator(result)) { return result; } else { throw new Error(message.call(this, result)); } }; }
javascript
function returns(func, validator, message) { message = messageBuilder(message || 'vet/utils/returns error!'); return function _returnsInstance() { var args = arguments; var result = func.apply(this, arguments); if (validator(result)) { return result; } else { throw new Error(message.call(this, result)); } }; }
[ "function", "returns", "(", "func", ",", "validator", ",", "message", ")", "{", "message", "=", "messageBuilder", "(", "message", "||", "'vet/utils/returns error!'", ")", ";", "return", "function", "_returnsInstance", "(", ")", "{", "var", "args", "=", "arguments", ";", "var", "result", "=", "func", ".", "apply", "(", "this", ",", "arguments", ")", ";", "if", "(", "validator", "(", "result", ")", ")", "{", "return", "result", ";", "}", "else", "{", "throw", "new", "Error", "(", "message", ".", "call", "(", "this", ",", "result", ")", ")", ";", "}", "}", ";", "}" ]
Wraps a function in a validator which checks its return value, and throws an error if the return value is bad. @param func - the function to wrap @param validator - the validator function. This gets passed the return value @param message - an optional message string to pass into the error thrown @returns a wrapped function that throws an error if the return value doed not pass validation @memberof vet.utils
[ "Wraps", "a", "function", "in", "a", "validator", "which", "checks", "its", "return", "value", "and", "throws", "an", "error", "if", "the", "return", "value", "is", "bad", "." ]
4557abeb6a8b470cb4a5823a2cc802c825ef29ef
https://github.com/somesocks/vet/blob/4557abeb6a8b470cb4a5823a2cc802c825ef29ef/dist/utils/returns.js#L18-L31
train
feedhenry/fh-amqp-js
lib/amqpjs.js
setupConn
function setupConn(connectCfg, options) { var conn = amqp.createConnection(connectCfg, options); conn.on('ready', function() { debug('received ready event from node-amqp'); var eventName = 'connection'; //Ready event will be emitted when re-connected. //To keep backward compatible, only emit 'connection' event for the first time if (_connection) { eventName = 'reconnect'; } _connection = conn; _connection._isClosed = false; self.emit('ready'); // wrapped in 'nextTick' for unit test friendliness process.nextTick(function() { debug('going to emit ' + eventName); self.emit(eventName); }); autoSubscribe(); publishCachedMessages(); _rpcReplyQ = null; _rpcReplyQName = null; _rpcSubscribed = false; if (_.size(_rpcCallbacks) > 0) { debug('found ' + _.size(_rpcCallbacks) + ' callbacks left after reconnect'); //still have callbacks that are waiting for response.However, since we have reconnected, they won't receive the messages _.each(_rpcCallbacks, function(cb) { return cb('connection_error'); }); } _rpcCallbacks = {}; }); conn.on('error', function(err) { self.emit('error', err); }); conn.on('close', function() { if (_connection) { _connection._isClosed = true; } }); }
javascript
function setupConn(connectCfg, options) { var conn = amqp.createConnection(connectCfg, options); conn.on('ready', function() { debug('received ready event from node-amqp'); var eventName = 'connection'; //Ready event will be emitted when re-connected. //To keep backward compatible, only emit 'connection' event for the first time if (_connection) { eventName = 'reconnect'; } _connection = conn; _connection._isClosed = false; self.emit('ready'); // wrapped in 'nextTick' for unit test friendliness process.nextTick(function() { debug('going to emit ' + eventName); self.emit(eventName); }); autoSubscribe(); publishCachedMessages(); _rpcReplyQ = null; _rpcReplyQName = null; _rpcSubscribed = false; if (_.size(_rpcCallbacks) > 0) { debug('found ' + _.size(_rpcCallbacks) + ' callbacks left after reconnect'); //still have callbacks that are waiting for response.However, since we have reconnected, they won't receive the messages _.each(_rpcCallbacks, function(cb) { return cb('connection_error'); }); } _rpcCallbacks = {}; }); conn.on('error', function(err) { self.emit('error', err); }); conn.on('close', function() { if (_connection) { _connection._isClosed = true; } }); }
[ "function", "setupConn", "(", "connectCfg", ",", "options", ")", "{", "var", "conn", "=", "amqp", ".", "createConnection", "(", "connectCfg", ",", "options", ")", ";", "conn", ".", "on", "(", "'ready'", ",", "function", "(", ")", "{", "debug", "(", "'received ready event from node-amqp'", ")", ";", "var", "eventName", "=", "'connection'", ";", "if", "(", "_connection", ")", "{", "eventName", "=", "'reconnect'", ";", "}", "_connection", "=", "conn", ";", "_connection", ".", "_isClosed", "=", "false", ";", "self", ".", "emit", "(", "'ready'", ")", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "debug", "(", "'going to emit '", "+", "eventName", ")", ";", "self", ".", "emit", "(", "eventName", ")", ";", "}", ")", ";", "autoSubscribe", "(", ")", ";", "publishCachedMessages", "(", ")", ";", "_rpcReplyQ", "=", "null", ";", "_rpcReplyQName", "=", "null", ";", "_rpcSubscribed", "=", "false", ";", "if", "(", "_", ".", "size", "(", "_rpcCallbacks", ")", ">", "0", ")", "{", "debug", "(", "'found '", "+", "_", ".", "size", "(", "_rpcCallbacks", ")", "+", "' callbacks left after reconnect'", ")", ";", "_", ".", "each", "(", "_rpcCallbacks", ",", "function", "(", "cb", ")", "{", "return", "cb", "(", "'connection_error'", ")", ";", "}", ")", ";", "}", "_rpcCallbacks", "=", "{", "}", ";", "}", ")", ";", "conn", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "conn", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "if", "(", "_connection", ")", "{", "_connection", ".", "_isClosed", "=", "true", ";", "}", "}", ")", ";", "}" ]
Private functions Setup the connection @param {Object} connectCfg AMQP connection configurations. @param {Object} options AMQP connection options. See https://github.com/postwait/node-amqp#connection-options-and-url for the format of the connectCfg and options
[ "Private", "functions", "Setup", "the", "connection" ]
611adf62f661e4d42066f1c4d5a39dd8692ec720
https://github.com/feedhenry/fh-amqp-js/blob/611adf62f661e4d42066f1c4d5a39dd8692ec720/lib/amqpjs.js#L323-L364
train
feedhenry/fh-amqp-js
lib/amqpjs.js
autoSubscribe
function autoSubscribe() { //re-add pending subscribers if (_pendingSubscribers.length > 0) { async.each(_pendingSubscribers, function(sub, callback) { debug('Add pending subscriber', sub); self.subscribeToTopic(sub.exchange, sub.queue, sub.filter, sub.subscriber, sub.opts, function(err) { if (err) { debug('Failed to add subscriber, keep it', sub); } else { //done, remove the item from the pending subscribers var idx = _pendingSubscribers.indexOf(sub); _pendingSubscribers.splice(idx, 1); debug('pending subsriber added, now there are ' + _pendingSubscribers.length + ' left'); } return callback(); }); }, function() { debug('pending subscribers are added'); }); } }
javascript
function autoSubscribe() { //re-add pending subscribers if (_pendingSubscribers.length > 0) { async.each(_pendingSubscribers, function(sub, callback) { debug('Add pending subscriber', sub); self.subscribeToTopic(sub.exchange, sub.queue, sub.filter, sub.subscriber, sub.opts, function(err) { if (err) { debug('Failed to add subscriber, keep it', sub); } else { //done, remove the item from the pending subscribers var idx = _pendingSubscribers.indexOf(sub); _pendingSubscribers.splice(idx, 1); debug('pending subsriber added, now there are ' + _pendingSubscribers.length + ' left'); } return callback(); }); }, function() { debug('pending subscribers are added'); }); } }
[ "function", "autoSubscribe", "(", ")", "{", "if", "(", "_pendingSubscribers", ".", "length", ">", "0", ")", "{", "async", ".", "each", "(", "_pendingSubscribers", ",", "function", "(", "sub", ",", "callback", ")", "{", "debug", "(", "'Add pending subscriber'", ",", "sub", ")", ";", "self", ".", "subscribeToTopic", "(", "sub", ".", "exchange", ",", "sub", ".", "queue", ",", "sub", ".", "filter", ",", "sub", ".", "subscriber", ",", "sub", ".", "opts", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "'Failed to add subscriber, keep it'", ",", "sub", ")", ";", "}", "else", "{", "var", "idx", "=", "_pendingSubscribers", ".", "indexOf", "(", "sub", ")", ";", "_pendingSubscribers", ".", "splice", "(", "idx", ",", "1", ")", ";", "debug", "(", "'pending subsriber added, now there are '", "+", "_pendingSubscribers", ".", "length", "+", "' left'", ")", ";", "}", "return", "callback", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "debug", "(", "'pending subscribers are added'", ")", ";", "}", ")", ";", "}", "}" ]
Re-add subscriber functions that are created when there is no connection
[ "Re", "-", "add", "subscriber", "functions", "that", "are", "created", "when", "there", "is", "no", "connection" ]
611adf62f661e4d42066f1c4d5a39dd8692ec720
https://github.com/feedhenry/fh-amqp-js/blob/611adf62f661e4d42066f1c4d5a39dd8692ec720/lib/amqpjs.js#L369-L389
train
feedhenry/fh-amqp-js
lib/amqpjs.js
publishCachedMessages
function publishCachedMessages() { if (_cachedPublishMessages.length > 0) { async.each(_cachedPublishMessages, function(message, callback) { debug('republish message', message); self.publishTopic(message.exchange, message.topic, message.message, message.options, function(err) { if (err) { debug('Failed to republish message', message); } else { var idx = _cachedPublishMessages.indexOf(message); _cachedPublishMessages.splice(idx, 1); debug('cached publish message re-published, now there are ' + _cachedPublishMessages.length + ' messages left'); } return callback(); }); }, function() { debug('cached publish messages processed'); }); } }
javascript
function publishCachedMessages() { if (_cachedPublishMessages.length > 0) { async.each(_cachedPublishMessages, function(message, callback) { debug('republish message', message); self.publishTopic(message.exchange, message.topic, message.message, message.options, function(err) { if (err) { debug('Failed to republish message', message); } else { var idx = _cachedPublishMessages.indexOf(message); _cachedPublishMessages.splice(idx, 1); debug('cached publish message re-published, now there are ' + _cachedPublishMessages.length + ' messages left'); } return callback(); }); }, function() { debug('cached publish messages processed'); }); } }
[ "function", "publishCachedMessages", "(", ")", "{", "if", "(", "_cachedPublishMessages", ".", "length", ">", "0", ")", "{", "async", ".", "each", "(", "_cachedPublishMessages", ",", "function", "(", "message", ",", "callback", ")", "{", "debug", "(", "'republish message'", ",", "message", ")", ";", "self", ".", "publishTopic", "(", "message", ".", "exchange", ",", "message", ".", "topic", ",", "message", ".", "message", ",", "message", ".", "options", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "'Failed to republish message'", ",", "message", ")", ";", "}", "else", "{", "var", "idx", "=", "_cachedPublishMessages", ".", "indexOf", "(", "message", ")", ";", "_cachedPublishMessages", ".", "splice", "(", "idx", ",", "1", ")", ";", "debug", "(", "'cached publish message re-published, now there are '", "+", "_cachedPublishMessages", ".", "length", "+", "' messages left'", ")", ";", "}", "return", "callback", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "debug", "(", "'cached publish messages processed'", ")", ";", "}", ")", ";", "}", "}" ]
Re-publish messages that received when there is no connection
[ "Re", "-", "publish", "messages", "that", "received", "when", "there", "is", "no", "connection" ]
611adf62f661e4d42066f1c4d5a39dd8692ec720
https://github.com/feedhenry/fh-amqp-js/blob/611adf62f661e4d42066f1c4d5a39dd8692ec720/lib/amqpjs.js#L394-L412
train
cloudkick/whiskey
lib/extern/optparse/lib/optparse.js
filter_email
function filter_email(value) { var m = EMAIL_RE.exec(value); if(m == null) throw OptError('Excpeted an email address.'); return m[1]; }
javascript
function filter_email(value) { var m = EMAIL_RE.exec(value); if(m == null) throw OptError('Excpeted an email address.'); return m[1]; }
[ "function", "filter_email", "(", "value", ")", "{", "var", "m", "=", "EMAIL_RE", ".", "exec", "(", "value", ")", ";", "if", "(", "m", "==", "null", ")", "throw", "OptError", "(", "'Excpeted an email address.'", ")", ";", "return", "m", "[", "1", "]", ";", "}" ]
Switch argument filter that expects an email address. An exception is throwed if the criteria doesn`t match.
[ "Switch", "argument", "filter", "that", "expects", "an", "email", "address", ".", "An", "exception", "is", "throwed", "if", "the", "criteria", "doesn", "t", "match", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/extern/optparse/lib/optparse.js#L56-L60
train
cloudkick/whiskey
lib/extern/optparse/lib/optparse.js
build_rules
function build_rules(filters, arr) { var rules = []; for(var i=0; i<arr.length; i++) { var r = arr[i], rule if(!contains_expr(r)) throw OptError('Rule MUST contain an option.'); switch(r.length) { case 1: rule = build_rule(filters, r[0]); break; case 2: var expr = LONG_SWITCH_RE.test(r[0]) ? 0 : 1; var alias = expr == 0 ? -1 : 0; var desc = alias == -1 ? 1 : -1; rule = build_rule(filters, r[alias], r[expr], r[desc]); break; case 3: rule = build_rule(filters, r[0], r[1], r[2]); break; default: case 0: continue; } rules.push(rule) } return rules; }
javascript
function build_rules(filters, arr) { var rules = []; for(var i=0; i<arr.length; i++) { var r = arr[i], rule if(!contains_expr(r)) throw OptError('Rule MUST contain an option.'); switch(r.length) { case 1: rule = build_rule(filters, r[0]); break; case 2: var expr = LONG_SWITCH_RE.test(r[0]) ? 0 : 1; var alias = expr == 0 ? -1 : 0; var desc = alias == -1 ? 1 : -1; rule = build_rule(filters, r[alias], r[expr], r[desc]); break; case 3: rule = build_rule(filters, r[0], r[1], r[2]); break; default: case 0: continue; } rules.push(rule) } return rules; }
[ "function", "build_rules", "(", "filters", ",", "arr", ")", "{", "var", "rules", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "var", "r", "=", "arr", "[", "i", "]", ",", "rule", "if", "(", "!", "contains_expr", "(", "r", ")", ")", "throw", "OptError", "(", "'Rule MUST contain an option.'", ")", ";", "switch", "(", "r", ".", "length", ")", "{", "case", "1", ":", "rule", "=", "build_rule", "(", "filters", ",", "r", "[", "0", "]", ")", ";", "break", ";", "case", "2", ":", "var", "expr", "=", "LONG_SWITCH_RE", ".", "test", "(", "r", "[", "0", "]", ")", "?", "0", ":", "1", ";", "var", "alias", "=", "expr", "==", "0", "?", "-", "1", ":", "0", ";", "var", "desc", "=", "alias", "==", "-", "1", "?", "1", ":", "-", "1", ";", "rule", "=", "build_rule", "(", "filters", ",", "r", "[", "alias", "]", ",", "r", "[", "expr", "]", ",", "r", "[", "desc", "]", ")", ";", "break", ";", "case", "3", ":", "rule", "=", "build_rule", "(", "filters", ",", "r", "[", "0", "]", ",", "r", "[", "1", "]", ",", "r", "[", "2", "]", ")", ";", "break", ";", "default", ":", "case", "0", ":", "continue", ";", "}", "rules", ".", "push", "(", "rule", ")", "}", "return", "rules", ";", "}" ]
Buildes rules from a switches collection. The switches collection is defined when constructing a new OptionParser object.
[ "Buildes", "rules", "from", "a", "switches", "collection", ".", "The", "switches", "collection", "is", "defined", "when", "constructing", "a", "new", "OptionParser", "object", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/extern/optparse/lib/optparse.js#L73-L98
train
cloudkick/whiskey
lib/extern/optparse/lib/optparse.js
extend
function extend(dest, src) { var result = dest; for(var n in src) { result[n] = src[n]; } return result; }
javascript
function extend(dest, src) { var result = dest; for(var n in src) { result[n] = src[n]; } return result; }
[ "function", "extend", "(", "dest", ",", "src", ")", "{", "var", "result", "=", "dest", ";", "for", "(", "var", "n", "in", "src", ")", "{", "result", "[", "n", "]", "=", "src", "[", "n", "]", ";", "}", "return", "result", ";", "}" ]
Extends destination object with members of source object
[ "Extends", "destination", "object", "with", "members", "of", "source", "object" ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/extern/optparse/lib/optparse.js#L149-L155
train
cloudkick/whiskey
lib/extern/optparse/lib/optparse.js
spaces
function spaces(arg1, arg2) { var l, builder = []; if(arg1.constructor === Number) { l = arg1; } else { if(arg1.length == arg2) return arg1; l = arg2 - arg1.length; builder.push(arg1); } while(l-- > 0) builder.push(' '); return builder.join(''); }
javascript
function spaces(arg1, arg2) { var l, builder = []; if(arg1.constructor === Number) { l = arg1; } else { if(arg1.length == arg2) return arg1; l = arg2 - arg1.length; builder.push(arg1); } while(l-- > 0) builder.push(' '); return builder.join(''); }
[ "function", "spaces", "(", "arg1", ",", "arg2", ")", "{", "var", "l", ",", "builder", "=", "[", "]", ";", "if", "(", "arg1", ".", "constructor", "===", "Number", ")", "{", "l", "=", "arg1", ";", "}", "else", "{", "if", "(", "arg1", ".", "length", "==", "arg2", ")", "return", "arg1", ";", "l", "=", "arg2", "-", "arg1", ".", "length", ";", "builder", ".", "push", "(", "arg1", ")", ";", "}", "while", "(", "l", "--", ">", "0", ")", "builder", ".", "push", "(", "' '", ")", ";", "return", "builder", ".", "join", "(", "''", ")", ";", "}" ]
Appends spaces to match specified number of chars
[ "Appends", "spaces", "to", "match", "specified", "number", "of", "chars" ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/extern/optparse/lib/optparse.js#L158-L169
train
cloudkick/whiskey
lib/extern/optparse/lib/optparse.js
function(value, fn) { if(value.constructor === Function ) { this.default_handler = value; } else if(value.constructor === Number) { this.on_args[value] = fn; } else { this.on_switches[value] = fn; } }
javascript
function(value, fn) { if(value.constructor === Function ) { this.default_handler = value; } else if(value.constructor === Number) { this.on_args[value] = fn; } else { this.on_switches[value] = fn; } }
[ "function", "(", "value", ",", "fn", ")", "{", "if", "(", "value", ".", "constructor", "===", "Function", ")", "{", "this", ".", "default_handler", "=", "value", ";", "}", "else", "if", "(", "value", ".", "constructor", "===", "Number", ")", "{", "this", ".", "on_args", "[", "value", "]", "=", "fn", ";", "}", "else", "{", "this", ".", "on_switches", "[", "value", "]", "=", "fn", ";", "}", "}" ]
Adds args and switchs handler.
[ "Adds", "args", "and", "switchs", "handler", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/extern/optparse/lib/optparse.js#L203-L211
train
cloudkick/whiskey
lib/extern/optparse/lib/optparse.js
function(args) { var result = [], callback; var rules = build_rules(this.filters, this._rules); var tokens = args.concat([]); var token; while(this._halt == false && (token = tokens.shift())) { if(LONG_SWITCH_RE.test(token) || SHORT_SWITCH_RE.test(token)) { var arg = undefined; // The token is a long or a short switch. Get the corresponding // rule, filter and handle it. Pass the switch to the default // handler if no rule matched. for(var i = 0; i < rules.length; i++) { var rule = rules[i]; if(rule.long == token || rule.short == token) { if(rule.filter !== undefined) { arg = tokens.shift(); if(!LONG_SWITCH_RE.test(arg) && !SHORT_SWITCH_RE.test(arg)) { try { arg = rule.filter(arg); } catch(e) { throw OptError(token + ': ' + e.toString()); } } else if(rule.optional_arg) { tokens.unshift(arg); } else { throw OptError('Expected switch argument.'); } } callback = this.on_switches[rule.name]; if (!callback) callback = this.on_switches['*']; if(callback) callback.apply(this, [rule.name, arg]); break; } } if(i == rules.length) this.default_handler.apply(this, [token]); } else { // Did not match long or short switch. Parse the token as a // normal argument. callback = this.on_args[result.length]; result.push(token); if(callback) callback.apply(this, [token]); } } return this._halt ? this.on_halt.apply(this, [tokens]) : result; }
javascript
function(args) { var result = [], callback; var rules = build_rules(this.filters, this._rules); var tokens = args.concat([]); var token; while(this._halt == false && (token = tokens.shift())) { if(LONG_SWITCH_RE.test(token) || SHORT_SWITCH_RE.test(token)) { var arg = undefined; // The token is a long or a short switch. Get the corresponding // rule, filter and handle it. Pass the switch to the default // handler if no rule matched. for(var i = 0; i < rules.length; i++) { var rule = rules[i]; if(rule.long == token || rule.short == token) { if(rule.filter !== undefined) { arg = tokens.shift(); if(!LONG_SWITCH_RE.test(arg) && !SHORT_SWITCH_RE.test(arg)) { try { arg = rule.filter(arg); } catch(e) { throw OptError(token + ': ' + e.toString()); } } else if(rule.optional_arg) { tokens.unshift(arg); } else { throw OptError('Expected switch argument.'); } } callback = this.on_switches[rule.name]; if (!callback) callback = this.on_switches['*']; if(callback) callback.apply(this, [rule.name, arg]); break; } } if(i == rules.length) this.default_handler.apply(this, [token]); } else { // Did not match long or short switch. Parse the token as a // normal argument. callback = this.on_args[result.length]; result.push(token); if(callback) callback.apply(this, [token]); } } return this._halt ? this.on_halt.apply(this, [tokens]) : result; }
[ "function", "(", "args", ")", "{", "var", "result", "=", "[", "]", ",", "callback", ";", "var", "rules", "=", "build_rules", "(", "this", ".", "filters", ",", "this", ".", "_rules", ")", ";", "var", "tokens", "=", "args", ".", "concat", "(", "[", "]", ")", ";", "var", "token", ";", "while", "(", "this", ".", "_halt", "==", "false", "&&", "(", "token", "=", "tokens", ".", "shift", "(", ")", ")", ")", "{", "if", "(", "LONG_SWITCH_RE", ".", "test", "(", "token", ")", "||", "SHORT_SWITCH_RE", ".", "test", "(", "token", ")", ")", "{", "var", "arg", "=", "undefined", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rules", ".", "length", ";", "i", "++", ")", "{", "var", "rule", "=", "rules", "[", "i", "]", ";", "if", "(", "rule", ".", "long", "==", "token", "||", "rule", ".", "short", "==", "token", ")", "{", "if", "(", "rule", ".", "filter", "!==", "undefined", ")", "{", "arg", "=", "tokens", ".", "shift", "(", ")", ";", "if", "(", "!", "LONG_SWITCH_RE", ".", "test", "(", "arg", ")", "&&", "!", "SHORT_SWITCH_RE", ".", "test", "(", "arg", ")", ")", "{", "try", "{", "arg", "=", "rule", ".", "filter", "(", "arg", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "OptError", "(", "token", "+", "': '", "+", "e", ".", "toString", "(", ")", ")", ";", "}", "}", "else", "if", "(", "rule", ".", "optional_arg", ")", "{", "tokens", ".", "unshift", "(", "arg", ")", ";", "}", "else", "{", "throw", "OptError", "(", "'Expected switch argument.'", ")", ";", "}", "}", "callback", "=", "this", ".", "on_switches", "[", "rule", ".", "name", "]", ";", "if", "(", "!", "callback", ")", "callback", "=", "this", ".", "on_switches", "[", "'*'", "]", ";", "if", "(", "callback", ")", "callback", ".", "apply", "(", "this", ",", "[", "rule", ".", "name", ",", "arg", "]", ")", ";", "break", ";", "}", "}", "if", "(", "i", "==", "rules", ".", "length", ")", "this", ".", "default_handler", ".", "apply", "(", "this", ",", "[", "token", "]", ")", ";", "}", "else", "{", "callback", "=", "this", ".", "on_args", "[", "result", ".", "length", "]", ";", "result", ".", "push", "(", "token", ")", ";", "if", "(", "callback", ")", "callback", ".", "apply", "(", "this", ",", "[", "token", "]", ")", ";", "}", "}", "return", "this", ".", "_halt", "?", "this", ".", "on_halt", ".", "apply", "(", "this", ",", "[", "tokens", "]", ")", ":", "result", ";", "}" ]
Parses specified args. Returns remaining arguments.
[ "Parses", "specified", "args", ".", "Returns", "remaining", "arguments", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/extern/optparse/lib/optparse.js#L222-L266
train
cloudkick/whiskey
lib/extern/optparse/lib/optparse.js
function() { var builder = [this.banner, '', this.options_title], shorts = false, longest = 0, rule; var rules = build_rules(this.filters, this._rules); for(var i = 0; i < rules.length; i++) { rule = rules[i]; // Quick-analyze the options. if(rule.short) shorts = true; if(rule.decl.length > longest) longest = rule.decl.length; } for(var i = 0; i < rules.length; i++) { var text = spaces(6); rule = rules[i]; if(shorts) { if(rule.short) text = spaces(2) + rule.short + ', '; } text += spaces(rule.decl, longest) + spaces(3); text += rule.desc; builder.push(text); } return builder.join('\n'); }
javascript
function() { var builder = [this.banner, '', this.options_title], shorts = false, longest = 0, rule; var rules = build_rules(this.filters, this._rules); for(var i = 0; i < rules.length; i++) { rule = rules[i]; // Quick-analyze the options. if(rule.short) shorts = true; if(rule.decl.length > longest) longest = rule.decl.length; } for(var i = 0; i < rules.length; i++) { var text = spaces(6); rule = rules[i]; if(shorts) { if(rule.short) text = spaces(2) + rule.short + ', '; } text += spaces(rule.decl, longest) + spaces(3); text += rule.desc; builder.push(text); } return builder.join('\n'); }
[ "function", "(", ")", "{", "var", "builder", "=", "[", "this", ".", "banner", ",", "''", ",", "this", ".", "options_title", "]", ",", "shorts", "=", "false", ",", "longest", "=", "0", ",", "rule", ";", "var", "rules", "=", "build_rules", "(", "this", ".", "filters", ",", "this", ".", "_rules", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rules", ".", "length", ";", "i", "++", ")", "{", "rule", "=", "rules", "[", "i", "]", ";", "if", "(", "rule", ".", "short", ")", "shorts", "=", "true", ";", "if", "(", "rule", ".", "decl", ".", "length", ">", "longest", ")", "longest", "=", "rule", ".", "decl", ".", "length", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rules", ".", "length", ";", "i", "++", ")", "{", "var", "text", "=", "spaces", "(", "6", ")", ";", "rule", "=", "rules", "[", "i", "]", ";", "if", "(", "shorts", ")", "{", "if", "(", "rule", ".", "short", ")", "text", "=", "spaces", "(", "2", ")", "+", "rule", ".", "short", "+", "', '", ";", "}", "text", "+=", "spaces", "(", "rule", ".", "decl", ",", "longest", ")", "+", "spaces", "(", "3", ")", ";", "text", "+=", "rule", ".", "desc", ";", "builder", ".", "push", "(", "text", ")", ";", "}", "return", "builder", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Returns a string representation of this OptionParser instance.
[ "Returns", "a", "string", "representation", "of", "this", "OptionParser", "instance", "." ]
25739d420526bc78881493b335a5174a0fb56e8f
https://github.com/cloudkick/whiskey/blob/25739d420526bc78881493b335a5174a0fb56e8f/lib/extern/optparse/lib/optparse.js#L282-L303
train
somesocks/vet
dist/strings/matches.js
matches
function matches(regex) { return function(val) { regex.lastIndex = 0; return isString(val) && regex.test(val); }; }
javascript
function matches(regex) { return function(val) { regex.lastIndex = 0; return isString(val) && regex.test(val); }; }
[ "function", "matches", "(", "regex", ")", "{", "return", "function", "(", "val", ")", "{", "regex", ".", "lastIndex", "=", "0", ";", "return", "isString", "(", "val", ")", "&&", "regex", ".", "test", "(", "val", ")", ";", "}", ";", "}" ]
Builds a function that checks to see if a value matches a regular expression @param regex - the regular expression to check against @returns a function that takes in a value val, and returns true if it is a string that matches regex @memberof vet.strings
[ "Builds", "a", "function", "that", "checks", "to", "see", "if", "a", "value", "matches", "a", "regular", "expression" ]
4557abeb6a8b470cb4a5823a2cc802c825ef29ef
https://github.com/somesocks/vet/blob/4557abeb6a8b470cb4a5823a2cc802c825ef29ef/dist/strings/matches.js#L10-L15
train
cheminfo-js/netcdf-gcms
src/index.js
netcdfGcms
function netcdfGcms(data, options = {}) { let reader = new NetCDFReader(data); const globalAttributes = reader.globalAttributes; let instrument_mfr = reader.getDataVariableAsString('instrument_mfr'); let dataset_origin = reader.attributeExists('dataset_origin'); let mass_values = reader.dataVariableExists('mass_values'); let detector_name = reader.getAttribute('detector_name'); let aia_template_revision = reader.attributeExists('aia_template_revision'); let source_file_format = reader.getAttribute('source_file_format'); let ans; if (mass_values && dataset_origin) { ans = agilentGCMS(reader); } else if ( mass_values && instrument_mfr && instrument_mfr.match(/finnigan/i) ) { ans = finniganGCMS(reader); } else if (mass_values && instrument_mfr && instrument_mfr.match(/bruker/i)) { ans = brukerGCMS(reader); } else if ( mass_values && source_file_format && source_file_format.match(/shimadzu/i) ) { ans = shimadzuGCMS(reader); } else if (detector_name && detector_name.match(/(dad|tic)/i)) { // diode array agilent HPLC ans = agilentHPLC(reader); } else if (aia_template_revision) { ans = aiaTemplate(reader); } else { throw new TypeError('Unknown file format'); } if (options.meta) { ans.meta = addMeta(globalAttributes); } if (options.variables) { ans.variables = addVariables(reader); } return ans; }
javascript
function netcdfGcms(data, options = {}) { let reader = new NetCDFReader(data); const globalAttributes = reader.globalAttributes; let instrument_mfr = reader.getDataVariableAsString('instrument_mfr'); let dataset_origin = reader.attributeExists('dataset_origin'); let mass_values = reader.dataVariableExists('mass_values'); let detector_name = reader.getAttribute('detector_name'); let aia_template_revision = reader.attributeExists('aia_template_revision'); let source_file_format = reader.getAttribute('source_file_format'); let ans; if (mass_values && dataset_origin) { ans = agilentGCMS(reader); } else if ( mass_values && instrument_mfr && instrument_mfr.match(/finnigan/i) ) { ans = finniganGCMS(reader); } else if (mass_values && instrument_mfr && instrument_mfr.match(/bruker/i)) { ans = brukerGCMS(reader); } else if ( mass_values && source_file_format && source_file_format.match(/shimadzu/i) ) { ans = shimadzuGCMS(reader); } else if (detector_name && detector_name.match(/(dad|tic)/i)) { // diode array agilent HPLC ans = agilentHPLC(reader); } else if (aia_template_revision) { ans = aiaTemplate(reader); } else { throw new TypeError('Unknown file format'); } if (options.meta) { ans.meta = addMeta(globalAttributes); } if (options.variables) { ans.variables = addVariables(reader); } return ans; }
[ "function", "netcdfGcms", "(", "data", ",", "options", "=", "{", "}", ")", "{", "let", "reader", "=", "new", "NetCDFReader", "(", "data", ")", ";", "const", "globalAttributes", "=", "reader", ".", "globalAttributes", ";", "let", "instrument_mfr", "=", "reader", ".", "getDataVariableAsString", "(", "'instrument_mfr'", ")", ";", "let", "dataset_origin", "=", "reader", ".", "attributeExists", "(", "'dataset_origin'", ")", ";", "let", "mass_values", "=", "reader", ".", "dataVariableExists", "(", "'mass_values'", ")", ";", "let", "detector_name", "=", "reader", ".", "getAttribute", "(", "'detector_name'", ")", ";", "let", "aia_template_revision", "=", "reader", ".", "attributeExists", "(", "'aia_template_revision'", ")", ";", "let", "source_file_format", "=", "reader", ".", "getAttribute", "(", "'source_file_format'", ")", ";", "let", "ans", ";", "if", "(", "mass_values", "&&", "dataset_origin", ")", "{", "ans", "=", "agilentGCMS", "(", "reader", ")", ";", "}", "else", "if", "(", "mass_values", "&&", "instrument_mfr", "&&", "instrument_mfr", ".", "match", "(", "/", "finnigan", "/", "i", ")", ")", "{", "ans", "=", "finniganGCMS", "(", "reader", ")", ";", "}", "else", "if", "(", "mass_values", "&&", "instrument_mfr", "&&", "instrument_mfr", ".", "match", "(", "/", "bruker", "/", "i", ")", ")", "{", "ans", "=", "brukerGCMS", "(", "reader", ")", ";", "}", "else", "if", "(", "mass_values", "&&", "source_file_format", "&&", "source_file_format", ".", "match", "(", "/", "shimadzu", "/", "i", ")", ")", "{", "ans", "=", "shimadzuGCMS", "(", "reader", ")", ";", "}", "else", "if", "(", "detector_name", "&&", "detector_name", ".", "match", "(", "/", "(dad|tic)", "/", "i", ")", ")", "{", "ans", "=", "agilentHPLC", "(", "reader", ")", ";", "}", "else", "if", "(", "aia_template_revision", ")", "{", "ans", "=", "aiaTemplate", "(", "reader", ")", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'Unknown file format'", ")", ";", "}", "if", "(", "options", ".", "meta", ")", "{", "ans", ".", "meta", "=", "addMeta", "(", "globalAttributes", ")", ";", "}", "if", "(", "options", ".", "variables", ")", "{", "ans", ".", "variables", "=", "addVariables", "(", "reader", ")", ";", "}", "return", "ans", ";", "}" ]
Reads a NetCDF file and returns a formatted JSON with the data from it @param {ArrayBuffer} data - ArrayBuffer or any Typed Array (including Node.js' Buffer from v4) with the data @param {object} [options={}] @param {boolean} [options.meta] - add meta information @param {boolean} [options.variables] -add variables information @return {{times, series}} - JSON with the time, TIC and mass spectra values
[ "Reads", "a", "NetCDF", "file", "and", "returns", "a", "formatted", "JSON", "with", "the", "data", "from", "it" ]
f2d2207d1af02528b5fb4c392122a8461cb5d7f1
https://github.com/cheminfo-js/netcdf-gcms/blob/f2d2207d1af02528b5fb4c392122a8461cb5d7f1/src/index.js#L20-L67
train
yodaiken/dolphinsr
dist/bundle.js
getCardId
function getCardId(o) { return o.master + '#' + o.combination.front.join(',') + '@' + o.combination.back.join(','); }
javascript
function getCardId(o) { return o.master + '#' + o.combination.front.join(',') + '@' + o.combination.back.join(','); }
[ "function", "getCardId", "(", "o", ")", "{", "return", "o", ".", "master", "+", "'#'", "+", "o", ".", "combination", ".", "front", ".", "join", "(", "','", ")", "+", "'@'", "+", "o", ".", "combination", ".", "back", ".", "join", "(", "','", ")", ";", "}" ]
numbers are indexes on master.fields
[ "numbers", "are", "indexes", "on", "master", ".", "fields" ]
5a833fdb1d9d6b87ed48a9599ebb1ee17cc67ca8
https://github.com/yodaiken/dolphinsr/blob/5a833fdb1d9d6b87ed48a9599ebb1ee17cc67ca8/dist/bundle.js#L19-L21
train
yodaiken/dolphinsr
dist/bundle.js
addReview
function addReview(reviews, review) { if (!reviews.length) { return [review]; } var i = reviews.length - 1; for (; i >= 0; i -= 1) { if (reviews[i].ts <= review.ts) { break; } } var newReviews = reviews.slice(0); newReviews.splice(i + 1, 0, review); return newReviews; }
javascript
function addReview(reviews, review) { if (!reviews.length) { return [review]; } var i = reviews.length - 1; for (; i >= 0; i -= 1) { if (reviews[i].ts <= review.ts) { break; } } var newReviews = reviews.slice(0); newReviews.splice(i + 1, 0, review); return newReviews; }
[ "function", "addReview", "(", "reviews", ",", "review", ")", "{", "if", "(", "!", "reviews", ".", "length", ")", "{", "return", "[", "review", "]", ";", "}", "var", "i", "=", "reviews", ".", "length", "-", "1", ";", "for", "(", ";", "i", ">=", "0", ";", "i", "-=", "1", ")", "{", "if", "(", "reviews", "[", "i", "]", ".", "ts", "<=", "review", ".", "ts", ")", "{", "break", ";", "}", "}", "var", "newReviews", "=", "reviews", ".", "slice", "(", "0", ")", ";", "newReviews", ".", "splice", "(", "i", "+", "1", ",", "0", ",", "review", ")", ";", "return", "newReviews", ";", "}" ]
This function only works if reviews is always sorted by timestamp
[ "This", "function", "only", "works", "if", "reviews", "is", "always", "sorted", "by", "timestamp" ]
5a833fdb1d9d6b87ed48a9599ebb1ee17cc67ca8
https://github.com/yodaiken/dolphinsr/blob/5a833fdb1d9d6b87ed48a9599ebb1ee17cc67ca8/dist/bundle.js#L43-L59
train
appcelerator/appc-logger
lib/logger.js
searchForArrowCloudLogDir
function searchForArrowCloudLogDir() { if (isWritable('/ctlog')) { return '/ctlog'; } if (process.env.HOME && isWritable(path.join(process.env.HOME, 'ctlog'))) { return path.join(process.env.HOME, 'ctlog'); } if (process.env.USERPROFILE && isWritable(path.join(process.env.USERPROFILE, 'ctlog'))) { return path.join(process.env.USERPROFILE, 'ctlog'); } if (isWritable('./logs')) { return path.resolve('./logs'); } throw new Error('No writable logging directory was found.'); }
javascript
function searchForArrowCloudLogDir() { if (isWritable('/ctlog')) { return '/ctlog'; } if (process.env.HOME && isWritable(path.join(process.env.HOME, 'ctlog'))) { return path.join(process.env.HOME, 'ctlog'); } if (process.env.USERPROFILE && isWritable(path.join(process.env.USERPROFILE, 'ctlog'))) { return path.join(process.env.USERPROFILE, 'ctlog'); } if (isWritable('./logs')) { return path.resolve('./logs'); } throw new Error('No writable logging directory was found.'); }
[ "function", "searchForArrowCloudLogDir", "(", ")", "{", "if", "(", "isWritable", "(", "'/ctlog'", ")", ")", "{", "return", "'/ctlog'", ";", "}", "if", "(", "process", ".", "env", ".", "HOME", "&&", "isWritable", "(", "path", ".", "join", "(", "process", ".", "env", ".", "HOME", ",", "'ctlog'", ")", ")", ")", "{", "return", "path", ".", "join", "(", "process", ".", "env", ".", "HOME", ",", "'ctlog'", ")", ";", "}", "if", "(", "process", ".", "env", ".", "USERPROFILE", "&&", "isWritable", "(", "path", ".", "join", "(", "process", ".", "env", ".", "USERPROFILE", ",", "'ctlog'", ")", ")", ")", "{", "return", "path", ".", "join", "(", "process", ".", "env", ".", "USERPROFILE", ",", "'ctlog'", ")", ";", "}", "if", "(", "isWritable", "(", "'./logs'", ")", ")", "{", "return", "path", ".", "resolve", "(", "'./logs'", ")", ";", "}", "throw", "new", "Error", "(", "'No writable logging directory was found.'", ")", ";", "}" ]
istanbul ignore next Looks through the filesystem for a writable spot to which we can write the logs. @returns {string}
[ "istanbul", "ignore", "next", "Looks", "through", "the", "filesystem", "for", "a", "writable", "spot", "to", "which", "we", "can", "write", "the", "logs", "." ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/logger.js#L17-L31
train
appcelerator/appc-logger
lib/logger.js
isWritable
function isWritable(dir) { debug('checking if ' + dir + ' is writable'); try { if (!fs.existsSync(dir)) { debug(' - it does not exist yet, attempting to create it'); fs.mkdirSync(dir); } if (fs.accessSync) { fs.accessSync(dir, fs.W_OK); } else { debug(' - fs.accessSync is not available, falling back to manual write detection'); fs.writeFileSync(path.join(dir, '.foo'), 'foo'); assert.equal(fs.readFileSync(path.join(dir, '.foo'), 'UTF-8'), 'foo'); fs.unlinkSync(path.join(dir, '.foo')); } debug(' - yes, it is writable'); return true; } catch (exc) { debug(' - no, it is not writable: ', exc); return false; } }
javascript
function isWritable(dir) { debug('checking if ' + dir + ' is writable'); try { if (!fs.existsSync(dir)) { debug(' - it does not exist yet, attempting to create it'); fs.mkdirSync(dir); } if (fs.accessSync) { fs.accessSync(dir, fs.W_OK); } else { debug(' - fs.accessSync is not available, falling back to manual write detection'); fs.writeFileSync(path.join(dir, '.foo'), 'foo'); assert.equal(fs.readFileSync(path.join(dir, '.foo'), 'UTF-8'), 'foo'); fs.unlinkSync(path.join(dir, '.foo')); } debug(' - yes, it is writable'); return true; } catch (exc) { debug(' - no, it is not writable: ', exc); return false; } }
[ "function", "isWritable", "(", "dir", ")", "{", "debug", "(", "'checking if '", "+", "dir", "+", "' is writable'", ")", ";", "try", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "dir", ")", ")", "{", "debug", "(", "' - it does not exist yet, attempting to create it'", ")", ";", "fs", ".", "mkdirSync", "(", "dir", ")", ";", "}", "if", "(", "fs", ".", "accessSync", ")", "{", "fs", ".", "accessSync", "(", "dir", ",", "fs", ".", "W_OK", ")", ";", "}", "else", "{", "debug", "(", "' - fs.accessSync is not available, falling back to manual write detection'", ")", ";", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "dir", ",", "'.foo'", ")", ",", "'foo'", ")", ";", "assert", ".", "equal", "(", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "dir", ",", "'.foo'", ")", ",", "'UTF-8'", ")", ",", "'foo'", ")", ";", "fs", ".", "unlinkSync", "(", "path", ".", "join", "(", "dir", ",", "'.foo'", ")", ")", ";", "}", "debug", "(", "' - yes, it is writable'", ")", ";", "return", "true", ";", "}", "catch", "(", "exc", ")", "{", "debug", "(", "' - no, it is not writable: '", ",", "exc", ")", ";", "return", "false", ";", "}", "}" ]
istanbul ignore next Checks if a directory is writable, returning a boolean or throwing an exception, depending on the arguments. @param {string} dir The directory to check. @returns {boolean} Whether or not the directory is writable.
[ "istanbul", "ignore", "next", "Checks", "if", "a", "directory", "is", "writable", "returning", "a", "boolean", "or", "throwing", "an", "exception", "depending", "on", "the", "arguments", "." ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/logger.js#L39-L60
train
appcelerator/appc-logger
lib/logger.js
getPort
function getPort(req) { if (req.connection && req.connection.localPort) { return req.connection.localPort.toString(); } const host = req.headers && req.headers.host; let protocolSrc = 80; if (host && ((host.match(/:/g) || []).length) === 1) { const possiblePort = host.split(':')[1]; protocolSrc = isNaN(possiblePort) ? protocolSrc : possiblePort; } return protocolSrc; }
javascript
function getPort(req) { if (req.connection && req.connection.localPort) { return req.connection.localPort.toString(); } const host = req.headers && req.headers.host; let protocolSrc = 80; if (host && ((host.match(/:/g) || []).length) === 1) { const possiblePort = host.split(':')[1]; protocolSrc = isNaN(possiblePort) ? protocolSrc : possiblePort; } return protocolSrc; }
[ "function", "getPort", "(", "req", ")", "{", "if", "(", "req", ".", "connection", "&&", "req", ".", "connection", ".", "localPort", ")", "{", "return", "req", ".", "connection", ".", "localPort", ".", "toString", "(", ")", ";", "}", "const", "host", "=", "req", ".", "headers", "&&", "req", ".", "headers", ".", "host", ";", "let", "protocolSrc", "=", "80", ";", "if", "(", "host", "&&", "(", "(", "host", ".", "match", "(", "/", ":", "/", "g", ")", "||", "[", "]", ")", ".", "length", ")", "===", "1", ")", "{", "const", "possiblePort", "=", "host", ".", "split", "(", "':'", ")", "[", "1", "]", ";", "protocolSrc", "=", "isNaN", "(", "possiblePort", ")", "?", "protocolSrc", ":", "possiblePort", ";", "}", "return", "protocolSrc", ";", "}" ]
derive the port if its in the host string. @param {Object} req a express req object @return {string} string representation of port
[ "derive", "the", "port", "if", "its", "in", "the", "host", "string", "." ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/logger.js#L217-L228
train
appcelerator/appc-logger
lib/logger.js
getStatus
function getStatus (res) { let status; const statusCode = res.statusCode; if (statusCode) { status = Math.floor(statusCode / 100) * 100; } switch (status) { case 100: case 200: case 300: return 'success'; default: return 'failure'; } }
javascript
function getStatus (res) { let status; const statusCode = res.statusCode; if (statusCode) { status = Math.floor(statusCode / 100) * 100; } switch (status) { case 100: case 200: case 300: return 'success'; default: return 'failure'; } }
[ "function", "getStatus", "(", "res", ")", "{", "let", "status", ";", "const", "statusCode", "=", "res", ".", "statusCode", ";", "if", "(", "statusCode", ")", "{", "status", "=", "Math", ".", "floor", "(", "statusCode", "/", "100", ")", "*", "100", ";", "}", "switch", "(", "status", ")", "{", "case", "100", ":", "case", "200", ":", "case", "300", ":", "return", "'success'", ";", "default", ":", "return", "'failure'", ";", "}", "}" ]
derive the status string from the status code @param {Object} res express res object @return {string} success or error string
[ "derive", "the", "status", "string", "from", "the", "status", "code" ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/logger.js#L234-L248
train
appcelerator/appc-logger
lib/logger.js
isWhitelisted
function isWhitelisted(url) { return options.adiPathFilter.some(function (route) { return url.substr(0, route.length) === route; }); }
javascript
function isWhitelisted(url) { return options.adiPathFilter.some(function (route) { return url.substr(0, route.length) === route; }); }
[ "function", "isWhitelisted", "(", "url", ")", "{", "return", "options", ".", "adiPathFilter", ".", "some", "(", "function", "(", "route", ")", "{", "return", "url", ".", "substr", "(", "0", ",", "route", ".", "length", ")", "===", "route", ";", "}", ")", ";", "}" ]
Determine whether a certain URL is whitelisted based off the prefix @param {string} url URL to check @return {boolean} Is the URL in the whitelist
[ "Determine", "whether", "a", "certain", "URL", "is", "whitelisted", "based", "off", "the", "prefix" ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/logger.js#L263-L267
train
appcelerator/appc-logger
lib/logger.js
createDefaultLogger
function createDefaultLogger(options) { const ConsoleLogger = require('./console'), consoleLogger = new ConsoleLogger(options), config = _.mergeWith({ name: 'logger', streams: [ { level: options && options.level || 'trace', type: 'raw', stream: consoleLogger } ] }, options, function (a, b) { return _.isArray(a) ? a.concat(b) : undefined; }); consoleLogger.level = bunyan.resolveLevel(options && options.level || 'trace'); // default is to add the problem logger if (!options || options.problemLogger || options.problemLogger === undefined) { const ProblemLogger = require('./problem'); config.streams.push({ level: 'trace', type: 'raw', stream: new ProblemLogger(options) }); } const defaultLogger = bunyan.createLogger(config); /** * Set log level * Backward compatible with Arrow Cloud MVC framework * @param {Object} nameOrNum log level in string or number * @return {String} */ defaultLogger.setLevel = function (nameOrNum) { var level = 'trace'; try { level = bunyan.resolveLevel(nameOrNum); } catch (e) {} // eslint-disable-line no-empty consoleLogger.level = level; return this.level(level); }; return defaultLogger; }
javascript
function createDefaultLogger(options) { const ConsoleLogger = require('./console'), consoleLogger = new ConsoleLogger(options), config = _.mergeWith({ name: 'logger', streams: [ { level: options && options.level || 'trace', type: 'raw', stream: consoleLogger } ] }, options, function (a, b) { return _.isArray(a) ? a.concat(b) : undefined; }); consoleLogger.level = bunyan.resolveLevel(options && options.level || 'trace'); // default is to add the problem logger if (!options || options.problemLogger || options.problemLogger === undefined) { const ProblemLogger = require('./problem'); config.streams.push({ level: 'trace', type: 'raw', stream: new ProblemLogger(options) }); } const defaultLogger = bunyan.createLogger(config); /** * Set log level * Backward compatible with Arrow Cloud MVC framework * @param {Object} nameOrNum log level in string or number * @return {String} */ defaultLogger.setLevel = function (nameOrNum) { var level = 'trace'; try { level = bunyan.resolveLevel(nameOrNum); } catch (e) {} // eslint-disable-line no-empty consoleLogger.level = level; return this.level(level); }; return defaultLogger; }
[ "function", "createDefaultLogger", "(", "options", ")", "{", "const", "ConsoleLogger", "=", "require", "(", "'./console'", ")", ",", "consoleLogger", "=", "new", "ConsoleLogger", "(", "options", ")", ",", "config", "=", "_", ".", "mergeWith", "(", "{", "name", ":", "'logger'", ",", "streams", ":", "[", "{", "level", ":", "options", "&&", "options", ".", "level", "||", "'trace'", ",", "type", ":", "'raw'", ",", "stream", ":", "consoleLogger", "}", "]", "}", ",", "options", ",", "function", "(", "a", ",", "b", ")", "{", "return", "_", ".", "isArray", "(", "a", ")", "?", "a", ".", "concat", "(", "b", ")", ":", "undefined", ";", "}", ")", ";", "consoleLogger", ".", "level", "=", "bunyan", ".", "resolveLevel", "(", "options", "&&", "options", ".", "level", "||", "'trace'", ")", ";", "if", "(", "!", "options", "||", "options", ".", "problemLogger", "||", "options", ".", "problemLogger", "===", "undefined", ")", "{", "const", "ProblemLogger", "=", "require", "(", "'./problem'", ")", ";", "config", ".", "streams", ".", "push", "(", "{", "level", ":", "'trace'", ",", "type", ":", "'raw'", ",", "stream", ":", "new", "ProblemLogger", "(", "options", ")", "}", ")", ";", "}", "const", "defaultLogger", "=", "bunyan", ".", "createLogger", "(", "config", ")", ";", "defaultLogger", ".", "setLevel", "=", "function", "(", "nameOrNum", ")", "{", "var", "level", "=", "'trace'", ";", "try", "{", "level", "=", "bunyan", ".", "resolveLevel", "(", "nameOrNum", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "consoleLogger", ".", "level", "=", "level", ";", "return", "this", ".", "level", "(", "level", ")", ";", "}", ";", "return", "defaultLogger", ";", "}" ]
Create a default logger @param {Object} options - options @returns {Object}
[ "Create", "a", "default", "logger" ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/logger.js#L447-L491
train
Metatavu/kunta-api-spec
javascript-generated/src/api/CodesApi.js
function(apiClient) { this.apiClient = apiClient || ApiClient.instance; /** * Finds a code * Finds a code * @param {String} codeId Id of the code * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Code} */ this.findCode = function(codeId) { var postBody = null; // verify the required parameter 'codeId' is set if (codeId == undefined || codeId == null) { throw "Missing the required parameter 'codeId' when calling findCode"; } var pathParams = { 'codeId': codeId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = Code; return this.apiClient.callApi( '/codes/{codeId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * Lists codes * Lists codes * @param {Object} opts Optional parameters * @param {Array.<String>} opts.types Filter results by types * @param {String} opts.search Search codes by free-text query * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is SCORE * @param {String} opts.sortDir ASC or DESC. Default is ASC * @param {Integer} opts.firstResult First result * @param {Integer} opts.maxResults Max results * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Code>} */ this.listCodes = function(opts) { opts = opts || {}; var postBody = null; var pathParams = { }; var queryParams = { 'types': this.apiClient.buildCollectionParam(opts['types'], 'csv'), 'search': opts['search'], 'sortBy': opts['sortBy'], 'sortDir': opts['sortDir'], 'firstResult': opts['firstResult'], 'maxResults': opts['maxResults'] }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = [Code]; return this.apiClient.callApi( '/codes', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } }
javascript
function(apiClient) { this.apiClient = apiClient || ApiClient.instance; /** * Finds a code * Finds a code * @param {String} codeId Id of the code * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Code} */ this.findCode = function(codeId) { var postBody = null; // verify the required parameter 'codeId' is set if (codeId == undefined || codeId == null) { throw "Missing the required parameter 'codeId' when calling findCode"; } var pathParams = { 'codeId': codeId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = Code; return this.apiClient.callApi( '/codes/{codeId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * Lists codes * Lists codes * @param {Object} opts Optional parameters * @param {Array.<String>} opts.types Filter results by types * @param {String} opts.search Search codes by free-text query * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is SCORE * @param {String} opts.sortDir ASC or DESC. Default is ASC * @param {Integer} opts.firstResult First result * @param {Integer} opts.maxResults Max results * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Code>} */ this.listCodes = function(opts) { opts = opts || {}; var postBody = null; var pathParams = { }; var queryParams = { 'types': this.apiClient.buildCollectionParam(opts['types'], 'csv'), 'search': opts['search'], 'sortBy': opts['sortBy'], 'sortDir': opts['sortDir'], 'firstResult': opts['firstResult'], 'maxResults': opts['maxResults'] }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = [Code]; return this.apiClient.callApi( '/codes', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } }
[ "function", "(", "apiClient", ")", "{", "this", ".", "apiClient", "=", "apiClient", "||", "ApiClient", ".", "instance", ";", "this", ".", "findCode", "=", "function", "(", "codeId", ")", "{", "var", "postBody", "=", "null", ";", "if", "(", "codeId", "==", "undefined", "||", "codeId", "==", "null", ")", "{", "throw", "\"Missing the required parameter 'codeId' when calling findCode\"", ";", "}", "var", "pathParams", "=", "{", "'codeId'", ":", "codeId", "}", ";", "var", "queryParams", "=", "{", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "Code", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/codes/{codeId}'", ",", "'GET'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "this", ".", "listCodes", "=", "function", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "postBody", "=", "null", ";", "var", "pathParams", "=", "{", "}", ";", "var", "queryParams", "=", "{", "'types'", ":", "this", ".", "apiClient", ".", "buildCollectionParam", "(", "opts", "[", "'types'", "]", ",", "'csv'", ")", ",", "'search'", ":", "opts", "[", "'search'", "]", ",", "'sortBy'", ":", "opts", "[", "'sortBy'", "]", ",", "'sortDir'", ":", "opts", "[", "'sortDir'", "]", ",", "'firstResult'", ":", "opts", "[", "'firstResult'", "]", ",", "'maxResults'", ":", "opts", "[", "'maxResults'", "]", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "[", "Code", "]", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/codes'", ",", "'GET'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "}" ]
Codes service. @module api/CodesApi @version 0.0.139 Constructs a new CodesApi. @alias module:api/CodesApi @class @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} if unspecified.
[ "Codes", "service", "." ]
4daa78ccd8c50736c2af2cc625b6237539f3b43a
https://github.com/Metatavu/kunta-api-spec/blob/4daa78ccd8c50736c2af2cc625b6237539f3b43a/javascript-generated/src/api/CodesApi.js#L55-L141
train
appcelerator/appc-logger
lib/console.js
ConsoleLogger
function ConsoleLogger(options) { EventEmitter.call(this); this.options = options || {}; // allow use to customize if they want the label or not this.prefix = this.options.prefix === undefined ? true : this.options.prefix; this.showcr = this.options.showcr === undefined ? true : this.options.showcr; this.showtab = this.options.showtab === undefined ? true : this.options.showtab; this.colorize = this.options.colorize === undefined ? checkColorize() : this.options.colorize; this.logPrepend = this.options.logPrepend; chalk.enabled = !!this.colorize; // if we are logging from a cluster worker, prepend the process PID // istanbul ignore if if (cluster.isWorker) { if (chalk.enabled) { this.logPrepend = chalk.black.inverse(String(process.pid)) + grey(' |'); } else { this.logPrepend = process.pid + ' |'; } } this.remapLevels(); }
javascript
function ConsoleLogger(options) { EventEmitter.call(this); this.options = options || {}; // allow use to customize if they want the label or not this.prefix = this.options.prefix === undefined ? true : this.options.prefix; this.showcr = this.options.showcr === undefined ? true : this.options.showcr; this.showtab = this.options.showtab === undefined ? true : this.options.showtab; this.colorize = this.options.colorize === undefined ? checkColorize() : this.options.colorize; this.logPrepend = this.options.logPrepend; chalk.enabled = !!this.colorize; // if we are logging from a cluster worker, prepend the process PID // istanbul ignore if if (cluster.isWorker) { if (chalk.enabled) { this.logPrepend = chalk.black.inverse(String(process.pid)) + grey(' |'); } else { this.logPrepend = process.pid + ' |'; } } this.remapLevels(); }
[ "function", "ConsoleLogger", "(", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "prefix", "=", "this", ".", "options", ".", "prefix", "===", "undefined", "?", "true", ":", "this", ".", "options", ".", "prefix", ";", "this", ".", "showcr", "=", "this", ".", "options", ".", "showcr", "===", "undefined", "?", "true", ":", "this", ".", "options", ".", "showcr", ";", "this", ".", "showtab", "=", "this", ".", "options", ".", "showtab", "===", "undefined", "?", "true", ":", "this", ".", "options", ".", "showtab", ";", "this", ".", "colorize", "=", "this", ".", "options", ".", "colorize", "===", "undefined", "?", "checkColorize", "(", ")", ":", "this", ".", "options", ".", "colorize", ";", "this", ".", "logPrepend", "=", "this", ".", "options", ".", "logPrepend", ";", "chalk", ".", "enabled", "=", "!", "!", "this", ".", "colorize", ";", "if", "(", "cluster", ".", "isWorker", ")", "{", "if", "(", "chalk", ".", "enabled", ")", "{", "this", ".", "logPrepend", "=", "chalk", ".", "black", ".", "inverse", "(", "String", "(", "process", ".", "pid", ")", ")", "+", "grey", "(", "' |'", ")", ";", "}", "else", "{", "this", ".", "logPrepend", "=", "process", ".", "pid", "+", "' |'", ";", "}", "}", "this", ".", "remapLevels", "(", ")", ";", "}" ]
Console logging functionality @param {Object} options - options
[ "Console", "logging", "functionality" ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/console.js#L25-L46
train
mWater/mwater-forms
lib/ResponseAnswersComponent.js
isLoadNeeded
function isLoadNeeded(newProps, oldProps) { return !_.isEqual(newProps.formDesign, oldProps.formDesign) || !_.isEqual(newProps.data, oldProps.data); }
javascript
function isLoadNeeded(newProps, oldProps) { return !_.isEqual(newProps.formDesign, oldProps.formDesign) || !_.isEqual(newProps.data, oldProps.data); }
[ "function", "isLoadNeeded", "(", "newProps", ",", "oldProps", ")", "{", "return", "!", "_", ".", "isEqual", "(", "newProps", ".", "formDesign", ",", "oldProps", ".", "formDesign", ")", "||", "!", "_", ".", "isEqual", "(", "newProps", ".", "data", ",", "oldProps", ".", "data", ")", ";", "}" ]
Check if form design or data are different
[ "Check", "if", "form", "design", "or", "data", "are", "different" ]
8c707c285ae0e6fa9aaa065471fa8a0e9e43d40c
https://github.com/mWater/mwater-forms/blob/8c707c285ae0e6fa9aaa065471fa8a0e9e43d40c/lib/ResponseAnswersComponent.js#L47-L49
train
Metatavu/kunta-api-spec
javascript-generated/src/api/OrganizationsApi.js
function(apiClient) { this.apiClient = apiClient || ApiClient.instance; /** * Find organization * Find organization * @param {String} organizationId organization id * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Organization} */ this.findOrganization = function(organizationId) { var postBody = null; // verify the required parameter 'organizationId' is set if (organizationId == undefined || organizationId == null) { throw "Missing the required parameter 'organizationId' when calling findOrganization"; } var pathParams = { 'organizationId': organizationId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = Organization; return this.apiClient.callApi( '/organizations/{organizationId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * List organizations * List organizations * @param {Object} opts Optional parameters * @param {String} opts.businessName Filter by organization&#39;s business name * @param {String} opts.businessCode Filter by organization&#39;s business code * @param {String} opts.search Search organizations by free-text query * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is NATURAL * @param {String} opts.sortDir ASC or DESC. Default is ASC * @param {Integer} opts.firstResult First result * @param {Integer} opts.maxResults Max results * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Organization>} */ this.listOrganizations = function(opts) { opts = opts || {}; var postBody = null; var pathParams = { }; var queryParams = { 'businessName': opts['businessName'], 'businessCode': opts['businessCode'], 'search': opts['search'], 'sortBy': opts['sortBy'], 'sortDir': opts['sortDir'], 'firstResult': opts['firstResult'], 'maxResults': opts['maxResults'] }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = [Organization]; return this.apiClient.callApi( '/organizations', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } }
javascript
function(apiClient) { this.apiClient = apiClient || ApiClient.instance; /** * Find organization * Find organization * @param {String} organizationId organization id * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Organization} */ this.findOrganization = function(organizationId) { var postBody = null; // verify the required parameter 'organizationId' is set if (organizationId == undefined || organizationId == null) { throw "Missing the required parameter 'organizationId' when calling findOrganization"; } var pathParams = { 'organizationId': organizationId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = Organization; return this.apiClient.callApi( '/organizations/{organizationId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * List organizations * List organizations * @param {Object} opts Optional parameters * @param {String} opts.businessName Filter by organization&#39;s business name * @param {String} opts.businessCode Filter by organization&#39;s business code * @param {String} opts.search Search organizations by free-text query * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is NATURAL * @param {String} opts.sortDir ASC or DESC. Default is ASC * @param {Integer} opts.firstResult First result * @param {Integer} opts.maxResults Max results * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Organization>} */ this.listOrganizations = function(opts) { opts = opts || {}; var postBody = null; var pathParams = { }; var queryParams = { 'businessName': opts['businessName'], 'businessCode': opts['businessCode'], 'search': opts['search'], 'sortBy': opts['sortBy'], 'sortDir': opts['sortDir'], 'firstResult': opts['firstResult'], 'maxResults': opts['maxResults'] }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = [Organization]; return this.apiClient.callApi( '/organizations', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } }
[ "function", "(", "apiClient", ")", "{", "this", ".", "apiClient", "=", "apiClient", "||", "ApiClient", ".", "instance", ";", "this", ".", "findOrganization", "=", "function", "(", "organizationId", ")", "{", "var", "postBody", "=", "null", ";", "if", "(", "organizationId", "==", "undefined", "||", "organizationId", "==", "null", ")", "{", "throw", "\"Missing the required parameter 'organizationId' when calling findOrganization\"", ";", "}", "var", "pathParams", "=", "{", "'organizationId'", ":", "organizationId", "}", ";", "var", "queryParams", "=", "{", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "Organization", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/organizations/{organizationId}'", ",", "'GET'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "this", ".", "listOrganizations", "=", "function", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "postBody", "=", "null", ";", "var", "pathParams", "=", "{", "}", ";", "var", "queryParams", "=", "{", "'businessName'", ":", "opts", "[", "'businessName'", "]", ",", "'businessCode'", ":", "opts", "[", "'businessCode'", "]", ",", "'search'", ":", "opts", "[", "'search'", "]", ",", "'sortBy'", ":", "opts", "[", "'sortBy'", "]", ",", "'sortDir'", ":", "opts", "[", "'sortDir'", "]", ",", "'firstResult'", ":", "opts", "[", "'firstResult'", "]", ",", "'maxResults'", ":", "opts", "[", "'maxResults'", "]", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "[", "Organization", "]", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/organizations'", ",", "'GET'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "}" ]
Organizations service. @module api/OrganizationsApi @version 0.0.139 Constructs a new OrganizationsApi. @alias module:api/OrganizationsApi @class @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} if unspecified.
[ "Organizations", "service", "." ]
4daa78ccd8c50736c2af2cc625b6237539f3b43a
https://github.com/Metatavu/kunta-api-spec/blob/4daa78ccd8c50736c2af2cc625b6237539f3b43a/javascript-generated/src/api/OrganizationsApi.js#L55-L143
train
appcelerator/appc-logger
lib/index.js
createLogger
function createLogger(fn) { return function () { var args = [], self = this, c; for (c = 0; c < arguments.length; c++) { args[c] = logger.specialObjectClone(arguments[c]); } return fn.apply(self, args); }; }
javascript
function createLogger(fn) { return function () { var args = [], self = this, c; for (c = 0; c < arguments.length; c++) { args[c] = logger.specialObjectClone(arguments[c]); } return fn.apply(self, args); }; }
[ "function", "createLogger", "(", "fn", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "[", "]", ",", "self", "=", "this", ",", "c", ";", "for", "(", "c", "=", "0", ";", "c", "<", "arguments", ".", "length", ";", "c", "++", ")", "{", "args", "[", "c", "]", "=", "logger", ".", "specialObjectClone", "(", "arguments", "[", "c", "]", ")", ";", "}", "return", "fn", ".", "apply", "(", "self", ",", "args", ")", ";", "}", ";", "}" ]
create a log adapter that will handle masking @param {Function} fn [description] @return {Function} [description]
[ "create", "a", "log", "adapter", "that", "will", "handle", "masking" ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/index.js#L20-L30
train
Metatavu/kunta-api-spec
javascript-generated/src/api/FragmentsApi.js
function(apiClient) { this.apiClient = apiClient || ApiClient.instance; /** * Finds organizations page fragment * Finds single organization page fragment * @param {String} organizationId Organization id * @param {String} fragmentId fragment id * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Fragment} */ this.findOrganizationFragment = function(organizationId, fragmentId) { var postBody = null; // verify the required parameter 'organizationId' is set if (organizationId == undefined || organizationId == null) { throw "Missing the required parameter 'organizationId' when calling findOrganizationFragment"; } // verify the required parameter 'fragmentId' is set if (fragmentId == undefined || fragmentId == null) { throw "Missing the required parameter 'fragmentId' when calling findOrganizationFragment"; } var pathParams = { 'organizationId': organizationId, 'fragmentId': fragmentId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = Fragment; return this.apiClient.callApi( '/organizations/{organizationId}/fragments/{fragmentId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * Lists organizations page fragments * Lists organizations page fragments * @param {String} organizationId Organization id * @param {Object} opts Optional parameters * @param {String} opts.slug Filter results by fragment slug * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Fragment>} */ this.listOrganizationFragments = function(organizationId, opts) { opts = opts || {}; var postBody = null; // verify the required parameter 'organizationId' is set if (organizationId == undefined || organizationId == null) { throw "Missing the required parameter 'organizationId' when calling listOrganizationFragments"; } var pathParams = { 'organizationId': organizationId }; var queryParams = { 'slug': opts['slug'] }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = [Fragment]; return this.apiClient.callApi( '/organizations/{organizationId}/fragments', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } }
javascript
function(apiClient) { this.apiClient = apiClient || ApiClient.instance; /** * Finds organizations page fragment * Finds single organization page fragment * @param {String} organizationId Organization id * @param {String} fragmentId fragment id * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Fragment} */ this.findOrganizationFragment = function(organizationId, fragmentId) { var postBody = null; // verify the required parameter 'organizationId' is set if (organizationId == undefined || organizationId == null) { throw "Missing the required parameter 'organizationId' when calling findOrganizationFragment"; } // verify the required parameter 'fragmentId' is set if (fragmentId == undefined || fragmentId == null) { throw "Missing the required parameter 'fragmentId' when calling findOrganizationFragment"; } var pathParams = { 'organizationId': organizationId, 'fragmentId': fragmentId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = Fragment; return this.apiClient.callApi( '/organizations/{organizationId}/fragments/{fragmentId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * Lists organizations page fragments * Lists organizations page fragments * @param {String} organizationId Organization id * @param {Object} opts Optional parameters * @param {String} opts.slug Filter results by fragment slug * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/Fragment>} */ this.listOrganizationFragments = function(organizationId, opts) { opts = opts || {}; var postBody = null; // verify the required parameter 'organizationId' is set if (organizationId == undefined || organizationId == null) { throw "Missing the required parameter 'organizationId' when calling listOrganizationFragments"; } var pathParams = { 'organizationId': organizationId }; var queryParams = { 'slug': opts['slug'] }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = [Fragment]; return this.apiClient.callApi( '/organizations/{organizationId}/fragments', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } }
[ "function", "(", "apiClient", ")", "{", "this", ".", "apiClient", "=", "apiClient", "||", "ApiClient", ".", "instance", ";", "this", ".", "findOrganizationFragment", "=", "function", "(", "organizationId", ",", "fragmentId", ")", "{", "var", "postBody", "=", "null", ";", "if", "(", "organizationId", "==", "undefined", "||", "organizationId", "==", "null", ")", "{", "throw", "\"Missing the required parameter 'organizationId' when calling findOrganizationFragment\"", ";", "}", "if", "(", "fragmentId", "==", "undefined", "||", "fragmentId", "==", "null", ")", "{", "throw", "\"Missing the required parameter 'fragmentId' when calling findOrganizationFragment\"", ";", "}", "var", "pathParams", "=", "{", "'organizationId'", ":", "organizationId", ",", "'fragmentId'", ":", "fragmentId", "}", ";", "var", "queryParams", "=", "{", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "Fragment", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/organizations/{organizationId}/fragments/{fragmentId}'", ",", "'GET'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "this", ".", "listOrganizationFragments", "=", "function", "(", "organizationId", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "postBody", "=", "null", ";", "if", "(", "organizationId", "==", "undefined", "||", "organizationId", "==", "null", ")", "{", "throw", "\"Missing the required parameter 'organizationId' when calling listOrganizationFragments\"", ";", "}", "var", "pathParams", "=", "{", "'organizationId'", ":", "organizationId", "}", ";", "var", "queryParams", "=", "{", "'slug'", ":", "opts", "[", "'slug'", "]", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "[", "Fragment", "]", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/organizations/{organizationId}/fragments'", ",", "'GET'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "}" ]
Fragments service. @module api/FragmentsApi @version 0.0.139 Constructs a new FragmentsApi. @alias module:api/FragmentsApi @class @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} if unspecified.
[ "Fragments", "service", "." ]
4daa78ccd8c50736c2af2cc625b6237539f3b43a
https://github.com/Metatavu/kunta-api-spec/blob/4daa78ccd8c50736c2af2cc625b6237539f3b43a/javascript-generated/src/api/FragmentsApi.js#L55-L145
train
canjs/can-compute
proto-compute.js
function() { canReflect.onValue( observation, updater,"notify"); if (observation.hasOwnProperty("_value")) {// can-observation 4.1+ compute.value = observation._value; } else {// can-observation < 4.1 compute.value = observation.value; } }
javascript
function() { canReflect.onValue( observation, updater,"notify"); if (observation.hasOwnProperty("_value")) {// can-observation 4.1+ compute.value = observation._value; } else {// can-observation < 4.1 compute.value = observation.value; } }
[ "function", "(", ")", "{", "canReflect", ".", "onValue", "(", "observation", ",", "updater", ",", "\"notify\"", ")", ";", "if", "(", "observation", ".", "hasOwnProperty", "(", "\"_value\"", ")", ")", "{", "compute", ".", "value", "=", "observation", ".", "_value", ";", "}", "else", "{", "compute", ".", "value", "=", "observation", ".", "value", ";", "}", "}" ]
Call `onchanged` when any source observables change.
[ "Call", "onchanged", "when", "any", "source", "observables", "change", "." ]
ac271cf6a68ec936e2f7992df2bb9bc1f5a7cf36
https://github.com/canjs/can-compute/blob/ac271cf6a68ec936e2f7992df2bb9bc1f5a7cf36/proto-compute.js#L147-L154
train
Metatavu/kunta-api-spec
javascript-generated/src/api/PhoneServiceChannelsApi.js
function(apiClient) { this.apiClient = apiClient || ApiClient.instance; /** * Finds a phone service channel by id * Finds a phone service channel by id * @param {String} phoneServiceChannelId Phone service channel id * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PhoneServiceChannel} */ this.findPhoneServiceChannel = function(phoneServiceChannelId) { var postBody = null; // verify the required parameter 'phoneServiceChannelId' is set if (phoneServiceChannelId == undefined || phoneServiceChannelId == null) { throw "Missing the required parameter 'phoneServiceChannelId' when calling findPhoneServiceChannel"; } var pathParams = { 'phoneServiceChannelId': phoneServiceChannelId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = PhoneServiceChannel; return this.apiClient.callApi( '/phoneServiceChannels/{phoneServiceChannelId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * Lists phone service channels * Lists phone service channels * @param {Object} opts Optional parameters * @param {String} opts.organizationId Organization id * @param {String} opts.search Search channels by free-text query * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is NATURAL * @param {String} opts.sortDir ASC or DESC. Default is ASC * @param {Integer} opts.firstResult First result * @param {Integer} opts.maxResults Max results * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/PhoneServiceChannel>} */ this.listPhoneServiceChannels = function(opts) { opts = opts || {}; var postBody = null; var pathParams = { }; var queryParams = { 'organizationId': opts['organizationId'], 'search': opts['search'], 'sortBy': opts['sortBy'], 'sortDir': opts['sortDir'], 'firstResult': opts['firstResult'], 'maxResults': opts['maxResults'] }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = [PhoneServiceChannel]; return this.apiClient.callApi( '/phoneServiceChannels', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * Updates a channel * Updates a service channel * @param {String} phoneServiceChannelId phone channel id * @param {module:model/PhoneServiceChannel} payload New phone service data * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PhoneServiceChannel} */ this.updatePhoneServiceChannel = function(phoneServiceChannelId, payload) { var postBody = payload; // verify the required parameter 'phoneServiceChannelId' is set if (phoneServiceChannelId == undefined || phoneServiceChannelId == null) { throw "Missing the required parameter 'phoneServiceChannelId' when calling updatePhoneServiceChannel"; } // verify the required parameter 'payload' is set if (payload == undefined || payload == null) { throw "Missing the required parameter 'payload' when calling updatePhoneServiceChannel"; } var pathParams = { 'phoneServiceChannelId': phoneServiceChannelId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = PhoneServiceChannel; return this.apiClient.callApi( '/phoneServiceChannels/{phoneServiceChannelId}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } }
javascript
function(apiClient) { this.apiClient = apiClient || ApiClient.instance; /** * Finds a phone service channel by id * Finds a phone service channel by id * @param {String} phoneServiceChannelId Phone service channel id * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PhoneServiceChannel} */ this.findPhoneServiceChannel = function(phoneServiceChannelId) { var postBody = null; // verify the required parameter 'phoneServiceChannelId' is set if (phoneServiceChannelId == undefined || phoneServiceChannelId == null) { throw "Missing the required parameter 'phoneServiceChannelId' when calling findPhoneServiceChannel"; } var pathParams = { 'phoneServiceChannelId': phoneServiceChannelId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = PhoneServiceChannel; return this.apiClient.callApi( '/phoneServiceChannels/{phoneServiceChannelId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * Lists phone service channels * Lists phone service channels * @param {Object} opts Optional parameters * @param {String} opts.organizationId Organization id * @param {String} opts.search Search channels by free-text query * @param {String} opts.sortBy define order (NATURAL or SCORE). Default is NATURAL * @param {String} opts.sortDir ASC or DESC. Default is ASC * @param {Integer} opts.firstResult First result * @param {Integer} opts.maxResults Max results * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link Array.<module:model/PhoneServiceChannel>} */ this.listPhoneServiceChannels = function(opts) { opts = opts || {}; var postBody = null; var pathParams = { }; var queryParams = { 'organizationId': opts['organizationId'], 'search': opts['search'], 'sortBy': opts['sortBy'], 'sortDir': opts['sortDir'], 'firstResult': opts['firstResult'], 'maxResults': opts['maxResults'] }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = [PhoneServiceChannel]; return this.apiClient.callApi( '/phoneServiceChannels', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } /** * Updates a channel * Updates a service channel * @param {String} phoneServiceChannelId phone channel id * @param {module:model/PhoneServiceChannel} payload New phone service data * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/PhoneServiceChannel} */ this.updatePhoneServiceChannel = function(phoneServiceChannelId, payload) { var postBody = payload; // verify the required parameter 'phoneServiceChannelId' is set if (phoneServiceChannelId == undefined || phoneServiceChannelId == null) { throw "Missing the required parameter 'phoneServiceChannelId' when calling updatePhoneServiceChannel"; } // verify the required parameter 'payload' is set if (payload == undefined || payload == null) { throw "Missing the required parameter 'payload' when calling updatePhoneServiceChannel"; } var pathParams = { 'phoneServiceChannelId': phoneServiceChannelId }; var queryParams = { }; var headerParams = { }; var formParams = { }; var authNames = ['basicAuth']; var contentTypes = ['application/json;charset=utf-8']; var accepts = ['application/json;charset=utf-8']; var returnType = PhoneServiceChannel; return this.apiClient.callApi( '/phoneServiceChannels/{phoneServiceChannelId}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType ); } }
[ "function", "(", "apiClient", ")", "{", "this", ".", "apiClient", "=", "apiClient", "||", "ApiClient", ".", "instance", ";", "this", ".", "findPhoneServiceChannel", "=", "function", "(", "phoneServiceChannelId", ")", "{", "var", "postBody", "=", "null", ";", "if", "(", "phoneServiceChannelId", "==", "undefined", "||", "phoneServiceChannelId", "==", "null", ")", "{", "throw", "\"Missing the required parameter 'phoneServiceChannelId' when calling findPhoneServiceChannel\"", ";", "}", "var", "pathParams", "=", "{", "'phoneServiceChannelId'", ":", "phoneServiceChannelId", "}", ";", "var", "queryParams", "=", "{", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "PhoneServiceChannel", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/phoneServiceChannels/{phoneServiceChannelId}'", ",", "'GET'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "this", ".", "listPhoneServiceChannels", "=", "function", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "postBody", "=", "null", ";", "var", "pathParams", "=", "{", "}", ";", "var", "queryParams", "=", "{", "'organizationId'", ":", "opts", "[", "'organizationId'", "]", ",", "'search'", ":", "opts", "[", "'search'", "]", ",", "'sortBy'", ":", "opts", "[", "'sortBy'", "]", ",", "'sortDir'", ":", "opts", "[", "'sortDir'", "]", ",", "'firstResult'", ":", "opts", "[", "'firstResult'", "]", ",", "'maxResults'", ":", "opts", "[", "'maxResults'", "]", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "[", "PhoneServiceChannel", "]", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/phoneServiceChannels'", ",", "'GET'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "this", ".", "updatePhoneServiceChannel", "=", "function", "(", "phoneServiceChannelId", ",", "payload", ")", "{", "var", "postBody", "=", "payload", ";", "if", "(", "phoneServiceChannelId", "==", "undefined", "||", "phoneServiceChannelId", "==", "null", ")", "{", "throw", "\"Missing the required parameter 'phoneServiceChannelId' when calling updatePhoneServiceChannel\"", ";", "}", "if", "(", "payload", "==", "undefined", "||", "payload", "==", "null", ")", "{", "throw", "\"Missing the required parameter 'payload' when calling updatePhoneServiceChannel\"", ";", "}", "var", "pathParams", "=", "{", "'phoneServiceChannelId'", ":", "phoneServiceChannelId", "}", ";", "var", "queryParams", "=", "{", "}", ";", "var", "headerParams", "=", "{", "}", ";", "var", "formParams", "=", "{", "}", ";", "var", "authNames", "=", "[", "'basicAuth'", "]", ";", "var", "contentTypes", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "accepts", "=", "[", "'application/json;charset=utf-8'", "]", ";", "var", "returnType", "=", "PhoneServiceChannel", ";", "return", "this", ".", "apiClient", ".", "callApi", "(", "'/phoneServiceChannels/{phoneServiceChannelId}'", ",", "'PUT'", ",", "pathParams", ",", "queryParams", ",", "headerParams", ",", "formParams", ",", "postBody", ",", "authNames", ",", "contentTypes", ",", "accepts", ",", "returnType", ")", ";", "}", "}" ]
PhoneServiceChannels service. @module api/PhoneServiceChannelsApi @version 0.0.139 Constructs a new PhoneServiceChannelsApi. @alias module:api/PhoneServiceChannelsApi @class @param {module:ApiClient} apiClient Optional API client implementation to use, default to {@link module:ApiClient#instance} if unspecified.
[ "PhoneServiceChannels", "service", "." ]
4daa78ccd8c50736c2af2cc625b6237539f3b43a
https://github.com/Metatavu/kunta-api-spec/blob/4daa78ccd8c50736c2af2cc625b6237539f3b43a/javascript-generated/src/api/PhoneServiceChannelsApi.js#L55-L185
train
appcelerator/appc-logger
lib/problem.js
ProblemLogger
function ProblemLogger(options) { options = options || {}; ConsoleLogger.call(this); const tmpdir = require('os').tmpdir(); this.filename = path.join(tmpdir, 'logger-' + (+new Date()) + '.log'); this.name = options.problemLogName || ((options.name || 'problem') + '.log'); this.stream = fs.createWriteStream(this.filename); this.write({ level: bunyan.TRACE, msg: util.format('log file opened') }); streams.push(this); }
javascript
function ProblemLogger(options) { options = options || {}; ConsoleLogger.call(this); const tmpdir = require('os').tmpdir(); this.filename = path.join(tmpdir, 'logger-' + (+new Date()) + '.log'); this.name = options.problemLogName || ((options.name || 'problem') + '.log'); this.stream = fs.createWriteStream(this.filename); this.write({ level: bunyan.TRACE, msg: util.format('log file opened') }); streams.push(this); }
[ "function", "ProblemLogger", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "ConsoleLogger", ".", "call", "(", "this", ")", ";", "const", "tmpdir", "=", "require", "(", "'os'", ")", ".", "tmpdir", "(", ")", ";", "this", ".", "filename", "=", "path", ".", "join", "(", "tmpdir", ",", "'logger-'", "+", "(", "+", "new", "Date", "(", ")", ")", "+", "'.log'", ")", ";", "this", ".", "name", "=", "options", ".", "problemLogName", "||", "(", "(", "options", ".", "name", "||", "'problem'", ")", "+", "'.log'", ")", ";", "this", ".", "stream", "=", "fs", ".", "createWriteStream", "(", "this", ".", "filename", ")", ";", "this", ".", "write", "(", "{", "level", ":", "bunyan", ".", "TRACE", ",", "msg", ":", "util", ".", "format", "(", "'log file opened'", ")", "}", ")", ";", "streams", ".", "push", "(", "this", ")", ";", "}" ]
Logger stream that will only write out a log file if the process exits non-zero in the current directory @param {Object} options - options @constructor
[ "Logger", "stream", "that", "will", "only", "write", "out", "a", "log", "file", "if", "the", "process", "exits", "non", "-", "zero", "in", "the", "current", "directory" ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/problem.js#L19-L28
train
appcelerator/appc-logger
lib/problem.js
closeStreams
function closeStreams(exitCode) { // default is 0 if not specified exitCode = exitCode === undefined ? 0 : exitCode; if (streams.length) { streams.forEach(function (logger) { logger.write({ level: bunyan.TRACE, msg: util.format('exited with code %d', exitCode) }); logger.stream.end(); // jscs:disable jsDoc logger.write = function () {}; }); } }
javascript
function closeStreams(exitCode) { // default is 0 if not specified exitCode = exitCode === undefined ? 0 : exitCode; if (streams.length) { streams.forEach(function (logger) { logger.write({ level: bunyan.TRACE, msg: util.format('exited with code %d', exitCode) }); logger.stream.end(); // jscs:disable jsDoc logger.write = function () {}; }); } }
[ "function", "closeStreams", "(", "exitCode", ")", "{", "exitCode", "=", "exitCode", "===", "undefined", "?", "0", ":", "exitCode", ";", "if", "(", "streams", ".", "length", ")", "{", "streams", ".", "forEach", "(", "function", "(", "logger", ")", "{", "logger", ".", "write", "(", "{", "level", ":", "bunyan", ".", "TRACE", ",", "msg", ":", "util", ".", "format", "(", "'exited with code %d'", ",", "exitCode", ")", "}", ")", ";", "logger", ".", "stream", ".", "end", "(", ")", ";", "logger", ".", "write", "=", "function", "(", ")", "{", "}", ";", "}", ")", ";", "}", "}" ]
Close the stream @param {number} exitCode - numeric entry code
[ "Close", "the", "stream" ]
7ded47e93f7c59de4dbd83e61cff5be890ae17fa
https://github.com/appcelerator/appc-logger/blob/7ded47e93f7c59de4dbd83e61cff5be890ae17fa/lib/problem.js#L59-L71
train
noodlefrenzy/node-amqp10
lib/session.js
function(l) { debug('Attaching link ' + l.name + ':' + l.handle + ' after begin received'); if (l.state() !== 'attached' && l.state() !== 'attaching') l.attach(); }
javascript
function(l) { debug('Attaching link ' + l.name + ':' + l.handle + ' after begin received'); if (l.state() !== 'attached' && l.state() !== 'attaching') l.attach(); }
[ "function", "(", "l", ")", "{", "debug", "(", "'Attaching link '", "+", "l", ".", "name", "+", "':'", "+", "l", ".", "handle", "+", "' after begin received'", ")", ";", "if", "(", "l", ".", "state", "(", ")", "!==", "'attached'", "&&", "l", ".", "state", "(", ")", "!==", "'attaching'", ")", "l", ".", "attach", "(", ")", ";", "}" ]
attach all links
[ "attach", "all", "links" ]
f5c2aa570830a8dd454e89ed3f4222fc7953fcf7
https://github.com/noodlefrenzy/node-amqp10/blob/f5c2aa570830a8dd454e89ed3f4222fc7953fcf7/lib/session.js#L441-L444
train
noodlefrenzy/node-amqp10
lib/frames.js
role
function role(value) { if (typeof value === 'boolean') return value; if (value !== 'sender' && value !== 'receiver') throw new errors.EncodingError(value, 'invalid role'); return (value === 'sender') ? false : true; }
javascript
function role(value) { if (typeof value === 'boolean') return value; if (value !== 'sender' && value !== 'receiver') throw new errors.EncodingError(value, 'invalid role'); return (value === 'sender') ? false : true; }
[ "function", "role", "(", "value", ")", "{", "if", "(", "typeof", "value", "===", "'boolean'", ")", "return", "value", ";", "if", "(", "value", "!==", "'sender'", "&&", "value", "!==", "'receiver'", ")", "throw", "new", "errors", ".", "EncodingError", "(", "value", ",", "'invalid role'", ")", ";", "return", "(", "value", "===", "'sender'", ")", "?", "false", ":", "true", ";", "}" ]
restricted type helpers
[ "restricted", "type", "helpers" ]
f5c2aa570830a8dd454e89ed3f4222fc7953fcf7
https://github.com/noodlefrenzy/node-amqp10/blob/f5c2aa570830a8dd454e89ed3f4222fc7953fcf7/lib/frames.js#L154-L161
train
noodlefrenzy/node-amqp10
lib/types.js
listBuilder
function listBuilder(list, bufb, codec, width) { if (!Array.isArray(list)) { throw new errors.EncodingError(list, 'Unsure how to encode non-array as list'); } if (!width && list.length === 0) { bufb.appendUInt8(0x45); return; } // Encode all elements into a temp buffer to allow us to front-load appropriate size and count. var tempBuilder = new Builder(); var _len = list.length; for (var _i = 0; _i < _len; ++_i) codec.encode(list[_i], tempBuilder); var tempBuffer = tempBuilder.get(); // Code, size, length, data if (width === 1 || (tempBuffer.length < 0xFF && list.length < 0xFF && width !== 4)) { // list8 if (!width) bufb.appendUInt8(0xC0); bufb.appendUInt8(tempBuffer.length + 1); bufb.appendUInt8(list.length); } else { // list32 if (!width) bufb.appendUInt8(0xD0); bufb.appendUInt32BE(tempBuffer.length + 4); bufb.appendUInt32BE(list.length); } bufb.appendBuffer(tempBuffer); }
javascript
function listBuilder(list, bufb, codec, width) { if (!Array.isArray(list)) { throw new errors.EncodingError(list, 'Unsure how to encode non-array as list'); } if (!width && list.length === 0) { bufb.appendUInt8(0x45); return; } // Encode all elements into a temp buffer to allow us to front-load appropriate size and count. var tempBuilder = new Builder(); var _len = list.length; for (var _i = 0; _i < _len; ++_i) codec.encode(list[_i], tempBuilder); var tempBuffer = tempBuilder.get(); // Code, size, length, data if (width === 1 || (tempBuffer.length < 0xFF && list.length < 0xFF && width !== 4)) { // list8 if (!width) bufb.appendUInt8(0xC0); bufb.appendUInt8(tempBuffer.length + 1); bufb.appendUInt8(list.length); } else { // list32 if (!width) bufb.appendUInt8(0xD0); bufb.appendUInt32BE(tempBuffer.length + 4); bufb.appendUInt32BE(list.length); } bufb.appendBuffer(tempBuffer); }
[ "function", "listBuilder", "(", "list", ",", "bufb", ",", "codec", ",", "width", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "list", ")", ")", "{", "throw", "new", "errors", ".", "EncodingError", "(", "list", ",", "'Unsure how to encode non-array as list'", ")", ";", "}", "if", "(", "!", "width", "&&", "list", ".", "length", "===", "0", ")", "{", "bufb", ".", "appendUInt8", "(", "0x45", ")", ";", "return", ";", "}", "var", "tempBuilder", "=", "new", "Builder", "(", ")", ";", "var", "_len", "=", "list", ".", "length", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "_len", ";", "++", "_i", ")", "codec", ".", "encode", "(", "list", "[", "_i", "]", ",", "tempBuilder", ")", ";", "var", "tempBuffer", "=", "tempBuilder", ".", "get", "(", ")", ";", "if", "(", "width", "===", "1", "||", "(", "tempBuffer", ".", "length", "<", "0xFF", "&&", "list", ".", "length", "<", "0xFF", "&&", "width", "!==", "4", ")", ")", "{", "if", "(", "!", "width", ")", "bufb", ".", "appendUInt8", "(", "0xC0", ")", ";", "bufb", ".", "appendUInt8", "(", "tempBuffer", ".", "length", "+", "1", ")", ";", "bufb", ".", "appendUInt8", "(", "list", ".", "length", ")", ";", "}", "else", "{", "if", "(", "!", "width", ")", "bufb", ".", "appendUInt8", "(", "0xD0", ")", ";", "bufb", ".", "appendUInt32BE", "(", "tempBuffer", ".", "length", "+", "4", ")", ";", "bufb", ".", "appendUInt32BE", "(", "list", ".", "length", ")", ";", "}", "bufb", ".", "appendBuffer", "(", "tempBuffer", ")", ";", "}" ]
Decoder methods decode an incoming buffer into an appropriate concrete JS entity. @function decoder @param {Buffer} buf Buffer to decode, stripped of prefix code (e.g. 0xA1 0x03 'foo' would have the 0xA1 stripped) @param {Codec} [codec] If needed, the codec to decode sub-values for composite types. @return Decoded value Encoder for list types, specified in AMQP 1.0 as: <pre> +----------= count items =----------+ | | n OCTETs n OCTETs | | +----------+----------+--------------+------------+-------+ | size | count | ... /| item |\ ... | +----------+----------+------------/ +------------+ \-----+ / / \ \ / / \ \ / / \ \ +-------------+----------+ | constructor | data | +-------------+----------+ Subcategory n ================= 0xC 1 0xD 4 </pre> @param {Array} val Value to encode. @param {Builder} bufb Buffer-encoder to write encoded list into. @param {Codec} codec Codec to use for encoding list entries. @param {Number} [width] Should be 1 or 4. If given, encoder assumes code already written, and will ensure array is encoded to the given byte-width type. Useful for arrays. @private
[ "Decoder", "methods", "decode", "an", "incoming", "buffer", "into", "an", "appropriate", "concrete", "JS", "entity", "." ]
f5c2aa570830a8dd454e89ed3f4222fc7953fcf7
https://github.com/noodlefrenzy/node-amqp10/blob/f5c2aa570830a8dd454e89ed3f4222fc7953fcf7/lib/types.js#L99-L129
train
noodlefrenzy/node-amqp10
lib/types.js
mapBuilder
function mapBuilder(map, bufb, codec, width) { if (typeof map !== 'object') { throw new errors.EncodingError(map, 'Unsure how to encode non-object as map'); } if (Array.isArray(map)) { throw new errors.EncodingError(map, 'Unsure how to encode array as map'); } var keys = Object.keys(map); if (!width && keys.length === 0) { bufb.appendUInt8(0xC1); bufb.appendUInt8(1); bufb.appendUInt8(0); return; } // Encode all elements into a temp buffer to allow us to front-load appropriate size and count. var tempBuilder = new Builder(); var _len = keys.length; for (var _i = 0; _i < _len; ++_i) { codec.encode(keys[_i], tempBuilder); codec.encode(map[keys[_i]], tempBuilder); } var tempBuffer = tempBuilder.get(); // Code, size, length, data if (width === 1 || (width !== 4 && tempBuffer.length < 0xFF)) { // map8 if (!width) bufb.appendUInt8(0xC1); bufb.appendUInt8(tempBuffer.length + 1); bufb.appendUInt8(keys.length * 2); } else { // map32 if (!width) bufb.appendUInt8(0xD1); bufb.appendUInt32BE(tempBuffer.length + 4); bufb.appendUInt32BE(keys.length * 2); } bufb.appendBuffer(tempBuffer); }
javascript
function mapBuilder(map, bufb, codec, width) { if (typeof map !== 'object') { throw new errors.EncodingError(map, 'Unsure how to encode non-object as map'); } if (Array.isArray(map)) { throw new errors.EncodingError(map, 'Unsure how to encode array as map'); } var keys = Object.keys(map); if (!width && keys.length === 0) { bufb.appendUInt8(0xC1); bufb.appendUInt8(1); bufb.appendUInt8(0); return; } // Encode all elements into a temp buffer to allow us to front-load appropriate size and count. var tempBuilder = new Builder(); var _len = keys.length; for (var _i = 0; _i < _len; ++_i) { codec.encode(keys[_i], tempBuilder); codec.encode(map[keys[_i]], tempBuilder); } var tempBuffer = tempBuilder.get(); // Code, size, length, data if (width === 1 || (width !== 4 && tempBuffer.length < 0xFF)) { // map8 if (!width) bufb.appendUInt8(0xC1); bufb.appendUInt8(tempBuffer.length + 1); bufb.appendUInt8(keys.length * 2); } else { // map32 if (!width) bufb.appendUInt8(0xD1); bufb.appendUInt32BE(tempBuffer.length + 4); bufb.appendUInt32BE(keys.length * 2); } bufb.appendBuffer(tempBuffer); }
[ "function", "mapBuilder", "(", "map", ",", "bufb", ",", "codec", ",", "width", ")", "{", "if", "(", "typeof", "map", "!==", "'object'", ")", "{", "throw", "new", "errors", ".", "EncodingError", "(", "map", ",", "'Unsure how to encode non-object as map'", ")", ";", "}", "if", "(", "Array", ".", "isArray", "(", "map", ")", ")", "{", "throw", "new", "errors", ".", "EncodingError", "(", "map", ",", "'Unsure how to encode array as map'", ")", ";", "}", "var", "keys", "=", "Object", ".", "keys", "(", "map", ")", ";", "if", "(", "!", "width", "&&", "keys", ".", "length", "===", "0", ")", "{", "bufb", ".", "appendUInt8", "(", "0xC1", ")", ";", "bufb", ".", "appendUInt8", "(", "1", ")", ";", "bufb", ".", "appendUInt8", "(", "0", ")", ";", "return", ";", "}", "var", "tempBuilder", "=", "new", "Builder", "(", ")", ";", "var", "_len", "=", "keys", ".", "length", ";", "for", "(", "var", "_i", "=", "0", ";", "_i", "<", "_len", ";", "++", "_i", ")", "{", "codec", ".", "encode", "(", "keys", "[", "_i", "]", ",", "tempBuilder", ")", ";", "codec", ".", "encode", "(", "map", "[", "keys", "[", "_i", "]", "]", ",", "tempBuilder", ")", ";", "}", "var", "tempBuffer", "=", "tempBuilder", ".", "get", "(", ")", ";", "if", "(", "width", "===", "1", "||", "(", "width", "!==", "4", "&&", "tempBuffer", ".", "length", "<", "0xFF", ")", ")", "{", "if", "(", "!", "width", ")", "bufb", ".", "appendUInt8", "(", "0xC1", ")", ";", "bufb", ".", "appendUInt8", "(", "tempBuffer", ".", "length", "+", "1", ")", ";", "bufb", ".", "appendUInt8", "(", "keys", ".", "length", "*", "2", ")", ";", "}", "else", "{", "if", "(", "!", "width", ")", "bufb", ".", "appendUInt8", "(", "0xD1", ")", ";", "bufb", ".", "appendUInt32BE", "(", "tempBuffer", ".", "length", "+", "4", ")", ";", "bufb", ".", "appendUInt32BE", "(", "keys", ".", "length", "*", "2", ")", ";", "}", "bufb", ".", "appendBuffer", "(", "tempBuffer", ")", ";", "}" ]
A map is encoded as a compound value where the constituent elements form alternating key value pairs. <pre> item 0 item 1 item n-1 item n +-------+-------+----+---------+---------+ | key 1 | val 1 | .. | key n/2 | val n/2 | +-------+-------+----+---------+---------+ </pre> Map encodings must contain an even number of items (i.e. an equal number of keys and values). A map in which there exist two identical key values is invalid. Unless known to be otherwise, maps must be considered to be ordered - that is the order of the key-value pairs is semantically important and two maps which are different only in the order in which their key-value pairs are encoded are not equal. @param {Object} val Value to encode. @param {Builder} bufb Buffer-builder to encode map into. @param {Codec} codec Codec to use for encoding keys and values. @param {Number} [width] Should be 1 or 4. If given, encoder assumes code already written, and will ensure array is encoded to the given byte-width type. Useful for arrays. @private
[ "A", "map", "is", "encoded", "as", "a", "compound", "value", "where", "the", "constituent", "elements", "form", "alternating", "key", "value", "pairs", "." ]
f5c2aa570830a8dd454e89ed3f4222fc7953fcf7
https://github.com/noodlefrenzy/node-amqp10/blob/f5c2aa570830a8dd454e89ed3f4222fc7953fcf7/lib/types.js#L270-L310
train
noodlefrenzy/node-amqp10
lib/utilities.js
assertArguments
function assertArguments(options, argnames) { if (!argnames) return; if (!options) throw new TypeError('missing arguments: ' + argnames); argnames.forEach(function (argname) { if (!options.hasOwnProperty(argname)) { throw new TypeError('missing argument: ' + argname); } }); }
javascript
function assertArguments(options, argnames) { if (!argnames) return; if (!options) throw new TypeError('missing arguments: ' + argnames); argnames.forEach(function (argname) { if (!options.hasOwnProperty(argname)) { throw new TypeError('missing argument: ' + argname); } }); }
[ "function", "assertArguments", "(", "options", ",", "argnames", ")", "{", "if", "(", "!", "argnames", ")", "return", ";", "if", "(", "!", "options", ")", "throw", "new", "TypeError", "(", "'missing arguments: '", "+", "argnames", ")", ";", "argnames", ".", "forEach", "(", "function", "(", "argname", ")", "{", "if", "(", "!", "options", ".", "hasOwnProperty", "(", "argname", ")", ")", "{", "throw", "new", "TypeError", "(", "'missing argument: '", "+", "argname", ")", ";", "}", "}", ")", ";", "}" ]
Convenience method to assert that a given options object contains the required arguments. @param options @param argnames
[ "Convenience", "method", "to", "assert", "that", "a", "given", "options", "object", "contains", "the", "required", "arguments", "." ]
f5c2aa570830a8dd454e89ed3f4222fc7953fcf7
https://github.com/noodlefrenzy/node-amqp10/blob/f5c2aa570830a8dd454e89ed3f4222fc7953fcf7/lib/utilities.js#L87-L95
train
noodlefrenzy/node-amqp10
lib/sasl/sasl.js
Sasl
function Sasl(mechanism, handler) { if (!mechanism || !handler) { throw new errors.NotImplementedError('Need both the mechanism and the handler'); } this.mechanism = mechanism; this.handler = handler; this.receivedHeader = false; }
javascript
function Sasl(mechanism, handler) { if (!mechanism || !handler) { throw new errors.NotImplementedError('Need both the mechanism and the handler'); } this.mechanism = mechanism; this.handler = handler; this.receivedHeader = false; }
[ "function", "Sasl", "(", "mechanism", ",", "handler", ")", "{", "if", "(", "!", "mechanism", "||", "!", "handler", ")", "{", "throw", "new", "errors", ".", "NotImplementedError", "(", "'Need both the mechanism and the handler'", ")", ";", "}", "this", ".", "mechanism", "=", "mechanism", ";", "this", ".", "handler", "=", "handler", ";", "this", ".", "receivedHeader", "=", "false", ";", "}" ]
Currently, only supports SASL ANONYMOUS or PLAIN @constructor
[ "Currently", "only", "supports", "SASL", "ANONYMOUS", "or", "PLAIN" ]
f5c2aa570830a8dd454e89ed3f4222fc7953fcf7
https://github.com/noodlefrenzy/node-amqp10/blob/f5c2aa570830a8dd454e89ed3f4222fc7953fcf7/lib/sasl/sasl.js#L21-L28
train
noodlefrenzy/node-amqp10
lib/policies/policy.js
Policy
function Policy(overrides) { if (!(this instanceof Policy)) return new Policy(overrides); u.defaults(this, overrides, { /** * support subjects in link names with the following characteristics: * receiver: "amq.topic/news", means a filter on the ReceiverLink will be made * for messages send with a subject "news" * * sender: "amq.topic/news", will automatically set "news" as the subject for * messages sent on this link, unless the user explicitly overrides * the subject. * * @name Policy#defaultSubjects * @property {boolean} */ defaultSubjects: true, /** * Options related to the reconnect behavior of the client. If this value is `null` reconnect * is effectively disabled * * @name Policy#reconnect * @type {Object|null} * @property {number|null} [retries] How many times to attempt reconnection * @property {string} [strategy='fibonacci'] The algorithm used for backoff. Can be `fibonacci` or `exponential` * @property {boolean} [forever] Whether or not to attempt reconnection forever */ reconnect: { retries: 10, strategy: 'fibonacci', // || 'exponential' forever: true }, /** * @name Policy#connect * @type {object} * @property {object} options Options passed into the open performative on initial connection * @property {string|function} options.containerId The id of the source container * @property {string} options.hostname The name of the target host * @property {number} options.maxFrameSize The largest frame size that the sending peer is able to accept on this connection * @property {number} options.channelMax The channel-max value is the highest channel number that can be used on the connection * @property {number} options.idleTimeout The idle timeout required by the sender * @property {array<string>|null} options.outgoingLocales A list of the locales that the peer supports for sending informational text * @property {array<string>|null} options.incomingLocales A list of locales that the sending peer permits for incoming informational text * @property {array<string>|null} options.offeredCapabilities A list of extension capabilities the peer may use if the sender offers them * @property {array|null} options.desiredCapabilities The desired-capability list defines which extension capabilities the sender may use if the receiver offers them * @property {object|null} options.properties The properties map contains a set of fields intended to indicate information about the connection and its container * @property {object} sslOptions Options used to initiate a TLS/SSL connection, with the exception of the following options all options in this object are passed directly to node's [tls.connect](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback) method. * @property {string|null} sslOptions.keyFile Path to the file containing the private key for the client * @property {string|null} sslOptions.certFile Path to the file containing the certificate key for the client * @property {string|null} sslOptions.caFile Path to the file containing the trusted cert for the client * @property {boolean} sslOptions.rejectUnauthorized * @property {string|null} saslMechanism Allows the sasl mechanism to be overriden by policy */ connect: { options: { containerId: containerName(), hostname: 'localhost', maxFrameSize: constants.defaultMaxFrameSize, channelMax: constants.defaultChannelMax, idleTimeout: constants.defaultIdleTimeout, outgoingLocales: constants.defaultOutgoingLocales, incomingLocales: constants.defaultIncomingLocales, offeredCapabilities: null, desiredCapabilities: null, properties: {}, }, sslOptions: { keyFile: null, certFile: null, caFile: null, rejectUnauthorized: false }, saslMechanism: null }, /** * @name Policy#session * @type {object} * @property {object} options Options passed into the `begin` performative on session start * @property {number} options.nextOutgoingId The transfer-id to assign to the next transfer frame * @property {number} options.incomingWindow The maximum number of incoming transfer frames that the endpoint can currently receive * @property {number} options.outgoingWindow The maximum number of outgoing transfer frames that the endpoint can currently send * @property {function} window A function used to calculate how/when the flow control window should change * @property {number} windowQuantum Quantum used in predefined window policies * @property {boolean} enableSessionFlowControl Whether or not session flow control should be performed at all * @property {object|null} reestablish=null Whether the session should attempt to reestablish when ended by the broker */ session: { options: { nextOutgoingId: constants.session.defaultOutgoingId, incomingWindow: constants.session.defaultIncomingWindow, outgoingWindow: constants.session.defaultOutgoingWindow }, window: putils.WindowPolicies.RefreshAtHalf, windowQuantum: constants.session.defaultIncomingWindow, enableSessionFlowControl: true, reestablish: null }, /** * @name Policy#senderLink * @type {object} * @property {object} attach Options passed into the `attach` performative on link attachment * @property {string|function} attach.name This name uniquely identifies the link from the container of the source to the container of the target node * @property {string|boolean} attach.role The role being played by the peer * @property {string|number} attach.sndSettleMode The delivery settlement policy for the sender * @property {number} attach.maxMessageSize The maximum message size supported by the link endpoint * @property {number} attach.initialDeliveryCount This must not be null if role is sender, and it is ignored if the role is receiver. * @property {string} callback Determines when a send should call its callback ('settle', 'sent', 'none') * @property {function|null} encoder=null The optional encoder used for all outgoing sends * @property {boolean|null} reattach=null Whether the link should attempt reattach on detach */ senderLink: { attach: { name: linkName('sender'), role: constants.linkRole.sender, sndSettleMode: constants.senderSettleMode.mixed, maxMessageSize: 0, initialDeliveryCount: 1 }, callback: putils.SenderCallbackPolicies.OnSettle, encoder: null, reattach: null }, /** * @name Policy#receiverLink * @type {object} * @property {object} attach Options passed into the `attach` performative on link attachment * @property {string|function} attach.name This name uniquely identifies the link from the container of the source to the container of the target node * @property {boolean} attach.role The role being played by the peer * @property {number|string} attach.rcvSettleMode The delivery settlement policy for the receiver * @property {number} attach.maxMessageSize The maximum message size supported by the link endpoint * @property {number} attach.initialDeliveryCount This must not be null if role is sender, and it is ignored if the role is receiver. * @property {function} credit A function that determines when (if ever) to refresh the receiver link's credit * @property {number} creditQuantum Quantum used in pre-defined credit policy functions * @property {function|null} decoder=null The optional decoder used for all incoming data * @property {boolean|null} reattach=null Whether the link should attempt reattach on detach */ receiverLink: { attach: { name: linkName('receiver'), role: constants.linkRole.receiver, rcvSettleMode: constants.receiverSettleMode.autoSettle, maxMessageSize: 10000, // Arbitrary choice initialDeliveryCount: 1 }, credit: putils.CreditPolicies.RefreshAtHalf, creditQuantum: 100, decoder: null, reattach: null }, }); putils.fixDeprecatedLinkOptions(this.senderLink); putils.fixDeprecatedLinkOptions(this.receiverLink); return this; }
javascript
function Policy(overrides) { if (!(this instanceof Policy)) return new Policy(overrides); u.defaults(this, overrides, { /** * support subjects in link names with the following characteristics: * receiver: "amq.topic/news", means a filter on the ReceiverLink will be made * for messages send with a subject "news" * * sender: "amq.topic/news", will automatically set "news" as the subject for * messages sent on this link, unless the user explicitly overrides * the subject. * * @name Policy#defaultSubjects * @property {boolean} */ defaultSubjects: true, /** * Options related to the reconnect behavior of the client. If this value is `null` reconnect * is effectively disabled * * @name Policy#reconnect * @type {Object|null} * @property {number|null} [retries] How many times to attempt reconnection * @property {string} [strategy='fibonacci'] The algorithm used for backoff. Can be `fibonacci` or `exponential` * @property {boolean} [forever] Whether or not to attempt reconnection forever */ reconnect: { retries: 10, strategy: 'fibonacci', // || 'exponential' forever: true }, /** * @name Policy#connect * @type {object} * @property {object} options Options passed into the open performative on initial connection * @property {string|function} options.containerId The id of the source container * @property {string} options.hostname The name of the target host * @property {number} options.maxFrameSize The largest frame size that the sending peer is able to accept on this connection * @property {number} options.channelMax The channel-max value is the highest channel number that can be used on the connection * @property {number} options.idleTimeout The idle timeout required by the sender * @property {array<string>|null} options.outgoingLocales A list of the locales that the peer supports for sending informational text * @property {array<string>|null} options.incomingLocales A list of locales that the sending peer permits for incoming informational text * @property {array<string>|null} options.offeredCapabilities A list of extension capabilities the peer may use if the sender offers them * @property {array|null} options.desiredCapabilities The desired-capability list defines which extension capabilities the sender may use if the receiver offers them * @property {object|null} options.properties The properties map contains a set of fields intended to indicate information about the connection and its container * @property {object} sslOptions Options used to initiate a TLS/SSL connection, with the exception of the following options all options in this object are passed directly to node's [tls.connect](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback) method. * @property {string|null} sslOptions.keyFile Path to the file containing the private key for the client * @property {string|null} sslOptions.certFile Path to the file containing the certificate key for the client * @property {string|null} sslOptions.caFile Path to the file containing the trusted cert for the client * @property {boolean} sslOptions.rejectUnauthorized * @property {string|null} saslMechanism Allows the sasl mechanism to be overriden by policy */ connect: { options: { containerId: containerName(), hostname: 'localhost', maxFrameSize: constants.defaultMaxFrameSize, channelMax: constants.defaultChannelMax, idleTimeout: constants.defaultIdleTimeout, outgoingLocales: constants.defaultOutgoingLocales, incomingLocales: constants.defaultIncomingLocales, offeredCapabilities: null, desiredCapabilities: null, properties: {}, }, sslOptions: { keyFile: null, certFile: null, caFile: null, rejectUnauthorized: false }, saslMechanism: null }, /** * @name Policy#session * @type {object} * @property {object} options Options passed into the `begin` performative on session start * @property {number} options.nextOutgoingId The transfer-id to assign to the next transfer frame * @property {number} options.incomingWindow The maximum number of incoming transfer frames that the endpoint can currently receive * @property {number} options.outgoingWindow The maximum number of outgoing transfer frames that the endpoint can currently send * @property {function} window A function used to calculate how/when the flow control window should change * @property {number} windowQuantum Quantum used in predefined window policies * @property {boolean} enableSessionFlowControl Whether or not session flow control should be performed at all * @property {object|null} reestablish=null Whether the session should attempt to reestablish when ended by the broker */ session: { options: { nextOutgoingId: constants.session.defaultOutgoingId, incomingWindow: constants.session.defaultIncomingWindow, outgoingWindow: constants.session.defaultOutgoingWindow }, window: putils.WindowPolicies.RefreshAtHalf, windowQuantum: constants.session.defaultIncomingWindow, enableSessionFlowControl: true, reestablish: null }, /** * @name Policy#senderLink * @type {object} * @property {object} attach Options passed into the `attach` performative on link attachment * @property {string|function} attach.name This name uniquely identifies the link from the container of the source to the container of the target node * @property {string|boolean} attach.role The role being played by the peer * @property {string|number} attach.sndSettleMode The delivery settlement policy for the sender * @property {number} attach.maxMessageSize The maximum message size supported by the link endpoint * @property {number} attach.initialDeliveryCount This must not be null if role is sender, and it is ignored if the role is receiver. * @property {string} callback Determines when a send should call its callback ('settle', 'sent', 'none') * @property {function|null} encoder=null The optional encoder used for all outgoing sends * @property {boolean|null} reattach=null Whether the link should attempt reattach on detach */ senderLink: { attach: { name: linkName('sender'), role: constants.linkRole.sender, sndSettleMode: constants.senderSettleMode.mixed, maxMessageSize: 0, initialDeliveryCount: 1 }, callback: putils.SenderCallbackPolicies.OnSettle, encoder: null, reattach: null }, /** * @name Policy#receiverLink * @type {object} * @property {object} attach Options passed into the `attach` performative on link attachment * @property {string|function} attach.name This name uniquely identifies the link from the container of the source to the container of the target node * @property {boolean} attach.role The role being played by the peer * @property {number|string} attach.rcvSettleMode The delivery settlement policy for the receiver * @property {number} attach.maxMessageSize The maximum message size supported by the link endpoint * @property {number} attach.initialDeliveryCount This must not be null if role is sender, and it is ignored if the role is receiver. * @property {function} credit A function that determines when (if ever) to refresh the receiver link's credit * @property {number} creditQuantum Quantum used in pre-defined credit policy functions * @property {function|null} decoder=null The optional decoder used for all incoming data * @property {boolean|null} reattach=null Whether the link should attempt reattach on detach */ receiverLink: { attach: { name: linkName('receiver'), role: constants.linkRole.receiver, rcvSettleMode: constants.receiverSettleMode.autoSettle, maxMessageSize: 10000, // Arbitrary choice initialDeliveryCount: 1 }, credit: putils.CreditPolicies.RefreshAtHalf, creditQuantum: 100, decoder: null, reattach: null }, }); putils.fixDeprecatedLinkOptions(this.senderLink); putils.fixDeprecatedLinkOptions(this.receiverLink); return this; }
[ "function", "Policy", "(", "overrides", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Policy", ")", ")", "return", "new", "Policy", "(", "overrides", ")", ";", "u", ".", "defaults", "(", "this", ",", "overrides", ",", "{", "defaultSubjects", ":", "true", ",", "reconnect", ":", "{", "retries", ":", "10", ",", "strategy", ":", "'fibonacci'", ",", "forever", ":", "true", "}", ",", "connect", ":", "{", "options", ":", "{", "containerId", ":", "containerName", "(", ")", ",", "hostname", ":", "'localhost'", ",", "maxFrameSize", ":", "constants", ".", "defaultMaxFrameSize", ",", "channelMax", ":", "constants", ".", "defaultChannelMax", ",", "idleTimeout", ":", "constants", ".", "defaultIdleTimeout", ",", "outgoingLocales", ":", "constants", ".", "defaultOutgoingLocales", ",", "incomingLocales", ":", "constants", ".", "defaultIncomingLocales", ",", "offeredCapabilities", ":", "null", ",", "desiredCapabilities", ":", "null", ",", "properties", ":", "{", "}", ",", "}", ",", "sslOptions", ":", "{", "keyFile", ":", "null", ",", "certFile", ":", "null", ",", "caFile", ":", "null", ",", "rejectUnauthorized", ":", "false", "}", ",", "saslMechanism", ":", "null", "}", ",", "session", ":", "{", "options", ":", "{", "nextOutgoingId", ":", "constants", ".", "session", ".", "defaultOutgoingId", ",", "incomingWindow", ":", "constants", ".", "session", ".", "defaultIncomingWindow", ",", "outgoingWindow", ":", "constants", ".", "session", ".", "defaultOutgoingWindow", "}", ",", "window", ":", "putils", ".", "WindowPolicies", ".", "RefreshAtHalf", ",", "windowQuantum", ":", "constants", ".", "session", ".", "defaultIncomingWindow", ",", "enableSessionFlowControl", ":", "true", ",", "reestablish", ":", "null", "}", ",", "senderLink", ":", "{", "attach", ":", "{", "name", ":", "linkName", "(", "'sender'", ")", ",", "role", ":", "constants", ".", "linkRole", ".", "sender", ",", "sndSettleMode", ":", "constants", ".", "senderSettleMode", ".", "mixed", ",", "maxMessageSize", ":", "0", ",", "initialDeliveryCount", ":", "1", "}", ",", "callback", ":", "putils", ".", "SenderCallbackPolicies", ".", "OnSettle", ",", "encoder", ":", "null", ",", "reattach", ":", "null", "}", ",", "receiverLink", ":", "{", "attach", ":", "{", "name", ":", "linkName", "(", "'receiver'", ")", ",", "role", ":", "constants", ".", "linkRole", ".", "receiver", ",", "rcvSettleMode", ":", "constants", ".", "receiverSettleMode", ".", "autoSettle", ",", "maxMessageSize", ":", "10000", ",", "initialDeliveryCount", ":", "1", "}", ",", "credit", ":", "putils", ".", "CreditPolicies", ".", "RefreshAtHalf", ",", "creditQuantum", ":", "100", ",", "decoder", ":", "null", ",", "reattach", ":", "null", "}", ",", "}", ")", ";", "putils", ".", "fixDeprecatedLinkOptions", "(", "this", ".", "senderLink", ")", ";", "putils", ".", "fixDeprecatedLinkOptions", "(", "this", ".", "receiverLink", ")", ";", "return", "this", ";", "}" ]
The default policy for amqp10 clients @class @param {object} overrides override values for the default policy
[ "The", "default", "policy", "for", "amqp10", "clients" ]
f5c2aa570830a8dd454e89ed3f4222fc7953fcf7
https://github.com/noodlefrenzy/node-amqp10/blob/f5c2aa570830a8dd454e89ed3f4222fc7953fcf7/lib/policies/policy.js#L25-L187
train
imonology/scalra
modules/reporting.js
function (onDone) { // store what to do after connected // NOTE: may be called repeatedly (if initial attempts fail or disconnect happens) if (typeof onDone === 'function') l_onConnect = onDone; if (l_ip_port === undefined) { LOG.warn('not init (or already disposed), cannot connect to server'); return; } if (l_connector === undefined) l_connector = new SR.Connector(l_config); // establish connection LOG.warn('connecting to: ', l_name); LOG.warn(l_ip_port, l_name); l_connector.connect(l_ip_port, function (err, socket) { if (err) { // try-again later LOG.warn('connect failed, try to re-connect in: ' + l_timeoutConnectRetry + 'ms', l_name); setTimeout(l_connect, l_timeoutConnectRetry); return; } LOG.warn('connection to: ' + socket.host + ':' + socket.port + ' established', l_name); UTIL.safeCall(l_onConnect); }); }
javascript
function (onDone) { // store what to do after connected // NOTE: may be called repeatedly (if initial attempts fail or disconnect happens) if (typeof onDone === 'function') l_onConnect = onDone; if (l_ip_port === undefined) { LOG.warn('not init (or already disposed), cannot connect to server'); return; } if (l_connector === undefined) l_connector = new SR.Connector(l_config); // establish connection LOG.warn('connecting to: ', l_name); LOG.warn(l_ip_port, l_name); l_connector.connect(l_ip_port, function (err, socket) { if (err) { // try-again later LOG.warn('connect failed, try to re-connect in: ' + l_timeoutConnectRetry + 'ms', l_name); setTimeout(l_connect, l_timeoutConnectRetry); return; } LOG.warn('connection to: ' + socket.host + ':' + socket.port + ' established', l_name); UTIL.safeCall(l_onConnect); }); }
[ "function", "(", "onDone", ")", "{", "if", "(", "typeof", "onDone", "===", "'function'", ")", "l_onConnect", "=", "onDone", ";", "if", "(", "l_ip_port", "===", "undefined", ")", "{", "LOG", ".", "warn", "(", "'not init (or already disposed), cannot connect to server'", ")", ";", "return", ";", "}", "if", "(", "l_connector", "===", "undefined", ")", "l_connector", "=", "new", "SR", ".", "Connector", "(", "l_config", ")", ";", "LOG", ".", "warn", "(", "'connecting to: '", ",", "l_name", ")", ";", "LOG", ".", "warn", "(", "l_ip_port", ",", "l_name", ")", ";", "l_connector", ".", "connect", "(", "l_ip_port", ",", "function", "(", "err", ",", "socket", ")", "{", "if", "(", "err", ")", "{", "LOG", ".", "warn", "(", "'connect failed, try to re-connect in: '", "+", "l_timeoutConnectRetry", "+", "'ms'", ",", "l_name", ")", ";", "setTimeout", "(", "l_connect", ",", "l_timeoutConnectRetry", ")", ";", "return", ";", "}", "LOG", ".", "warn", "(", "'connection to: '", "+", "socket", ".", "host", "+", "':'", "+", "socket", ".", "port", "+", "' established'", ",", "l_name", ")", ";", "UTIL", ".", "safeCall", "(", "l_onConnect", ")", ";", "}", ")", ";", "}" ]
connect to remote server
[ "connect", "to", "remote", "server" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/modules/reporting.js#L278-L309
train
imonology/scalra
handlers/system.js
function (latest_log) { if (latest_log !== null && latest_log.type !== "SYSTEM_DOWN") { LOG.warn("server crashed last time", 'handlers.system'); LOG.event("SYSTEM_CRASHED", SR.Settings.SERVER_INFO); } LOG.event("SYSTEM_UP", SR.Settings.SERVER_INFO); }
javascript
function (latest_log) { if (latest_log !== null && latest_log.type !== "SYSTEM_DOWN") { LOG.warn("server crashed last time", 'handlers.system'); LOG.event("SYSTEM_CRASHED", SR.Settings.SERVER_INFO); } LOG.event("SYSTEM_UP", SR.Settings.SERVER_INFO); }
[ "function", "(", "latest_log", ")", "{", "if", "(", "latest_log", "!==", "null", "&&", "latest_log", ".", "type", "!==", "\"SYSTEM_DOWN\"", ")", "{", "LOG", ".", "warn", "(", "\"server crashed last time\"", ",", "'handlers.system'", ")", ";", "LOG", ".", "event", "(", "\"SYSTEM_CRASHED\"", ",", "SR", ".", "Settings", ".", "SERVER_INFO", ")", ";", "}", "LOG", ".", "event", "(", "\"SYSTEM_UP\"", ",", "SR", ".", "Settings", ".", "SERVER_INFO", ")", ";", "}" ]
perform event log
[ "perform", "event", "log" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/handlers/system.js#L248-L255
train
imonology/scalra
extension/socketio.js
function () { if (queue.length > 0) { if (queue.length % 500 === 0) LOG.warn('socketio queue: ' + queue.length); var item = queue.shift(); socket.busy = true; socket.emit('SRR', item); } }
javascript
function () { if (queue.length > 0) { if (queue.length % 500 === 0) LOG.warn('socketio queue: ' + queue.length); var item = queue.shift(); socket.busy = true; socket.emit('SRR', item); } }
[ "function", "(", ")", "{", "if", "(", "queue", ".", "length", ">", "0", ")", "{", "if", "(", "queue", ".", "length", "%", "500", "===", "0", ")", "LOG", ".", "warn", "(", "'socketio queue: '", "+", "queue", ".", "length", ")", ";", "var", "item", "=", "queue", ".", "shift", "(", ")", ";", "socket", ".", "busy", "=", "true", ";", "socket", ".", "emit", "(", "'SRR'", ",", "item", ")", ";", "}", "}" ]
check if message queue has something to send
[ "check", "if", "message", "queue", "has", "something", "to", "send" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/socketio.js#L132-L141
train
imonology/scalra
core/log_manager.js
function () { SR.fs.close(l_logs[log_id].fd, function () { console.log(l_name + '::l_closeLog::' + SR.Tags.YELLOW + 'LogID=' + log_id + ' closed.' + SR.Tags.ERREND); delete l_logs[log_id]; onDone(log_id); } ); }
javascript
function () { SR.fs.close(l_logs[log_id].fd, function () { console.log(l_name + '::l_closeLog::' + SR.Tags.YELLOW + 'LogID=' + log_id + ' closed.' + SR.Tags.ERREND); delete l_logs[log_id]; onDone(log_id); } ); }
[ "function", "(", ")", "{", "SR", ".", "fs", ".", "close", "(", "l_logs", "[", "log_id", "]", ".", "fd", ",", "function", "(", ")", "{", "console", ".", "log", "(", "l_name", "+", "'::l_closeLog::'", "+", "SR", ".", "Tags", ".", "YELLOW", "+", "'LogID='", "+", "log_id", "+", "' closed.'", "+", "SR", ".", "Tags", ".", "ERREND", ")", ";", "delete", "l_logs", "[", "log_id", "]", ";", "onDone", "(", "log_id", ")", ";", "}", ")", ";", "}" ]
perform actual file close
[ "perform", "actual", "file", "close" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/log_manager.js#L243-L252
train
imonology/scalra
extension/location.js
function (appID, locationID) { // check if location exists if (l_locations.hasOwnProperty(locationID) === false) { LOG.error('locationID: ' + locationID + ' does not exist', 'addApp'); return; } // check if already exists, ignore action if already exists if (l_apps.hasOwnProperty(appID) === true) { LOG.error('appID: ' + appID + ' already exists', 'addApp'); return; } // insert new app record for this location l_apps[appID] = { locationID: locationID, users: {} } // build mapping from location to app // TODO: (needed? or can simplfiy?) l_locations[locationID].apps[appID] = l_apps[appID]; }
javascript
function (appID, locationID) { // check if location exists if (l_locations.hasOwnProperty(locationID) === false) { LOG.error('locationID: ' + locationID + ' does not exist', 'addApp'); return; } // check if already exists, ignore action if already exists if (l_apps.hasOwnProperty(appID) === true) { LOG.error('appID: ' + appID + ' already exists', 'addApp'); return; } // insert new app record for this location l_apps[appID] = { locationID: locationID, users: {} } // build mapping from location to app // TODO: (needed? or can simplfiy?) l_locations[locationID].apps[appID] = l_apps[appID]; }
[ "function", "(", "appID", ",", "locationID", ")", "{", "if", "(", "l_locations", ".", "hasOwnProperty", "(", "locationID", ")", "===", "false", ")", "{", "LOG", ".", "error", "(", "'locationID: '", "+", "locationID", "+", "' does not exist'", ",", "'addApp'", ")", ";", "return", ";", "}", "if", "(", "l_apps", ".", "hasOwnProperty", "(", "appID", ")", "===", "true", ")", "{", "LOG", ".", "error", "(", "'appID: '", "+", "appID", "+", "' already exists'", ",", "'addApp'", ")", ";", "return", ";", "}", "l_apps", "[", "appID", "]", "=", "{", "locationID", ":", "locationID", ",", "users", ":", "{", "}", "}", "l_locations", "[", "locationID", "]", ".", "apps", "[", "appID", "]", "=", "l_apps", "[", "appID", "]", ";", "}" ]
add a new app
[ "add", "a", "new", "app" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/location.js#L113-L136
train
imonology/scalra
modules/express.js
function (upload) { if (!upload || !upload.path || !upload.name || !upload.size) { LOG.error('upload object incomplete:', l_name); return; } // record basic file info var arr = upload.path.split('/'); var upload_name = arr[arr.length-1]; var filename = (preserve_name ? upload.name : upload_name); LOG.warn("The file " + upload.name + " was uploaded as: " + filename + ". size: " + upload.size, l_name); uploaded.push({name: filename, size: upload.size, type: upload.type}); // check if we might need to re-name // default is to rename (preserve upload file names) if (preserve_name === false) { return; } var new_name = SR.path.resolve(form.uploadDir, upload.name); SR.fs.rename(upload.path, new_name, function (err) { if (err) { return LOG.error('rename fail: ' + new_name, l_name); } LOG.warn("File " + upload_name + " renamed as: " + upload.name + " . size: " + upload.size, l_name); }); }
javascript
function (upload) { if (!upload || !upload.path || !upload.name || !upload.size) { LOG.error('upload object incomplete:', l_name); return; } // record basic file info var arr = upload.path.split('/'); var upload_name = arr[arr.length-1]; var filename = (preserve_name ? upload.name : upload_name); LOG.warn("The file " + upload.name + " was uploaded as: " + filename + ". size: " + upload.size, l_name); uploaded.push({name: filename, size: upload.size, type: upload.type}); // check if we might need to re-name // default is to rename (preserve upload file names) if (preserve_name === false) { return; } var new_name = SR.path.resolve(form.uploadDir, upload.name); SR.fs.rename(upload.path, new_name, function (err) { if (err) { return LOG.error('rename fail: ' + new_name, l_name); } LOG.warn("File " + upload_name + " renamed as: " + upload.name + " . size: " + upload.size, l_name); }); }
[ "function", "(", "upload", ")", "{", "if", "(", "!", "upload", "||", "!", "upload", ".", "path", "||", "!", "upload", ".", "name", "||", "!", "upload", ".", "size", ")", "{", "LOG", ".", "error", "(", "'upload object incomplete:'", ",", "l_name", ")", ";", "return", ";", "}", "var", "arr", "=", "upload", ".", "path", ".", "split", "(", "'/'", ")", ";", "var", "upload_name", "=", "arr", "[", "arr", ".", "length", "-", "1", "]", ";", "var", "filename", "=", "(", "preserve_name", "?", "upload", ".", "name", ":", "upload_name", ")", ";", "LOG", ".", "warn", "(", "\"The file \"", "+", "upload", ".", "name", "+", "\" was uploaded as: \"", "+", "filename", "+", "\". size: \"", "+", "upload", ".", "size", ",", "l_name", ")", ";", "uploaded", ".", "push", "(", "{", "name", ":", "filename", ",", "size", ":", "upload", ".", "size", ",", "type", ":", "upload", ".", "type", "}", ")", ";", "if", "(", "preserve_name", "===", "false", ")", "{", "return", ";", "}", "var", "new_name", "=", "SR", ".", "path", ".", "resolve", "(", "form", ".", "uploadDir", ",", "upload", ".", "name", ")", ";", "SR", ".", "fs", ".", "rename", "(", "upload", ".", "path", ",", "new_name", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "LOG", ".", "error", "(", "'rename fail: '", "+", "new_name", ",", "l_name", ")", ";", "}", "LOG", ".", "warn", "(", "\"File \"", "+", "upload_name", "+", "\" renamed as: \"", "+", "upload", ".", "name", "+", "\" . size: \"", "+", "upload", ".", "size", ",", "l_name", ")", ";", "}", ")", ";", "}" ]
modify uploaded file to have original filename
[ "modify", "uploaded", "file", "to", "have", "original", "filename" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/modules/express.js#L181-L208
train
imonology/scalra
core/execute.js
function (id) { LOG.warn('server started: ' + server_type, l_name); // check if we should notify start server request for (var i=0; i < l_pendingStart.length; i++) { var task = l_pendingStart[i]; if (task.server_type !== server_type) { continue; } LOG.warn('pending type matched: ' + task.server_type, l_name); // record server id, check for return task.servers.push(id); task.curr++; // store this process id if (l_started.hasOwnProperty(server_type) === false) l_started[server_type] = []; // NOTE: we currently do not maintain this id, should we? l_started[server_type].push(id); // check if all servers of a particular type are started if (task.curr === task.total) { UTIL.safeCall(task.onDone, null, task.servers); // remove this item until app servers have also reported back l_pendingStart.splice(i, 1); } break; } // delete log l_deleteStartedServer({ owner: args.owner, project: args.project, name: args.name }); // log started server l_getServerInfo({ owner: args.owner, project: args.project, name: args.name, size: args.size }, 1); }
javascript
function (id) { LOG.warn('server started: ' + server_type, l_name); // check if we should notify start server request for (var i=0; i < l_pendingStart.length; i++) { var task = l_pendingStart[i]; if (task.server_type !== server_type) { continue; } LOG.warn('pending type matched: ' + task.server_type, l_name); // record server id, check for return task.servers.push(id); task.curr++; // store this process id if (l_started.hasOwnProperty(server_type) === false) l_started[server_type] = []; // NOTE: we currently do not maintain this id, should we? l_started[server_type].push(id); // check if all servers of a particular type are started if (task.curr === task.total) { UTIL.safeCall(task.onDone, null, task.servers); // remove this item until app servers have also reported back l_pendingStart.splice(i, 1); } break; } // delete log l_deleteStartedServer({ owner: args.owner, project: args.project, name: args.name }); // log started server l_getServerInfo({ owner: args.owner, project: args.project, name: args.name, size: args.size }, 1); }
[ "function", "(", "id", ")", "{", "LOG", ".", "warn", "(", "'server started: '", "+", "server_type", ",", "l_name", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "l_pendingStart", ".", "length", ";", "i", "++", ")", "{", "var", "task", "=", "l_pendingStart", "[", "i", "]", ";", "if", "(", "task", ".", "server_type", "!==", "server_type", ")", "{", "continue", ";", "}", "LOG", ".", "warn", "(", "'pending type matched: '", "+", "task", ".", "server_type", ",", "l_name", ")", ";", "task", ".", "servers", ".", "push", "(", "id", ")", ";", "task", ".", "curr", "++", ";", "if", "(", "l_started", ".", "hasOwnProperty", "(", "server_type", ")", "===", "false", ")", "l_started", "[", "server_type", "]", "=", "[", "]", ";", "l_started", "[", "server_type", "]", ".", "push", "(", "id", ")", ";", "if", "(", "task", ".", "curr", "===", "task", ".", "total", ")", "{", "UTIL", ".", "safeCall", "(", "task", ".", "onDone", ",", "null", ",", "task", ".", "servers", ")", ";", "l_pendingStart", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "break", ";", "}", "l_deleteStartedServer", "(", "{", "owner", ":", "args", ".", "owner", ",", "project", ":", "args", ".", "project", ",", "name", ":", "args", ".", "name", "}", ")", ";", "l_getServerInfo", "(", "{", "owner", ":", "args", ".", "owner", ",", "project", ":", "args", ".", "project", ",", "name", ":", "args", ".", "name", ",", "size", ":", "args", ".", "size", "}", ",", "1", ")", ";", "}" ]
notify if a server process has started
[ "notify", "if", "a", "server", "process", "has", "started" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/execute.js#L107-L157
train
imonology/scalra
core/execute.js
function (exec_path, onExec) { var onFound = function () { // if file found, execute directly // store starting path args.exec_path = exec_path; LOG.warn('starting ' + size + ' [' + server_type + '] servers', l_name); // store an entry for the callback when all servers are started as requested // TODO: if it takes too long to start all app servers, then force return in some interval l_pendingStart.push({ onDone: onDone, total: size, curr: 0, server_type: server_type, servers: [] }); start_server(); } var file_path = SR.path.join(exec_path, args.name, 'frontier.js'); LOG.warn('validate file_path: ' + file_path, l_name); // verify frontier file exists, if not then we try package.json SR.fs.stat(file_path, function (err, stats) { // file not found if (err) { file_path = SR.path.join(exec_path, 'package.json'); // remove server name from parameter args.name = ''; SR.fs.stat(file_path, function (err, stats) { if (err) { return onExec('cannot find entry file'); } onFound(); }); } onFound(); }); }
javascript
function (exec_path, onExec) { var onFound = function () { // if file found, execute directly // store starting path args.exec_path = exec_path; LOG.warn('starting ' + size + ' [' + server_type + '] servers', l_name); // store an entry for the callback when all servers are started as requested // TODO: if it takes too long to start all app servers, then force return in some interval l_pendingStart.push({ onDone: onDone, total: size, curr: 0, server_type: server_type, servers: [] }); start_server(); } var file_path = SR.path.join(exec_path, args.name, 'frontier.js'); LOG.warn('validate file_path: ' + file_path, l_name); // verify frontier file exists, if not then we try package.json SR.fs.stat(file_path, function (err, stats) { // file not found if (err) { file_path = SR.path.join(exec_path, 'package.json'); // remove server name from parameter args.name = ''; SR.fs.stat(file_path, function (err, stats) { if (err) { return onExec('cannot find entry file'); } onFound(); }); } onFound(); }); }
[ "function", "(", "exec_path", ",", "onExec", ")", "{", "var", "onFound", "=", "function", "(", ")", "{", "args", ".", "exec_path", "=", "exec_path", ";", "LOG", ".", "warn", "(", "'starting '", "+", "size", "+", "' ['", "+", "server_type", "+", "'] servers'", ",", "l_name", ")", ";", "l_pendingStart", ".", "push", "(", "{", "onDone", ":", "onDone", ",", "total", ":", "size", ",", "curr", ":", "0", ",", "server_type", ":", "server_type", ",", "servers", ":", "[", "]", "}", ")", ";", "start_server", "(", ")", ";", "}", "var", "file_path", "=", "SR", ".", "path", ".", "join", "(", "exec_path", ",", "args", ".", "name", ",", "'frontier.js'", ")", ";", "LOG", ".", "warn", "(", "'validate file_path: '", "+", "file_path", ",", "l_name", ")", ";", "SR", ".", "fs", ".", "stat", "(", "file_path", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "{", "file_path", "=", "SR", ".", "path", ".", "join", "(", "exec_path", ",", "'package.json'", ")", ";", "args", ".", "name", "=", "''", ";", "SR", ".", "fs", ".", "stat", "(", "file_path", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "{", "return", "onExec", "(", "'cannot find entry file'", ")", ";", "}", "onFound", "(", ")", ";", "}", ")", ";", "}", "onFound", "(", ")", ";", "}", ")", ";", "}" ]
try to execute on a given path
[ "try", "to", "execute", "on", "a", "given", "path" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/execute.js#L175-L220
train
particle-iot/particle-commands
src/cmd/api.js
convertApiError
function convertApiError(err) { if (err.error && err.error.response && err.error.response.text) { const obj = JSON.parse(err.error.response.text); if (obj.errors && obj.errors.length) { err = { message: obj.errors[0].message, error:err.error }; } } return err; }
javascript
function convertApiError(err) { if (err.error && err.error.response && err.error.response.text) { const obj = JSON.parse(err.error.response.text); if (obj.errors && obj.errors.length) { err = { message: obj.errors[0].message, error:err.error }; } } return err; }
[ "function", "convertApiError", "(", "err", ")", "{", "if", "(", "err", ".", "error", "&&", "err", ".", "error", ".", "response", "&&", "err", ".", "error", ".", "response", ".", "text", ")", "{", "const", "obj", "=", "JSON", ".", "parse", "(", "err", ".", "error", ".", "response", ".", "text", ")", ";", "if", "(", "obj", ".", "errors", "&&", "obj", ".", "errors", ".", "length", ")", "{", "err", "=", "{", "message", ":", "obj", ".", "errors", "[", "0", "]", ".", "message", ",", "error", ":", "err", ".", "error", "}", ";", "}", "}", "return", "err", ";", "}" ]
Converts an error thrown by the API to a simpler object containing a `message` property. @param {object} err The error raised by the API. @returns {object} With message and error properties.
[ "Converts", "an", "error", "thrown", "by", "the", "API", "to", "a", "simpler", "object", "containing", "a", "message", "property", "." ]
012252e0faef5f4ee21aa3b36c58eace7296a633
https://github.com/particle-iot/particle-commands/blob/012252e0faef5f4ee21aa3b36c58eace7296a633/src/cmd/api.js#L9-L17
train
imonology/scalra
core/comm.js
function (area, layer) { // check if layer exists if (l_layers.hasOwnProperty(layer) === false) return []; // get all current subscriptions at this layer var subs = l_layers[layer]; // prepare list of connection of subscribers matching / covering the area var connections = []; // check each subscription to see if it overlaps with the given area for (var id in subs) { var subscription = subs[id]; // check for overlaps (distance between the two centers is less than sum of radii) if (l_dist(subscription, para) <= (subscription.r + para.r)) connections.push(subscription.conn); } return connections; }
javascript
function (area, layer) { // check if layer exists if (l_layers.hasOwnProperty(layer) === false) return []; // get all current subscriptions at this layer var subs = l_layers[layer]; // prepare list of connection of subscribers matching / covering the area var connections = []; // check each subscription to see if it overlaps with the given area for (var id in subs) { var subscription = subs[id]; // check for overlaps (distance between the two centers is less than sum of radii) if (l_dist(subscription, para) <= (subscription.r + para.r)) connections.push(subscription.conn); } return connections; }
[ "function", "(", "area", ",", "layer", ")", "{", "if", "(", "l_layers", ".", "hasOwnProperty", "(", "layer", ")", "===", "false", ")", "return", "[", "]", ";", "var", "subs", "=", "l_layers", "[", "layer", "]", ";", "var", "connections", "=", "[", "]", ";", "for", "(", "var", "id", "in", "subs", ")", "{", "var", "subscription", "=", "subs", "[", "id", "]", ";", "if", "(", "l_dist", "(", "subscription", ",", "para", ")", "<=", "(", "subscription", ".", "r", "+", "para", ".", "r", ")", ")", "connections", ".", "push", "(", "subscription", ".", "conn", ")", ";", "}", "return", "connections", ";", "}" ]
find a list of subscribers covering a given point or area
[ "find", "a", "list", "of", "subscribers", "covering", "a", "given", "point", "or", "area" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/comm.js#L261-L283
train
imonology/scalra
core/event_manager.js
function (event) { // if event is not from socket, no need to queue // TODO: remove connection-specific code from here if (event.conn.type !== 'socket') return true; var socket = event.conn.connector; // if no mechanism to store (such as from a bot), just ignore // TODO: this is not clean if (typeof socket.queuedEvents === 'undefined') socket.queuedEvents = {}; var queue_size = Object.keys(socket.queuedEvents).length; if (queue_size > l_queuedEventsPerSocket) { LOG.warn('queued event size: ' + queue_size + ' limit exceeded (' + l_queuedEventsPerSocket + ')', l_name); // DEBUG purpose (print out events queued) for (var i in socket.queuedEvents) LOG.sys('queuedEvents[' + i + '] =' + UTIL.stringify(socket.queuedEvents[i].data), l_name); return false; } // store event with the ID to socket's eventlist socket.queuedEvents[event.id] = event; return true; }
javascript
function (event) { // if event is not from socket, no need to queue // TODO: remove connection-specific code from here if (event.conn.type !== 'socket') return true; var socket = event.conn.connector; // if no mechanism to store (such as from a bot), just ignore // TODO: this is not clean if (typeof socket.queuedEvents === 'undefined') socket.queuedEvents = {}; var queue_size = Object.keys(socket.queuedEvents).length; if (queue_size > l_queuedEventsPerSocket) { LOG.warn('queued event size: ' + queue_size + ' limit exceeded (' + l_queuedEventsPerSocket + ')', l_name); // DEBUG purpose (print out events queued) for (var i in socket.queuedEvents) LOG.sys('queuedEvents[' + i + '] =' + UTIL.stringify(socket.queuedEvents[i].data), l_name); return false; } // store event with the ID to socket's eventlist socket.queuedEvents[event.id] = event; return true; }
[ "function", "(", "event", ")", "{", "if", "(", "event", ".", "conn", ".", "type", "!==", "'socket'", ")", "return", "true", ";", "var", "socket", "=", "event", ".", "conn", ".", "connector", ";", "if", "(", "typeof", "socket", ".", "queuedEvents", "===", "'undefined'", ")", "socket", ".", "queuedEvents", "=", "{", "}", ";", "var", "queue_size", "=", "Object", ".", "keys", "(", "socket", ".", "queuedEvents", ")", ".", "length", ";", "if", "(", "queue_size", ">", "l_queuedEventsPerSocket", ")", "{", "LOG", ".", "warn", "(", "'queued event size: '", "+", "queue_size", "+", "' limit exceeded ('", "+", "l_queuedEventsPerSocket", "+", "')'", ",", "l_name", ")", ";", "for", "(", "var", "i", "in", "socket", ".", "queuedEvents", ")", "LOG", ".", "sys", "(", "'queuedEvents['", "+", "i", "+", "'] ='", "+", "UTIL", ".", "stringify", "(", "socket", ".", "queuedEvents", "[", "i", "]", ".", "data", ")", ",", "l_name", ")", ";", "return", "false", ";", "}", "socket", ".", "queuedEvents", "[", "event", ".", "id", "]", "=", "event", ";", "return", "true", ";", "}" ]
function to store a event pending to send
[ "function", "to", "store", "a", "event", "pending", "to", "send" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/event_manager.js#L93-L123
train
imonology/scalra
core/event_manager.js
function (event) { // check if connection object exists if (typeof event.conn === 'undefined') { LOG.error('no connection records, cannot respond to request', l_name); return false; } // if no mechanism to store (such as from a bot), just ignore // TODO: cleaner approach? if (event.conn.type !== 'socket' || event.conn.connector.queuedEvents === undefined) { return true; } var socket = event.conn.connector; // check if id exist if (socket.queuedEvents.hasOwnProperty(event.id) === false) { LOG.error('event not found. id = ' + event.id, l_name); LOG.stack(); return false; } // remove current event from the socket's event queues delete socket.queuedEvents[event.id]; return true; }
javascript
function (event) { // check if connection object exists if (typeof event.conn === 'undefined') { LOG.error('no connection records, cannot respond to request', l_name); return false; } // if no mechanism to store (such as from a bot), just ignore // TODO: cleaner approach? if (event.conn.type !== 'socket' || event.conn.connector.queuedEvents === undefined) { return true; } var socket = event.conn.connector; // check if id exist if (socket.queuedEvents.hasOwnProperty(event.id) === false) { LOG.error('event not found. id = ' + event.id, l_name); LOG.stack(); return false; } // remove current event from the socket's event queues delete socket.queuedEvents[event.id]; return true; }
[ "function", "(", "event", ")", "{", "if", "(", "typeof", "event", ".", "conn", "===", "'undefined'", ")", "{", "LOG", ".", "error", "(", "'no connection records, cannot respond to request'", ",", "l_name", ")", ";", "return", "false", ";", "}", "if", "(", "event", ".", "conn", ".", "type", "!==", "'socket'", "||", "event", ".", "conn", ".", "connector", ".", "queuedEvents", "===", "undefined", ")", "{", "return", "true", ";", "}", "var", "socket", "=", "event", ".", "conn", ".", "connector", ";", "if", "(", "socket", ".", "queuedEvents", ".", "hasOwnProperty", "(", "event", ".", "id", ")", "===", "false", ")", "{", "LOG", ".", "error", "(", "'event not found. id = '", "+", "event", ".", "id", ",", "l_name", ")", ";", "LOG", ".", "stack", "(", ")", ";", "return", "false", ";", "}", "delete", "socket", ".", "queuedEvents", "[", "event", ".", "id", "]", ";", "return", "true", ";", "}" ]
opposite of queueEvent
[ "opposite", "of", "queueEvent" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/event_manager.js#L126-L154
train
imonology/scalra
core/REST/server.js
function (req, res) { LOG.warn('handle_request'); // attach custom res methods (borrowed from express) res = UTIL.mixin(res, response); LOG.sys('HTTP req received, header', 'SR.REST'); LOG.sys(req.headers, 'SR.REST'); var content_type = req.headers['content-type']; // NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) { LOG.warn('parsing form request...', 'SR.REST'); route(req, res); return; } // temp buffer for incoming request var data = ''; var JSONobj = undefined; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { var JSONobj = undefined; try { if (data !== '') { if (content_type.startsWith('application/x-www-form-urlencoded')) { JSONobj = qs.parse(data); } else if (content_type.startsWith('application/json')) { JSONobj = UTIL.convertJSON(decodeURIComponent(data)); } else if (content_type.startsWith('application/sdp')) { JSONobj = data; } else { var msg = 'content type not known: ' + content_type; LOG.warn(msg, 'SR.REST'); SR.REST.reply(res, msg); //res.writeHead(200, {'Content-Type': 'text/plain'}); //res.end(msg); return; } } } catch (e) { var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type; LOG.error(msg, 'SR.REST'); //res.writeHead(200, {'Content-Type': 'text/plain'}); //res.end(msg); SR.REST.reply(res, msg); return; } route(req, res, JSONobj); }) }
javascript
function (req, res) { LOG.warn('handle_request'); // attach custom res methods (borrowed from express) res = UTIL.mixin(res, response); LOG.sys('HTTP req received, header', 'SR.REST'); LOG.sys(req.headers, 'SR.REST'); var content_type = req.headers['content-type']; // NOTE: multi-part needs to be handled first, because req.on('data') will not be able to process correctly if (typeof content_type === 'string' && content_type.startsWith('multipart/form-data; boundary=')) { LOG.warn('parsing form request...', 'SR.REST'); route(req, res); return; } // temp buffer for incoming request var data = ''; var JSONobj = undefined; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { var JSONobj = undefined; try { if (data !== '') { if (content_type.startsWith('application/x-www-form-urlencoded')) { JSONobj = qs.parse(data); } else if (content_type.startsWith('application/json')) { JSONobj = UTIL.convertJSON(decodeURIComponent(data)); } else if (content_type.startsWith('application/sdp')) { JSONobj = data; } else { var msg = 'content type not known: ' + content_type; LOG.warn(msg, 'SR.REST'); SR.REST.reply(res, msg); //res.writeHead(200, {'Content-Type': 'text/plain'}); //res.end(msg); return; } } } catch (e) { var msg = 'JSON parsing error for data: ' + data + '\n content_type: ' + content_type; LOG.error(msg, 'SR.REST'); //res.writeHead(200, {'Content-Type': 'text/plain'}); //res.end(msg); SR.REST.reply(res, msg); return; } route(req, res, JSONobj); }) }
[ "function", "(", "req", ",", "res", ")", "{", "LOG", ".", "warn", "(", "'handle_request'", ")", ";", "res", "=", "UTIL", ".", "mixin", "(", "res", ",", "response", ")", ";", "LOG", ".", "sys", "(", "'HTTP req received, header'", ",", "'SR.REST'", ")", ";", "LOG", ".", "sys", "(", "req", ".", "headers", ",", "'SR.REST'", ")", ";", "var", "content_type", "=", "req", ".", "headers", "[", "'content-type'", "]", ";", "if", "(", "typeof", "content_type", "===", "'string'", "&&", "content_type", ".", "startsWith", "(", "'multipart/form-data; boundary='", ")", ")", "{", "LOG", ".", "warn", "(", "'parsing form request...'", ",", "'SR.REST'", ")", ";", "route", "(", "req", ",", "res", ")", ";", "return", ";", "}", "var", "data", "=", "''", ";", "var", "JSONobj", "=", "undefined", ";", "req", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "data", "+=", "chunk", ";", "}", ")", ";", "req", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "var", "JSONobj", "=", "undefined", ";", "try", "{", "if", "(", "data", "!==", "''", ")", "{", "if", "(", "content_type", ".", "startsWith", "(", "'application/x-www-form-urlencoded'", ")", ")", "{", "JSONobj", "=", "qs", ".", "parse", "(", "data", ")", ";", "}", "else", "if", "(", "content_type", ".", "startsWith", "(", "'application/json'", ")", ")", "{", "JSONobj", "=", "UTIL", ".", "convertJSON", "(", "decodeURIComponent", "(", "data", ")", ")", ";", "}", "else", "if", "(", "content_type", ".", "startsWith", "(", "'application/sdp'", ")", ")", "{", "JSONobj", "=", "data", ";", "}", "else", "{", "var", "msg", "=", "'content type not known: '", "+", "content_type", ";", "LOG", ".", "warn", "(", "msg", ",", "'SR.REST'", ")", ";", "SR", ".", "REST", ".", "reply", "(", "res", ",", "msg", ")", ";", "return", ";", "}", "}", "}", "catch", "(", "e", ")", "{", "var", "msg", "=", "'JSON parsing error for data: '", "+", "data", "+", "'\\n content_type: '", "+", "\\n", ";", "content_type", "LOG", ".", "error", "(", "msg", ",", "'SR.REST'", ")", ";", "SR", ".", "REST", ".", "reply", "(", "res", ",", "msg", ")", ";", "}", "return", ";", "}", ")", "}" ]
main place to receive HTTP-related requests
[ "main", "place", "to", "receive", "HTTP", "-", "related", "requests" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/REST/server.js#L34-L93
train
imonology/scalra
extension/user.js
function (account, data, conn) { //if (l_logins.hasOwnProperty(account) === true) //return false; // check if user's unique data exists if (typeof data.data !== 'object') { LOG.error('data field does not exist, cannot add login data'); return false; } LOG.warn('account: ' + account + ' data:', 'addLogin'); LOG.warn(data); // attach login name to connection // NOTE: we attach connection object to the data stored in memory (not clean?) if (conn) { // NOTE: we use session because this request could come from an HTTP request // that does not have a persistent connectino record in SR.Conn SR.Conn.setSessionName(conn, account); data._conn = conn; } l_logins[account] = data; LOG.warn('user [' + account + '] login success, total count: ' + Object.keys(l_logins).length, 'user'); delete data._conn; //console.log(data); // error check: make sure lastStatus field exists if (data.hasOwnProperty('lastStatus') === false || data.lastStatus === null) data.lastStatus = {loginCount: 0}; data.lastStatus.loginIP = conn.host; data.lastStatus.loginCount = data.lastStatus.loginCount + 1; data.lastStatus.time = conn.time; SR.DB.updateData(SR.Settings.DB_NAME_ACCOUNT, {account: account}, data, function () { }, function () { }); return true; }
javascript
function (account, data, conn) { //if (l_logins.hasOwnProperty(account) === true) //return false; // check if user's unique data exists if (typeof data.data !== 'object') { LOG.error('data field does not exist, cannot add login data'); return false; } LOG.warn('account: ' + account + ' data:', 'addLogin'); LOG.warn(data); // attach login name to connection // NOTE: we attach connection object to the data stored in memory (not clean?) if (conn) { // NOTE: we use session because this request could come from an HTTP request // that does not have a persistent connectino record in SR.Conn SR.Conn.setSessionName(conn, account); data._conn = conn; } l_logins[account] = data; LOG.warn('user [' + account + '] login success, total count: ' + Object.keys(l_logins).length, 'user'); delete data._conn; //console.log(data); // error check: make sure lastStatus field exists if (data.hasOwnProperty('lastStatus') === false || data.lastStatus === null) data.lastStatus = {loginCount: 0}; data.lastStatus.loginIP = conn.host; data.lastStatus.loginCount = data.lastStatus.loginCount + 1; data.lastStatus.time = conn.time; SR.DB.updateData(SR.Settings.DB_NAME_ACCOUNT, {account: account}, data, function () { }, function () { }); return true; }
[ "function", "(", "account", ",", "data", ",", "conn", ")", "{", "if", "(", "typeof", "data", ".", "data", "!==", "'object'", ")", "{", "LOG", ".", "error", "(", "'data field does not exist, cannot add login data'", ")", ";", "return", "false", ";", "}", "LOG", ".", "warn", "(", "'account: '", "+", "account", "+", "' data:'", ",", "'addLogin'", ")", ";", "LOG", ".", "warn", "(", "data", ")", ";", "if", "(", "conn", ")", "{", "SR", ".", "Conn", ".", "setSessionName", "(", "conn", ",", "account", ")", ";", "data", ".", "_conn", "=", "conn", ";", "}", "l_logins", "[", "account", "]", "=", "data", ";", "LOG", ".", "warn", "(", "'user ['", "+", "account", "+", "'] login success, total count: '", "+", "Object", ".", "keys", "(", "l_logins", ")", ".", "length", ",", "'user'", ")", ";", "delete", "data", ".", "_conn", ";", "if", "(", "data", ".", "hasOwnProperty", "(", "'lastStatus'", ")", "===", "false", "||", "data", ".", "lastStatus", "===", "null", ")", "data", ".", "lastStatus", "=", "{", "loginCount", ":", "0", "}", ";", "data", ".", "lastStatus", ".", "loginIP", "=", "conn", ".", "host", ";", "data", ".", "lastStatus", ".", "loginCount", "=", "data", ".", "lastStatus", ".", "loginCount", "+", "1", ";", "data", ".", "lastStatus", ".", "time", "=", "conn", ".", "time", ";", "SR", ".", "DB", ".", "updateData", "(", "SR", ".", "Settings", ".", "DB_NAME_ACCOUNT", ",", "{", "account", ":", "account", "}", ",", "data", ",", "function", "(", ")", "{", "}", ",", "function", "(", ")", "{", "}", ")", ";", "return", "true", ";", "}" ]
store & remove user data to cache
[ "store", "&", "remove", "user", "data", "to", "cache" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/user.js#L88-L132
train
imonology/scalra
extension/user.js
function (error) { if (error) { var err = new Error("set custom data for account [" + account + "] fail"); err.name = "setUser Error"; LOG.error('set custom data for account [' + account + '] fail', 'user'); UTIL.safeCall(onDone, err); } else { LOG.warn('set custom data for account [' + account + '] success', 'user'); UTIL.safeCall(onDone, null); } }
javascript
function (error) { if (error) { var err = new Error("set custom data for account [" + account + "] fail"); err.name = "setUser Error"; LOG.error('set custom data for account [' + account + '] fail', 'user'); UTIL.safeCall(onDone, err); } else { LOG.warn('set custom data for account [' + account + '] success', 'user'); UTIL.safeCall(onDone, null); } }
[ "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "var", "err", "=", "new", "Error", "(", "\"set custom data for account [\"", "+", "account", "+", "\"] fail\"", ")", ";", "err", ".", "name", "=", "\"setUser Error\"", ";", "LOG", ".", "error", "(", "'set custom data for account ['", "+", "account", "+", "'] fail'", ",", "'user'", ")", ";", "UTIL", ".", "safeCall", "(", "onDone", ",", "err", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "'set custom data for account ['", "+", "account", "+", "'] success'", ",", "'user'", ")", ";", "UTIL", ".", "safeCall", "(", "onDone", ",", "null", ")", ";", "}", "}" ]
perform DB write-back
[ "perform", "DB", "write", "-", "back" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/user.js#L526-L538
train
imonology/scalra
extension/user.js
function (uid, token) { // TODO: check if local account already exists, or replace existing one // multiple accounts storable for one local server // NOTE: field name is a variable // ref: http://stackoverflow.com/questions/11133912/how-to-use-a-variable-as-a-field-name-in-mongodb-native-findandmodify var field = 'data.accounts.' + server + '.' + uid; var onUpdated = function (error) { if (error) { var err = new Error("ADD_LOCAL_ACCOUNT_FAIL: " + account); err.name = "addLocal Error"; err.code = 1; UTIL.safeCall(onDone, err); } else { UTIL.safeCall(onDone, null, {code: 0, msg: 'ADD_LOCAL_ACCOUNT_SUCCESS: ' + account}); } }; l_updateUser({account: account}, field, token, onUpdated); }
javascript
function (uid, token) { // TODO: check if local account already exists, or replace existing one // multiple accounts storable for one local server // NOTE: field name is a variable // ref: http://stackoverflow.com/questions/11133912/how-to-use-a-variable-as-a-field-name-in-mongodb-native-findandmodify var field = 'data.accounts.' + server + '.' + uid; var onUpdated = function (error) { if (error) { var err = new Error("ADD_LOCAL_ACCOUNT_FAIL: " + account); err.name = "addLocal Error"; err.code = 1; UTIL.safeCall(onDone, err); } else { UTIL.safeCall(onDone, null, {code: 0, msg: 'ADD_LOCAL_ACCOUNT_SUCCESS: ' + account}); } }; l_updateUser({account: account}, field, token, onUpdated); }
[ "function", "(", "uid", ",", "token", ")", "{", "var", "field", "=", "'data.accounts.'", "+", "server", "+", "'.'", "+", "uid", ";", "var", "onUpdated", "=", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "var", "err", "=", "new", "Error", "(", "\"ADD_LOCAL_ACCOUNT_FAIL: \"", "+", "account", ")", ";", "err", ".", "name", "=", "\"addLocal Error\"", ";", "err", ".", "code", "=", "1", ";", "UTIL", ".", "safeCall", "(", "onDone", ",", "err", ")", ";", "}", "else", "{", "UTIL", ".", "safeCall", "(", "onDone", ",", "null", ",", "{", "code", ":", "0", ",", "msg", ":", "'ADD_LOCAL_ACCOUNT_SUCCESS: '", "+", "account", "}", ")", ";", "}", "}", ";", "l_updateUser", "(", "{", "account", ":", "account", "}", ",", "field", ",", "token", ",", "onUpdated", ")", ";", "}" ]
build callback to store local account if it's verified
[ "build", "callback", "to", "store", "local", "account", "if", "it", "s", "verified" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/user.js#L691-L712
train
imonology/scalra
extension/user.js
function (error) { if (error) { var err = new Error(error.toString()); err.name = "l_createToken Error"; UTIL.safeCall(onDone, err); } else { LOG.warn('pass_token [' + token + '] stored'); UTIL.safeCall(onDone, null, token); } }
javascript
function (error) { if (error) { var err = new Error(error.toString()); err.name = "l_createToken Error"; UTIL.safeCall(onDone, err); } else { LOG.warn('pass_token [' + token + '] stored'); UTIL.safeCall(onDone, null, token); } }
[ "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "var", "err", "=", "new", "Error", "(", "error", ".", "toString", "(", ")", ")", ";", "err", ".", "name", "=", "\"l_createToken Error\"", ";", "UTIL", ".", "safeCall", "(", "onDone", ",", "err", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "'pass_token ['", "+", "token", "+", "'] stored'", ")", ";", "UTIL", ".", "safeCall", "(", "onDone", ",", "null", ",", "token", ")", ";", "}", "}" ]
store token back to DB
[ "store", "token", "back", "to", "DB" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/user.js#L750-L760
train
imonology/scalra
core/handler.js
function (msgtype, event) { // we only forward for non-SR user-defined events at lobby if (SR.Settings.SERVER_INFO.type !== 'lobby' || msgtype.startsWith('SR')) return false; // check if we're lobby and same-name app servers are available var list = SR.AppConn.queryAppServers(); LOG.sys('check forward for: ' + msgtype + ' app server size: ' + Object.keys(list).length, l_name); var minload_id = undefined; var minload = 10000; for (var id in list) { var info = list[id]; if (info.type === 'app' && info.name === SR.Settings.SERVER_INFO.name) { LOG.warn('found forward target [' + id + '] loading: ' + info.usercount, l_name); if (info.usercount < minload) { minload_id = id; minload = info.usercount; } } } // an app server with minimal loading is available, relay the event if (minload_id) { SR.RPC.relayEvent(minload_id, msgtype, event); return true; } // no need to forward, local execution return false; }
javascript
function (msgtype, event) { // we only forward for non-SR user-defined events at lobby if (SR.Settings.SERVER_INFO.type !== 'lobby' || msgtype.startsWith('SR')) return false; // check if we're lobby and same-name app servers are available var list = SR.AppConn.queryAppServers(); LOG.sys('check forward for: ' + msgtype + ' app server size: ' + Object.keys(list).length, l_name); var minload_id = undefined; var minload = 10000; for (var id in list) { var info = list[id]; if (info.type === 'app' && info.name === SR.Settings.SERVER_INFO.name) { LOG.warn('found forward target [' + id + '] loading: ' + info.usercount, l_name); if (info.usercount < minload) { minload_id = id; minload = info.usercount; } } } // an app server with minimal loading is available, relay the event if (minload_id) { SR.RPC.relayEvent(minload_id, msgtype, event); return true; } // no need to forward, local execution return false; }
[ "function", "(", "msgtype", ",", "event", ")", "{", "if", "(", "SR", ".", "Settings", ".", "SERVER_INFO", ".", "type", "!==", "'lobby'", "||", "msgtype", ".", "startsWith", "(", "'SR'", ")", ")", "return", "false", ";", "var", "list", "=", "SR", ".", "AppConn", ".", "queryAppServers", "(", ")", ";", "LOG", ".", "sys", "(", "'check forward for: '", "+", "msgtype", "+", "' app server size: '", "+", "Object", ".", "keys", "(", "list", ")", ".", "length", ",", "l_name", ")", ";", "var", "minload_id", "=", "undefined", ";", "var", "minload", "=", "10000", ";", "for", "(", "var", "id", "in", "list", ")", "{", "var", "info", "=", "list", "[", "id", "]", ";", "if", "(", "info", ".", "type", "===", "'app'", "&&", "info", ".", "name", "===", "SR", ".", "Settings", ".", "SERVER_INFO", ".", "name", ")", "{", "LOG", ".", "warn", "(", "'found forward target ['", "+", "id", "+", "'] loading: '", "+", "info", ".", "usercount", ",", "l_name", ")", ";", "if", "(", "info", ".", "usercount", "<", "minload", ")", "{", "minload_id", "=", "id", ";", "minload", "=", "info", ".", "usercount", ";", "}", "}", "}", "if", "(", "minload_id", ")", "{", "SR", ".", "RPC", ".", "relayEvent", "(", "minload_id", ",", "msgtype", ",", "event", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
check if an event should be forwarded to another app server for execution
[ "check", "if", "an", "event", "should", "be", "forwarded", "to", "another", "app", "server", "for", "execution" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/handler.js#L287-L319
train
imonology/scalra
core/handler.js
function (response_type, event) { LOG.sys('handling event response [' + response_type + ']', l_name); // go over each registered callback function and see which one responds for (var i=0; i < l_responders[response_type].length; i++) { // find the callback with matching client id // call callback and see whether it has been processed if (l_responders[response_type][i].cid === event.cid) { // log incoming message type & IP/port LOG.sys(SR.Tags.RCV + response_type + ' from ' + event.printSource() + SR.Tags.END, l_name); // make callback UTIL.safeCall(l_responders[response_type][i].onResponse, event); // then remove it l_responders[response_type].splice(i, 1); i--; } } }
javascript
function (response_type, event) { LOG.sys('handling event response [' + response_type + ']', l_name); // go over each registered callback function and see which one responds for (var i=0; i < l_responders[response_type].length; i++) { // find the callback with matching client id // call callback and see whether it has been processed if (l_responders[response_type][i].cid === event.cid) { // log incoming message type & IP/port LOG.sys(SR.Tags.RCV + response_type + ' from ' + event.printSource() + SR.Tags.END, l_name); // make callback UTIL.safeCall(l_responders[response_type][i].onResponse, event); // then remove it l_responders[response_type].splice(i, 1); i--; } } }
[ "function", "(", "response_type", ",", "event", ")", "{", "LOG", ".", "sys", "(", "'handling event response ['", "+", "response_type", "+", "']'", ",", "l_name", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "l_responders", "[", "response_type", "]", ".", "length", ";", "i", "++", ")", "{", "if", "(", "l_responders", "[", "response_type", "]", "[", "i", "]", ".", "cid", "===", "event", ".", "cid", ")", "{", "LOG", ".", "sys", "(", "SR", ".", "Tags", ".", "RCV", "+", "response_type", "+", "' from '", "+", "event", ".", "printSource", "(", ")", "+", "SR", ".", "Tags", ".", "END", ",", "l_name", ")", ";", "UTIL", ".", "safeCall", "(", "l_responders", "[", "response_type", "]", "[", "i", "]", ".", "onResponse", ",", "event", ")", ";", "l_responders", "[", "response_type", "]", ".", "splice", "(", "i", ",", "1", ")", ";", "i", "--", ";", "}", "}", "}" ]
notify that a response to a particular event is received
[ "notify", "that", "a", "response", "to", "a", "particular", "event", "is", "received" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/handler.js#L632-L652
train
imonology/scalra
extension/proxy.js
function (e, req, res, host) { LOG.error('proxy error for host: ' + host + '. remove from active proxy list:', 'SR.Proxy'); LOG.error(e, 'SR.Proxy'); // remove proxy info from list delete l_proxies[host]; // notify for proxy failure UTIL.safeCall(onProxyFail, host); // send back to client about the proxy error res.writeHead(502, { 'Content-Type': 'text/plain' }); res.end('PROXY_ERROR: cannot access proxy: ' + host); }
javascript
function (e, req, res, host) { LOG.error('proxy error for host: ' + host + '. remove from active proxy list:', 'SR.Proxy'); LOG.error(e, 'SR.Proxy'); // remove proxy info from list delete l_proxies[host]; // notify for proxy failure UTIL.safeCall(onProxyFail, host); // send back to client about the proxy error res.writeHead(502, { 'Content-Type': 'text/plain' }); res.end('PROXY_ERROR: cannot access proxy: ' + host); }
[ "function", "(", "e", ",", "req", ",", "res", ",", "host", ")", "{", "LOG", ".", "error", "(", "'proxy error for host: '", "+", "host", "+", "'. remove from active proxy list:'", ",", "'SR.Proxy'", ")", ";", "LOG", ".", "error", "(", "e", ",", "'SR.Proxy'", ")", ";", "delete", "l_proxies", "[", "host", "]", ";", "UTIL", ".", "safeCall", "(", "onProxyFail", ",", "host", ")", ";", "res", ".", "writeHead", "(", "502", ",", "{", "'Content-Type'", ":", "'text/plain'", "}", ")", ";", "res", ".", "end", "(", "'PROXY_ERROR: cannot access proxy: '", "+", "host", ")", ";", "}" ]
same error handling for both HTTP or WebSocket proxies
[ "same", "error", "handling", "for", "both", "HTTP", "or", "WebSocket", "proxies" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/proxy.js#L223-L238
train
imonology/scalra
core/job_queue.js
JobQueue
function JobQueue(para) { this.queue = []; this.curr = 0; this.all_passed = true; this.timeout = ((typeof para === 'object' && typeof para.timeout === 'number') ? para.timeout : 0); }
javascript
function JobQueue(para) { this.queue = []; this.curr = 0; this.all_passed = true; this.timeout = ((typeof para === 'object' && typeof para.timeout === 'number') ? para.timeout : 0); }
[ "function", "JobQueue", "(", "para", ")", "{", "this", ".", "queue", "=", "[", "]", ";", "this", ".", "curr", "=", "0", ";", "this", ".", "all_passed", "=", "true", ";", "this", ".", "timeout", "=", "(", "(", "typeof", "para", "===", "'object'", "&&", "typeof", "para", ".", "timeout", "===", "'number'", ")", "?", "para", ".", "timeout", ":", "0", ")", ";", "}" ]
object-based JobQueue functions
[ "object", "-", "based", "JobQueue", "functions" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/job_queue.js#L127-L132
train
imonology/scalra
core/job_queue.js
function () { if (item.done === false) { LOG.error('job timeout! please check if the job calls onDone eventually. ' + (item.name ? '[' + item.name + ']' : ''), l_name); // force this job be done onJobDone(false); } }
javascript
function () { if (item.done === false) { LOG.error('job timeout! please check if the job calls onDone eventually. ' + (item.name ? '[' + item.name + ']' : ''), l_name); // force this job be done onJobDone(false); } }
[ "function", "(", ")", "{", "if", "(", "item", ".", "done", "===", "false", ")", "{", "LOG", ".", "error", "(", "'job timeout! please check if the job calls onDone eventually. '", "+", "(", "item", ".", "name", "?", "'['", "+", "item", ".", "name", "+", "']'", ":", "''", ")", ",", "l_name", ")", ";", "onJobDone", "(", "false", ")", ";", "}", "}" ]
if the job does not finish in time
[ "if", "the", "job", "does", "not", "finish", "in", "time" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/job_queue.js#L195-L202
train
imonology/scalra
entry/handler.js
function (list) { for (var i=0; i < list.length; i++) { for (var j=0; j < l_entries.length; j++) { if (list[i] === l_entries[j]) { l_entries.splice(j, 1); break; } } } }
javascript
function (list) { for (var i=0; i < list.length; i++) { for (var j=0; j < l_entries.length; j++) { if (list[i] === l_entries[j]) { l_entries.splice(j, 1); break; } } } }
[ "function", "(", "list", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "l_entries", ".", "length", ";", "j", "++", ")", "{", "if", "(", "list", "[", "i", "]", "===", "l_entries", "[", "j", "]", ")", "{", "l_entries", ".", "splice", "(", "j", ",", "1", ")", ";", "break", ";", "}", "}", "}", "}" ]
remove entry from list
[ "remove", "entry", "from", "list" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/entry/handler.js#L29-L39
train
imonology/scalra
demo/web/logic.js
getInput
function getInput() { var account = document.getElementById('account').value; var email = (document.getElementById('email') ? document.getElementById('email').value : ''); var password = document.getElementById('password').value; return {account: account, email: email, password: password}; }
javascript
function getInput() { var account = document.getElementById('account').value; var email = (document.getElementById('email') ? document.getElementById('email').value : ''); var password = document.getElementById('password').value; return {account: account, email: email, password: password}; }
[ "function", "getInput", "(", ")", "{", "var", "account", "=", "document", ".", "getElementById", "(", "'account'", ")", ".", "value", ";", "var", "email", "=", "(", "document", ".", "getElementById", "(", "'email'", ")", "?", "document", ".", "getElementById", "(", "'email'", ")", ".", "value", ":", "''", ")", ";", "var", "password", "=", "document", ".", "getElementById", "(", "'password'", ")", ".", "value", ";", "return", "{", "account", ":", "account", ",", "email", ":", "email", ",", "password", ":", "password", "}", ";", "}" ]
retrieve account & password from HTML elements
[ "retrieve", "account", "&", "password", "from", "HTML", "elements" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/demo/web/logic.js#L44-L51
train
imonology/scalra
handlers/login.js
function (err, data) { if (err) { LOG.warn(err.toString()); } else { for (var server in data.accounts) { LOG.warn('local server: ' + server); var user_list = data.accounts[server]; for (var uid in user_list) { var token = user_list[uid]; LOG.warn('local uid: ' + uid + ' token: ' + token); l_send_remote_login(server, uid, token); } } } }
javascript
function (err, data) { if (err) { LOG.warn(err.toString()); } else { for (var server in data.accounts) { LOG.warn('local server: ' + server); var user_list = data.accounts[server]; for (var uid in user_list) { var token = user_list[uid]; LOG.warn('local uid: ' + uid + ' token: ' + token); l_send_remote_login(server, uid, token); } } } }
[ "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "LOG", ".", "warn", "(", "err", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "for", "(", "var", "server", "in", "data", ".", "accounts", ")", "{", "LOG", ".", "warn", "(", "'local server: '", "+", "server", ")", ";", "var", "user_list", "=", "data", ".", "accounts", "[", "server", "]", ";", "for", "(", "var", "uid", "in", "user_list", ")", "{", "var", "token", "=", "user_list", "[", "uid", "]", ";", "LOG", ".", "warn", "(", "'local uid: '", "+", "uid", "+", "' token: '", "+", "token", ")", ";", "l_send_remote_login", "(", "server", ",", "uid", ",", "token", ")", ";", "}", "}", "}", "}" ]
get all local accounts & perform login
[ "get", "all", "local", "accounts", "&", "perform", "login" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/handlers/login.js#L29-L45
train
imonology/scalra
handlers/login.js
function (server, uid, token) { try { // convert uid to number if not already if (typeof uid === 'string') uid = parseInt(uid); } catch (e) { LOG.error('uid cannot be parsed as integer...', 'login.send_remote_login'); return false; } SR.User.loginLocal(server, uid, token, function (result) { // NOTE: if local server is not registered, will return 'undefined' as result if (result) { // NOTE: result has U and P fields LOG.warn('local login result for [' + uid + ']: ' + (result.code === 0)); } else LOG.warn('local login result for [' + uid + ']: remote server not online'); }); return true; }
javascript
function (server, uid, token) { try { // convert uid to number if not already if (typeof uid === 'string') uid = parseInt(uid); } catch (e) { LOG.error('uid cannot be parsed as integer...', 'login.send_remote_login'); return false; } SR.User.loginLocal(server, uid, token, function (result) { // NOTE: if local server is not registered, will return 'undefined' as result if (result) { // NOTE: result has U and P fields LOG.warn('local login result for [' + uid + ']: ' + (result.code === 0)); } else LOG.warn('local login result for [' + uid + ']: remote server not online'); }); return true; }
[ "function", "(", "server", ",", "uid", ",", "token", ")", "{", "try", "{", "if", "(", "typeof", "uid", "===", "'string'", ")", "uid", "=", "parseInt", "(", "uid", ")", ";", "}", "catch", "(", "e", ")", "{", "LOG", ".", "error", "(", "'uid cannot be parsed as integer...'", ",", "'login.send_remote_login'", ")", ";", "return", "false", ";", "}", "SR", ".", "User", ".", "loginLocal", "(", "server", ",", "uid", ",", "token", ",", "function", "(", "result", ")", "{", "if", "(", "result", ")", "{", "LOG", ".", "warn", "(", "'local login result for ['", "+", "uid", "+", "']: '", "+", "(", "result", ".", "code", "===", "0", ")", ")", ";", "}", "else", "LOG", ".", "warn", "(", "'local login result for ['", "+", "uid", "+", "']: remote server not online'", ")", ";", "}", ")", ";", "return", "true", ";", "}" ]
send login info for local server
[ "send", "login", "info", "for", "local", "server" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/handlers/login.js#L50-L73
train
imonology/scalra
handlers/login.js
function (login_id, session, data) { // acknowledge as 'logined' l_loginID[login_id] = data.account; // init session session['_account'] = data.account; // TODO: needs to fix this, should read "groups" from DB session['_groups'] = data.groups; session['_permissions'] = data.permissions; session['lastStatus'] = data.lastStatus; // TODO: centralize handling of logined users? //SR.User.addGroup(user_data.account, ['user', 'admin']); }
javascript
function (login_id, session, data) { // acknowledge as 'logined' l_loginID[login_id] = data.account; // init session session['_account'] = data.account; // TODO: needs to fix this, should read "groups" from DB session['_groups'] = data.groups; session['_permissions'] = data.permissions; session['lastStatus'] = data.lastStatus; // TODO: centralize handling of logined users? //SR.User.addGroup(user_data.account, ['user', 'admin']); }
[ "function", "(", "login_id", ",", "session", ",", "data", ")", "{", "l_loginID", "[", "login_id", "]", "=", "data", ".", "account", ";", "session", "[", "'_account'", "]", "=", "data", ".", "account", ";", "session", "[", "'_groups'", "]", "=", "data", ".", "groups", ";", "session", "[", "'_permissions'", "]", "=", "data", ".", "permissions", ";", "session", "[", "'lastStatus'", "]", "=", "data", ".", "lastStatus", ";", "}" ]
initialize session content based on registered or logined user data
[ "initialize", "session", "content", "based", "on", "registered", "or", "logined", "user", "data" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/handlers/login.js#L193-L208
train
imonology/scalra
handlers/login.js
function (err, result) { // if login is successful, we record the user's account in cache if (err) { LOG.warn(err.toString()); result = {code: err.code, msg: err.message}; } else { if (result.code === 0) { LOG.warn('login success, result: '); LOG.warn(result); var data = { account: user_data.account, groups: result.data.groups, lastStatus: result.data.lastStatus, permissions: [] } l_initSession(event.data.login_id, event.session, data); /* // todo: read permssion from DB //event.session['_permissions'] = result.data.permissions; var xx = []; var onSuccess = function(dat){ //console.log(dat.permission); if (dat === null) { console.log("no permission"); } else { for (var i in dat.permission) { //console.log("pushing: " + dat.permission[i]); xx.push(dat.permission[i]); } } //event.done("get group", {"status": "success", "data": data}); }; var onFail = function(dat){ //event.done("get group", {"status": "failure", "data": data}); }; for (var i in event.session['_groups']) { //console.log("getting: " + event.session['_groups'][i]); SR.DB.getData(groupPermissionDB, {"group": event.session['_groups'][i], part: "group"}, onSuccess, onFail); } */ // TODO: login at once to all local accounts // NOTE: need to query all local login account name & password, then perform individual logins l_login_local_accounts(user_data.account); } } //LOG.warn('event before sending login response:'); //LOG.warn(event); //if (result.data) delete result.data; // return response regardless success or fail event.done('SR_LOGIN_RESPONSE', result); }
javascript
function (err, result) { // if login is successful, we record the user's account in cache if (err) { LOG.warn(err.toString()); result = {code: err.code, msg: err.message}; } else { if (result.code === 0) { LOG.warn('login success, result: '); LOG.warn(result); var data = { account: user_data.account, groups: result.data.groups, lastStatus: result.data.lastStatus, permissions: [] } l_initSession(event.data.login_id, event.session, data); /* // todo: read permssion from DB //event.session['_permissions'] = result.data.permissions; var xx = []; var onSuccess = function(dat){ //console.log(dat.permission); if (dat === null) { console.log("no permission"); } else { for (var i in dat.permission) { //console.log("pushing: " + dat.permission[i]); xx.push(dat.permission[i]); } } //event.done("get group", {"status": "success", "data": data}); }; var onFail = function(dat){ //event.done("get group", {"status": "failure", "data": data}); }; for (var i in event.session['_groups']) { //console.log("getting: " + event.session['_groups'][i]); SR.DB.getData(groupPermissionDB, {"group": event.session['_groups'][i], part: "group"}, onSuccess, onFail); } */ // TODO: login at once to all local accounts // NOTE: need to query all local login account name & password, then perform individual logins l_login_local_accounts(user_data.account); } } //LOG.warn('event before sending login response:'); //LOG.warn(event); //if (result.data) delete result.data; // return response regardless success or fail event.done('SR_LOGIN_RESPONSE', result); }
[ "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "LOG", ".", "warn", "(", "err", ".", "toString", "(", ")", ")", ";", "result", "=", "{", "code", ":", "err", ".", "code", ",", "msg", ":", "err", ".", "message", "}", ";", "}", "else", "{", "if", "(", "result", ".", "code", "===", "0", ")", "{", "LOG", ".", "warn", "(", "'login success, result: '", ")", ";", "LOG", ".", "warn", "(", "result", ")", ";", "var", "data", "=", "{", "account", ":", "user_data", ".", "account", ",", "groups", ":", "result", ".", "data", ".", "groups", ",", "lastStatus", ":", "result", ".", "data", ".", "lastStatus", ",", "permissions", ":", "[", "]", "}", "l_initSession", "(", "event", ".", "data", ".", "login_id", ",", "event", ".", "session", ",", "data", ")", ";", "l_login_local_accounts", "(", "user_data", ".", "account", ")", ";", "}", "}", "event", ".", "done", "(", "'SR_LOGIN_RESPONSE'", ",", "result", ")", ";", "}" ]
otherwise perform local login
[ "otherwise", "perform", "local", "login" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/handlers/login.js#L320-L379
train
imonology/scalra
handlers/login.js
function (arg) { if ( ! arg.allow ){ return; } var exist = false; for (var i in data.allow) { if (data.allow[i] === arg.allow) { exist = true; } } if ( exist === false ) { data.allow[data.allow.length] = arg.allow; } }
javascript
function (arg) { if ( ! arg.allow ){ return; } var exist = false; for (var i in data.allow) { if (data.allow[i] === arg.allow) { exist = true; } } if ( exist === false ) { data.allow[data.allow.length] = arg.allow; } }
[ "function", "(", "arg", ")", "{", "if", "(", "!", "arg", ".", "allow", ")", "{", "return", ";", "}", "var", "exist", "=", "false", ";", "for", "(", "var", "i", "in", "data", ".", "allow", ")", "{", "if", "(", "data", ".", "allow", "[", "i", "]", "===", "arg", ".", "allow", ")", "{", "exist", "=", "true", ";", "}", "}", "if", "(", "exist", "===", "false", ")", "{", "data", ".", "allow", "[", "data", ".", "allow", ".", "length", "]", "=", "arg", ".", "allow", ";", "}", "}" ]
level exists, to modify this level
[ "level", "exists", "to", "modify", "this", "level" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/handlers/login.js#L694-L708
train
imonology/scalra
core/conn.js
Connection
function Connection (type, sender, from) { // provide default 'from' values from = from || {}; // connection-specific UUID this.connID = UTIL.createUUID(); // a project-specific / supplied name (can be account or app name) this.name = ''; // sender function associated with this connection this.connector = sender; // store pointers on how to respond this.type = type; // where the connection comes from (default to nothing) this.host = from.host || ''; this.port = from.port || 0; // time when this connection is established this.time = new Date(); // append cookie, if available (this is useful if the event will be relayed to another server to execute, // cookie can then be preserved if (from.cookie) this.cookie = from.cookie; }
javascript
function Connection (type, sender, from) { // provide default 'from' values from = from || {}; // connection-specific UUID this.connID = UTIL.createUUID(); // a project-specific / supplied name (can be account or app name) this.name = ''; // sender function associated with this connection this.connector = sender; // store pointers on how to respond this.type = type; // where the connection comes from (default to nothing) this.host = from.host || ''; this.port = from.port || 0; // time when this connection is established this.time = new Date(); // append cookie, if available (this is useful if the event will be relayed to another server to execute, // cookie can then be preserved if (from.cookie) this.cookie = from.cookie; }
[ "function", "Connection", "(", "type", ",", "sender", ",", "from", ")", "{", "from", "=", "from", "||", "{", "}", ";", "this", ".", "connID", "=", "UTIL", ".", "createUUID", "(", ")", ";", "this", ".", "name", "=", "''", ";", "this", ".", "connector", "=", "sender", ";", "this", ".", "type", "=", "type", ";", "this", ".", "host", "=", "from", ".", "host", "||", "''", ";", "this", ".", "port", "=", "from", ".", "port", "||", "0", ";", "this", ".", "time", "=", "new", "Date", "(", ")", ";", "if", "(", "from", ".", "cookie", ")", "this", ".", "cookie", "=", "from", ".", "cookie", ";", "}" ]
definition for a connection object
[ "definition", "for", "a", "connection", "object" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/conn.js#L168-L196
train
imonology/scalra
core/queue.js
function () { // get a event from the front of queue var tmdata = queue.dequeue(); // whether to keep processing (default is no) busy = false; // check if data exists if (tmdata === undefined) { return; } // handle the event if handler is available if (handler === null) { console.log(SR.Tags.ERR + 'handler undefined, cannot process event' + ERREND); return; } switch (handler(tmdata)) { // if the event is not handled, re-queue it case false: queue.enqueue(tmdata); break; // return true, keep processing case true: break; /* // NOTE: we do not pause continuing execution, because it's possible for a event // to consider it finished, re-activate the queue (which it think it has paused), // but then the execution runs to the end of handler, and returning a undefine to pause icQueue // this will thus cause a event to indefinitely pause without any on-going progress. // // Currently if the event has returned, we assume it's been processed. // If not yet, then it's up to the handler to re-enqueue the event (by returning 'false') // note that it's possible that the previous event is still being processed // (for example, waiting for DB to return), while the next event starts processing // so the ordering may not be preserved. // The assumption we have is that events are relatively independent from each other // so such out-of-sequence processing may be "okay," as long as handler will properly re-queue the event // in case it needs to be processed again // */ // did not return anything, pause execution default: //console.log(SR.Tags.WARN + 'pause processing event, callee: ' + arguments.callee.name); return; break; } // keep processing busy = true; UTIL.asyncCall(processEvent); }
javascript
function () { // get a event from the front of queue var tmdata = queue.dequeue(); // whether to keep processing (default is no) busy = false; // check if data exists if (tmdata === undefined) { return; } // handle the event if handler is available if (handler === null) { console.log(SR.Tags.ERR + 'handler undefined, cannot process event' + ERREND); return; } switch (handler(tmdata)) { // if the event is not handled, re-queue it case false: queue.enqueue(tmdata); break; // return true, keep processing case true: break; /* // NOTE: we do not pause continuing execution, because it's possible for a event // to consider it finished, re-activate the queue (which it think it has paused), // but then the execution runs to the end of handler, and returning a undefine to pause icQueue // this will thus cause a event to indefinitely pause without any on-going progress. // // Currently if the event has returned, we assume it's been processed. // If not yet, then it's up to the handler to re-enqueue the event (by returning 'false') // note that it's possible that the previous event is still being processed // (for example, waiting for DB to return), while the next event starts processing // so the ordering may not be preserved. // The assumption we have is that events are relatively independent from each other // so such out-of-sequence processing may be "okay," as long as handler will properly re-queue the event // in case it needs to be processed again // */ // did not return anything, pause execution default: //console.log(SR.Tags.WARN + 'pause processing event, callee: ' + arguments.callee.name); return; break; } // keep processing busy = true; UTIL.asyncCall(processEvent); }
[ "function", "(", ")", "{", "var", "tmdata", "=", "queue", ".", "dequeue", "(", ")", ";", "busy", "=", "false", ";", "if", "(", "tmdata", "===", "undefined", ")", "{", "return", ";", "}", "if", "(", "handler", "===", "null", ")", "{", "console", ".", "log", "(", "SR", ".", "Tags", ".", "ERR", "+", "'handler undefined, cannot process event'", "+", "ERREND", ")", ";", "return", ";", "}", "switch", "(", "handler", "(", "tmdata", ")", ")", "{", "case", "false", ":", "queue", ".", "enqueue", "(", "tmdata", ")", ";", "break", ";", "case", "true", ":", "break", ";", "default", ":", "return", ";", "break", ";", "}", "busy", "=", "true", ";", "UTIL", ".", "asyncCall", "(", "processEvent", ")", ";", "}" ]
this is private method to process
[ "this", "is", "private", "method", "to", "process" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/queue.js#L74-L131
train
imonology/scalra
extension/sync.js
function (arr) { // extract collection name if (arr && typeof arr._name === 'string') { var size = arr.length - arr._index; if (size <= 0) return false; LOG.sys('try to store to array [' + arr._name + '], # of elements to store: ' + size, 'SR.Sync'); // TODO: wasteful of space? // NOTE: only new array entries will be stored to DB var elements = []; for (var i=arr._index; i < arr.length; i++) elements.push(arr[i]); // update index count (regardless of update success or not?) arr._index = arr.length; // TODO: find right way to store // store away // NOTE: $each is used here (try to hide it?) SR.DB.updateArray(SR.Settings.DB_NAME_SYNC, {name: arr._name}, {data: elements}, function (result) { LOG.sys('update array success: ' + result, 'SR.Sync'); }, function (result) { LOG.error('update array fail: ' + result, 'SR.Sync'); } ); return true; } else LOG.error('cannot store to DB, arr_name unavailable', 'SR.Sync'); return false; }
javascript
function (arr) { // extract collection name if (arr && typeof arr._name === 'string') { var size = arr.length - arr._index; if (size <= 0) return false; LOG.sys('try to store to array [' + arr._name + '], # of elements to store: ' + size, 'SR.Sync'); // TODO: wasteful of space? // NOTE: only new array entries will be stored to DB var elements = []; for (var i=arr._index; i < arr.length; i++) elements.push(arr[i]); // update index count (regardless of update success or not?) arr._index = arr.length; // TODO: find right way to store // store away // NOTE: $each is used here (try to hide it?) SR.DB.updateArray(SR.Settings.DB_NAME_SYNC, {name: arr._name}, {data: elements}, function (result) { LOG.sys('update array success: ' + result, 'SR.Sync'); }, function (result) { LOG.error('update array fail: ' + result, 'SR.Sync'); } ); return true; } else LOG.error('cannot store to DB, arr_name unavailable', 'SR.Sync'); return false; }
[ "function", "(", "arr", ")", "{", "if", "(", "arr", "&&", "typeof", "arr", ".", "_name", "===", "'string'", ")", "{", "var", "size", "=", "arr", ".", "length", "-", "arr", ".", "_index", ";", "if", "(", "size", "<=", "0", ")", "return", "false", ";", "LOG", ".", "sys", "(", "'try to store to array ['", "+", "arr", ".", "_name", "+", "'], # of elements to store: '", "+", "size", ",", "'SR.Sync'", ")", ";", "var", "elements", "=", "[", "]", ";", "for", "(", "var", "i", "=", "arr", ".", "_index", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "elements", ".", "push", "(", "arr", "[", "i", "]", ")", ";", "arr", ".", "_index", "=", "arr", ".", "length", ";", "SR", ".", "DB", ".", "updateArray", "(", "SR", ".", "Settings", ".", "DB_NAME_SYNC", ",", "{", "name", ":", "arr", ".", "_name", "}", ",", "{", "data", ":", "elements", "}", ",", "function", "(", "result", ")", "{", "LOG", ".", "sys", "(", "'update array success: '", "+", "result", ",", "'SR.Sync'", ")", ";", "}", ",", "function", "(", "result", ")", "{", "LOG", ".", "error", "(", "'update array fail: '", "+", "result", ",", "'SR.Sync'", ")", ";", "}", ")", ";", "return", "true", ";", "}", "else", "LOG", ".", "error", "(", "'cannot store to DB, arr_name unavailable'", ",", "'SR.Sync'", ")", ";", "return", "false", ";", "}" ]
store a particular record to DB
[ "store", "a", "particular", "record", "to", "DB" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/sync.js#L62-L100
train
imonology/scalra
extension/sync.js
function (arrays, config, onDone) { var names = []; // load array's content from DB, if any SR.DB.getArray(SR.Settings.DB_NAME_SYNC, function (result) { // NOTE: if array does not exist it'll return success with an empty array if (result === null || result.length === 0) { LOG.warn('no arrays found, cannot load', 'SR.Sync'); } else { var array_limit = (typeof config.limit === 'number' ? config.limit : 0); LOG.sys('arrays exist, try to load (limit: ' + array_limit + ')', 'SR.Sync'); for (var i=0; i < result.length; i++) { var record = result[i]; var arr = arrays[record.name] = []; // load data (clone is better?) var limit = (record.data.length > array_limit ? array_limit : record.data.length); var start = record.data.length - limit; for (var j=0; j < limit; j++) arr[j] = UTIL.clone(record.data[start+j]); // override array's default behavior arr.push = l_push; // store array's name arr._name = record.name; // store last stored index (next index to store) arr._index = j; LOG.sys('[' + record.name + '] DB record length: ' + record.data.length + ' start: ' + start + ' actual limit: ' + limit + ' _index: ' + arr._index, 'SR.Sync'); l_names[record.name] = arr; names.push(record.name); } } UTIL.safeCall(onDone, names); }, function (result) { UTIL.safeCall(onDone, names); }, {}); }
javascript
function (arrays, config, onDone) { var names = []; // load array's content from DB, if any SR.DB.getArray(SR.Settings.DB_NAME_SYNC, function (result) { // NOTE: if array does not exist it'll return success with an empty array if (result === null || result.length === 0) { LOG.warn('no arrays found, cannot load', 'SR.Sync'); } else { var array_limit = (typeof config.limit === 'number' ? config.limit : 0); LOG.sys('arrays exist, try to load (limit: ' + array_limit + ')', 'SR.Sync'); for (var i=0; i < result.length; i++) { var record = result[i]; var arr = arrays[record.name] = []; // load data (clone is better?) var limit = (record.data.length > array_limit ? array_limit : record.data.length); var start = record.data.length - limit; for (var j=0; j < limit; j++) arr[j] = UTIL.clone(record.data[start+j]); // override array's default behavior arr.push = l_push; // store array's name arr._name = record.name; // store last stored index (next index to store) arr._index = j; LOG.sys('[' + record.name + '] DB record length: ' + record.data.length + ' start: ' + start + ' actual limit: ' + limit + ' _index: ' + arr._index, 'SR.Sync'); l_names[record.name] = arr; names.push(record.name); } } UTIL.safeCall(onDone, names); }, function (result) { UTIL.safeCall(onDone, names); }, {}); }
[ "function", "(", "arrays", ",", "config", ",", "onDone", ")", "{", "var", "names", "=", "[", "]", ";", "SR", ".", "DB", ".", "getArray", "(", "SR", ".", "Settings", ".", "DB_NAME_SYNC", ",", "function", "(", "result", ")", "{", "if", "(", "result", "===", "null", "||", "result", ".", "length", "===", "0", ")", "{", "LOG", ".", "warn", "(", "'no arrays found, cannot load'", ",", "'SR.Sync'", ")", ";", "}", "else", "{", "var", "array_limit", "=", "(", "typeof", "config", ".", "limit", "===", "'number'", "?", "config", ".", "limit", ":", "0", ")", ";", "LOG", ".", "sys", "(", "'arrays exist, try to load (limit: '", "+", "array_limit", "+", "')'", ",", "'SR.Sync'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "result", ".", "length", ";", "i", "++", ")", "{", "var", "record", "=", "result", "[", "i", "]", ";", "var", "arr", "=", "arrays", "[", "record", ".", "name", "]", "=", "[", "]", ";", "var", "limit", "=", "(", "record", ".", "data", ".", "length", ">", "array_limit", "?", "array_limit", ":", "record", ".", "data", ".", "length", ")", ";", "var", "start", "=", "record", ".", "data", ".", "length", "-", "limit", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "limit", ";", "j", "++", ")", "arr", "[", "j", "]", "=", "UTIL", ".", "clone", "(", "record", ".", "data", "[", "start", "+", "j", "]", ")", ";", "arr", ".", "push", "=", "l_push", ";", "arr", ".", "_name", "=", "record", ".", "name", ";", "arr", ".", "_index", "=", "j", ";", "LOG", ".", "sys", "(", "'['", "+", "record", ".", "name", "+", "'] DB record length: '", "+", "record", ".", "data", ".", "length", "+", "' start: '", "+", "start", "+", "' actual limit: '", "+", "limit", "+", "' _index: '", "+", "arr", ".", "_index", ",", "'SR.Sync'", ")", ";", "l_names", "[", "record", ".", "name", "]", "=", "arr", ";", "names", ".", "push", "(", "record", ".", "name", ")", ";", "}", "}", "UTIL", ".", "safeCall", "(", "onDone", ",", "names", ")", ";", "}", ",", "function", "(", "result", ")", "{", "UTIL", ".", "safeCall", "(", "onDone", ",", "names", ")", ";", "}", ",", "{", "}", ")", ";", "}" ]
load data from DB to an in-memory array returns a list of the names of arrays loaded
[ "load", "data", "from", "DB", "to", "an", "in", "-", "memory", "array", "returns", "a", "list", "of", "the", "names", "of", "arrays", "loaded" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/extension/sync.js#L212-L264
train
imonology/scalra
core/API.js
function (args, result, func, extra) { return new SR.promise(function (resolve, reject) { UTIL.safeCall(func, args, result, function () { UTIL.safeCall(resolve); }, extra); }); }
javascript
function (args, result, func, extra) { return new SR.promise(function (resolve, reject) { UTIL.safeCall(func, args, result, function () { UTIL.safeCall(resolve); }, extra); }); }
[ "function", "(", "args", ",", "result", ",", "func", ",", "extra", ")", "{", "return", "new", "SR", ".", "promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "UTIL", ".", "safeCall", "(", "func", ",", "args", ",", "result", ",", "function", "(", ")", "{", "UTIL", ".", "safeCall", "(", "resolve", ")", ";", "}", ",", "extra", ")", ";", "}", ")", ";", "}" ]
define post-event action
[ "define", "post", "-", "event", "action" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/API.js#L52-L58
train
imonology/scalra
core/API.js
function (args, onDone, extra) { // if args are not provided then we shift the parameters if (typeof args === 'function') { extra = onDone; onDone = args; args = {}; } // TODO: perform argument type check (currently there's none, so internal API calls won't do type checks) // TODO: move checker to here var onError = function(err) { LOG.error('onError '+ err, l_name); UTIL.safeCall(onDone, err); } function onExec() { // make actual call to user-defined function // NOTE: we also return values for direct function calls return UTIL.safeCall(l_list[name], args, function (err, result, unsupported_return) { if (err) { LOG.error('[' + name + '] error:', l_name); LOG.error(err, l_name); } if (unsupported_return) { var errmsg = 'onDone() in SR.API does not support more than one return variable, please return everything inside a result object'; LOG.error(errmsg, l_name); LOG.stack(); return UTIL.safeCall(onDone, errmsg); } // perform post-event actions, if any if (l_afterActions.hasOwnProperty(name) === false) { return UTIL.safeCall(onDone, err, result); } var posts = l_afterActions[name]; var promise = undefined; for (var i=0; i < posts.length; i++) { if (!promise) { promise = post_action(args, { err: err, result: result }, posts[i], extra); } else { promise = promise.then(post_action(args, { err: err, result: result }, posts[i], extra)); } } // last action promise.then(new SR.promise(function (resolve, reject) { //LOG.warn('everything is done... call original onDone...', l_name); UTIL.safeCall(onDone, err, result); resolve(); })); }, extra); } // perform pre-event actions, if any if (l_beforeActions.hasOwnProperty(name) === false) { return onExec(); } const pres = l_beforeActions[name].map((callback) => pre_action(args, callback, extra)); pres.reduce((p, callback) => p.then(() => callback), Promise.resolve()) .then(onExec) .catch((err) => { LOG.error(err); onDone(err); }); }
javascript
function (args, onDone, extra) { // if args are not provided then we shift the parameters if (typeof args === 'function') { extra = onDone; onDone = args; args = {}; } // TODO: perform argument type check (currently there's none, so internal API calls won't do type checks) // TODO: move checker to here var onError = function(err) { LOG.error('onError '+ err, l_name); UTIL.safeCall(onDone, err); } function onExec() { // make actual call to user-defined function // NOTE: we also return values for direct function calls return UTIL.safeCall(l_list[name], args, function (err, result, unsupported_return) { if (err) { LOG.error('[' + name + '] error:', l_name); LOG.error(err, l_name); } if (unsupported_return) { var errmsg = 'onDone() in SR.API does not support more than one return variable, please return everything inside a result object'; LOG.error(errmsg, l_name); LOG.stack(); return UTIL.safeCall(onDone, errmsg); } // perform post-event actions, if any if (l_afterActions.hasOwnProperty(name) === false) { return UTIL.safeCall(onDone, err, result); } var posts = l_afterActions[name]; var promise = undefined; for (var i=0; i < posts.length; i++) { if (!promise) { promise = post_action(args, { err: err, result: result }, posts[i], extra); } else { promise = promise.then(post_action(args, { err: err, result: result }, posts[i], extra)); } } // last action promise.then(new SR.promise(function (resolve, reject) { //LOG.warn('everything is done... call original onDone...', l_name); UTIL.safeCall(onDone, err, result); resolve(); })); }, extra); } // perform pre-event actions, if any if (l_beforeActions.hasOwnProperty(name) === false) { return onExec(); } const pres = l_beforeActions[name].map((callback) => pre_action(args, callback, extra)); pres.reduce((p, callback) => p.then(() => callback), Promise.resolve()) .then(onExec) .catch((err) => { LOG.error(err); onDone(err); }); }
[ "function", "(", "args", ",", "onDone", ",", "extra", ")", "{", "if", "(", "typeof", "args", "===", "'function'", ")", "{", "extra", "=", "onDone", ";", "onDone", "=", "args", ";", "args", "=", "{", "}", ";", "}", "var", "onError", "=", "function", "(", "err", ")", "{", "LOG", ".", "error", "(", "'onError '", "+", "err", ",", "l_name", ")", ";", "UTIL", ".", "safeCall", "(", "onDone", ",", "err", ")", ";", "}", "function", "onExec", "(", ")", "{", "return", "UTIL", ".", "safeCall", "(", "l_list", "[", "name", "]", ",", "args", ",", "function", "(", "err", ",", "result", ",", "unsupported_return", ")", "{", "if", "(", "err", ")", "{", "LOG", ".", "error", "(", "'['", "+", "name", "+", "'] error:'", ",", "l_name", ")", ";", "LOG", ".", "error", "(", "err", ",", "l_name", ")", ";", "}", "if", "(", "unsupported_return", ")", "{", "var", "errmsg", "=", "'onDone() in SR.API does not support more than one return variable, please return everything inside a result object'", ";", "LOG", ".", "error", "(", "errmsg", ",", "l_name", ")", ";", "LOG", ".", "stack", "(", ")", ";", "return", "UTIL", ".", "safeCall", "(", "onDone", ",", "errmsg", ")", ";", "}", "if", "(", "l_afterActions", ".", "hasOwnProperty", "(", "name", ")", "===", "false", ")", "{", "return", "UTIL", ".", "safeCall", "(", "onDone", ",", "err", ",", "result", ")", ";", "}", "var", "posts", "=", "l_afterActions", "[", "name", "]", ";", "var", "promise", "=", "undefined", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "posts", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "promise", ")", "{", "promise", "=", "post_action", "(", "args", ",", "{", "err", ":", "err", ",", "result", ":", "result", "}", ",", "posts", "[", "i", "]", ",", "extra", ")", ";", "}", "else", "{", "promise", "=", "promise", ".", "then", "(", "post_action", "(", "args", ",", "{", "err", ":", "err", ",", "result", ":", "result", "}", ",", "posts", "[", "i", "]", ",", "extra", ")", ")", ";", "}", "}", "promise", ".", "then", "(", "new", "SR", ".", "promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "UTIL", ".", "safeCall", "(", "onDone", ",", "err", ",", "result", ")", ";", "resolve", "(", ")", ";", "}", ")", ")", ";", "}", ",", "extra", ")", ";", "}", "if", "(", "l_beforeActions", ".", "hasOwnProperty", "(", "name", ")", "===", "false", ")", "{", "return", "onExec", "(", ")", ";", "}", "const", "pres", "=", "l_beforeActions", "[", "name", "]", ".", "map", "(", "(", "callback", ")", "=>", "pre_action", "(", "args", ",", "callback", ",", "extra", ")", ")", ";", "pres", ".", "reduce", "(", "(", "p", ",", "callback", ")", "=>", "p", ".", "then", "(", "(", ")", "=>", "callback", ")", ",", "Promise", ".", "resolve", "(", ")", ")", ".", "then", "(", "onExec", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "LOG", ".", "error", "(", "err", ")", ";", "onDone", "(", "err", ")", ";", "}", ")", ";", "}" ]
define wrapper function
[ "define", "wrapper", "function" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/API.js#L81-L150
train
imonology/scalra
modules/account.js
function (account) { // check if DB is initialized if (typeof l_accounts === 'undefined') { LOG.error('DB module is not loaded, please enable DB module', l_name); return false; } if (l_accounts.hasOwnProperty(account) === false) { LOG.error('[' + account + '] not found', l_name); return false; } return true; }
javascript
function (account) { // check if DB is initialized if (typeof l_accounts === 'undefined') { LOG.error('DB module is not loaded, please enable DB module', l_name); return false; } if (l_accounts.hasOwnProperty(account) === false) { LOG.error('[' + account + '] not found', l_name); return false; } return true; }
[ "function", "(", "account", ")", "{", "if", "(", "typeof", "l_accounts", "===", "'undefined'", ")", "{", "LOG", ".", "error", "(", "'DB module is not loaded, please enable DB module'", ",", "l_name", ")", ";", "return", "false", ";", "}", "if", "(", "l_accounts", ".", "hasOwnProperty", "(", "account", ")", "===", "false", ")", "{", "LOG", ".", "error", "(", "'['", "+", "account", "+", "'] not found'", ",", "l_name", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
helper functions check if an account is valid
[ "helper", "functions", "check", "if", "an", "account", "is", "valid" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/modules/account.js#L42-L55
train
imonology/scalra
modules/account.js
getUIDCallback
function getUIDCallback (err, uid) { if (err) { return onDone('UID_ERROR'); } var ip = (extra) ? extra.conn.host : "server"; // NOTE: by default a user is a normal user, user 'groups' can later be customized var reg = { uid: uid, account: args.account, password: l_encryptPass(args.password), email: args.email, // verify: {email_verify: false, phone_verify: false}, tokens: {reset: '', pass: {}}, enc_type: l_enc_type, control: {groups: args.groups || [], permissions: []}, data: args.data || {}, login: {IP: ip, count: 1} }; // special handling (by default 'admin' account is special and will be part of the 'admin' group by default if (!args.authWP && reg.account === 'admin') { reg.control.groups.push('admin'); } LOG.warn('creating new account [' + args.account + ']...', l_name); l_accounts.add(reg, function (err) { if (err) { return onDone('DB_ERROR', err); } // register success LOG.warn('account register success', l_name); onDone(null); }); }
javascript
function getUIDCallback (err, uid) { if (err) { return onDone('UID_ERROR'); } var ip = (extra) ? extra.conn.host : "server"; // NOTE: by default a user is a normal user, user 'groups' can later be customized var reg = { uid: uid, account: args.account, password: l_encryptPass(args.password), email: args.email, // verify: {email_verify: false, phone_verify: false}, tokens: {reset: '', pass: {}}, enc_type: l_enc_type, control: {groups: args.groups || [], permissions: []}, data: args.data || {}, login: {IP: ip, count: 1} }; // special handling (by default 'admin' account is special and will be part of the 'admin' group by default if (!args.authWP && reg.account === 'admin') { reg.control.groups.push('admin'); } LOG.warn('creating new account [' + args.account + ']...', l_name); l_accounts.add(reg, function (err) { if (err) { return onDone('DB_ERROR', err); } // register success LOG.warn('account register success', l_name); onDone(null); }); }
[ "function", "getUIDCallback", "(", "err", ",", "uid", ")", "{", "if", "(", "err", ")", "{", "return", "onDone", "(", "'UID_ERROR'", ")", ";", "}", "var", "ip", "=", "(", "extra", ")", "?", "extra", ".", "conn", ".", "host", ":", "\"server\"", ";", "var", "reg", "=", "{", "uid", ":", "uid", ",", "account", ":", "args", ".", "account", ",", "password", ":", "l_encryptPass", "(", "args", ".", "password", ")", ",", "email", ":", "args", ".", "email", ",", "tokens", ":", "{", "reset", ":", "''", ",", "pass", ":", "{", "}", "}", ",", "enc_type", ":", "l_enc_type", ",", "control", ":", "{", "groups", ":", "args", ".", "groups", "||", "[", "]", ",", "permissions", ":", "[", "]", "}", ",", "data", ":", "args", ".", "data", "||", "{", "}", ",", "login", ":", "{", "IP", ":", "ip", ",", "count", ":", "1", "}", "}", ";", "if", "(", "!", "args", ".", "authWP", "&&", "reg", ".", "account", "===", "'admin'", ")", "{", "reg", ".", "control", ".", "groups", ".", "push", "(", "'admin'", ")", ";", "}", "LOG", ".", "warn", "(", "'creating new account ['", "+", "args", ".", "account", "+", "']...'", ",", "l_name", ")", ";", "l_accounts", ".", "add", "(", "reg", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "onDone", "(", "'DB_ERROR'", ",", "err", ")", ";", "}", "LOG", ".", "warn", "(", "'account register success'", ",", "l_name", ")", ";", "onDone", "(", "null", ")", ";", "}", ")", ";", "}" ]
generate unique user_id
[ "generate", "unique", "user_id" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/modules/account.js#L239-L272
train
imonology/scalra
core/app_connector.js
function (conn) { LOG.error('AppManager disconnected', 'SR.AppConnector'); if (SR.Settings.APPSERVER_AUTOSHUT === true) { // shutdown this frontier l_dispose(); SR.Settings.FRONTIER.dispose(); } else { LOG.warn('auto-shutdown is false, attempt to re-connect AppManager in ' + l_timeoutReconnect + ' ms...'); // keep app server alive and try to re-connect if lobby shuts down setTimeout(l_connect, l_timeoutReconnect); } }
javascript
function (conn) { LOG.error('AppManager disconnected', 'SR.AppConnector'); if (SR.Settings.APPSERVER_AUTOSHUT === true) { // shutdown this frontier l_dispose(); SR.Settings.FRONTIER.dispose(); } else { LOG.warn('auto-shutdown is false, attempt to re-connect AppManager in ' + l_timeoutReconnect + ' ms...'); // keep app server alive and try to re-connect if lobby shuts down setTimeout(l_connect, l_timeoutReconnect); } }
[ "function", "(", "conn", ")", "{", "LOG", ".", "error", "(", "'AppManager disconnected'", ",", "'SR.AppConnector'", ")", ";", "if", "(", "SR", ".", "Settings", ".", "APPSERVER_AUTOSHUT", "===", "true", ")", "{", "l_dispose", "(", ")", ";", "SR", ".", "Settings", ".", "FRONTIER", ".", "dispose", "(", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "'auto-shutdown is false, attempt to re-connect AppManager in '", "+", "l_timeoutReconnect", "+", "' ms...'", ")", ";", "setTimeout", "(", "l_connect", ",", "l_timeoutReconnect", ")", ";", "}", "}" ]
custom handling for removing a connection
[ "custom", "handling", "for", "removing", "a", "connection" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/app_connector.js#L36-L52
train
imonology/scalra
core/app_connector.js
function () { LOG.warn('appinfo sent to lobby:'); LOG.warn(l_appinfo); // notify AppManager we're ready l_notifyLobby('SR_APP_READY', l_appinfo, 'SR_APP_READY_RES', function (event) { if (event.data.op === true) LOG.sys('SR_APP_READY returns ok', 'l_HandlerPool'); else LOG.error('SR_APP_READY returns fail', 'l_HandlerPool'); // call onDone if exists (but just once) if (l_onDone) { UTIL.safeCall(l_onDone); l_onDone = undefined; } } ); }
javascript
function () { LOG.warn('appinfo sent to lobby:'); LOG.warn(l_appinfo); // notify AppManager we're ready l_notifyLobby('SR_APP_READY', l_appinfo, 'SR_APP_READY_RES', function (event) { if (event.data.op === true) LOG.sys('SR_APP_READY returns ok', 'l_HandlerPool'); else LOG.error('SR_APP_READY returns fail', 'l_HandlerPool'); // call onDone if exists (but just once) if (l_onDone) { UTIL.safeCall(l_onDone); l_onDone = undefined; } } ); }
[ "function", "(", ")", "{", "LOG", ".", "warn", "(", "'appinfo sent to lobby:'", ")", ";", "LOG", ".", "warn", "(", "l_appinfo", ")", ";", "l_notifyLobby", "(", "'SR_APP_READY'", ",", "l_appinfo", ",", "'SR_APP_READY_RES'", ",", "function", "(", "event", ")", "{", "if", "(", "event", ".", "data", ".", "op", "===", "true", ")", "LOG", ".", "sys", "(", "'SR_APP_READY returns ok'", ",", "'l_HandlerPool'", ")", ";", "else", "LOG", ".", "error", "(", "'SR_APP_READY returns fail'", ",", "'l_HandlerPool'", ")", ";", "if", "(", "l_onDone", ")", "{", "UTIL", ".", "safeCall", "(", "l_onDone", ")", ";", "l_onDone", "=", "undefined", ";", "}", "}", ")", ";", "}" ]
register myself as a app to app manager do it after connector init success
[ "register", "myself", "as", "a", "app", "to", "app", "manager", "do", "it", "after", "connector", "init", "success" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/app_connector.js#L102-L123
train
imonology/scalra
core/app_connector.js
function (ip_port, onDone) { if (l_appConnector === undefined) { LOG.warn('appConnector not init, cannot connect'); return; } // retrieve from previous connect attempt, also store for later connect attempt // TODO: will need to change when lobby port becomes not fixed ip_port = ip_port || l_ip_port; l_ip_port = ip_port; // store callback to be called later // TODO: better approach? l_onDone = onDone || l_onDone; l_appConnector.connect(ip_port, function (err, socket) { if (err) { LOG.error('connection to manager: ' + ip_port.IP + ':' + ip_port.port + ' fail, try again in ' + l_timeoutReconnect + ' ms'); // TODO: do not keep trying, but rather try to re-connect after being notified by monitor server setTimeout(l_connect, l_timeoutReconnect); } // connection is successful else { LOG.warn('connection to manager: ' + ip_port.IP + ':' + ip_port.port + ' established'); l_register(); } }); }
javascript
function (ip_port, onDone) { if (l_appConnector === undefined) { LOG.warn('appConnector not init, cannot connect'); return; } // retrieve from previous connect attempt, also store for later connect attempt // TODO: will need to change when lobby port becomes not fixed ip_port = ip_port || l_ip_port; l_ip_port = ip_port; // store callback to be called later // TODO: better approach? l_onDone = onDone || l_onDone; l_appConnector.connect(ip_port, function (err, socket) { if (err) { LOG.error('connection to manager: ' + ip_port.IP + ':' + ip_port.port + ' fail, try again in ' + l_timeoutReconnect + ' ms'); // TODO: do not keep trying, but rather try to re-connect after being notified by monitor server setTimeout(l_connect, l_timeoutReconnect); } // connection is successful else { LOG.warn('connection to manager: ' + ip_port.IP + ':' + ip_port.port + ' established'); l_register(); } }); }
[ "function", "(", "ip_port", ",", "onDone", ")", "{", "if", "(", "l_appConnector", "===", "undefined", ")", "{", "LOG", ".", "warn", "(", "'appConnector not init, cannot connect'", ")", ";", "return", ";", "}", "ip_port", "=", "ip_port", "||", "l_ip_port", ";", "l_ip_port", "=", "ip_port", ";", "l_onDone", "=", "onDone", "||", "l_onDone", ";", "l_appConnector", ".", "connect", "(", "ip_port", ",", "function", "(", "err", ",", "socket", ")", "{", "if", "(", "err", ")", "{", "LOG", ".", "error", "(", "'connection to manager: '", "+", "ip_port", ".", "IP", "+", "':'", "+", "ip_port", ".", "port", "+", "' fail, try again in '", "+", "l_timeoutReconnect", "+", "' ms'", ")", ";", "setTimeout", "(", "l_connect", ",", "l_timeoutReconnect", ")", ";", "}", "else", "{", "LOG", ".", "warn", "(", "'connection to manager: '", "+", "ip_port", ".", "IP", "+", "':'", "+", "ip_port", ".", "port", "+", "' established'", ")", ";", "l_register", "(", ")", ";", "}", "}", ")", ";", "}" ]
attempt to connect to manager
[ "attempt", "to", "connect", "to", "manager" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/core/app_connector.js#L126-L155
train
imonology/scalra
demo/lobby/router.js
function (req) { var session = l_getSession(req); if (session.hasOwnProperty('_user')) { var login = session._user; login.admin = (session._user.account === 'admin'); return login; } LOG.warn('user not yet logined...'); return {control: {groups: [], permissions: []}}; }
javascript
function (req) { var session = l_getSession(req); if (session.hasOwnProperty('_user')) { var login = session._user; login.admin = (session._user.account === 'admin'); return login; } LOG.warn('user not yet logined...'); return {control: {groups: [], permissions: []}}; }
[ "function", "(", "req", ")", "{", "var", "session", "=", "l_getSession", "(", "req", ")", ";", "if", "(", "session", ".", "hasOwnProperty", "(", "'_user'", ")", ")", "{", "var", "login", "=", "session", ".", "_user", ";", "login", ".", "admin", "=", "(", "session", ".", "_user", ".", "account", "===", "'admin'", ")", ";", "return", "login", ";", "}", "LOG", ".", "warn", "(", "'user not yet logined...'", ")", ";", "return", "{", "control", ":", "{", "groups", ":", "[", "]", ",", "permissions", ":", "[", "]", "}", "}", ";", "}" ]
pass in request object, returns session data if logined, otherwise returns null
[ "pass", "in", "request", "object", "returns", "session", "data", "if", "logined", "otherwise", "returns", "null" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/demo/lobby/router.js#L31-L41
train
gastonelhordoy/grunt-rpm
tasks/rpm.js
copyFilesToPack
function copyFilesToPack(grunt, buildPath, filesToPack) { return function(callback) { grunt.util.async.forEach(filesToPack, function(fileConfig, callback) { try { var filepathDest; if (detectDestType(grunt, fileConfig.dest) === 'directory') { var dest = (fileConfig.orig.expand) ? fileConfig.dest : path.join(fileConfig.dest, fileConfig.src); filepathDest = path.join(buildPath, dest); } else { filepathDest = path.join(buildPath, fileConfig.dest); } if (grunt.file.isDir(fileConfig.src)) { if (fileConfig.directory) { // Copy a whole folder to the destination directory. grunt.verbose.writeln('Copying folder "' + fileConfig.src + '" to "' + filepathDest + '"'); fs.copyRecursive(fileConfig.src, filepathDest, callback); } else { // Create a folder inside the destination directory. grunt.verbose.writeln('Creating folder "' + filepathDest + '"'); fs.mkdirs(filepathDest, callback); } } else { // Copy a file to the destination directory inside the tmp folder. if (fileConfig.link) { grunt.verbose.writeln('Copying symlink "' + fileConfig.src + '->' + fileConfig.link + '" to "' + filepathDest + '"'); //ensure the parent directory exists when making symlinks fs.mkdirs(getDirName(filepathDest), function(err) { if (err) throw err; _fs.symlink(fileConfig.link, filepathDest, 'file', callback); }); } else { grunt.verbose.writeln('Copying file "' + fileConfig.src + '" to "' + filepathDest + '"'); grunt.file.copy(fileConfig.src, filepathDest); fs.lstat(fileConfig.src, function(err, stat) { if (err) throw err; _fs.chmod(filepathDest, stat.mode, callback); }); } } } catch(e) { callback(e); } }, callback); }; }
javascript
function copyFilesToPack(grunt, buildPath, filesToPack) { return function(callback) { grunt.util.async.forEach(filesToPack, function(fileConfig, callback) { try { var filepathDest; if (detectDestType(grunt, fileConfig.dest) === 'directory') { var dest = (fileConfig.orig.expand) ? fileConfig.dest : path.join(fileConfig.dest, fileConfig.src); filepathDest = path.join(buildPath, dest); } else { filepathDest = path.join(buildPath, fileConfig.dest); } if (grunt.file.isDir(fileConfig.src)) { if (fileConfig.directory) { // Copy a whole folder to the destination directory. grunt.verbose.writeln('Copying folder "' + fileConfig.src + '" to "' + filepathDest + '"'); fs.copyRecursive(fileConfig.src, filepathDest, callback); } else { // Create a folder inside the destination directory. grunt.verbose.writeln('Creating folder "' + filepathDest + '"'); fs.mkdirs(filepathDest, callback); } } else { // Copy a file to the destination directory inside the tmp folder. if (fileConfig.link) { grunt.verbose.writeln('Copying symlink "' + fileConfig.src + '->' + fileConfig.link + '" to "' + filepathDest + '"'); //ensure the parent directory exists when making symlinks fs.mkdirs(getDirName(filepathDest), function(err) { if (err) throw err; _fs.symlink(fileConfig.link, filepathDest, 'file', callback); }); } else { grunt.verbose.writeln('Copying file "' + fileConfig.src + '" to "' + filepathDest + '"'); grunt.file.copy(fileConfig.src, filepathDest); fs.lstat(fileConfig.src, function(err, stat) { if (err) throw err; _fs.chmod(filepathDest, stat.mode, callback); }); } } } catch(e) { callback(e); } }, callback); }; }
[ "function", "copyFilesToPack", "(", "grunt", ",", "buildPath", ",", "filesToPack", ")", "{", "return", "function", "(", "callback", ")", "{", "grunt", ".", "util", ".", "async", ".", "forEach", "(", "filesToPack", ",", "function", "(", "fileConfig", ",", "callback", ")", "{", "try", "{", "var", "filepathDest", ";", "if", "(", "detectDestType", "(", "grunt", ",", "fileConfig", ".", "dest", ")", "===", "'directory'", ")", "{", "var", "dest", "=", "(", "fileConfig", ".", "orig", ".", "expand", ")", "?", "fileConfig", ".", "dest", ":", "path", ".", "join", "(", "fileConfig", ".", "dest", ",", "fileConfig", ".", "src", ")", ";", "filepathDest", "=", "path", ".", "join", "(", "buildPath", ",", "dest", ")", ";", "}", "else", "{", "filepathDest", "=", "path", ".", "join", "(", "buildPath", ",", "fileConfig", ".", "dest", ")", ";", "}", "if", "(", "grunt", ".", "file", ".", "isDir", "(", "fileConfig", ".", "src", ")", ")", "{", "if", "(", "fileConfig", ".", "directory", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'Copying folder \"'", "+", "fileConfig", ".", "src", "+", "'\" to \"'", "+", "filepathDest", "+", "'\"'", ")", ";", "fs", ".", "copyRecursive", "(", "fileConfig", ".", "src", ",", "filepathDest", ",", "callback", ")", ";", "}", "else", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'Creating folder \"'", "+", "filepathDest", "+", "'\"'", ")", ";", "fs", ".", "mkdirs", "(", "filepathDest", ",", "callback", ")", ";", "}", "}", "else", "{", "if", "(", "fileConfig", ".", "link", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'Copying symlink \"'", "+", "fileConfig", ".", "src", "+", "'->'", "+", "fileConfig", ".", "link", "+", "'\" to \"'", "+", "filepathDest", "+", "'\"'", ")", ";", "fs", ".", "mkdirs", "(", "getDirName", "(", "filepathDest", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "_fs", ".", "symlink", "(", "fileConfig", ".", "link", ",", "filepathDest", ",", "'file'", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "{", "grunt", ".", "verbose", ".", "writeln", "(", "'Copying file \"'", "+", "fileConfig", ".", "src", "+", "'\" to \"'", "+", "filepathDest", "+", "'\"'", ")", ";", "grunt", ".", "file", ".", "copy", "(", "fileConfig", ".", "src", ",", "filepathDest", ")", ";", "fs", ".", "lstat", "(", "fileConfig", ".", "src", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "_fs", ".", "chmod", "(", "filepathDest", ",", "stat", ".", "mode", ",", "callback", ")", ";", "}", ")", ";", "}", "}", "}", "catch", "(", "e", ")", "{", "callback", "(", "e", ")", ";", "}", "}", ",", "callback", ")", ";", "}", ";", "}" ]
Copy all the selected files to the tmp folder which wikll be the buildroot directory for rpmbuild
[ "Copy", "all", "the", "selected", "files", "to", "the", "tmp", "folder", "which", "wikll", "be", "the", "buildroot", "directory", "for", "rpmbuild" ]
8c6761959f912aab7234b68ea40893612d6b9b3d
https://github.com/gastonelhordoy/grunt-rpm/blob/8c6761959f912aab7234b68ea40893612d6b9b3d/tasks/rpm.js#L93-L141
train
gastonelhordoy/grunt-rpm
tasks/rpm.js
writeSpecFile
function writeSpecFile(grunt, options, filesToPack) { return function(callback) { try { var specPath = path.join(options.destination, specFolder); options.files = filesToPack; var pkg = grunt.file.readJSON('package.json'); grunt.util._.defaults(options, pkg); options.specFilepath = path.join(specPath, options.name + '.spec'); spec(options, callback); } catch(e) { callback(e); } }; }
javascript
function writeSpecFile(grunt, options, filesToPack) { return function(callback) { try { var specPath = path.join(options.destination, specFolder); options.files = filesToPack; var pkg = grunt.file.readJSON('package.json'); grunt.util._.defaults(options, pkg); options.specFilepath = path.join(specPath, options.name + '.spec'); spec(options, callback); } catch(e) { callback(e); } }; }
[ "function", "writeSpecFile", "(", "grunt", ",", "options", ",", "filesToPack", ")", "{", "return", "function", "(", "callback", ")", "{", "try", "{", "var", "specPath", "=", "path", ".", "join", "(", "options", ".", "destination", ",", "specFolder", ")", ";", "options", ".", "files", "=", "filesToPack", ";", "var", "pkg", "=", "grunt", ".", "file", ".", "readJSON", "(", "'package.json'", ")", ";", "grunt", ".", "util", ".", "_", ".", "defaults", "(", "options", ",", "pkg", ")", ";", "options", ".", "specFilepath", "=", "path", ".", "join", "(", "specPath", ",", "options", ".", "name", "+", "'.spec'", ")", ";", "spec", "(", "options", ",", "callback", ")", ";", "}", "catch", "(", "e", ")", "{", "callback", "(", "e", ")", ";", "}", "}", ";", "}" ]
Write the spec file that rpmbuild will read for the rpm details
[ "Write", "the", "spec", "file", "that", "rpmbuild", "will", "read", "for", "the", "rpm", "details" ]
8c6761959f912aab7234b68ea40893612d6b9b3d
https://github.com/gastonelhordoy/grunt-rpm/blob/8c6761959f912aab7234b68ea40893612d6b9b3d/tasks/rpm.js#L146-L160
train
imonology/scalra
modules/cloud_connector.js
function () { if (l_ip_port === undefined) { LOG.warn('not init (or already disposed), cannot connect to server'); return; } if (l_connector === undefined) l_connector = new SR.Connector(l_config); // establish connection LOG.warn('connecting to: ' + l_ip_port); l_connector.connect(l_ip_port, function (err, socket) { if (err) { // try-again later LOG.warn('attempt to re-connect in: ' + l_timeoutConnectRetry + 'ms'); setTimeout(l_connect, l_timeoutConnectRetry); return; } LOG.warn('connection to: ' + socket.host + ':' + socket.port + ' established'); l_connector.send('SR_REGISTER_SERVER', l_para, 'SR_REGISTER_SERVER_R', function (res) { console.log(res.data); }); }); }
javascript
function () { if (l_ip_port === undefined) { LOG.warn('not init (or already disposed), cannot connect to server'); return; } if (l_connector === undefined) l_connector = new SR.Connector(l_config); // establish connection LOG.warn('connecting to: ' + l_ip_port); l_connector.connect(l_ip_port, function (err, socket) { if (err) { // try-again later LOG.warn('attempt to re-connect in: ' + l_timeoutConnectRetry + 'ms'); setTimeout(l_connect, l_timeoutConnectRetry); return; } LOG.warn('connection to: ' + socket.host + ':' + socket.port + ' established'); l_connector.send('SR_REGISTER_SERVER', l_para, 'SR_REGISTER_SERVER_R', function (res) { console.log(res.data); }); }); }
[ "function", "(", ")", "{", "if", "(", "l_ip_port", "===", "undefined", ")", "{", "LOG", ".", "warn", "(", "'not init (or already disposed), cannot connect to server'", ")", ";", "return", ";", "}", "if", "(", "l_connector", "===", "undefined", ")", "l_connector", "=", "new", "SR", ".", "Connector", "(", "l_config", ")", ";", "LOG", ".", "warn", "(", "'connecting to: '", "+", "l_ip_port", ")", ";", "l_connector", ".", "connect", "(", "l_ip_port", ",", "function", "(", "err", ",", "socket", ")", "{", "if", "(", "err", ")", "{", "LOG", ".", "warn", "(", "'attempt to re-connect in: '", "+", "l_timeoutConnectRetry", "+", "'ms'", ")", ";", "setTimeout", "(", "l_connect", ",", "l_timeoutConnectRetry", ")", ";", "return", ";", "}", "LOG", ".", "warn", "(", "'connection to: '", "+", "socket", ".", "host", "+", "':'", "+", "socket", ".", "port", "+", "' established'", ")", ";", "l_connector", ".", "send", "(", "'SR_REGISTER_SERVER'", ",", "l_para", ",", "'SR_REGISTER_SERVER_R'", ",", "function", "(", "res", ")", "{", "console", ".", "log", "(", "res", ".", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
connect to cloud server
[ "connect", "to", "cloud", "server" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/modules/cloud_connector.js#L36-L62
train
imonology/scalra
monitor/REST_handle.js
function (res, res_obj) { // return response if exist, otherwise response might be returned // AFTER some callback is done handling (i.e., response will be returned within the handler) if (typeof res_obj === 'string') { LOG.sys('replying a string: ' + res_obj); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(res_obj); } else { LOG.sys('replying a JSON: ' + JSON.stringify(res_obj)); res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(res_obj)); } }
javascript
function (res, res_obj) { // return response if exist, otherwise response might be returned // AFTER some callback is done handling (i.e., response will be returned within the handler) if (typeof res_obj === 'string') { LOG.sys('replying a string: ' + res_obj); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(res_obj); } else { LOG.sys('replying a JSON: ' + JSON.stringify(res_obj)); res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(res_obj)); } }
[ "function", "(", "res", ",", "res_obj", ")", "{", "if", "(", "typeof", "res_obj", "===", "'string'", ")", "{", "LOG", ".", "sys", "(", "'replying a string: '", "+", "res_obj", ")", ";", "res", ".", "writeHead", "(", "200", ",", "{", "'Content-Type'", ":", "'text/plain'", "}", ")", ";", "res", ".", "end", "(", "res_obj", ")", ";", "}", "else", "{", "LOG", ".", "sys", "(", "'replying a JSON: '", "+", "JSON", ".", "stringify", "(", "res_obj", ")", ")", ";", "res", ".", "writeHead", "(", "200", ",", "{", "'Content-Type'", ":", "'application/json'", "}", ")", ";", "res", ".", "end", "(", "JSON", ".", "stringify", "(", "res_obj", ")", ")", ";", "}", "}" ]
helper code send back response to client
[ "helper", "code", "send", "back", "response", "to", "client" ]
0cf7377d02bf1e6beb90d6821c144eefb89feaa9
https://github.com/imonology/scalra/blob/0cf7377d02bf1e6beb90d6821c144eefb89feaa9/monitor/REST_handle.js#L31-L45
train