id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
35,100
psychobunny/nodebb-plugin-gallery
public/vendor/fancybox/jquery.fancybox.js
function (e, onlyAbsolute) { var current = F.current, wrap = current ? current.wrap : null, pos; if (wrap) { pos = F._getPosition(onlyAbsolute); if (e && e.type === 'scroll') { delete pos.position; wrap.stop(true, true).animate(pos, 200); } else { wrap.css(pos); current.pos = $.extend({}, current.dim, pos); } } }
javascript
function (e, onlyAbsolute) { var current = F.current, wrap = current ? current.wrap : null, pos; if (wrap) { pos = F._getPosition(onlyAbsolute); if (e && e.type === 'scroll') { delete pos.position; wrap.stop(true, true).animate(pos, 200); } else { wrap.css(pos); current.pos = $.extend({}, current.dim, pos); } } }
[ "function", "(", "e", ",", "onlyAbsolute", ")", "{", "var", "current", "=", "F", ".", "current", ",", "wrap", "=", "current", "?", "current", ".", "wrap", ":", "null", ",", "pos", ";", "if", "(", "wrap", ")", "{", "pos", "=", "F", ".", "_getPosit...
Center inside viewport and toggle position type to fixed or absolute if needed
[ "Center", "inside", "viewport", "and", "toggle", "position", "type", "to", "fixed", "or", "absolute", "if", "needed" ]
2e90f0f7a2bbfe75585bfee2cfa2df52e9a42631
https://github.com/psychobunny/nodebb-plugin-gallery/blob/2e90f0f7a2bbfe75585bfee2cfa2df52e9a42631/public/vendor/fancybox/jquery.fancybox.js#L527-L546
35,101
psychobunny/nodebb-plugin-gallery
public/vendor/fancybox/jquery.fancybox.js
function ( action ) { if (F.isOpen) { F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView; // Help browser to restore document dimensions if (isTouch) { F.wrap.removeAttr('style').addClass('fancybox-tmp'); F.trigger('onUpdate'); } F.update(); } }
javascript
function ( action ) { if (F.isOpen) { F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView; // Help browser to restore document dimensions if (isTouch) { F.wrap.removeAttr('style').addClass('fancybox-tmp'); F.trigger('onUpdate'); } F.update(); } }
[ "function", "(", "action", ")", "{", "if", "(", "F", ".", "isOpen", ")", "{", "F", ".", "current", ".", "fitToView", "=", "$", ".", "type", "(", "action", ")", "===", "\"boolean\"", "?", "action", ":", "!", "F", ".", "current", ".", "fitToView", ...
Shrink content to fit inside viewport or restore if resized
[ "Shrink", "content", "to", "fit", "inside", "viewport", "or", "restore", "if", "resized" ]
2e90f0f7a2bbfe75585bfee2cfa2df52e9a42631
https://github.com/psychobunny/nodebb-plugin-gallery/blob/2e90f0f7a2bbfe75585bfee2cfa2df52e9a42631/public/vendor/fancybox/jquery.fancybox.js#L587-L600
35,102
psychobunny/nodebb-plugin-gallery
public/vendor/fancybox/jquery.fancybox.js
function(opts) { opts = $.extend({}, this.defaults, opts); if (this.overlay) { this.close(); } this.overlay = $('<div class="fancybox-overlay"></div>').appendTo( F.coming ? F.coming.parent : opts.parent ); this.fixed = false; if (opts.fixed && F.defaults.fixed) { this.overlay.addClass('fancybox-overlay-fixed'); this.fixed = true; } }
javascript
function(opts) { opts = $.extend({}, this.defaults, opts); if (this.overlay) { this.close(); } this.overlay = $('<div class="fancybox-overlay"></div>').appendTo( F.coming ? F.coming.parent : opts.parent ); this.fixed = false; if (opts.fixed && F.defaults.fixed) { this.overlay.addClass('fancybox-overlay-fixed'); this.fixed = true; } }
[ "function", "(", "opts", ")", "{", "opts", "=", "$", ".", "extend", "(", "{", "}", ",", "this", ".", "defaults", ",", "opts", ")", ";", "if", "(", "this", ".", "overlay", ")", "{", "this", ".", "close", "(", ")", ";", "}", "this", ".", "overl...
element that contains "the lock" Public methods
[ "element", "that", "contains", "the", "lock", "Public", "methods" ]
2e90f0f7a2bbfe75585bfee2cfa2df52e9a42631
https://github.com/psychobunny/nodebb-plugin-gallery/blob/2e90f0f7a2bbfe75585bfee2cfa2df52e9a42631/public/vendor/fancybox/jquery.fancybox.js#L1705-L1720
35,103
psychobunny/nodebb-plugin-gallery
public/vendor/fancybox/jquery.fancybox.js
function (opts, obj) { var overlay = this.overlay; $('.fancybox-overlay').stop(true, true); if (!overlay) { this.create(opts); } if (opts.locked && this.fixed && obj.fixed) { if (!overlay) { this.margin = D.height() > W.height() ? $('html').css('margin-right').replace("px", "") : false; } obj.locked = this.overlay.append( obj.wrap ); obj.fixed = false; } if (opts.showEarly === true) { this.beforeShow.apply(this, arguments); } }
javascript
function (opts, obj) { var overlay = this.overlay; $('.fancybox-overlay').stop(true, true); if (!overlay) { this.create(opts); } if (opts.locked && this.fixed && obj.fixed) { if (!overlay) { this.margin = D.height() > W.height() ? $('html').css('margin-right').replace("px", "") : false; } obj.locked = this.overlay.append( obj.wrap ); obj.fixed = false; } if (opts.showEarly === true) { this.beforeShow.apply(this, arguments); } }
[ "function", "(", "opts", ",", "obj", ")", "{", "var", "overlay", "=", "this", ".", "overlay", ";", "$", "(", "'.fancybox-overlay'", ")", ".", "stop", "(", "true", ",", "true", ")", ";", "if", "(", "!", "overlay", ")", "{", "this", ".", "create", ...
This is where we can manipulate DOM, because later it would cause iframes to reload
[ "This", "is", "where", "we", "can", "manipulate", "DOM", "because", "later", "it", "would", "cause", "iframes", "to", "reload" ]
2e90f0f7a2bbfe75585bfee2cfa2df52e9a42631
https://github.com/psychobunny/nodebb-plugin-gallery/blob/2e90f0f7a2bbfe75585bfee2cfa2df52e9a42631/public/vendor/fancybox/jquery.fancybox.js#L1805-L1826
35,104
layerhq/node-layer-api
lib/resources/conversations.js
function(conversationId, callback) { conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); utils.debug('Conversation get: ' + conversationId); request.get({ path: '/conversations/' + conversationId }, callback); }
javascript
function(conversationId, callback) { conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); utils.debug('Conversation get: ' + conversationId); request.get({ path: '/conversations/' + conversationId }, callback); }
[ "function", "(", "conversationId", ",", "callback", ")", "{", "conversationId", "=", "utils", ".", "toUUID", "(", "conversationId", ")", ";", "if", "(", "!", "conversationId", ")", "return", "callback", "(", "new", "Error", "(", "utils", ".", "i18n", ".", ...
Retrieve a conversation @param {String} conversationId Conversation ID @param {Function} callback Callback function
[ "Retrieve", "a", "conversation" ]
284c161350e2cf3d3f5b45f2918798d981f1ada4
https://github.com/layerhq/node-layer-api/blob/284c161350e2cf3d3f5b45f2918798d981f1ada4/lib/resources/conversations.js#L37-L45
35,105
layerhq/node-layer-api
lib/resources/conversations.js
function(userId, conversationId, callback) { if (!userId) return callback(new Error(utils.i18n.conversations.userId)); conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); utils.debug('Conversation getFromUser: ' + userId + ', ' + conversationId); request.get({ path: '/users/' + querystring.escape(userId) + '/conversations/' + conversationId }, callback); }
javascript
function(userId, conversationId, callback) { if (!userId) return callback(new Error(utils.i18n.conversations.userId)); conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); utils.debug('Conversation getFromUser: ' + userId + ', ' + conversationId); request.get({ path: '/users/' + querystring.escape(userId) + '/conversations/' + conversationId }, callback); }
[ "function", "(", "userId", ",", "conversationId", ",", "callback", ")", "{", "if", "(", "!", "userId", ")", "return", "callback", "(", "new", "Error", "(", "utils", ".", "i18n", ".", "conversations", ".", "userId", ")", ")", ";", "conversationId", "=", ...
Retrieve a conversation from user @param {String} userId User ID @param {String} conversationId Conversation ID @param {Function} callback Callback function
[ "Retrieve", "a", "conversation", "from", "user" ]
284c161350e2cf3d3f5b45f2918798d981f1ada4
https://github.com/layerhq/node-layer-api/blob/284c161350e2cf3d3f5b45f2918798d981f1ada4/lib/resources/conversations.js#L54-L63
35,106
layerhq/node-layer-api
lib/resources/conversations.js
function(userId, params, callback) { if (!userId) return callback(new Error(utils.i18n.conversations.userId)); utils.debug('Conversation getAllFromUser: ' + userId); var queryParams = ''; if (typeof params === 'function') callback = params; else queryParams = '?' + querystring.stringify(params); request.get({ path: '/users/' + querystring.escape(userId) + '/conversations' + queryParams }, callback); }
javascript
function(userId, params, callback) { if (!userId) return callback(new Error(utils.i18n.conversations.userId)); utils.debug('Conversation getAllFromUser: ' + userId); var queryParams = ''; if (typeof params === 'function') callback = params; else queryParams = '?' + querystring.stringify(params); request.get({ path: '/users/' + querystring.escape(userId) + '/conversations' + queryParams }, callback); }
[ "function", "(", "userId", ",", "params", ",", "callback", ")", "{", "if", "(", "!", "userId", ")", "return", "callback", "(", "new", "Error", "(", "utils", ".", "i18n", ".", "conversations", ".", "userId", ")", ")", ";", "utils", ".", "debug", "(", ...
Retrieve all conversations from user @param {String} userId User ID @param {String} [params] Query parameters @param {Function} callback Callback function
[ "Retrieve", "all", "conversations", "from", "user" ]
284c161350e2cf3d3f5b45f2918798d981f1ada4
https://github.com/layerhq/node-layer-api/blob/284c161350e2cf3d3f5b45f2918798d981f1ada4/lib/resources/conversations.js#L72-L83
35,107
layerhq/node-layer-api
lib/resources/conversations.js
function(conversationId, operations, callback) { conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); if (!utils.isArray(operations)) return callback(new Error(utils.i18n.conversations.operations)); utils.debug('Conversation edit: ' + conversationId); edit(conversationId, operations, callback); }
javascript
function(conversationId, operations, callback) { conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); if (!utils.isArray(operations)) return callback(new Error(utils.i18n.conversations.operations)); utils.debug('Conversation edit: ' + conversationId); edit(conversationId, operations, callback); }
[ "function", "(", "conversationId", ",", "operations", ",", "callback", ")", "{", "conversationId", "=", "utils", ".", "toUUID", "(", "conversationId", ")", ";", "if", "(", "!", "conversationId", ")", "return", "callback", "(", "new", "Error", "(", "utils", ...
Edit a conversation @param {String} conversationId Conversation UUID @param {Array} operations Array of operations @param {Function} callback Callback function
[ "Edit", "a", "conversation" ]
284c161350e2cf3d3f5b45f2918798d981f1ada4
https://github.com/layerhq/node-layer-api/blob/284c161350e2cf3d3f5b45f2918798d981f1ada4/lib/resources/conversations.js#L92-L99
35,108
layerhq/node-layer-api
lib/resources/conversations.js
function(conversationId, properties, callback) { conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); utils.debug('Conversation setMetadataProperties: ' + conversationId); var operations = []; Object.keys(properties).forEach(function(name) { var fullName = name; if (name !== 'metadata' && name.indexOf('metadata.') !== 0) { fullName = 'metadata.' + name; } operations.push({ operation: 'set', property: fullName, value: String(properties[name]), }); }); edit(conversationId, operations, callback); }
javascript
function(conversationId, properties, callback) { conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); utils.debug('Conversation setMetadataProperties: ' + conversationId); var operations = []; Object.keys(properties).forEach(function(name) { var fullName = name; if (name !== 'metadata' && name.indexOf('metadata.') !== 0) { fullName = 'metadata.' + name; } operations.push({ operation: 'set', property: fullName, value: String(properties[name]), }); }); edit(conversationId, operations, callback); }
[ "function", "(", "conversationId", ",", "properties", ",", "callback", ")", "{", "conversationId", "=", "utils", ".", "toUUID", "(", "conversationId", ")", ";", "if", "(", "!", "conversationId", ")", "return", "callback", "(", "new", "Error", "(", "utils", ...
Set metadata on a conversation @param {String} conversationId Conversation UUID @param {Object} properties Properties object @param {Function} callback Callback function
[ "Set", "metadata", "on", "a", "conversation" ]
284c161350e2cf3d3f5b45f2918798d981f1ada4
https://github.com/layerhq/node-layer-api/blob/284c161350e2cf3d3f5b45f2918798d981f1ada4/lib/resources/conversations.js#L108-L126
35,109
layerhq/node-layer-api
lib/resources/conversations.js
function(conversationId, properties, callback) { conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); utils.debug('Conversation deleteMetadataProperties: ' + conversationId); var operations = []; Object.keys(properties).forEach(function(property) { if (property !== 'metadata' && property.indexOf('metadata.') !== 0) { property = 'metadata.' + property; } operations.push({ operation: 'delete', property: property, }); }); edit(conversationId, operations, callback); }
javascript
function(conversationId, properties, callback) { conversationId = utils.toUUID(conversationId); if (!conversationId) return callback(new Error(utils.i18n.conversations.id)); utils.debug('Conversation deleteMetadataProperties: ' + conversationId); var operations = []; Object.keys(properties).forEach(function(property) { if (property !== 'metadata' && property.indexOf('metadata.') !== 0) { property = 'metadata.' + property; } operations.push({ operation: 'delete', property: property, }); }); edit(conversationId, operations, callback); }
[ "function", "(", "conversationId", ",", "properties", ",", "callback", ")", "{", "conversationId", "=", "utils", ".", "toUUID", "(", "conversationId", ")", ";", "if", "(", "!", "conversationId", ")", "return", "callback", "(", "new", "Error", "(", "utils", ...
Delete metadata on a conversation @param {String} conversationId Conversation UUID @param {Object} properties Properties object @param {Function} callback Callback function
[ "Delete", "metadata", "on", "a", "conversation" ]
284c161350e2cf3d3f5b45f2918798d981f1ada4
https://github.com/layerhq/node-layer-api/blob/284c161350e2cf3d3f5b45f2918798d981f1ada4/lib/resources/conversations.js#L135-L152
35,110
60frames/jestpack
Plugin.js
resolveArgument
function resolveArgument(expr, argIndex) { if (typeof argIndex === 'undefined') { argIndex = 0; } if (!expr.arguments.length || !expr.arguments[argIndex]) { return; } this.applyPluginsBailResult('call require:commonjs:item', expr, this.evaluateExpression(expr.arguments[argIndex])); }
javascript
function resolveArgument(expr, argIndex) { if (typeof argIndex === 'undefined') { argIndex = 0; } if (!expr.arguments.length || !expr.arguments[argIndex]) { return; } this.applyPluginsBailResult('call require:commonjs:item', expr, this.evaluateExpression(expr.arguments[argIndex])); }
[ "function", "resolveArgument", "(", "expr", ",", "argIndex", ")", "{", "if", "(", "typeof", "argIndex", "===", "'undefined'", ")", "{", "argIndex", "=", "0", ";", "}", "if", "(", "!", "expr", ".", "arguments", ".", "length", "||", "!", "expr", ".", "...
Resolves module paths. @param {Object} expr The expression. @param {Number} argIndex Which argument to resolve, defaults to the first arg.
[ "Resolves", "module", "paths", "." ]
2e3c26d856ebe4c1b3b786a26178e3ba81108616
https://github.com/60frames/jestpack/blob/2e3c26d856ebe4c1b3b786a26178e3ba81108616/Plugin.js#L10-L19
35,111
60frames/jestpack
example/webpack.config.js
getEntryPoints
function getEntryPoints(globPattern) { var testFiles = glob.sync(globPattern); var entryPoints = {}; testFiles.forEach(function(file) { entryPoints[file.replace(/\.js$/, '')] = './' + file; }); return entryPoints; }
javascript
function getEntryPoints(globPattern) { var testFiles = glob.sync(globPattern); var entryPoints = {}; testFiles.forEach(function(file) { entryPoints[file.replace(/\.js$/, '')] = './' + file; }); return entryPoints; }
[ "function", "getEntryPoints", "(", "globPattern", ")", "{", "var", "testFiles", "=", "glob", ".", "sync", "(", "globPattern", ")", ";", "var", "entryPoints", "=", "{", "}", ";", "testFiles", ".", "forEach", "(", "function", "(", "file", ")", "{", "entryP...
Given a glob pattern returns the matched paths as an entry point object for Webpack. @param {String} globPattern A glob pattern to match tests. @return {Object} Key value pairs, keyed on filepath.
[ "Given", "a", "glob", "pattern", "returns", "the", "matched", "paths", "as", "an", "entry", "point", "object", "for", "Webpack", "." ]
2e3c26d856ebe4c1b3b786a26178e3ba81108616
https://github.com/60frames/jestpack/blob/2e3c26d856ebe4c1b3b786a26178e3ba81108616/example/webpack.config.js#L13-L20
35,112
Collaborne/gulp-polymer-build-utils
polymer-build.js
polymerBuild
function polymerBuild(config) { const skipRootFolder = function(file) { const rootFolder = config.root || '.'; file.dirname = path.relative(rootFolder, file.dirname); }; const project = new build.PolymerProject(config); const bundler = project.bundler({ // XXX: sourcemaps makes V8 run out of memory sourcemaps: false, stripComments: true, }).on('error', e => console.error(e)); return merge(project.sources(), project.dependencies()) .pipe(bundler) .pipe(size({title: 'polymer-bundler'})) .pipe(rename(skipRootFolder)); }
javascript
function polymerBuild(config) { const skipRootFolder = function(file) { const rootFolder = config.root || '.'; file.dirname = path.relative(rootFolder, file.dirname); }; const project = new build.PolymerProject(config); const bundler = project.bundler({ // XXX: sourcemaps makes V8 run out of memory sourcemaps: false, stripComments: true, }).on('error', e => console.error(e)); return merge(project.sources(), project.dependencies()) .pipe(bundler) .pipe(size({title: 'polymer-bundler'})) .pipe(rename(skipRootFolder)); }
[ "function", "polymerBuild", "(", "config", ")", "{", "const", "skipRootFolder", "=", "function", "(", "file", ")", "{", "const", "rootFolder", "=", "config", ".", "root", "||", "'.'", ";", "file", ".", "dirname", "=", "path", ".", "relative", "(", "rootF...
Executes the polymer-build, which a.o. vulcanizes and minifies the HTML @param {Object} config Content of polymer.json @returns
[ "Executes", "the", "polymer", "-", "build", "which", "a", ".", "o", ".", "vulcanizes", "and", "minifies", "the", "HTML" ]
76f83ea018f726a9e4390444deef65dbe9dde1ff
https://github.com/Collaborne/gulp-polymer-build-utils/blob/76f83ea018f726a9e4390444deef65dbe9dde1ff/polymer-build.js#L15-L33
35,113
medialab/sandcrawler
src/helpers.js
serializeError
function serializeError(err) { var o = {}; Object.getOwnPropertyNames(err).forEach(function (k) { o[k] = err[k]; }); return _.omit(o, ['stack', 'type', 'arguments']); }
javascript
function serializeError(err) { var o = {}; Object.getOwnPropertyNames(err).forEach(function (k) { o[k] = err[k]; }); return _.omit(o, ['stack', 'type', 'arguments']); }
[ "function", "serializeError", "(", "err", ")", "{", "var", "o", "=", "{", "}", ";", "Object", ".", "getOwnPropertyNames", "(", "err", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "o", "[", "k", "]", "=", "err", "[", "k", "]", ";", ...
Serialize a JavaScript error
[ "Serialize", "a", "JavaScript", "error" ]
c08e19095eee42c8ce1f84685960e5ea6cb0fd1d
https://github.com/medialab/sandcrawler/blob/c08e19095eee42c8ce1f84685960e5ea6cb0fd1d/src/helpers.js#L34-L42
35,114
medialab/sandcrawler
src/helpers.js
serializeCookie
function serializeCookie(cookie) { return { path: cookie.path, name: cookie.key, value: cookie.value, domain: cookie.domain }; }
javascript
function serializeCookie(cookie) { return { path: cookie.path, name: cookie.key, value: cookie.value, domain: cookie.domain }; }
[ "function", "serializeCookie", "(", "cookie", ")", "{", "return", "{", "path", ":", "cookie", ".", "path", ",", "name", ":", "cookie", ".", "key", ",", "value", ":", "cookie", ".", "value", ",", "domain", ":", "cookie", ".", "domain", "}", ";", "}" ]
Serialize a tough-cookie Cookie instance
[ "Serialize", "a", "tough", "-", "cookie", "Cookie", "instance" ]
c08e19095eee42c8ce1f84685960e5ea6cb0fd1d
https://github.com/medialab/sandcrawler/blob/c08e19095eee42c8ce1f84685960e5ea6cb0fd1d/src/helpers.js#L45-L52
35,115
dbkaplun/hterm-umdjs
dist/index.js
norm16
function norm16(v) { v = parseInt(v, 16); return size == 2 ? v : // 16 bit size == 1 ? v << 4 : // 8 bit v >> (4 * (size - 2)); // 24 or 32 bit }
javascript
function norm16(v) { v = parseInt(v, 16); return size == 2 ? v : // 16 bit size == 1 ? v << 4 : // 8 bit v >> (4 * (size - 2)); // 24 or 32 bit }
[ "function", "norm16", "(", "v", ")", "{", "v", "=", "parseInt", "(", "v", ",", "16", ")", ";", "return", "size", "==", "2", "?", "v", ":", "// 16 bit", "size", "==", "1", "?", "v", "<<", "4", ":", "// 8 bit", "v", ">>", "(", "4", "*", "(", ...
Normalize to 16 bits.
[ "Normalize", "to", "16", "bits", "." ]
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L485-L490
35,116
dbkaplun/hterm-umdjs
dist/index.js
format
function format(value) { if (typeof value == 'number') return value; var str = String(value); var ary = str.split('\n').map((e) => JSON.stringify(e)); if (ary.length > 1) { // If the string has newlines, start it off on its own line so that // it's easier to compare against another string with newlines. return '\n' + ary.join('\n'); } else { return ary.join('\n'); } }
javascript
function format(value) { if (typeof value == 'number') return value; var str = String(value); var ary = str.split('\n').map((e) => JSON.stringify(e)); if (ary.length > 1) { // If the string has newlines, start it off on its own line so that // it's easier to compare against another string with newlines. return '\n' + ary.join('\n'); } else { return ary.join('\n'); } }
[ "function", "format", "(", "value", ")", "{", "if", "(", "typeof", "value", "==", "'number'", ")", "return", "value", ";", "var", "str", "=", "String", "(", "value", ")", ";", "var", "ary", "=", "str", ".", "split", "(", "'\\n'", ")", ".", "map", ...
Utility function to pretty up the log.
[ "Utility", "function", "to", "pretty", "up", "the", "log", "." ]
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L4536-L4549
35,117
dbkaplun/hterm-umdjs
dist/index.js
ak
function ak(a, b) { return function(e, k) { var action = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || !self.keyboard.applicationKeypad) ? a : b; return resolve(action, e, k); }; }
javascript
function ak(a, b) { return function(e, k) { var action = (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || !self.keyboard.applicationKeypad) ? a : b; return resolve(action, e, k); }; }
[ "function", "ak", "(", "a", ",", "b", ")", "{", "return", "function", "(", "e", ",", "k", ")", "{", "var", "action", "=", "(", "e", ".", "shiftKey", "||", "e", ".", "ctrlKey", "||", "e", ".", "altKey", "||", "e", ".", "metaKey", "||", "!", "s...
If not application keypad a, else b. The keys that care about application keypad ignore it when the key is modified.
[ "If", "not", "application", "keypad", "a", "else", "b", ".", "The", "keys", "that", "care", "about", "application", "keypad", "ignore", "it", "when", "the", "key", "is", "modified", "." ]
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L7298-L7304
35,118
dbkaplun/hterm-umdjs
dist/index.js
bs
function bs(a, b) { return function(e, k) { var action = !self.keyboard.backspaceSendsBackspace ? a : b; return resolve(action, e, k); }; }
javascript
function bs(a, b) { return function(e, k) { var action = !self.keyboard.backspaceSendsBackspace ? a : b; return resolve(action, e, k); }; }
[ "function", "bs", "(", "a", ",", "b", ")", "{", "return", "function", "(", "e", ",", "k", ")", "{", "var", "action", "=", "!", "self", ".", "keyboard", ".", "backspaceSendsBackspace", "?", "a", ":", "b", ";", "return", "resolve", "(", "action", ","...
If not backspace-sends-backspace keypad a, else b.
[ "If", "not", "backspace", "-", "sends", "-", "backspace", "keypad", "a", "else", "b", "." ]
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L7317-L7322
35,119
dbkaplun/hterm-umdjs
dist/index.js
alt
function alt(a, b) { return function(e, k) { var action = !e.altKey ? a : b; return resolve(action, e, k); }; }
javascript
function alt(a, b) { return function(e, k) { var action = !e.altKey ? a : b; return resolve(action, e, k); }; }
[ "function", "alt", "(", "a", ",", "b", ")", "{", "return", "function", "(", "e", ",", "k", ")", "{", "var", "action", "=", "!", "e", ".", "altKey", "?", "a", ":", "b", ";", "return", "resolve", "(", "action", ",", "e", ",", "k", ")", ";", "...
If not e.altKey a, else b.
[ "If", "not", "e", ".", "altKey", "a", "else", "b", "." ]
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L7334-L7339
35,120
dbkaplun/hterm-umdjs
dist/index.js
mod
function mod(a, b) { return function(e, k) { var action = !(e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) ? a : b; return resolve(action, e, k); }; }
javascript
function mod(a, b) { return function(e, k) { var action = !(e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) ? a : b; return resolve(action, e, k); }; }
[ "function", "mod", "(", "a", ",", "b", ")", "{", "return", "function", "(", "e", ",", "k", ")", "{", "var", "action", "=", "!", "(", "e", ".", "shiftKey", "||", "e", ".", "ctrlKey", "||", "e", ".", "altKey", "||", "e", ".", "metaKey", ")", "?...
If no modifiers a, else b.
[ "If", "no", "modifiers", "a", "else", "b", "." ]
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L7342-L7347
35,121
dbkaplun/hterm-umdjs
dist/index.js
med
function med(fn) { return function(e, k) { if (!self.keyboard.mediaKeysAreFKeys) { // Block Back, Forward, and Reload keys to avoid navigating away from // the current page. return (e.keyCode == 166 || e.keyCode == 167 || e.keyCode == 168) ? hterm.Keyboard.KeyActions.CANCEL : hterm.Keyboard.KeyActions.PASS; } return resolve(fn, e, k); }; }
javascript
function med(fn) { return function(e, k) { if (!self.keyboard.mediaKeysAreFKeys) { // Block Back, Forward, and Reload keys to avoid navigating away from // the current page. return (e.keyCode == 166 || e.keyCode == 167 || e.keyCode == 168) ? hterm.Keyboard.KeyActions.CANCEL : hterm.Keyboard.KeyActions.PASS; } return resolve(fn, e, k); }; }
[ "function", "med", "(", "fn", ")", "{", "return", "function", "(", "e", ",", "k", ")", "{", "if", "(", "!", "self", ".", "keyboard", ".", "mediaKeysAreFKeys", ")", "{", "// Block Back, Forward, and Reload keys to avoid navigating away from", "// the current page.", ...
Ignore if not trapping media keys.
[ "Ignore", "if", "not", "trapping", "media", "keys", "." ]
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L7356-L7367
35,122
dbkaplun/hterm-umdjs
dist/index.js
anchorFirst
function anchorFirst() { self.startRow = anchorRow; self.startNode = selection.anchorNode; self.startOffset = selection.anchorOffset; self.endRow = focusRow; self.endNode = selection.focusNode; self.endOffset = selection.focusOffset; }
javascript
function anchorFirst() { self.startRow = anchorRow; self.startNode = selection.anchorNode; self.startOffset = selection.anchorOffset; self.endRow = focusRow; self.endNode = selection.focusNode; self.endOffset = selection.focusOffset; }
[ "function", "anchorFirst", "(", ")", "{", "self", ".", "startRow", "=", "anchorRow", ";", "self", ".", "startNode", "=", "selection", ".", "anchorNode", ";", "self", ".", "startOffset", "=", "selection", ".", "anchorOffset", ";", "self", ".", "endRow", "="...
The dom selection object has no way to tell which nodes come first in the document, so we have to figure that out. This function is used when we detect that the "anchor" node is first.
[ "The", "dom", "selection", "object", "has", "no", "way", "to", "tell", "which", "nodes", "come", "first", "in", "the", "document", "so", "we", "have", "to", "figure", "that", "out", ".", "This", "function", "is", "used", "when", "we", "detect", "that", ...
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L10518-L10525
35,123
dbkaplun/hterm-umdjs
dist/index.js
removeUntilNode
function removeUntilNode(currentNode, targetNode) { while (currentNode != targetNode) { if (!currentNode) throw 'Did not encounter target node'; if (currentNode == self.bottomFold_) throw 'Encountered bottom fold before target node'; var deadNode = currentNode; currentNode = currentNode.nextSibling; deadNode.parentNode.removeChild(deadNode); } }
javascript
function removeUntilNode(currentNode, targetNode) { while (currentNode != targetNode) { if (!currentNode) throw 'Did not encounter target node'; if (currentNode == self.bottomFold_) throw 'Encountered bottom fold before target node'; var deadNode = currentNode; currentNode = currentNode.nextSibling; deadNode.parentNode.removeChild(deadNode); } }
[ "function", "removeUntilNode", "(", "currentNode", ",", "targetNode", ")", "{", "while", "(", "currentNode", "!=", "targetNode", ")", "{", "if", "(", "!", "currentNode", ")", "throw", "'Did not encounter target node'", ";", "if", "(", "currentNode", "==", "self"...
Keep removing nodes, starting with currentNode, until we encounter targetNode. Throws on failure.
[ "Keep", "removing", "nodes", "starting", "with", "currentNode", "until", "we", "encounter", "targetNode", ".", "Throws", "on", "failure", "." ]
5cf0fe1f73302ca543c6bcd2d27852362ecada97
https://github.com/dbkaplun/hterm-umdjs/blob/5cf0fe1f73302ca543c6bcd2d27852362ecada97/dist/index.js#L11310-L11322
35,124
Urigo/meteor-native-packages
packages/autoupdate/autoupdate_server.js
function (shouldReloadClientProgram) { // Step 1: load the current client program on the server and update the // hash values in __meteor_runtime_config__. if (shouldReloadClientProgram) { WebAppInternals.reloadClientPrograms(); } // If we just re-read the client program, or if we don't have an autoupdate // version, calculate it. if (shouldReloadClientProgram || Autoupdate.autoupdateVersion === null) { Autoupdate.autoupdateVersion = process.env.AUTOUPDATE_VERSION || WebApp.calculateClientHashNonRefreshable(); } // If we just recalculated it OR if it was set by (eg) test-in-browser, // ensure it ends up in __meteor_runtime_config__. __meteor_runtime_config__.autoupdateVersion = Autoupdate.autoupdateVersion; Autoupdate.autoupdateVersionRefreshable = __meteor_runtime_config__.autoupdateVersionRefreshable = process.env.AUTOUPDATE_VERSION || WebApp.calculateClientHashRefreshable(); Autoupdate.autoupdateVersionCordova = __meteor_runtime_config__.autoupdateVersionCordova = process.env.AUTOUPDATE_VERSION || WebApp.calculateClientHashCordova(); // Step 2: form the new client boilerplate which contains the updated // assets and __meteor_runtime_config__. if (shouldReloadClientProgram) { WebAppInternals.generateBoilerplate(); } // XXX COMPAT WITH 0.8.3 if (! ClientVersions.findOne({current: true})) { // To ensure apps with version of Meteor prior to 0.9.0 (in // which the structure of documents in `ClientVersions` was // different) also reload. ClientVersions.insert({current: true}); } if (! ClientVersions.findOne({_id: "version"})) { ClientVersions.insert({ _id: "version", version: Autoupdate.autoupdateVersion }); } else { ClientVersions.update("version", { $set: { version: Autoupdate.autoupdateVersion }}); } if (! ClientVersions.findOne({_id: "version-cordova"})) { ClientVersions.insert({ _id: "version-cordova", version: Autoupdate.autoupdateVersionCordova, refreshable: false }); } else { ClientVersions.update("version-cordova", { $set: { version: Autoupdate.autoupdateVersionCordova }}); } // Use `onListening` here because we need to use // `WebAppInternals.refreshableAssets`, which is only set after // `WebApp.generateBoilerplate` is called by `main` in webapp. WebApp.onListening(function () { if (! ClientVersions.findOne({_id: "version-refreshable"})) { ClientVersions.insert({ _id: "version-refreshable", version: Autoupdate.autoupdateVersionRefreshable, assets: WebAppInternals.refreshableAssets }); } else { ClientVersions.update("version-refreshable", { $set: { version: Autoupdate.autoupdateVersionRefreshable, assets: WebAppInternals.refreshableAssets }}); } }); }
javascript
function (shouldReloadClientProgram) { // Step 1: load the current client program on the server and update the // hash values in __meteor_runtime_config__. if (shouldReloadClientProgram) { WebAppInternals.reloadClientPrograms(); } // If we just re-read the client program, or if we don't have an autoupdate // version, calculate it. if (shouldReloadClientProgram || Autoupdate.autoupdateVersion === null) { Autoupdate.autoupdateVersion = process.env.AUTOUPDATE_VERSION || WebApp.calculateClientHashNonRefreshable(); } // If we just recalculated it OR if it was set by (eg) test-in-browser, // ensure it ends up in __meteor_runtime_config__. __meteor_runtime_config__.autoupdateVersion = Autoupdate.autoupdateVersion; Autoupdate.autoupdateVersionRefreshable = __meteor_runtime_config__.autoupdateVersionRefreshable = process.env.AUTOUPDATE_VERSION || WebApp.calculateClientHashRefreshable(); Autoupdate.autoupdateVersionCordova = __meteor_runtime_config__.autoupdateVersionCordova = process.env.AUTOUPDATE_VERSION || WebApp.calculateClientHashCordova(); // Step 2: form the new client boilerplate which contains the updated // assets and __meteor_runtime_config__. if (shouldReloadClientProgram) { WebAppInternals.generateBoilerplate(); } // XXX COMPAT WITH 0.8.3 if (! ClientVersions.findOne({current: true})) { // To ensure apps with version of Meteor prior to 0.9.0 (in // which the structure of documents in `ClientVersions` was // different) also reload. ClientVersions.insert({current: true}); } if (! ClientVersions.findOne({_id: "version"})) { ClientVersions.insert({ _id: "version", version: Autoupdate.autoupdateVersion }); } else { ClientVersions.update("version", { $set: { version: Autoupdate.autoupdateVersion }}); } if (! ClientVersions.findOne({_id: "version-cordova"})) { ClientVersions.insert({ _id: "version-cordova", version: Autoupdate.autoupdateVersionCordova, refreshable: false }); } else { ClientVersions.update("version-cordova", { $set: { version: Autoupdate.autoupdateVersionCordova }}); } // Use `onListening` here because we need to use // `WebAppInternals.refreshableAssets`, which is only set after // `WebApp.generateBoilerplate` is called by `main` in webapp. WebApp.onListening(function () { if (! ClientVersions.findOne({_id: "version-refreshable"})) { ClientVersions.insert({ _id: "version-refreshable", version: Autoupdate.autoupdateVersionRefreshable, assets: WebAppInternals.refreshableAssets }); } else { ClientVersions.update("version-refreshable", { $set: { version: Autoupdate.autoupdateVersionRefreshable, assets: WebAppInternals.refreshableAssets }}); } }); }
[ "function", "(", "shouldReloadClientProgram", ")", "{", "// Step 1: load the current client program on the server and update the", "// hash values in __meteor_runtime_config__.", "if", "(", "shouldReloadClientProgram", ")", "{", "WebAppInternals", ".", "reloadClientPrograms", "(", ")...
updateVersions can only be called after the server has fully loaded.
[ "updateVersions", "can", "only", "be", "called", "after", "the", "server", "has", "fully", "loaded", "." ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/autoupdate/autoupdate_server.js#L57-L140
35,125
Urigo/meteor-native-packages
packages/ddp-server/livedata_server.js
function (collectionName, sessionCallbacks) { var self = this; self.collectionName = collectionName; self.documents = {}; self.callbacks = sessionCallbacks; }
javascript
function (collectionName, sessionCallbacks) { var self = this; self.collectionName = collectionName; self.documents = {}; self.callbacks = sessionCallbacks; }
[ "function", "(", "collectionName", ",", "sessionCallbacks", ")", "{", "var", "self", "=", "this", ";", "self", ".", "collectionName", "=", "collectionName", ";", "self", ".", "documents", "=", "{", "}", ";", "self", ".", "callbacks", "=", "sessionCallbacks",...
Represents a client's view of a single collection @param {String} collectionName Name of the collection it represents @param {Object.<String, Function>} sessionCallbacks The callbacks for added, changed, removed @class SessionCollectionView
[ "Represents", "a", "client", "s", "view", "of", "a", "single", "collection" ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/ddp-server/livedata_server.js#L112-L117
35,126
Urigo/meteor-native-packages
packages/ddp-server/livedata_server.js
function (reason, offendingMessage) { var self = this; var msg = {msg: 'error', reason: reason}; if (offendingMessage) msg.offendingMessage = offendingMessage; self.send(msg); }
javascript
function (reason, offendingMessage) { var self = this; var msg = {msg: 'error', reason: reason}; if (offendingMessage) msg.offendingMessage = offendingMessage; self.send(msg); }
[ "function", "(", "reason", ",", "offendingMessage", ")", "{", "var", "self", "=", "this", ";", "var", "msg", "=", "{", "msg", ":", "'error'", ",", "reason", ":", "reason", "}", ";", "if", "(", "offendingMessage", ")", "msg", ".", "offendingMessage", "=...
Send a connection error.
[ "Send", "a", "connection", "error", "." ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/ddp-server/livedata_server.js#L475-L481
35,127
Urigo/meteor-native-packages
packages/ddp-server/livedata_server.js
function(userId) { var self = this; if (userId !== null && typeof userId !== "string") throw new Error("setUserId must be called on string or null, not " + typeof userId); // Prevent newly-created universal subscriptions from being added to our // session; they will be found below when we call startUniversalSubs. // // (We don't have to worry about named subscriptions, because we only add // them when we process a 'sub' message. We are currently processing a // 'method' message, and the method did not unblock, because it is illegal // to call setUserId after unblock. Thus we cannot be concurrently adding a // new named subscription.) self._dontStartNewUniversalSubs = true; // Prevent current subs from updating our collectionViews and call their // stop callbacks. This may yield. self._eachSub(function (sub) { sub._deactivate(); }); // All subs should now be deactivated. Stop sending messages to the client, // save the state of the published collections, reset to an empty view, and // update the userId. self._isSending = false; var beforeCVs = self.collectionViews; self.collectionViews = {}; self.userId = userId; // Save the old named subs, and reset to having no subscriptions. var oldNamedSubs = self._namedSubs; self._namedSubs = {}; self._universalSubs = []; _.each(oldNamedSubs, function (sub, subscriptionId) { self._namedSubs[subscriptionId] = sub._recreate(); // nb: if the handler throws or calls this.error(), it will in fact // immediately send its 'nosub'. This is OK, though. self._namedSubs[subscriptionId]._runHandler(); }); // Allow newly-created universal subs to be started on our connection in // parallel with the ones we're spinning up here, and spin up universal // subs. self._dontStartNewUniversalSubs = false; self.startUniversalSubs(); // Start sending messages again, beginning with the diff from the previous // state of the world to the current state. No yields are allowed during // this diff, so that other changes cannot interleave. Meteor._noYieldsAllowed(function () { self._isSending = true; self._diffCollectionViews(beforeCVs); if (!_.isEmpty(self._pendingReady)) { self.sendReady(self._pendingReady); self._pendingReady = []; } }); }
javascript
function(userId) { var self = this; if (userId !== null && typeof userId !== "string") throw new Error("setUserId must be called on string or null, not " + typeof userId); // Prevent newly-created universal subscriptions from being added to our // session; they will be found below when we call startUniversalSubs. // // (We don't have to worry about named subscriptions, because we only add // them when we process a 'sub' message. We are currently processing a // 'method' message, and the method did not unblock, because it is illegal // to call setUserId after unblock. Thus we cannot be concurrently adding a // new named subscription.) self._dontStartNewUniversalSubs = true; // Prevent current subs from updating our collectionViews and call their // stop callbacks. This may yield. self._eachSub(function (sub) { sub._deactivate(); }); // All subs should now be deactivated. Stop sending messages to the client, // save the state of the published collections, reset to an empty view, and // update the userId. self._isSending = false; var beforeCVs = self.collectionViews; self.collectionViews = {}; self.userId = userId; // Save the old named subs, and reset to having no subscriptions. var oldNamedSubs = self._namedSubs; self._namedSubs = {}; self._universalSubs = []; _.each(oldNamedSubs, function (sub, subscriptionId) { self._namedSubs[subscriptionId] = sub._recreate(); // nb: if the handler throws or calls this.error(), it will in fact // immediately send its 'nosub'. This is OK, though. self._namedSubs[subscriptionId]._runHandler(); }); // Allow newly-created universal subs to be started on our connection in // parallel with the ones we're spinning up here, and spin up universal // subs. self._dontStartNewUniversalSubs = false; self.startUniversalSubs(); // Start sending messages again, beginning with the diff from the previous // state of the world to the current state. No yields are allowed during // this diff, so that other changes cannot interleave. Meteor._noYieldsAllowed(function () { self._isSending = true; self._diffCollectionViews(beforeCVs); if (!_.isEmpty(self._pendingReady)) { self.sendReady(self._pendingReady); self._pendingReady = []; } }); }
[ "function", "(", "userId", ")", "{", "var", "self", "=", "this", ";", "if", "(", "userId", "!==", "null", "&&", "typeof", "userId", "!==", "\"string\"", ")", "throw", "new", "Error", "(", "\"setUserId must be called on string or null, not \"", "+", "typeof", "...
Sets the current user id in all appropriate contexts and reruns all subscriptions
[ "Sets", "the", "current", "user", "id", "in", "all", "appropriate", "contexts", "and", "reruns", "all", "subscriptions" ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/ddp-server/livedata_server.js#L781-L841
35,128
Urigo/meteor-native-packages
packages/ddp-server/livedata_server.js
function () { var self = this; _.each(self._namedSubs, function (sub, id) { sub._deactivate(); }); self._namedSubs = {}; _.each(self._universalSubs, function (sub) { sub._deactivate(); }); self._universalSubs = []; }
javascript
function () { var self = this; _.each(self._namedSubs, function (sub, id) { sub._deactivate(); }); self._namedSubs = {}; _.each(self._universalSubs, function (sub) { sub._deactivate(); }); self._universalSubs = []; }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "_", ".", "each", "(", "self", ".", "_namedSubs", ",", "function", "(", "sub", ",", "id", ")", "{", "sub", ".", "_deactivate", "(", ")", ";", "}", ")", ";", "self", ".", "_namedSubs", ...
tear down all subscriptions. Note that this does NOT send removed or nosub messages, since we assume the client is gone.
[ "tear", "down", "all", "subscriptions", ".", "Note", "that", "this", "does", "NOT", "send", "removed", "or", "nosub", "messages", "since", "we", "assume", "the", "client", "is", "gone", "." ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/ddp-server/livedata_server.js#L883-L895
35,129
Urigo/meteor-native-packages
packages/ddp-server/livedata_server.js
function () { var self = this; Meteor._noYieldsAllowed(function () { _.each(self._documents, function(collectionDocs, collectionName) { // Iterate over _.keys instead of the dictionary itself, since we'll be // mutating it. _.each(_.keys(collectionDocs), function (strId) { self.removed(collectionName, self._idFilter.idParse(strId)); }); }); }); }
javascript
function () { var self = this; Meteor._noYieldsAllowed(function () { _.each(self._documents, function(collectionDocs, collectionName) { // Iterate over _.keys instead of the dictionary itself, since we'll be // mutating it. _.each(_.keys(collectionDocs), function (strId) { self.removed(collectionName, self._idFilter.idParse(strId)); }); }); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "Meteor", ".", "_noYieldsAllowed", "(", "function", "(", ")", "{", "_", ".", "each", "(", "self", ".", "_documents", ",", "function", "(", "collectionDocs", ",", "collectionName", ")", "{", "/...
Send remove messages for every document.
[ "Send", "remove", "messages", "for", "every", "document", "." ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/ddp-server/livedata_server.js#L1150-L1161
35,130
AmpersandJS/ampersand-select-view
ampersand-select-view.js
function(value) { var model; if (this.options.isCollection) { // find value in collection, error if no model found if (this.options.indexOf(value) === -1) model = this.getModelForId(value); else model = value; if (!model) throw new Error('model or model idAttribute not found in options collection'); return this.yieldModel ? model : model[this.idAttribute]; } else if (Array.isArray(this.options)) { // find value value in options array // find option, formatted [['val', 'text'], ...] if (this.options.length && Array.isArray(this.options[0])) { for (var i = this.options.length - 1; i >= 0; i--) { if (this.options[i][0] == value) return this.options[i]; } } // find option, formatted ['valAndText', ...] format if (this.options.length && this.options.indexOf(value) !== -1) return value; throw new Error('value not in set of provided options'); } throw new Error('select option set invalid'); }
javascript
function(value) { var model; if (this.options.isCollection) { // find value in collection, error if no model found if (this.options.indexOf(value) === -1) model = this.getModelForId(value); else model = value; if (!model) throw new Error('model or model idAttribute not found in options collection'); return this.yieldModel ? model : model[this.idAttribute]; } else if (Array.isArray(this.options)) { // find value value in options array // find option, formatted [['val', 'text'], ...] if (this.options.length && Array.isArray(this.options[0])) { for (var i = this.options.length - 1; i >= 0; i--) { if (this.options[i][0] == value) return this.options[i]; } } // find option, formatted ['valAndText', ...] format if (this.options.length && this.options.indexOf(value) !== -1) return value; throw new Error('value not in set of provided options'); } throw new Error('select option set invalid'); }
[ "function", "(", "value", ")", "{", "var", "model", ";", "if", "(", "this", ".", "options", ".", "isCollection", ")", "{", "// find value in collection, error if no model found", "if", "(", "this", ".", "options", ".", "indexOf", "(", "value", ")", "===", "-...
Gets the option corresponding to provided value. @param {*} string, state, or model @return {*} string, array, state, or model
[ "Gets", "the", "option", "corresponding", "to", "provided", "value", "." ]
05ce030a20be3f46a99eb5677e2d952c48df16df
https://github.com/AmpersandJS/ampersand-select-view/blob/05ce030a20be3f46a99eb5677e2d952c48df16df/ampersand-select-view.js#L355-L376
35,131
daviestar/glfx-es6
demo/index.js
fixCurves
function fixCurves() { if (point[0] == 0) start = point[1]; if (point[0] == 1) end = point[1]; var points = filter[curves.name]; var foundStart = false; var foundEnd = false; for (var i = 0; i < points.length; i++) { var p = points[i]; if (p[0] == 0) { foundStart = true; if (point[0] == 0 && p != point) points.splice(i--, 1); } else if (p[0] == 1) { foundEnd = true; if (point[0] == 1 && p != point) points.splice(i--, 1); } } if (!foundStart) points.push([0, start]); if (!foundEnd) points.push([1, end]); }
javascript
function fixCurves() { if (point[0] == 0) start = point[1]; if (point[0] == 1) end = point[1]; var points = filter[curves.name]; var foundStart = false; var foundEnd = false; for (var i = 0; i < points.length; i++) { var p = points[i]; if (p[0] == 0) { foundStart = true; if (point[0] == 0 && p != point) points.splice(i--, 1); } else if (p[0] == 1) { foundEnd = true; if (point[0] == 1 && p != point) points.splice(i--, 1); } } if (!foundStart) points.push([0, start]); if (!foundEnd) points.push([1, end]); }
[ "function", "fixCurves", "(", ")", "{", "if", "(", "point", "[", "0", "]", "==", "0", ")", "start", "=", "point", "[", "1", "]", ";", "if", "(", "point", "[", "0", "]", "==", "1", ")", "end", "=", "point", "[", "1", "]", ";", "var", "points...
Make sure there's always a start and end node
[ "Make", "sure", "there", "s", "always", "a", "start", "and", "end", "node" ]
88d35c4e230cdca3ae8311bcd85fa8d001f6930d
https://github.com/daviestar/glfx-es6/blob/88d35c4e230cdca3ae8311bcd85fa8d001f6930d/demo/index.js#L216-L234
35,132
60frames/jestpack
ModuleLoader.js
loadSimpleResourceMap
function loadSimpleResourceMap(config) { return new Promise((resolve, reject) => { // Convert Jest config into glob pattern. let testPathDirs; let testFileExtensions; let generatedGlob; if (config.testPathDirs.length === 1) { testPathDirs = config.testPathDirs[0]; } else { testPathDirs = '{' + config.testPathDirs.join(',') + '}'; } if (config.testFileExtensions.length === 1) { testFileExtensions = config.testFileExtensions[0]; } else { testFileExtensions = '{' + config.testFileExtensions.join(',') + '}'; } generatedGlob = testPathDirs + '/' + '**/' + config.testDirectoryName + '/**/*.' + testFileExtensions; glob(generatedGlob, (err, files) => { if (err) { reject(err); } else { let resourceMap; resourceMap = { resourcePathMap: {} }; files.forEach(file => { let fullPath = path.resolve(file); resourceMap.resourcePathMap[fullPath] = { path: fullPath }; }); resolve(resourceMap); } }); }); }
javascript
function loadSimpleResourceMap(config) { return new Promise((resolve, reject) => { // Convert Jest config into glob pattern. let testPathDirs; let testFileExtensions; let generatedGlob; if (config.testPathDirs.length === 1) { testPathDirs = config.testPathDirs[0]; } else { testPathDirs = '{' + config.testPathDirs.join(',') + '}'; } if (config.testFileExtensions.length === 1) { testFileExtensions = config.testFileExtensions[0]; } else { testFileExtensions = '{' + config.testFileExtensions.join(',') + '}'; } generatedGlob = testPathDirs + '/' + '**/' + config.testDirectoryName + '/**/*.' + testFileExtensions; glob(generatedGlob, (err, files) => { if (err) { reject(err); } else { let resourceMap; resourceMap = { resourcePathMap: {} }; files.forEach(file => { let fullPath = path.resolve(file); resourceMap.resourcePathMap[fullPath] = { path: fullPath }; }); resolve(resourceMap); } }); }); }
[ "function", "loadSimpleResourceMap", "(", "config", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "// Convert Jest config into glob pattern.", "let", "testPathDirs", ";", "let", "testFileExtensions", ";", "let", "generated...
Builds simple resource map containing only the bundled test files. @param {Object} config The Jest config. @return {Promise} The 'node-haste'(ish) resource map.
[ "Builds", "simple", "resource", "map", "containing", "only", "the", "bundled", "test", "files", "." ]
2e3c26d856ebe4c1b3b786a26178e3ba81108616
https://github.com/60frames/jestpack/blob/2e3c26d856ebe4c1b3b786a26178e3ba81108616/ModuleLoader.js#L17-L58
35,133
60frames/jestpack
ModuleLoader.js
getWebpackStats
function getWebpackStats(config) { let statsPaths = config.testPathDirs.map(testPathDir => { return path.join(testPathDir, 'stats.json'); }); statsPaths.some(statsPath => { try { webpackStats = require(statsPath); } catch (oh) { // not found } return !!webpackStats; }); if (!webpackStats) { throw new Error('Cannot find Webpack stats in: \n' + statsPaths.join('\n')); } return webpackStats; }
javascript
function getWebpackStats(config) { let statsPaths = config.testPathDirs.map(testPathDir => { return path.join(testPathDir, 'stats.json'); }); statsPaths.some(statsPath => { try { webpackStats = require(statsPath); } catch (oh) { // not found } return !!webpackStats; }); if (!webpackStats) { throw new Error('Cannot find Webpack stats in: \n' + statsPaths.join('\n')); } return webpackStats; }
[ "function", "getWebpackStats", "(", "config", ")", "{", "let", "statsPaths", "=", "config", ".", "testPathDirs", ".", "map", "(", "testPathDir", "=>", "{", "return", "path", ".", "join", "(", "testPathDir", ",", "'stats.json'", ")", ";", "}", ")", ";", "...
Checks the root of each `config.testPathDirs` directory for the Webpack `stats.json`. @param {Object} config The Jest config. @return {Object} The Webpack stats json.
[ "Checks", "the", "root", "of", "each", "config", ".", "testPathDirs", "directory", "for", "the", "Webpack", "stats", ".", "json", "." ]
2e3c26d856ebe4c1b3b786a26178e3ba81108616
https://github.com/60frames/jestpack/blob/2e3c26d856ebe4c1b3b786a26178e3ba81108616/ModuleLoader.js#L65-L85
35,134
edspencer/jaml
Jaml-all.js
function(attrs) { for (var key in attrs) { //convert cls to class var mappedKey = key == 'cls' ? 'class' : key; this.attributes[mappedKey] = attrs[key]; } return this; }
javascript
function(attrs) { for (var key in attrs) { //convert cls to class var mappedKey = key == 'cls' ? 'class' : key; this.attributes[mappedKey] = attrs[key]; } return this; }
[ "function", "(", "attrs", ")", "{", "for", "(", "var", "key", "in", "attrs", ")", "{", "//convert cls to class", "var", "mappedKey", "=", "key", "==", "'cls'", "?", "'class'", ":", "key", ";", "this", ".", "attributes", "[", "mappedKey", "]", "=", "att...
Adds attributes to this node @param {Object} attrs Object containing key: value pairs of node attributes
[ "Adds", "attributes", "to", "this", "node" ]
2de4bd49ab816f300f4ed05108c5588a9a4c9477
https://github.com/edspencer/jaml/blob/2de4bd49ab816f300f4ed05108c5588a9a4c9477/Jaml-all.js#L67-L75
35,135
edspencer/jaml
Jaml-all.js
function(lpad) { lpad = lpad || 0; var node = [], attrs = [], textnode = (this instanceof Jaml.TextNode), multiline = this.multiLineTag(); //add any left padding if (!textnode) node.push(this.getPadding(lpad)); //open the tag node.push("<" + this.tagName); for (var key in this.attributes) { attrs.push(key + "=\"" + this.attributes[key] + "\""); } attrs.sort() //add any tag attributes for (var i=0; i<attrs.length; i++) { node.push(" " + attrs[i]); } if (this.isSelfClosing() && this.children.length==0) { node.push("/>\n"); } else { node.push(">"); if (multiline) node.push("\n"); this.renderChildren(node, this.children, lpad); if (multiline) node.push(this.getPadding(lpad)); node.push("</", this.tagName, ">\n"); } return node.join(""); }
javascript
function(lpad) { lpad = lpad || 0; var node = [], attrs = [], textnode = (this instanceof Jaml.TextNode), multiline = this.multiLineTag(); //add any left padding if (!textnode) node.push(this.getPadding(lpad)); //open the tag node.push("<" + this.tagName); for (var key in this.attributes) { attrs.push(key + "=\"" + this.attributes[key] + "\""); } attrs.sort() //add any tag attributes for (var i=0; i<attrs.length; i++) { node.push(" " + attrs[i]); } if (this.isSelfClosing() && this.children.length==0) { node.push("/>\n"); } else { node.push(">"); if (multiline) node.push("\n"); this.renderChildren(node, this.children, lpad); if (multiline) node.push(this.getPadding(lpad)); node.push("</", this.tagName, ">\n"); } return node.join(""); }
[ "function", "(", "lpad", ")", "{", "lpad", "=", "lpad", "||", "0", ";", "var", "node", "=", "[", "]", ",", "attrs", "=", "[", "]", ",", "textnode", "=", "(", "this", "instanceof", "Jaml", ".", "TextNode", ")", ",", "multiline", "=", "this", ".", ...
Renders this node with its attributes and children @param {Number} lpad Amount of whitespace to add to the left of the string (defaults to 0) @return {String} The rendered node
[ "Renders", "this", "node", "with", "its", "attributes", "and", "children" ]
2de4bd49ab816f300f4ed05108c5588a9a4c9477
https://github.com/edspencer/jaml/blob/2de4bd49ab816f300f4ed05108c5588a9a4c9477/Jaml-all.js#L91-L129
35,136
edspencer/jaml
Jaml-all.js
function(node, children, lpad) { var childLpad = lpad + 2; for (var i=0; i < children.length; i++) { var child = children[i]; if (child instanceof Array) { var nestedChildren = child; this.renderChildren(node, nestedChildren, lpad) } else { node.push(child.render(childLpad)); } } }
javascript
function(node, children, lpad) { var childLpad = lpad + 2; for (var i=0; i < children.length; i++) { var child = children[i]; if (child instanceof Array) { var nestedChildren = child; this.renderChildren(node, nestedChildren, lpad) } else { node.push(child.render(childLpad)); } } }
[ "function", "(", "node", ",", "children", ",", "lpad", ")", "{", "var", "childLpad", "=", "lpad", "+", "2", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "children", ".", "length", ";", "i", "++", ")", "{", "var", "child", "=", "childre...
Renders an array of children @node {Array} the current array of rendered lines @children {Array} the child nodes to be rendered @param {Number} lpad Amount of whitespace to add to the left of the string
[ "Renders", "an", "array", "of", "children" ]
2de4bd49ab816f300f4ed05108c5588a9a4c9477
https://github.com/edspencer/jaml/blob/2de4bd49ab816f300f4ed05108c5588a9a4c9477/Jaml-all.js#L137-L149
35,137
edspencer/jaml
Jaml-all.js
function(thisObj, data) { data = data || (thisObj = thisObj || {}); //the 'data' argument can come in two flavours - array or non-array. Normalise it //here so that it always looks like an array. if (data.constructor.toString().indexOf("Array") == -1) { data = [data]; } with(this) { for (var i=0; i < data.length; i++) { eval("(" + this.tpl.toString() + ").call(thisObj, data[i], i)"); }; } var roots = this.getRoots(), output = ""; for (var i=0; i < roots.length; i++) { output += roots[i].render(); }; return output; }
javascript
function(thisObj, data) { data = data || (thisObj = thisObj || {}); //the 'data' argument can come in two flavours - array or non-array. Normalise it //here so that it always looks like an array. if (data.constructor.toString().indexOf("Array") == -1) { data = [data]; } with(this) { for (var i=0; i < data.length; i++) { eval("(" + this.tpl.toString() + ").call(thisObj, data[i], i)"); }; } var roots = this.getRoots(), output = ""; for (var i=0; i < roots.length; i++) { output += roots[i].render(); }; return output; }
[ "function", "(", "thisObj", ",", "data", ")", "{", "data", "=", "data", "||", "(", "thisObj", "=", "thisObj", "||", "{", "}", ")", ";", "//the 'data' argument can come in two flavours - array or non-array. Normalise it", "//here so that it always looks like an array.", "i...
Renders this template given the supplied data @param {Object} thisObj Optional data object @param {Object} data Optional data object @return {String} The rendered HTML string
[ "Renders", "this", "template", "given", "the", "supplied", "data" ]
2de4bd49ab816f300f4ed05108c5588a9a4c9477
https://github.com/edspencer/jaml/blob/2de4bd49ab816f300f4ed05108c5588a9a4c9477/Jaml-all.js#L233-L256
35,138
edspencer/jaml
Jaml-all.js
function(tagName) { return function(attrs) { var node = new Jaml.Node(tagName); var firstArgIsAttributes = (typeof attrs == 'object') && !(attrs instanceof Jaml.Node) && !(attrs instanceof Jaml.TextNode); if (firstArgIsAttributes) node.setAttributes(attrs); var startIndex = firstArgIsAttributes ? 1 : 0; for (var i=startIndex; i < arguments.length; i++) { var arg = arguments[i]; if (typeof arg == "string" || arg == undefined) { arg = new Jaml.TextNode(arg || ""); } if (arg instanceof Jaml.Node || arg instanceof Jaml.TextNode) { arg.parent = node; } node.addChild(arg); }; this.nodes.push(node); return node; }; }
javascript
function(tagName) { return function(attrs) { var node = new Jaml.Node(tagName); var firstArgIsAttributes = (typeof attrs == 'object') && !(attrs instanceof Jaml.Node) && !(attrs instanceof Jaml.TextNode); if (firstArgIsAttributes) node.setAttributes(attrs); var startIndex = firstArgIsAttributes ? 1 : 0; for (var i=startIndex; i < arguments.length; i++) { var arg = arguments[i]; if (typeof arg == "string" || arg == undefined) { arg = new Jaml.TextNode(arg || ""); } if (arg instanceof Jaml.Node || arg instanceof Jaml.TextNode) { arg.parent = node; } node.addChild(arg); }; this.nodes.push(node); return node; }; }
[ "function", "(", "tagName", ")", "{", "return", "function", "(", "attrs", ")", "{", "var", "node", "=", "new", "Jaml", ".", "Node", "(", "tagName", ")", ";", "var", "firstArgIsAttributes", "=", "(", "typeof", "attrs", "==", "'object'", ")", "&&", "!", ...
This function is created for each tag name and assigned to Template's prototype below
[ "This", "function", "is", "created", "for", "each", "tag", "name", "and", "assigned", "to", "Template", "s", "prototype", "below" ]
2de4bd49ab816f300f4ed05108c5588a9a4c9477
https://github.com/edspencer/jaml/blob/2de4bd49ab816f300f4ed05108c5588a9a4c9477/Jaml-all.js#L297-L327
35,139
uber-web/type-analyzer
src/analyzer.js
valueIsNullForValidator
function valueIsNullForValidator(value, validatorName) { if (value === null || value === CONSTANT.NULL || typeof value === 'undefined') { return true; } if (value === '' && VALIDATOR_CONSIDERS_EMPTY_STRING_NULL[validatorName]) { return true; } return false; }
javascript
function valueIsNullForValidator(value, validatorName) { if (value === null || value === CONSTANT.NULL || typeof value === 'undefined') { return true; } if (value === '' && VALIDATOR_CONSIDERS_EMPTY_STRING_NULL[validatorName]) { return true; } return false; }
[ "function", "valueIsNullForValidator", "(", "value", ",", "validatorName", ")", "{", "if", "(", "value", "===", "null", "||", "value", "===", "CONSTANT", ".", "NULL", "||", "typeof", "value", "===", "'undefined'", ")", "{", "return", "true", ";", "}", "if"...
Check if a given value is a null for a validator @param {String} value - value to be checked if null @param {String} validatorName - the name of the current validation function @return {Boolean} whether or not the current value is null
[ "Check", "if", "a", "given", "value", "is", "a", "null", "for", "a", "validator" ]
3b713fc6b02eda11b7f4b7567347371a6bf6cfb5
https://github.com/uber-web/type-analyzer/blob/3b713fc6b02eda11b7f4b7567347371a6bf6cfb5/src/analyzer.js#L47-L57
35,140
Urigo/meteor-native-packages
packages/ddp-server/crossbar.js
function (msg) { var self = this; if (! _.has(msg, 'collection')) { return ''; } else if (typeof(msg.collection) === 'string') { if (msg.collection === '') throw Error("Message has empty collection!"); return msg.collection; } else { throw Error("Message has non-string collection!"); } }
javascript
function (msg) { var self = this; if (! _.has(msg, 'collection')) { return ''; } else if (typeof(msg.collection) === 'string') { if (msg.collection === '') throw Error("Message has empty collection!"); return msg.collection; } else { throw Error("Message has non-string collection!"); } }
[ "function", "(", "msg", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "_", ".", "has", "(", "msg", ",", "'collection'", ")", ")", "{", "return", "''", ";", "}", "else", "if", "(", "typeof", "(", "msg", ".", "collection", ")", "==="...
msg is a trigger or a notification
[ "msg", "is", "a", "trigger", "or", "a", "notification" ]
8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7
https://github.com/Urigo/meteor-native-packages/blob/8eb7fdd554aad0ff78a0dc19b9c62016d2b2e7a7/packages/ddp-server/crossbar.js#L20-L31
35,141
layerhq/node-layer-api
lib/resources/blocklist.js
function(ownerId, callback) { if (!ownerId) return callback(new Error(utils.i18n.blocklist.ownerId)); utils.debug('Blocklist get: ' + ownerId); request.get({ path: '/users/' + querystring.escape(ownerId) + '/blocks' }, callback); }
javascript
function(ownerId, callback) { if (!ownerId) return callback(new Error(utils.i18n.blocklist.ownerId)); utils.debug('Blocklist get: ' + ownerId); request.get({ path: '/users/' + querystring.escape(ownerId) + '/blocks' }, callback); }
[ "function", "(", "ownerId", ",", "callback", ")", "{", "if", "(", "!", "ownerId", ")", "return", "callback", "(", "new", "Error", "(", "utils", ".", "i18n", ".", "blocklist", ".", "ownerId", ")", ")", ";", "utils", ".", "debug", "(", "'Blocklist get: '...
Retrieve the block list for a user that owns the block list @param {Strng} ownerId Owner ID of the block list @param {Function} callback Callback function
[ "Retrieve", "the", "block", "list", "for", "a", "user", "that", "owns", "the", "block", "list" ]
284c161350e2cf3d3f5b45f2918798d981f1ada4
https://github.com/layerhq/node-layer-api/blob/284c161350e2cf3d3f5b45f2918798d981f1ada4/lib/resources/blocklist.js#L20-L27
35,142
layerhq/node-layer-api
lib/resources/blocklist.js
function(ownerId, userId, callback) { if (!ownerId) return callback(new Error(utils.i18n.blocklist.ownerId)); if (!userId) return callback(new Error(utils.i18n.blocklist.userId)); utils.debug('Blocklist block: ' + ownerId + ' userId: ' + userId); request.post({ path: '/users/' + querystring.escape(ownerId) + '/blocks', body: { user_id: userId } }, callback || utils.nop); }
javascript
function(ownerId, userId, callback) { if (!ownerId) return callback(new Error(utils.i18n.blocklist.ownerId)); if (!userId) return callback(new Error(utils.i18n.blocklist.userId)); utils.debug('Blocklist block: ' + ownerId + ' userId: ' + userId); request.post({ path: '/users/' + querystring.escape(ownerId) + '/blocks', body: { user_id: userId } }, callback || utils.nop); }
[ "function", "(", "ownerId", ",", "userId", ",", "callback", ")", "{", "if", "(", "!", "ownerId", ")", "return", "callback", "(", "new", "Error", "(", "utils", ".", "i18n", ".", "blocklist", ".", "ownerId", ")", ")", ";", "if", "(", "!", "userId", "...
Block a single user @param {String} ownerId Owner ID of the block list @param {String} userId User being blocked @param {Function} callback Callback function
[ "Block", "a", "single", "user" ]
284c161350e2cf3d3f5b45f2918798d981f1ada4
https://github.com/layerhq/node-layer-api/blob/284c161350e2cf3d3f5b45f2918798d981f1ada4/lib/resources/blocklist.js#L36-L47
35,143
medialab/sandcrawler
src/phantom_script.js
argNames
function argNames(str) { // Matching var matches = str.match(regexes.argMatch); if (!matches) throw Error('sandcrawler.phantom_script.arguments: not enough arguments to compile a correct phantom scraper.'); return [matches[1], matches[2]]; }
javascript
function argNames(str) { // Matching var matches = str.match(regexes.argMatch); if (!matches) throw Error('sandcrawler.phantom_script.arguments: not enough arguments to compile a correct phantom scraper.'); return [matches[1], matches[2]]; }
[ "function", "argNames", "(", "str", ")", "{", "// Matching", "var", "matches", "=", "str", ".", "match", "(", "regexes", ".", "argMatch", ")", ";", "if", "(", "!", "matches", ")", "throw", "Error", "(", "'sandcrawler.phantom_script.arguments: not enough argument...
Retrieve the first two arguments of the given stringified function
[ "Retrieve", "the", "first", "two", "arguments", "of", "the", "given", "stringified", "function" ]
c08e19095eee42c8ce1f84685960e5ea6cb0fd1d
https://github.com/medialab/sandcrawler/blob/c08e19095eee42c8ce1f84685960e5ea6cb0fd1d/src/phantom_script.js#L17-L26
35,144
medialab/sandcrawler
src/phantom_script.js
argName
function argName(str) { // Matching var matches = str.match(regexes.singleArgMatch); if (!matches) throw Error('sandcrawler.phantom_script.arguments: not enough arguments to compile a correct phantom scraper.'); return [matches[1]]; }
javascript
function argName(str) { // Matching var matches = str.match(regexes.singleArgMatch); if (!matches) throw Error('sandcrawler.phantom_script.arguments: not enough arguments to compile a correct phantom scraper.'); return [matches[1]]; }
[ "function", "argName", "(", "str", ")", "{", "// Matching", "var", "matches", "=", "str", ".", "match", "(", "regexes", ".", "singleArgMatch", ")", ";", "if", "(", "!", "matches", ")", "throw", "Error", "(", "'sandcrawler.phantom_script.arguments: not enough arg...
Retrieve the first argument of the given stringified function
[ "Retrieve", "the", "first", "argument", "of", "the", "given", "stringified", "function" ]
c08e19095eee42c8ce1f84685960e5ea6cb0fd1d
https://github.com/medialab/sandcrawler/blob/c08e19095eee42c8ce1f84685960e5ea6cb0fd1d/src/phantom_script.js#L29-L38
35,145
medialab/sandcrawler
src/phantom_script.js
wrap
function wrap(str, dollarName, doneName) { return doneName ? '(function(' + dollarName + ', ' + doneName + ', undefined){' + str + '})(artoo.$, artoo.done);' : '(function(' + dollarName + ', undefined){' + str + '})(artoo.$);'; }
javascript
function wrap(str, dollarName, doneName) { return doneName ? '(function(' + dollarName + ', ' + doneName + ', undefined){' + str + '})(artoo.$, artoo.done);' : '(function(' + dollarName + ', undefined){' + str + '})(artoo.$);'; }
[ "function", "wrap", "(", "str", ",", "dollarName", ",", "doneName", ")", "{", "return", "doneName", "?", "'(function('", "+", "dollarName", "+", "', '", "+", "doneName", "+", "', undefined){'", "+", "str", "+", "'})(artoo.$, artoo.done);'", ":", "'(function('", ...
Wrap in context to name several really important variables
[ "Wrap", "in", "context", "to", "name", "several", "really", "important", "variables" ]
c08e19095eee42c8ce1f84685960e5ea6cb0fd1d
https://github.com/medialab/sandcrawler/blob/c08e19095eee42c8ce1f84685960e5ea6cb0fd1d/src/phantom_script.js#L41-L45
35,146
bunsn/boiler
lib/table.js
nodeText
function nodeText (node) { return squashWhitespace(node.textContent) function squashWhitespace (string) { return string.replace(/\s{2,}/g, ' ').trim() } }
javascript
function nodeText (node) { return squashWhitespace(node.textContent) function squashWhitespace (string) { return string.replace(/\s{2,}/g, ' ').trim() } }
[ "function", "nodeText", "(", "node", ")", "{", "return", "squashWhitespace", "(", "node", ".", "textContent", ")", "function", "squashWhitespace", "(", "string", ")", "{", "return", "string", ".", "replace", "(", "/", "\\s{2,}", "/", "g", ",", "' '", ")", ...
Squashed and trimmed node text content
[ "Squashed", "and", "trimmed", "node", "text", "content" ]
21413dcc1003d9526041e105734287cc83a596ff
https://github.com/bunsn/boiler/blob/21413dcc1003d9526041e105734287cc83a596ff/lib/table.js#L39-L45
35,147
runk/node-thin
examples/helpers.js
sendModifiedResponse
function sendModifiedResponse(clientRes, response, transform) { var dataPipe = response, decompressor = decompressorFor(response), chunks = []; if(decompressor) { dataPipe = dataPipe.pipe(decompressor); } dataPipe.on('data', function(chunk) { chunks.push(chunk); }); dataPipe.on('end', function () { var origContent = Buffer.concat(chunks); transform(origContent, function (modifiedContent) { response.headers['content-length'] = modifiedContent.length; // The response has been de-chunked and uncompressed, so delete // these headers from the response. delete response.headers['content-encoding']; delete response.headers['content-transfer-encoding']; clientRes.writeHead(response.statusCode, response.headers); clientRes.end(modifiedContent); }); }); }
javascript
function sendModifiedResponse(clientRes, response, transform) { var dataPipe = response, decompressor = decompressorFor(response), chunks = []; if(decompressor) { dataPipe = dataPipe.pipe(decompressor); } dataPipe.on('data', function(chunk) { chunks.push(chunk); }); dataPipe.on('end', function () { var origContent = Buffer.concat(chunks); transform(origContent, function (modifiedContent) { response.headers['content-length'] = modifiedContent.length; // The response has been de-chunked and uncompressed, so delete // these headers from the response. delete response.headers['content-encoding']; delete response.headers['content-transfer-encoding']; clientRes.writeHead(response.statusCode, response.headers); clientRes.end(modifiedContent); }); }); }
[ "function", "sendModifiedResponse", "(", "clientRes", ",", "response", ",", "transform", ")", "{", "var", "dataPipe", "=", "response", ",", "decompressor", "=", "decompressorFor", "(", "response", ")", ",", "chunks", "=", "[", "]", ";", "if", "(", "decompres...
Transform the server's response and send it to the proxy client. @param {http.ServerResponse} clientRes - Response to the client. @param {http.IncomingMessage} response - Response from the server. @param {transformCallback} transform - How to transform the server's response.
[ "Transform", "the", "server", "s", "response", "and", "send", "it", "to", "the", "proxy", "client", "." ]
93cd074978484b856323fbaedf370e521e24ad8a
https://github.com/runk/node-thin/blob/93cd074978484b856323fbaedf370e521e24ad8a/examples/helpers.js#L36-L59
35,148
runk/node-thin
examples/helpers.js
sendOriginalResponse
function sendOriginalResponse(clientRes, response) { clientRes.writeHead(response.statusCode, response.headers); response.pipe(clientRes); }
javascript
function sendOriginalResponse(clientRes, response) { clientRes.writeHead(response.statusCode, response.headers); response.pipe(clientRes); }
[ "function", "sendOriginalResponse", "(", "clientRes", ",", "response", ")", "{", "clientRes", ".", "writeHead", "(", "response", ".", "statusCode", ",", "response", ".", "headers", ")", ";", "response", ".", "pipe", "(", "clientRes", ")", ";", "}" ]
Transform server response content. There's no error value, because even if the transform fails, *something* should be returned to the client. Figuring out what that should be is application-specific (i.e, your problem). @callback transformCallback @param {Buffer} input - The server's response content. @returns {Buffer} - The transformed response. Send a server response to the proxy client as-is, without modification. @param {http.ServerResponse} clientRes - Response to the client. @param {http.IncomingMessage} response - Response from the server (to send).
[ "Transform", "server", "response", "content", "." ]
93cd074978484b856323fbaedf370e521e24ad8a
https://github.com/runk/node-thin/blob/93cd074978484b856323fbaedf370e521e24ad8a/examples/helpers.js#L79-L82
35,149
runk/node-thin
examples/helpers.js
makeSNICallback
function makeSNICallback() { var caKey = fs.readFileSync(__dirname + '/../cert/dummy.key', 'utf8'), caCert = fs.readFileSync(__dirname + '/../cert/dummy.crt', 'utf8'), serial = Math.floor(Date.now() / 1000), cache = {}; var ver = process.version.match(/^v(\d+)\.(\d+)/); var canUseSNI = ver[1] > 1 || ver[2] >= 12; // >= 0.12.0 console.log('Per-site certificate generation is: ' + (canUseSNI ? 'ENABLED' : 'DISABLED')); console.log('Feature requires SNI support (node >= v0.12), running version is: ' + ver[0]); if(!canUseSNI) { return undefined; } var createCertificateAsync = Promise.promisify(pem.createCertificate); return function SNICallback(servername, cb) { if(!cache.hasOwnProperty(servername)) { // Slow path, put a promise for the cert into cache. Need to increment // the serial or browsers will complain. console.log('Generating new TLS certificate for: ' + servername); var certOptions = { commonName: servername, serviceKey: caKey, serviceCertificate: caCert, serial: serial++, days: 3650 }; cache[servername] = createCertificateAsync(certOptions).then(function (keys) { return tls.createSecureContext({ key: keys.clientKey, cert: keys.certificate, ca: caCert }).context; }); } cache[servername].then(function (ctx) { cb(null, ctx); }).catch(function (err) { console.log('Error generating TLS certificate: ', err); cb(err, null); }); } }
javascript
function makeSNICallback() { var caKey = fs.readFileSync(__dirname + '/../cert/dummy.key', 'utf8'), caCert = fs.readFileSync(__dirname + '/../cert/dummy.crt', 'utf8'), serial = Math.floor(Date.now() / 1000), cache = {}; var ver = process.version.match(/^v(\d+)\.(\d+)/); var canUseSNI = ver[1] > 1 || ver[2] >= 12; // >= 0.12.0 console.log('Per-site certificate generation is: ' + (canUseSNI ? 'ENABLED' : 'DISABLED')); console.log('Feature requires SNI support (node >= v0.12), running version is: ' + ver[0]); if(!canUseSNI) { return undefined; } var createCertificateAsync = Promise.promisify(pem.createCertificate); return function SNICallback(servername, cb) { if(!cache.hasOwnProperty(servername)) { // Slow path, put a promise for the cert into cache. Need to increment // the serial or browsers will complain. console.log('Generating new TLS certificate for: ' + servername); var certOptions = { commonName: servername, serviceKey: caKey, serviceCertificate: caCert, serial: serial++, days: 3650 }; cache[servername] = createCertificateAsync(certOptions).then(function (keys) { return tls.createSecureContext({ key: keys.clientKey, cert: keys.certificate, ca: caCert }).context; }); } cache[servername].then(function (ctx) { cb(null, ctx); }).catch(function (err) { console.log('Error generating TLS certificate: ', err); cb(err, null); }); } }
[ "function", "makeSNICallback", "(", ")", "{", "var", "caKey", "=", "fs", ".", "readFileSync", "(", "__dirname", "+", "'/../cert/dummy.key'", ",", "'utf8'", ")", ",", "caCert", "=", "fs", ".", "readFileSync", "(", "__dirname", "+", "'/../cert/dummy.crt'", ",", ...
Return an SNICallback to dynamically generate certificates signed by a CA. This allows you to install 'dummy.crt' as a root cert once, and then access all TLS sites without any further warnings from your browser. NOTE: This only works in node 0.12; in older versions it is not possible to generate certs asynchronously, because there was no callback argument for SNICallback. NOTE: The OpenSSL command must be in your $PATH for the 'pem' library to work. NOTE: No cache eviction is implemented, this will eventually run out of memory if implemented "as is" in a long-running process.
[ "Return", "an", "SNICallback", "to", "dynamically", "generate", "certificates", "signed", "by", "a", "CA", "." ]
93cd074978484b856323fbaedf370e521e24ad8a
https://github.com/runk/node-thin/blob/93cd074978484b856323fbaedf370e521e24ad8a/examples/helpers.js#L96-L139
35,150
bunsn/boiler
statement.js
Statement
function Statement (attributes) { for (var key in attributes) { if (attributes.hasOwnProperty(key)) this[key] = result(attributes[key]) } // Convert table rows to array of transactions var transactions = Table.prototype.rowsToArray(this.rows, { processRow: function (row) { return this.createTransaction(weld(this.columns, row)) }.bind(this) }) this.transactions = new Transactions(transactions, this) }
javascript
function Statement (attributes) { for (var key in attributes) { if (attributes.hasOwnProperty(key)) this[key] = result(attributes[key]) } // Convert table rows to array of transactions var transactions = Table.prototype.rowsToArray(this.rows, { processRow: function (row) { return this.createTransaction(weld(this.columns, row)) }.bind(this) }) this.transactions = new Transactions(transactions, this) }
[ "function", "Statement", "(", "attributes", ")", "{", "for", "(", "var", "key", "in", "attributes", ")", "{", "if", "(", "attributes", ".", "hasOwnProperty", "(", "key", ")", ")", "this", "[", "key", "]", "=", "result", "(", "attributes", "[", "key", ...
Represents a Statement @constructor @param {Object} attributes - Usually a statement definition
[ "Represents", "a", "Statement" ]
21413dcc1003d9526041e105734287cc83a596ff
https://github.com/bunsn/boiler/blob/21413dcc1003d9526041e105734287cc83a596ff/statement.js#L13-L25
35,151
goofballLogic/ld-query
src/ld-query.js
select
function select( state, json, path, isSeekAll ) { var steps = getSteps( state, path ); if ( !steps.length ) { return { json: null }; } var paths = getCachedPaths( state, json ); var walker = !!paths ? cachedWalk : walk; var found = walker( paths || json, isSeekAll ? [] : null, selectStep( steps, isSeekAll ) ); var lastStep = steps[ 0 ].path; return { json: found, isFinal: ( isSeekAll ? found.length === 0 : found === null ) || !!~[ "@id", "@index", "@value", "@type" ].indexOf( lastStep ) }; }
javascript
function select( state, json, path, isSeekAll ) { var steps = getSteps( state, path ); if ( !steps.length ) { return { json: null }; } var paths = getCachedPaths( state, json ); var walker = !!paths ? cachedWalk : walk; var found = walker( paths || json, isSeekAll ? [] : null, selectStep( steps, isSeekAll ) ); var lastStep = steps[ 0 ].path; return { json: found, isFinal: ( isSeekAll ? found.length === 0 : found === null ) || !!~[ "@id", "@index", "@value", "@type" ].indexOf( lastStep ) }; }
[ "function", "select", "(", "state", ",", "json", ",", "path", ",", "isSeekAll", ")", "{", "var", "steps", "=", "getSteps", "(", "state", ",", "path", ")", ";", "if", "(", "!", "steps", ".", "length", ")", "{", "return", "{", "json", ":", "null", ...
select json for this path
[ "select", "json", "for", "this", "path" ]
2067cf63993358c53b65ff561ff01d55b32d2420
https://github.com/goofballLogic/ld-query/blob/2067cf63993358c53b65ff561ff01d55b32d2420/src/ld-query.js#L586-L606
35,152
gfycat/gfycat-sdk
src/es5-gfycat-sdk.js
function(options, callback) { if (!options) options = {}; if (!(this.client_id || this.client_secret) && !(options.client_id || options.client_secret)) { return _handleErr('Please provide client_id and client_secret in options', callback); } var options = { api: '/oauth', endpoint: '/token', method: 'POST', payload: { client_id: options.client_id || this.client_id, client_secret: options.client_secret || this.client_secret, grant_type: options.grant_type || 'client_credentials' } } var self = this; if (callback) { return this._request(options, function(err, res) { if (!err) { self._setToken(res); callback(null, res); } else callback(err); }) } else { return this._request(options) .then(function(res) { self._setToken(res); Promise.resolve(res); }) .catch(function(err) { Promise.reject(err); }) } }
javascript
function(options, callback) { if (!options) options = {}; if (!(this.client_id || this.client_secret) && !(options.client_id || options.client_secret)) { return _handleErr('Please provide client_id and client_secret in options', callback); } var options = { api: '/oauth', endpoint: '/token', method: 'POST', payload: { client_id: options.client_id || this.client_id, client_secret: options.client_secret || this.client_secret, grant_type: options.grant_type || 'client_credentials' } } var self = this; if (callback) { return this._request(options, function(err, res) { if (!err) { self._setToken(res); callback(null, res); } else callback(err); }) } else { return this._request(options) .then(function(res) { self._setToken(res); Promise.resolve(res); }) .catch(function(err) { Promise.reject(err); }) } }
[ "function", "(", "options", ",", "callback", ")", "{", "if", "(", "!", "options", ")", "options", "=", "{", "}", ";", "if", "(", "!", "(", "this", ".", "client_id", "||", "this", ".", "client_secret", ")", "&&", "!", "(", "options", ".", "client_id...
Retrieve Oauth token. @param options - (optional if id and secret were provided in constructor) @param {string} options.client_id - Gfycat client id. @param {string} options.client_secret - Gfycat client secret. @param {string} options.grant_type - Oauth grant type. 'client_credentials' by default. @param {requestCallback} callback - (optional) callback function to run when the request completes.
[ "Retrieve", "Oauth", "token", "." ]
1a4902422a02762423e3820ad23f497dc4ad92b6
https://github.com/gfycat/gfycat-sdk/blob/1a4902422a02762423e3820ad23f497dc4ad92b6/src/es5-gfycat-sdk.js#L67-L103
35,153
gfycat/gfycat-sdk
src/es5-gfycat-sdk.js
getTrending
function getTrending(options, callback) { if (!options) options = {}; return this._request({ api: '/gfycats', endpoint: '/trending', method: 'GET', query: { count: options.count || 100, cursor: options.cursor || null, tagName: options.tagName || null } }, callback); }
javascript
function getTrending(options, callback) { if (!options) options = {}; return this._request({ api: '/gfycats', endpoint: '/trending', method: 'GET', query: { count: options.count || 100, cursor: options.cursor || null, tagName: options.tagName || null } }, callback); }
[ "function", "getTrending", "(", "options", ",", "callback", ")", "{", "if", "(", "!", "options", ")", "options", "=", "{", "}", ";", "return", "this", ".", "_request", "(", "{", "api", ":", "'/gfycats'", ",", "endpoint", ":", "'/trending'", ",", "metho...
Retrieve JSON array of trending GIFs for a given tag. If no tag name is provided, the API returns overall trending GIFs. @param {Object} options @param {number} options.count - number of GIFs to include per category. @param {string} options.cursor - cursor for pagination. @param {string} options.tagName - (optional) - name of the tag to get trending GIFs from. @param {requestCallback} callback - (optional) callback function to run when the request completes.
[ "Retrieve", "JSON", "array", "of", "trending", "GIFs", "for", "a", "given", "tag", ".", "If", "no", "tag", "name", "is", "provided", "the", "API", "returns", "overall", "trending", "GIFs", "." ]
1a4902422a02762423e3820ad23f497dc4ad92b6
https://github.com/gfycat/gfycat-sdk/blob/1a4902422a02762423e3820ad23f497dc4ad92b6/src/es5-gfycat-sdk.js#L169-L182
35,154
gfycat/gfycat-sdk
src/es5-gfycat-sdk.js
function(options, callback) { return this._request({ api: '/gfycats', endpoint: '/' + options.id + '/related', method: 'GET', query: { cursor: options.cursor, count: options.count, from: options.from } }, callback); }
javascript
function(options, callback) { return this._request({ api: '/gfycats', endpoint: '/' + options.id + '/related', method: 'GET', query: { cursor: options.cursor, count: options.count, from: options.from } }, callback); }
[ "function", "(", "options", ",", "callback", ")", "{", "return", "this", ".", "_request", "(", "{", "api", ":", "'/gfycats'", ",", "endpoint", ":", "'/'", "+", "options", ".", "id", "+", "'/related'", ",", "method", ":", "'GET'", ",", "query", ":", "...
Get a list of gifs related to a given gif @param {Object} options @param {string} options.id - gfycat id @param {requestCallback} callback - (optional) callback function to run when the request completes.
[ "Get", "a", "list", "of", "gifs", "related", "to", "a", "given", "gif" ]
1a4902422a02762423e3820ad23f497dc4ad92b6
https://github.com/gfycat/gfycat-sdk/blob/1a4902422a02762423e3820ad23f497dc4ad92b6/src/es5-gfycat-sdk.js#L271-L282
35,155
digitalbazaar/le-store-redis
index.js
getRedisOptions
function getRedisOptions() { var defaults = { debug: false, certExpiry: 100 * 60 * 60 * 24, // all cert data expires after 100 days redisOptions: { db: 3, retry_strategy: function(options) { // reconnect after 60 seconds, keep trying forever return 60 * 1000; } } }; var mergedOptions = _.merge(defaults, options); _debug('le-store-redis.getRedisOptions', mergedOptions); return mergedOptions; }
javascript
function getRedisOptions() { var defaults = { debug: false, certExpiry: 100 * 60 * 60 * 24, // all cert data expires after 100 days redisOptions: { db: 3, retry_strategy: function(options) { // reconnect after 60 seconds, keep trying forever return 60 * 1000; } } }; var mergedOptions = _.merge(defaults, options); _debug('le-store-redis.getRedisOptions', mergedOptions); return mergedOptions; }
[ "function", "getRedisOptions", "(", ")", "{", "var", "defaults", "=", "{", "debug", ":", "false", ",", "certExpiry", ":", "100", "*", "60", "*", "60", "*", "24", ",", "// all cert data expires after 100 days", "redisOptions", ":", "{", "db", ":", "3", ",",...
Gets the default options merged with the options passed to the plugin. @return {Object} default options overlayed with provided options.
[ "Gets", "the", "default", "options", "merged", "with", "the", "options", "passed", "to", "the", "plugin", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L73-L90
35,156
digitalbazaar/le-store-redis
index.js
redisSetAccountKeypair
function redisSetAccountKeypair(options, keypair, callback) { _debug('le-store-redis.redisSetAccountKeypair', '\nkeypair:', keypair); var keypairId = 'keypair-' + crypto.createHash('sha256').update(keypair.publicKeyPem).digest('hex'); var jsonKeypair = JSON.stringify(keypair); async.parallel([ function(callback) { // write the keypair data client.set(keypairId, jsonKeypair, callback); }, function(callback) { // create an index for email if one was given if(options.email) { return _createIndex('idx-e2k', options.email, keypairId, callback); } callback(null, 'NOP'); }], function(err, results) { if(err) { return callback(err); } if(results[0] !== null && results[1] !== null) { callback(null, keypair); } }); }
javascript
function redisSetAccountKeypair(options, keypair, callback) { _debug('le-store-redis.redisSetAccountKeypair', '\nkeypair:', keypair); var keypairId = 'keypair-' + crypto.createHash('sha256').update(keypair.publicKeyPem).digest('hex'); var jsonKeypair = JSON.stringify(keypair); async.parallel([ function(callback) { // write the keypair data client.set(keypairId, jsonKeypair, callback); }, function(callback) { // create an index for email if one was given if(options.email) { return _createIndex('idx-e2k', options.email, keypairId, callback); } callback(null, 'NOP'); }], function(err, results) { if(err) { return callback(err); } if(results[0] !== null && results[1] !== null) { callback(null, keypair); } }); }
[ "function", "redisSetAccountKeypair", "(", "options", ",", "keypair", ",", "callback", ")", "{", "_debug", "(", "'le-store-redis.redisSetAccountKeypair'", ",", "'\\nkeypair:'", ",", "keypair", ")", ";", "var", "keypairId", "=", "'keypair-'", "+", "crypto", ".", "c...
Creates a new instance of a le-store-redis storage driver. @param {Object[]} options - options passed to storage called @param {string} options[].email - optional email address to associate with the keypair. @param {string} options[].accountId - optional accountId to associate with the keypair. @param {Object} keypair - a keypair provided by the node-letsencrypt package. @param {Function} callback(err, keypair) - called when an error occurs, or when a keypair is successfully written to the database.
[ "Creates", "a", "new", "instance", "of", "a", "le", "-", "store", "-", "redis", "storage", "driver", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L105-L130
35,157
digitalbazaar/le-store-redis
index.js
redisCheckAccountKeypair
function redisCheckAccountKeypair(options, callback) { _debug('le-store-redis.redisCheckAccountKeypair:', options.email, options.accountId); if(options.email) { return _getByIndex('idx-e2k', options.email, callback); } else if(options.accountId) { return _getByIndex('idx-a2k', options.accountId, callback); } callback(new Error('le-store-redis.redisCheckAccountKeypair ' + 'lookup requires options.email or options.accountId.')); }
javascript
function redisCheckAccountKeypair(options, callback) { _debug('le-store-redis.redisCheckAccountKeypair:', options.email, options.accountId); if(options.email) { return _getByIndex('idx-e2k', options.email, callback); } else if(options.accountId) { return _getByIndex('idx-a2k', options.accountId, callback); } callback(new Error('le-store-redis.redisCheckAccountKeypair ' + 'lookup requires options.email or options.accountId.')); }
[ "function", "redisCheckAccountKeypair", "(", "options", ",", "callback", ")", "{", "_debug", "(", "'le-store-redis.redisCheckAccountKeypair:'", ",", "options", ".", "email", ",", "options", ".", "accountId", ")", ";", "if", "(", "options", ".", "email", ")", "{"...
Retrieves a keypair associated with an account from the database. @param {Object[]} options - options passed to storage call @param {string} options[].email - email address associated with registration. @param {string} options[].accountId - account ID as returned from redisSetAccount() @param {Function} callback(err, keypair) - called after storage attempt, keypair will be null if it was not found.
[ "Retrieves", "a", "keypair", "associated", "with", "an", "account", "from", "the", "database", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L143-L155
35,158
digitalbazaar/le-store-redis
index.js
redisCheckAccount
function redisCheckAccount(options, callback) { _debug('le-store-redis.redisCheckAccount:', options.email, options.accountId, options.domains); if(options.email) { return _getByIndex('idx-e2a', options.email, callback); } else if(options.accountId) { return client.get(options.accountId, _deserializeJson(callback)); } else if(options.domains) { // FIXME: implement domain indexing return client.get(options.domains, _deserializeJson(callback)); } callback(new Error('le-store-redis.redisCheckAccount requires ' + 'options.email, options.accountId, or options.domains')); }
javascript
function redisCheckAccount(options, callback) { _debug('le-store-redis.redisCheckAccount:', options.email, options.accountId, options.domains); if(options.email) { return _getByIndex('idx-e2a', options.email, callback); } else if(options.accountId) { return client.get(options.accountId, _deserializeJson(callback)); } else if(options.domains) { // FIXME: implement domain indexing return client.get(options.domains, _deserializeJson(callback)); } callback(new Error('le-store-redis.redisCheckAccount requires ' + 'options.email, options.accountId, or options.domains')); }
[ "function", "redisCheckAccount", "(", "options", ",", "callback", ")", "{", "_debug", "(", "'le-store-redis.redisCheckAccount:'", ",", "options", ".", "email", ",", "options", ".", "accountId", ",", "options", ".", "domains", ")", ";", "if", "(", "options", "....
Checks to see if an account exists in the database. The provided options describe how the account should be looked up. @param {Object[]} options - options passed to storage called @param {string} options[].email - optional email address to use when looking up the account. @param {string} options[].accountId - optional accountId to use when looking up the account. @param {string} options[].domains - optional domains to use when looking up the account. @param {Function} callback(err, account) - called when an error occurs, or when an account is successfully retrieved from the database.
[ "Checks", "to", "see", "if", "an", "account", "exists", "in", "the", "database", ".", "The", "provided", "options", "describe", "how", "the", "account", "should", "be", "looked", "up", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L171-L186
35,159
digitalbazaar/le-store-redis
index.js
redisSetAccount
function redisSetAccount(options, reg, callback) { _debug('le-store-redis.redisSetAccount', '\nregistration:', reg); var accountId = 'account-' + crypto.createHash('sha256') .update(reg.keypair.publicKeyPem).digest('hex'); var account = _.cloneDeep(reg); account.id = accountId; account.accountId = accountId; account.email = options.email; account.agreeTos = options.agreeTos || reg.agreeTos; var jsonAccount = JSON.stringify(account); async.parallel([ function(callback) { return client.set(accountId, jsonAccount, callback); }, function(callback) { if(account.email) { return _createIndex('idx-e2a', account.email, account.id, callback); } callback(null, 'NOP'); }], function(err, results) { if(err) { return callback(err); } if(results[0] !== null && results[1] !== null) { callback(null, account); } }); }
javascript
function redisSetAccount(options, reg, callback) { _debug('le-store-redis.redisSetAccount', '\nregistration:', reg); var accountId = 'account-' + crypto.createHash('sha256') .update(reg.keypair.publicKeyPem).digest('hex'); var account = _.cloneDeep(reg); account.id = accountId; account.accountId = accountId; account.email = options.email; account.agreeTos = options.agreeTos || reg.agreeTos; var jsonAccount = JSON.stringify(account); async.parallel([ function(callback) { return client.set(accountId, jsonAccount, callback); }, function(callback) { if(account.email) { return _createIndex('idx-e2a', account.email, account.id, callback); } callback(null, 'NOP'); }], function(err, results) { if(err) { return callback(err); } if(results[0] !== null && results[1] !== null) { callback(null, account); } }); }
[ "function", "redisSetAccount", "(", "options", ",", "reg", ",", "callback", ")", "{", "_debug", "(", "'le-store-redis.redisSetAccount'", ",", "'\\nregistration:'", ",", "reg", ")", ";", "var", "accountId", "=", "'account-'", "+", "crypto", ".", "createHash", "("...
Stores an account in the database. @param {Object[]} options - options passed to storage called @param {string} options[].email - email address associated with registration. @param {Object[]} reg - ACME registration information. @param {string} reg[].keypair - keypair used for registration. @param {string} reg[].receipt - ACME registration receipt. @param {Function} callback(err, account) - called after storage attempt.
[ "Stores", "an", "account", "in", "the", "database", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L199-L228
35,160
digitalbazaar/le-store-redis
index.js
redisSetCertificateKeypair
function redisSetCertificateKeypair(options, keypair, callback) { _debug('le-store-redis.redisSetCertificateKeypair', '\nkeypair:', keypair); var keypairId = 'keypair-' + crypto.createHash('sha256') .update(keypair.publicKeyPem).digest('hex'); var jsonKeypair = JSON.stringify(keypair); async.parallel([ function(callback) { // write the cert to the database client.set(keypairId, jsonKeypair, callback); return client.expire(keypairId, moduleOptions.certExpiry); }, function(callback) { if(options.domains) { // create a domain to keypair index return async.each(options.domains, function(domain, callback) { _createIndex('idx-d2k', domain, keypairId, moduleOptions.certExpiry, callback); }, function(err) { callback(err); }); } callback(); }], function(err) { if(err) { return callback(err); } callback(null, keypair); }); }
javascript
function redisSetCertificateKeypair(options, keypair, callback) { _debug('le-store-redis.redisSetCertificateKeypair', '\nkeypair:', keypair); var keypairId = 'keypair-' + crypto.createHash('sha256') .update(keypair.publicKeyPem).digest('hex'); var jsonKeypair = JSON.stringify(keypair); async.parallel([ function(callback) { // write the cert to the database client.set(keypairId, jsonKeypair, callback); return client.expire(keypairId, moduleOptions.certExpiry); }, function(callback) { if(options.domains) { // create a domain to keypair index return async.each(options.domains, function(domain, callback) { _createIndex('idx-d2k', domain, keypairId, moduleOptions.certExpiry, callback); }, function(err) { callback(err); }); } callback(); }], function(err) { if(err) { return callback(err); } callback(null, keypair); }); }
[ "function", "redisSetCertificateKeypair", "(", "options", ",", "keypair", ",", "callback", ")", "{", "_debug", "(", "'le-store-redis.redisSetCertificateKeypair'", ",", "'\\nkeypair:'", ",", "keypair", ")", ";", "var", "keypairId", "=", "'keypair-'", "+", "crypto", "...
Stores a keypair associated with a certificate in the database. @param {Object[]} options - options passed to storage call @param {string} options[].domains - domains that should be associated with the certificate via database indexes (to aid in lookups). @param {Function} callback(err, keypair) - called when an error occurs, or when a keypair is successfully written to the database.
[ "Stores", "a", "keypair", "associated", "with", "a", "certificate", "in", "the", "database", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L239-L268
35,161
digitalbazaar/le-store-redis
index.js
redisCheckCertificateKeypair
function redisCheckCertificateKeypair(options, callback) { _debug('le-store-redis.redisCheckCertificateKeypair:', options.domains); if(options.domains && options.domains[0]) { return _getByIndex('idx-d2k', options.domains[0], callback); } callback(new Error('le-store-redis.redisCheckCertificateKeypair requires ' + 'options.domains')); }
javascript
function redisCheckCertificateKeypair(options, callback) { _debug('le-store-redis.redisCheckCertificateKeypair:', options.domains); if(options.domains && options.domains[0]) { return _getByIndex('idx-d2k', options.domains[0], callback); } callback(new Error('le-store-redis.redisCheckCertificateKeypair requires ' + 'options.domains')); }
[ "function", "redisCheckCertificateKeypair", "(", "options", ",", "callback", ")", "{", "_debug", "(", "'le-store-redis.redisCheckCertificateKeypair:'", ",", "options", ".", "domains", ")", ";", "if", "(", "options", ".", "domains", "&&", "options", ".", "domains", ...
Retrieves a keypair associated with a certificate from the database. @param {Object[]} options - options passed to storage call @param {string} options[].domains - an array of domains that may be associated with the certificate keypair. Only the first domain is used. @param {Function} callback(err, keypair) - called after storage attempt, keypair will be null if it was not found.
[ "Retrieves", "a", "keypair", "associated", "with", "a", "certificate", "from", "the", "database", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L279-L288
35,162
digitalbazaar/le-store-redis
index.js
redisCheckCertificate
function redisCheckCertificate(options, callback) { _debug('le-store-redis.redisCheckCertificate:', options.domains, options.email, options.accountId); if(options.domains && options.domains.length > 0) { return _getByIndex('idx-d2c', options.domains[0], callback); } else if(options.email) { return _getByIndex('idx-e2c', options.email, callback); } else if(options.accountId) { return _getByIndex('idx-a2c', options.accoundId, callback); } callback(new Error('le-store-redis.redisCheckCertificate requires ' + 'options.domains, options.email, or options.accoundId')); }
javascript
function redisCheckCertificate(options, callback) { _debug('le-store-redis.redisCheckCertificate:', options.domains, options.email, options.accountId); if(options.domains && options.domains.length > 0) { return _getByIndex('idx-d2c', options.domains[0], callback); } else if(options.email) { return _getByIndex('idx-e2c', options.email, callback); } else if(options.accountId) { return _getByIndex('idx-a2c', options.accoundId, callback); } callback(new Error('le-store-redis.redisCheckCertificate requires ' + 'options.domains, options.email, or options.accoundId')); }
[ "function", "redisCheckCertificate", "(", "options", ",", "callback", ")", "{", "_debug", "(", "'le-store-redis.redisCheckCertificate:'", ",", "options", ".", "domains", ",", "options", ".", "email", ",", "options", ".", "accountId", ")", ";", "if", "(", "option...
Checks to see if a certificate exists in the database. The provided options describe how the certificate should be looked up. @param {Object[]} options - options passed to check call. @param {string} options[].domains - domains to use when looking up the account. These will be used for the lookup first. @param {string} options[].email - optional email address to use when looking up the certificate. @param {string} options[].accountId - optional accountId to use when looking up the certificate. @param {Function} callback(err, cert) - called when an error occurs, or when a certificate is successfully retrieved from the database.
[ "Checks", "to", "see", "if", "a", "certificate", "exists", "in", "the", "database", ".", "The", "provided", "options", "describe", "how", "the", "certificate", "should", "be", "looked", "up", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L304-L318
35,163
digitalbazaar/le-store-redis
index.js
redisSetCertificate
function redisSetCertificate(options, callback) { _debug('le-store-redis.redisSetCertificate', '\npems:', options.pems); var certId = 'cert-' + crypto.createHash('sha256') .update(options.pems.cert).digest('hex'); var cert = _.cloneDeep(options.pems); var jsonCert = JSON.stringify(cert); async.parallel([ function(callback) { // write the cert to the database client.set(certId, jsonCert, callback); return client.expire(certId, moduleOptions.certExpiry); }, function(callback) { if(options.accountId) { // create an accountId to cert index return _createIndex('idx-a2c', options.accountId, certId, moduleOptions.certExpiry, callback); } callback(); }, function(callback) { if(options.email) { // create an email to cert index return _createIndex('idx-e2c', options.email, certId, moduleOptions.certExpiry, callback); } callback(); }, function(callback) { if(options.domains) { // create a domain to cert index return async.each(options.domains, function(domain, callback) { _createIndex('idx-d2c', domain, certId, moduleOptions.certExpiry, callback); }, function(err) { callback(err); }); } callback(); }], function(err) { if(err) { return callback(err); } callback(null, cert); }); }
javascript
function redisSetCertificate(options, callback) { _debug('le-store-redis.redisSetCertificate', '\npems:', options.pems); var certId = 'cert-' + crypto.createHash('sha256') .update(options.pems.cert).digest('hex'); var cert = _.cloneDeep(options.pems); var jsonCert = JSON.stringify(cert); async.parallel([ function(callback) { // write the cert to the database client.set(certId, jsonCert, callback); return client.expire(certId, moduleOptions.certExpiry); }, function(callback) { if(options.accountId) { // create an accountId to cert index return _createIndex('idx-a2c', options.accountId, certId, moduleOptions.certExpiry, callback); } callback(); }, function(callback) { if(options.email) { // create an email to cert index return _createIndex('idx-e2c', options.email, certId, moduleOptions.certExpiry, callback); } callback(); }, function(callback) { if(options.domains) { // create a domain to cert index return async.each(options.domains, function(domain, callback) { _createIndex('idx-d2c', domain, certId, moduleOptions.certExpiry, callback); }, function(err) { callback(err); }); } callback(); }], function(err) { if(err) { return callback(err); } callback(null, cert); }); }
[ "function", "redisSetCertificate", "(", "options", ",", "callback", ")", "{", "_debug", "(", "'le-store-redis.redisSetCertificate'", ",", "'\\npems:'", ",", "options", ".", "pems", ")", ";", "var", "certId", "=", "'cert-'", "+", "crypto", ".", "createHash", "(",...
Stores a certificate in the database. @param {Object[]} options - options passed to the storage call. @param {string} options[].domains - domains associated with certificate. @param {string} options[].email - email address associated with certificate. @param {string} options[].accountId - accound identifier associated with certificate. @param {Object[]} options[].pems - The PEM-encoded certificate data to store. @param {string} options[].pems[].privkey - the private key. @param {string} options[].pems[].cert - the certificate. @param {string} options[].pems[].chain - the certificate chain. @param {Function} callback(err, pems) - called when an error occurs, or when all the certificate data is successfully written to the database.
[ "Stores", "a", "certificate", "in", "the", "database", "." ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L337-L385
35,164
digitalbazaar/le-store-redis
index.js
_createIndex
function _createIndex(indexName, indexData, value, ex, cb) { var callback = cb; var expiry = ex; if(!callback) { expiry = null; callback = ex; } // generate the index value var index = indexName + '-' + crypto.createHash('sha256').update(indexData).digest('hex'); client.set(index, value, function(err, reply) { if(err) { return callback(err); } if(expiry) { return client.expire(index, expiry, function(err) { callback(err, reply); }); } callback(err, reply); }); }
javascript
function _createIndex(indexName, indexData, value, ex, cb) { var callback = cb; var expiry = ex; if(!callback) { expiry = null; callback = ex; } // generate the index value var index = indexName + '-' + crypto.createHash('sha256').update(indexData).digest('hex'); client.set(index, value, function(err, reply) { if(err) { return callback(err); } if(expiry) { return client.expire(index, expiry, function(err) { callback(err, reply); }); } callback(err, reply); }); }
[ "function", "_createIndex", "(", "indexName", ",", "indexData", ",", "value", ",", "ex", ",", "cb", ")", "{", "var", "callback", "=", "cb", ";", "var", "expiry", "=", "ex", ";", "if", "(", "!", "callback", ")", "{", "expiry", "=", "null", ";", "cal...
utility function to create a Redis-based index to a particular value
[ "utility", "function", "to", "create", "a", "Redis", "-", "based", "index", "to", "a", "particular", "value" ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L388-L411
35,165
digitalbazaar/le-store-redis
index.js
_getByIndex
function _getByIndex(indexName, indexData, callback) { // generate the index var index = indexName + '-' + crypto.createHash('sha256').update(indexData).digest('hex'); // fetch the value of the index client.get(index, function(err, reply) { if(err) { return callback(err); } if(!reply) { // index does not exist return callback(null, null); } // fetch the actual data client.get(reply, _deserializeJson(callback)); }); }
javascript
function _getByIndex(indexName, indexData, callback) { // generate the index var index = indexName + '-' + crypto.createHash('sha256').update(indexData).digest('hex'); // fetch the value of the index client.get(index, function(err, reply) { if(err) { return callback(err); } if(!reply) { // index does not exist return callback(null, null); } // fetch the actual data client.get(reply, _deserializeJson(callback)); }); }
[ "function", "_getByIndex", "(", "indexName", ",", "indexData", ",", "callback", ")", "{", "// generate the index", "var", "index", "=", "indexName", "+", "'-'", "+", "crypto", ".", "createHash", "(", "'sha256'", ")", ".", "update", "(", "indexData", ")", "."...
utility function to get a Redis-based value based on an index
[ "utility", "function", "to", "get", "a", "Redis", "-", "based", "value", "based", "on", "an", "index" ]
67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e
https://github.com/digitalbazaar/le-store-redis/blob/67f8fe5e5548bfe863f5a446f174c6e5c4eb7b6e/index.js#L414-L432
35,166
ginman86/deluge
index.js
executeApiCall
function executeApiCall(callback, needConnection) { needConnection = typeof needConnection !== 'undefined' ? needConnection : true; authenticate(function (error, result) { if (error || !result) { callback(error, result); return; } if (needConnection) { isConnected(function (error, result) { if (error || !result) { console.error("[Deluge] WebUI not connected to a daemon"); return; } callback(error, result); }); } else { callback(error, result); } }); }
javascript
function executeApiCall(callback, needConnection) { needConnection = typeof needConnection !== 'undefined' ? needConnection : true; authenticate(function (error, result) { if (error || !result) { callback(error, result); return; } if (needConnection) { isConnected(function (error, result) { if (error || !result) { console.error("[Deluge] WebUI not connected to a daemon"); return; } callback(error, result); }); } else { callback(error, result); } }); }
[ "function", "executeApiCall", "(", "callback", ",", "needConnection", ")", "{", "needConnection", "=", "typeof", "needConnection", "!==", "'undefined'", "?", "needConnection", ":", "true", ";", "authenticate", "(", "function", "(", "error", ",", "result", ")", "...
Connect if not connected then execute the callback method @param callback
[ "Connect", "if", "not", "connected", "then", "execute", "the", "callback", "method" ]
1a8fadf0657bcdd527b874608ca6d0174a592f74
https://github.com/ginman86/deluge/blob/1a8fadf0657bcdd527b874608ca6d0174a592f74/index.js#L124-L143
35,167
ginman86/deluge
index.js
downloadTorrentFile
function downloadTorrentFile(url, cookie, callback) { post({ method: 'web.download_torrent_from_url', params: [url,cookie] }, callback); }
javascript
function downloadTorrentFile(url, cookie, callback) { post({ method: 'web.download_torrent_from_url', params: [url,cookie] }, callback); }
[ "function", "downloadTorrentFile", "(", "url", ",", "cookie", ",", "callback", ")", "{", "post", "(", "{", "method", ":", "'web.download_torrent_from_url'", ",", "params", ":", "[", "url", ",", "cookie", "]", "}", ",", "callback", ")", ";", "}" ]
Download a torrent file from an url @param url @param callback containing the error and the path where the torrent file have been downloaded
[ "Download", "a", "torrent", "file", "from", "an", "url" ]
1a8fadf0657bcdd527b874608ca6d0174a592f74
https://github.com/ginman86/deluge/blob/1a8fadf0657bcdd527b874608ca6d0174a592f74/index.js#L196-L201
35,168
ginman86/deluge
index.js
searchCookieJar
function searchCookieJar(url){ var cookie = ''; for (var key in COOKIE_JAR) { // Check if url starts with key, see: http://stackoverflow.com/q/646628/2402914 if (COOKIE_JAR.hasOwnProperty(key) && url.lastIndexOf(key, 0) === 0) { cookie = COOKIE_JAR[key]; console.log("Using cookies for "+key); break; } } return cookie; }
javascript
function searchCookieJar(url){ var cookie = ''; for (var key in COOKIE_JAR) { // Check if url starts with key, see: http://stackoverflow.com/q/646628/2402914 if (COOKIE_JAR.hasOwnProperty(key) && url.lastIndexOf(key, 0) === 0) { cookie = COOKIE_JAR[key]; console.log("Using cookies for "+key); break; } } return cookie; }
[ "function", "searchCookieJar", "(", "url", ")", "{", "var", "cookie", "=", "''", ";", "for", "(", "var", "key", "in", "COOKIE_JAR", ")", "{", "// Check if url starts with key, see: http://stackoverflow.com/q/646628/2402914", "if", "(", "COOKIE_JAR", ".", "hasOwnProper...
Search for a URL in the cookie jar. @param url
[ "Search", "for", "a", "URL", "in", "the", "cookie", "jar", "." ]
1a8fadf0657bcdd527b874608ca6d0174a592f74
https://github.com/ginman86/deluge/blob/1a8fadf0657bcdd527b874608ca6d0174a592f74/index.js#L207-L218
35,169
cthrax/gulp-bower-normalize
index.js
getComponents
function getComponents(file) { var relativePath = file.relative; var pathParts = Path.dirname(relativePath).split(Path.sep); return { ext: Path.extname(relativePath).substr(1), // strip dot filename: Path.basename(relativePath), packageName: pathParts[0] }; }
javascript
function getComponents(file) { var relativePath = file.relative; var pathParts = Path.dirname(relativePath).split(Path.sep); return { ext: Path.extname(relativePath).substr(1), // strip dot filename: Path.basename(relativePath), packageName: pathParts[0] }; }
[ "function", "getComponents", "(", "file", ")", "{", "var", "relativePath", "=", "file", ".", "relative", ";", "var", "pathParts", "=", "Path", ".", "dirname", "(", "relativePath", ")", ".", "split", "(", "Path", ".", "sep", ")", ";", "return", "{", "ex...
Gets the component parts, package name, filename, ext
[ "Gets", "the", "component", "parts", "package", "name", "filename", "ext" ]
07fe3283596946d5b071d72fa23ca0e787bace33
https://github.com/cthrax/gulp-bower-normalize/blob/07fe3283596946d5b071d72fa23ca0e787bace33/index.js#L14-L22
35,170
infusion/Angles.js
angles.js
function(n, a, b) { // Check if an angle n is between a and b var c = this['SCALE']; n = mod(n, c); a = mod(a, c); b = mod(b, c); if (a < b) return a <= n && n <= b; // return 0 <= n && n <= b || a <= n && n < 360; return a <= n || n <= b; }
javascript
function(n, a, b) { // Check if an angle n is between a and b var c = this['SCALE']; n = mod(n, c); a = mod(a, c); b = mod(b, c); if (a < b) return a <= n && n <= b; // return 0 <= n && n <= b || a <= n && n < 360; return a <= n || n <= b; }
[ "function", "(", "n", ",", "a", ",", "b", ")", "{", "// Check if an angle n is between a and b", "var", "c", "=", "this", "[", "'SCALE'", "]", ";", "n", "=", "mod", "(", "n", ",", "c", ")", ";", "a", "=", "mod", "(", "a", ",", "c", ")", ";", "b...
Checks if an angle is between two other angles @param {number} n @param {number} a @param {number} b @returns {boolean}
[ "Checks", "if", "an", "angle", "is", "between", "two", "other", "angles" ]
61ee48f2a46593bcf46fdfef25328ff6372e2d7b
https://github.com/infusion/Angles.js/blob/61ee48f2a46593bcf46fdfef25328ff6372e2d7b/angles.js#L86-L97
35,171
infusion/Angles.js
angles.js
function(a, b) { var m = this['SCALE']; var h = m / 2; // One-Liner: //return Math.min(mod(a - b, m), mod(b - a, m)); var diff = this['normalizeHalf'](a - b); if (diff > h) diff = diff - m; return Math.abs(diff); }
javascript
function(a, b) { var m = this['SCALE']; var h = m / 2; // One-Liner: //return Math.min(mod(a - b, m), mod(b - a, m)); var diff = this['normalizeHalf'](a - b); if (diff > h) diff = diff - m; return Math.abs(diff); }
[ "function", "(", "a", ",", "b", ")", "{", "var", "m", "=", "this", "[", "'SCALE'", "]", ";", "var", "h", "=", "m", "/", "2", ";", "// One-Liner:", "//return Math.min(mod(a - b, m), mod(b - a, m));", "var", "diff", "=", "this", "[", "'normalizeHalf'", "]", ...
Calculate the minimal distance between two angles @param {number} a @param {number} b @returns {number}
[ "Calculate", "the", "minimal", "distance", "between", "two", "angles" ]
61ee48f2a46593bcf46fdfef25328ff6372e2d7b
https://github.com/infusion/Angles.js/blob/61ee48f2a46593bcf46fdfef25328ff6372e2d7b/angles.js#L114-L128
35,172
infusion/Angles.js
angles.js
function(sin, cos) { var s = this['SCALE']; var angle = (1 + Math.acos(cos) / TAU) * s; if (sin < 0) { angle = s - angle; } return mod(angle, s); }
javascript
function(sin, cos) { var s = this['SCALE']; var angle = (1 + Math.acos(cos) / TAU) * s; if (sin < 0) { angle = s - angle; } return mod(angle, s); }
[ "function", "(", "sin", ",", "cos", ")", "{", "var", "s", "=", "this", "[", "'SCALE'", "]", ";", "var", "angle", "=", "(", "1", "+", "Math", ".", "acos", "(", "cos", ")", "/", "TAU", ")", "*", "s", ";", "if", "(", "sin", "<", "0", ")", "{...
Given the sine and cosine of an angle, what is the original angle? @param {number} sin @param {number} cos @returns {number}
[ "Given", "the", "sine", "and", "cosine", "of", "an", "angle", "what", "is", "the", "original", "angle?" ]
61ee48f2a46593bcf46fdfef25328ff6372e2d7b
https://github.com/infusion/Angles.js/blob/61ee48f2a46593bcf46fdfef25328ff6372e2d7b/angles.js#L166-L175
35,173
infusion/Angles.js
angles.js
function(p1, p2) { var s = this['SCALE']; var angle = (TAU + Math.atan2(p2[1] - p1[1], p2[0] - p1[0])) % TAU; return angle / TAU * s; }
javascript
function(p1, p2) { var s = this['SCALE']; var angle = (TAU + Math.atan2(p2[1] - p1[1], p2[0] - p1[0])) % TAU; return angle / TAU * s; }
[ "function", "(", "p1", ",", "p2", ")", "{", "var", "s", "=", "this", "[", "'SCALE'", "]", ";", "var", "angle", "=", "(", "TAU", "+", "Math", ".", "atan2", "(", "p2", "[", "1", "]", "-", "p1", "[", "1", "]", ",", "p2", "[", "0", "]", "-", ...
What is the angle of two points making a line @param {Array} p1 @param {Array} p2 @returns {number}
[ "What", "is", "the", "angle", "of", "two", "points", "making", "a", "line" ]
61ee48f2a46593bcf46fdfef25328ff6372e2d7b
https://github.com/infusion/Angles.js/blob/61ee48f2a46593bcf46fdfef25328ff6372e2d7b/angles.js#L183-L189
35,174
infusion/Angles.js
angles.js
function(x, y, k, shift) { var s = this['SCALE']; if (k === undefined) k = 4; // How many regions? 4 = quadrant, 8 = octant, ... if (shift === undefined) shift = 0; // Rotate the coordinate system by shift° (positiv = counter-clockwise) /* shift = PI / k, k = 4: * I) 45-135 * II) 135-225 * III) 225-315 * IV) 315-360 */ /* shift = 0, k = 4: * I) 0-90 * II) 90-180 * III) 180-270 * IV) 270-360 */ var phi = (Math.atan2(y, x) + TAU) / TAU; if (Math.abs(phi * s % (s / k)) < EPS) { return 0; } return 1 + mod(Math.floor(k * shift / s + k * phi), k); }
javascript
function(x, y, k, shift) { var s = this['SCALE']; if (k === undefined) k = 4; // How many regions? 4 = quadrant, 8 = octant, ... if (shift === undefined) shift = 0; // Rotate the coordinate system by shift° (positiv = counter-clockwise) /* shift = PI / k, k = 4: * I) 45-135 * II) 135-225 * III) 225-315 * IV) 315-360 */ /* shift = 0, k = 4: * I) 0-90 * II) 90-180 * III) 180-270 * IV) 270-360 */ var phi = (Math.atan2(y, x) + TAU) / TAU; if (Math.abs(phi * s % (s / k)) < EPS) { return 0; } return 1 + mod(Math.floor(k * shift / s + k * phi), k); }
[ "function", "(", "x", ",", "y", ",", "k", ",", "shift", ")", "{", "var", "s", "=", "this", "[", "'SCALE'", "]", ";", "if", "(", "k", "===", "undefined", ")", "k", "=", "4", ";", "// How many regions? 4 = quadrant, 8 = octant, ...", "if", "(", "shift", ...
Returns the quadrant @param {number} x The point x-coordinate @param {number} y The point y-coordinate @param {number=} k The optional number of regions in the coordinate-system @param {number=} shift An optional angle to rotate the coordinate system @returns {number}
[ "Returns", "the", "quadrant" ]
61ee48f2a46593bcf46fdfef25328ff6372e2d7b
https://github.com/infusion/Angles.js/blob/61ee48f2a46593bcf46fdfef25328ff6372e2d7b/angles.js#L199-L230
35,175
infusion/Angles.js
angles.js
function(course) { // 0° = N // 90° = E // 180° = S // 270° = W var s = this['SCALE']; var k = DIRECTIONS.length; // floor((2ck + s) / (2s)) = round((c / s) * k) var dir = Math.round(course / s * k); return DIRECTIONS[mod(dir, k)]; }
javascript
function(course) { // 0° = N // 90° = E // 180° = S // 270° = W var s = this['SCALE']; var k = DIRECTIONS.length; // floor((2ck + s) / (2s)) = round((c / s) * k) var dir = Math.round(course / s * k); return DIRECTIONS[mod(dir, k)]; }
[ "function", "(", "course", ")", "{", "// 0° = N", "// 90° = E", "// 180° = S", "// 270° = W", "var", "s", "=", "this", "[", "'SCALE'", "]", ";", "var", "k", "=", "DIRECTIONS", ".", "length", ";", "// floor((2ck + s) / (2s)) = round((c / s) * k)", "var", "dir", "...
Calculates the compass direction of the given angle @param {number} course @returns {string}
[ "Calculates", "the", "compass", "direction", "of", "the", "given", "angle" ]
61ee48f2a46593bcf46fdfef25328ff6372e2d7b
https://github.com/infusion/Angles.js/blob/61ee48f2a46593bcf46fdfef25328ff6372e2d7b/angles.js#L237-L251
35,176
infusion/Angles.js
angles.js
function(a, b, p, dir) { var s = this['SCALE']; a = mod(a, s); b = mod(b, s); if (a === b) return a; // dir becomes an offset if we have to add a full revolution (=scale) if (!dir) dir =-s; else if ((dir === 1) === (a < b)) dir*= s; else dir = 0; return mod(a + p * (b - a - dir), s); }
javascript
function(a, b, p, dir) { var s = this['SCALE']; a = mod(a, s); b = mod(b, s); if (a === b) return a; // dir becomes an offset if we have to add a full revolution (=scale) if (!dir) dir =-s; else if ((dir === 1) === (a < b)) dir*= s; else dir = 0; return mod(a + p * (b - a - dir), s); }
[ "function", "(", "a", ",", "b", ",", "p", ",", "dir", ")", "{", "var", "s", "=", "this", "[", "'SCALE'", "]", ";", "a", "=", "mod", "(", "a", ",", "s", ")", ";", "b", "=", "mod", "(", "b", ",", "s", ")", ";", "if", "(", "a", "===", "b...
Calculates the linear interpolation of two angles @param {number} a Angle one @param {number} b Angle two @param {number} p Percentage @param {number} dir Direction (either 1 [=CW] or -1 [=CCW]) @returns {number}
[ "Calculates", "the", "linear", "interpolation", "of", "two", "angles" ]
61ee48f2a46593bcf46fdfef25328ff6372e2d7b
https://github.com/infusion/Angles.js/blob/61ee48f2a46593bcf46fdfef25328ff6372e2d7b/angles.js#L261-L279
35,177
glenjamin/react-hotkey
example/index.js
describeKey
function describeKey(e) { var via = ''; var desc = []; if (e.getModifierState("Shift")) desc.push("Shift"); if (e.getModifierState("Control")) desc.push("Control"); if (e.getModifierState("Alt")) desc.push("Alt"); if (e.getModifierState("Meta")) desc.push("Meta"); if (e.key !== 'Unidentified') { desc.push(e.key); via = 'e.key' + (e.nativeEvent.key ? '' : ' polyfill'); } else if (e.nativeEvent.keyIdentifier) { var keyId = e.nativeEvent.keyIdentifier; if (keyId.substring(0, 2) === 'U+') { var code = parseInt(keyId.substring(2), 16); desc.push(String.fromCharCode(code)); } else { desc.push(keyId); } via = 'e.keyIdentifier'; } else if (specials[e.which]) { desc.push(specials[e.which]); via = 'e.which + lookup'; } else { desc.push(String.fromCharCode(e.which)); via = 'e.which'; } e.persist(); console.log(e); return '{' + desc.join('+') + '} (' + via + ')'; }
javascript
function describeKey(e) { var via = ''; var desc = []; if (e.getModifierState("Shift")) desc.push("Shift"); if (e.getModifierState("Control")) desc.push("Control"); if (e.getModifierState("Alt")) desc.push("Alt"); if (e.getModifierState("Meta")) desc.push("Meta"); if (e.key !== 'Unidentified') { desc.push(e.key); via = 'e.key' + (e.nativeEvent.key ? '' : ' polyfill'); } else if (e.nativeEvent.keyIdentifier) { var keyId = e.nativeEvent.keyIdentifier; if (keyId.substring(0, 2) === 'U+') { var code = parseInt(keyId.substring(2), 16); desc.push(String.fromCharCode(code)); } else { desc.push(keyId); } via = 'e.keyIdentifier'; } else if (specials[e.which]) { desc.push(specials[e.which]); via = 'e.which + lookup'; } else { desc.push(String.fromCharCode(e.which)); via = 'e.which'; } e.persist(); console.log(e); return '{' + desc.join('+') + '} (' + via + ')'; }
[ "function", "describeKey", "(", "e", ")", "{", "var", "via", "=", "''", ";", "var", "desc", "=", "[", "]", ";", "if", "(", "e", ".", "getModifierState", "(", "\"Shift\"", ")", ")", "desc", ".", "push", "(", "\"Shift\"", ")", ";", "if", "(", "e", ...
Produce a useful textual description of the key being handled
[ "Produce", "a", "useful", "textual", "description", "of", "the", "key", "being", "handled" ]
7cd9eec4f7f5c9f5a726c953591bcbb1c1668786
https://github.com/glenjamin/react-hotkey/blob/7cd9eec4f7f5c9f5a726c953591bcbb1c1668786/example/index.js#L60-L89
35,178
lwmqn/mqtt-node
lib/init.js
function (cb) { var devAttrs = { transId: null, lifetime: qn.lifetime, ip: qn.ip, version: qn.version }; qn._update(devAttrs, function (err, rsp) {}); cb(null); }
javascript
function (cb) { var devAttrs = { transId: null, lifetime: qn.lifetime, ip: qn.ip, version: qn.version }; qn._update(devAttrs, function (err, rsp) {}); cb(null); }
[ "function", "(", "cb", ")", "{", "var", "devAttrs", "=", "{", "transId", ":", "null", ",", "lifetime", ":", "qn", ".", "lifetime", ",", "ip", ":", "qn", ".", "ip", ",", "version", ":", "qn", ".", "version", "}", ";", "qn", ".", "_update", "(", ...
rid = 8
[ "rid", "=", "8" ]
3b94086d6f43ea83d04e6522ab817b1a135a86d6
https://github.com/lwmqn/mqtt-node/blob/3b94086d6f43ea83d04e6522ab817b1a135a86d6/lib/init.js#L40-L50
35,179
lwmqn/mqtt-node
lib/init.js
function (cb) { network.get_active_interface(function(err, info) { if (err) cb(err); else cb(null, info.ip_address); }); }
javascript
function (cb) { network.get_active_interface(function(err, info) { if (err) cb(err); else cb(null, info.ip_address); }); }
[ "function", "(", "cb", ")", "{", "network", ".", "get_active_interface", "(", "function", "(", "err", ",", "info", ")", "{", "if", "(", "err", ")", "cb", "(", "err", ")", ";", "else", "cb", "(", "null", ",", "info", ".", "ip_address", ")", ";", "...
rid = 4
[ "rid", "=", "4" ]
3b94086d6f43ea83d04e6522ab817b1a135a86d6
https://github.com/lwmqn/mqtt-node/blob/3b94086d6f43ea83d04e6522ab817b1a135a86d6/lib/init.js#L79-L86
35,180
lwmqn/mqtt-node
lib/init.js
function (cb) { network.get_active_interface(function(err, info) { if (err) cb(err); else cb(null, info.gateway_ip); }); }
javascript
function (cb) { network.get_active_interface(function(err, info) { if (err) cb(err); else cb(null, info.gateway_ip); }); }
[ "function", "(", "cb", ")", "{", "network", ".", "get_active_interface", "(", "function", "(", "err", ",", "info", ")", "{", "if", "(", "err", ")", "cb", "(", "err", ")", ";", "else", "cb", "(", "null", ",", "info", ".", "gateway_ip", ")", ";", "...
rid = 5
[ "rid", "=", "5" ]
3b94086d6f43ea83d04e6522ab817b1a135a86d6
https://github.com/lwmqn/mqtt-node/blob/3b94086d6f43ea83d04e6522ab817b1a135a86d6/lib/init.js#L89-L96
35,181
garex/nodejs-color-difference
lib/compare.js
compare
function compare(color1, color2, method) { var methodName = method || 'CIE76Difference'; if (undefined === methods[methodName]) { throw new Error('Method "' + methodName + '" is unknown. See implemented methods in ./lib/method directory.'); } /** @type Abstract */ var methodObj = new methods[methodName]; return methodObj.compare(new HexRgb(color1), new HexRgb(color2)); }
javascript
function compare(color1, color2, method) { var methodName = method || 'CIE76Difference'; if (undefined === methods[methodName]) { throw new Error('Method "' + methodName + '" is unknown. See implemented methods in ./lib/method directory.'); } /** @type Abstract */ var methodObj = new methods[methodName]; return methodObj.compare(new HexRgb(color1), new HexRgb(color2)); }
[ "function", "compare", "(", "color1", ",", "color2", ",", "method", ")", "{", "var", "methodName", "=", "method", "||", "'CIE76Difference'", ";", "if", "(", "undefined", "===", "methods", "[", "methodName", "]", ")", "{", "throw", "new", "Error", "(", "'...
Compares two colors and returns difference from 1 to 100 @param {String} color1 @param {String} color2 @param {String} method Default method is best from currently implemented @return {Number} difference
[ "Compares", "two", "colors", "and", "returns", "difference", "from", "1", "to", "100" ]
debdca61d5616bdab6631e1aa28453fac3efef64
https://github.com/garex/nodejs-color-difference/blob/debdca61d5616bdab6631e1aa28453fac3efef64/lib/compare.js#L17-L28
35,182
bunsn/boiler
transaction-dates.js
inUniqs
function inUniqs (d) { return uniqs.some(function (u) { return u.year === d.year && u.month === d.month && u.date === d.date }) }
javascript
function inUniqs (d) { return uniqs.some(function (u) { return u.year === d.year && u.month === d.month && u.date === d.date }) }
[ "function", "inUniqs", "(", "d", ")", "{", "return", "uniqs", ".", "some", "(", "function", "(", "u", ")", "{", "return", "u", ".", "year", "===", "d", ".", "year", "&&", "u", ".", "month", "===", "d", ".", "month", "&&", "u", ".", "date", "===...
Determines whether a date already exists in the uniqs array
[ "Determines", "whether", "a", "date", "already", "exists", "in", "the", "uniqs", "array" ]
21413dcc1003d9526041e105734287cc83a596ff
https://github.com/bunsn/boiler/blob/21413dcc1003d9526041e105734287cc83a596ff/transaction-dates.js#L40-L44
35,183
stackgl/gl-mat3
clone.js
clone
function clone(a) { var out = new Float32Array(9) out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[3] out[4] = a[4] out[5] = a[5] out[6] = a[6] out[7] = a[7] out[8] = a[8] return out }
javascript
function clone(a) { var out = new Float32Array(9) out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[3] out[4] = a[4] out[5] = a[5] out[6] = a[6] out[7] = a[7] out[8] = a[8] return out }
[ "function", "clone", "(", "a", ")", "{", "var", "out", "=", "new", "Float32Array", "(", "9", ")", "out", "[", "0", "]", "=", "a", "[", "0", "]", "out", "[", "1", "]", "=", "a", "[", "1", "]", "out", "[", "2", "]", "=", "a", "[", "2", "]...
Creates a new mat3 initialized with values from an existing matrix @alias mat3.clone @param {mat3} a matrix to clone @returns {mat3} a new 3x3 matrix
[ "Creates", "a", "new", "mat3", "initialized", "with", "values", "from", "an", "existing", "matrix" ]
df6df371ab119fb0c9f2b428d3a4f8d05cd2119e
https://github.com/stackgl/gl-mat3/blob/df6df371ab119fb0c9f2b428d3a4f8d05cd2119e/clone.js#L10-L22
35,184
bbc/ShouldIT
lib/configBuilder.js
overrideConfig
function overrideConfig(config) { if (fs.existsSync(config.config)) { var content = fs.readFileSync(config.config, { encoding: "utf8" }); var configFile = JSON.parse(content); for (var key in configFile) { if (configFile.hasOwnProperty(key)) { config[key] = configFile[key]; } } } return config; }
javascript
function overrideConfig(config) { if (fs.existsSync(config.config)) { var content = fs.readFileSync(config.config, { encoding: "utf8" }); var configFile = JSON.parse(content); for (var key in configFile) { if (configFile.hasOwnProperty(key)) { config[key] = configFile[key]; } } } return config; }
[ "function", "overrideConfig", "(", "config", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "config", ".", "config", ")", ")", "{", "var", "content", "=", "fs", ".", "readFileSync", "(", "config", ".", "config", ",", "{", "encoding", ":", "\"utf8\"...
Config options override.
[ "Config", "options", "override", "." ]
e7a9286339970c896c61058009e1d6fe812ac0df
https://github.com/bbc/ShouldIT/blob/e7a9286339970c896c61058009e1d6fe812ac0df/lib/configBuilder.js#L41-L54
35,185
itslab-kyushu/youtube-comment-scraper
lib/scraper.js
check_header
function check_header() { // PhantomJS doesn't arrow functions. page.evaluate(function() { return document.getElementsByClassName("comment-section-header-renderer").length; }).then((res) => { if (res != 0) { resolve(); } else { setTimeout(check_header, 1000); } }).catch(reject); }
javascript
function check_header() { // PhantomJS doesn't arrow functions. page.evaluate(function() { return document.getElementsByClassName("comment-section-header-renderer").length; }).then((res) => { if (res != 0) { resolve(); } else { setTimeout(check_header, 1000); } }).catch(reject); }
[ "function", "check_header", "(", ")", "{", "// PhantomJS doesn't arrow functions.", "page", ".", "evaluate", "(", "function", "(", ")", "{", "return", "document", ".", "getElementsByClassName", "(", "\"comment-section-header-renderer\"", ")", ".", "length", ";", "}", ...
Check header information has been loaded. If not, wait 1000 msec and try again, until loading is finished.
[ "Check", "header", "information", "has", "been", "loaded", ".", "If", "not", "wait", "1000", "msec", "and", "try", "again", "until", "loading", "is", "finished", "." ]
615549d47fb5f5ca8aa53c3b86515b3b1ff97cfb
https://github.com/itslab-kyushu/youtube-comment-scraper/blob/615549d47fb5f5ca8aa53c3b86515b3b1ff97cfb/lib/scraper.js#L79-L90
35,186
itslab-kyushu/youtube-comment-scraper
lib/phantom-helper.js
get_or_create
function get_or_create() { if (locked) { setTimeout(wait, 100); } else { locked = true; if (phantom_instance != null) { locked = false; resolve(phantom_instance); } else { phantom.create().then((instance) => { phantom_instance = instance; locked = false; resolve(instance); }); } } }
javascript
function get_or_create() { if (locked) { setTimeout(wait, 100); } else { locked = true; if (phantom_instance != null) { locked = false; resolve(phantom_instance); } else { phantom.create().then((instance) => { phantom_instance = instance; locked = false; resolve(instance); }); } } }
[ "function", "get_or_create", "(", ")", "{", "if", "(", "locked", ")", "{", "setTimeout", "(", "wait", ",", "100", ")", ";", "}", "else", "{", "locked", "=", "true", ";", "if", "(", "phantom_instance", "!=", "null", ")", "{", "locked", "=", "false", ...
Creates an instance of PhantomJS if there are no instance created. and returns it. Otherwise, returns the existing instance.
[ "Creates", "an", "instance", "of", "PhantomJS", "if", "there", "are", "no", "instance", "created", ".", "and", "returns", "it", ".", "Otherwise", "returns", "the", "existing", "instance", "." ]
615549d47fb5f5ca8aa53c3b86515b3b1ff97cfb
https://github.com/itslab-kyushu/youtube-comment-scraper/blob/615549d47fb5f5ca8aa53c3b86515b3b1ff97cfb/lib/phantom-helper.js#L30-L47
35,187
bunsn/boiler
transaction-date.js
TransactionDate
function TransactionDate (dateString, format, options) { options = options || {} var parsed = parseDate(dateString, format) this.year = parsed.year this.month = parsed.month this.date = parsed.date if (!this.year && options.succeedingDate) { this.year = this.calculateYear(options.succeedingDate) } }
javascript
function TransactionDate (dateString, format, options) { options = options || {} var parsed = parseDate(dateString, format) this.year = parsed.year this.month = parsed.month this.date = parsed.date if (!this.year && options.succeedingDate) { this.year = this.calculateYear(options.succeedingDate) } }
[ "function", "TransactionDate", "(", "dateString", ",", "format", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", "var", "parsed", "=", "parseDate", "(", "dateString", ",", "format", ")", "this", ".", "year", "=", "parsed", ".", "year...
Represents a transaction date @constructor @private
[ "Represents", "a", "transaction", "date" ]
21413dcc1003d9526041e105734287cc83a596ff
https://github.com/bunsn/boiler/blob/21413dcc1003d9526041e105734287cc83a596ff/transaction-date.js#L9-L20
35,188
bbc/ShouldIT
lib/inspector.js
searchAndCompare
function searchAndCompare(specObject, comparisonObject, currentDescription) { if (comparisonObject === undefined) { comparisonObject = {}; } for (var key in specObject) { if (specObject.hasOwnProperty(key)) { currentDescription.push(key); if (typeof(specObject[key]) === "string") { compare(specObject[key], comparisonObject[key], currentDescription); } else { searchAndCompare(specObject[key].specs, comparisonObject[key], currentDescription); } currentDescription.pop(); } } }
javascript
function searchAndCompare(specObject, comparisonObject, currentDescription) { if (comparisonObject === undefined) { comparisonObject = {}; } for (var key in specObject) { if (specObject.hasOwnProperty(key)) { currentDescription.push(key); if (typeof(specObject[key]) === "string") { compare(specObject[key], comparisonObject[key], currentDescription); } else { searchAndCompare(specObject[key].specs, comparisonObject[key], currentDescription); } currentDescription.pop(); } } }
[ "function", "searchAndCompare", "(", "specObject", ",", "comparisonObject", ",", "currentDescription", ")", "{", "if", "(", "comparisonObject", "===", "undefined", ")", "{", "comparisonObject", "=", "{", "}", ";", "}", "for", "(", "var", "key", "in", "specObje...
A recursive function to find nested results
[ "A", "recursive", "function", "to", "find", "nested", "results" ]
e7a9286339970c896c61058009e1d6fe812ac0df
https://github.com/bbc/ShouldIT/blob/e7a9286339970c896c61058009e1d6fe812ac0df/lib/inspector.js#L31-L48
35,189
bbc/ShouldIT
lib/inspector.js
compare
function compare(specValue, comparisonValue, currentDescription) { var lengthIndex = currentDescription.length - 1, suite = currentDescription.slice(0, (lengthIndex)).join(" "), spec = currentDescription[lengthIndex], object = {}; if (suite === "") { object[spec] = specValue; } else { object[suite] = {}; object[suite][spec] = specValue; } if (typeof(specValue) !== 'undefined' && typeof(comparisonValue) !== 'undefined') { if (comparisonValue === "PASSED") { response.passed.push(object); } else { response.failed.push(object); } } else { if (config.hint) { console.log(("ShouldIt? is running in " + config.hint + " hint mode.\n").green); console.log("One of your features has not been implelented."); console.log((object[suite][spec] + '\n').grey); console.log("The recommended test for you to implement is below:\n"); console.log(templates(config.hint, suite, spec).yellow); console.log("\n"); throw "end"; } response.pending.push(object); } }
javascript
function compare(specValue, comparisonValue, currentDescription) { var lengthIndex = currentDescription.length - 1, suite = currentDescription.slice(0, (lengthIndex)).join(" "), spec = currentDescription[lengthIndex], object = {}; if (suite === "") { object[spec] = specValue; } else { object[suite] = {}; object[suite][spec] = specValue; } if (typeof(specValue) !== 'undefined' && typeof(comparisonValue) !== 'undefined') { if (comparisonValue === "PASSED") { response.passed.push(object); } else { response.failed.push(object); } } else { if (config.hint) { console.log(("ShouldIt? is running in " + config.hint + " hint mode.\n").green); console.log("One of your features has not been implelented."); console.log((object[suite][spec] + '\n').grey); console.log("The recommended test for you to implement is below:\n"); console.log(templates(config.hint, suite, spec).yellow); console.log("\n"); throw "end"; } response.pending.push(object); } }
[ "function", "compare", "(", "specValue", ",", "comparisonValue", ",", "currentDescription", ")", "{", "var", "lengthIndex", "=", "currentDescription", ".", "length", "-", "1", ",", "suite", "=", "currentDescription", ".", "slice", "(", "0", ",", "(", "lengthIn...
Compare results and build the response
[ "Compare", "results", "and", "build", "the", "response" ]
e7a9286339970c896c61058009e1d6fe812ac0df
https://github.com/bbc/ShouldIT/blob/e7a9286339970c896c61058009e1d6fe812ac0df/lib/inspector.js#L57-L90
35,190
mikolalysenko/greedy-mesher
greedy.js
compileMesher
function compileMesher(options) { options = options || {} if(!options.order) { throw new Error("greedy-mesher: Missing order field") } if(!options.append) { throw new Error("greedy-mesher: Missing append field") } return generateMesher( options.order, options.skip, options.merge, options.append, options.extraArgs|0, options, !!options.useGetter ) }
javascript
function compileMesher(options) { options = options || {} if(!options.order) { throw new Error("greedy-mesher: Missing order field") } if(!options.append) { throw new Error("greedy-mesher: Missing append field") } return generateMesher( options.order, options.skip, options.merge, options.append, options.extraArgs|0, options, !!options.useGetter ) }
[ "function", "compileMesher", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", "if", "(", "!", "options", ".", "order", ")", "{", "throw", "new", "Error", "(", "\"greedy-mesher: Missing order field\"", ")", "}", "if", "(", "!", "options"...
The actual mesh compiler
[ "The", "actual", "mesh", "compiler" ]
080338c59e36ad209edd460252a36613dcda75fd
https://github.com/mikolalysenko/greedy-mesher/blob/080338c59e36ad209edd460252a36613dcda75fd/greedy.js#L179-L196
35,191
bbc/ShouldIT
lib/resultCollector.js
collectResults
function collectResults(resultsGlob) { var glob = require("glob"), fs = require("fs"), Q = require('q'), JunitConverter = require("./formats/junitConverter"), response = {}, count = 0, specs, files = [], converter, result; for (var i = 0; i < resultsGlob.length; i++) { files = files.concat(glob.sync(resultsGlob[i])); } var converterCallback = function(output) { result = output; }; for (i = 0; i < files.length; i++) { if (files[i].indexOf(".xml") !== -1) { converter = new JunitConverter(files[i]); converter.exec(converterCallback); } else { try { result = JSON.parse(fs.readFileSync(files[i])); } catch (err) { console.log('Error parsing JSON of ' + files[i]); result = {}; } } response = mergeResults(result, response); count++; } return Q.fcall(function () { return response; }); }
javascript
function collectResults(resultsGlob) { var glob = require("glob"), fs = require("fs"), Q = require('q'), JunitConverter = require("./formats/junitConverter"), response = {}, count = 0, specs, files = [], converter, result; for (var i = 0; i < resultsGlob.length; i++) { files = files.concat(glob.sync(resultsGlob[i])); } var converterCallback = function(output) { result = output; }; for (i = 0; i < files.length; i++) { if (files[i].indexOf(".xml") !== -1) { converter = new JunitConverter(files[i]); converter.exec(converterCallback); } else { try { result = JSON.parse(fs.readFileSync(files[i])); } catch (err) { console.log('Error parsing JSON of ' + files[i]); result = {}; } } response = mergeResults(result, response); count++; } return Q.fcall(function () { return response; }); }
[ "function", "collectResults", "(", "resultsGlob", ")", "{", "var", "glob", "=", "require", "(", "\"glob\"", ")", ",", "fs", "=", "require", "(", "\"fs\"", ")", ",", "Q", "=", "require", "(", "'q'", ")", ",", "JunitConverter", "=", "require", "(", "\"./...
Get tht results from a glob and merges the results into a single object
[ "Get", "tht", "results", "from", "a", "glob", "and", "merges", "the", "results", "into", "a", "single", "object" ]
e7a9286339970c896c61058009e1d6fe812ac0df
https://github.com/bbc/ShouldIT/blob/e7a9286339970c896c61058009e1d6fe812ac0df/lib/resultCollector.js#L7-L45
35,192
bbc/ShouldIT
lib/resultCollector.js
mergeResults
function mergeResults(spec, response) { for (var key in spec) { if (spec.hasOwnProperty(key)) { if (!response[key]) { response[key] = {}; } for (var test in spec[key]) { if (spec[key].hasOwnProperty(test)) { response[key][test] = spec[key][test]; } } } } return response; }
javascript
function mergeResults(spec, response) { for (var key in spec) { if (spec.hasOwnProperty(key)) { if (!response[key]) { response[key] = {}; } for (var test in spec[key]) { if (spec[key].hasOwnProperty(test)) { response[key][test] = spec[key][test]; } } } } return response; }
[ "function", "mergeResults", "(", "spec", ",", "response", ")", "{", "for", "(", "var", "key", "in", "spec", ")", "{", "if", "(", "spec", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "!", "response", "[", "key", "]", ")", "{", "res...
Merge the results
[ "Merge", "the", "results" ]
e7a9286339970c896c61058009e1d6fe812ac0df
https://github.com/bbc/ShouldIT/blob/e7a9286339970c896c61058009e1d6fe812ac0df/lib/resultCollector.js#L50-L65
35,193
stackgl/gl-mat3
fromMat4.js
fromMat4
function fromMat4(out, a) { out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[4] out[4] = a[5] out[5] = a[6] out[6] = a[8] out[7] = a[9] out[8] = a[10] return out }
javascript
function fromMat4(out, a) { out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[4] out[4] = a[5] out[5] = a[6] out[6] = a[8] out[7] = a[9] out[8] = a[10] return out }
[ "function", "fromMat4", "(", "out", ",", "a", ")", "{", "out", "[", "0", "]", "=", "a", "[", "0", "]", "out", "[", "1", "]", "=", "a", "[", "1", "]", "out", "[", "2", "]", "=", "a", "[", "2", "]", "out", "[", "3", "]", "=", "a", "[", ...
Copies the upper-left 3x3 values into the given mat3. @alias mat3.fromMat4 @param {mat3} out the receiving 3x3 matrix @param {mat4} a the source 4x4 matrix @returns {mat3} out
[ "Copies", "the", "upper", "-", "left", "3x3", "values", "into", "the", "given", "mat3", "." ]
df6df371ab119fb0c9f2b428d3a4f8d05cd2119e
https://github.com/stackgl/gl-mat3/blob/df6df371ab119fb0c9f2b428d3a4f8d05cd2119e/fromMat4.js#L11-L22
35,194
stackgl/gl-mat3
frob.js
frob
function frob(a) { return Math.sqrt( a[0]*a[0] + a[1]*a[1] + a[2]*a[2] + a[3]*a[3] + a[4]*a[4] + a[5]*a[5] + a[6]*a[6] + a[7]*a[7] + a[8]*a[8] ) }
javascript
function frob(a) { return Math.sqrt( a[0]*a[0] + a[1]*a[1] + a[2]*a[2] + a[3]*a[3] + a[4]*a[4] + a[5]*a[5] + a[6]*a[6] + a[7]*a[7] + a[8]*a[8] ) }
[ "function", "frob", "(", "a", ")", "{", "return", "Math", ".", "sqrt", "(", "a", "[", "0", "]", "*", "a", "[", "0", "]", "+", "a", "[", "1", "]", "*", "a", "[", "1", "]", "+", "a", "[", "2", "]", "*", "a", "[", "2", "]", "+", "a", "...
Returns Frobenius norm of a mat3 @alias mat3.frob @param {mat3} a the matrix to calculate Frobenius norm of @returns {Number} Frobenius norm
[ "Returns", "Frobenius", "norm", "of", "a", "mat3" ]
df6df371ab119fb0c9f2b428d3a4f8d05cd2119e
https://github.com/stackgl/gl-mat3/blob/df6df371ab119fb0c9f2b428d3a4f8d05cd2119e/frob.js#L10-L22
35,195
jonschlinkert/mixin-object
index.js
copy
function copy(target, obj) { if (isObject(obj)) { forIn(obj, function(value, key) { target[key] = value; }); } }
javascript
function copy(target, obj) { if (isObject(obj)) { forIn(obj, function(value, key) { target[key] = value; }); } }
[ "function", "copy", "(", "target", ",", "obj", ")", "{", "if", "(", "isObject", "(", "obj", ")", ")", "{", "forIn", "(", "obj", ",", "function", "(", "value", ",", "key", ")", "{", "target", "[", "key", "]", "=", "value", ";", "}", ")", ";", ...
copy properties from the source object to the target object. We don't use `Object.keys` here, since "mixin" also adds non-enumerable keys. @param {*} `value` @param {String} `key`
[ "copy", "properties", "from", "the", "source", "object", "to", "the", "target", "object", ".", "We", "don", "t", "use", "Object", ".", "keys", "here", "since", "mixin", "also", "adds", "non", "-", "enumerable", "keys", "." ]
1da6680d395b80604a4cb2918455b2639593655e
https://github.com/jonschlinkert/mixin-object/blob/1da6680d395b80604a4cb2918455b2639593655e/index.js#L29-L35
35,196
cucumber-attic/gherkin-syntax-highlighters
shjs/shjs-0.6-src/sh_main.js
sh_mergeTags
function sh_mergeTags(originalTags, highlightTags) { var numOriginalTags = originalTags.length; if (numOriginalTags === 0) { return highlightTags; } var numHighlightTags = highlightTags.length; if (numHighlightTags === 0) { return originalTags; } var result = []; var originalIndex = 0; var highlightIndex = 0; while (originalIndex < numOriginalTags && highlightIndex < numHighlightTags) { var originalTag = originalTags[originalIndex]; var highlightTag = highlightTags[highlightIndex]; if (originalTag.pos <= highlightTag.pos) { result.push(originalTag); originalIndex++; } else { result.push(highlightTag); if (highlightTags[highlightIndex + 1].pos <= originalTag.pos) { highlightIndex++; result.push(highlightTags[highlightIndex]); highlightIndex++; } else { // new end tag result.push({pos: originalTag.pos}); // new start tag highlightTags[highlightIndex] = {node: highlightTag.node.cloneNode(false), pos: originalTag.pos}; } } } while (originalIndex < numOriginalTags) { result.push(originalTags[originalIndex]); originalIndex++; } while (highlightIndex < numHighlightTags) { result.push(highlightTags[highlightIndex]); highlightIndex++; } return result; }
javascript
function sh_mergeTags(originalTags, highlightTags) { var numOriginalTags = originalTags.length; if (numOriginalTags === 0) { return highlightTags; } var numHighlightTags = highlightTags.length; if (numHighlightTags === 0) { return originalTags; } var result = []; var originalIndex = 0; var highlightIndex = 0; while (originalIndex < numOriginalTags && highlightIndex < numHighlightTags) { var originalTag = originalTags[originalIndex]; var highlightTag = highlightTags[highlightIndex]; if (originalTag.pos <= highlightTag.pos) { result.push(originalTag); originalIndex++; } else { result.push(highlightTag); if (highlightTags[highlightIndex + 1].pos <= originalTag.pos) { highlightIndex++; result.push(highlightTags[highlightIndex]); highlightIndex++; } else { // new end tag result.push({pos: originalTag.pos}); // new start tag highlightTags[highlightIndex] = {node: highlightTag.node.cloneNode(false), pos: originalTag.pos}; } } } while (originalIndex < numOriginalTags) { result.push(originalTags[originalIndex]); originalIndex++; } while (highlightIndex < numHighlightTags) { result.push(highlightTags[highlightIndex]); highlightIndex++; } return result; }
[ "function", "sh_mergeTags", "(", "originalTags", ",", "highlightTags", ")", "{", "var", "numOriginalTags", "=", "originalTags", ".", "length", ";", "if", "(", "numOriginalTags", "===", "0", ")", "{", "return", "highlightTags", ";", "}", "var", "numHighlightTags"...
Merges the original tags from an element with the tags produced by highlighting. @param originalTags an array containing the original tags @param highlightTags an array containing the highlighting tags - these must not overlap @result an array containing the merged tags
[ "Merges", "the", "original", "tags", "from", "an", "element", "with", "the", "tags", "produced", "by", "highlighting", "." ]
0eb0eadc1bc274c86047d12f7267c6e905bd35be
https://github.com/cucumber-attic/gherkin-syntax-highlighters/blob/0eb0eadc1bc274c86047d12f7267c6e905bd35be/shjs/shjs-0.6-src/sh_main.js#L342-L393
35,197
cucumber-attic/gherkin-syntax-highlighters
shjs/shjs-0.6-src/sh_main.js
sh_insertTags
function sh_insertTags(tags, text) { var doc = document; var result = document.createDocumentFragment(); var tagIndex = 0; var numTags = tags.length; var textPos = 0; var textLength = text.length; var currentNode = result; // output one tag or text node every iteration while (textPos < textLength || tagIndex < numTags) { var tag; var tagPos; if (tagIndex < numTags) { tag = tags[tagIndex]; tagPos = tag.pos; } else { tagPos = textLength; } if (tagPos <= textPos) { // output the tag if (tag.node) { // start tag var newNode = tag.node; currentNode.appendChild(newNode); currentNode = newNode; } else { // end tag currentNode = currentNode.parentNode; } tagIndex++; } else { // output text currentNode.appendChild(doc.createTextNode(text.substring(textPos, tagPos))); textPos = tagPos; } } return result; }
javascript
function sh_insertTags(tags, text) { var doc = document; var result = document.createDocumentFragment(); var tagIndex = 0; var numTags = tags.length; var textPos = 0; var textLength = text.length; var currentNode = result; // output one tag or text node every iteration while (textPos < textLength || tagIndex < numTags) { var tag; var tagPos; if (tagIndex < numTags) { tag = tags[tagIndex]; tagPos = tag.pos; } else { tagPos = textLength; } if (tagPos <= textPos) { // output the tag if (tag.node) { // start tag var newNode = tag.node; currentNode.appendChild(newNode); currentNode = newNode; } else { // end tag currentNode = currentNode.parentNode; } tagIndex++; } else { // output text currentNode.appendChild(doc.createTextNode(text.substring(textPos, tagPos))); textPos = tagPos; } } return result; }
[ "function", "sh_insertTags", "(", "tags", ",", "text", ")", "{", "var", "doc", "=", "document", ";", "var", "result", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "var", "tagIndex", "=", "0", ";", "var", "numTags", "=", "tags", ".", "...
Inserts tags into text. @param tags an array of tag objects @param text a string representing the text @return a DOM DocumentFragment representing the resulting HTML
[ "Inserts", "tags", "into", "text", "." ]
0eb0eadc1bc274c86047d12f7267c6e905bd35be
https://github.com/cucumber-attic/gherkin-syntax-highlighters/blob/0eb0eadc1bc274c86047d12f7267c6e905bd35be/shjs/shjs-0.6-src/sh_main.js#L401-L445
35,198
bunsn/boiler
lib/weld.js
weld
function weld (keys, values) { var object = {} for (var i = keys.length - 1; i >= 0; i--) object[keys[i]] = values[i] return object }
javascript
function weld (keys, values) { var object = {} for (var i = keys.length - 1; i >= 0; i--) object[keys[i]] = values[i] return object }
[ "function", "weld", "(", "keys", ",", "values", ")", "{", "var", "object", "=", "{", "}", "for", "(", "var", "i", "=", "keys", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "object", "[", "keys", "[", "i", "]", "]", "="...
Maps keys to values @param {Array} keys - An array of keys @param {Array} values - An array of raw values @returns {Object}
[ "Maps", "keys", "to", "values" ]
21413dcc1003d9526041e105734287cc83a596ff
https://github.com/bunsn/boiler/blob/21413dcc1003d9526041e105734287cc83a596ff/lib/weld.js#L8-L12
35,199
bunsn/boiler
transactions.js
Transactions
function Transactions (transactions, statement) { Transactions._injectPrototypeMethods(transactions) /** * Some financial institutions omit the year part in their date cells. * This workaround calculates the year for each transaction affected. */ if (!/Y{2,}/.test(statement.dateFormat)) { if (!transactions.chronological()) transactions = transactions.reverse() var succeedingDate = statement.date for (var i = transactions.length - 1; i >= 0; i--) { var transaction = transactions[i] transaction.setDate({ succeedingDate: succeedingDate }) succeedingDate = transaction.get('date') } } return transactions }
javascript
function Transactions (transactions, statement) { Transactions._injectPrototypeMethods(transactions) /** * Some financial institutions omit the year part in their date cells. * This workaround calculates the year for each transaction affected. */ if (!/Y{2,}/.test(statement.dateFormat)) { if (!transactions.chronological()) transactions = transactions.reverse() var succeedingDate = statement.date for (var i = transactions.length - 1; i >= 0; i--) { var transaction = transactions[i] transaction.setDate({ succeedingDate: succeedingDate }) succeedingDate = transaction.get('date') } } return transactions }
[ "function", "Transactions", "(", "transactions", ",", "statement", ")", "{", "Transactions", ".", "_injectPrototypeMethods", "(", "transactions", ")", "/**\n * Some financial institutions omit the year part in their date cells.\n * This workaround calculates the year for each transac...
An array-like class that represents a collection of transactions @constructor @param {Array} transactions - An array of Transaction objects @param {Object} statement - The parent statement @returns {Array} - An array of transactions with convenience methods
[ "An", "array", "-", "like", "class", "that", "represents", "a", "collection", "of", "transactions" ]
21413dcc1003d9526041e105734287cc83a596ff
https://github.com/bunsn/boiler/blob/21413dcc1003d9526041e105734287cc83a596ff/transactions.js#L11-L31