id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
54,000
anoopchaurasia/jsfm
jsfm.js
separeteMethodsAndFields
function separeteMethodsAndFields( obj ) { var methods = [], fields = {}; eachPropertyOf(obj, function( v, k ) { if (typeof v == 'function') { methods.push(k + ""); } else { fields[k + ""] = v; } }); obj = undefined; return { methods : methods, fields : fields }; }
javascript
function separeteMethodsAndFields( obj ) { var methods = [], fields = {}; eachPropertyOf(obj, function( v, k ) { if (typeof v == 'function') { methods.push(k + ""); } else { fields[k + ""] = v; } }); obj = undefined; return { methods : methods, fields : fields }; }
[ "function", "separeteMethodsAndFields", "(", "obj", ")", "{", "var", "methods", "=", "[", "]", ",", "fields", "=", "{", "}", ";", "eachPropertyOf", "(", "obj", ",", "function", "(", "v", ",", "k", ")", "{", "if", "(", "typeof", "v", "==", "'function'", ")", "{", "methods", ".", "push", "(", "k", "+", "\"\"", ")", ";", "}", "else", "{", "fields", "[", "k", "+", "\"\"", "]", "=", "v", ";", "}", "}", ")", ";", "obj", "=", "undefined", ";", "return", "{", "methods", ":", "methods", ",", "fields", ":", "fields", "}", ";", "}" ]
Separate all methods and fields of object;
[ "Separate", "all", "methods", "and", "fields", "of", "object", ";" ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L1051-L1066
54,001
anoopchaurasia/jsfm
jsfm.js
getAllImportClass
function getAllImportClass( imp ) { var newImports = {}, splited; for ( var k = 0; imp && k < imp.length; k++) { splited = imp[k].split("."); newImports[splited[splited.length - 1]] = fm.stringToObject(imp[k]); } return newImports; }
javascript
function getAllImportClass( imp ) { var newImports = {}, splited; for ( var k = 0; imp && k < imp.length; k++) { splited = imp[k].split("."); newImports[splited[splited.length - 1]] = fm.stringToObject(imp[k]); } return newImports; }
[ "function", "getAllImportClass", "(", "imp", ")", "{", "var", "newImports", "=", "{", "}", ",", "splited", ";", "for", "(", "var", "k", "=", "0", ";", "imp", "&&", "k", "<", "imp", ".", "length", ";", "k", "++", ")", "{", "splited", "=", "imp", "[", "k", "]", ".", "split", "(", "\".\"", ")", ";", "newImports", "[", "splited", "[", "splited", ".", "length", "-", "1", "]", "]", "=", "fm", ".", "stringToObject", "(", "imp", "[", "k", "]", ")", ";", "}", "return", "newImports", ";", "}" ]
return all imported classes string into object
[ "return", "all", "imported", "classes", "string", "into", "object" ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L1080-L1087
54,002
anoopchaurasia/jsfm
jsfm.js
addExtras
function addExtras( currentObj, baseObj, fn ) { // Return function name. var clss = currentObj.getClass(); for ( var k in currentObj) { if (currentObj.hasOwnProperty(k) && typeof currentObj[k] == 'function' && k != fn) { currentObj[k] = currentObj[k].bind(currentObj); currentObj[k].$name = k; currentObj[k].$Class = clss; } } addInstance(currentObj); // eachPropertyOf(currentObj.Private, function(val, key){ if (currentObj.Private && typeof currentObj.Private[fn] == 'function') { currentObj[fn] = currentObj.Private[fn]; } if (currentObj[fn]) { currentObj[fn].$Class = currentObj.getClass(); currentObj[fn].$name = fn; } // Check if function have constant. if (currentObj.Const) { var cnt = currentObj.Const; delete cnt.Static; for (k in cnt) { cnt.hasOwnProperty(k) && currentObj.$add(currentObj, k, cnt[k], true); } } // migrate information about abstract method to base class. if (currentObj.isAbstract) { var absMethods = currentObj.prototype.$get("Abstract"); currentObj.setAbstractMethods = function( solidObj ) { for ( var k in absMethods) { if (absMethods.hasOwnProperty(k)) { if (typeof solidObj[k] != 'function') { throw "Abstract method " + k + " is not implemented by " + solidObj.getClass(); } this[k] = solidObj[k]; } } if (baseObj && baseObj.prototype.isAbstract) { baseObj.prototype.setAbstractMethods(solidObj); } }; } if (baseObj) { if (baseObj.prototype.isAbstract) { baseObj.prototype.getSub = function( ) { return currentObj.isAbstract ? currentObj.getSub() : currentObj; }; } currentObj.base = baseObj; baseObj.$ADD(currentObj); } }
javascript
function addExtras( currentObj, baseObj, fn ) { // Return function name. var clss = currentObj.getClass(); for ( var k in currentObj) { if (currentObj.hasOwnProperty(k) && typeof currentObj[k] == 'function' && k != fn) { currentObj[k] = currentObj[k].bind(currentObj); currentObj[k].$name = k; currentObj[k].$Class = clss; } } addInstance(currentObj); // eachPropertyOf(currentObj.Private, function(val, key){ if (currentObj.Private && typeof currentObj.Private[fn] == 'function') { currentObj[fn] = currentObj.Private[fn]; } if (currentObj[fn]) { currentObj[fn].$Class = currentObj.getClass(); currentObj[fn].$name = fn; } // Check if function have constant. if (currentObj.Const) { var cnt = currentObj.Const; delete cnt.Static; for (k in cnt) { cnt.hasOwnProperty(k) && currentObj.$add(currentObj, k, cnt[k], true); } } // migrate information about abstract method to base class. if (currentObj.isAbstract) { var absMethods = currentObj.prototype.$get("Abstract"); currentObj.setAbstractMethods = function( solidObj ) { for ( var k in absMethods) { if (absMethods.hasOwnProperty(k)) { if (typeof solidObj[k] != 'function') { throw "Abstract method " + k + " is not implemented by " + solidObj.getClass(); } this[k] = solidObj[k]; } } if (baseObj && baseObj.prototype.isAbstract) { baseObj.prototype.setAbstractMethods(solidObj); } }; } if (baseObj) { if (baseObj.prototype.isAbstract) { baseObj.prototype.getSub = function( ) { return currentObj.isAbstract ? currentObj.getSub() : currentObj; }; } currentObj.base = baseObj; baseObj.$ADD(currentObj); } }
[ "function", "addExtras", "(", "currentObj", ",", "baseObj", ",", "fn", ")", "{", "// Return function name.", "var", "clss", "=", "currentObj", ".", "getClass", "(", ")", ";", "for", "(", "var", "k", "in", "currentObj", ")", "{", "if", "(", "currentObj", ".", "hasOwnProperty", "(", "k", ")", "&&", "typeof", "currentObj", "[", "k", "]", "==", "'function'", "&&", "k", "!=", "fn", ")", "{", "currentObj", "[", "k", "]", "=", "currentObj", "[", "k", "]", ".", "bind", "(", "currentObj", ")", ";", "currentObj", "[", "k", "]", ".", "$name", "=", "k", ";", "currentObj", "[", "k", "]", ".", "$Class", "=", "clss", ";", "}", "}", "addInstance", "(", "currentObj", ")", ";", "// eachPropertyOf(currentObj.Private, function(val, key){", "if", "(", "currentObj", ".", "Private", "&&", "typeof", "currentObj", ".", "Private", "[", "fn", "]", "==", "'function'", ")", "{", "currentObj", "[", "fn", "]", "=", "currentObj", ".", "Private", "[", "fn", "]", ";", "}", "if", "(", "currentObj", "[", "fn", "]", ")", "{", "currentObj", "[", "fn", "]", ".", "$Class", "=", "currentObj", ".", "getClass", "(", ")", ";", "currentObj", "[", "fn", "]", ".", "$name", "=", "fn", ";", "}", "// Check if function have constant.", "if", "(", "currentObj", ".", "Const", ")", "{", "var", "cnt", "=", "currentObj", ".", "Const", ";", "delete", "cnt", ".", "Static", ";", "for", "(", "k", "in", "cnt", ")", "{", "cnt", ".", "hasOwnProperty", "(", "k", ")", "&&", "currentObj", ".", "$add", "(", "currentObj", ",", "k", ",", "cnt", "[", "k", "]", ",", "true", ")", ";", "}", "}", "// migrate information about abstract method to base class.", "if", "(", "currentObj", ".", "isAbstract", ")", "{", "var", "absMethods", "=", "currentObj", ".", "prototype", ".", "$get", "(", "\"Abstract\"", ")", ";", "currentObj", ".", "setAbstractMethods", "=", "function", "(", "solidObj", ")", "{", "for", "(", "var", "k", "in", "absMethods", ")", "{", "if", "(", "absMethods", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "if", "(", "typeof", "solidObj", "[", "k", "]", "!=", "'function'", ")", "{", "throw", "\"Abstract method \"", "+", "k", "+", "\" is not implemented by \"", "+", "solidObj", ".", "getClass", "(", ")", ";", "}", "this", "[", "k", "]", "=", "solidObj", "[", "k", "]", ";", "}", "}", "if", "(", "baseObj", "&&", "baseObj", ".", "prototype", ".", "isAbstract", ")", "{", "baseObj", ".", "prototype", ".", "setAbstractMethods", "(", "solidObj", ")", ";", "}", "}", ";", "}", "if", "(", "baseObj", ")", "{", "if", "(", "baseObj", ".", "prototype", ".", "isAbstract", ")", "{", "baseObj", ".", "prototype", ".", "getSub", "=", "function", "(", ")", "{", "return", "currentObj", ".", "isAbstract", "?", "currentObj", ".", "getSub", "(", ")", ":", "currentObj", ";", "}", ";", "}", "currentObj", ".", "base", "=", "baseObj", ";", "baseObj", ".", "$ADD", "(", "currentObj", ")", ";", "}", "}" ]
Add extra information into newly created object.
[ "Add", "extra", "information", "into", "newly", "created", "object", "." ]
20ca3bd7417008c331285237e64b106c30887e36
https://github.com/anoopchaurasia/jsfm/blob/20ca3bd7417008c331285237e64b106c30887e36/jsfm.js#L1241-L1297
54,003
linyngfly/omelo
lib/connectors/commands/heartbeat.js
function(opts) { opts = opts || {}; this.heartbeat = null; this.timeout = null; this.disconnectOnTimeout = opts.disconnectOnTimeout; if(opts.heartbeat) { this.heartbeat = opts.heartbeat * 1000; // heartbeat interval this.timeout = opts.timeout * 1000 || this.heartbeat * 2; // max heartbeat message timeout this.disconnectOnTimeout = true; } this.timeouts = {}; this.clients = {}; }
javascript
function(opts) { opts = opts || {}; this.heartbeat = null; this.timeout = null; this.disconnectOnTimeout = opts.disconnectOnTimeout; if(opts.heartbeat) { this.heartbeat = opts.heartbeat * 1000; // heartbeat interval this.timeout = opts.timeout * 1000 || this.heartbeat * 2; // max heartbeat message timeout this.disconnectOnTimeout = true; } this.timeouts = {}; this.clients = {}; }
[ "function", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "heartbeat", "=", "null", ";", "this", ".", "timeout", "=", "null", ";", "this", ".", "disconnectOnTimeout", "=", "opts", ".", "disconnectOnTimeout", ";", "if", "(", "opts", ".", "heartbeat", ")", "{", "this", ".", "heartbeat", "=", "opts", ".", "heartbeat", "*", "1000", ";", "// heartbeat interval", "this", ".", "timeout", "=", "opts", ".", "timeout", "*", "1000", "||", "this", ".", "heartbeat", "*", "2", ";", "// max heartbeat message timeout", "this", ".", "disconnectOnTimeout", "=", "true", ";", "}", "this", ".", "timeouts", "=", "{", "}", ";", "this", ".", "clients", "=", "{", "}", ";", "}" ]
Process heartbeat request. @param {Object} opts option request opts.heartbeat heartbeat interval
[ "Process", "heartbeat", "request", "." ]
fb5f79fa31c69de36bd1c370bad5edfa753ca601
https://github.com/linyngfly/omelo/blob/fb5f79fa31c69de36bd1c370bad5edfa753ca601/lib/connectors/commands/heartbeat.js#L10-L24
54,004
meyfa/fs-adapters
lib/memory.js
MemoryAdapter
function MemoryAdapter(initialFiles) { if (!(this instanceof MemoryAdapter)) { return new MemoryAdapter(initialFiles); } this.entries = new Map(); // load initial file buffers if (typeof initialFiles === "object" && initialFiles) { Object.keys(initialFiles).forEach((fileName) => { const buf = Buffer.from(initialFiles[fileName]); this.entries.set(fileName, buf); }); } }
javascript
function MemoryAdapter(initialFiles) { if (!(this instanceof MemoryAdapter)) { return new MemoryAdapter(initialFiles); } this.entries = new Map(); // load initial file buffers if (typeof initialFiles === "object" && initialFiles) { Object.keys(initialFiles).forEach((fileName) => { const buf = Buffer.from(initialFiles[fileName]); this.entries.set(fileName, buf); }); } }
[ "function", "MemoryAdapter", "(", "initialFiles", ")", "{", "if", "(", "!", "(", "this", "instanceof", "MemoryAdapter", ")", ")", "{", "return", "new", "MemoryAdapter", "(", "initialFiles", ")", ";", "}", "this", ".", "entries", "=", "new", "Map", "(", ")", ";", "// load initial file buffers", "if", "(", "typeof", "initialFiles", "===", "\"object\"", "&&", "initialFiles", ")", "{", "Object", ".", "keys", "(", "initialFiles", ")", ".", "forEach", "(", "(", "fileName", ")", "=>", "{", "const", "buf", "=", "Buffer", ".", "from", "(", "initialFiles", "[", "fileName", "]", ")", ";", "this", ".", "entries", ".", "set", "(", "fileName", ",", "buf", ")", ";", "}", ")", ";", "}", "}" ]
Construct a new MemoryAdapter. @param {Object.<string, Buffer>} initialFiles The files already in this virtual directory. @constructor
[ "Construct", "a", "new", "MemoryAdapter", "." ]
20708bcc4512da1931cfb97a14a840d369ba1311
https://github.com/meyfa/fs-adapters/blob/20708bcc4512da1931cfb97a14a840d369ba1311/lib/memory.js#L18-L32
54,005
erizocosmico/node-cordova
index.js
function (cmd, cwd, callback) { var async = typeof callback === 'function'; var result = exec( cmd, {cwd: cwd}, async ? callback : undefined ); return result.code !== 0 && !async ? result.stdout : undefined; }
javascript
function (cmd, cwd, callback) { var async = typeof callback === 'function'; var result = exec( cmd, {cwd: cwd}, async ? callback : undefined ); return result.code !== 0 && !async ? result.stdout : undefined; }
[ "function", "(", "cmd", ",", "cwd", ",", "callback", ")", "{", "var", "async", "=", "typeof", "callback", "===", "'function'", ";", "var", "result", "=", "exec", "(", "cmd", ",", "{", "cwd", ":", "cwd", "}", ",", "async", "?", "callback", ":", "undefined", ")", ";", "return", "result", ".", "code", "!==", "0", "&&", "!", "async", "?", "result", ".", "stdout", ":", "undefined", ";", "}" ]
Executes a terminal command @param {String} cmd Command to execute @param {String} cwd Current working directory @param {Function} callback Callback only if the command is async @return {String|undefined}
[ "Executes", "a", "terminal", "command" ]
e5244dc6a2093b0b2593b6741e72aba40eef0254
https://github.com/erizocosmico/node-cordova/blob/e5244dc6a2093b0b2593b6741e72aba40eef0254/index.js#L22-L32
54,006
erizocosmico/node-cordova
index.js
function () { return [CORDOVA_PATH] .concat(Array.prototype.map.call(arguments || [], function (arg) { return '\'' + arg.replace("'", "\\'") + '\''; })).join(' '); }
javascript
function () { return [CORDOVA_PATH] .concat(Array.prototype.map.call(arguments || [], function (arg) { return '\'' + arg.replace("'", "\\'") + '\''; })).join(' '); }
[ "function", "(", ")", "{", "return", "[", "CORDOVA_PATH", "]", ".", "concat", "(", "Array", ".", "prototype", ".", "map", ".", "call", "(", "arguments", "||", "[", "]", ",", "function", "(", "arg", ")", "{", "return", "'\\''", "+", "arg", ".", "replace", "(", "\"'\"", ",", "\"\\\\'\"", ")", "+", "'\\''", ";", "}", ")", ")", ".", "join", "(", "' '", ")", ";", "}" ]
Builds a command escaping all command parts @return {String} Final command
[ "Builds", "a", "command", "escaping", "all", "command", "parts" ]
e5244dc6a2093b0b2593b6741e72aba40eef0254
https://github.com/erizocosmico/node-cordova/blob/e5244dc6a2093b0b2593b6741e72aba40eef0254/index.js#L38-L43
54,007
teabyii/qa
lib/prompts/list.js
moveRender
function moveRender (type) { var method = type ? 'down' : 'up' ui .left(lastLen + 2) .up(count - cur) .write(' ') // Each time move to right-bottom. ui[method]() .left(2) .write(chalk.blue(pointer)) .left(2) .down(count - (type ? ++cur : --cur)) .right(lastLen + 2) }
javascript
function moveRender (type) { var method = type ? 'down' : 'up' ui .left(lastLen + 2) .up(count - cur) .write(' ') // Each time move to right-bottom. ui[method]() .left(2) .write(chalk.blue(pointer)) .left(2) .down(count - (type ? ++cur : --cur)) .right(lastLen + 2) }
[ "function", "moveRender", "(", "type", ")", "{", "var", "method", "=", "type", "?", "'down'", ":", "'up'", "ui", ".", "left", "(", "lastLen", "+", "2", ")", ".", "up", "(", "count", "-", "cur", ")", ".", "write", "(", "' '", ")", "// Each time move to right-bottom.", "ui", "[", "method", "]", "(", ")", ".", "left", "(", "2", ")", ".", "write", "(", "chalk", ".", "blue", "(", "pointer", ")", ")", ".", "left", "(", "2", ")", ".", "down", "(", "count", "-", "(", "type", "?", "++", "cur", ":", "--", "cur", ")", ")", ".", "right", "(", "lastLen", "+", "2", ")", "}" ]
Move cursor and render pointer, type 0 for up, 1 for down.
[ "Move", "cursor", "and", "render", "pointer", "type", "0", "for", "up", "1", "for", "down", "." ]
9224180dcb9e6b57c021f83b259316e84ebc573e
https://github.com/teabyii/qa/blob/9224180dcb9e6b57c021f83b259316e84ebc573e/lib/prompts/list.js#L62-L77
54,008
aledbf/deis-api
lib/auth.js
cancel
function cancel(callback) { if (!deis._authenticated) { return callback(new Error('You need to login first')); } commons.del(format('/%s/auth/cancel/', deis.version), function() { deis.api.logout(callback); }); }
javascript
function cancel(callback) { if (!deis._authenticated) { return callback(new Error('You need to login first')); } commons.del(format('/%s/auth/cancel/', deis.version), function() { deis.api.logout(callback); }); }
[ "function", "cancel", "(", "callback", ")", "{", "if", "(", "!", "deis", ".", "_authenticated", ")", "{", "return", "callback", "(", "new", "Error", "(", "'You need to login first'", ")", ")", ";", "}", "commons", ".", "del", "(", "format", "(", "'/%s/auth/cancel/'", ",", "deis", ".", "version", ")", ",", "function", "(", ")", "{", "deis", ".", "api", ".", "logout", "(", "callback", ")", ";", "}", ")", ";", "}" ]
remove the account currently logged
[ "remove", "the", "account", "currently", "logged" ]
f0833789998032b11221a3a617bb566ade1fcc13
https://github.com/aledbf/deis-api/blob/f0833789998032b11221a3a617bb566ade1fcc13/lib/auth.js#L11-L19
54,009
AndreasMadsen/steer
steer.js
createProfile
function createProfile(done) { if (self.closed) return done(null); temp.mkdir('browser-controller', function(err, dirpath) { if (err) return done(err); self.userDir = dirpath; done(null); }); }
javascript
function createProfile(done) { if (self.closed) return done(null); temp.mkdir('browser-controller', function(err, dirpath) { if (err) return done(err); self.userDir = dirpath; done(null); }); }
[ "function", "createProfile", "(", "done", ")", "{", "if", "(", "self", ".", "closed", ")", "return", "done", "(", "null", ")", ";", "temp", ".", "mkdir", "(", "'browser-controller'", ",", "function", "(", "err", ",", "dirpath", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "self", ".", "userDir", "=", "dirpath", ";", "done", "(", "null", ")", ";", "}", ")", ";", "}" ]
create a chrome profile directory
[ "create", "a", "chrome", "profile", "directory" ]
5f19587abb1d6384bcff3e4bdede1fdce178d7b2
https://github.com/AndreasMadsen/steer/blob/5f19587abb1d6384bcff3e4bdede1fdce178d7b2/steer.js#L66-L76
54,010
AndreasMadsen/steer
steer.js
closeChromium
function closeChromium(done) { var child = self.process; // remove error handlers if (child) { child.removeListener('error', handlers.relayError); child.removeListener('exit', handlers.prematureExit); child.stderr.removeListener('error', handlers.relayError); child.stdout.removeListener('error', handlers.relayError); } // kill chromium if (isKilled(child) === false) { // make sure stdout & stderr isn't paused, since the child won't // emit 'close' until the file descriptors are destroyed child.stdout.resume(); child.stderr.resume(); child.once('close', done); child.kill(); } else { done(null); } }
javascript
function closeChromium(done) { var child = self.process; // remove error handlers if (child) { child.removeListener('error', handlers.relayError); child.removeListener('exit', handlers.prematureExit); child.stderr.removeListener('error', handlers.relayError); child.stdout.removeListener('error', handlers.relayError); } // kill chromium if (isKilled(child) === false) { // make sure stdout & stderr isn't paused, since the child won't // emit 'close' until the file descriptors are destroyed child.stdout.resume(); child.stderr.resume(); child.once('close', done); child.kill(); } else { done(null); } }
[ "function", "closeChromium", "(", "done", ")", "{", "var", "child", "=", "self", ".", "process", ";", "// remove error handlers", "if", "(", "child", ")", "{", "child", ".", "removeListener", "(", "'error'", ",", "handlers", ".", "relayError", ")", ";", "child", ".", "removeListener", "(", "'exit'", ",", "handlers", ".", "prematureExit", ")", ";", "child", ".", "stderr", ".", "removeListener", "(", "'error'", ",", "handlers", ".", "relayError", ")", ";", "child", ".", "stdout", ".", "removeListener", "(", "'error'", ",", "handlers", ".", "relayError", ")", ";", "}", "// kill chromium", "if", "(", "isKilled", "(", "child", ")", "===", "false", ")", "{", "// make sure stdout & stderr isn't paused, since the child won't", "// emit 'close' until the file descriptors are destroyed", "child", ".", "stdout", ".", "resume", "(", ")", ";", "child", ".", "stderr", ".", "resume", "(", ")", ";", "child", ".", "once", "(", "'close'", ",", "done", ")", ";", "child", ".", "kill", "(", ")", ";", "}", "else", "{", "done", "(", "null", ")", ";", "}", "}" ]
if browser is alive, kill it
[ "if", "browser", "is", "alive", "kill", "it" ]
5f19587abb1d6384bcff3e4bdede1fdce178d7b2
https://github.com/AndreasMadsen/steer/blob/5f19587abb1d6384bcff3e4bdede1fdce178d7b2/steer.js#L282-L304
54,011
AndreasMadsen/steer
steer.js
removePofile
function removePofile(done) { if (!self.userDir) return done(null); rimraf(self.userDir, done); }
javascript
function removePofile(done) { if (!self.userDir) return done(null); rimraf(self.userDir, done); }
[ "function", "removePofile", "(", "done", ")", "{", "if", "(", "!", "self", ".", "userDir", ")", "return", "done", "(", "null", ")", ";", "rimraf", "(", "self", ".", "userDir", ",", "done", ")", ";", "}" ]
cleanup profile directory
[ "cleanup", "profile", "directory" ]
5f19587abb1d6384bcff3e4bdede1fdce178d7b2
https://github.com/AndreasMadsen/steer/blob/5f19587abb1d6384bcff3e4bdede1fdce178d7b2/steer.js#L329-L333
54,012
glennschler/spotspec
lib/service.js
SvcAws
function SvcAws (requestedSvc, options) { if (this.constructor.name === 'Object') { throw new Error('Must be instantiated using new') } else if (this.constructor.name === 'SvcAws') { throw new Error('Abstract class ' + this.constructor.name + ' should not be instantiated') } EventEmitter.call(this) let self = this // initialize the property bag of AWS services which will be created this._services = {} let credOptions = Object.assign({}, options) internals.initLogger(options.isLogging) this.logger = internals.logger credOptions.logger = this.logger let credsManager = new Credentials(credOptions) credsManager.once(internals.EVENT_INITIALIZED, function (err, data) { if (err) { self.logger.warn(internals.EVENT_INITIALIZED, err) internals.emitAsync.call(self, internals.EVENT_INITIALIZED, err) return } else { self.logger.info(internals.EVENT_INITIALIZED, 'success') } if (self._services.hasOwnProperty(requestedSvc.serviceIdentifier)) { let serviceName = requestedSvc.serviceIdentifier self.logger.info('Refreshing service: ' + serviceName) } // Always instantiate the requested aws service, even if old one exists internals.newService.call(self, credsManager._awsConfig, requestedSvc) }) }
javascript
function SvcAws (requestedSvc, options) { if (this.constructor.name === 'Object') { throw new Error('Must be instantiated using new') } else if (this.constructor.name === 'SvcAws') { throw new Error('Abstract class ' + this.constructor.name + ' should not be instantiated') } EventEmitter.call(this) let self = this // initialize the property bag of AWS services which will be created this._services = {} let credOptions = Object.assign({}, options) internals.initLogger(options.isLogging) this.logger = internals.logger credOptions.logger = this.logger let credsManager = new Credentials(credOptions) credsManager.once(internals.EVENT_INITIALIZED, function (err, data) { if (err) { self.logger.warn(internals.EVENT_INITIALIZED, err) internals.emitAsync.call(self, internals.EVENT_INITIALIZED, err) return } else { self.logger.info(internals.EVENT_INITIALIZED, 'success') } if (self._services.hasOwnProperty(requestedSvc.serviceIdentifier)) { let serviceName = requestedSvc.serviceIdentifier self.logger.info('Refreshing service: ' + serviceName) } // Always instantiate the requested aws service, even if old one exists internals.newService.call(self, credsManager._awsConfig, requestedSvc) }) }
[ "function", "SvcAws", "(", "requestedSvc", ",", "options", ")", "{", "if", "(", "this", ".", "constructor", ".", "name", "===", "'Object'", ")", "{", "throw", "new", "Error", "(", "'Must be instantiated using new'", ")", "}", "else", "if", "(", "this", ".", "constructor", ".", "name", "===", "'SvcAws'", ")", "{", "throw", "new", "Error", "(", "'Abstract class '", "+", "this", ".", "constructor", ".", "name", "+", "' should not be instantiated'", ")", "}", "EventEmitter", ".", "call", "(", "this", ")", "let", "self", "=", "this", "// initialize the property bag of AWS services which will be created", "this", ".", "_services", "=", "{", "}", "let", "credOptions", "=", "Object", ".", "assign", "(", "{", "}", ",", "options", ")", "internals", ".", "initLogger", "(", "options", ".", "isLogging", ")", "this", ".", "logger", "=", "internals", ".", "logger", "credOptions", ".", "logger", "=", "this", ".", "logger", "let", "credsManager", "=", "new", "Credentials", "(", "credOptions", ")", "credsManager", ".", "once", "(", "internals", ".", "EVENT_INITIALIZED", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "self", ".", "logger", ".", "warn", "(", "internals", ".", "EVENT_INITIALIZED", ",", "err", ")", "internals", ".", "emitAsync", ".", "call", "(", "self", ",", "internals", ".", "EVENT_INITIALIZED", ",", "err", ")", "return", "}", "else", "{", "self", ".", "logger", ".", "info", "(", "internals", ".", "EVENT_INITIALIZED", ",", "'success'", ")", "}", "if", "(", "self", ".", "_services", ".", "hasOwnProperty", "(", "requestedSvc", ".", "serviceIdentifier", ")", ")", "{", "let", "serviceName", "=", "requestedSvc", ".", "serviceIdentifier", "self", ".", "logger", ".", "info", "(", "'Refreshing service: '", "+", "serviceName", ")", "}", "// Always instantiate the requested aws service, even if old one exists", "internals", ".", "newService", ".", "call", "(", "self", ",", "credsManager", ".", "_awsConfig", ",", "requestedSvc", ")", "}", ")", "}" ]
Constructs a new SvcAws object for managing aws credentials @constructor @abstract @arg {class} requestedSvc - The AWS.Service class to instantiate [aws docs]{@link http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Service.html} @arg {object} options - The AWS service IAM credentials @arg {object} options.keys - Credentials for the service API authentication. See [aws docs]{@link http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html} @arg {string} options.keys.accessKeyId - AWS access key ID @arg {string} options.keys.secretAccessKey - AWS secret access key @arg {string} options.keys.region - The EC2 region to send service requests @arg {object} options.upgrade - Temporary Session Token credentials. See [aws docs]{@link http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/STS.html#getSessionToken-property} @arg {string} options.upgrade.serialNumber - Identifies the user's hardware or virtual MFA device @arg {number} options.upgrade.tokenCode - Time-based one-time password (TOTP) that the MFA devices produces @arg {number} [options.upgrade.durationSeconds=900] - The duration, in seconds, that the credentials should remain valid @arg {boolean} [options.isLogging=false] - Use internal logging @throws {error} @emits {intialized}
[ "Constructs", "a", "new", "SvcAws", "object", "for", "managing", "aws", "credentials" ]
ca6f5b17b84b3536b6b2ce9a472d5ae91c8cd727
https://github.com/glennschler/spotspec/blob/ca6f5b17b84b3536b6b2ce9a472d5ae91c8cd727/lib/service.js#L75-L114
54,013
mitchallen/maze-generator-core
modules/index.js
function(x,y,depth,maxDepth) { if( depth >= maxDepth ) { console.warn("MAXIMUM DEPTH REACHED: %d", maxDepth); return; } if(!this.isCell(x,y)) { return; } let dirs = this.getShuffledNeighborDirs( x, y ); for( var key in dirs ) { var sDir = dirs[key]; var n = this.getNeighbor(x, y, sDir); if(n===null) { continue; } if(this.isMasked(n.x,n.y)) { continue; } if( this.isCell(n.x, n.y) && !this.hasConnections(n.x, n.y) ) { // Connect cell to neighbor this.connectUndirected( x, y, sDir); this.carveMaze( n.x, n.y, depth + 1, maxDepth ); } } }
javascript
function(x,y,depth,maxDepth) { if( depth >= maxDepth ) { console.warn("MAXIMUM DEPTH REACHED: %d", maxDepth); return; } if(!this.isCell(x,y)) { return; } let dirs = this.getShuffledNeighborDirs( x, y ); for( var key in dirs ) { var sDir = dirs[key]; var n = this.getNeighbor(x, y, sDir); if(n===null) { continue; } if(this.isMasked(n.x,n.y)) { continue; } if( this.isCell(n.x, n.y) && !this.hasConnections(n.x, n.y) ) { // Connect cell to neighbor this.connectUndirected( x, y, sDir); this.carveMaze( n.x, n.y, depth + 1, maxDepth ); } } }
[ "function", "(", "x", ",", "y", ",", "depth", ",", "maxDepth", ")", "{", "if", "(", "depth", ">=", "maxDepth", ")", "{", "console", ".", "warn", "(", "\"MAXIMUM DEPTH REACHED: %d\"", ",", "maxDepth", ")", ";", "return", ";", "}", "if", "(", "!", "this", ".", "isCell", "(", "x", ",", "y", ")", ")", "{", "return", ";", "}", "let", "dirs", "=", "this", ".", "getShuffledNeighborDirs", "(", "x", ",", "y", ")", ";", "for", "(", "var", "key", "in", "dirs", ")", "{", "var", "sDir", "=", "dirs", "[", "key", "]", ";", "var", "n", "=", "this", ".", "getNeighbor", "(", "x", ",", "y", ",", "sDir", ")", ";", "if", "(", "n", "===", "null", ")", "{", "continue", ";", "}", "if", "(", "this", ".", "isMasked", "(", "n", ".", "x", ",", "n", ".", "y", ")", ")", "{", "continue", ";", "}", "if", "(", "this", ".", "isCell", "(", "n", ".", "x", ",", "n", ".", "y", ")", "&&", "!", "this", ".", "hasConnections", "(", "n", ".", "x", ",", "n", ".", "y", ")", ")", "{", "// Connect cell to neighbor", "this", ".", "connectUndirected", "(", "x", ",", "y", ",", "sDir", ")", ";", "this", ".", "carveMaze", "(", "n", ".", "x", ",", "n", ".", "y", ",", "depth", "+", "1", ",", "maxDepth", ")", ";", "}", "}", "}" ]
leave undocumented for now
[ "leave", "undocumented", "for", "now" ]
dddf3f2645dd8719b5361bbbba99dcf44b54fd14
https://github.com/mitchallen/maze-generator-core/blob/dddf3f2645dd8719b5361bbbba99dcf44b54fd14/modules/index.js#L55-L83
54,014
mitchallen/maze-generator-core
modules/index.js
function(spec) { spec = spec || {}; let aMask = spec.mask || [], start = spec.start || {}, x = start.c || 0, y = start.r || 0; this.fill(0); for( var mKey in aMask ) { var mask = aMask[mKey]; this.mask(mask.c,mask.r); } let maxDepth = this.xSize * this.ySize; this.carveMaze(x,y,0,maxDepth); // derived class can parse extra spec parameters this.afterGenerate(spec); }
javascript
function(spec) { spec = spec || {}; let aMask = spec.mask || [], start = spec.start || {}, x = start.c || 0, y = start.r || 0; this.fill(0); for( var mKey in aMask ) { var mask = aMask[mKey]; this.mask(mask.c,mask.r); } let maxDepth = this.xSize * this.ySize; this.carveMaze(x,y,0,maxDepth); // derived class can parse extra spec parameters this.afterGenerate(spec); }
[ "function", "(", "spec", ")", "{", "spec", "=", "spec", "||", "{", "}", ";", "let", "aMask", "=", "spec", ".", "mask", "||", "[", "]", ",", "start", "=", "spec", ".", "start", "||", "{", "}", ",", "x", "=", "start", ".", "c", "||", "0", ",", "y", "=", "start", ".", "r", "||", "0", ";", "this", ".", "fill", "(", "0", ")", ";", "for", "(", "var", "mKey", "in", "aMask", ")", "{", "var", "mask", "=", "aMask", "[", "mKey", "]", ";", "this", ".", "mask", "(", "mask", ".", "c", ",", "mask", ".", "r", ")", ";", "}", "let", "maxDepth", "=", "this", ".", "xSize", "*", "this", ".", "ySize", ";", "this", ".", "carveMaze", "(", "x", ",", "y", ",", "0", ",", "maxDepth", ")", ";", "// derived class can parse extra spec parameters", "this", ".", "afterGenerate", "(", "spec", ")", ";", "}" ]
Generators a maze @param {Object} options Named parameters for generating a maze @param {Array} options.mask An array of cells to mask off from maze generation @param {Array} options.open An array of objects designation what borders to open after generation @param {Object} opions.start An object containing the x and y parameter of a cell to start maze generation from. @function @instance @memberof module:maze-generator-core @returns {boolean} @example <caption>generate</caption> maze.generate(); @example <caption>mask</caption> let spec = { mask: [ { c: 2, r: 3 }, { c: 2, r: 4 } ] }; mazeGenerator.generate(spec); @example <caption>start and mask</caption> let spec = { start: { c: 3, r: 3 }, mask: [ { c: 0, r: 0 }, { c: 0, r: 1 }, { c: 1, r: 0 }, { c: 1, r: 1 } ] }; mazeGenerator.generate(spec);
[ "Generators", "a", "maze" ]
dddf3f2645dd8719b5361bbbba99dcf44b54fd14
https://github.com/mitchallen/maze-generator-core/blob/dddf3f2645dd8719b5361bbbba99dcf44b54fd14/modules/index.js#L139-L163
54,015
lewisdawson/slinker
index.js
invokeOnComplete
function invokeOnComplete(slinkerOptions) { if (typeof slinkerOptions.onComplete === 'function' && slinkerOptions.modules.length === symlinksCreated.length) { slinkerOptions.onComplete(); } }
javascript
function invokeOnComplete(slinkerOptions) { if (typeof slinkerOptions.onComplete === 'function' && slinkerOptions.modules.length === symlinksCreated.length) { slinkerOptions.onComplete(); } }
[ "function", "invokeOnComplete", "(", "slinkerOptions", ")", "{", "if", "(", "typeof", "slinkerOptions", ".", "onComplete", "===", "'function'", "&&", "slinkerOptions", ".", "modules", ".", "length", "===", "symlinksCreated", ".", "length", ")", "{", "slinkerOptions", ".", "onComplete", "(", ")", ";", "}", "}" ]
Invoked when slinker has finished creating all symlinks. If an onComplete callback has been specified, it is invoked. @param {Object} slinkerOptions The options passed to slinker
[ "Invoked", "when", "slinker", "has", "finished", "creating", "all", "symlinks", ".", "If", "an", "onComplete", "callback", "has", "been", "specified", "it", "is", "invoked", "." ]
5b2662fc8bd04e6ea910ea7c5b64ccc84341dbbc
https://github.com/lewisdawson/slinker/blob/5b2662fc8bd04e6ea910ea7c5b64ccc84341dbbc/index.js#L69-L73
54,016
lewisdawson/slinker
index.js
checkPreconditions
function checkPreconditions(options) { if (!options) { throw Error("'options' must be specified!"); } if (!(options.modules instanceof Array)) { throw Error("'options.modules' must be an array!"); } // If the modules array is empty, immediately call the onComplete() if it exists if (!options.modules.length) { if (options.onComplete) { invokeOnComplete(options); } return false; } return true; }
javascript
function checkPreconditions(options) { if (!options) { throw Error("'options' must be specified!"); } if (!(options.modules instanceof Array)) { throw Error("'options.modules' must be an array!"); } // If the modules array is empty, immediately call the onComplete() if it exists if (!options.modules.length) { if (options.onComplete) { invokeOnComplete(options); } return false; } return true; }
[ "function", "checkPreconditions", "(", "options", ")", "{", "if", "(", "!", "options", ")", "{", "throw", "Error", "(", "\"'options' must be specified!\"", ")", ";", "}", "if", "(", "!", "(", "options", ".", "modules", "instanceof", "Array", ")", ")", "{", "throw", "Error", "(", "\"'options.modules' must be an array!\"", ")", ";", "}", "// If the modules array is empty, immediately call the onComplete() if it exists", "if", "(", "!", "options", ".", "modules", ".", "length", ")", "{", "if", "(", "options", ".", "onComplete", ")", "{", "invokeOnComplete", "(", "options", ")", ";", "}", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks the preconditions when slinker is invoked. Returns true if all preconditions have been met and slinker should be invoked. options {Object} options The options passed to slinker
[ "Checks", "the", "preconditions", "when", "slinker", "is", "invoked", ".", "Returns", "true", "if", "all", "preconditions", "have", "been", "met", "and", "slinker", "should", "be", "invoked", "." ]
5b2662fc8bd04e6ea910ea7c5b64ccc84341dbbc
https://github.com/lewisdawson/slinker/blob/5b2662fc8bd04e6ea910ea7c5b64ccc84341dbbc/index.js#L97-L116
54,017
tjbutz/class.js
class.js
function() { if (!(this instanceof clazz)) { throw new Error("Use new keyword to create a new instance or call/apply class with right scope"); } Class.onBeforeInstantiation && Class.onBeforeInstantiation(this); // remember the current super property var temp = this.__super__; // set the right super class prototype this.__super__ = superClass; // call the right constructor if (constructor) { constructor.apply(this, arguments); } else if (superClass) { superClass.apply(this, arguments); } // reset the current super property this.__super__ = temp; Class.onAfterInstantiation && Class.onAfterInstantiation(this); }
javascript
function() { if (!(this instanceof clazz)) { throw new Error("Use new keyword to create a new instance or call/apply class with right scope"); } Class.onBeforeInstantiation && Class.onBeforeInstantiation(this); // remember the current super property var temp = this.__super__; // set the right super class prototype this.__super__ = superClass; // call the right constructor if (constructor) { constructor.apply(this, arguments); } else if (superClass) { superClass.apply(this, arguments); } // reset the current super property this.__super__ = temp; Class.onAfterInstantiation && Class.onAfterInstantiation(this); }
[ "function", "(", ")", "{", "if", "(", "!", "(", "this", "instanceof", "clazz", ")", ")", "{", "throw", "new", "Error", "(", "\"Use new keyword to create a new instance or call/apply class with right scope\"", ")", ";", "}", "Class", ".", "onBeforeInstantiation", "&&", "Class", ".", "onBeforeInstantiation", "(", "this", ")", ";", "// remember the current super property", "var", "temp", "=", "this", ".", "__super__", ";", "// set the right super class prototype", "this", ".", "__super__", "=", "superClass", ";", "// call the right constructor", "if", "(", "constructor", ")", "{", "constructor", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "else", "if", "(", "superClass", ")", "{", "superClass", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", "// reset the current super property", "this", ".", "__super__", "=", "temp", ";", "Class", ".", "onAfterInstantiation", "&&", "Class", ".", "onAfterInstantiation", "(", "this", ")", ";", "}" ]
use clazz instead of class as it is a reserved keyword
[ "use", "clazz", "instead", "of", "class", "as", "it", "is", "a", "reserved", "keyword" ]
92914c9b164ede1198b42cc0f210f7c85cd88d69
https://github.com/tjbutz/class.js/blob/92914c9b164ede1198b42cc0f210f7c85cd88d69/class.js#L64-L84
54,018
ForbesLindesay/code-mirror
mode/clojure.js
eatCharacter
function eatCharacter(stream) { var first = stream.next(); // Read special literals: backspace, newline, space, return. // Just read all lowercase letters. if (first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) { return; } // Read unicode character: \u1000 \uA0a1 if (first === "u") { stream.match(/[0-9a-z]{4}/i, true); } }
javascript
function eatCharacter(stream) { var first = stream.next(); // Read special literals: backspace, newline, space, return. // Just read all lowercase letters. if (first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) { return; } // Read unicode character: \u1000 \uA0a1 if (first === "u") { stream.match(/[0-9a-z]{4}/i, true); } }
[ "function", "eatCharacter", "(", "stream", ")", "{", "var", "first", "=", "stream", ".", "next", "(", ")", ";", "// Read special literals: backspace, newline, space, return.", "// Just read all lowercase letters.", "if", "(", "first", ".", "match", "(", "/", "[a-z]", "/", ")", "&&", "stream", ".", "match", "(", "/", "[a-z]+", "/", ",", "true", ")", ")", "{", "return", ";", "}", "// Read unicode character: \\u1000 \\uA0a1", "if", "(", "first", "===", "\"u\"", ")", "{", "stream", ".", "match", "(", "/", "[0-9a-z]{4}", "/", "i", ",", "true", ")", ";", "}", "}" ]
Eat character that starts after backslash \
[ "Eat", "character", "that", "starts", "after", "backslash", "\\" ]
d790ea213aa354756adc7d4d9fcfffcfdc2f1278
https://github.com/ForbesLindesay/code-mirror/blob/d790ea213aa354756adc7d4d9fcfffcfdc2f1278/mode/clojure.js#L100-L111
54,019
MonetDBSolutions/npm-monetdb-import
index.js
__typeCheck
function __typeCheck(type, valueToCheck, optional) { var correct = typeof(valueToCheck) == type; if(optional) { // Exception if the variable is optional, than it also may be undefined or null correct = correct || valueToCheck === undefined || valueToCheck === null; } if(!correct) { throw new Error("Invalid argument type received; expected "+type+ ", but received "+typeof(valueToCheck)); } }
javascript
function __typeCheck(type, valueToCheck, optional) { var correct = typeof(valueToCheck) == type; if(optional) { // Exception if the variable is optional, than it also may be undefined or null correct = correct || valueToCheck === undefined || valueToCheck === null; } if(!correct) { throw new Error("Invalid argument type received; expected "+type+ ", but received "+typeof(valueToCheck)); } }
[ "function", "__typeCheck", "(", "type", ",", "valueToCheck", ",", "optional", ")", "{", "var", "correct", "=", "typeof", "(", "valueToCheck", ")", "==", "type", ";", "if", "(", "optional", ")", "{", "// Exception if the variable is optional, than it also may be undefined or null", "correct", "=", "correct", "||", "valueToCheck", "===", "undefined", "||", "valueToCheck", "===", "null", ";", "}", "if", "(", "!", "correct", ")", "{", "throw", "new", "Error", "(", "\"Invalid argument type received; expected \"", "+", "type", "+", "\", but received \"", "+", "typeof", "(", "valueToCheck", ")", ")", ";", "}", "}" ]
Private functions that are not tied to the Importer object and thus do not use the this keyword
[ "Private", "functions", "that", "are", "not", "tied", "to", "the", "Importer", "object", "and", "thus", "do", "not", "use", "the", "this", "keyword" ]
396acf530d2c822b92a5a918e9e0fb22bd9b2b93
https://github.com/MonetDBSolutions/npm-monetdb-import/blob/396acf530d2c822b92a5a918e9e0fb22bd9b2b93/index.js#L11-L21
54,020
NumminorihSF/bramqp-wrapper
domain/queue.js
Queue
function Queue(client, channel){ EE.call(this); this.client = client; this.channel = channel; this.id = channel.$getId(); return this; }
javascript
function Queue(client, channel){ EE.call(this); this.client = client; this.channel = channel; this.id = channel.$getId(); return this; }
[ "function", "Queue", "(", "client", ",", "channel", ")", "{", "EE", ".", "call", "(", "this", ")", ";", "this", ".", "client", "=", "client", ";", "this", ".", "channel", "=", "channel", ";", "this", ".", "id", "=", "channel", ".", "$getId", "(", ")", ";", "return", "this", ";", "}" ]
Work with queues. Queues store and forward messages. Queues can be configured in the server or created at runtime. Queues must be attached to at least one exchange in order to receive messages from publishers. @param {BRAMQPClient} client Client object that returns from bramqp#openAMQPCommunication() method. @param {Channel} channel Channel object (should be opened). @return {Queue} @extends EventEmitter @constructor @class Queue
[ "Work", "with", "queues", "." ]
3e2bd769a2828f7592eba79556c9ef1491177781
https://github.com/NumminorihSF/bramqp-wrapper/blob/3e2bd769a2828f7592eba79556c9ef1491177781/domain/queue.js#L29-L36
54,021
joemccann/photopipe
public/js/pipe.js
checkForAuths
function checkForAuths(){ $twitter.isAuthenticated = $body.attr('data-twitter-auth') === 'true' ? true : false $facebook.isAuthenticated = $body.attr('data-facebook-auth') === 'true' ? true : false $dropbox.isAuthenticated = $body.attr('data-dropbox-auth') === 'true' ? true : false }
javascript
function checkForAuths(){ $twitter.isAuthenticated = $body.attr('data-twitter-auth') === 'true' ? true : false $facebook.isAuthenticated = $body.attr('data-facebook-auth') === 'true' ? true : false $dropbox.isAuthenticated = $body.attr('data-dropbox-auth') === 'true' ? true : false }
[ "function", "checkForAuths", "(", ")", "{", "$twitter", ".", "isAuthenticated", "=", "$body", ".", "attr", "(", "'data-twitter-auth'", ")", "===", "'true'", "?", "true", ":", "false", "$facebook", ".", "isAuthenticated", "=", "$body", ".", "attr", "(", "'data-facebook-auth'", ")", "===", "'true'", "?", "true", ":", "false", "$dropbox", ".", "isAuthenticated", "=", "$body", ".", "attr", "(", "'data-dropbox-auth'", ")", "===", "'true'", "?", "true", ":", "false", "}" ]
Set some flags for later to see if we are auth'd for said service or not.
[ "Set", "some", "flags", "for", "later", "to", "see", "if", "we", "are", "auth", "d", "for", "said", "service", "or", "not", "." ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L51-L57
54,022
joemccann/photopipe
public/js/pipe.js
wireDestinationClickHandlers
function wireDestinationClickHandlers(){ $twitter.isAuthenticated && $twitterDestination.bind('click', twitterDestinationClickHandler) $facebook.isAuthenticated && $facebookDestination.bind('click', facebookDestinationClickHandler) $dropbox.isAuthenticated && $dropboxDestination.bind('click', dropboxDestinationClickHandler) }
javascript
function wireDestinationClickHandlers(){ $twitter.isAuthenticated && $twitterDestination.bind('click', twitterDestinationClickHandler) $facebook.isAuthenticated && $facebookDestination.bind('click', facebookDestinationClickHandler) $dropbox.isAuthenticated && $dropboxDestination.bind('click', dropboxDestinationClickHandler) }
[ "function", "wireDestinationClickHandlers", "(", ")", "{", "$twitter", ".", "isAuthenticated", "&&", "$twitterDestination", ".", "bind", "(", "'click'", ",", "twitterDestinationClickHandler", ")", "$facebook", ".", "isAuthenticated", "&&", "$facebookDestination", ".", "bind", "(", "'click'", ",", "facebookDestinationClickHandler", ")", "$dropbox", ".", "isAuthenticated", "&&", "$dropboxDestination", ".", "bind", "(", "'click'", ",", "dropboxDestinationClickHandler", ")", "}" ]
Attach click handlers to respective elements.
[ "Attach", "click", "handlers", "to", "respective", "elements", "." ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L77-L83
54,023
joemccann/photopipe
public/js/pipe.js
fetchImagesForFbGallery
function fetchImagesForFbGallery(id){ $ .get('/facebook/get_photos_from_album_id?id='+id) .success(function(d, resp, x){ console.dir(d) var thumbs = "" if(d.message) thumbs += "<p>"+d.message+"</p>" else{ d.data.forEach(function(el,i){ // console.dir(el) thumbs += "<img data-standard-resolution='"+el.images[2].source+"' src='"+el.picture+"' />" }) } $oneUpFacebookWrapper .before(thumbs) $photoPickerFacebook .show() $spin .hide() // wire up the images int the fb gallery wireFacebookGalleryPicker() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) }) .error(function(e){ if(e.status === 404) alert(e.responseText || 'Images were not found.') if(e.status === 403) alert(e.responseText || 'That request was not allowed.') if(e.status === 500) alert(e.responseText || 'Something went really wrong.') }) }
javascript
function fetchImagesForFbGallery(id){ $ .get('/facebook/get_photos_from_album_id?id='+id) .success(function(d, resp, x){ console.dir(d) var thumbs = "" if(d.message) thumbs += "<p>"+d.message+"</p>" else{ d.data.forEach(function(el,i){ // console.dir(el) thumbs += "<img data-standard-resolution='"+el.images[2].source+"' src='"+el.picture+"' />" }) } $oneUpFacebookWrapper .before(thumbs) $photoPickerFacebook .show() $spin .hide() // wire up the images int the fb gallery wireFacebookGalleryPicker() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) }) .error(function(e){ if(e.status === 404) alert(e.responseText || 'Images were not found.') if(e.status === 403) alert(e.responseText || 'That request was not allowed.') if(e.status === 500) alert(e.responseText || 'Something went really wrong.') }) }
[ "function", "fetchImagesForFbGallery", "(", "id", ")", "{", "$", ".", "get", "(", "'/facebook/get_photos_from_album_id?id='", "+", "id", ")", ".", "success", "(", "function", "(", "d", ",", "resp", ",", "x", ")", "{", "console", ".", "dir", "(", "d", ")", "var", "thumbs", "=", "\"\"", "if", "(", "d", ".", "message", ")", "thumbs", "+=", "\"<p>\"", "+", "d", ".", "message", "+", "\"</p>\"", "else", "{", "d", ".", "data", ".", "forEach", "(", "function", "(", "el", ",", "i", ")", "{", "// console.dir(el)", "thumbs", "+=", "\"<img data-standard-resolution='\"", "+", "el", ".", "images", "[", "2", "]", ".", "source", "+", "\"' src='\"", "+", "el", ".", "picture", "+", "\"' />\"", "}", ")", "}", "$oneUpFacebookWrapper", ".", "before", "(", "thumbs", ")", "$photoPickerFacebook", ".", "show", "(", ")", "$spin", ".", "hide", "(", ")", "// wire up the images int the fb gallery", "wireFacebookGalleryPicker", "(", ")", "progressToNextStep", "(", "$stepTwo", ",", "function", "(", ")", "{", "$stepThree", ".", "slideDown", "(", "333", ")", "}", ")", "}", ")", ".", "error", "(", "function", "(", "e", ")", "{", "if", "(", "e", ".", "status", "===", "404", ")", "alert", "(", "e", ".", "responseText", "||", "'Images were not found.'", ")", "if", "(", "e", ".", "status", "===", "403", ")", "alert", "(", "e", ".", "responseText", "||", "'That request was not allowed.'", ")", "if", "(", "e", ".", "status", "===", "500", ")", "alert", "(", "e", ".", "responseText", "||", "'Something went really wrong.'", ")", "}", ")", "}" ]
Initial fetch of fb galleries
[ "Initial", "fetch", "of", "fb", "galleries" ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L246-L289
54,024
joemccann/photopipe
public/js/pipe.js
twitterOneUpClickHandler
function twitterOneUpClickHandler(e){ closeOneUp() var standardResUrl = $(e.target).attr('data-standard-resolution') // e.target.dataset.standardResolution var img = new Image() $spin.show() img.src = standardResUrl img.onload = function(){ $spin.hide() $oneUpTwitter .prepend(img) var $oneUpContainer = $photoPickerTwitter.find('.one-up-wrapper') positionFromTop( $photoPickerTwitter, $oneUpContainer ) showOverlay() $oneUpTwitter .find('> .close-one-up:first') .show() .end() .show() } }
javascript
function twitterOneUpClickHandler(e){ closeOneUp() var standardResUrl = $(e.target).attr('data-standard-resolution') // e.target.dataset.standardResolution var img = new Image() $spin.show() img.src = standardResUrl img.onload = function(){ $spin.hide() $oneUpTwitter .prepend(img) var $oneUpContainer = $photoPickerTwitter.find('.one-up-wrapper') positionFromTop( $photoPickerTwitter, $oneUpContainer ) showOverlay() $oneUpTwitter .find('> .close-one-up:first') .show() .end() .show() } }
[ "function", "twitterOneUpClickHandler", "(", "e", ")", "{", "closeOneUp", "(", ")", "var", "standardResUrl", "=", "$", "(", "e", ".", "target", ")", ".", "attr", "(", "'data-standard-resolution'", ")", "// e.target.dataset.standardResolution", "var", "img", "=", "new", "Image", "(", ")", "$spin", ".", "show", "(", ")", "img", ".", "src", "=", "standardResUrl", "img", ".", "onload", "=", "function", "(", ")", "{", "$spin", ".", "hide", "(", ")", "$oneUpTwitter", ".", "prepend", "(", "img", ")", "var", "$oneUpContainer", "=", "$photoPickerTwitter", ".", "find", "(", "'.one-up-wrapper'", ")", "positionFromTop", "(", "$photoPickerTwitter", ",", "$oneUpContainer", ")", "showOverlay", "(", ")", "$oneUpTwitter", ".", "find", "(", "'> .close-one-up:first'", ")", ".", "show", "(", ")", ".", "end", "(", ")", ".", "show", "(", ")", "}", "}" ]
Fetch twitter image and show in one up
[ "Fetch", "twitter", "image", "and", "show", "in", "one", "up" ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L374-L405
54,025
joemccann/photopipe
public/js/pipe.js
wireOneUpHandlers
function wireOneUpHandlers(){ // Bind ESC key $document.bind('keyup', function(e){ if (e.keyCode === 27) { return closeOneUp() } }) // end keyup // The "x" button on the one up, close it. $closeOneUp.bind('click', closeOneUp ) // The overlay $overlay.bind('click', closeOneUp ) }
javascript
function wireOneUpHandlers(){ // Bind ESC key $document.bind('keyup', function(e){ if (e.keyCode === 27) { return closeOneUp() } }) // end keyup // The "x" button on the one up, close it. $closeOneUp.bind('click', closeOneUp ) // The overlay $overlay.bind('click', closeOneUp ) }
[ "function", "wireOneUpHandlers", "(", ")", "{", "// Bind ESC key", "$document", ".", "bind", "(", "'keyup'", ",", "function", "(", "e", ")", "{", "if", "(", "e", ".", "keyCode", "===", "27", ")", "{", "return", "closeOneUp", "(", ")", "}", "}", ")", "// end keyup", "// The \"x\" button on the one up, close it.", "$closeOneUp", ".", "bind", "(", "'click'", ",", "closeOneUp", ")", "// The overlay", "$overlay", ".", "bind", "(", "'click'", ",", "closeOneUp", ")", "}" ]
Bind events to the document & close button to close the one up view
[ "Bind", "events", "to", "the", "document", "&", "close", "button", "to", "close", "the", "one", "up", "view" ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L459-L473
54,026
joemccann/photopipe
public/js/pipe.js
wireUsePhotoHandlers
function wireUsePhotoHandlers(){ $usePhoto.bind('click submit', function(e){ if(e.target.id === 'facebook-use-photo'){ // We don't want to show the facebook option, because // it is the source of the image. $facebookDestination.hide() _photoToUse = localStorage.imageToPipe || $('.one-up:visible').find('img')[0].src closeOneUp() $stepFourDestinationWrapper.show() progressToNextStep($stepThree, function(){ $stepFour.slideDown(333) }) } if(e.target.id === 'twitter-use-photo'){ // We don't want to show the facebook option, because // it is the source of the image. $twitterDestination.hide() _photoToUse = localStorage.imageToPipe || $('.one-up:visible').find('img')[0].src closeOneUp() $stepThreeDestinationWrapper.show() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) } if(e.target.id === 'url-use-photo'){ _photoToUse = $photoFromUrl.val() || localStorage.imageToPipe $stepThreeDestinationWrapper.show() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) } localStorage.imageToPipe = _photoToUse console.log(_photoToUse) console.log(localStorage.imageToPipe) return false }) // end bind() }
javascript
function wireUsePhotoHandlers(){ $usePhoto.bind('click submit', function(e){ if(e.target.id === 'facebook-use-photo'){ // We don't want to show the facebook option, because // it is the source of the image. $facebookDestination.hide() _photoToUse = localStorage.imageToPipe || $('.one-up:visible').find('img')[0].src closeOneUp() $stepFourDestinationWrapper.show() progressToNextStep($stepThree, function(){ $stepFour.slideDown(333) }) } if(e.target.id === 'twitter-use-photo'){ // We don't want to show the facebook option, because // it is the source of the image. $twitterDestination.hide() _photoToUse = localStorage.imageToPipe || $('.one-up:visible').find('img')[0].src closeOneUp() $stepThreeDestinationWrapper.show() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) } if(e.target.id === 'url-use-photo'){ _photoToUse = $photoFromUrl.val() || localStorage.imageToPipe $stepThreeDestinationWrapper.show() progressToNextStep($stepTwo, function(){ $stepThree.slideDown(333) }) } localStorage.imageToPipe = _photoToUse console.log(_photoToUse) console.log(localStorage.imageToPipe) return false }) // end bind() }
[ "function", "wireUsePhotoHandlers", "(", ")", "{", "$usePhoto", ".", "bind", "(", "'click submit'", ",", "function", "(", "e", ")", "{", "if", "(", "e", ".", "target", ".", "id", "===", "'facebook-use-photo'", ")", "{", "// We don't want to show the facebook option, because", "// it is the source of the image.", "$facebookDestination", ".", "hide", "(", ")", "_photoToUse", "=", "localStorage", ".", "imageToPipe", "||", "$", "(", "'.one-up:visible'", ")", ".", "find", "(", "'img'", ")", "[", "0", "]", ".", "src", "closeOneUp", "(", ")", "$stepFourDestinationWrapper", ".", "show", "(", ")", "progressToNextStep", "(", "$stepThree", ",", "function", "(", ")", "{", "$stepFour", ".", "slideDown", "(", "333", ")", "}", ")", "}", "if", "(", "e", ".", "target", ".", "id", "===", "'twitter-use-photo'", ")", "{", "// We don't want to show the facebook option, because", "// it is the source of the image.", "$twitterDestination", ".", "hide", "(", ")", "_photoToUse", "=", "localStorage", ".", "imageToPipe", "||", "$", "(", "'.one-up:visible'", ")", ".", "find", "(", "'img'", ")", "[", "0", "]", ".", "src", "closeOneUp", "(", ")", "$stepThreeDestinationWrapper", ".", "show", "(", ")", "progressToNextStep", "(", "$stepTwo", ",", "function", "(", ")", "{", "$stepThree", ".", "slideDown", "(", "333", ")", "}", ")", "}", "if", "(", "e", ".", "target", ".", "id", "===", "'url-use-photo'", ")", "{", "_photoToUse", "=", "$photoFromUrl", ".", "val", "(", ")", "||", "localStorage", ".", "imageToPipe", "$stepThreeDestinationWrapper", ".", "show", "(", ")", "progressToNextStep", "(", "$stepTwo", ",", "function", "(", ")", "{", "$stepThree", ".", "slideDown", "(", "333", ")", "}", ")", "}", "localStorage", ".", "imageToPipe", "=", "_photoToUse", "console", ".", "log", "(", "_photoToUse", ")", "console", ".", "log", "(", "localStorage", ".", "imageToPipe", ")", "return", "false", "}", ")", "// end bind()", "}" ]
Bind up the click handlers for one-up view when a user selects the photo they want to pipe
[ "Bind", "up", "the", "click", "handlers", "for", "one", "-", "up", "view", "when", "a", "user", "selects", "the", "photo", "they", "want", "to", "pipe" ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L477-L544
54,027
joemccann/photopipe
public/js/pipe.js
_cleanseInput
function _cleanseInput(dirty){ var clean = '' clean = dirty.replace('@', '') clean = clean.replace('#', '') clean = clean.replace(/\s/g, '') return clean }
javascript
function _cleanseInput(dirty){ var clean = '' clean = dirty.replace('@', '') clean = clean.replace('#', '') clean = clean.replace(/\s/g, '') return clean }
[ "function", "_cleanseInput", "(", "dirty", ")", "{", "var", "clean", "=", "''", "clean", "=", "dirty", ".", "replace", "(", "'@'", ",", "''", ")", "clean", "=", "clean", ".", "replace", "(", "'#'", ",", "''", ")", "clean", "=", "clean", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", "return", "clean", "}" ]
Super hack and certainly not bullet proof.
[ "Super", "hack", "and", "certainly", "not", "bullet", "proof", "." ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L734-L740
54,028
joemccann/photopipe
public/js/pipe.js
_failHandler
function _failHandler(e){ $spin.hide() if(e.status === 400) alert(e.responseText || 'Bad request.') if(e.status === 401) alert(e.responseText || 'Unauthorized request.') if(e.status === 402) alert(e.responseText || 'Forbidden request.') if(e.status === 403) alert(e.responseText || 'Forbidden request.') if(e.status === 404) alert(e.responseText || 'Images were not found.') if(e.status === 405) alert(e.responseText || 'That method is not allowed.') if(e.status === 408) alert(e.responseText || 'The request timed out. Try again.') if(e.status === 500) alert(e.responseText || 'Something went really wrong.') postData = postUrl = '' cb & cb() }
javascript
function _failHandler(e){ $spin.hide() if(e.status === 400) alert(e.responseText || 'Bad request.') if(e.status === 401) alert(e.responseText || 'Unauthorized request.') if(e.status === 402) alert(e.responseText || 'Forbidden request.') if(e.status === 403) alert(e.responseText || 'Forbidden request.') if(e.status === 404) alert(e.responseText || 'Images were not found.') if(e.status === 405) alert(e.responseText || 'That method is not allowed.') if(e.status === 408) alert(e.responseText || 'The request timed out. Try again.') if(e.status === 500) alert(e.responseText || 'Something went really wrong.') postData = postUrl = '' cb & cb() }
[ "function", "_failHandler", "(", "e", ")", "{", "$spin", ".", "hide", "(", ")", "if", "(", "e", ".", "status", "===", "400", ")", "alert", "(", "e", ".", "responseText", "||", "'Bad request.'", ")", "if", "(", "e", ".", "status", "===", "401", ")", "alert", "(", "e", ".", "responseText", "||", "'Unauthorized request.'", ")", "if", "(", "e", ".", "status", "===", "402", ")", "alert", "(", "e", ".", "responseText", "||", "'Forbidden request.'", ")", "if", "(", "e", ".", "status", "===", "403", ")", "alert", "(", "e", ".", "responseText", "||", "'Forbidden request.'", ")", "if", "(", "e", ".", "status", "===", "404", ")", "alert", "(", "e", ".", "responseText", "||", "'Images were not found.'", ")", "if", "(", "e", ".", "status", "===", "405", ")", "alert", "(", "e", ".", "responseText", "||", "'That method is not allowed.'", ")", "if", "(", "e", ".", "status", "===", "408", ")", "alert", "(", "e", ".", "responseText", "||", "'The request timed out. Try again.'", ")", "if", "(", "e", ".", "status", "===", "500", ")", "alert", "(", "e", ".", "responseText", "||", "'Something went really wrong.'", ")", "postData", "=", "postUrl", "=", "''", "cb", "&", "cb", "(", ")", "}" ]
end done handler
[ "end", "done", "handler" ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L823-L839
54,029
joemccann/photopipe
public/js/pipe.js
_selectPhotoForPipe
function _selectPhotoForPipe(e){ var img = $('.one-up:visible').find('img')[0].src localStorage.imageToPipe = img closeOneUp() window.location = "/instagram/pipe/to" }
javascript
function _selectPhotoForPipe(e){ var img = $('.one-up:visible').find('img')[0].src localStorage.imageToPipe = img closeOneUp() window.location = "/instagram/pipe/to" }
[ "function", "_selectPhotoForPipe", "(", "e", ")", "{", "var", "img", "=", "$", "(", "'.one-up:visible'", ")", ".", "find", "(", "'img'", ")", "[", "0", "]", ".", "src", "localStorage", ".", "imageToPipe", "=", "img", "closeOneUp", "(", ")", "window", ".", "location", "=", "\"/instagram/pipe/to\"", "}" ]
This method is where we select the image to be piped to another location.
[ "This", "method", "is", "where", "we", "select", "the", "image", "to", "be", "piped", "to", "another", "location", "." ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L979-L988
54,030
joemccann/photopipe
public/js/pipe.js
positionFromTop
function positionFromTop(container, el){ var containerTop = container.position().top , windowTop = $window.scrollTop() if(containerTop > windowTop) return el.css('top', 0) var pos = windowTop - containerTop return el.css('top', pos) }
javascript
function positionFromTop(container, el){ var containerTop = container.position().top , windowTop = $window.scrollTop() if(containerTop > windowTop) return el.css('top', 0) var pos = windowTop - containerTop return el.css('top', pos) }
[ "function", "positionFromTop", "(", "container", ",", "el", ")", "{", "var", "containerTop", "=", "container", ".", "position", "(", ")", ".", "top", ",", "windowTop", "=", "$window", ".", "scrollTop", "(", ")", "if", "(", "containerTop", ">", "windowTop", ")", "return", "el", ".", "css", "(", "'top'", ",", "0", ")", "var", "pos", "=", "windowTop", "-", "containerTop", "return", "el", ".", "css", "(", "'top'", ",", "pos", ")", "}" ]
Position via offset
[ "Position", "via", "offset" ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L1398-L1409
54,031
joemccann/photopipe
public/js/pipe.js
featureDetector
function featureDetector(){ // Check if client can access file sytem (from Modernizer) var elem = document.createElement('input') elem.type = 'file' window.Photopipe.hasFileSystem = !elem.disabled // Check if client has media capture access window.Photopipe.hasMediaCapture = !!navigator.getUserMedia || !!navigator.webkitGetUserMedia || !!navigator.mozGetUserMedia || !!navigator.msGetUserMedia // Check if client has the download attribute for anchor tags window.Photopipe.hasDownloadAttribute = ("download" in document.createElement("a")) // Check for localstorage var storage try{ if(localStorage.getItem) {storage = localStorage} }catch(e){} window.Photopipe.hasLocalStorage = storage }
javascript
function featureDetector(){ // Check if client can access file sytem (from Modernizer) var elem = document.createElement('input') elem.type = 'file' window.Photopipe.hasFileSystem = !elem.disabled // Check if client has media capture access window.Photopipe.hasMediaCapture = !!navigator.getUserMedia || !!navigator.webkitGetUserMedia || !!navigator.mozGetUserMedia || !!navigator.msGetUserMedia // Check if client has the download attribute for anchor tags window.Photopipe.hasDownloadAttribute = ("download" in document.createElement("a")) // Check for localstorage var storage try{ if(localStorage.getItem) {storage = localStorage} }catch(e){} window.Photopipe.hasLocalStorage = storage }
[ "function", "featureDetector", "(", ")", "{", "// Check if client can access file sytem (from Modernizer) ", "var", "elem", "=", "document", ".", "createElement", "(", "'input'", ")", "elem", ".", "type", "=", "'file'", "window", ".", "Photopipe", ".", "hasFileSystem", "=", "!", "elem", ".", "disabled", "// Check if client has media capture access ", "window", ".", "Photopipe", ".", "hasMediaCapture", "=", "!", "!", "navigator", ".", "getUserMedia", "||", "!", "!", "navigator", ".", "webkitGetUserMedia", "||", "!", "!", "navigator", ".", "mozGetUserMedia", "||", "!", "!", "navigator", ".", "msGetUserMedia", "// Check if client has the download attribute for anchor tags ", "window", ".", "Photopipe", ".", "hasDownloadAttribute", "=", "(", "\"download\"", "in", "document", ".", "createElement", "(", "\"a\"", ")", ")", "// Check for localstorage", "var", "storage", "try", "{", "if", "(", "localStorage", ".", "getItem", ")", "{", "storage", "=", "localStorage", "}", "}", "catch", "(", "e", ")", "{", "}", "window", ".", "Photopipe", ".", "hasLocalStorage", "=", "storage", "}" ]
Determine browser capabilities
[ "Determine", "browser", "capabilities" ]
20318fde11163a8b732b077a141a8d8530372333
https://github.com/joemccann/photopipe/blob/20318fde11163a8b732b077a141a8d8530372333/public/js/pipe.js#L1417-L1437
54,032
yeptlabs/wns
src/core/base/wnEvent.js
function (listener,evtObj) { if (!_.isFunction(listener) || !_.isObject(evtObj)) return false; var args = evtObj.arguments; switch (args.length) { case 1: listener(args[0]); break; case 2: listener(args[0],args[1]); break; case 3: listener(args[0],args[1],args[2]); break; case 4: listener(args[0],args[1],args[2],args[3]); break; case 5: listener(args[0],args[1],args[2],args[3],args[4]); break; default: listener.apply(undefined,args); } }
javascript
function (listener,evtObj) { if (!_.isFunction(listener) || !_.isObject(evtObj)) return false; var args = evtObj.arguments; switch (args.length) { case 1: listener(args[0]); break; case 2: listener(args[0],args[1]); break; case 3: listener(args[0],args[1],args[2]); break; case 4: listener(args[0],args[1],args[2],args[3]); break; case 5: listener(args[0],args[1],args[2],args[3],args[4]); break; default: listener.apply(undefined,args); } }
[ "function", "(", "listener", ",", "evtObj", ")", "{", "if", "(", "!", "_", ".", "isFunction", "(", "listener", ")", "||", "!", "_", ".", "isObject", "(", "evtObj", ")", ")", "return", "false", ";", "var", "args", "=", "evtObj", ".", "arguments", ";", "switch", "(", "args", ".", "length", ")", "{", "case", "1", ":", "listener", "(", "args", "[", "0", "]", ")", ";", "break", ";", "case", "2", ":", "listener", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ")", ";", "break", ";", "case", "3", ":", "listener", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ",", "args", "[", "2", "]", ")", ";", "break", ";", "case", "4", ":", "listener", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ",", "args", "[", "2", "]", ",", "args", "[", "3", "]", ")", ";", "break", ";", "case", "5", ":", "listener", "(", "args", "[", "0", "]", ",", "args", "[", "1", "]", ",", "args", "[", "2", "]", ",", "args", "[", "3", "]", ",", "args", "[", "4", "]", ")", ";", "break", ";", "default", ":", "listener", ".", "apply", "(", "undefined", ",", "args", ")", ";", "}", "}" ]
Call the listener @param {function} listener @param {object} event object
[ "Call", "the", "listener" ]
c42602b062dcf6bbffc22e4365bba2cbf363fe2f
https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnEvent.js#L43-L69
54,033
yeptlabs/wns
src/core/base/wnEvent.js
function (listener,prepend) { if ('function' !== typeof listener) return false; if (!_listeners) _listeners=listener; else if (typeof _listeners == 'object') { if (!prepend) _listeners.push(listener); else _listeners.unshift(listener); } else { if (!prepend) _listeners = [_listeners,listener]; else _listeners = [listener,_listeners]; } return this; }
javascript
function (listener,prepend) { if ('function' !== typeof listener) return false; if (!_listeners) _listeners=listener; else if (typeof _listeners == 'object') { if (!prepend) _listeners.push(listener); else _listeners.unshift(listener); } else { if (!prepend) _listeners = [_listeners,listener]; else _listeners = [listener,_listeners]; } return this; }
[ "function", "(", "listener", ",", "prepend", ")", "{", "if", "(", "'function'", "!==", "typeof", "listener", ")", "return", "false", ";", "if", "(", "!", "_listeners", ")", "_listeners", "=", "listener", ";", "else", "if", "(", "typeof", "_listeners", "==", "'object'", ")", "{", "if", "(", "!", "prepend", ")", "_listeners", ".", "push", "(", "listener", ")", ";", "else", "_listeners", ".", "unshift", "(", "listener", ")", ";", "}", "else", "{", "if", "(", "!", "prepend", ")", "_listeners", "=", "[", "_listeners", ",", "listener", "]", ";", "else", "_listeners", "=", "[", "listener", ",", "_listeners", "]", ";", "}", "return", "this", ";", "}" ]
Add a new handler to this event.' @param function $listener listener of the event @param boolean $prepend
[ "Add", "a", "new", "handler", "to", "this", "event", "." ]
c42602b062dcf6bbffc22e4365bba2cbf363fe2f
https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnEvent.js#L151-L172
54,034
yeptlabs/wns
src/core/base/wnEvent.js
function (listener, prepend) { if ('function' === typeof listener) { var self = this, g = function (e) { e.lastListeners--; self.removeListener(g); listener.apply(listener, arguments); }; g.listener = listener; this.addListener(g,prepend) } return this; }
javascript
function (listener, prepend) { if ('function' === typeof listener) { var self = this, g = function (e) { e.lastListeners--; self.removeListener(g); listener.apply(listener, arguments); }; g.listener = listener; this.addListener(g,prepend) } return this; }
[ "function", "(", "listener", ",", "prepend", ")", "{", "if", "(", "'function'", "===", "typeof", "listener", ")", "{", "var", "self", "=", "this", ",", "g", "=", "function", "(", "e", ")", "{", "e", ".", "lastListeners", "--", ";", "self", ".", "removeListener", "(", "g", ")", ";", "listener", ".", "apply", "(", "listener", ",", "arguments", ")", ";", "}", ";", "g", ".", "listener", "=", "listener", ";", "this", ".", "addListener", "(", "g", ",", "prepend", ")", "}", "return", "this", ";", "}" ]
Add a new one-time-listener to this event. @param $listener function listener of the event
[ "Add", "a", "new", "one", "-", "time", "-", "listener", "to", "this", "event", "." ]
c42602b062dcf6bbffc22e4365bba2cbf363fe2f
https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnEvent.js#L195-L210
54,035
yeptlabs/wns
src/core/base/wnEvent.js
function (listener) { if ('function' !== typeof listener) return false; var list = _listeners; var position = -1; if (list === listener || (typeof list.listener === 'function' && list.listener === listener)) _listeners = undefined; else if (typeof list === 'object') { for (var i = 0, length = list.length; i < length; i++) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position > -1) list.splice(position, 1); if (list.length == 1) _listeners = list[0]; } return this; }
javascript
function (listener) { if ('function' !== typeof listener) return false; var list = _listeners; var position = -1; if (list === listener || (typeof list.listener === 'function' && list.listener === listener)) _listeners = undefined; else if (typeof list === 'object') { for (var i = 0, length = list.length; i < length; i++) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position > -1) list.splice(position, 1); if (list.length == 1) _listeners = list[0]; } return this; }
[ "function", "(", "listener", ")", "{", "if", "(", "'function'", "!==", "typeof", "listener", ")", "return", "false", ";", "var", "list", "=", "_listeners", ";", "var", "position", "=", "-", "1", ";", "if", "(", "list", "===", "listener", "||", "(", "typeof", "list", ".", "listener", "===", "'function'", "&&", "list", ".", "listener", "===", "listener", ")", ")", "_listeners", "=", "undefined", ";", "else", "if", "(", "typeof", "list", "===", "'object'", ")", "{", "for", "(", "var", "i", "=", "0", ",", "length", "=", "list", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "list", "[", "i", "]", "===", "listener", "||", "(", "list", "[", "i", "]", ".", "listener", "&&", "list", "[", "i", "]", ".", "listener", "===", "listener", ")", ")", "{", "position", "=", "i", ";", "break", ";", "}", "}", "if", "(", "position", ">", "-", "1", ")", "list", ".", "splice", "(", "position", ",", "1", ")", ";", "if", "(", "list", ".", "length", "==", "1", ")", "_listeners", "=", "list", "[", "0", "]", ";", "}", "return", "this", ";", "}" ]
Remove a listener from this event. @param $listener function listener of the event
[ "Remove", "a", "listener", "from", "this", "event", "." ]
c42602b062dcf6bbffc22e4365bba2cbf363fe2f
https://github.com/yeptlabs/wns/blob/c42602b062dcf6bbffc22e4365bba2cbf363fe2f/src/core/base/wnEvent.js#L216-L248
54,036
icetan/backbone-recursive-model
index.js
function(b) { if (b instanceof Model) { if (this.constructor !== b.constructor) return false; b = b.attributes; } return _.isEqual(this.attributes, b); }
javascript
function(b) { if (b instanceof Model) { if (this.constructor !== b.constructor) return false; b = b.attributes; } return _.isEqual(this.attributes, b); }
[ "function", "(", "b", ")", "{", "if", "(", "b", "instanceof", "Model", ")", "{", "if", "(", "this", ".", "constructor", "!==", "b", ".", "constructor", ")", "return", "false", ";", "b", "=", "b", ".", "attributes", ";", "}", "return", "_", ".", "isEqual", "(", "this", ".", "attributes", ",", "b", ")", ";", "}" ]
Custom Underscore equality method.
[ "Custom", "Underscore", "equality", "method", "." ]
f28eaf85040fcbf03f624a7fbc9e837355d28951
https://github.com/icetan/backbone-recursive-model/blob/f28eaf85040fcbf03f624a7fbc9e837355d28951/index.js#L14-L20
54,037
supercrabtree/tape-worm
index.js
setInitalStyle
function setInitalStyle() { document.body.style.margin = 0; document.body.style.borderTopWidth = '10px'; document.body.style.borderTopStyle = 'solid'; }
javascript
function setInitalStyle() { document.body.style.margin = 0; document.body.style.borderTopWidth = '10px'; document.body.style.borderTopStyle = 'solid'; }
[ "function", "setInitalStyle", "(", ")", "{", "document", ".", "body", ".", "style", ".", "margin", "=", "0", ";", "document", ".", "body", ".", "style", ".", "borderTopWidth", "=", "'10px'", ";", "document", ".", "body", ".", "style", ".", "borderTopStyle", "=", "'solid'", ";", "}" ]
Some initial styles, border color is changed when tests are run
[ "Some", "initial", "styles", "border", "color", "is", "changed", "when", "tests", "are", "run" ]
fe448d916cf7ee233e494580a89c8a44545603ae
https://github.com/supercrabtree/tape-worm/blob/fe448d916cf7ee233e494580a89c8a44545603ae/index.js#L52-L56
54,038
supercrabtree/tape-worm
index.js
style
function style() { var testsAre = 'pending'; if (failed > 0) { testsAre = 'failing'; } else if (passed > 0) { testsAre = 'passing'; } document.body.style.borderTopColor = richColors[testsAre]; faviconEl.setAttribute('href', favicons[testsAre]); document.body.style.backgroundColor = colors[testsAre]; }
javascript
function style() { var testsAre = 'pending'; if (failed > 0) { testsAre = 'failing'; } else if (passed > 0) { testsAre = 'passing'; } document.body.style.borderTopColor = richColors[testsAre]; faviconEl.setAttribute('href', favicons[testsAre]); document.body.style.backgroundColor = colors[testsAre]; }
[ "function", "style", "(", ")", "{", "var", "testsAre", "=", "'pending'", ";", "if", "(", "failed", ">", "0", ")", "{", "testsAre", "=", "'failing'", ";", "}", "else", "if", "(", "passed", ">", "0", ")", "{", "testsAre", "=", "'passing'", ";", "}", "document", ".", "body", ".", "style", ".", "borderTopColor", "=", "richColors", "[", "testsAre", "]", ";", "faviconEl", ".", "setAttribute", "(", "'href'", ",", "favicons", "[", "testsAre", "]", ")", ";", "document", ".", "body", ".", "style", ".", "backgroundColor", "=", "colors", "[", "testsAre", "]", ";", "}" ]
Style the page
[ "Style", "the", "page" ]
fe448d916cf7ee233e494580a89c8a44545603ae
https://github.com/supercrabtree/tape-worm/blob/fe448d916cf7ee233e494580a89c8a44545603ae/index.js#L74-L87
54,039
supercrabtree/tape-worm
index.js
hijackLog
function hijackLog() { var oldLog = console.log; console.log = function (message) { count(message); style(); var match = (message + '').match(/^# #tapeworm-html(.*)/); var isHtml = !!match; if (match) { var html = match[1]; var div = testResults.appendChild(document.createElement('div')); div.innerHTML = html; } else { var pre = testResults.appendChild(document.createElement('pre')); pre.style.margin = 0; pre.innerHTML = message + '\n'; oldLog.apply(console, arguments); } }; }
javascript
function hijackLog() { var oldLog = console.log; console.log = function (message) { count(message); style(); var match = (message + '').match(/^# #tapeworm-html(.*)/); var isHtml = !!match; if (match) { var html = match[1]; var div = testResults.appendChild(document.createElement('div')); div.innerHTML = html; } else { var pre = testResults.appendChild(document.createElement('pre')); pre.style.margin = 0; pre.innerHTML = message + '\n'; oldLog.apply(console, arguments); } }; }
[ "function", "hijackLog", "(", ")", "{", "var", "oldLog", "=", "console", ".", "log", ";", "console", ".", "log", "=", "function", "(", "message", ")", "{", "count", "(", "message", ")", ";", "style", "(", ")", ";", "var", "match", "=", "(", "message", "+", "''", ")", ".", "match", "(", "/", "^# #tapeworm-html(.*)", "/", ")", ";", "var", "isHtml", "=", "!", "!", "match", ";", "if", "(", "match", ")", "{", "var", "html", "=", "match", "[", "1", "]", ";", "var", "div", "=", "testResults", ".", "appendChild", "(", "document", ".", "createElement", "(", "'div'", ")", ")", ";", "div", ".", "innerHTML", "=", "html", ";", "}", "else", "{", "var", "pre", "=", "testResults", ".", "appendChild", "(", "document", ".", "createElement", "(", "'pre'", ")", ")", ";", "pre", ".", "style", ".", "margin", "=", "0", ";", "pre", ".", "innerHTML", "=", "message", "+", "'\\n'", ";", "oldLog", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", "}", ";", "}" ]
Create a wrapper around console.log
[ "Create", "a", "wrapper", "around", "console", ".", "log" ]
fe448d916cf7ee233e494580a89c8a44545603ae
https://github.com/supercrabtree/tape-worm/blob/fe448d916cf7ee233e494580a89c8a44545603ae/index.js#L108-L132
54,040
supercrabtree/tape-worm
index.js
infect
function infect(tape) { if (!document) { tape.Test.prototype.html = function () {}; return; } injectFavicon(); createTestResults(); setInitalStyle(); decorateTape(tape); hijackLog(); style(); }
javascript
function infect(tape) { if (!document) { tape.Test.prototype.html = function () {}; return; } injectFavicon(); createTestResults(); setInitalStyle(); decorateTape(tape); hijackLog(); style(); }
[ "function", "infect", "(", "tape", ")", "{", "if", "(", "!", "document", ")", "{", "tape", ".", "Test", ".", "prototype", ".", "html", "=", "function", "(", ")", "{", "}", ";", "return", ";", "}", "injectFavicon", "(", ")", ";", "createTestResults", "(", ")", ";", "setInitalStyle", "(", ")", ";", "decorateTape", "(", "tape", ")", ";", "hijackLog", "(", ")", ";", "style", "(", ")", ";", "}" ]
Infect is the only exposed method @param tape - A instace of tape / bluetape / redtape etc.
[ "Infect", "is", "the", "only", "exposed", "method" ]
fe448d916cf7ee233e494580a89c8a44545603ae
https://github.com/supercrabtree/tape-worm/blob/fe448d916cf7ee233e494580a89c8a44545603ae/index.js#L147-L158
54,041
SolarNetwork/solarnetwork-d3
src/ui/Matrix.js
function(angle) { // TODO this clears any scale, should we care? var a = Math.cos(angle); var b = Math.sin(angle); this.matrix[0] = this.matrix[3] = a; this.matrix[1] = (0-b); this.matrix[2] = b; }
javascript
function(angle) { // TODO this clears any scale, should we care? var a = Math.cos(angle); var b = Math.sin(angle); this.matrix[0] = this.matrix[3] = a; this.matrix[1] = (0-b); this.matrix[2] = b; }
[ "function", "(", "angle", ")", "{", "// TODO this clears any scale, should we care?", "var", "a", "=", "Math", ".", "cos", "(", "angle", ")", ";", "var", "b", "=", "Math", ".", "sin", "(", "angle", ")", ";", "this", ".", "matrix", "[", "0", "]", "=", "this", ".", "matrix", "[", "3", "]", "=", "a", ";", "this", ".", "matrix", "[", "1", "]", "=", "(", "0", "-", "b", ")", ";", "this", ".", "matrix", "[", "2", "]", "=", "b", ";", "}" ]
Set the z-axis rotation of the matrix. @param {Number} angle the rotation angle, in radians @preserve
[ "Set", "the", "z", "-", "axis", "rotation", "of", "the", "matrix", "." ]
26848b1c303b98b7c0ddeefb8c68c5f5bf78927e
https://github.com/SolarNetwork/solarnetwork-d3/blob/26848b1c303b98b7c0ddeefb8c68c5f5bf78927e/src/ui/Matrix.js#L113-L120
54,042
dogada/tflow
tflow.js
nextTickFn
function nextTickFn() { // setImmediate allows to run task after already queued I/O callbacks if (typeof setImmediate === 'function') { return setImmediate; } else if (typeof process !== 'undefined' && process.nextTick) { return function(fn) { process.nextTick(fn); } } else { return function(fn) { setTimeout(fn, 0); } } }
javascript
function nextTickFn() { // setImmediate allows to run task after already queued I/O callbacks if (typeof setImmediate === 'function') { return setImmediate; } else if (typeof process !== 'undefined' && process.nextTick) { return function(fn) { process.nextTick(fn); } } else { return function(fn) { setTimeout(fn, 0); } } }
[ "function", "nextTickFn", "(", ")", "{", "// setImmediate allows to run task after already queued I/O callbacks", "if", "(", "typeof", "setImmediate", "===", "'function'", ")", "{", "return", "setImmediate", ";", "}", "else", "if", "(", "typeof", "process", "!==", "'undefined'", "&&", "process", ".", "nextTick", ")", "{", "return", "function", "(", "fn", ")", "{", "process", ".", "nextTick", "(", "fn", ")", ";", "}", "}", "else", "{", "return", "function", "(", "fn", ")", "{", "setTimeout", "(", "fn", ",", "0", ")", ";", "}", "}", "}" ]
Return next tick function for current environment.
[ "Return", "next", "tick", "function", "for", "current", "environment", "." ]
e3ea0d7f45862abf55ec7dc1c6bd573fd3e71664
https://github.com/dogada/tflow/blob/e3ea0d7f45862abf55ec7dc1c6bd573fd3e71664/tflow.js#L6-L19
54,043
clempat/gulp-systemjs-resolver
index.js
resolve
function resolve(val, i, isPath) { val = val.replace('~', ''); return Promise.resolve(System.normalize(val)) .then(function(normalized) { return System.locate({name: normalized, metadata: {}}); }) .then(function(address) { if (isPath) { options.includePaths.push( path.resolve(address.replace('file:', '').replace('.js', '')) ); } else { var originalRelativePath = path.relative( path.dirname(file.path), path.resolve(address.replace('file:', '').replace('.js', '')) ); var originalRelativePathArray = originalRelativePath.split(path.sep); replacements[i] = path.posix? path.posix.join.apply(this, originalRelativePathArray): path.normalize(originalRelativePath).replace(/\\/g, '/').replace('//', '/'); } }); }
javascript
function resolve(val, i, isPath) { val = val.replace('~', ''); return Promise.resolve(System.normalize(val)) .then(function(normalized) { return System.locate({name: normalized, metadata: {}}); }) .then(function(address) { if (isPath) { options.includePaths.push( path.resolve(address.replace('file:', '').replace('.js', '')) ); } else { var originalRelativePath = path.relative( path.dirname(file.path), path.resolve(address.replace('file:', '').replace('.js', '')) ); var originalRelativePathArray = originalRelativePath.split(path.sep); replacements[i] = path.posix? path.posix.join.apply(this, originalRelativePathArray): path.normalize(originalRelativePath).replace(/\\/g, '/').replace('//', '/'); } }); }
[ "function", "resolve", "(", "val", ",", "i", ",", "isPath", ")", "{", "val", "=", "val", ".", "replace", "(", "'~'", ",", "''", ")", ";", "return", "Promise", ".", "resolve", "(", "System", ".", "normalize", "(", "val", ")", ")", ".", "then", "(", "function", "(", "normalized", ")", "{", "return", "System", ".", "locate", "(", "{", "name", ":", "normalized", ",", "metadata", ":", "{", "}", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "address", ")", "{", "if", "(", "isPath", ")", "{", "options", ".", "includePaths", ".", "push", "(", "path", ".", "resolve", "(", "address", ".", "replace", "(", "'file:'", ",", "''", ")", ".", "replace", "(", "'.js'", ",", "''", ")", ")", ")", ";", "}", "else", "{", "var", "originalRelativePath", "=", "path", ".", "relative", "(", "path", ".", "dirname", "(", "file", ".", "path", ")", ",", "path", ".", "resolve", "(", "address", ".", "replace", "(", "'file:'", ",", "''", ")", ".", "replace", "(", "'.js'", ",", "''", ")", ")", ")", ";", "var", "originalRelativePathArray", "=", "originalRelativePath", ".", "split", "(", "path", ".", "sep", ")", ";", "replacements", "[", "i", "]", "=", "path", ".", "posix", "?", "path", ".", "posix", ".", "join", ".", "apply", "(", "this", ",", "originalRelativePathArray", ")", ":", "path", ".", "normalize", "(", "originalRelativePath", ")", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ".", "replace", "(", "'//'", ",", "'/'", ")", ";", "}", "}", ")", ";", "}" ]
Use systemjs to resolve include files @param val @param i @param {Boolean} isPath @returns {*}
[ "Use", "systemjs", "to", "resolve", "include", "files" ]
b486e8ffd23d4e295dfa57634e6435685dc1d27c
https://github.com/clempat/gulp-systemjs-resolver/blob/b486e8ffd23d4e295dfa57634e6435685dc1d27c/index.js#L51-L74
54,044
clempat/gulp-systemjs-resolver
index.js
resolveAll
function resolveAll(fileContent) { var matches = [].concat(fileContent.match(regexFile)).filter(Boolean).map(extractFile); var pathsMatches = [].concat(fileContent.match(regexPath)).filter(Boolean).map(extractFile); if (matches.length === 0 && pathsMatches.length === 0) { return new RSVP.Promise(function(resolve) { resolve(fileContent) }); } var promises = [].concat(matches.map(resolveFile)).filter(Boolean); var promisesPaths = [].concat(pathsMatches.map(resolvePath)).filter(Boolean); return RSVP.all(promises.concat(promisesPaths)).then(function() { for (var i = 0, len = matches.length; i < len; i++) { fileContent = fileContent.replace(matches[i], replacements[i]); } return fileContent; }); }
javascript
function resolveAll(fileContent) { var matches = [].concat(fileContent.match(regexFile)).filter(Boolean).map(extractFile); var pathsMatches = [].concat(fileContent.match(regexPath)).filter(Boolean).map(extractFile); if (matches.length === 0 && pathsMatches.length === 0) { return new RSVP.Promise(function(resolve) { resolve(fileContent) }); } var promises = [].concat(matches.map(resolveFile)).filter(Boolean); var promisesPaths = [].concat(pathsMatches.map(resolvePath)).filter(Boolean); return RSVP.all(promises.concat(promisesPaths)).then(function() { for (var i = 0, len = matches.length; i < len; i++) { fileContent = fileContent.replace(matches[i], replacements[i]); } return fileContent; }); }
[ "function", "resolveAll", "(", "fileContent", ")", "{", "var", "matches", "=", "[", "]", ".", "concat", "(", "fileContent", ".", "match", "(", "regexFile", ")", ")", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "extractFile", ")", ";", "var", "pathsMatches", "=", "[", "]", ".", "concat", "(", "fileContent", ".", "match", "(", "regexPath", ")", ")", ".", "filter", "(", "Boolean", ")", ".", "map", "(", "extractFile", ")", ";", "if", "(", "matches", ".", "length", "===", "0", "&&", "pathsMatches", ".", "length", "===", "0", ")", "{", "return", "new", "RSVP", ".", "Promise", "(", "function", "(", "resolve", ")", "{", "resolve", "(", "fileContent", ")", "}", ")", ";", "}", "var", "promises", "=", "[", "]", ".", "concat", "(", "matches", ".", "map", "(", "resolveFile", ")", ")", ".", "filter", "(", "Boolean", ")", ";", "var", "promisesPaths", "=", "[", "]", ".", "concat", "(", "pathsMatches", ".", "map", "(", "resolvePath", ")", ")", ".", "filter", "(", "Boolean", ")", ";", "return", "RSVP", ".", "all", "(", "promises", ".", "concat", "(", "promisesPaths", ")", ")", ".", "then", "(", "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "matches", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "fileContent", "=", "fileContent", ".", "replace", "(", "matches", "[", "i", "]", ",", "replacements", "[", "i", "]", ")", ";", "}", "return", "fileContent", ";", "}", ")", ";", "}" ]
Resolve the imports @param fileContent
[ "Resolve", "the", "imports" ]
b486e8ffd23d4e295dfa57634e6435685dc1d27c
https://github.com/clempat/gulp-systemjs-resolver/blob/b486e8ffd23d4e295dfa57634e6435685dc1d27c/index.js#L109-L129
54,045
colmharte/geteventstore-client
lib/Client.js
Client
function Client(opts) { this.opts = new clientOptions(opts) this.streamData = {} this.currentIndex = 0 this.cachedItems = new lru({maxSize: this.opts.maxCacheSize}) }
javascript
function Client(opts) { this.opts = new clientOptions(opts) this.streamData = {} this.currentIndex = 0 this.cachedItems = new lru({maxSize: this.opts.maxCacheSize}) }
[ "function", "Client", "(", "opts", ")", "{", "this", ".", "opts", "=", "new", "clientOptions", "(", "opts", ")", "this", ".", "streamData", "=", "{", "}", "this", ".", "currentIndex", "=", "0", "this", ".", "cachedItems", "=", "new", "lru", "(", "{", "maxSize", ":", "this", ".", "opts", ".", "maxCacheSize", "}", ")", "}" ]
Client interface fabricator
[ "Client", "interface", "fabricator" ]
49ac3ea0d4b5a3383144053bc42d7417921880da
https://github.com/colmharte/geteventstore-client/blob/49ac3ea0d4b5a3383144053bc42d7417921880da/lib/Client.js#L32-L38
54,046
chrishayesmu/DubBotBase
src/config.js
create
function create(basedir, defaults) { LOG.info("Initializing application configuration"); var config = defaults || {}; _loadConfigurationFiles(basedir, config); _validateConfig(config); if (config.DubBotBase.isConfigImmutable) { _freezeConfig(config); LOG.info("Configuration set up successfully. The config object is now frozen and no changes can be made to it."); } else { LOG.info("Configuration set up successfully. Config has not been frozen due to override of the DubBotBase.isConfigImmutable property."); } return config; }
javascript
function create(basedir, defaults) { LOG.info("Initializing application configuration"); var config = defaults || {}; _loadConfigurationFiles(basedir, config); _validateConfig(config); if (config.DubBotBase.isConfigImmutable) { _freezeConfig(config); LOG.info("Configuration set up successfully. The config object is now frozen and no changes can be made to it."); } else { LOG.info("Configuration set up successfully. Config has not been frozen due to override of the DubBotBase.isConfigImmutable property."); } return config; }
[ "function", "create", "(", "basedir", ",", "defaults", ")", "{", "LOG", ".", "info", "(", "\"Initializing application configuration\"", ")", ";", "var", "config", "=", "defaults", "||", "{", "}", ";", "_loadConfigurationFiles", "(", "basedir", ",", "config", ")", ";", "_validateConfig", "(", "config", ")", ";", "if", "(", "config", ".", "DubBotBase", ".", "isConfigImmutable", ")", "{", "_freezeConfig", "(", "config", ")", ";", "LOG", ".", "info", "(", "\"Configuration set up successfully. The config object is now frozen and no changes can be made to it.\"", ")", ";", "}", "else", "{", "LOG", ".", "info", "(", "\"Configuration set up successfully. Config has not been frozen due to override of the DubBotBase.isConfigImmutable property.\"", ")", ";", "}", "return", "config", ";", "}" ]
Initializes the application's configuration by reading from a config file defined in NPM configuration. @param {string} basedir - The base directory of the bot, containing a "config" subdirectory @param {object} defaults - An optional object containing default configuration. @returns {object} An object representing configuration
[ "Initializes", "the", "application", "s", "configuration", "by", "reading", "from", "a", "config", "file", "defined", "in", "NPM", "configuration", "." ]
0e4b5e65531c23293d22ac766850c802b1266e48
https://github.com/chrishayesmu/DubBotBase/blob/0e4b5e65531c23293d22ac766850c802b1266e48/src/config.js#L25-L41
54,047
chrishayesmu/DubBotBase
src/config.js
_copyConfigFromFile
function _copyConfigFromFile(filePath, config) { LOG.info("Attempting to load configuration file '{}'", filePath); var fileConfig = require(filePath); _mergeConfig(config, fileConfig); LOG.info("Successfully read configuration file '{}'", filePath); }
javascript
function _copyConfigFromFile(filePath, config) { LOG.info("Attempting to load configuration file '{}'", filePath); var fileConfig = require(filePath); _mergeConfig(config, fileConfig); LOG.info("Successfully read configuration file '{}'", filePath); }
[ "function", "_copyConfigFromFile", "(", "filePath", ",", "config", ")", "{", "LOG", ".", "info", "(", "\"Attempting to load configuration file '{}'\"", ",", "filePath", ")", ";", "var", "fileConfig", "=", "require", "(", "filePath", ")", ";", "_mergeConfig", "(", "config", ",", "fileConfig", ")", ";", "LOG", ".", "info", "(", "\"Successfully read configuration file '{}'\"", ",", "filePath", ")", ";", "}" ]
Reads the JSON configuration out of the file specified. @param {string} filePath - The path to the file to load @params {object} config - The current config object
[ "Reads", "the", "JSON", "configuration", "out", "of", "the", "file", "specified", "." ]
0e4b5e65531c23293d22ac766850c802b1266e48
https://github.com/chrishayesmu/DubBotBase/blob/0e4b5e65531c23293d22ac766850c802b1266e48/src/config.js#L80-L87
54,048
chrishayesmu/DubBotBase
src/config.js
_freezeConfig
function _freezeConfig(config) { Object.freeze(config); for (var key in config) { if (typeof config[key] === "object") { _freezeConfig(config[key]); } } }
javascript
function _freezeConfig(config) { Object.freeze(config); for (var key in config) { if (typeof config[key] === "object") { _freezeConfig(config[key]); } } }
[ "function", "_freezeConfig", "(", "config", ")", "{", "Object", ".", "freeze", "(", "config", ")", ";", "for", "(", "var", "key", "in", "config", ")", "{", "if", "(", "typeof", "config", "[", "key", "]", "===", "\"object\"", ")", "{", "_freezeConfig", "(", "config", "[", "key", "]", ")", ";", "}", "}", "}" ]
Freezes the configuration object and makes it immutable. This is a deep method; all subobjects will also be immutable. @param {object} config - The current config object
[ "Freezes", "the", "configuration", "object", "and", "makes", "it", "immutable", ".", "This", "is", "a", "deep", "method", ";", "all", "subobjects", "will", "also", "be", "immutable", "." ]
0e4b5e65531c23293d22ac766850c802b1266e48
https://github.com/chrishayesmu/DubBotBase/blob/0e4b5e65531c23293d22ac766850c802b1266e48/src/config.js#L95-L103
54,049
chrishayesmu/DubBotBase
src/config.js
_mergeConfig
function _mergeConfig(base, override) { for (var key in override) { if (base[key] && typeof base[key] === "object" && typeof override[key] === "object") { _mergeConfig(base[key], override[key]); } else { base[key] = override[key]; } } }
javascript
function _mergeConfig(base, override) { for (var key in override) { if (base[key] && typeof base[key] === "object" && typeof override[key] === "object") { _mergeConfig(base[key], override[key]); } else { base[key] = override[key]; } } }
[ "function", "_mergeConfig", "(", "base", ",", "override", ")", "{", "for", "(", "var", "key", "in", "override", ")", "{", "if", "(", "base", "[", "key", "]", "&&", "typeof", "base", "[", "key", "]", "===", "\"object\"", "&&", "typeof", "override", "[", "key", "]", "===", "\"object\"", ")", "{", "_mergeConfig", "(", "base", "[", "key", "]", ",", "override", "[", "key", "]", ")", ";", "}", "else", "{", "base", "[", "key", "]", "=", "override", "[", "key", "]", ";", "}", "}", "}" ]
Merges the 'override' object into the 'base' object. Scalar values which exist in both places are overridden, while object values are merged recursively. @param {object} base - The base object to merge into @param {object} override - An object containing overriding values to merge from
[ "Merges", "the", "override", "object", "into", "the", "base", "object", ".", "Scalar", "values", "which", "exist", "in", "both", "places", "are", "overridden", "while", "object", "values", "are", "merged", "recursively", "." ]
0e4b5e65531c23293d22ac766850c802b1266e48
https://github.com/chrishayesmu/DubBotBase/blob/0e4b5e65531c23293d22ac766850c802b1266e48/src/config.js#L112-L121
54,050
chrishayesmu/DubBotBase
src/config.js
_validateConfig
function _validateConfig(config) { for (var i = 0; i < REQUIRED_CONFIG_VARIABLES.length; i++) { var key = REQUIRED_CONFIG_VARIABLES[i]; var value = config.DubBotBase[key]; if (!value || value === "UNSET") { throw new Error("No value has been set in config for key: DubBotBase." + key); } } }
javascript
function _validateConfig(config) { for (var i = 0; i < REQUIRED_CONFIG_VARIABLES.length; i++) { var key = REQUIRED_CONFIG_VARIABLES[i]; var value = config.DubBotBase[key]; if (!value || value === "UNSET") { throw new Error("No value has been set in config for key: DubBotBase." + key); } } }
[ "function", "_validateConfig", "(", "config", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "REQUIRED_CONFIG_VARIABLES", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "REQUIRED_CONFIG_VARIABLES", "[", "i", "]", ";", "var", "value", "=", "config", ".", "DubBotBase", "[", "key", "]", ";", "if", "(", "!", "value", "||", "value", "===", "\"UNSET\"", ")", "{", "throw", "new", "Error", "(", "\"No value has been set in config for key: DubBotBase.\"", "+", "key", ")", ";", "}", "}", "}" ]
Performs validation to ensure the npm environment has been set up properly. If anything is wrong, throws an error. @params {object} config - The current config object to validate
[ "Performs", "validation", "to", "ensure", "the", "npm", "environment", "has", "been", "set", "up", "properly", ".", "If", "anything", "is", "wrong", "throws", "an", "error", "." ]
0e4b5e65531c23293d22ac766850c802b1266e48
https://github.com/chrishayesmu/DubBotBase/blob/0e4b5e65531c23293d22ac766850c802b1266e48/src/config.js#L129-L137
54,051
robgietema/twist
public/libs/less.js/1.3.1/less.js
function () { var value, c = input.charCodeAt(i); if ((c > 57 || c < 45) || c === 47) return; if (value = $(/^(-?\d*\.?\d+)(px|%|em|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn|dpi|dpcm|dppx|rem|vw|vh|vmin|vm|ch)?/)) { return new(tree.Dimension)(value[1], value[2]); } }
javascript
function () { var value, c = input.charCodeAt(i); if ((c > 57 || c < 45) || c === 47) return; if (value = $(/^(-?\d*\.?\d+)(px|%|em|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn|dpi|dpcm|dppx|rem|vw|vh|vmin|vm|ch)?/)) { return new(tree.Dimension)(value[1], value[2]); } }
[ "function", "(", ")", "{", "var", "value", ",", "c", "=", "input", ".", "charCodeAt", "(", "i", ")", ";", "if", "(", "(", "c", ">", "57", "||", "c", "<", "45", ")", "||", "c", "===", "47", ")", "return", ";", "if", "(", "value", "=", "$", "(", "/", "^(-?\\d*\\.?\\d+)(px|%|em|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn|dpi|dpcm|dppx|rem|vw|vh|vmin|vm|ch)?", "/", ")", ")", "{", "return", "new", "(", "tree", ".", "Dimension", ")", "(", "value", "[", "1", "]", ",", "value", "[", "2", "]", ")", ";", "}", "}" ]
A Dimension, that is, a number and a unit 0.5em 95%
[ "A", "Dimension", "that", "is", "a", "number", "and", "a", "unit", "0", ".", "5em", "95%" ]
7dc81080c6c28f34ad8e2334118ff416d2a004a0
https://github.com/robgietema/twist/blob/7dc81080c6c28f34ad8e2334118ff416d2a004a0/public/libs/less.js/1.3.1/less.js#L847-L854
54,052
robgietema/twist
public/libs/tquery/r53/tquery-bundle.js
function(srcUrl, dstW, dstH, callback){ // to compute the width/height while keeping aspect var cpuScaleAspect = function(maxW, maxH, curW, curH){ var ratio = curH / curW; if( curW >= maxW && ratio <= 1 ){ curW = maxW; curH = maxW * ratio; }else if(curH >= maxH){ curH = maxH; curW = maxH / ratio; } return { width: curW, height: curH }; } // callback once the image is loaded var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; var onLoad = __bind(function(){ // init the canvas var canvas = document.createElement('canvas'); canvas.width = dstW; canvas.height = dstH; var ctx = canvas.getContext('2d'); // TODO is this needed ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); // scale the image while preserving the aspect var scaled = cpuScaleAspect(canvas.width, canvas.height, image.width, image.height); // actually draw the image on canvas var offsetX = (canvas.width - scaled.width )/2; var offsetY = (canvas.height - scaled.height)/2; ctx.drawImage(image, offsetX, offsetY, scaled.width, scaled.height); // dump the canvas to an URL var mimetype = "image/png"; var newDataUrl = canvas.toDataURL(mimetype); // notify the url to the caller callback && callback(newDataUrl) }, this); // Create new Image object var image = new Image(); image.onload = onLoad; image.src = srcUrl; }
javascript
function(srcUrl, dstW, dstH, callback){ // to compute the width/height while keeping aspect var cpuScaleAspect = function(maxW, maxH, curW, curH){ var ratio = curH / curW; if( curW >= maxW && ratio <= 1 ){ curW = maxW; curH = maxW * ratio; }else if(curH >= maxH){ curH = maxH; curW = maxH / ratio; } return { width: curW, height: curH }; } // callback once the image is loaded var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; var onLoad = __bind(function(){ // init the canvas var canvas = document.createElement('canvas'); canvas.width = dstW; canvas.height = dstH; var ctx = canvas.getContext('2d'); // TODO is this needed ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); // scale the image while preserving the aspect var scaled = cpuScaleAspect(canvas.width, canvas.height, image.width, image.height); // actually draw the image on canvas var offsetX = (canvas.width - scaled.width )/2; var offsetY = (canvas.height - scaled.height)/2; ctx.drawImage(image, offsetX, offsetY, scaled.width, scaled.height); // dump the canvas to an URL var mimetype = "image/png"; var newDataUrl = canvas.toDataURL(mimetype); // notify the url to the caller callback && callback(newDataUrl) }, this); // Create new Image object var image = new Image(); image.onload = onLoad; image.src = srcUrl; }
[ "function", "(", "srcUrl", ",", "dstW", ",", "dstH", ",", "callback", ")", "{", "// to compute the width/height while keeping aspect", "var", "cpuScaleAspect", "=", "function", "(", "maxW", ",", "maxH", ",", "curW", ",", "curH", ")", "{", "var", "ratio", "=", "curH", "/", "curW", ";", "if", "(", "curW", ">=", "maxW", "&&", "ratio", "<=", "1", ")", "{", "curW", "=", "maxW", ";", "curH", "=", "maxW", "*", "ratio", ";", "}", "else", "if", "(", "curH", ">=", "maxH", ")", "{", "curH", "=", "maxH", ";", "curW", "=", "maxH", "/", "ratio", ";", "}", "return", "{", "width", ":", "curW", ",", "height", ":", "curH", "}", ";", "}", "// callback once the image is loaded", "var", "__bind", "=", "function", "(", "fn", ",", "me", ")", "{", "return", "function", "(", ")", "{", "return", "fn", ".", "apply", "(", "me", ",", "arguments", ")", ";", "}", ";", "}", ";", "var", "onLoad", "=", "__bind", "(", "function", "(", ")", "{", "// init the canvas", "var", "canvas", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "canvas", ".", "width", "=", "dstW", ";", "canvas", ".", "height", "=", "dstH", ";", "var", "ctx", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "// TODO is this needed", "ctx", ".", "fillStyle", "=", "\"black\"", ";", "ctx", ".", "fillRect", "(", "0", ",", "0", ",", "canvas", ".", "width", ",", "canvas", ".", "height", ")", ";", "// scale the image while preserving the aspect", "var", "scaled", "=", "cpuScaleAspect", "(", "canvas", ".", "width", ",", "canvas", ".", "height", ",", "image", ".", "width", ",", "image", ".", "height", ")", ";", "// actually draw the image on canvas", "var", "offsetX", "=", "(", "canvas", ".", "width", "-", "scaled", ".", "width", ")", "/", "2", ";", "var", "offsetY", "=", "(", "canvas", ".", "height", "-", "scaled", ".", "height", ")", "/", "2", ";", "ctx", ".", "drawImage", "(", "image", ",", "offsetX", ",", "offsetY", ",", "scaled", ".", "width", ",", "scaled", ".", "height", ")", ";", "// dump the canvas to an URL\t\t", "var", "mimetype", "=", "\"image/png\"", ";", "var", "newDataUrl", "=", "canvas", ".", "toDataURL", "(", "mimetype", ")", ";", "// notify the url to the caller", "callback", "&&", "callback", "(", "newDataUrl", ")", "}", ",", "this", ")", ";", "// Create new Image object", "var", "image", "=", "new", "Image", "(", ")", ";", "image", ".", "onload", "=", "onLoad", ";", "image", ".", "src", "=", "srcUrl", ";", "}" ]
resize an image to another resolution while preserving aspect @param {String} srcUrl the url of the image to resize @param {Number} dstWidth the destination width of the image @param {Number} dstHeight the destination height of the image @param {Number} callback the callback to notify once completed with callback(newImageUrl)
[ "resize", "an", "image", "to", "another", "resolution", "while", "preserving", "aspect" ]
7dc81080c6c28f34ad8e2334118ff416d2a004a0
https://github.com/robgietema/twist/blob/7dc81080c6c28f34ad8e2334118ff416d2a004a0/public/libs/tquery/r53/tquery-bundle.js#L39155-L39199
54,053
purtuga/observables
src/objectCreateComputedProp.js
objectCreateComputedProp
function objectCreateComputedProp(obj, prop, setter, enumerable = true) { let propValue; let newValue; let needsInitialization = true; let allowSet = false; let needsNewValue = true; let isGeneratingNewValue = false; const dependencyTracker = () => { if (needsNewValue) { return; } needsNewValue = true; // If we have watchers on this computed prop, then queue the // value generator function. // else, just notify dependents. if (alwaysForceExec || setter.forceExec || obj[OBSERVABLE_IDENTIFIER].props[prop].watchers.size) { nextTick.queue(setPropValue); } else if (obj[OBSERVABLE_IDENTIFIER].props[prop].dependents.size) { obj[OBSERVABLE_IDENTIFIER].props[prop].dependents.notify(); } }; const setPropValue = silentSet => { // if there is no longer a need to regenerate the value, exit. // this can happen when other logic accesses the computed getter // between scheduled updates. // Also, in order to avoid looping, if value is currently being // generated, then also exit. if (!needsNewValue || isGeneratingNewValue) { return; } isGeneratingNewValue = true; try { setDependencyTracker(dependencyTracker); newValue = setter.call(obj, obj); unsetDependencyTracker(dependencyTracker); // IMPORTANT: turn if off right after setter is run! if (silentSet) { propValue = newValue; if (obj[OBSERVABLE_IDENTIFIER].props[prop].deep) { makeObservable(propValue); } } else { // Update is done via the prop assignment, which means that // handing of `deep` and all dependent/watcher notifiers is handled // as part of the objectWatchProp() functionality. // Doing the update this way also supports the use of these // objects with other library that may also intercept getter/setters. allowSet = true; needsNewValue = false; obj[prop] = newValue; } } catch (e) { allowSet = needsNewValue = isGeneratingNewValue = false; newValue = undefined; unsetDependencyTracker(dependencyTracker); throw e; } allowSet = needsNewValue = isGeneratingNewValue = false; newValue = undefined; }; dependencyTracker.asDependent = true; dependencyTracker.forProp = setPropValue.forProp = prop; // Does property already exists? Delete it. if (prop in obj) { delete obj[prop]; // Was prop an observable? if so, signal that interceptors must be redefined. if (obj[OBSERVABLE_IDENTIFIER] && obj[OBSERVABLE_IDENTIFIER].props[prop]) { obj[OBSERVABLE_IDENTIFIER].props[prop].setupInterceptors = true; } } defineProperty( obj, prop, undefined, function(){ if (needsInitialization) { needsInitialization = false; setPropValue(true); } else if (needsNewValue) { setPropValue(); } return propValue; }, function () { if (allowSet) { propValue = newValue; } return propValue; }, true, !!enumerable ); objectWatchProp(obj, prop); }
javascript
function objectCreateComputedProp(obj, prop, setter, enumerable = true) { let propValue; let newValue; let needsInitialization = true; let allowSet = false; let needsNewValue = true; let isGeneratingNewValue = false; const dependencyTracker = () => { if (needsNewValue) { return; } needsNewValue = true; // If we have watchers on this computed prop, then queue the // value generator function. // else, just notify dependents. if (alwaysForceExec || setter.forceExec || obj[OBSERVABLE_IDENTIFIER].props[prop].watchers.size) { nextTick.queue(setPropValue); } else if (obj[OBSERVABLE_IDENTIFIER].props[prop].dependents.size) { obj[OBSERVABLE_IDENTIFIER].props[prop].dependents.notify(); } }; const setPropValue = silentSet => { // if there is no longer a need to regenerate the value, exit. // this can happen when other logic accesses the computed getter // between scheduled updates. // Also, in order to avoid looping, if value is currently being // generated, then also exit. if (!needsNewValue || isGeneratingNewValue) { return; } isGeneratingNewValue = true; try { setDependencyTracker(dependencyTracker); newValue = setter.call(obj, obj); unsetDependencyTracker(dependencyTracker); // IMPORTANT: turn if off right after setter is run! if (silentSet) { propValue = newValue; if (obj[OBSERVABLE_IDENTIFIER].props[prop].deep) { makeObservable(propValue); } } else { // Update is done via the prop assignment, which means that // handing of `deep` and all dependent/watcher notifiers is handled // as part of the objectWatchProp() functionality. // Doing the update this way also supports the use of these // objects with other library that may also intercept getter/setters. allowSet = true; needsNewValue = false; obj[prop] = newValue; } } catch (e) { allowSet = needsNewValue = isGeneratingNewValue = false; newValue = undefined; unsetDependencyTracker(dependencyTracker); throw e; } allowSet = needsNewValue = isGeneratingNewValue = false; newValue = undefined; }; dependencyTracker.asDependent = true; dependencyTracker.forProp = setPropValue.forProp = prop; // Does property already exists? Delete it. if (prop in obj) { delete obj[prop]; // Was prop an observable? if so, signal that interceptors must be redefined. if (obj[OBSERVABLE_IDENTIFIER] && obj[OBSERVABLE_IDENTIFIER].props[prop]) { obj[OBSERVABLE_IDENTIFIER].props[prop].setupInterceptors = true; } } defineProperty( obj, prop, undefined, function(){ if (needsInitialization) { needsInitialization = false; setPropValue(true); } else if (needsNewValue) { setPropValue(); } return propValue; }, function () { if (allowSet) { propValue = newValue; } return propValue; }, true, !!enumerable ); objectWatchProp(obj, prop); }
[ "function", "objectCreateComputedProp", "(", "obj", ",", "prop", ",", "setter", ",", "enumerable", "=", "true", ")", "{", "let", "propValue", ";", "let", "newValue", ";", "let", "needsInitialization", "=", "true", ";", "let", "allowSet", "=", "false", ";", "let", "needsNewValue", "=", "true", ";", "let", "isGeneratingNewValue", "=", "false", ";", "const", "dependencyTracker", "=", "(", ")", "=>", "{", "if", "(", "needsNewValue", ")", "{", "return", ";", "}", "needsNewValue", "=", "true", ";", "// If we have watchers on this computed prop, then queue the", "// value generator function.", "// else, just notify dependents.", "if", "(", "alwaysForceExec", "||", "setter", ".", "forceExec", "||", "obj", "[", "OBSERVABLE_IDENTIFIER", "]", ".", "props", "[", "prop", "]", ".", "watchers", ".", "size", ")", "{", "nextTick", ".", "queue", "(", "setPropValue", ")", ";", "}", "else", "if", "(", "obj", "[", "OBSERVABLE_IDENTIFIER", "]", ".", "props", "[", "prop", "]", ".", "dependents", ".", "size", ")", "{", "obj", "[", "OBSERVABLE_IDENTIFIER", "]", ".", "props", "[", "prop", "]", ".", "dependents", ".", "notify", "(", ")", ";", "}", "}", ";", "const", "setPropValue", "=", "silentSet", "=>", "{", "// if there is no longer a need to regenerate the value, exit.", "// this can happen when other logic accesses the computed getter", "// between scheduled updates.", "// Also, in order to avoid looping, if value is currently being", "// generated, then also exit.", "if", "(", "!", "needsNewValue", "||", "isGeneratingNewValue", ")", "{", "return", ";", "}", "isGeneratingNewValue", "=", "true", ";", "try", "{", "setDependencyTracker", "(", "dependencyTracker", ")", ";", "newValue", "=", "setter", ".", "call", "(", "obj", ",", "obj", ")", ";", "unsetDependencyTracker", "(", "dependencyTracker", ")", ";", "// IMPORTANT: turn if off right after setter is run!", "if", "(", "silentSet", ")", "{", "propValue", "=", "newValue", ";", "if", "(", "obj", "[", "OBSERVABLE_IDENTIFIER", "]", ".", "props", "[", "prop", "]", ".", "deep", ")", "{", "makeObservable", "(", "propValue", ")", ";", "}", "}", "else", "{", "// Update is done via the prop assignment, which means that", "// handing of `deep` and all dependent/watcher notifiers is handled", "// as part of the objectWatchProp() functionality.", "// Doing the update this way also supports the use of these", "// objects with other library that may also intercept getter/setters.", "allowSet", "=", "true", ";", "needsNewValue", "=", "false", ";", "obj", "[", "prop", "]", "=", "newValue", ";", "}", "}", "catch", "(", "e", ")", "{", "allowSet", "=", "needsNewValue", "=", "isGeneratingNewValue", "=", "false", ";", "newValue", "=", "undefined", ";", "unsetDependencyTracker", "(", "dependencyTracker", ")", ";", "throw", "e", ";", "}", "allowSet", "=", "needsNewValue", "=", "isGeneratingNewValue", "=", "false", ";", "newValue", "=", "undefined", ";", "}", ";", "dependencyTracker", ".", "asDependent", "=", "true", ";", "dependencyTracker", ".", "forProp", "=", "setPropValue", ".", "forProp", "=", "prop", ";", "// Does property already exists? Delete it.", "if", "(", "prop", "in", "obj", ")", "{", "delete", "obj", "[", "prop", "]", ";", "// Was prop an observable? if so, signal that interceptors must be redefined.", "if", "(", "obj", "[", "OBSERVABLE_IDENTIFIER", "]", "&&", "obj", "[", "OBSERVABLE_IDENTIFIER", "]", ".", "props", "[", "prop", "]", ")", "{", "obj", "[", "OBSERVABLE_IDENTIFIER", "]", ".", "props", "[", "prop", "]", ".", "setupInterceptors", "=", "true", ";", "}", "}", "defineProperty", "(", "obj", ",", "prop", ",", "undefined", ",", "function", "(", ")", "{", "if", "(", "needsInitialization", ")", "{", "needsInitialization", "=", "false", ";", "setPropValue", "(", "true", ")", ";", "}", "else", "if", "(", "needsNewValue", ")", "{", "setPropValue", "(", ")", ";", "}", "return", "propValue", ";", "}", ",", "function", "(", ")", "{", "if", "(", "allowSet", ")", "{", "propValue", "=", "newValue", ";", "}", "return", "propValue", ";", "}", ",", "true", ",", "!", "!", "enumerable", ")", ";", "objectWatchProp", "(", "obj", ",", "prop", ")", ";", "}" ]
Creates a computed property on a given object. @param {Object} obj @param {String} prop @param {Function} setter A callback function that will be used to retrieve the computed prop's value. Function is called with a context (`this`) of the object and will receive one input param - the Object itself. Callback is executed only when the property is accessed or a tracked dependency changes AND watchers or dependents on this computed exist. To force a value to be generated everytime (even if no dependents/watchers) add a property to the function named `forceExec=true`. @param {Boolean} [enumerable=true] @example const obj = { firstName: "paul", lastName: "Tavares" }; objectCreateComputedProp(obj, "name", function () { return `${ this.firstName } ${ this.lastName }`; }); // Or, to always force the callback to generate a value function generateName() { return `${ this.firstName } ${ this.lastName }`; } generateName.forceExec = true; objectCreateComputedProp(obj, "name", genereateName);
[ "Creates", "a", "computed", "property", "on", "a", "given", "object", "." ]
68847b1294734c4cd50b26e5f6156a8b460f77a2
https://github.com/purtuga/observables/blob/68847b1294734c4cd50b26e5f6156a8b460f77a2/src/objectCreateComputedProp.js#L51-L160
54,054
jhermsmeier/node-mime-lib
lib/mime.js
function( input, charset ) { if( charset && !Buffer.isBuffer( input ) ) { return MIME.Iconv.encode( input, charset ) } else { return Buffer.isBuffer( input ) ? input.toString( 'base64' ) : Buffer.from( input ).toString( 'base64' ) } }
javascript
function( input, charset ) { if( charset && !Buffer.isBuffer( input ) ) { return MIME.Iconv.encode( input, charset ) } else { return Buffer.isBuffer( input ) ? input.toString( 'base64' ) : Buffer.from( input ).toString( 'base64' ) } }
[ "function", "(", "input", ",", "charset", ")", "{", "if", "(", "charset", "&&", "!", "Buffer", ".", "isBuffer", "(", "input", ")", ")", "{", "return", "MIME", ".", "Iconv", ".", "encode", "(", "input", ",", "charset", ")", "}", "else", "{", "return", "Buffer", ".", "isBuffer", "(", "input", ")", "?", "input", ".", "toString", "(", "'base64'", ")", ":", "Buffer", ".", "from", "(", "input", ")", ".", "toString", "(", "'base64'", ")", "}", "}" ]
Base64 encodes a buffer or string. @param {String|Buffer} input @param {String} charset @return {String}
[ "Base64", "encodes", "a", "buffer", "or", "string", "." ]
7260792c2ba00720c193a539064f1f939aaa508e
https://github.com/jhermsmeier/node-mime-lib/blob/7260792c2ba00720c193a539064f1f939aaa508e/lib/mime.js#L66-L74
54,055
jhermsmeier/node-mime-lib
lib/mime.js
function( input, charset ) { if( /iso-?2022-?jp/i.test( charset ) ) { charset = 'shift_jis' } if( charset ) { return MIME.Iconv.decode( Buffer.from( input, 'base64' ), charset ) } else { return Buffer.from( input, 'base64' ).toString() } }
javascript
function( input, charset ) { if( /iso-?2022-?jp/i.test( charset ) ) { charset = 'shift_jis' } if( charset ) { return MIME.Iconv.decode( Buffer.from( input, 'base64' ), charset ) } else { return Buffer.from( input, 'base64' ).toString() } }
[ "function", "(", "input", ",", "charset", ")", "{", "if", "(", "/", "iso-?2022-?jp", "/", "i", ".", "test", "(", "charset", ")", ")", "{", "charset", "=", "'shift_jis'", "}", "if", "(", "charset", ")", "{", "return", "MIME", ".", "Iconv", ".", "decode", "(", "Buffer", ".", "from", "(", "input", ",", "'base64'", ")", ",", "charset", ")", "}", "else", "{", "return", "Buffer", ".", "from", "(", "input", ",", "'base64'", ")", ".", "toString", "(", ")", "}", "}" ]
Decodes a base64 encoded string. @param {String} input @param {String} charset @return {String|Buffer}
[ "Decodes", "a", "base64", "encoded", "string", "." ]
7260792c2ba00720c193a539064f1f939aaa508e
https://github.com/jhermsmeier/node-mime-lib/blob/7260792c2ba00720c193a539064f1f939aaa508e/lib/mime.js#L83-L95
54,056
twolfson/icomoon-phantomjs
lib/icomoon-phantomjs.js
waitFor
function waitFor(checkFn, timeout, cb) { var start = Date.now(); function runWaitFor() { if (checkFn()) { cb(); } else if ((Date.now() - start) <= timeout) { setTimeout(runWaitFor, 100); } else { cb(new Error('Timeout of ' + timeout + 'ms reached. This usually means something went wrong. Please try your SVGs inside icomoon itself, https://icomoon.io/app-old')); } } runWaitFor(); }
javascript
function waitFor(checkFn, timeout, cb) { var start = Date.now(); function runWaitFor() { if (checkFn()) { cb(); } else if ((Date.now() - start) <= timeout) { setTimeout(runWaitFor, 100); } else { cb(new Error('Timeout of ' + timeout + 'ms reached. This usually means something went wrong. Please try your SVGs inside icomoon itself, https://icomoon.io/app-old')); } } runWaitFor(); }
[ "function", "waitFor", "(", "checkFn", ",", "timeout", ",", "cb", ")", "{", "var", "start", "=", "Date", ".", "now", "(", ")", ";", "function", "runWaitFor", "(", ")", "{", "if", "(", "checkFn", "(", ")", ")", "{", "cb", "(", ")", ";", "}", "else", "if", "(", "(", "Date", ".", "now", "(", ")", "-", "start", ")", "<=", "timeout", ")", "{", "setTimeout", "(", "runWaitFor", ",", "100", ")", ";", "}", "else", "{", "cb", "(", "new", "Error", "(", "'Timeout of '", "+", "timeout", "+", "'ms reached. This usually means something went wrong. Please try your SVGs inside icomoon itself, https://icomoon.io/app-old'", ")", ")", ";", "}", "}", "runWaitFor", "(", ")", ";", "}" ]
Run a check function every 100 ms
[ "Run", "a", "check", "function", "every", "100", "ms" ]
6c513af003e49c57e81859da2276810fc03d4366
https://github.com/twolfson/icomoon-phantomjs/blob/6c513af003e49c57e81859da2276810fc03d4366/lib/icomoon-phantomjs.js#L20-L32
54,057
ljharb/set-tojson
index.js
function (set, receive) { var values = setValues.call(set); var next; do { next = values.next(); } while (!next.done && receive(next.value)); }
javascript
function (set, receive) { var values = setValues.call(set); var next; do { next = values.next(); } while (!next.done && receive(next.value)); }
[ "function", "(", "set", ",", "receive", ")", "{", "var", "values", "=", "setValues", ".", "call", "(", "set", ")", ";", "var", "next", ";", "do", "{", "next", "=", "values", ".", "next", "(", ")", ";", "}", "while", "(", "!", "next", ".", "done", "&&", "receive", "(", "next", ".", "value", ")", ")", ";", "}" ]
polyfilled Sets with es6-shim might exist without for..of
[ "polyfilled", "Sets", "with", "es6", "-", "shim", "might", "exist", "without", "for", "..", "of" ]
0c39288f0a05c80271eef235c752bbaf087577f5
https://github.com/ljharb/set-tojson/blob/0c39288f0a05c80271eef235c752bbaf087577f5/index.js#L13-L19
54,058
ahultgren/hamster
lib/Cache.js
done
function done () { that.fetchQueue.stopFetching(key, arguments); that.store(key, arguments, callback); }
javascript
function done () { that.fetchQueue.stopFetching(key, arguments); that.store(key, arguments, callback); }
[ "function", "done", "(", ")", "{", "that", ".", "fetchQueue", ".", "stopFetching", "(", "key", ",", "arguments", ")", ";", "that", ".", "store", "(", "key", ",", "arguments", ",", "callback", ")", ";", "}" ]
This callback is used if async
[ "This", "callback", "is", "used", "if", "async" ]
d56acb53d2261fcbc31c8be8ebcce3eafcfd5ffd
https://github.com/ahultgren/hamster/blob/d56acb53d2261fcbc31c8be8ebcce3eafcfd5ffd/lib/Cache.js#L219-L222
54,059
robgietema/twist
public/libs/obviel/1.0b5/obviel-forms.js
function(source, target) { var linkedTarget = $(target); clearLinkedData(target); $.each(source, function(key, sourceValue) { if (isInternal(key)) { return; } var targetValue = null; if ($.isPlainObject(sourceValue)) { targetValue = target[key]; setLinkedData(sourceValue, targetValue); } else if ($.isArray(sourceValue)) { targetValue = target[key]; $.each(sourceValue, function(index, arrayValue) { var targetArrayValue = targetValue[index]; setLinkedData(arrayValue, targetArrayValue); }); } else { linkedTarget.setField(key, sourceValue); } return; }); }
javascript
function(source, target) { var linkedTarget = $(target); clearLinkedData(target); $.each(source, function(key, sourceValue) { if (isInternal(key)) { return; } var targetValue = null; if ($.isPlainObject(sourceValue)) { targetValue = target[key]; setLinkedData(sourceValue, targetValue); } else if ($.isArray(sourceValue)) { targetValue = target[key]; $.each(sourceValue, function(index, arrayValue) { var targetArrayValue = targetValue[index]; setLinkedData(arrayValue, targetArrayValue); }); } else { linkedTarget.setField(key, sourceValue); } return; }); }
[ "function", "(", "source", ",", "target", ")", "{", "var", "linkedTarget", "=", "$", "(", "target", ")", ";", "clearLinkedData", "(", "target", ")", ";", "$", ".", "each", "(", "source", ",", "function", "(", "key", ",", "sourceValue", ")", "{", "if", "(", "isInternal", "(", "key", ")", ")", "{", "return", ";", "}", "var", "targetValue", "=", "null", ";", "if", "(", "$", ".", "isPlainObject", "(", "sourceValue", ")", ")", "{", "targetValue", "=", "target", "[", "key", "]", ";", "setLinkedData", "(", "sourceValue", ",", "targetValue", ")", ";", "}", "else", "if", "(", "$", ".", "isArray", "(", "sourceValue", ")", ")", "{", "targetValue", "=", "target", "[", "key", "]", ";", "$", ".", "each", "(", "sourceValue", ",", "function", "(", "index", ",", "arrayValue", ")", "{", "var", "targetArrayValue", "=", "targetValue", "[", "index", "]", ";", "setLinkedData", "(", "arrayValue", ",", "targetArrayValue", ")", ";", "}", ")", ";", "}", "else", "{", "linkedTarget", ".", "setField", "(", "key", ",", "sourceValue", ")", ";", "}", "return", ";", "}", ")", ";", "}" ]
use setField to set values in target according to source source and target must have same structure
[ "use", "setField", "to", "set", "values", "in", "target", "according", "to", "source", "source", "and", "target", "must", "have", "same", "structure" ]
7dc81080c6c28f34ad8e2334118ff416d2a004a0
https://github.com/robgietema/twist/blob/7dc81080c6c28f34ad8e2334118ff416d2a004a0/public/libs/obviel/1.0b5/obviel-forms.js#L312-L334
54,060
andrezsanchez/css-selector-classes
index.js
getCssSelectorClasses
function getCssSelectorClasses(selector) { var list = [] var ast = cssSelector.parse(selector) visitRules(ast, function(ruleSet) { if (ruleSet.classNames) { list = list.concat(ruleSet.classNames) } }) return uniq(list) }
javascript
function getCssSelectorClasses(selector) { var list = [] var ast = cssSelector.parse(selector) visitRules(ast, function(ruleSet) { if (ruleSet.classNames) { list = list.concat(ruleSet.classNames) } }) return uniq(list) }
[ "function", "getCssSelectorClasses", "(", "selector", ")", "{", "var", "list", "=", "[", "]", "var", "ast", "=", "cssSelector", ".", "parse", "(", "selector", ")", "visitRules", "(", "ast", ",", "function", "(", "ruleSet", ")", "{", "if", "(", "ruleSet", ".", "classNames", ")", "{", "list", "=", "list", ".", "concat", "(", "ruleSet", ".", "classNames", ")", "}", "}", ")", "return", "uniq", "(", "list", ")", "}" ]
Return all the classes in a CSS selector. @param {String} selector A CSS selector @return {String[]} An array of every class present in the CSS selector
[ "Return", "all", "the", "classes", "in", "a", "CSS", "selector", "." ]
8f9a4d60067fa2120b296774dd4be2eae1427428
https://github.com/andrezsanchez/css-selector-classes/blob/8f9a4d60067fa2120b296774dd4be2eae1427428/index.js#L20-L29
54,061
alex-seville/feta
lib/feta.js
loadScript
function loadScript(url) { s = document.createElement('script'); s.src =url; document.body.appendChild(s); }
javascript
function loadScript(url) { s = document.createElement('script'); s.src =url; document.body.appendChild(s); }
[ "function", "loadScript", "(", "url", ")", "{", "s", "=", "document", ".", "createElement", "(", "'script'", ")", ";", "s", ".", "src", "=", "url", ";", "document", ".", "body", ".", "appendChild", "(", "s", ")", ";", "}" ]
Unused for now, but might be handy
[ "Unused", "for", "now", "but", "might", "be", "handy" ]
2ba603320ccba3fec313d26a3a70fab3d6f39e3a
https://github.com/alex-seville/feta/blob/2ba603320ccba3fec313d26a3a70fab3d6f39e3a/lib/feta.js#L15-L19
54,062
mattdesl/kami-texture
index.js
Texture
function Texture(context, options) { if (!(this instanceof Texture)) return new Texture(context, options); //sets up base Kami object.. BaseObject.call(this, context); /** * When a texture is created, we keep track of the arguments provided to * its constructor. On context loss and restore, these arguments are re-supplied * to the Texture, so as to re-create it in its correct form. * * This is mainly useful if you are procedurally creating textures and passing * their data directly (e.g. for generic lookup tables in a shader). For image * or media based textures, it would be better to use an AssetManager to manage * the asynchronous texture upload. * * Upon destroying a texture, a reference to this is also lost. * * @property managedArgs * @type {Object} the options given to the Texture constructor, or undefined */ this.managedArgs = options; /** * The WebGLTexture which backs this Texture object. This * can be used for low-level GL calls. * * @type {WebGLTexture} */ this.id = null; //initialized in create() /** * The target for this texture unit, i.e. TEXTURE_2D. Subclasses * should override the create() method to change this, for correct * usage with context restore. * * @property target * @type {GLenum} * @default gl.TEXTURE_2D */ this.target = this.context.gl.TEXTURE_2D; /** * The width of this texture, in pixels. * * @property width * @readOnly * @type {Number} the width */ this.width = 0; //initialized on texture upload /** * The height of this texture, in pixels. * * @property height * @readOnly * @type {Number} the height */ this.height = 0; //initialized on texture upload this.__shape = [0, 0]; /** * The S wrap parameter. * @property {GLenum} wrapS */ this.wrapS = Texture.DEFAULT_WRAP; /** * The T wrap parameter. * @property {GLenum} wrapT */ this.wrapT = Texture.DEFAULT_WRAP; /** * The minifcation filter. * @property {GLenum} minFilter */ this.minFilter = Texture.DEFAULT_FILTER; /** * The magnification filter. * @property {GLenum} magFilter */ this.magFilter = Texture.DEFAULT_FILTER; //manage if we're dealing with a kami-context this.context.addManagedObject(this); this.create(); }
javascript
function Texture(context, options) { if (!(this instanceof Texture)) return new Texture(context, options); //sets up base Kami object.. BaseObject.call(this, context); /** * When a texture is created, we keep track of the arguments provided to * its constructor. On context loss and restore, these arguments are re-supplied * to the Texture, so as to re-create it in its correct form. * * This is mainly useful if you are procedurally creating textures and passing * their data directly (e.g. for generic lookup tables in a shader). For image * or media based textures, it would be better to use an AssetManager to manage * the asynchronous texture upload. * * Upon destroying a texture, a reference to this is also lost. * * @property managedArgs * @type {Object} the options given to the Texture constructor, or undefined */ this.managedArgs = options; /** * The WebGLTexture which backs this Texture object. This * can be used for low-level GL calls. * * @type {WebGLTexture} */ this.id = null; //initialized in create() /** * The target for this texture unit, i.e. TEXTURE_2D. Subclasses * should override the create() method to change this, for correct * usage with context restore. * * @property target * @type {GLenum} * @default gl.TEXTURE_2D */ this.target = this.context.gl.TEXTURE_2D; /** * The width of this texture, in pixels. * * @property width * @readOnly * @type {Number} the width */ this.width = 0; //initialized on texture upload /** * The height of this texture, in pixels. * * @property height * @readOnly * @type {Number} the height */ this.height = 0; //initialized on texture upload this.__shape = [0, 0]; /** * The S wrap parameter. * @property {GLenum} wrapS */ this.wrapS = Texture.DEFAULT_WRAP; /** * The T wrap parameter. * @property {GLenum} wrapT */ this.wrapT = Texture.DEFAULT_WRAP; /** * The minifcation filter. * @property {GLenum} minFilter */ this.minFilter = Texture.DEFAULT_FILTER; /** * The magnification filter. * @property {GLenum} magFilter */ this.magFilter = Texture.DEFAULT_FILTER; //manage if we're dealing with a kami-context this.context.addManagedObject(this); this.create(); }
[ "function", "Texture", "(", "context", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Texture", ")", ")", "return", "new", "Texture", "(", "context", ",", "options", ")", ";", "//sets up base Kami object..", "BaseObject", ".", "call", "(", "this", ",", "context", ")", ";", "/**\n\t\t * When a texture is created, we keep track of the arguments provided to \n\t\t * its constructor. On context loss and restore, these arguments are re-supplied\n\t\t * to the Texture, so as to re-create it in its correct form.\n\t\t *\n\t\t * This is mainly useful if you are procedurally creating textures and passing\n\t\t * their data directly (e.g. for generic lookup tables in a shader). For image\n\t\t * or media based textures, it would be better to use an AssetManager to manage\n\t\t * the asynchronous texture upload.\n\t\t *\n\t\t * Upon destroying a texture, a reference to this is also lost.\n\t\t *\n\t\t * @property managedArgs\n\t\t * @type {Object} the options given to the Texture constructor, or undefined\n\t\t */", "this", ".", "managedArgs", "=", "options", ";", "/**\n\t\t * The WebGLTexture which backs this Texture object. This\n\t\t * can be used for low-level GL calls.\n\t\t * \n\t\t * @type {WebGLTexture}\n\t\t */", "this", ".", "id", "=", "null", ";", "//initialized in create()", "/**\n\t\t * The target for this texture unit, i.e. TEXTURE_2D. Subclasses\n\t\t * should override the create() method to change this, for correct\n\t\t * usage with context restore.\n\t\t * \n\t\t * @property target\n\t\t * @type {GLenum}\n\t\t * @default gl.TEXTURE_2D\n\t\t */", "this", ".", "target", "=", "this", ".", "context", ".", "gl", ".", "TEXTURE_2D", ";", "/**\n\t\t * The width of this texture, in pixels.\n\t\t * \n\t\t * @property width\n\t\t * @readOnly\n\t\t * @type {Number} the width\n\t\t */", "this", ".", "width", "=", "0", ";", "//initialized on texture upload", "/**\n\t\t * The height of this texture, in pixels.\n\t\t * \n\t\t * @property height\n\t\t * @readOnly\n\t\t * @type {Number} the height\n\t\t */", "this", ".", "height", "=", "0", ";", "//initialized on texture upload", "this", ".", "__shape", "=", "[", "0", ",", "0", "]", ";", "/**\n\t\t * The S wrap parameter.\n\t\t * @property {GLenum} wrapS\n\t\t */", "this", ".", "wrapS", "=", "Texture", ".", "DEFAULT_WRAP", ";", "/**\n\t\t * The T wrap parameter.\n\t\t * @property {GLenum} wrapT\n\t\t */", "this", ".", "wrapT", "=", "Texture", ".", "DEFAULT_WRAP", ";", "/**\n\t\t * The minifcation filter.\n\t\t * @property {GLenum} minFilter \n\t\t */", "this", ".", "minFilter", "=", "Texture", ".", "DEFAULT_FILTER", ";", "/**\n\t\t * The magnification filter.\n\t\t * @property {GLenum} magFilter \n\t\t */", "this", ".", "magFilter", "=", "Texture", ".", "DEFAULT_FILTER", ";", "//manage if we're dealing with a kami-context", "this", ".", "context", ".", "addManagedObject", "(", "this", ")", ";", "this", ".", "create", "(", ")", ";", "}" ]
Creates a new texture with the optional width, height, and data. If the constructor is passed no parameters other than the context, then it will not be initialized and will be non-renderable. You will need to manually uploadData or uploadImage yourself. If the options passed includes 'src', it assumes an image is to be loaded, and will use the width/height from that resulting image. Otherwise, it will look for 'data', which may be a typed array or any valid "image" object. A typed array will need its width/height passed explicitly. If the context is a kami-context, we will try to manage the Texture object by keeping the arguments in memory for future use. Most users will want to use the AssetManager to create and manage their textures with asynchronous loading and context loss. @class Texture @constructor @param {WebGLRenderingContext|kami-context} context the WebGL context @param {Object} options the options to create this texture @param {String} options.src the path to the image file, if ommitted we assume data will be given @param {Function} options.onLoad called when the image is loaded (if src is provided) @param {Function} options.onError called when there was an error loading the image (if src is provided) @param {String} options.crossOrigin the image cross-origin parameter (if src is provided) @param {ArrayBuffer} options.data some typed array with texture data, ignored if 'src' is specified @param {GLenum} options.format the texture format, default Texture.Format.RGBA (for when data is specified) @param {GLenum} options.type the data type, default Texture.DataType.UNSIGNED_BYTE (for when data is specified) @param {Number} options.width the width of the texture (if we are not specifying an image URL) @param {Number} options.height the height of the texture (if we are not specifying an image URL) @param {Boolean} options.genMipmaps whether to generate mipmaps after upload
[ "Creates", "a", "new", "texture", "with", "the", "optional", "width", "height", "and", "data", "." ]
b2659e524fad19aec348a8af519fbbb044116018
https://github.com/mattdesl/kami-texture/blob/b2659e524fad19aec348a8af519fbbb044116018/index.js#L47-L135
54,063
mattdesl/kami-texture
index.js
function(options) { var gl = this.gl; //If no options is provided... this method does nothing. if (!options) return; // width, height, format, dataType, data, genMipmaps //If 'src' is provided, try to load the image from a path... if (options.src && typeof options.src==="string") { var img = new Image(); var path = options.src; var crossOrigin = options.crossOrigin; var successCB = typeof options.onLoad === "function" ? options.onLoad : null; var failCB = typeof options.onError === "function" ? options.onError : null; var genMipmaps = options.genMipmaps; var self = this; //If you try to render a texture that is not yet "renderable" (i.e. the //async load hasn't completed yet, which is always the case in Chrome since requestAnimationFrame //fires before img.onload), WebGL will throw us errors. So instead we will just upload some //dummy data until the texture load is complete. Users can disable this with the global flag. if (Texture.USE_DUMMY_1x1_DATA) { self.uploadData(1, 1); this.width = this.height = 0; } img.crossOrigin = crossOrigin; img.onload = function(ev) { self.uploadImage(img, undefined, undefined, genMipmaps); if (typeof successCB === "function") successCB.call(self, ev, self); } img.onerror = function(ev) { if (genMipmaps) //we still need to gen mipmaps on the 1x1 dummy gl.generateMipmap(gl.TEXTURE_2D); if (typeof failCB === "function") failCB.call(self, ev, self); } img.onabort = function(ev) { if (genMipmaps) gl.generateMipmap(gl.TEXTURE_2D); if (typeof failCB === "function") failCB.call(self, ev, self); } img.src = path; } //otherwise see if we have an 'image' specified else if (options.image) { this.uploadImage(options.image, options.format, options.dataType, options.data, options.genMipmaps); } //otherwise assume our regular list of width/height arguments are passed else { this.uploadData(options.width, options.height, options.format, options.dataType, options.data, options.genMipmaps); } }
javascript
function(options) { var gl = this.gl; //If no options is provided... this method does nothing. if (!options) return; // width, height, format, dataType, data, genMipmaps //If 'src' is provided, try to load the image from a path... if (options.src && typeof options.src==="string") { var img = new Image(); var path = options.src; var crossOrigin = options.crossOrigin; var successCB = typeof options.onLoad === "function" ? options.onLoad : null; var failCB = typeof options.onError === "function" ? options.onError : null; var genMipmaps = options.genMipmaps; var self = this; //If you try to render a texture that is not yet "renderable" (i.e. the //async load hasn't completed yet, which is always the case in Chrome since requestAnimationFrame //fires before img.onload), WebGL will throw us errors. So instead we will just upload some //dummy data until the texture load is complete. Users can disable this with the global flag. if (Texture.USE_DUMMY_1x1_DATA) { self.uploadData(1, 1); this.width = this.height = 0; } img.crossOrigin = crossOrigin; img.onload = function(ev) { self.uploadImage(img, undefined, undefined, genMipmaps); if (typeof successCB === "function") successCB.call(self, ev, self); } img.onerror = function(ev) { if (genMipmaps) //we still need to gen mipmaps on the 1x1 dummy gl.generateMipmap(gl.TEXTURE_2D); if (typeof failCB === "function") failCB.call(self, ev, self); } img.onabort = function(ev) { if (genMipmaps) gl.generateMipmap(gl.TEXTURE_2D); if (typeof failCB === "function") failCB.call(self, ev, self); } img.src = path; } //otherwise see if we have an 'image' specified else if (options.image) { this.uploadImage(options.image, options.format, options.dataType, options.data, options.genMipmaps); } //otherwise assume our regular list of width/height arguments are passed else { this.uploadData(options.width, options.height, options.format, options.dataType, options.data, options.genMipmaps); } }
[ "function", "(", "options", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "//If no options is provided... this method does nothing.", "if", "(", "!", "options", ")", "return", ";", "// width, height, format, dataType, data, genMipmaps", "//If 'src' is provided, try to load the image from a path...", "if", "(", "options", ".", "src", "&&", "typeof", "options", ".", "src", "===", "\"string\"", ")", "{", "var", "img", "=", "new", "Image", "(", ")", ";", "var", "path", "=", "options", ".", "src", ";", "var", "crossOrigin", "=", "options", ".", "crossOrigin", ";", "var", "successCB", "=", "typeof", "options", ".", "onLoad", "===", "\"function\"", "?", "options", ".", "onLoad", ":", "null", ";", "var", "failCB", "=", "typeof", "options", ".", "onError", "===", "\"function\"", "?", "options", ".", "onError", ":", "null", ";", "var", "genMipmaps", "=", "options", ".", "genMipmaps", ";", "var", "self", "=", "this", ";", "//If you try to render a texture that is not yet \"renderable\" (i.e. the ", "//async load hasn't completed yet, which is always the case in Chrome since requestAnimationFrame", "//fires before img.onload), WebGL will throw us errors. So instead we will just upload some", "//dummy data until the texture load is complete. Users can disable this with the global flag.", "if", "(", "Texture", ".", "USE_DUMMY_1x1_DATA", ")", "{", "self", ".", "uploadData", "(", "1", ",", "1", ")", ";", "this", ".", "width", "=", "this", ".", "height", "=", "0", ";", "}", "img", ".", "crossOrigin", "=", "crossOrigin", ";", "img", ".", "onload", "=", "function", "(", "ev", ")", "{", "self", ".", "uploadImage", "(", "img", ",", "undefined", ",", "undefined", ",", "genMipmaps", ")", ";", "if", "(", "typeof", "successCB", "===", "\"function\"", ")", "successCB", ".", "call", "(", "self", ",", "ev", ",", "self", ")", ";", "}", "img", ".", "onerror", "=", "function", "(", "ev", ")", "{", "if", "(", "genMipmaps", ")", "//we still need to gen mipmaps on the 1x1 dummy", "gl", ".", "generateMipmap", "(", "gl", ".", "TEXTURE_2D", ")", ";", "if", "(", "typeof", "failCB", "===", "\"function\"", ")", "failCB", ".", "call", "(", "self", ",", "ev", ",", "self", ")", ";", "}", "img", ".", "onabort", "=", "function", "(", "ev", ")", "{", "if", "(", "genMipmaps", ")", "gl", ".", "generateMipmap", "(", "gl", ".", "TEXTURE_2D", ")", ";", "if", "(", "typeof", "failCB", "===", "\"function\"", ")", "failCB", ".", "call", "(", "self", ",", "ev", ",", "self", ")", ";", "}", "img", ".", "src", "=", "path", ";", "}", "//otherwise see if we have an 'image' specified", "else", "if", "(", "options", ".", "image", ")", "{", "this", ".", "uploadImage", "(", "options", ".", "image", ",", "options", ".", "format", ",", "options", ".", "dataType", ",", "options", ".", "data", ",", "options", ".", "genMipmaps", ")", ";", "}", "//otherwise assume our regular list of width/height arguments are passed", "else", "{", "this", ".", "uploadData", "(", "options", ".", "width", ",", "options", ".", "height", ",", "options", ".", "format", ",", "options", ".", "dataType", ",", "options", ".", "data", ",", "options", ".", "genMipmaps", ")", ";", "}", "}" ]
This can be called after creating a Texture to load an Image object asynchronously, or upload image data directly. It takes the same options as the constructor. Users will generally not need to call this directly. @protected @method setup
[ "This", "can", "be", "called", "after", "creating", "a", "Texture", "to", "load", "an", "Image", "object", "asynchronously", "or", "upload", "image", "data", "directly", ".", "It", "takes", "the", "same", "options", "as", "the", "constructor", "." ]
b2659e524fad19aec348a8af519fbbb044116018
https://github.com/mattdesl/kami-texture/blob/b2659e524fad19aec348a8af519fbbb044116018/index.js#L146-L209
54,064
mattdesl/kami-texture
index.js
function() { if (this.id && this.gl) this.gl.deleteTexture(this.id); if (this.context) this.context.removeManagedObject(this); this.width = this.height = 0; this.id = null; this.managedArgs = null; this.context = null; this.gl = null; }
javascript
function() { if (this.id && this.gl) this.gl.deleteTexture(this.id); if (this.context) this.context.removeManagedObject(this); this.width = this.height = 0; this.id = null; this.managedArgs = null; this.context = null; this.gl = null; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "id", "&&", "this", ".", "gl", ")", "this", ".", "gl", ".", "deleteTexture", "(", "this", ".", "id", ")", ";", "if", "(", "this", ".", "context", ")", "this", ".", "context", ".", "removeManagedObject", "(", "this", ")", ";", "this", ".", "width", "=", "this", ".", "height", "=", "0", ";", "this", ".", "id", "=", "null", ";", "this", ".", "managedArgs", "=", "null", ";", "this", ".", "context", "=", "null", ";", "this", ".", "gl", "=", "null", ";", "}" ]
Destroys this texture by deleting the GL resource, removing it from the WebGLContext management stack, setting its size to zero, and id and managed arguments to null. Trying to use this texture after may lead to undefined behaviour. @method destroy
[ "Destroys", "this", "texture", "by", "deleting", "the", "GL", "resource", "removing", "it", "from", "the", "WebGLContext", "management", "stack", "setting", "its", "size", "to", "zero", "and", "id", "and", "managed", "arguments", "to", "null", "." ]
b2659e524fad19aec348a8af519fbbb044116018
https://github.com/mattdesl/kami-texture/blob/b2659e524fad19aec348a8af519fbbb044116018/index.js#L254-L264
54,065
mattdesl/kami-texture
index.js
function(s, t, ignoreBind) { //TODO: support R wrap mode if (s && t) { this.wrapS = s; this.wrapT = t; } else this.wrapS = this.wrapT = s; //enforce POT rules.. this._checkPOT(); if (!ignoreBind) this.bind(); var gl = this.gl; gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, this.wrapS); gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, this.wrapT); }
javascript
function(s, t, ignoreBind) { //TODO: support R wrap mode if (s && t) { this.wrapS = s; this.wrapT = t; } else this.wrapS = this.wrapT = s; //enforce POT rules.. this._checkPOT(); if (!ignoreBind) this.bind(); var gl = this.gl; gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, this.wrapS); gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, this.wrapT); }
[ "function", "(", "s", ",", "t", ",", "ignoreBind", ")", "{", "//TODO: support R wrap mode", "if", "(", "s", "&&", "t", ")", "{", "this", ".", "wrapS", "=", "s", ";", "this", ".", "wrapT", "=", "t", ";", "}", "else", "this", ".", "wrapS", "=", "this", ".", "wrapT", "=", "s", ";", "//enforce POT rules..", "this", ".", "_checkPOT", "(", ")", ";", "if", "(", "!", "ignoreBind", ")", "this", ".", "bind", "(", ")", ";", "var", "gl", "=", "this", ".", "gl", ";", "gl", ".", "texParameteri", "(", "this", ".", "target", ",", "gl", ".", "TEXTURE_WRAP_S", ",", "this", ".", "wrapS", ")", ";", "gl", ".", "texParameteri", "(", "this", ".", "target", ",", "gl", ".", "TEXTURE_WRAP_T", ",", "this", ".", "wrapT", ")", ";", "}" ]
Sets the wrap mode for this texture; if the second argument is undefined or falsy, then both S and T wrap will use the first argument. You can use Texture.Wrap constants for convenience, to avoid needing a GL reference. @method setWrap @param {GLenum} s the S wrap mode @param {GLenum} t the T wrap mode @param {Boolean} ignoreBind (optional) if true, the bind will be ignored.
[ "Sets", "the", "wrap", "mode", "for", "this", "texture", ";", "if", "the", "second", "argument", "is", "undefined", "or", "falsy", "then", "both", "S", "and", "T", "wrap", "will", "use", "the", "first", "argument", "." ]
b2659e524fad19aec348a8af519fbbb044116018
https://github.com/mattdesl/kami-texture/blob/b2659e524fad19aec348a8af519fbbb044116018/index.js#L279-L295
54,066
mattdesl/kami-texture
index.js
function(min, mag, ignoreBind) { if (min && mag) { this.minFilter = min; this.magFilter = mag; } else this.minFilter = this.magFilter = min; //enforce POT rules.. this._checkPOT(); if (!ignoreBind) this.bind(); var gl = this.gl; gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, this.minFilter); gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, this.magFilter); }
javascript
function(min, mag, ignoreBind) { if (min && mag) { this.minFilter = min; this.magFilter = mag; } else this.minFilter = this.magFilter = min; //enforce POT rules.. this._checkPOT(); if (!ignoreBind) this.bind(); var gl = this.gl; gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, this.minFilter); gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, this.magFilter); }
[ "function", "(", "min", ",", "mag", ",", "ignoreBind", ")", "{", "if", "(", "min", "&&", "mag", ")", "{", "this", ".", "minFilter", "=", "min", ";", "this", ".", "magFilter", "=", "mag", ";", "}", "else", "this", ".", "minFilter", "=", "this", ".", "magFilter", "=", "min", ";", "//enforce POT rules..", "this", ".", "_checkPOT", "(", ")", ";", "if", "(", "!", "ignoreBind", ")", "this", ".", "bind", "(", ")", ";", "var", "gl", "=", "this", ".", "gl", ";", "gl", ".", "texParameteri", "(", "this", ".", "target", ",", "gl", ".", "TEXTURE_MIN_FILTER", ",", "this", ".", "minFilter", ")", ";", "gl", ".", "texParameteri", "(", "this", ".", "target", ",", "gl", ".", "TEXTURE_MAG_FILTER", ",", "this", ".", "magFilter", ")", ";", "}" ]
Sets the min and mag filter for this texture; if mag is undefined or falsy, then both min and mag will use the filter specified for min. You can use Texture.Filter constants for convenience, to avoid needing a GL reference. @method setFilter @param {GLenum} min the minification filter @param {GLenum} mag the magnification filter @param {Boolean} ignoreBind if true, the bind will be ignored.
[ "Sets", "the", "min", "and", "mag", "filter", "for", "this", "texture", ";", "if", "mag", "is", "undefined", "or", "falsy", "then", "both", "min", "and", "mag", "will", "use", "the", "filter", "specified", "for", "min", "." ]
b2659e524fad19aec348a8af519fbbb044116018
https://github.com/mattdesl/kami-texture/blob/b2659e524fad19aec348a8af519fbbb044116018/index.js#L311-L327
54,067
mattdesl/kami-texture
index.js
function(width, height, format, type, data, genMipmaps) { var gl = this.gl; format = format || gl.RGBA; type = type || gl.UNSIGNED_BYTE; data = data || null; //make sure falsey value is null for texImage2D this.width = (width || width==0) ? width : this.width; this.height = (height || height==0) ? height : this.height; this._checkPOT(); this.bind(); gl.texImage2D(this.target, 0, format, this.width, this.height, 0, format, type, data); if (genMipmaps) gl.generateMipmap(this.target); }
javascript
function(width, height, format, type, data, genMipmaps) { var gl = this.gl; format = format || gl.RGBA; type = type || gl.UNSIGNED_BYTE; data = data || null; //make sure falsey value is null for texImage2D this.width = (width || width==0) ? width : this.width; this.height = (height || height==0) ? height : this.height; this._checkPOT(); this.bind(); gl.texImage2D(this.target, 0, format, this.width, this.height, 0, format, type, data); if (genMipmaps) gl.generateMipmap(this.target); }
[ "function", "(", "width", ",", "height", ",", "format", ",", "type", ",", "data", ",", "genMipmaps", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "format", "=", "format", "||", "gl", ".", "RGBA", ";", "type", "=", "type", "||", "gl", ".", "UNSIGNED_BYTE", ";", "data", "=", "data", "||", "null", ";", "//make sure falsey value is null for texImage2D", "this", ".", "width", "=", "(", "width", "||", "width", "==", "0", ")", "?", "width", ":", "this", ".", "width", ";", "this", ".", "height", "=", "(", "height", "||", "height", "==", "0", ")", "?", "height", ":", "this", ".", "height", ";", "this", ".", "_checkPOT", "(", ")", ";", "this", ".", "bind", "(", ")", ";", "gl", ".", "texImage2D", "(", "this", ".", "target", ",", "0", ",", "format", ",", "this", ".", "width", ",", "this", ".", "height", ",", "0", ",", "format", ",", "type", ",", "data", ")", ";", "if", "(", "genMipmaps", ")", "gl", ".", "generateMipmap", "(", "this", ".", "target", ")", ";", "}" ]
A low-level method to upload the specified ArrayBufferView to this texture. This will cause the width and height of this texture to change. @method uploadData @param {Number} width the new width of this texture, defaults to the last used width (or zero) @param {Number} height the new height of this texture defaults to the last used height (or zero) @param {GLenum} format the data format, default RGBA @param {GLenum} type the data type, default UNSIGNED_BYTE (Uint8Array) @param {ArrayBufferView} data the raw data for this texture, or null for an empty image @param {Boolean} genMipmaps whether to generate mipmaps after uploading the data, default false
[ "A", "low", "-", "level", "method", "to", "upload", "the", "specified", "ArrayBufferView", "to", "this", "texture", ".", "This", "will", "cause", "the", "width", "and", "height", "of", "this", "texture", "to", "change", "." ]
b2659e524fad19aec348a8af519fbbb044116018
https://github.com/mattdesl/kami-texture/blob/b2659e524fad19aec348a8af519fbbb044116018/index.js#L344-L364
54,068
mattdesl/kami-texture
index.js
function(domObject, format, type, genMipmaps) { var gl = this.gl; format = format || gl.RGBA; type = type || gl.UNSIGNED_BYTE; this.width = domObject.width; this.height = domObject.height; this._checkPOT(); this.bind(); gl.texImage2D(this.target, 0, format, format, type, domObject); if (genMipmaps) gl.generateMipmap(this.target); }
javascript
function(domObject, format, type, genMipmaps) { var gl = this.gl; format = format || gl.RGBA; type = type || gl.UNSIGNED_BYTE; this.width = domObject.width; this.height = domObject.height; this._checkPOT(); this.bind(); gl.texImage2D(this.target, 0, format, format, type, domObject); if (genMipmaps) gl.generateMipmap(this.target); }
[ "function", "(", "domObject", ",", "format", ",", "type", ",", "genMipmaps", ")", "{", "var", "gl", "=", "this", ".", "gl", ";", "format", "=", "format", "||", "gl", ".", "RGBA", ";", "type", "=", "type", "||", "gl", ".", "UNSIGNED_BYTE", ";", "this", ".", "width", "=", "domObject", ".", "width", ";", "this", ".", "height", "=", "domObject", ".", "height", ";", "this", ".", "_checkPOT", "(", ")", ";", "this", ".", "bind", "(", ")", ";", "gl", ".", "texImage2D", "(", "this", ".", "target", ",", "0", ",", "format", ",", "format", ",", "type", ",", "domObject", ")", ";", "if", "(", "genMipmaps", ")", "gl", ".", "generateMipmap", "(", "this", ".", "target", ")", ";", "}" ]
Uploads ImageData, HTMLImageElement, HTMLCanvasElement or HTMLVideoElement. @method uploadImage @param {Object} domObject the DOM image container @param {GLenum} format the format, default gl.RGBA @param {GLenum} type the data type, default gl.UNSIGNED_BYTE @param {Boolean} genMipmaps whether to generate mipmaps after uploading the data, default false
[ "Uploads", "ImageData", "HTMLImageElement", "HTMLCanvasElement", "or", "HTMLVideoElement", "." ]
b2659e524fad19aec348a8af519fbbb044116018
https://github.com/mattdesl/kami-texture/blob/b2659e524fad19aec348a8af519fbbb044116018/index.js#L376-L394
54,069
mattdesl/kami-texture
index.js
function() { if (!Texture.FORCE_POT) { //If minFilter is anything but LINEAR or NEAREST //or if wrapS or wrapT are not CLAMP_TO_EDGE... var wrongFilter = (this.minFilter !== Texture.Filter.LINEAR && this.minFilter !== Texture.Filter.NEAREST); var wrongWrap = (this.wrapS !== Texture.Wrap.CLAMP_TO_EDGE || this.wrapT !== Texture.Wrap.CLAMP_TO_EDGE); if ( wrongFilter || wrongWrap ) { if (!isPowerOfTwo(this.width) || !isPowerOfTwo(this.height)) throw new Error(wrongFilter ? "Non-power-of-two textures cannot use mipmapping as filter" : "Non-power-of-two textures must use CLAMP_TO_EDGE as wrap"); } } }
javascript
function() { if (!Texture.FORCE_POT) { //If minFilter is anything but LINEAR or NEAREST //or if wrapS or wrapT are not CLAMP_TO_EDGE... var wrongFilter = (this.minFilter !== Texture.Filter.LINEAR && this.minFilter !== Texture.Filter.NEAREST); var wrongWrap = (this.wrapS !== Texture.Wrap.CLAMP_TO_EDGE || this.wrapT !== Texture.Wrap.CLAMP_TO_EDGE); if ( wrongFilter || wrongWrap ) { if (!isPowerOfTwo(this.width) || !isPowerOfTwo(this.height)) throw new Error(wrongFilter ? "Non-power-of-two textures cannot use mipmapping as filter" : "Non-power-of-two textures must use CLAMP_TO_EDGE as wrap"); } } }
[ "function", "(", ")", "{", "if", "(", "!", "Texture", ".", "FORCE_POT", ")", "{", "//If minFilter is anything but LINEAR or NEAREST", "//or if wrapS or wrapT are not CLAMP_TO_EDGE...", "var", "wrongFilter", "=", "(", "this", ".", "minFilter", "!==", "Texture", ".", "Filter", ".", "LINEAR", "&&", "this", ".", "minFilter", "!==", "Texture", ".", "Filter", ".", "NEAREST", ")", ";", "var", "wrongWrap", "=", "(", "this", ".", "wrapS", "!==", "Texture", ".", "Wrap", ".", "CLAMP_TO_EDGE", "||", "this", ".", "wrapT", "!==", "Texture", ".", "Wrap", ".", "CLAMP_TO_EDGE", ")", ";", "if", "(", "wrongFilter", "||", "wrongWrap", ")", "{", "if", "(", "!", "isPowerOfTwo", "(", "this", ".", "width", ")", "||", "!", "isPowerOfTwo", "(", "this", ".", "height", ")", ")", "throw", "new", "Error", "(", "wrongFilter", "?", "\"Non-power-of-two textures cannot use mipmapping as filter\"", ":", "\"Non-power-of-two textures must use CLAMP_TO_EDGE as wrap\"", ")", ";", "}", "}", "}" ]
If FORCE_POT is false, we verify this texture to see if it is valid, as per non-power-of-two rules. If it is non-power-of-two, it must have a wrap mode of CLAMP_TO_EDGE, and the minification filter must be LINEAR or NEAREST. If we don't satisfy these needs, an error is thrown. @method _checkPOT @private @return {[type]} [description]
[ "If", "FORCE_POT", "is", "false", "we", "verify", "this", "texture", "to", "see", "if", "it", "is", "valid", "as", "per", "non", "-", "power", "-", "of", "-", "two", "rules", ".", "If", "it", "is", "non", "-", "power", "-", "of", "-", "two", "it", "must", "have", "a", "wrap", "mode", "of", "CLAMP_TO_EDGE", "and", "the", "minification", "filter", "must", "be", "LINEAR", "or", "NEAREST", ".", "If", "we", "don", "t", "satisfy", "these", "needs", "an", "error", "is", "thrown", "." ]
b2659e524fad19aec348a8af519fbbb044116018
https://github.com/mattdesl/kami-texture/blob/b2659e524fad19aec348a8af519fbbb044116018/index.js#L410-L424
54,070
phil-taylor/nreports
lib/parameter.js
ReportParameter
function ReportParameter(name, type, value) { this.parameterTypes = [ "string", "number", "boolean", "datetime", "date", "time" ]; this.name = name; this.type = type; this.value = value; this.dependsOn = null; //use when you need cascading values this.label = null; // display label this.displayControl = null; // display control }
javascript
function ReportParameter(name, type, value) { this.parameterTypes = [ "string", "number", "boolean", "datetime", "date", "time" ]; this.name = name; this.type = type; this.value = value; this.dependsOn = null; //use when you need cascading values this.label = null; // display label this.displayControl = null; // display control }
[ "function", "ReportParameter", "(", "name", ",", "type", ",", "value", ")", "{", "this", ".", "parameterTypes", "=", "[", "\"string\"", ",", "\"number\"", ",", "\"boolean\"", ",", "\"datetime\"", ",", "\"date\"", ",", "\"time\"", "]", ";", "this", ".", "name", "=", "name", ";", "this", ".", "type", "=", "type", ";", "this", ".", "value", "=", "value", ";", "this", ".", "dependsOn", "=", "null", ";", "//use when you need cascading values", "this", ".", "label", "=", "null", ";", "// display label", "this", ".", "displayControl", "=", "null", ";", "// display control", "}" ]
Defines a reporting parameter used when calling your reporting datasource. @param {String} name @param {String} type @param {Boolean|Number|String} value
[ "Defines", "a", "reporting", "parameter", "used", "when", "calling", "your", "reporting", "datasource", "." ]
ffc7691de1bfb3d81d6dde66fc3c0f95603e7c11
https://github.com/phil-taylor/nreports/blob/ffc7691de1bfb3d81d6dde66fc3c0f95603e7c11/lib/parameter.js#L7-L27
54,071
quantumpayments/hdwallet
lib/util.js
sha2
function sha2(str) { var md = forge.md.sha256.create(); md.update(str); return md.digest().toHex() }
javascript
function sha2(str) { var md = forge.md.sha256.create(); md.update(str); return md.digest().toHex() }
[ "function", "sha2", "(", "str", ")", "{", "var", "md", "=", "forge", ".", "md", ".", "sha256", ".", "create", "(", ")", ";", "md", ".", "update", "(", "str", ")", ";", "return", "md", ".", "digest", "(", ")", ".", "toHex", "(", ")", "}" ]
sha2 get the sha256 of a string @param {String} str the string @return {String} the hash
[ "sha2", "get", "the", "sha256", "of", "a", "string" ]
9f48062b10ee49f145abcb6c9424b8df96c26cd8
https://github.com/quantumpayments/hdwallet/blob/9f48062b10ee49f145abcb6c9424b8df96c26cd8/lib/util.js#L23-L27
54,072
quantumpayments/hdwallet
lib/util.js
hashToInts
function hashToInts(hash) { var arr = [] var num = 4 for (var i = 0; i < 4; i++) { var part = hash.substr(i*8,8) var n = parseInt(part, 16) & 0x7fffffff arr.push(n) } return arr }
javascript
function hashToInts(hash) { var arr = [] var num = 4 for (var i = 0; i < 4; i++) { var part = hash.substr(i*8,8) var n = parseInt(part, 16) & 0x7fffffff arr.push(n) } return arr }
[ "function", "hashToInts", "(", "hash", ")", "{", "var", "arr", "=", "[", "]", "var", "num", "=", "4", "for", "(", "var", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "var", "part", "=", "hash", ".", "substr", "(", "i", "*", "8", ",", "8", ")", "var", "n", "=", "parseInt", "(", "part", ",", "16", ")", "&", "0x7fffffff", "arr", ".", "push", "(", "n", ")", "}", "return", "arr", "}" ]
hashToInts get hash to ints minus first bit @param {String} hash a hex array @return {Array} 4 numbers
[ "hashToInts", "get", "hash", "to", "ints", "minus", "first", "bit" ]
9f48062b10ee49f145abcb6c9424b8df96c26cd8
https://github.com/quantumpayments/hdwallet/blob/9f48062b10ee49f145abcb6c9424b8df96c26cd8/lib/util.js#L34-L46
54,073
quantumpayments/hdwallet
lib/util.js
mnemonicToPubKey
function mnemonicToPubKey(str) { var m = new Mnemonic(str); var xpriv1 = m.toHDPrivateKey(); // no passphrase var xpub1 = xpriv1.hdPublicKey; return xpub1 }
javascript
function mnemonicToPubKey(str) { var m = new Mnemonic(str); var xpriv1 = m.toHDPrivateKey(); // no passphrase var xpub1 = xpriv1.hdPublicKey; return xpub1 }
[ "function", "mnemonicToPubKey", "(", "str", ")", "{", "var", "m", "=", "new", "Mnemonic", "(", "str", ")", ";", "var", "xpriv1", "=", "m", ".", "toHDPrivateKey", "(", ")", ";", "// no passphrase", "var", "xpub1", "=", "xpriv1", ".", "hdPublicKey", ";", "return", "xpub1", "}" ]
get a public key from a mnemonic @param {String} str The mnemonic @return {Object} The HD Public Key
[ "get", "a", "public", "key", "from", "a", "mnemonic" ]
9f48062b10ee49f145abcb6c9424b8df96c26cd8
https://github.com/quantumpayments/hdwallet/blob/9f48062b10ee49f145abcb6c9424b8df96c26cd8/lib/util.js#L53-L62
54,074
quantumpayments/hdwallet
lib/util.js
webidAndPubKeyToAddress
function webidAndPubKeyToAddress(webid, pubKey, testnet) { if (typeof(pubKey) === 'string') { pubKey = new bitcore.HDPublicKey(pubKey) } var hash = sha2(webid) var ints = hashToInts(hash) var dep2 = pubKey.derive(ints[0]).derive(ints[1]).derive(ints[2]).derive(ints[3]) //console.log(dep2); if (testnet) { var address2 = new bitcore.Address(dep2.publicKey, bitcore.Networks.testnet) } else { var address2 = new bitcore.Address(dep2.publicKey) } //console.log(address1); //console.log(address2); return address2 }
javascript
function webidAndPubKeyToAddress(webid, pubKey, testnet) { if (typeof(pubKey) === 'string') { pubKey = new bitcore.HDPublicKey(pubKey) } var hash = sha2(webid) var ints = hashToInts(hash) var dep2 = pubKey.derive(ints[0]).derive(ints[1]).derive(ints[2]).derive(ints[3]) //console.log(dep2); if (testnet) { var address2 = new bitcore.Address(dep2.publicKey, bitcore.Networks.testnet) } else { var address2 = new bitcore.Address(dep2.publicKey) } //console.log(address1); //console.log(address2); return address2 }
[ "function", "webidAndPubKeyToAddress", "(", "webid", ",", "pubKey", ",", "testnet", ")", "{", "if", "(", "typeof", "(", "pubKey", ")", "===", "'string'", ")", "{", "pubKey", "=", "new", "bitcore", ".", "HDPublicKey", "(", "pubKey", ")", "}", "var", "hash", "=", "sha2", "(", "webid", ")", "var", "ints", "=", "hashToInts", "(", "hash", ")", "var", "dep2", "=", "pubKey", ".", "derive", "(", "ints", "[", "0", "]", ")", ".", "derive", "(", "ints", "[", "1", "]", ")", ".", "derive", "(", "ints", "[", "2", "]", ")", ".", "derive", "(", "ints", "[", "3", "]", ")", "//console.log(dep2);", "if", "(", "testnet", ")", "{", "var", "address2", "=", "new", "bitcore", ".", "Address", "(", "dep2", ".", "publicKey", ",", "bitcore", ".", "Networks", ".", "testnet", ")", "}", "else", "{", "var", "address2", "=", "new", "bitcore", ".", "Address", "(", "dep2", ".", "publicKey", ")", "}", "//console.log(address1);", "//console.log(address2);", "return", "address2", "}" ]
get an address from webid and hd pub key @param {String} webid The WebID @param {String} pubKey The HD public key @param {boolean} testnet Use testnet @return {String} bitcoin address
[ "get", "an", "address", "from", "webid", "and", "hd", "pub", "key" ]
9f48062b10ee49f145abcb6c9424b8df96c26cd8
https://github.com/quantumpayments/hdwallet/blob/9f48062b10ee49f145abcb6c9424b8df96c26cd8/lib/util.js#L115-L137
54,075
quantumpayments/hdwallet
lib/util.js
webidAndPrivKeyToAddress
function webidAndPrivKeyToAddress(webid, privKey, testnet) { if (typeof(privKey) === 'string') { privKey = new bitcore.HDPrivateKey(privKey) } var hash = sha2(webid) var ints = hashToInts(hash) var dep2 = privKey.derive(ints[0]).derive(ints[1]).derive(ints[2]).derive(ints[3]) //console.log(dep2); if (testnet) { var address2 = dep2.privateKey } else { var address2 = dep2.privateKey } //console.log(address1); //console.log(address2); return address2 }
javascript
function webidAndPrivKeyToAddress(webid, privKey, testnet) { if (typeof(privKey) === 'string') { privKey = new bitcore.HDPrivateKey(privKey) } var hash = sha2(webid) var ints = hashToInts(hash) var dep2 = privKey.derive(ints[0]).derive(ints[1]).derive(ints[2]).derive(ints[3]) //console.log(dep2); if (testnet) { var address2 = dep2.privateKey } else { var address2 = dep2.privateKey } //console.log(address1); //console.log(address2); return address2 }
[ "function", "webidAndPrivKeyToAddress", "(", "webid", ",", "privKey", ",", "testnet", ")", "{", "if", "(", "typeof", "(", "privKey", ")", "===", "'string'", ")", "{", "privKey", "=", "new", "bitcore", ".", "HDPrivateKey", "(", "privKey", ")", "}", "var", "hash", "=", "sha2", "(", "webid", ")", "var", "ints", "=", "hashToInts", "(", "hash", ")", "var", "dep2", "=", "privKey", ".", "derive", "(", "ints", "[", "0", "]", ")", ".", "derive", "(", "ints", "[", "1", "]", ")", ".", "derive", "(", "ints", "[", "2", "]", ")", ".", "derive", "(", "ints", "[", "3", "]", ")", "//console.log(dep2);", "if", "(", "testnet", ")", "{", "var", "address2", "=", "dep2", ".", "privateKey", "}", "else", "{", "var", "address2", "=", "dep2", ".", "privateKey", "}", "//console.log(address1);", "//console.log(address2);", "return", "address2", "}" ]
get an address from webid and hd priv key @param {String} webid The WebID @param {String} pubKey The HD private key @param {boolean} testnet Use testnet @return {String} bitcoin address
[ "get", "an", "address", "from", "webid", "and", "hd", "priv", "key" ]
9f48062b10ee49f145abcb6c9424b8df96c26cd8
https://github.com/quantumpayments/hdwallet/blob/9f48062b10ee49f145abcb6c9424b8df96c26cd8/lib/util.js#L146-L168
54,076
linyngfly/omelo
lib/connectors/hybrid/switcher.js
function(server, opts) { EventEmitter.call(this); this.server = server; this.wsprocessor = new WSProcessor(); this.tcpprocessor = new TCPProcessor(opts.closeMethod); this.id = 1; this.timeout = (opts.timeout || DEFAULT_TIMEOUT) * 1000; this.setNoDelay = opts.setNoDelay; if (!opts.ssl) { this.server.on('connection', this.newSocket.bind(this)); } else { this.server.on('secureConnection', this.newSocket.bind(this)); this.server.on('clientError', function(e, tlsSo) { logger.warn('an ssl error occured before handshake established: ', e); tlsSo.destroy(); }); } this.wsprocessor.on('connection', this.emit.bind(this, 'connection')); this.tcpprocessor.on('connection', this.emit.bind(this, 'connection')); this.state = ST_STARTED; }
javascript
function(server, opts) { EventEmitter.call(this); this.server = server; this.wsprocessor = new WSProcessor(); this.tcpprocessor = new TCPProcessor(opts.closeMethod); this.id = 1; this.timeout = (opts.timeout || DEFAULT_TIMEOUT) * 1000; this.setNoDelay = opts.setNoDelay; if (!opts.ssl) { this.server.on('connection', this.newSocket.bind(this)); } else { this.server.on('secureConnection', this.newSocket.bind(this)); this.server.on('clientError', function(e, tlsSo) { logger.warn('an ssl error occured before handshake established: ', e); tlsSo.destroy(); }); } this.wsprocessor.on('connection', this.emit.bind(this, 'connection')); this.tcpprocessor.on('connection', this.emit.bind(this, 'connection')); this.state = ST_STARTED; }
[ "function", "(", "server", ",", "opts", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "server", "=", "server", ";", "this", ".", "wsprocessor", "=", "new", "WSProcessor", "(", ")", ";", "this", ".", "tcpprocessor", "=", "new", "TCPProcessor", "(", "opts", ".", "closeMethod", ")", ";", "this", ".", "id", "=", "1", ";", "this", ".", "timeout", "=", "(", "opts", ".", "timeout", "||", "DEFAULT_TIMEOUT", ")", "*", "1000", ";", "this", ".", "setNoDelay", "=", "opts", ".", "setNoDelay", ";", "if", "(", "!", "opts", ".", "ssl", ")", "{", "this", ".", "server", ".", "on", "(", "'connection'", ",", "this", ".", "newSocket", ".", "bind", "(", "this", ")", ")", ";", "}", "else", "{", "this", ".", "server", ".", "on", "(", "'secureConnection'", ",", "this", ".", "newSocket", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "server", ".", "on", "(", "'clientError'", ",", "function", "(", "e", ",", "tlsSo", ")", "{", "logger", ".", "warn", "(", "'an ssl error occured before handshake established: '", ",", "e", ")", ";", "tlsSo", ".", "destroy", "(", ")", ";", "}", ")", ";", "}", "this", ".", "wsprocessor", ".", "on", "(", "'connection'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'connection'", ")", ")", ";", "this", ".", "tcpprocessor", ".", "on", "(", "'connection'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'connection'", ")", ")", ";", "this", ".", "state", "=", "ST_STARTED", ";", "}" ]
Switcher for tcp and websocket protocol @param {Object} server tcp server instance from node.js net module
[ "Switcher", "for", "tcp", "and", "websocket", "protocol" ]
fb5f79fa31c69de36bd1c370bad5edfa753ca601
https://github.com/linyngfly/omelo/blob/fb5f79fa31c69de36bd1c370bad5edfa753ca601/lib/connectors/hybrid/switcher.js#L21-L44
54,077
deanlandolt/bytespace
namespace.js
Namespace
function Namespace(path, hex) { this.hex = !!hex this.keyEncoding = hex ? 'utf8' : 'binary' this.path = path this.buffer = bytewise.encode(path) this.prehooks = [] this.posthooks = [] }
javascript
function Namespace(path, hex) { this.hex = !!hex this.keyEncoding = hex ? 'utf8' : 'binary' this.path = path this.buffer = bytewise.encode(path) this.prehooks = [] this.posthooks = [] }
[ "function", "Namespace", "(", "path", ",", "hex", ")", "{", "this", ".", "hex", "=", "!", "!", "hex", "this", ".", "keyEncoding", "=", "hex", "?", "'utf8'", ":", "'binary'", "this", ".", "path", "=", "path", "this", ".", "buffer", "=", "bytewise", ".", "encode", "(", "path", ")", "this", ".", "prehooks", "=", "[", "]", "this", ".", "posthooks", "=", "[", "]", "}" ]
brand namespace instance to keep track of subspace root
[ "brand", "namespace", "instance", "to", "keep", "track", "of", "subspace", "root" ]
3d3b92d5a8999eedf766fea62bfa7f5643fd467d
https://github.com/deanlandolt/bytespace/blob/3d3b92d5a8999eedf766fea62bfa7f5643fd467d/namespace.js#L12-L20
54,078
gummesson/tiny-csv
index.js
csv
function csv(input, delimiter) { if (!input) return [] delimiter = delimiter || ',' var lines = toArray(input, /\r?\n/) var first = lines.shift() var header = toArray(first, delimiter) var data = lines.map(function(line) { var row = toArray(line, delimiter) return toObject(row, header) }) return data }
javascript
function csv(input, delimiter) { if (!input) return [] delimiter = delimiter || ',' var lines = toArray(input, /\r?\n/) var first = lines.shift() var header = toArray(first, delimiter) var data = lines.map(function(line) { var row = toArray(line, delimiter) return toObject(row, header) }) return data }
[ "function", "csv", "(", "input", ",", "delimiter", ")", "{", "if", "(", "!", "input", ")", "return", "[", "]", "delimiter", "=", "delimiter", "||", "','", "var", "lines", "=", "toArray", "(", "input", ",", "/", "\\r?\\n", "/", ")", "var", "first", "=", "lines", ".", "shift", "(", ")", "var", "header", "=", "toArray", "(", "first", ",", "delimiter", ")", "var", "data", "=", "lines", ".", "map", "(", "function", "(", "line", ")", "{", "var", "row", "=", "toArray", "(", "line", ",", "delimiter", ")", "return", "toObject", "(", "row", ",", "header", ")", "}", ")", "return", "data", "}" ]
Parse a CSV string into an array of objects. @param {String} input @param {String|RegExp} delimiter @return {Array<Object>} @api public
[ "Parse", "a", "CSV", "string", "into", "an", "array", "of", "objects", "." ]
56dca2a417f893380b69009c646ec2b2fc23677f
https://github.com/gummesson/tiny-csv/blob/56dca2a417f893380b69009c646ec2b2fc23677f/index.js#L17-L31
54,079
gummesson/tiny-csv
index.js
toArray
function toArray(line, delimiter) { var arr = line .split(delimiter) .filter(Boolean) return arr }
javascript
function toArray(line, delimiter) { var arr = line .split(delimiter) .filter(Boolean) return arr }
[ "function", "toArray", "(", "line", ",", "delimiter", ")", "{", "var", "arr", "=", "line", ".", "split", "(", "delimiter", ")", ".", "filter", "(", "Boolean", ")", "return", "arr", "}" ]
Parse a string into an array by splitting it at `delimiter` and filtering out empty values. @param {String} line @param {String|RegExp} delimiter @return {Array} @api private
[ "Parse", "a", "string", "into", "an", "array", "by", "splitting", "it", "at", "delimiter", "and", "filtering", "out", "empty", "values", "." ]
56dca2a417f893380b69009c646ec2b2fc23677f
https://github.com/gummesson/tiny-csv/blob/56dca2a417f893380b69009c646ec2b2fc23677f/index.js#L44-L49
54,080
gummesson/tiny-csv
index.js
toObject
function toObject(row, header) { var obj = {} row.forEach(function(value, key) { obj[header[key]] = value }) return obj }
javascript
function toObject(row, header) { var obj = {} row.forEach(function(value, key) { obj[header[key]] = value }) return obj }
[ "function", "toObject", "(", "row", ",", "header", ")", "{", "var", "obj", "=", "{", "}", "row", ".", "forEach", "(", "function", "(", "value", ",", "key", ")", "{", "obj", "[", "header", "[", "key", "]", "]", "=", "value", "}", ")", "return", "obj", "}" ]
Construct an object by using the items in `row` as values and the items in `header` as keys. @param {Array} row @param {Array} header @return {Object} @api private
[ "Construct", "an", "object", "by", "using", "the", "items", "in", "row", "as", "values", "and", "the", "items", "in", "header", "as", "keys", "." ]
56dca2a417f893380b69009c646ec2b2fc23677f
https://github.com/gummesson/tiny-csv/blob/56dca2a417f893380b69009c646ec2b2fc23677f/index.js#L62-L68
54,081
SilentCicero/wafr
bin/wafr.js
writeContractsFile
function writeContractsFile(contractsFilePath, contractsObject, callback) { // eslint-disable-line if (typeof contractsFilePath !== 'string') { return callback(); } if (utils.filenameExtension(contractsFilePath) !== 'json') { throw new Error('Your contracts output file must be a JSON file (i.e. --output ./contracts.json)'); } fs.writeFile(path.resolve(contractsFilePath), JSON.stringify(contractsObject), (writeContractsFileError) => { if (writeContractsFileError) { throw new Error(`while writting output JSON file ${contractsFilePath}: ${writeContractsFileError}`); } callback(); }); }
javascript
function writeContractsFile(contractsFilePath, contractsObject, callback) { // eslint-disable-line if (typeof contractsFilePath !== 'string') { return callback(); } if (utils.filenameExtension(contractsFilePath) !== 'json') { throw new Error('Your contracts output file must be a JSON file (i.e. --output ./contracts.json)'); } fs.writeFile(path.resolve(contractsFilePath), JSON.stringify(contractsObject), (writeContractsFileError) => { if (writeContractsFileError) { throw new Error(`while writting output JSON file ${contractsFilePath}: ${writeContractsFileError}`); } callback(); }); }
[ "function", "writeContractsFile", "(", "contractsFilePath", ",", "contractsObject", ",", "callback", ")", "{", "// eslint-disable-line", "if", "(", "typeof", "contractsFilePath", "!==", "'string'", ")", "{", "return", "callback", "(", ")", ";", "}", "if", "(", "utils", ".", "filenameExtension", "(", "contractsFilePath", ")", "!==", "'json'", ")", "{", "throw", "new", "Error", "(", "'Your contracts output file must be a JSON file (i.e. --output ./contracts.json)'", ")", ";", "}", "fs", ".", "writeFile", "(", "path", ".", "resolve", "(", "contractsFilePath", ")", ",", "JSON", ".", "stringify", "(", "contractsObject", ")", ",", "(", "writeContractsFileError", ")", "=>", "{", "if", "(", "writeContractsFileError", ")", "{", "throw", "new", "Error", "(", "`", "${", "contractsFilePath", "}", "${", "writeContractsFileError", "}", "`", ")", ";", "}", "callback", "(", ")", ";", "}", ")", ";", "}" ]
write contracts file
[ "write", "contracts", "file" ]
2c7483feec5df346d8903cab5badc17143c3876d
https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/bin/wafr.js#L48-L64
54,082
SilentCicero/wafr
bin/wafr.js
writeStatsFile
function writeStatsFile(statsFilePath, statsObject, callback) { // eslint-disable-line if (typeof statsFilePath !== 'string') { return callback(); } if (utils.filenameExtension(statsFilePath) !== 'json') { throw new Error('Your stats output file must be a JSON file (i.e. --stats ./stats.json)'); } fs.writeFile(path.resolve(statsFilePath), JSON.stringify(statsObject, null, 2), (writeStatsFileError) => { if (writeStatsFileError) { throw new Error(`while writting stats JSON file ${statsFilePath}: ${writeStatsFileError}`); } callback(); }); }
javascript
function writeStatsFile(statsFilePath, statsObject, callback) { // eslint-disable-line if (typeof statsFilePath !== 'string') { return callback(); } if (utils.filenameExtension(statsFilePath) !== 'json') { throw new Error('Your stats output file must be a JSON file (i.e. --stats ./stats.json)'); } fs.writeFile(path.resolve(statsFilePath), JSON.stringify(statsObject, null, 2), (writeStatsFileError) => { if (writeStatsFileError) { throw new Error(`while writting stats JSON file ${statsFilePath}: ${writeStatsFileError}`); } callback(); }); }
[ "function", "writeStatsFile", "(", "statsFilePath", ",", "statsObject", ",", "callback", ")", "{", "// eslint-disable-line", "if", "(", "typeof", "statsFilePath", "!==", "'string'", ")", "{", "return", "callback", "(", ")", ";", "}", "if", "(", "utils", ".", "filenameExtension", "(", "statsFilePath", ")", "!==", "'json'", ")", "{", "throw", "new", "Error", "(", "'Your stats output file must be a JSON file (i.e. --stats ./stats.json)'", ")", ";", "}", "fs", ".", "writeFile", "(", "path", ".", "resolve", "(", "statsFilePath", ")", ",", "JSON", ".", "stringify", "(", "statsObject", ",", "null", ",", "2", ")", ",", "(", "writeStatsFileError", ")", "=>", "{", "if", "(", "writeStatsFileError", ")", "{", "throw", "new", "Error", "(", "`", "${", "statsFilePath", "}", "${", "writeStatsFileError", "}", "`", ")", ";", "}", "callback", "(", ")", ";", "}", ")", ";", "}" ]
write stats file
[ "write", "stats", "file" ]
2c7483feec5df346d8903cab5badc17143c3876d
https://github.com/SilentCicero/wafr/blob/2c7483feec5df346d8903cab5badc17143c3876d/bin/wafr.js#L67-L83
54,083
BenoitAverty/cycle-react-driver
src/makeCycleReactDriver.js
makeCycleReactDriver
function makeCycleReactDriver(element, querySelector) { if (typeof element === 'undefined') { throw Error('Missing or invalid react element'); } if (typeof querySelector !== 'string') { throw new Error('Missing or invalid querySelector'); } const source$ = new Rx.ReplaySubject(); const callback = (componentName) => (event) => { source$.next({ event, componentName, }); }; function cycleReactDriver(sink) { const tree = ( <CycleWrapper observable={sink} callback={callback}> {element} </CycleWrapper> ); ReactDOM.render(tree, document.querySelector(querySelector)); return { // Select function: use information passed in event to filter the stream then // map to the actual event. select: comp => source$.filter(e => e.componentName === comp.name).map(e => e.event), }; } cycleReactDriver.streamAdapter = RxJSAdapter; return cycleReactDriver; }
javascript
function makeCycleReactDriver(element, querySelector) { if (typeof element === 'undefined') { throw Error('Missing or invalid react element'); } if (typeof querySelector !== 'string') { throw new Error('Missing or invalid querySelector'); } const source$ = new Rx.ReplaySubject(); const callback = (componentName) => (event) => { source$.next({ event, componentName, }); }; function cycleReactDriver(sink) { const tree = ( <CycleWrapper observable={sink} callback={callback}> {element} </CycleWrapper> ); ReactDOM.render(tree, document.querySelector(querySelector)); return { // Select function: use information passed in event to filter the stream then // map to the actual event. select: comp => source$.filter(e => e.componentName === comp.name).map(e => e.event), }; } cycleReactDriver.streamAdapter = RxJSAdapter; return cycleReactDriver; }
[ "function", "makeCycleReactDriver", "(", "element", ",", "querySelector", ")", "{", "if", "(", "typeof", "element", "===", "'undefined'", ")", "{", "throw", "Error", "(", "'Missing or invalid react element'", ")", ";", "}", "if", "(", "typeof", "querySelector", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'Missing or invalid querySelector'", ")", ";", "}", "const", "source$", "=", "new", "Rx", ".", "ReplaySubject", "(", ")", ";", "const", "callback", "=", "(", "componentName", ")", "=>", "(", "event", ")", "=>", "{", "source$", ".", "next", "(", "{", "event", ",", "componentName", ",", "}", ")", ";", "}", ";", "function", "cycleReactDriver", "(", "sink", ")", "{", "const", "tree", "=", "(", "<", "CycleWrapper", "observable", "=", "{", "sink", "}", "callback", "=", "{", "callback", "}", ">", "\n ", "{", "element", "}", "\n ", "<", "/", "CycleWrapper", ">", ")", ";", "ReactDOM", ".", "render", "(", "tree", ",", "document", ".", "querySelector", "(", "querySelector", ")", ")", ";", "return", "{", "// Select function: use information passed in event to filter the stream then", "// map to the actual event.", "select", ":", "comp", "=>", "source$", ".", "filter", "(", "e", "=>", "e", ".", "componentName", "===", "comp", ".", "name", ")", ".", "map", "(", "e", "=>", "e", ".", "event", ")", ",", "}", ";", "}", "cycleReactDriver", ".", "streamAdapter", "=", "RxJSAdapter", ";", "return", "cycleReactDriver", ";", "}" ]
Factory method for the cycle react driver.
[ "Factory", "method", "for", "the", "cycle", "react", "driver", "." ]
bc5e718ce7ba493792fdbe540c29906c6726404b
https://github.com/BenoitAverty/cycle-react-driver/blob/bc5e718ce7ba493792fdbe540c29906c6726404b/src/makeCycleReactDriver.js#L12-L47
54,084
fcamarlinghi/grunt-esmin
tasks/esmin.js
function (callback, source, dest) { compressor.compress( // Source can either be a file path or source code source, // Options { charset: 'utf8', type: 'js', nomunge: true, 'preserve-semi': true }, // Compressor callback function (error, data, extra) { if (error) { grunt.warn(error); return callback(); } if (extra) grunt.log.writeln(extra); grunt.file.write(dest, data); callback(); } ); }
javascript
function (callback, source, dest) { compressor.compress( // Source can either be a file path or source code source, // Options { charset: 'utf8', type: 'js', nomunge: true, 'preserve-semi': true }, // Compressor callback function (error, data, extra) { if (error) { grunt.warn(error); return callback(); } if (extra) grunt.log.writeln(extra); grunt.file.write(dest, data); callback(); } ); }
[ "function", "(", "callback", ",", "source", ",", "dest", ")", "{", "compressor", ".", "compress", "(", "// Source can either be a file path or source code ", "source", ",", "// Options", "{", "charset", ":", "'utf8'", ",", "type", ":", "'js'", ",", "nomunge", ":", "true", ",", "'preserve-semi'", ":", "true", "}", ",", "// Compressor callback", "function", "(", "error", ",", "data", ",", "extra", ")", "{", "if", "(", "error", ")", "{", "grunt", ".", "warn", "(", "error", ")", ";", "return", "callback", "(", ")", ";", "}", "if", "(", "extra", ")", "grunt", ".", "log", ".", "writeln", "(", "extra", ")", ";", "grunt", ".", "file", ".", "write", "(", "dest", ",", "data", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "}" ]
Minifies the passed extendscript files using YUI.
[ "Minifies", "the", "passed", "extendscript", "files", "using", "YUI", "." ]
2e0ec34cfd9791475469076e562b5ed176ff98ce
https://github.com/fcamarlinghi/grunt-esmin/blob/2e0ec34cfd9791475469076e562b5ed176ff98ce/tasks/esmin.js#L35-L63
54,085
carrascoMDD/protractor-relaunchable
lib/launcher.js
function(task, pid) { this.task = task; this.pid = pid; this.failedCount = 0; this.buffer = ''; this.exitCode = -1; this.insertTag = true; }
javascript
function(task, pid) { this.task = task; this.pid = pid; this.failedCount = 0; this.buffer = ''; this.exitCode = -1; this.insertTag = true; }
[ "function", "(", "task", ",", "pid", ")", "{", "this", ".", "task", "=", "task", ";", "this", ".", "pid", "=", "pid", ";", "this", ".", "failedCount", "=", "0", ";", "this", ".", "buffer", "=", "''", ";", "this", ".", "exitCode", "=", "-", "1", ";", "this", ".", "insertTag", "=", "true", ";", "}" ]
A reporter for a specific task. @constructor @param {object} task Task that is being reported. @param {number} pid PID of process running the task.
[ "A", "reporter", "for", "a", "specific", "task", "." ]
c18e17ecd8b5b036217f87680800c6e14b47361f
https://github.com/carrascoMDD/protractor-relaunchable/blob/c18e17ecd8b5b036217f87680800c6e14b47361f/lib/launcher.js#L236-L243
54,086
senecajs/seneca-level-store
level-store.js
get_db
function get_db (ent, done) { var folder = internals.makefolderpath(opts.folder, ent) var db = dbmap[folder] if (db) { return done(null, db) } internals.ensurefolder(folder, internals.error(done, function () { db = dbmap[folder] if (db) { return done(null, db) } try { db = dbmap[folder] = LevelQuery(Levelup(folder, opts)) db.query.use(JsonqueryEngine()) } catch (e) { db = dbmap[folder] if (db) { return done(null, db) } return done(e) } return done(null, db) })) }
javascript
function get_db (ent, done) { var folder = internals.makefolderpath(opts.folder, ent) var db = dbmap[folder] if (db) { return done(null, db) } internals.ensurefolder(folder, internals.error(done, function () { db = dbmap[folder] if (db) { return done(null, db) } try { db = dbmap[folder] = LevelQuery(Levelup(folder, opts)) db.query.use(JsonqueryEngine()) } catch (e) { db = dbmap[folder] if (db) { return done(null, db) } return done(e) } return done(null, db) })) }
[ "function", "get_db", "(", "ent", ",", "done", ")", "{", "var", "folder", "=", "internals", ".", "makefolderpath", "(", "opts", ".", "folder", ",", "ent", ")", "var", "db", "=", "dbmap", "[", "folder", "]", "if", "(", "db", ")", "{", "return", "done", "(", "null", ",", "db", ")", "}", "internals", ".", "ensurefolder", "(", "folder", ",", "internals", ".", "error", "(", "done", ",", "function", "(", ")", "{", "db", "=", "dbmap", "[", "folder", "]", "if", "(", "db", ")", "{", "return", "done", "(", "null", ",", "db", ")", "}", "try", "{", "db", "=", "dbmap", "[", "folder", "]", "=", "LevelQuery", "(", "Levelup", "(", "folder", ",", "opts", ")", ")", "db", ".", "query", ".", "use", "(", "JsonqueryEngine", "(", ")", ")", "}", "catch", "(", "e", ")", "{", "db", "=", "dbmap", "[", "folder", "]", "if", "(", "db", ")", "{", "return", "done", "(", "null", ",", "db", ")", "}", "return", "done", "(", "e", ")", "}", "return", "done", "(", "null", ",", "db", ")", "}", ")", ")", "}" ]
Get the levelup reference
[ "Get", "the", "levelup", "reference" ]
9ab680cf6dab09d32e942348c82362e25d54c0d2
https://github.com/senecajs/seneca-level-store/blob/9ab680cf6dab09d32e942348c82362e25d54c0d2/level-store.js#L33-L57
54,087
Koyfin/EzetechTechanJS
src/plot/crosshair.js
crosshair
function crosshair(g) { var group = g.selectAll('g.data.top').data([change], function(d) { return d; }), groupEnter = group.enter(), dataEnter = groupEnter.append('g').attr('class', 'data top').style('display', 'none'); group.exit().remove(); dataEnter.append('path').attr('class', 'horizontal wire'); dataEnter.append('path').attr('class', 'vertical wire'); plot.annotation.append(dataEnter, xAnnotation, 'x'); plot.annotation.append(dataEnter, yAnnotation, 'y'); g.selectAll('rect').data([0]).enter().append('rect').style({ fill: 'none', 'pointer-events': 'all' }); crosshair.refresh(g); }
javascript
function crosshair(g) { var group = g.selectAll('g.data.top').data([change], function(d) { return d; }), groupEnter = group.enter(), dataEnter = groupEnter.append('g').attr('class', 'data top').style('display', 'none'); group.exit().remove(); dataEnter.append('path').attr('class', 'horizontal wire'); dataEnter.append('path').attr('class', 'vertical wire'); plot.annotation.append(dataEnter, xAnnotation, 'x'); plot.annotation.append(dataEnter, yAnnotation, 'y'); g.selectAll('rect').data([0]).enter().append('rect').style({ fill: 'none', 'pointer-events': 'all' }); crosshair.refresh(g); }
[ "function", "crosshair", "(", "g", ")", "{", "var", "group", "=", "g", ".", "selectAll", "(", "'g.data.top'", ")", ".", "data", "(", "[", "change", "]", ",", "function", "(", "d", ")", "{", "return", "d", ";", "}", ")", ",", "groupEnter", "=", "group", ".", "enter", "(", ")", ",", "dataEnter", "=", "groupEnter", ".", "append", "(", "'g'", ")", ".", "attr", "(", "'class'", ",", "'data top'", ")", ".", "style", "(", "'display'", ",", "'none'", ")", ";", "group", ".", "exit", "(", ")", ".", "remove", "(", ")", ";", "dataEnter", ".", "append", "(", "'path'", ")", ".", "attr", "(", "'class'", ",", "'horizontal wire'", ")", ";", "dataEnter", ".", "append", "(", "'path'", ")", ".", "attr", "(", "'class'", ",", "'vertical wire'", ")", ";", "plot", ".", "annotation", ".", "append", "(", "dataEnter", ",", "xAnnotation", ",", "'x'", ")", ";", "plot", ".", "annotation", ".", "append", "(", "dataEnter", ",", "yAnnotation", ",", "'y'", ")", ";", "g", ".", "selectAll", "(", "'rect'", ")", ".", "data", "(", "[", "0", "]", ")", ".", "enter", "(", ")", ".", "append", "(", "'rect'", ")", ".", "style", "(", "{", "fill", ":", "'none'", ",", "'pointer-events'", ":", "'all'", "}", ")", ";", "crosshair", ".", "refresh", "(", "g", ")", ";", "}" ]
Track changes to this object, to know when to redraw
[ "Track", "changes", "to", "this", "object", "to", "know", "when", "to", "redraw" ]
9edf5e7401bac127650c64c388e27159e7c03f89
https://github.com/Koyfin/EzetechTechanJS/blob/9edf5e7401bac127650c64c388e27159e7c03f89/src/plot/crosshair.js#L13-L29
54,088
pqml/dom
lib/Component.js
Component
function Component (props) { this._parent = null this._collector = { refs: [], components: [] } /** * > Contains all component properties and children. <br> * > Do not modify it directly, but recreate a new component using `cloneElement` instead * @type {object} * @category Properties */ this.props = props || {} /** * > HTMLElement used as "base" for the component instance. Can also be an array of elements if `template` return an array. * @type {(VNode|HTMLElement|array)} * @category Properties */ this.base = null /** * Set to true when component is mounted * @type {boolean} * @category Properties */ this.mounted = false }
javascript
function Component (props) { this._parent = null this._collector = { refs: [], components: [] } /** * > Contains all component properties and children. <br> * > Do not modify it directly, but recreate a new component using `cloneElement` instead * @type {object} * @category Properties */ this.props = props || {} /** * > HTMLElement used as "base" for the component instance. Can also be an array of elements if `template` return an array. * @type {(VNode|HTMLElement|array)} * @category Properties */ this.base = null /** * Set to true when component is mounted * @type {boolean} * @category Properties */ this.mounted = false }
[ "function", "Component", "(", "props", ")", "{", "this", ".", "_parent", "=", "null", "this", ".", "_collector", "=", "{", "refs", ":", "[", "]", ",", "components", ":", "[", "]", "}", "/**\n * > Contains all component properties and children. <br>\n * > Do not modify it directly, but recreate a new component using `cloneElement` instead\n * @type {object}\n * @category Properties\n */", "this", ".", "props", "=", "props", "||", "{", "}", "/**\n * > HTMLElement used as \"base\" for the component instance. Can also be an array of elements if `template` return an array.\n * @type {(VNode|HTMLElement|array)}\n * @category Properties\n */", "this", ".", "base", "=", "null", "/**\n * Set to true when component is mounted\n * @type {boolean}\n * @category Properties\n */", "this", ".", "mounted", "=", "false", "}" ]
Create a new Component @class Component @param {object} [props={}] Component properties / attributes. Can also contains children. @constructor
[ "Create", "a", "new", "Component" ]
c9dfc7c8237f7662361fc635af4b1e1302260f44
https://github.com/pqml/dom/blob/c9dfc7c8237f7662361fc635af4b1e1302260f44/lib/Component.js#L12-L37
54,089
azemoh/jusibe
index.js
Jusibe
function Jusibe(publicKey, accessToken) { if (!(publicKey || accessToken)) { throw new Error('Provide both Jusibe PUBLIC_KEY and ACCESS_TOKEN'); } if (!(this instanceof Jusibe)) { return new Jusibe(publicKey, accessToken); } this.options = { auth: { user: publicKey, pass: accessToken }, json: true }; }
javascript
function Jusibe(publicKey, accessToken) { if (!(publicKey || accessToken)) { throw new Error('Provide both Jusibe PUBLIC_KEY and ACCESS_TOKEN'); } if (!(this instanceof Jusibe)) { return new Jusibe(publicKey, accessToken); } this.options = { auth: { user: publicKey, pass: accessToken }, json: true }; }
[ "function", "Jusibe", "(", "publicKey", ",", "accessToken", ")", "{", "if", "(", "!", "(", "publicKey", "||", "accessToken", ")", ")", "{", "throw", "new", "Error", "(", "'Provide both Jusibe PUBLIC_KEY and ACCESS_TOKEN'", ")", ";", "}", "if", "(", "!", "(", "this", "instanceof", "Jusibe", ")", ")", "{", "return", "new", "Jusibe", "(", "publicKey", ",", "accessToken", ")", ";", "}", "this", ".", "options", "=", "{", "auth", ":", "{", "user", ":", "publicKey", ",", "pass", ":", "accessToken", "}", ",", "json", ":", "true", "}", ";", "}" ]
Create new Jusibe instances @param {String} publicKey Jusibe Public Key @param {String} accessToken Jusibe Access Token @return {Jusibe}
[ "Create", "new", "Jusibe", "instances" ]
9ebe6a83ea67b732881dfb952cee066f3f88c782
https://github.com/azemoh/jusibe/blob/9ebe6a83ea67b732881dfb952cee066f3f88c782/index.js#L10-L26
54,090
nullivex/oose-sdk
helpers/Prism.js
function(opts){ //setup options this.opts = new ObjectManage({ username: '', password: '', domain: 'cdn.oose.io', prism: { host: null, port: 5971 } }) this.opts.$load(opts) //set properties this.api = {} this.authenticated = false this.connected = false this.session = {} }
javascript
function(opts){ //setup options this.opts = new ObjectManage({ username: '', password: '', domain: 'cdn.oose.io', prism: { host: null, port: 5971 } }) this.opts.$load(opts) //set properties this.api = {} this.authenticated = false this.connected = false this.session = {} }
[ "function", "(", "opts", ")", "{", "//setup options", "this", ".", "opts", "=", "new", "ObjectManage", "(", "{", "username", ":", "''", ",", "password", ":", "''", ",", "domain", ":", "'cdn.oose.io'", ",", "prism", ":", "{", "host", ":", "null", ",", "port", ":", "5971", "}", "}", ")", "this", ".", "opts", ".", "$load", "(", "opts", ")", "//set properties", "this", ".", "api", "=", "{", "}", "this", ".", "authenticated", "=", "false", "this", ".", "connected", "=", "false", "this", ".", "session", "=", "{", "}", "}" ]
Prism Public Interaction Helper @param {object} opts @constructor
[ "Prism", "Public", "Interaction", "Helper" ]
46a3a950107b904825195b2a6645d9db5a3dd5bd
https://github.com/nullivex/oose-sdk/blob/46a3a950107b904825195b2a6645d9db5a3dd5bd/helpers/Prism.js#L21-L38
54,091
spacemaus/postvox
vox-server/interchangedb.js
ensureTimestamps
function ensureTimestamps(columns, allowSyncedAt) { var now = Date.now(); if (!allowSyncedAt || !columns.syncedAt) { columns.syncedAt = now; } if (!columns.createdAt) { // Take the value from the client, if present: columns.createdAt = columns.updatedAt; } }
javascript
function ensureTimestamps(columns, allowSyncedAt) { var now = Date.now(); if (!allowSyncedAt || !columns.syncedAt) { columns.syncedAt = now; } if (!columns.createdAt) { // Take the value from the client, if present: columns.createdAt = columns.updatedAt; } }
[ "function", "ensureTimestamps", "(", "columns", ",", "allowSyncedAt", ")", "{", "var", "now", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "!", "allowSyncedAt", "||", "!", "columns", ".", "syncedAt", ")", "{", "columns", ".", "syncedAt", "=", "now", ";", "}", "if", "(", "!", "columns", ".", "createdAt", ")", "{", "// Take the value from the client, if present:", "columns", ".", "createdAt", "=", "columns", ".", "updatedAt", ";", "}", "}" ]
Sets the `syncedAt` and `createdAt` timestamps, if they are not set.
[ "Sets", "the", "syncedAt", "and", "createdAt", "timestamps", "if", "they", "are", "not", "set", "." ]
de98e5ed37edaee1b1edadf93e15eb8f8d21f457
https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-server/interchangedb.js#L30-L39
54,092
spacemaus/postvox
vox-server/interchangedb.js
_queryForTargetSessions
function _queryForTargetSessions(url, minDbSeq) { var where = { isConnected: true }; if (minDbSeq) { where.connectedAtDbSeq = { gt: minDbSeq }; } return Session.findAll({ where: where, attributes: [ 'sessionId', 'connectedAtDbSeq', ], include: [{ model: Route, where: { routeUrl: url, weight: { gt: 0 } }, attributes: [] }], group: '`Session`.`sessionId`', }, { raw: true }) .then(function(sessions) { var sessionIds = []; var dbSeq = -1; for (var i = 0; i < sessions.length; i++) { var session = sessions[i]; var sessionId = session['sessionId']; sessionIds.push(sessionId); dbSeq = Math.max(session['connectedAtDbSeq'], dbSeq); } return { sessionIds: sessionIds, dbSeq: dbSeq }; }) }
javascript
function _queryForTargetSessions(url, minDbSeq) { var where = { isConnected: true }; if (minDbSeq) { where.connectedAtDbSeq = { gt: minDbSeq }; } return Session.findAll({ where: where, attributes: [ 'sessionId', 'connectedAtDbSeq', ], include: [{ model: Route, where: { routeUrl: url, weight: { gt: 0 } }, attributes: [] }], group: '`Session`.`sessionId`', }, { raw: true }) .then(function(sessions) { var sessionIds = []; var dbSeq = -1; for (var i = 0; i < sessions.length; i++) { var session = sessions[i]; var sessionId = session['sessionId']; sessionIds.push(sessionId); dbSeq = Math.max(session['connectedAtDbSeq'], dbSeq); } return { sessionIds: sessionIds, dbSeq: dbSeq }; }) }
[ "function", "_queryForTargetSessions", "(", "url", ",", "minDbSeq", ")", "{", "var", "where", "=", "{", "isConnected", ":", "true", "}", ";", "if", "(", "minDbSeq", ")", "{", "where", ".", "connectedAtDbSeq", "=", "{", "gt", ":", "minDbSeq", "}", ";", "}", "return", "Session", ".", "findAll", "(", "{", "where", ":", "where", ",", "attributes", ":", "[", "'sessionId'", ",", "'connectedAtDbSeq'", ",", "]", ",", "include", ":", "[", "{", "model", ":", "Route", ",", "where", ":", "{", "routeUrl", ":", "url", ",", "weight", ":", "{", "gt", ":", "0", "}", "}", ",", "attributes", ":", "[", "]", "}", "]", ",", "group", ":", "'`Session`.`sessionId`'", ",", "}", ",", "{", "raw", ":", "true", "}", ")", ".", "then", "(", "function", "(", "sessions", ")", "{", "var", "sessionIds", "=", "[", "]", ";", "var", "dbSeq", "=", "-", "1", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "sessions", ".", "length", ";", "i", "++", ")", "{", "var", "session", "=", "sessions", "[", "i", "]", ";", "var", "sessionId", "=", "session", "[", "'sessionId'", "]", ";", "sessionIds", ".", "push", "(", "sessionId", ")", ";", "dbSeq", "=", "Math", ".", "max", "(", "session", "[", "'connectedAtDbSeq'", "]", ",", "dbSeq", ")", ";", "}", "return", "{", "sessionIds", ":", "sessionIds", ",", "dbSeq", ":", "dbSeq", "}", ";", "}", ")", "}" ]
Queries for sessions that are connected and also have an active route for the given URL. @param {String} url The routeUrl to query for. @param {Number} [minDbSeq] The minimum connectedAtDbSeq to query for.
[ "Queries", "for", "sessions", "that", "are", "connected", "and", "also", "have", "an", "active", "route", "for", "the", "given", "URL", "." ]
de98e5ed37edaee1b1edadf93e15eb8f8d21f457
https://github.com/spacemaus/postvox/blob/de98e5ed37edaee1b1edadf93e15eb8f8d21f457/vox-server/interchangedb.js#L260-L289
54,093
MD4/potato-masher
lib/filter.js
_filter
function _filter(data, schema) { if (typeof data !== 'object' || data === null || schema === null) { return data; } if (schema instanceof Array) { return _filterByArraySchema(data, schema); } if (typeof schema === 'object') { return _filterByObjectSchema(data, schema); } return data; }
javascript
function _filter(data, schema) { if (typeof data !== 'object' || data === null || schema === null) { return data; } if (schema instanceof Array) { return _filterByArraySchema(data, schema); } if (typeof schema === 'object') { return _filterByObjectSchema(data, schema); } return data; }
[ "function", "_filter", "(", "data", ",", "schema", ")", "{", "if", "(", "typeof", "data", "!==", "'object'", "||", "data", "===", "null", "||", "schema", "===", "null", ")", "{", "return", "data", ";", "}", "if", "(", "schema", "instanceof", "Array", ")", "{", "return", "_filterByArraySchema", "(", "data", ",", "schema", ")", ";", "}", "if", "(", "typeof", "schema", "===", "'object'", ")", "{", "return", "_filterByObjectSchema", "(", "data", ",", "schema", ")", ";", "}", "return", "data", ";", "}" ]
private Returns a new object with fields from data and present in the given schema @param data Object to filter @param schema Fields to keep @returns {*} @private
[ "private", "Returns", "a", "new", "object", "with", "fields", "from", "data", "and", "present", "in", "the", "given", "schema" ]
88e21a45350e7204f4102e7186c5beaa8753bd7f
https://github.com/MD4/potato-masher/blob/88e21a45350e7204f4102e7186c5beaa8753bd7f/lib/filter.js#L16-L29
54,094
MD4/potato-masher
lib/filter.js
_filterByArraySchema
function _filterByArraySchema(data, schema) { return Object .keys(data) .filter(function (key) { return !!~schema.indexOf(key); }) .reduce(function (memo, key) { memo[key] = data[key]; return memo; }, {}); }
javascript
function _filterByArraySchema(data, schema) { return Object .keys(data) .filter(function (key) { return !!~schema.indexOf(key); }) .reduce(function (memo, key) { memo[key] = data[key]; return memo; }, {}); }
[ "function", "_filterByArraySchema", "(", "data", ",", "schema", ")", "{", "return", "Object", ".", "keys", "(", "data", ")", ".", "filter", "(", "function", "(", "key", ")", "{", "return", "!", "!", "~", "schema", ".", "indexOf", "(", "key", ")", ";", "}", ")", ".", "reduce", "(", "function", "(", "memo", ",", "key", ")", "{", "memo", "[", "key", "]", "=", "data", "[", "key", "]", ";", "return", "memo", ";", "}", ",", "{", "}", ")", ";", "}" ]
Filters an object from an array schema @param data Object to filter @param schema Fields to keep @returns {*} @private
[ "Filters", "an", "object", "from", "an", "array", "schema" ]
88e21a45350e7204f4102e7186c5beaa8753bd7f
https://github.com/MD4/potato-masher/blob/88e21a45350e7204f4102e7186c5beaa8753bd7f/lib/filter.js#L38-L48
54,095
MD4/potato-masher
lib/filter.js
_filterByObjectSchema
function _filterByObjectSchema(data, schema) { return Object .keys(data) .filter(function (key) { return schema.hasOwnProperty(key); }) .reduce(function (memo, key) { var value = data[key]; var schemaPart = schema[key]; if (typeof schemaPart === 'object') { memo[key] = _filter(value, schemaPart); } else { memo[key] = value; } return memo; }, {}); }
javascript
function _filterByObjectSchema(data, schema) { return Object .keys(data) .filter(function (key) { return schema.hasOwnProperty(key); }) .reduce(function (memo, key) { var value = data[key]; var schemaPart = schema[key]; if (typeof schemaPart === 'object') { memo[key] = _filter(value, schemaPart); } else { memo[key] = value; } return memo; }, {}); }
[ "function", "_filterByObjectSchema", "(", "data", ",", "schema", ")", "{", "return", "Object", ".", "keys", "(", "data", ")", ".", "filter", "(", "function", "(", "key", ")", "{", "return", "schema", ".", "hasOwnProperty", "(", "key", ")", ";", "}", ")", ".", "reduce", "(", "function", "(", "memo", ",", "key", ")", "{", "var", "value", "=", "data", "[", "key", "]", ";", "var", "schemaPart", "=", "schema", "[", "key", "]", ";", "if", "(", "typeof", "schemaPart", "===", "'object'", ")", "{", "memo", "[", "key", "]", "=", "_filter", "(", "value", ",", "schemaPart", ")", ";", "}", "else", "{", "memo", "[", "key", "]", "=", "value", ";", "}", "return", "memo", ";", "}", ",", "{", "}", ")", ";", "}" ]
Filters an object from an object schema @param data Object to filter @param schema Fields to keep @returns {*} @private
[ "Filters", "an", "object", "from", "an", "object", "schema" ]
88e21a45350e7204f4102e7186c5beaa8753bd7f
https://github.com/MD4/potato-masher/blob/88e21a45350e7204f4102e7186c5beaa8753bd7f/lib/filter.js#L57-L73
54,096
tillarnold/fixed-2d-array
lib/fixed-2d-array.js
Fixed2DArray
function Fixed2DArray(rows, cols, defaultValue) { if(rows <= 0 || cols <= 0){ throw new Error('fixed-2d-array: Must have more then 0 rows and 0 columns.'); } this._width = cols; this._height = rows; this._grid = []; for (var i = 0; i < rows; i++) { this._grid[i] = []; for (var j = 0; j < cols; j++) { this._grid[i][j] = defaultValue; } } }
javascript
function Fixed2DArray(rows, cols, defaultValue) { if(rows <= 0 || cols <= 0){ throw new Error('fixed-2d-array: Must have more then 0 rows and 0 columns.'); } this._width = cols; this._height = rows; this._grid = []; for (var i = 0; i < rows; i++) { this._grid[i] = []; for (var j = 0; j < cols; j++) { this._grid[i][j] = defaultValue; } } }
[ "function", "Fixed2DArray", "(", "rows", ",", "cols", ",", "defaultValue", ")", "{", "if", "(", "rows", "<=", "0", "||", "cols", "<=", "0", ")", "{", "throw", "new", "Error", "(", "'fixed-2d-array: Must have more then 0 rows and 0 columns.'", ")", ";", "}", "this", ".", "_width", "=", "cols", ";", "this", ".", "_height", "=", "rows", ";", "this", ".", "_grid", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rows", ";", "i", "++", ")", "{", "this", ".", "_grid", "[", "i", "]", "=", "[", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "cols", ";", "j", "++", ")", "{", "this", ".", "_grid", "[", "i", "]", "[", "j", "]", "=", "defaultValue", ";", "}", "}", "}" ]
An array with a fixed height and width. @param row {number} number of rows, corresponds to the height. @param cols {number} number of columns, corresponds to the width. @param defaultValue the initial value for the array elements @class
[ "An", "array", "with", "a", "fixed", "height", "and", "width", "." ]
39ffdfab7733157bc677ce068c908364f1a74c16
https://github.com/tillarnold/fixed-2d-array/blob/39ffdfab7733157bc677ce068c908364f1a74c16/lib/fixed-2d-array.js#L9-L24
54,097
cliffano/cmdt
lib/cli.js
exec
function exec() { var actions = { commands: { init: { action: _init }, run : { action: _run } } }; cli.command(__dirname, actions); }
javascript
function exec() { var actions = { commands: { init: { action: _init }, run : { action: _run } } }; cli.command(__dirname, actions); }
[ "function", "exec", "(", ")", "{", "var", "actions", "=", "{", "commands", ":", "{", "init", ":", "{", "action", ":", "_init", "}", ",", "run", ":", "{", "action", ":", "_run", "}", "}", "}", ";", "cli", ".", "command", "(", "__dirname", ",", "actions", ")", ";", "}" ]
Execute Cmdt CLI.
[ "Execute", "Cmdt", "CLI", "." ]
8b8de56a23994a02117069c9c6da5fa1a3176fe5
https://github.com/cliffano/cmdt/blob/8b8de56a23994a02117069c9c6da5fa1a3176fe5/lib/cli.js#L30-L40
54,098
megahertz/node-comments-parser
index.js
parse
function parse(content, options) { options = options || {}; options = defaults(options, { addEsprimaInfo: false, parseJsDocTags: true, hideJsDocTags: true, trim: true }); var comments = []; var ast = esprima.parse(content, { tolerant: true, comment: true, tokens: true, range: true, loc: true }).comments; for (var i = 0; i < ast.length; i++) { var node = ast[i]; var lines = node.value.replace(/\r\n/g,'\n').split('\n'); var comment = { start: node.loc.start.line, end: node.loc.end.line }; if (options.addEsprimaInfo) { comment.node = node; } comment.jsDoc = !!(lines[0] && lines[0].trim && '*' === lines[0].trim()); comment.lines = formatLines(lines, comment.jsDoc, options.trim); comment.tags = []; if (options.parseJsDocTags) { applyJsDocTags(comment, options.hideJsDocTags); if (options.hideJsDocTags) { comment.lines = arrayTrim(comment.lines); } } comments.push(comment); } return comments; }
javascript
function parse(content, options) { options = options || {}; options = defaults(options, { addEsprimaInfo: false, parseJsDocTags: true, hideJsDocTags: true, trim: true }); var comments = []; var ast = esprima.parse(content, { tolerant: true, comment: true, tokens: true, range: true, loc: true }).comments; for (var i = 0; i < ast.length; i++) { var node = ast[i]; var lines = node.value.replace(/\r\n/g,'\n').split('\n'); var comment = { start: node.loc.start.line, end: node.loc.end.line }; if (options.addEsprimaInfo) { comment.node = node; } comment.jsDoc = !!(lines[0] && lines[0].trim && '*' === lines[0].trim()); comment.lines = formatLines(lines, comment.jsDoc, options.trim); comment.tags = []; if (options.parseJsDocTags) { applyJsDocTags(comment, options.hideJsDocTags); if (options.hideJsDocTags) { comment.lines = arrayTrim(comment.lines); } } comments.push(comment); } return comments; }
[ "function", "parse", "(", "content", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", "=", "defaults", "(", "options", ",", "{", "addEsprimaInfo", ":", "false", ",", "parseJsDocTags", ":", "true", ",", "hideJsDocTags", ":", "true", ",", "trim", ":", "true", "}", ")", ";", "var", "comments", "=", "[", "]", ";", "var", "ast", "=", "esprima", ".", "parse", "(", "content", ",", "{", "tolerant", ":", "true", ",", "comment", ":", "true", ",", "tokens", ":", "true", ",", "range", ":", "true", ",", "loc", ":", "true", "}", ")", ".", "comments", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ast", ".", "length", ";", "i", "++", ")", "{", "var", "node", "=", "ast", "[", "i", "]", ";", "var", "lines", "=", "node", ".", "value", ".", "replace", "(", "/", "\\r\\n", "/", "g", ",", "'\\n'", ")", ".", "split", "(", "'\\n'", ")", ";", "var", "comment", "=", "{", "start", ":", "node", ".", "loc", ".", "start", ".", "line", ",", "end", ":", "node", ".", "loc", ".", "end", ".", "line", "}", ";", "if", "(", "options", ".", "addEsprimaInfo", ")", "{", "comment", ".", "node", "=", "node", ";", "}", "comment", ".", "jsDoc", "=", "!", "!", "(", "lines", "[", "0", "]", "&&", "lines", "[", "0", "]", ".", "trim", "&&", "'*'", "===", "lines", "[", "0", "]", ".", "trim", "(", ")", ")", ";", "comment", ".", "lines", "=", "formatLines", "(", "lines", ",", "comment", ".", "jsDoc", ",", "options", ".", "trim", ")", ";", "comment", ".", "tags", "=", "[", "]", ";", "if", "(", "options", ".", "parseJsDocTags", ")", "{", "applyJsDocTags", "(", "comment", ",", "options", ".", "hideJsDocTags", ")", ";", "if", "(", "options", ".", "hideJsDocTags", ")", "{", "comment", ".", "lines", "=", "arrayTrim", "(", "comment", ".", "lines", ")", ";", "}", "}", "comments", ".", "push", "(", "comment", ")", ";", "}", "return", "comments", ";", "}" ]
Return array of comment objects @param {string} content @param {Object} [options] @param {boolean} [options.addEsprimaInfo=false] Add node object which is generated by Esprima @param {boolean} [options.parseJsDocTags=true] @param {boolean} [options.hideJsDocTags=true] False to remove lines with jsdoc tags @param {boolean} [options.trim=true] true, false, 'right' @returns {Array<{start, end, lines, jsDoc, tags}>}
[ "Return", "array", "of", "comment", "objects" ]
d849f23bf4210e999a2aa56ebad31588b2199cb5
https://github.com/megahertz/node-comments-parser/blob/d849f23bf4210e999a2aa56ebad31588b2199cb5/index.js#L18-L66
54,099
megahertz/node-comments-parser
index.js
formatLines
function formatLines(lines, jsDoc, trim) { jsDoc = undefined === jsDoc || true; trim = undefined === trim || true; lines = lines.slice(); for (var i = 0; i < lines.length; i++) { var line = lines[i] + ''; if (jsDoc) { line = line.replace(/^\s*\*/, ''); } if ('right' === trim) { line = line.replace(/\s+$/, ''); } else if (trim) { line = line.trim(); } lines[i] = line; } lines = arrayTrim(lines); return lines; }
javascript
function formatLines(lines, jsDoc, trim) { jsDoc = undefined === jsDoc || true; trim = undefined === trim || true; lines = lines.slice(); for (var i = 0; i < lines.length; i++) { var line = lines[i] + ''; if (jsDoc) { line = line.replace(/^\s*\*/, ''); } if ('right' === trim) { line = line.replace(/\s+$/, ''); } else if (trim) { line = line.trim(); } lines[i] = line; } lines = arrayTrim(lines); return lines; }
[ "function", "formatLines", "(", "lines", ",", "jsDoc", ",", "trim", ")", "{", "jsDoc", "=", "undefined", "===", "jsDoc", "||", "true", ";", "trim", "=", "undefined", "===", "trim", "||", "true", ";", "lines", "=", "lines", ".", "slice", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "var", "line", "=", "lines", "[", "i", "]", "+", "''", ";", "if", "(", "jsDoc", ")", "{", "line", "=", "line", ".", "replace", "(", "/", "^\\s*\\*", "/", ",", "''", ")", ";", "}", "if", "(", "'right'", "===", "trim", ")", "{", "line", "=", "line", ".", "replace", "(", "/", "\\s+$", "/", ",", "''", ")", ";", "}", "else", "if", "(", "trim", ")", "{", "line", "=", "line", ".", "trim", "(", ")", ";", "}", "lines", "[", "i", "]", "=", "line", ";", "}", "lines", "=", "arrayTrim", "(", "lines", ")", ";", "return", "lines", ";", "}" ]
Remove whitespace and comment expressions @param {Array<string>} lines @param {boolean} [jsDoc=true] @param {boolean|string} [trim=true] true, false, 'right' @returns {Array}
[ "Remove", "whitespace", "and", "comment", "expressions" ]
d849f23bf4210e999a2aa56ebad31588b2199cb5
https://github.com/megahertz/node-comments-parser/blob/d849f23bf4210e999a2aa56ebad31588b2199cb5/index.js#L75-L99