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
partition
stringclasses
1 value
rxaviers/builder-amd-css
bower_components/require-css/normalize.js
relativeURI
function relativeURI(uri, base) { // reduce base and uri strings to just their difference string var baseParts = base.split('/'); baseParts.pop(); base = baseParts.join('/') + '/'; i = 0; while (base.substr(i, 1) == uri.substr(i, 1)) i++; while (base.substr(i, 1) != '/') i--; base = base.substr(i + 1); uri = uri.substr(i + 1); // each base folder difference is thus a backtrack baseParts = base.split('/'); var uriParts = uri.split('/'); out = ''; while (baseParts.shift()) out += '../'; // finally add uri parts while (curPart = uriParts.shift()) out += curPart + '/'; return out.substr(0, out.length - 1); }
javascript
function relativeURI(uri, base) { // reduce base and uri strings to just their difference string var baseParts = base.split('/'); baseParts.pop(); base = baseParts.join('/') + '/'; i = 0; while (base.substr(i, 1) == uri.substr(i, 1)) i++; while (base.substr(i, 1) != '/') i--; base = base.substr(i + 1); uri = uri.substr(i + 1); // each base folder difference is thus a backtrack baseParts = base.split('/'); var uriParts = uri.split('/'); out = ''; while (baseParts.shift()) out += '../'; // finally add uri parts while (curPart = uriParts.shift()) out += curPart + '/'; return out.substr(0, out.length - 1); }
[ "function", "relativeURI", "(", "uri", ",", "base", ")", "{", "var", "baseParts", "=", "base", ".", "split", "(", "'/'", ")", ";", "baseParts", ".", "pop", "(", ")", ";", "base", "=", "baseParts", ".", "join", "(", "'/'", ")", "+", "'/'", ";", "i", "=", "0", ";", "while", "(", "base", ".", "substr", "(", "i", ",", "1", ")", "==", "uri", ".", "substr", "(", "i", ",", "1", ")", ")", "i", "++", ";", "while", "(", "base", ".", "substr", "(", "i", ",", "1", ")", "!=", "'/'", ")", "i", "--", ";", "base", "=", "base", ".", "substr", "(", "i", "+", "1", ")", ";", "uri", "=", "uri", ".", "substr", "(", "i", "+", "1", ")", ";", "baseParts", "=", "base", ".", "split", "(", "'/'", ")", ";", "var", "uriParts", "=", "uri", ".", "split", "(", "'/'", ")", ";", "out", "=", "''", ";", "while", "(", "baseParts", ".", "shift", "(", ")", ")", "out", "+=", "'../'", ";", "while", "(", "curPart", "=", "uriParts", ".", "shift", "(", ")", ")", "out", "+=", "curPart", "+", "'/'", ";", "return", "out", ".", "substr", "(", "0", ",", "out", ".", "length", "-", "1", ")", ";", "}" ]
given an absolute URI, calculate the relative URI
[ "given", "an", "absolute", "URI", "calculate", "the", "relative", "URI" ]
ad225d76285a68c5fa750fdc31e2f2c7365aa8b3
https://github.com/rxaviers/builder-amd-css/blob/ad225d76285a68c5fa750fdc31e2f2c7365aa8b3/bower_components/require-css/normalize.js#L87-L113
train
ahinni/underscore-more
lib/functional.js
partialAny
function partialAny(fn /* arguments */) { var appliedArgs = Array.prototype.slice.call(arguments, 1); if ( appliedArgs.length < 1 ) return fn; return function () { var args = _.deepClone(appliedArgs); var partialArgs = _.toArray(arguments); for (var i=0; i < args.length; i++) { if ( args[i] === _ ) args[i] = partialArgs.shift(); } return fn.apply(this, args.concat(partialArgs)); }; }
javascript
function partialAny(fn /* arguments */) { var appliedArgs = Array.prototype.slice.call(arguments, 1); if ( appliedArgs.length < 1 ) return fn; return function () { var args = _.deepClone(appliedArgs); var partialArgs = _.toArray(arguments); for (var i=0; i < args.length; i++) { if ( args[i] === _ ) args[i] = partialArgs.shift(); } return fn.apply(this, args.concat(partialArgs)); }; }
[ "function", "partialAny", "(", "fn", ")", "{", "var", "appliedArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "if", "(", "appliedArgs", ".", "length", "<", "1", ")", "return", "fn", ";", "return", "function", "(", ")", "{", "var", "args", "=", "_", ".", "deepClone", "(", "appliedArgs", ")", ";", "var", "partialArgs", "=", "_", ".", "toArray", "(", "arguments", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "if", "(", "args", "[", "i", "]", "===", "_", ")", "args", "[", "i", "]", "=", "partialArgs", ".", "shift", "(", ")", ";", "}", "return", "fn", ".", "apply", "(", "this", ",", "args", ".", "concat", "(", "partialArgs", ")", ")", ";", "}", ";", "}" ]
use _ as a placeholder, and bind non placeholder arguments to fn When the new function is invoked, apply the passed arguments into the placeholders
[ "use", "_", "as", "a", "placeholder", "and", "bind", "non", "placeholder", "arguments", "to", "fn", "When", "the", "new", "function", "is", "invoked", "apply", "the", "passed", "arguments", "into", "the", "placeholders" ]
91c87a2c4bf6a3bd31edb94dbf0d15630cc5284e
https://github.com/ahinni/underscore-more/blob/91c87a2c4bf6a3bd31edb94dbf0d15630cc5284e/lib/functional.js#L21-L34
train
nelsonpecora/chain-of-promises
dist/index.js
tryFn
function tryFn(fn, args) { try { return Promise.resolve(fn.apply(null, args)); } catch (e) { return Promise.reject(e); } }
javascript
function tryFn(fn, args) { try { return Promise.resolve(fn.apply(null, args)); } catch (e) { return Promise.reject(e); } }
[ "function", "tryFn", "(", "fn", ",", "args", ")", "{", "try", "{", "return", "Promise", ".", "resolve", "(", "fn", ".", "apply", "(", "null", ",", "args", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "Promise", ".", "reject", "(", "e", ")", ";", "}", "}" ]
try to resolve a function. resolve if it returns a resolved promise or value reject if it returns a rejected promise or throws an error @param {function} fn @param {array} args @returns {Promise}
[ "try", "to", "resolve", "a", "function", ".", "resolve", "if", "it", "returns", "a", "resolved", "promise", "or", "value", "reject", "if", "it", "returns", "a", "rejected", "promise", "or", "throws", "an", "error" ]
16880d9618b05410ea82fa74c20c565f2ec6d580
https://github.com/nelsonpecora/chain-of-promises/blob/16880d9618b05410ea82fa74c20c565f2ec6d580/dist/index.js#L47-L53
train
activethread/vulpejs
lib/ui/public/javascripts/internal/01-services.js
function (key, value) { if (!supported) { try { $cookieStore.set(key, value); return value; } catch (e) { console.log('Local Storage not supported, make sure you have the $cookieStore supported.'); } } var saver = JSON.stringify(value); storage.setItem(key, saver); return privateMethods.parseValue(saver); }
javascript
function (key, value) { if (!supported) { try { $cookieStore.set(key, value); return value; } catch (e) { console.log('Local Storage not supported, make sure you have the $cookieStore supported.'); } } var saver = JSON.stringify(value); storage.setItem(key, saver); return privateMethods.parseValue(saver); }
[ "function", "(", "key", ",", "value", ")", "{", "if", "(", "!", "supported", ")", "{", "try", "{", "$cookieStore", ".", "set", "(", "key", ",", "value", ")", ";", "return", "value", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'Local Storage not supported, make sure you have the $cookieStore supported.'", ")", ";", "}", "}", "var", "saver", "=", "JSON", ".", "stringify", "(", "value", ")", ";", "storage", ".", "setItem", "(", "key", ",", "saver", ")", ";", "return", "privateMethods", ".", "parseValue", "(", "saver", ")", ";", "}" ]
Set - let's you set a new localStorage key pair set @param key - a string that will be used as the accessor for the pair @param value - the value of the localStorage item @return {*} - will return whatever it is you've stored in the local storage
[ "Set", "-", "let", "s", "you", "set", "a", "new", "localStorage", "key", "pair", "set" ]
cba9529ebb13892b2c7d07219c7fa69137151fbd
https://github.com/activethread/vulpejs/blob/cba9529ebb13892b2c7d07219c7fa69137151fbd/lib/ui/public/javascripts/internal/01-services.js#L67-L79
train
activethread/vulpejs
lib/ui/public/javascripts/internal/01-services.js
function (key) { if (!supported) { try { return privateMethods.parseValue($cookieStore.get(key)); } catch (e) { return null; } } var item = storage.getItem(key); return privateMethods.parseValue(item); }
javascript
function (key) { if (!supported) { try { return privateMethods.parseValue($cookieStore.get(key)); } catch (e) { return null; } } var item = storage.getItem(key); return privateMethods.parseValue(item); }
[ "function", "(", "key", ")", "{", "if", "(", "!", "supported", ")", "{", "try", "{", "return", "privateMethods", ".", "parseValue", "(", "$cookieStore", ".", "get", "(", "key", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "null", ";", "}", "}", "var", "item", "=", "storage", ".", "getItem", "(", "key", ")", ";", "return", "privateMethods", ".", "parseValue", "(", "item", ")", ";", "}" ]
Get - let's you get the value of any pair you've stored @param key - the string that you set as accessor for the pair @return {*} - Object,String,Float,Boolean depending on what you stored
[ "Get", "-", "let", "s", "you", "get", "the", "value", "of", "any", "pair", "you", "ve", "stored" ]
cba9529ebb13892b2c7d07219c7fa69137151fbd
https://github.com/activethread/vulpejs/blob/cba9529ebb13892b2c7d07219c7fa69137151fbd/lib/ui/public/javascripts/internal/01-services.js#L87-L97
train
activethread/vulpejs
lib/ui/public/javascripts/internal/01-services.js
function (key) { if (!supported) { try { $cookieStore.remove(key); return true; } catch (e) { return false; } } storage.removeItem(key); return true; }
javascript
function (key) { if (!supported) { try { $cookieStore.remove(key); return true; } catch (e) { return false; } } storage.removeItem(key); return true; }
[ "function", "(", "key", ")", "{", "if", "(", "!", "supported", ")", "{", "try", "{", "$cookieStore", ".", "remove", "(", "key", ")", ";", "return", "true", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}", "storage", ".", "removeItem", "(", "key", ")", ";", "return", "true", ";", "}" ]
Remove - let's you nuke a value from localStorage @param key - the accessor value @return {boolean} - if everything went as planned
[ "Remove", "-", "let", "s", "you", "nuke", "a", "value", "from", "localStorage" ]
cba9529ebb13892b2c7d07219c7fa69137151fbd
https://github.com/activethread/vulpejs/blob/cba9529ebb13892b2c7d07219c7fa69137151fbd/lib/ui/public/javascripts/internal/01-services.js#L105-L116
train
camshaft/canary-store
index.js
CanaryStore
function CanaryStore() { var self = this; EventEmitter.call(self); var counter = self._counter = new Counter(); counter.on('resource', self._onresource.bind(self)); self._id = 0; self._variants = {}; self._callbacks = {}; self._assigners = []; self._assignments = {}; self._overrides = {}; self._pending = 0; // create a global context for simple cases var context = this._globalContext = this.context(this.emit.bind(this, 'change')); this.get = context.get.bind(context); this.start = context.start.bind(context); this.stop = context.stop.bind(context); }
javascript
function CanaryStore() { var self = this; EventEmitter.call(self); var counter = self._counter = new Counter(); counter.on('resource', self._onresource.bind(self)); self._id = 0; self._variants = {}; self._callbacks = {}; self._assigners = []; self._assignments = {}; self._overrides = {}; self._pending = 0; // create a global context for simple cases var context = this._globalContext = this.context(this.emit.bind(this, 'change')); this.get = context.get.bind(context); this.start = context.start.bind(context); this.stop = context.stop.bind(context); }
[ "function", "CanaryStore", "(", ")", "{", "var", "self", "=", "this", ";", "EventEmitter", ".", "call", "(", "self", ")", ";", "var", "counter", "=", "self", ".", "_counter", "=", "new", "Counter", "(", ")", ";", "counter", ".", "on", "(", "'resource'", ",", "self", ".", "_onresource", ".", "bind", "(", "self", ")", ")", ";", "self", ".", "_id", "=", "0", ";", "self", ".", "_variants", "=", "{", "}", ";", "self", ".", "_callbacks", "=", "{", "}", ";", "self", ".", "_assigners", "=", "[", "]", ";", "self", ".", "_assignments", "=", "{", "}", ";", "self", ".", "_overrides", "=", "{", "}", ";", "self", ".", "_pending", "=", "0", ";", "var", "context", "=", "this", ".", "_globalContext", "=", "this", ".", "context", "(", "this", ".", "emit", ".", "bind", "(", "this", ",", "'change'", ")", ")", ";", "this", ".", "get", "=", "context", ".", "get", ".", "bind", "(", "context", ")", ";", "this", ".", "start", "=", "context", ".", "start", ".", "bind", "(", "context", ")", ";", "this", ".", "stop", "=", "context", ".", "stop", ".", "bind", "(", "context", ")", ";", "}" ]
Create a CanaryStore
[ "Create", "a", "CanaryStore" ]
dd4f2eb33ed5146136c2d233dd2ba4fa5b59aafc
https://github.com/camshaft/canary-store/blob/dd4f2eb33ed5146136c2d233dd2ba4fa5b59aafc/index.js#L23-L42
train
mongodb-js/mj
commands/install.js
isModuleInstalledGlobally
function isModuleInstalledGlobally(name, fn) { var cmd = 'npm ls --global --json --depth=0'; exec(cmd, function(err, stdout) { if (err) { return fn(err); } var data = JSON.parse(stdout); var installed = data.dependencies[name]; fn(null, installed !== undefined); }); }
javascript
function isModuleInstalledGlobally(name, fn) { var cmd = 'npm ls --global --json --depth=0'; exec(cmd, function(err, stdout) { if (err) { return fn(err); } var data = JSON.parse(stdout); var installed = data.dependencies[name]; fn(null, installed !== undefined); }); }
[ "function", "isModuleInstalledGlobally", "(", "name", ",", "fn", ")", "{", "var", "cmd", "=", "'npm ls --global --json --depth=0'", ";", "exec", "(", "cmd", ",", "function", "(", "err", ",", "stdout", ")", "{", "if", "(", "err", ")", "{", "return", "fn", "(", "err", ")", ";", "}", "var", "data", "=", "JSON", ".", "parse", "(", "stdout", ")", ";", "var", "installed", "=", "data", ".", "dependencies", "[", "name", "]", ";", "fn", "(", "null", ",", "installed", "!==", "undefined", ")", ";", "}", ")", ";", "}" ]
Check if a module with `name` is installed globally. @param {String} name of the module, e.g. jshint @param {Function} fn (error, exists)
[ "Check", "if", "a", "module", "with", "name", "is", "installed", "globally", "." ]
a643970372c74baf8cfc7087cda80d3f6001fe7b
https://github.com/mongodb-js/mj/blob/a643970372c74baf8cfc7087cda80d3f6001fe7b/commands/install.js#L27-L38
train
neikvon/rese-api
lib/router.js
controllerWrap
function controllerWrap(ctx, ctrl, hooks, next) { let result const preHooks = [] hooks.pre.map(pre => { preHooks.push(() => pre(ctx)) }) return sequenceAndReturnOne(preHooks) .then(() => { return ctrl(ctx) }) .then(data => { if (!data && ctx.body && ctx.body.data) { data = ctx.body.data } result = data const postHooks = [] hooks.post.map(post => { // Use pre action's result for next action's data postHooks.push(preResult => post(ctx, preResult || result)) }) return sequenceAndReturnOne(postHooks) }) .then(ret => { if (!ctx.body) { ctx.body = { code: 0, data: ret || result } } next && next() }) .catch(err => { // throw errors to app error handler throw err }) }
javascript
function controllerWrap(ctx, ctrl, hooks, next) { let result const preHooks = [] hooks.pre.map(pre => { preHooks.push(() => pre(ctx)) }) return sequenceAndReturnOne(preHooks) .then(() => { return ctrl(ctx) }) .then(data => { if (!data && ctx.body && ctx.body.data) { data = ctx.body.data } result = data const postHooks = [] hooks.post.map(post => { // Use pre action's result for next action's data postHooks.push(preResult => post(ctx, preResult || result)) }) return sequenceAndReturnOne(postHooks) }) .then(ret => { if (!ctx.body) { ctx.body = { code: 0, data: ret || result } } next && next() }) .catch(err => { // throw errors to app error handler throw err }) }
[ "function", "controllerWrap", "(", "ctx", ",", "ctrl", ",", "hooks", ",", "next", ")", "{", "let", "result", "const", "preHooks", "=", "[", "]", "hooks", ".", "pre", ".", "map", "(", "pre", "=>", "{", "preHooks", ".", "push", "(", "(", ")", "=>", "pre", "(", "ctx", ")", ")", "}", ")", "return", "sequenceAndReturnOne", "(", "preHooks", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "ctrl", "(", "ctx", ")", "}", ")", ".", "then", "(", "data", "=>", "{", "if", "(", "!", "data", "&&", "ctx", ".", "body", "&&", "ctx", ".", "body", ".", "data", ")", "{", "data", "=", "ctx", ".", "body", ".", "data", "}", "result", "=", "data", "const", "postHooks", "=", "[", "]", "hooks", ".", "post", ".", "map", "(", "post", "=>", "{", "postHooks", ".", "push", "(", "preResult", "=>", "post", "(", "ctx", ",", "preResult", "||", "result", ")", ")", "}", ")", "return", "sequenceAndReturnOne", "(", "postHooks", ")", "}", ")", ".", "then", "(", "ret", "=>", "{", "if", "(", "!", "ctx", ".", "body", ")", "{", "ctx", ".", "body", "=", "{", "code", ":", "0", ",", "data", ":", "ret", "||", "result", "}", "}", "next", "&&", "next", "(", ")", "}", ")", ".", "catch", "(", "err", "=>", "{", "throw", "err", "}", ")", "}" ]
controller wrap wrap controllers for router @param {object} ctx context @param {function} ctrl controller function @param {object} hooks controller hook functions @param {function} next koa router next function @returns
[ "controller", "wrap", "wrap", "controllers", "for", "router" ]
c2361cd256b08089a1b850db65112c4806a9f3fc
https://github.com/neikvon/rese-api/blob/c2361cd256b08089a1b850db65112c4806a9f3fc/lib/router.js#L16-L52
train
SamDelgado/async-lite
async-lite.js
function(arr, iterator, callback) { callback = _doOnce(callback || noop); var amount = arr.length; if (!isArray(arr)) return callback(); var completed = 0; doEach(arr, function(item) { iterator(item, doOnce(function(err) { if (err) { callback(err); callback = noop; } else { completed++; if (completed >= amount) callback(null); } })); }); }
javascript
function(arr, iterator, callback) { callback = _doOnce(callback || noop); var amount = arr.length; if (!isArray(arr)) return callback(); var completed = 0; doEach(arr, function(item) { iterator(item, doOnce(function(err) { if (err) { callback(err); callback = noop; } else { completed++; if (completed >= amount) callback(null); } })); }); }
[ "function", "(", "arr", ",", "iterator", ",", "callback", ")", "{", "callback", "=", "_doOnce", "(", "callback", "||", "noop", ")", ";", "var", "amount", "=", "arr", ".", "length", ";", "if", "(", "!", "isArray", "(", "arr", ")", ")", "return", "callback", "(", ")", ";", "var", "completed", "=", "0", ";", "doEach", "(", "arr", ",", "function", "(", "item", ")", "{", "iterator", "(", "item", ",", "doOnce", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "callback", "=", "noop", ";", "}", "else", "{", "completed", "++", ";", "if", "(", "completed", ">=", "amount", ")", "callback", "(", "null", ")", ";", "}", "}", ")", ")", ";", "}", ")", ";", "}" ]
runs the task on every item in the array at once
[ "runs", "the", "task", "on", "every", "item", "in", "the", "array", "at", "once" ]
45977c8f707f89b4606a6c980897166e529ab405
https://github.com/SamDelgado/async-lite/blob/45977c8f707f89b4606a6c980897166e529ab405/async-lite.js#L61-L79
train
SamDelgado/async-lite
async-lite.js
function(tasks, callback) { var keys; var length; var i; var results; var kind; var updated_tasks = []; var is_object; var counter = 0; if (isArray(tasks)) { length = tasks.length; results = []; } else if (isObject(tasks)) { is_object = true; keys = ObjectKeys(tasks); length = keys.length; results = {}; } else { return callback(); } for (i=0; i<length; i++) { if (is_object) { updated_tasks.push({ k: keys[i], t: tasks[keys[i]] }); } else { updated_tasks.push({ k: i, t: tasks[i] }); } } updated_tasks.forEach(function(task_object) { task_object.t(function(err, result) { if (err) return callback(err); results[task_object.k] = result; counter++; if (counter == length) callback(null, results); }); }); }
javascript
function(tasks, callback) { var keys; var length; var i; var results; var kind; var updated_tasks = []; var is_object; var counter = 0; if (isArray(tasks)) { length = tasks.length; results = []; } else if (isObject(tasks)) { is_object = true; keys = ObjectKeys(tasks); length = keys.length; results = {}; } else { return callback(); } for (i=0; i<length; i++) { if (is_object) { updated_tasks.push({ k: keys[i], t: tasks[keys[i]] }); } else { updated_tasks.push({ k: i, t: tasks[i] }); } } updated_tasks.forEach(function(task_object) { task_object.t(function(err, result) { if (err) return callback(err); results[task_object.k] = result; counter++; if (counter == length) callback(null, results); }); }); }
[ "function", "(", "tasks", ",", "callback", ")", "{", "var", "keys", ";", "var", "length", ";", "var", "i", ";", "var", "results", ";", "var", "kind", ";", "var", "updated_tasks", "=", "[", "]", ";", "var", "is_object", ";", "var", "counter", "=", "0", ";", "if", "(", "isArray", "(", "tasks", ")", ")", "{", "length", "=", "tasks", ".", "length", ";", "results", "=", "[", "]", ";", "}", "else", "if", "(", "isObject", "(", "tasks", ")", ")", "{", "is_object", "=", "true", ";", "keys", "=", "ObjectKeys", "(", "tasks", ")", ";", "length", "=", "keys", ".", "length", ";", "results", "=", "{", "}", ";", "}", "else", "{", "return", "callback", "(", ")", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "if", "(", "is_object", ")", "{", "updated_tasks", ".", "push", "(", "{", "k", ":", "keys", "[", "i", "]", ",", "t", ":", "tasks", "[", "keys", "[", "i", "]", "]", "}", ")", ";", "}", "else", "{", "updated_tasks", ".", "push", "(", "{", "k", ":", "i", ",", "t", ":", "tasks", "[", "i", "]", "}", ")", ";", "}", "}", "updated_tasks", ".", "forEach", "(", "function", "(", "task_object", ")", "{", "task_object", ".", "t", "(", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "results", "[", "task_object", ".", "k", "]", "=", "result", ";", "counter", "++", ";", "if", "(", "counter", "==", "length", ")", "callback", "(", "null", ",", "results", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
can accept an object or array will return an object or array of results in the correct order
[ "can", "accept", "an", "object", "or", "array", "will", "return", "an", "object", "or", "array", "of", "results", "in", "the", "correct", "order" ]
45977c8f707f89b4606a6c980897166e529ab405
https://github.com/SamDelgado/async-lite/blob/45977c8f707f89b4606a6c980897166e529ab405/async-lite.js#L111-L157
train
SamDelgado/async-lite
async-lite.js
function(tasks, callback) { if (!isArray(tasks)) return callback(); var length = tasks.length; var results = []; function runTask(index) { tasks[index](function(err, result) { if (err) return callback(err); results[index] = result; if (index < length - 1) return runTask(index + 1); return callback(null, results); }); } runTask(0); }
javascript
function(tasks, callback) { if (!isArray(tasks)) return callback(); var length = tasks.length; var results = []; function runTask(index) { tasks[index](function(err, result) { if (err) return callback(err); results[index] = result; if (index < length - 1) return runTask(index + 1); return callback(null, results); }); } runTask(0); }
[ "function", "(", "tasks", ",", "callback", ")", "{", "if", "(", "!", "isArray", "(", "tasks", ")", ")", "return", "callback", "(", ")", ";", "var", "length", "=", "tasks", ".", "length", ";", "var", "results", "=", "[", "]", ";", "function", "runTask", "(", "index", ")", "{", "tasks", "[", "index", "]", "(", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "results", "[", "index", "]", "=", "result", ";", "if", "(", "index", "<", "length", "-", "1", ")", "return", "runTask", "(", "index", "+", "1", ")", ";", "return", "callback", "(", "null", ",", "results", ")", ";", "}", ")", ";", "}", "runTask", "(", "0", ")", ";", "}" ]
only accepts an array since the preservation of the order of properties on an object can't be guaranteed returns an array of results in order
[ "only", "accepts", "an", "array", "since", "the", "preservation", "of", "the", "order", "of", "properties", "on", "an", "object", "can", "t", "be", "guaranteed", "returns", "an", "array", "of", "results", "in", "order" ]
45977c8f707f89b4606a6c980897166e529ab405
https://github.com/SamDelgado/async-lite/blob/45977c8f707f89b4606a6c980897166e529ab405/async-lite.js#L161-L178
train
samsonjs/batteries
lib/object.js
methodWrapper
function methodWrapper(fn) { return function() { var args = [].slice.call(arguments); args.unshift(this); return fn.apply(this, args); }; }
javascript
function methodWrapper(fn) { return function() { var args = [].slice.call(arguments); args.unshift(this); return fn.apply(this, args); }; }
[ "function", "methodWrapper", "(", "fn", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "args", ".", "unshift", "(", "this", ")", ";", "return", "fn", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ";", "}" ]
Make a wrapper than passes `this` as the first argument, Python style. All extension functions that can extend native types must follow this convention.
[ "Make", "a", "wrapper", "than", "passes", "this", "as", "the", "first", "argument", "Python", "style", ".", "All", "extension", "functions", "that", "can", "extend", "native", "types", "must", "follow", "this", "convention", "." ]
48ca583338a89a9ec344cda7011da92dfc2f6d03
https://github.com/samsonjs/batteries/blob/48ca583338a89a9ec344cda7011da92dfc2f6d03/lib/object.js#L43-L49
train
alphakevin/new-filename
index.js
getNewFilename
function getNewFilename(list, name) { if (list.indexOf(name) === -1) { return name; } const parsed = parseFilename(name); const base = parsed.base; const ext = parsed.ext; if (!base) { const newName = getNextNumberName(ext); return getNewFilename(list, newName); } else { const basename = getNextNumberName(base); return getNewFilename(list, `${basename}${ext}`); } }
javascript
function getNewFilename(list, name) { if (list.indexOf(name) === -1) { return name; } const parsed = parseFilename(name); const base = parsed.base; const ext = parsed.ext; if (!base) { const newName = getNextNumberName(ext); return getNewFilename(list, newName); } else { const basename = getNextNumberName(base); return getNewFilename(list, `${basename}${ext}`); } }
[ "function", "getNewFilename", "(", "list", ",", "name", ")", "{", "if", "(", "list", ".", "indexOf", "(", "name", ")", "===", "-", "1", ")", "{", "return", "name", ";", "}", "const", "parsed", "=", "parseFilename", "(", "name", ")", ";", "const", "base", "=", "parsed", ".", "base", ";", "const", "ext", "=", "parsed", ".", "ext", ";", "if", "(", "!", "base", ")", "{", "const", "newName", "=", "getNextNumberName", "(", "ext", ")", ";", "return", "getNewFilename", "(", "list", ",", "newName", ")", ";", "}", "else", "{", "const", "basename", "=", "getNextNumberName", "(", "base", ")", ";", "return", "getNewFilename", "(", "list", ",", "`", "${", "basename", "}", "${", "ext", "}", "`", ")", ";", "}", "}" ]
Generating a new filename to avoid names in the list by adding sequenced number @param {string[]} list - Filenames already in use @param {string} name - New filenames about to use @returns {string} - Generated new filename
[ "Generating", "a", "new", "filename", "to", "avoid", "names", "in", "the", "list", "by", "adding", "sequenced", "number" ]
a6aab955c8a3856376a02d2f90af0e9cde9593b0
https://github.com/alphakevin/new-filename/blob/a6aab955c8a3856376a02d2f90af0e9cde9593b0/index.js#L34-L48
train
bogdosarov/grunt-contrib-less-compiller
tasks/less.js
processDirective
function processDirective(list, directive) { _(options.paths).forEach(function(filepath) { _.each(list, function(item) { item = path.join(filepath, item); console.log(item); grunt.file.expand(grunt.template.process(item)).map(function(ea) { importDirectives.push('@import' + ' (' + directive + ') ' + '"' + ea + '";'); }); }); }); console.log(importDirectives); }
javascript
function processDirective(list, directive) { _(options.paths).forEach(function(filepath) { _.each(list, function(item) { item = path.join(filepath, item); console.log(item); grunt.file.expand(grunt.template.process(item)).map(function(ea) { importDirectives.push('@import' + ' (' + directive + ') ' + '"' + ea + '";'); }); }); }); console.log(importDirectives); }
[ "function", "processDirective", "(", "list", ",", "directive", ")", "{", "_", "(", "options", ".", "paths", ")", ".", "forEach", "(", "function", "(", "filepath", ")", "{", "_", ".", "each", "(", "list", ",", "function", "(", "item", ")", "{", "item", "=", "path", ".", "join", "(", "filepath", ",", "item", ")", ";", "console", ".", "log", "(", "item", ")", ";", "grunt", ".", "file", ".", "expand", "(", "grunt", ".", "template", ".", "process", "(", "item", ")", ")", ".", "map", "(", "function", "(", "ea", ")", "{", "importDirectives", ".", "push", "(", "'@import'", "+", "' ('", "+", "directive", "+", "') '", "+", "'\"'", "+", "ea", "+", "'\";'", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "console", ".", "log", "(", "importDirectives", ")", ";", "}" ]
Prepare import directives to be prepended to source files
[ "Prepare", "import", "directives", "to", "be", "prepended", "to", "source", "files" ]
b7538ce61763fa8eba0d4abf5ea2ebddffb4e854
https://github.com/bogdosarov/grunt-contrib-less-compiller/blob/b7538ce61763fa8eba0d4abf5ea2ebddffb4e854/tasks/less.js#L122-L133
train
PsychoLlama/panic-manager
src/spawn-clients/index.js
create
function create (config) { /** Generate each client as described. */ config.clients.forEach(function (client) { if (client.type === 'node') { /** Fork a new node process. */ fork(config.panic); } }); }
javascript
function create (config) { /** Generate each client as described. */ config.clients.forEach(function (client) { if (client.type === 'node') { /** Fork a new node process. */ fork(config.panic); } }); }
[ "function", "create", "(", "config", ")", "{", "config", ".", "clients", ".", "forEach", "(", "function", "(", "client", ")", "{", "if", "(", "client", ".", "type", "===", "'node'", ")", "{", "fork", "(", "config", ".", "panic", ")", ";", "}", "}", ")", ";", "}" ]
Create a bunch of panic clients. @param {Object} config - A description of clients to generate. @param {String} config.panic - The url to a panic server. @param {Object[]} config.clients - A list of clients to generate. Each should have a client "type" string. @returns {undefined} @example create({ panic: 'http://localhost:8080', clients: [{ type: 'node' }], })
[ "Create", "a", "bunch", "of", "panic", "clients", "." ]
d68c8c918994a5b93647bd7965e364d6ddc411de
https://github.com/PsychoLlama/panic-manager/blob/d68c8c918994a5b93647bd7965e364d6ddc411de/src/spawn-clients/index.js#L20-L30
train
alexindigo/multibundle
index.js
Multibundle
function Multibundle(config, components) { var tasks; if (!(this instanceof Multibundle)) { return new Multibundle(config, components); } // turn on object mode Readable.call(this, {objectMode: true}); // prepare config options this.config = lodash.merge({}, Multibundle._defaults, config); this.config.componentOptions = lodash.cloneDeep(components); // process each component in specific order tasks = this._getComponents() .map(this._processComponent.bind(this)) .map(this._prepareForRjs.bind(this)) ; // run optimize tasks asynchronously async.parallelLimit(tasks, this.config.parallelLimit, function(err) { if (err) { this.emit('error', err); return; } // be nice if (this.config.logLevel < 4) { console.log('\n-- All requirejs bundles have been processed.'); } // singal end of the stream this.push(null); }.bind(this)); }
javascript
function Multibundle(config, components) { var tasks; if (!(this instanceof Multibundle)) { return new Multibundle(config, components); } // turn on object mode Readable.call(this, {objectMode: true}); // prepare config options this.config = lodash.merge({}, Multibundle._defaults, config); this.config.componentOptions = lodash.cloneDeep(components); // process each component in specific order tasks = this._getComponents() .map(this._processComponent.bind(this)) .map(this._prepareForRjs.bind(this)) ; // run optimize tasks asynchronously async.parallelLimit(tasks, this.config.parallelLimit, function(err) { if (err) { this.emit('error', err); return; } // be nice if (this.config.logLevel < 4) { console.log('\n-- All requirejs bundles have been processed.'); } // singal end of the stream this.push(null); }.bind(this)); }
[ "function", "Multibundle", "(", "config", ",", "components", ")", "{", "var", "tasks", ";", "if", "(", "!", "(", "this", "instanceof", "Multibundle", ")", ")", "{", "return", "new", "Multibundle", "(", "config", ",", "components", ")", ";", "}", "Readable", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "config", "=", "lodash", ".", "merge", "(", "{", "}", ",", "Multibundle", ".", "_defaults", ",", "config", ")", ";", "this", ".", "config", ".", "componentOptions", "=", "lodash", ".", "cloneDeep", "(", "components", ")", ";", "tasks", "=", "this", ".", "_getComponents", "(", ")", ".", "map", "(", "this", ".", "_processComponent", ".", "bind", "(", "this", ")", ")", ".", "map", "(", "this", ".", "_prepareForRjs", ".", "bind", "(", "this", ")", ")", ";", "async", ".", "parallelLimit", "(", "tasks", ",", "this", ".", "config", ".", "parallelLimit", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "this", ".", "emit", "(", "'error'", ",", "err", ")", ";", "return", ";", "}", "if", "(", "this", ".", "config", ".", "logLevel", "<", "4", ")", "{", "console", ".", "log", "(", "'\\n-- All requirejs bundles have been processed.'", ")", ";", "}", "\\n", "}", ".", "this", ".", "push", "(", "null", ")", ";", "bind", ")", ";", "}" ]
Parses multibundle config and transforms it into requirejs compatible options. @constructor @param {object} config - process configuration object @param {array} components - list of bundles to build @alias module:Multibundle
[ "Parses", "multibundle", "config", "and", "transforms", "it", "into", "requirejs", "compatible", "options", "." ]
3eac4c590600cc71cd8dc18119187cc73c9175bb
https://github.com/alexindigo/multibundle/blob/3eac4c590600cc71cd8dc18119187cc73c9175bb/index.js#L47-L87
train
epeli/yalr
lib/md2json.js
function (tokens){ if (!this.next()) return; if (this.current.type === "heading" && this.current.depth === this.optionDepth) { return this.findDescription(this.current.text.trim()); } this.findOption(); }
javascript
function (tokens){ if (!this.next()) return; if (this.current.type === "heading" && this.current.depth === this.optionDepth) { return this.findDescription(this.current.text.trim()); } this.findOption(); }
[ "function", "(", "tokens", ")", "{", "if", "(", "!", "this", ".", "next", "(", ")", ")", "return", ";", "if", "(", "this", ".", "current", ".", "type", "===", "\"heading\"", "&&", "this", ".", "current", ".", "depth", "===", "this", ".", "optionDepth", ")", "{", "return", "this", ".", "findDescription", "(", "this", ".", "current", ".", "text", ".", "trim", "(", ")", ")", ";", "}", "this", ".", "findOption", "(", ")", ";", "}" ]
Find an option
[ "Find", "an", "option" ]
a6c3cab59fe9ac5745e52c55210dc22c7f9a8b54
https://github.com/epeli/yalr/blob/a6c3cab59fe9ac5745e52c55210dc22c7f9a8b54/lib/md2json.js#L45-L54
train
epeli/yalr
lib/md2json.js
function (option) { if (!this.next()) return; if (this.current.type === "paragraph") { this.results.push({ name: option, description: this.current.text.trim() }); return this.findOption(); } this.findDescription(option); }
javascript
function (option) { if (!this.next()) return; if (this.current.type === "paragraph") { this.results.push({ name: option, description: this.current.text.trim() }); return this.findOption(); } this.findDescription(option); }
[ "function", "(", "option", ")", "{", "if", "(", "!", "this", ".", "next", "(", ")", ")", "return", ";", "if", "(", "this", ".", "current", ".", "type", "===", "\"paragraph\"", ")", "{", "this", ".", "results", ".", "push", "(", "{", "name", ":", "option", ",", "description", ":", "this", ".", "current", ".", "text", ".", "trim", "(", ")", "}", ")", ";", "return", "this", ".", "findOption", "(", ")", ";", "}", "this", ".", "findDescription", "(", "option", ")", ";", "}" ]
Find a description for an option
[ "Find", "a", "description", "for", "an", "option" ]
a6c3cab59fe9ac5745e52c55210dc22c7f9a8b54
https://github.com/epeli/yalr/blob/a6c3cab59fe9ac5745e52c55210dc22c7f9a8b54/lib/md2json.js#L57-L70
train
vkiding/jud-styler
lib/validator.js
LENGTH_VALIDATOR
function LENGTH_VALIDATOR(v) { v = (v || '').toString() var match = v.match(LENGTH_REGEXP) if (match) { var unit = match[1] if (!unit) { return {value: parseFloat(v)} } else if (SUPPORT_CSS_UNIT.indexOf(unit) > -1) { return {value: v} } else { return { value: parseFloat(v), reason: function reason(k, v, result) { return 'NOTE: unit `' + unit + '` is not supported and property value `' + v + '` is autofixed to `' + result + '`' } } } } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only number and pixel values are supported)' } } }
javascript
function LENGTH_VALIDATOR(v) { v = (v || '').toString() var match = v.match(LENGTH_REGEXP) if (match) { var unit = match[1] if (!unit) { return {value: parseFloat(v)} } else if (SUPPORT_CSS_UNIT.indexOf(unit) > -1) { return {value: v} } else { return { value: parseFloat(v), reason: function reason(k, v, result) { return 'NOTE: unit `' + unit + '` is not supported and property value `' + v + '` is autofixed to `' + result + '`' } } } } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only number and pixel values are supported)' } } }
[ "function", "LENGTH_VALIDATOR", "(", "v", ")", "{", "v", "=", "(", "v", "||", "''", ")", ".", "toString", "(", ")", "var", "match", "=", "v", ".", "match", "(", "LENGTH_REGEXP", ")", "if", "(", "match", ")", "{", "var", "unit", "=", "match", "[", "1", "]", "if", "(", "!", "unit", ")", "{", "return", "{", "value", ":", "parseFloat", "(", "v", ")", "}", "}", "else", "if", "(", "SUPPORT_CSS_UNIT", ".", "indexOf", "(", "unit", ")", ">", "-", "1", ")", "{", "return", "{", "value", ":", "v", "}", "}", "else", "{", "return", "{", "value", ":", "parseFloat", "(", "v", ")", ",", "reason", ":", "function", "reason", "(", "k", ",", "v", ",", "result", ")", "{", "return", "'NOTE: unit `'", "+", "unit", "+", "'` is not supported and property value `'", "+", "v", "+", "'` is autofixed to `'", "+", "result", "+", "'`'", "}", "}", "}", "}", "return", "{", "value", ":", "null", ",", "reason", ":", "function", "reason", "(", "k", ",", "v", ",", "result", ")", "{", "return", "'ERROR: property value `'", "+", "v", "+", "'` is not supported for `'", "+", "util", ".", "camelCaseToHyphened", "(", "k", ")", "+", "'` (only number and pixel values are supported)'", "}", "}", "}" ]
the values below is valid - number - number + 'px' @param {string} v @return {function} a function to return - value: number|null - reason(k, v, result)
[ "the", "values", "below", "is", "valid", "-", "number", "-", "number", "+", "px" ]
1563f84b9acd649bd546a8859e9a9226689ef1dc
https://github.com/vkiding/jud-styler/blob/1563f84b9acd649bd546a8859e9a9226689ef1dc/lib/validator.js#L187-L215
train
vkiding/jud-styler
lib/validator.js
NUMBER_VALIDATOR
function NUMBER_VALIDATOR(v) { v = (v || '').toString() var match = v.match(LENGTH_REGEXP) if (match && !match[1]) { return {value: parseFloat(v)} } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only number is supported)' } } }
javascript
function NUMBER_VALIDATOR(v) { v = (v || '').toString() var match = v.match(LENGTH_REGEXP) if (match && !match[1]) { return {value: parseFloat(v)} } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only number is supported)' } } }
[ "function", "NUMBER_VALIDATOR", "(", "v", ")", "{", "v", "=", "(", "v", "||", "''", ")", ".", "toString", "(", ")", "var", "match", "=", "v", ".", "match", "(", "LENGTH_REGEXP", ")", "if", "(", "match", "&&", "!", "match", "[", "1", "]", ")", "{", "return", "{", "value", ":", "parseFloat", "(", "v", ")", "}", "}", "return", "{", "value", ":", "null", ",", "reason", ":", "function", "reason", "(", "k", ",", "v", ",", "result", ")", "{", "return", "'ERROR: property value `'", "+", "v", "+", "'` is not supported for `'", "+", "util", ".", "camelCaseToHyphened", "(", "k", ")", "+", "'` (only number is supported)'", "}", "}", "}" ]
only integer or float value is valid @param {string} v @return {function} a function to return - value: number|null - reason(k, v, result)
[ "only", "integer", "or", "float", "value", "is", "valid" ]
1563f84b9acd649bd546a8859e9a9226689ef1dc
https://github.com/vkiding/jud-styler/blob/1563f84b9acd649bd546a8859e9a9226689ef1dc/lib/validator.js#L292-L306
train
vkiding/jud-styler
lib/validator.js
INTEGER_VALIDATOR
function INTEGER_VALIDATOR(v) { v = (v || '').toString() if (v.match(/^[-+]?\d+$/)) { return {value: parseInt(v, 10)} } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only integer is supported)' } } }
javascript
function INTEGER_VALIDATOR(v) { v = (v || '').toString() if (v.match(/^[-+]?\d+$/)) { return {value: parseInt(v, 10)} } return { value: null, reason: function reason(k, v, result) { return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only integer is supported)' } } }
[ "function", "INTEGER_VALIDATOR", "(", "v", ")", "{", "v", "=", "(", "v", "||", "''", ")", ".", "toString", "(", ")", "if", "(", "v", ".", "match", "(", "/", "^[-+]?\\d+$", "/", ")", ")", "{", "return", "{", "value", ":", "parseInt", "(", "v", ",", "10", ")", "}", "}", "return", "{", "value", ":", "null", ",", "reason", ":", "function", "reason", "(", "k", ",", "v", ",", "result", ")", "{", "return", "'ERROR: property value `'", "+", "v", "+", "'` is not supported for `'", "+", "util", ".", "camelCaseToHyphened", "(", "k", ")", "+", "'` (only integer is supported)'", "}", "}", "}" ]
only integer value is valid @param {string} v @return {function} a function to return - value: number|null - reason(k, v, result)
[ "only", "integer", "value", "is", "valid" ]
1563f84b9acd649bd546a8859e9a9226689ef1dc
https://github.com/vkiding/jud-styler/blob/1563f84b9acd649bd546a8859e9a9226689ef1dc/lib/validator.js#L316-L329
train
vkiding/jud-styler
lib/validator.js
genValidatorMap
function genValidatorMap() { var groupName, group, name for (groupName in PROP_NAME_GROUPS) { group = PROP_NAME_GROUPS[groupName] for (name in group) { validatorMap[name] = group[name] } } }
javascript
function genValidatorMap() { var groupName, group, name for (groupName in PROP_NAME_GROUPS) { group = PROP_NAME_GROUPS[groupName] for (name in group) { validatorMap[name] = group[name] } } }
[ "function", "genValidatorMap", "(", ")", "{", "var", "groupName", ",", "group", ",", "name", "for", "(", "groupName", "in", "PROP_NAME_GROUPS", ")", "{", "group", "=", "PROP_NAME_GROUPS", "[", "groupName", "]", "for", "(", "name", "in", "group", ")", "{", "validatorMap", "[", "name", "]", "=", "group", "[", "name", "]", "}", "}", "}" ]
flatten `PROP_NAME_GROUPS` to `validatorMap`
[ "flatten", "PROP_NAME_GROUPS", "to", "validatorMap" ]
1563f84b9acd649bd546a8859e9a9226689ef1dc
https://github.com/vkiding/jud-styler/blob/1563f84b9acd649bd546a8859e9a9226689ef1dc/lib/validator.js#L544-L552
train
monoture/monoture-dashboard
public/app/services/post.js
function(post) { return $http({ url : '/api/v1/posts/' + post._id, method : 'PUT', params : {access_token : authProvider.getUser().token}, data : post }).catch(authProvider.checkApiResponse); }
javascript
function(post) { return $http({ url : '/api/v1/posts/' + post._id, method : 'PUT', params : {access_token : authProvider.getUser().token}, data : post }).catch(authProvider.checkApiResponse); }
[ "function", "(", "post", ")", "{", "return", "$http", "(", "{", "url", ":", "'/api/v1/posts/'", "+", "post", ".", "_id", ",", "method", ":", "'PUT'", ",", "params", ":", "{", "access_token", ":", "authProvider", ".", "getUser", "(", ")", ".", "token", "}", ",", "data", ":", "post", "}", ")", ".", "catch", "(", "authProvider", ".", "checkApiResponse", ")", ";", "}" ]
Saves a post
[ "Saves", "a", "post" ]
0f64656585a69fa0035adec130bce7b3d1b259f4
https://github.com/monoture/monoture-dashboard/blob/0f64656585a69fa0035adec130bce7b3d1b259f4/public/app/services/post.js#L23-L30
train
monoture/monoture-dashboard
public/app/services/post.js
function(id) { return $http({ url : '/api/v1/posts/' + id, method : 'DELETE', params : {access_token : authProvider.getUser().token} }).catch(authProvider.checkApiResponse); }
javascript
function(id) { return $http({ url : '/api/v1/posts/' + id, method : 'DELETE', params : {access_token : authProvider.getUser().token} }).catch(authProvider.checkApiResponse); }
[ "function", "(", "id", ")", "{", "return", "$http", "(", "{", "url", ":", "'/api/v1/posts/'", "+", "id", ",", "method", ":", "'DELETE'", ",", "params", ":", "{", "access_token", ":", "authProvider", ".", "getUser", "(", ")", ".", "token", "}", "}", ")", ".", "catch", "(", "authProvider", ".", "checkApiResponse", ")", ";", "}" ]
Deletes a post
[ "Deletes", "a", "post" ]
0f64656585a69fa0035adec130bce7b3d1b259f4
https://github.com/monoture/monoture-dashboard/blob/0f64656585a69fa0035adec130bce7b3d1b259f4/public/app/services/post.js#L43-L49
train
RnbWd/parse-browserify
lib/router.js
function() { if (!this.routes) { return; } var routes = []; for (var route in this.routes) { if (this.routes.hasOwnProperty(route)) { routes.unshift([route, this.routes[route]]); } } for (var i = 0, l = routes.length; i < l; i++) { this.route(routes[i][0], routes[i][1], this[routes[i][1]]); } }
javascript
function() { if (!this.routes) { return; } var routes = []; for (var route in this.routes) { if (this.routes.hasOwnProperty(route)) { routes.unshift([route, this.routes[route]]); } } for (var i = 0, l = routes.length; i < l; i++) { this.route(routes[i][0], routes[i][1], this[routes[i][1]]); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "routes", ")", "{", "return", ";", "}", "var", "routes", "=", "[", "]", ";", "for", "(", "var", "route", "in", "this", ".", "routes", ")", "{", "if", "(", "this", ".", "routes", ".", "hasOwnProperty", "(", "route", ")", ")", "{", "routes", ".", "unshift", "(", "[", "route", ",", "this", ".", "routes", "[", "route", "]", "]", ")", ";", "}", "}", "for", "(", "var", "i", "=", "0", ",", "l", "=", "routes", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "this", ".", "route", "(", "routes", "[", "i", "]", "[", "0", "]", ",", "routes", "[", "i", "]", "[", "1", "]", ",", "this", "[", "routes", "[", "i", "]", "[", "1", "]", "]", ")", ";", "}", "}" ]
Bind all defined routes to `Parse.history`. We have to reverse the order of the routes here to support behavior where the most general routes can be defined at the bottom of the route map.
[ "Bind", "all", "defined", "routes", "to", "Parse", ".", "history", ".", "We", "have", "to", "reverse", "the", "order", "of", "the", "routes", "here", "to", "support", "behavior", "where", "the", "most", "general", "routes", "can", "be", "defined", "at", "the", "bottom", "of", "the", "route", "map", "." ]
c19c1b798e4010a552e130b1a9ce3b5d084dc101
https://github.com/RnbWd/parse-browserify/blob/c19c1b798e4010a552e130b1a9ce3b5d084dc101/lib/router.js#L82-L95
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editable.js
function( editor, element ) { // Transform the element into a CKEDITOR.dom.element instance. this.base( element.$ || element ); this.editor = editor; /** * Indicates the initialization status of the editable element. The following statuses are available: * * * **unloaded** &ndash; the initial state. The editable's instance was created but * is not fully loaded (in particular it has no data). * * **ready** &ndash; the editable is fully initialized. The `ready` status is set after * the first {@link CKEDITOR.editor#method-setData} is called. * * **detached** &ndash; the editable was detached. * * @since 4.3.3 * @readonly * @property {String} */ this.status = 'unloaded'; /** * Indicates whether the editable element gained focus. * * @property {Boolean} hasFocus */ this.hasFocus = false; // The bootstrapping logic. this.setup(); }
javascript
function( editor, element ) { // Transform the element into a CKEDITOR.dom.element instance. this.base( element.$ || element ); this.editor = editor; /** * Indicates the initialization status of the editable element. The following statuses are available: * * * **unloaded** &ndash; the initial state. The editable's instance was created but * is not fully loaded (in particular it has no data). * * **ready** &ndash; the editable is fully initialized. The `ready` status is set after * the first {@link CKEDITOR.editor#method-setData} is called. * * **detached** &ndash; the editable was detached. * * @since 4.3.3 * @readonly * @property {String} */ this.status = 'unloaded'; /** * Indicates whether the editable element gained focus. * * @property {Boolean} hasFocus */ this.hasFocus = false; // The bootstrapping logic. this.setup(); }
[ "function", "(", "editor", ",", "element", ")", "{", "this", ".", "base", "(", "element", ".", "$", "||", "element", ")", ";", "this", ".", "editor", "=", "editor", ";", "this", ".", "status", "=", "'unloaded'", ";", "this", ".", "hasFocus", "=", "false", ";", "this", ".", "setup", "(", ")", ";", "}" ]
The constructor only stores generic editable creation logic that is commonly shared among all different editable elements. @constructor Creates an editable class instance. @param {CKEDITOR.editor} editor The editor instance on which the editable operates. @param {HTMLElement/CKEDITOR.dom.element} element Any DOM element that was as the editor's editing container, e.g. it could be either an HTML element with the `contenteditable` attribute set to the `true` that handles WYSIWYG editing or a `<textarea>` element that handles source editing.
[ "The", "constructor", "only", "stores", "generic", "editable", "creation", "logic", "that", "is", "commonly", "shared", "among", "all", "different", "editable", "elements", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L26-L56
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editable.js
function( cls ) { var classes = this.getCustomData( 'classes' ); if ( !this.hasClass( cls ) ) { !classes && ( classes = [] ), classes.push( cls ); this.setCustomData( 'classes', classes ); this.addClass( cls ); } }
javascript
function( cls ) { var classes = this.getCustomData( 'classes' ); if ( !this.hasClass( cls ) ) { !classes && ( classes = [] ), classes.push( cls ); this.setCustomData( 'classes', classes ); this.addClass( cls ); } }
[ "function", "(", "cls", ")", "{", "var", "classes", "=", "this", ".", "getCustomData", "(", "'classes'", ")", ";", "if", "(", "!", "this", ".", "hasClass", "(", "cls", ")", ")", "{", "!", "classes", "&&", "(", "classes", "=", "[", "]", ")", ",", "classes", ".", "push", "(", "cls", ")", ";", "this", ".", "setCustomData", "(", "'classes'", ",", "classes", ")", ";", "this", ".", "addClass", "(", "cls", ")", ";", "}", "}" ]
Adds a CSS class name to this editable that needs to be removed on detaching. @param {String} className The class name to be added. @see CKEDITOR.dom.element#addClass
[ "Adds", "a", "CSS", "class", "name", "to", "this", "editable", "that", "needs", "to", "be", "removed", "on", "detaching", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L206-L213
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editable.js
function( attr, val ) { var orgVal = this.getAttribute( attr ); if ( val !== orgVal ) { !this._.attrChanges && ( this._.attrChanges = {} ); // Saved the original attribute val. if ( !( attr in this._.attrChanges ) ) this._.attrChanges[ attr ] = orgVal; this.setAttribute( attr, val ); } }
javascript
function( attr, val ) { var orgVal = this.getAttribute( attr ); if ( val !== orgVal ) { !this._.attrChanges && ( this._.attrChanges = {} ); // Saved the original attribute val. if ( !( attr in this._.attrChanges ) ) this._.attrChanges[ attr ] = orgVal; this.setAttribute( attr, val ); } }
[ "function", "(", "attr", ",", "val", ")", "{", "var", "orgVal", "=", "this", ".", "getAttribute", "(", "attr", ")", ";", "if", "(", "val", "!==", "orgVal", ")", "{", "!", "this", ".", "_", ".", "attrChanges", "&&", "(", "this", ".", "_", ".", "attrChanges", "=", "{", "}", ")", ";", "if", "(", "!", "(", "attr", "in", "this", ".", "_", ".", "attrChanges", ")", ")", "this", ".", "_", ".", "attrChanges", "[", "attr", "]", "=", "orgVal", ";", "this", ".", "setAttribute", "(", "attr", ",", "val", ")", ";", "}", "}" ]
Make an attribution change that would be reverted on editable detaching. @param {String} attr The attribute name to be changed. @param {String} val The value of specified attribute.
[ "Make", "an", "attribution", "change", "that", "would", "be", "reverted", "on", "editable", "detaching", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L220-L231
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editable.js
function( element, range ) { var editor = this.editor, enterMode = editor.config.enterMode, elementName = element.getName(), isBlock = CKEDITOR.dtd.$block[ elementName ]; if ( range.checkReadOnly() ) return false; // Remove the original contents, merge split nodes. range.deleteContents( 1 ); // If range is placed in inermediate element (not td or th), we need to do three things: // * fill emptied <td/th>s with if browser needs them, // * remove empty text nodes so IE8 won't crash (http://dev.ckeditor.com/ticket/11183#comment:8), // * fix structure and move range into the <td/th> element. if ( range.startContainer.type == CKEDITOR.NODE_ELEMENT && range.startContainer.is( { tr: 1, table: 1, tbody: 1, thead: 1, tfoot: 1 } ) ) fixTableAfterContentsDeletion( range ); // If we're inserting a block at dtd-violated position, split // the parent blocks until we reach blockLimit. var current, dtd; if ( isBlock ) { while ( ( current = range.getCommonAncestor( 0, 1 ) ) && ( dtd = CKEDITOR.dtd[ current.getName() ] ) && !( dtd && dtd[ elementName ] ) ) { // Split up inline elements. if ( current.getName() in CKEDITOR.dtd.span ) range.splitElement( current ); // If we're in an empty block which indicate a new paragraph, // simply replace it with the inserting block.(#3664) else if ( range.checkStartOfBlock() && range.checkEndOfBlock() ) { range.setStartBefore( current ); range.collapse( true ); current.remove(); } else { range.splitBlock( enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p', editor.editable() ); } } } // Insert the new node. range.insertNode( element ); // Return true if insertion was successful. return true; }
javascript
function( element, range ) { var editor = this.editor, enterMode = editor.config.enterMode, elementName = element.getName(), isBlock = CKEDITOR.dtd.$block[ elementName ]; if ( range.checkReadOnly() ) return false; // Remove the original contents, merge split nodes. range.deleteContents( 1 ); // If range is placed in inermediate element (not td or th), we need to do three things: // * fill emptied <td/th>s with if browser needs them, // * remove empty text nodes so IE8 won't crash (http://dev.ckeditor.com/ticket/11183#comment:8), // * fix structure and move range into the <td/th> element. if ( range.startContainer.type == CKEDITOR.NODE_ELEMENT && range.startContainer.is( { tr: 1, table: 1, tbody: 1, thead: 1, tfoot: 1 } ) ) fixTableAfterContentsDeletion( range ); // If we're inserting a block at dtd-violated position, split // the parent blocks until we reach blockLimit. var current, dtd; if ( isBlock ) { while ( ( current = range.getCommonAncestor( 0, 1 ) ) && ( dtd = CKEDITOR.dtd[ current.getName() ] ) && !( dtd && dtd[ elementName ] ) ) { // Split up inline elements. if ( current.getName() in CKEDITOR.dtd.span ) range.splitElement( current ); // If we're in an empty block which indicate a new paragraph, // simply replace it with the inserting block.(#3664) else if ( range.checkStartOfBlock() && range.checkEndOfBlock() ) { range.setStartBefore( current ); range.collapse( true ); current.remove(); } else { range.splitBlock( enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p', editor.editable() ); } } } // Insert the new node. range.insertNode( element ); // Return true if insertion was successful. return true; }
[ "function", "(", "element", ",", "range", ")", "{", "var", "editor", "=", "this", ".", "editor", ",", "enterMode", "=", "editor", ".", "config", ".", "enterMode", ",", "elementName", "=", "element", ".", "getName", "(", ")", ",", "isBlock", "=", "CKEDITOR", ".", "dtd", ".", "$block", "[", "elementName", "]", ";", "if", "(", "range", ".", "checkReadOnly", "(", ")", ")", "return", "false", ";", "range", ".", "deleteContents", "(", "1", ")", ";", "if", "(", "range", ".", "startContainer", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "range", ".", "startContainer", ".", "is", "(", "{", "tr", ":", "1", ",", "table", ":", "1", ",", "tbody", ":", "1", ",", "thead", ":", "1", ",", "tfoot", ":", "1", "}", ")", ")", "fixTableAfterContentsDeletion", "(", "range", ")", ";", "var", "current", ",", "dtd", ";", "if", "(", "isBlock", ")", "{", "while", "(", "(", "current", "=", "range", ".", "getCommonAncestor", "(", "0", ",", "1", ")", ")", "&&", "(", "dtd", "=", "CKEDITOR", ".", "dtd", "[", "current", ".", "getName", "(", ")", "]", ")", "&&", "!", "(", "dtd", "&&", "dtd", "[", "elementName", "]", ")", ")", "{", "if", "(", "current", ".", "getName", "(", ")", "in", "CKEDITOR", ".", "dtd", ".", "span", ")", "range", ".", "splitElement", "(", "current", ")", ";", "else", "if", "(", "range", ".", "checkStartOfBlock", "(", ")", "&&", "range", ".", "checkEndOfBlock", "(", ")", ")", "{", "range", ".", "setStartBefore", "(", "current", ")", ";", "range", ".", "collapse", "(", "true", ")", ";", "current", ".", "remove", "(", ")", ";", "}", "else", "{", "range", ".", "splitBlock", "(", "enterMode", "==", "CKEDITOR", ".", "ENTER_DIV", "?", "'div'", ":", "'p'", ",", "editor", ".", "editable", "(", ")", ")", ";", "}", "}", "}", "range", ".", "insertNode", "(", "element", ")", ";", "return", "true", ";", "}" ]
Inserts an element into the position in the editor determined by range. @param {CKEDITOR.dom.element} element The element to be inserted. @param {CKEDITOR.dom.range} range The range as a place of insertion. @returns {Boolean} Informs whether insertion was successful.
[ "Inserts", "an", "element", "into", "the", "position", "in", "the", "editor", "determined", "by", "range", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L311-L359
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editable.js
function( element ) { // Prepare for the insertion. For example - focus editor (#11848). beforeInsert( this ); var editor = this.editor, enterMode = editor.activeEnterMode, selection = editor.getSelection(), range = selection.getRanges()[ 0 ], elementName = element.getName(), isBlock = CKEDITOR.dtd.$block[ elementName ]; // Insert element into first range only and ignore the rest (#11183). if ( this.insertElementIntoRange( element, range ) ) { range.moveToPosition( element, CKEDITOR.POSITION_AFTER_END ); // If we're inserting a block element, the new cursor position must be // optimized. (#3100,#5436,#8950) if ( isBlock ) { // Find next, meaningful element. var next = element.getNext( function( node ) { return isNotEmpty( node ) && !isBogus( node ); } ); if ( next && next.type == CKEDITOR.NODE_ELEMENT && next.is( CKEDITOR.dtd.$block ) ) { // If the next one is a text block, move cursor to the start of it's content. if ( next.getDtd()[ '#' ] ) range.moveToElementEditStart( next ); // Otherwise move cursor to the before end of the last element. else range.moveToElementEditEnd( element ); } // Open a new line if the block is inserted at the end of parent. else if ( !next && enterMode != CKEDITOR.ENTER_BR ) { next = range.fixBlock( true, enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' ); range.moveToElementEditStart( next ); } } } // Set up the correct selection. selection.selectRanges( [ range ] ); afterInsert( this ); }
javascript
function( element ) { // Prepare for the insertion. For example - focus editor (#11848). beforeInsert( this ); var editor = this.editor, enterMode = editor.activeEnterMode, selection = editor.getSelection(), range = selection.getRanges()[ 0 ], elementName = element.getName(), isBlock = CKEDITOR.dtd.$block[ elementName ]; // Insert element into first range only and ignore the rest (#11183). if ( this.insertElementIntoRange( element, range ) ) { range.moveToPosition( element, CKEDITOR.POSITION_AFTER_END ); // If we're inserting a block element, the new cursor position must be // optimized. (#3100,#5436,#8950) if ( isBlock ) { // Find next, meaningful element. var next = element.getNext( function( node ) { return isNotEmpty( node ) && !isBogus( node ); } ); if ( next && next.type == CKEDITOR.NODE_ELEMENT && next.is( CKEDITOR.dtd.$block ) ) { // If the next one is a text block, move cursor to the start of it's content. if ( next.getDtd()[ '#' ] ) range.moveToElementEditStart( next ); // Otherwise move cursor to the before end of the last element. else range.moveToElementEditEnd( element ); } // Open a new line if the block is inserted at the end of parent. else if ( !next && enterMode != CKEDITOR.ENTER_BR ) { next = range.fixBlock( true, enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' ); range.moveToElementEditStart( next ); } } } // Set up the correct selection. selection.selectRanges( [ range ] ); afterInsert( this ); }
[ "function", "(", "element", ")", "{", "beforeInsert", "(", "this", ")", ";", "var", "editor", "=", "this", ".", "editor", ",", "enterMode", "=", "editor", ".", "activeEnterMode", ",", "selection", "=", "editor", ".", "getSelection", "(", ")", ",", "range", "=", "selection", ".", "getRanges", "(", ")", "[", "0", "]", ",", "elementName", "=", "element", ".", "getName", "(", ")", ",", "isBlock", "=", "CKEDITOR", ".", "dtd", ".", "$block", "[", "elementName", "]", ";", "if", "(", "this", ".", "insertElementIntoRange", "(", "element", ",", "range", ")", ")", "{", "range", ".", "moveToPosition", "(", "element", ",", "CKEDITOR", ".", "POSITION_AFTER_END", ")", ";", "if", "(", "isBlock", ")", "{", "var", "next", "=", "element", ".", "getNext", "(", "function", "(", "node", ")", "{", "return", "isNotEmpty", "(", "node", ")", "&&", "!", "isBogus", "(", "node", ")", ";", "}", ")", ";", "if", "(", "next", "&&", "next", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "next", ".", "is", "(", "CKEDITOR", ".", "dtd", ".", "$block", ")", ")", "{", "if", "(", "next", ".", "getDtd", "(", ")", "[", "'#'", "]", ")", "range", ".", "moveToElementEditStart", "(", "next", ")", ";", "else", "range", ".", "moveToElementEditEnd", "(", "element", ")", ";", "}", "else", "if", "(", "!", "next", "&&", "enterMode", "!=", "CKEDITOR", ".", "ENTER_BR", ")", "{", "next", "=", "range", ".", "fixBlock", "(", "true", ",", "enterMode", "==", "CKEDITOR", ".", "ENTER_DIV", "?", "'div'", ":", "'p'", ")", ";", "range", ".", "moveToElementEditStart", "(", "next", ")", ";", "}", "}", "}", "selection", ".", "selectRanges", "(", "[", "range", "]", ")", ";", "afterInsert", "(", "this", ")", ";", "}" ]
Inserts an element into the currently selected position in the editor. @param {CKEDITOR.dom.element} element The element to be inserted.
[ "Inserts", "an", "element", "into", "the", "currently", "selected", "position", "in", "the", "editor", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L366-L409
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editable.js
needsBrFiller
function needsBrFiller( selection, path ) { // Fake selection does not need filler, because it is fake. if ( selection.isFake ) return 0; // Ensure bogus br could help to move cursor (out of styles) to the end of block. (#7041) var pathBlock = path.block || path.blockLimit, lastNode = pathBlock && pathBlock.getLast( isNotEmpty ); // Check some specialities of the current path block: // 1. It is really displayed as block; (#7221) // 2. It doesn't end with one inner block; (#7467) // 3. It doesn't have bogus br yet. if ( pathBlock && pathBlock.isBlockBoundary() && !( lastNode && lastNode.type == CKEDITOR.NODE_ELEMENT && lastNode.isBlockBoundary() ) && !pathBlock.is( 'pre' ) && !pathBlock.getBogus() ) return pathBlock; }
javascript
function needsBrFiller( selection, path ) { // Fake selection does not need filler, because it is fake. if ( selection.isFake ) return 0; // Ensure bogus br could help to move cursor (out of styles) to the end of block. (#7041) var pathBlock = path.block || path.blockLimit, lastNode = pathBlock && pathBlock.getLast( isNotEmpty ); // Check some specialities of the current path block: // 1. It is really displayed as block; (#7221) // 2. It doesn't end with one inner block; (#7467) // 3. It doesn't have bogus br yet. if ( pathBlock && pathBlock.isBlockBoundary() && !( lastNode && lastNode.type == CKEDITOR.NODE_ELEMENT && lastNode.isBlockBoundary() ) && !pathBlock.is( 'pre' ) && !pathBlock.getBogus() ) return pathBlock; }
[ "function", "needsBrFiller", "(", "selection", ",", "path", ")", "{", "if", "(", "selection", ".", "isFake", ")", "return", "0", ";", "var", "pathBlock", "=", "path", ".", "block", "||", "path", ".", "blockLimit", ",", "lastNode", "=", "pathBlock", "&&", "pathBlock", ".", "getLast", "(", "isNotEmpty", ")", ";", "if", "(", "pathBlock", "&&", "pathBlock", ".", "isBlockBoundary", "(", ")", "&&", "!", "(", "lastNode", "&&", "lastNode", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "lastNode", ".", "isBlockBoundary", "(", ")", ")", "&&", "!", "pathBlock", ".", "is", "(", "'pre'", ")", "&&", "!", "pathBlock", ".", "getBogus", "(", ")", ")", "return", "pathBlock", ";", "}" ]
Checks whether current selection requires br filler to be appended. @returns Block which needs filler or falsy value.
[ "Checks", "whether", "current", "selection", "requires", "br", "filler", "to", "be", "appended", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L965-L984
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editable.js
prepareRangeToDataInsertion
function prepareRangeToDataInsertion( that ) { var range = that.range, mergeCandidates = that.mergeCandidates, node, marker, path, startPath, endPath, previous, bm; // If range starts in inline element then insert a marker, so empty // inline elements won't be removed while range.deleteContents // and we will be able to move range back into this element. // E.g. 'aa<b>[bb</b>]cc' -> (after deleting) 'aa<b><span/></b>cc' if ( that.type == 'text' && range.shrink( CKEDITOR.SHRINK_ELEMENT, true, false ) ) { marker = CKEDITOR.dom.element.createFromHtml( '<span>&nbsp;</span>', range.document ); range.insertNode( marker ); range.setStartAfter( marker ); } // By using path we can recover in which element was startContainer // before deleting contents. // Start and endPathElements will be used to squash selected blocks, after removing // selection contents. See rule 5. startPath = new CKEDITOR.dom.elementPath( range.startContainer ); that.endPath = endPath = new CKEDITOR.dom.elementPath( range.endContainer ); if ( !range.collapsed ) { // Anticipate the possibly empty block at the end of range after deletion. node = endPath.block || endPath.blockLimit; var ancestor = range.getCommonAncestor(); if ( node && !( node.equals( ancestor ) || node.contains( ancestor ) ) && range.checkEndOfBlock() ) { that.zombies.push( node ); } range.deleteContents(); } // Rule 4. // Move range into the previous block. while ( ( previous = getRangePrevious( range ) ) && checkIfElement( previous ) && previous.isBlockBoundary() && // Check if previousNode was parent of range's startContainer before deleteContents. startPath.contains( previous ) ) range.moveToPosition( previous, CKEDITOR.POSITION_BEFORE_END ); // Rule 5. mergeAncestorElementsOfSelectionEnds( range, that.blockLimit, startPath, endPath ); // Rule 1. if ( marker ) { // If marker was created then move collapsed range into its place. range.setEndBefore( marker ); range.collapse(); marker.remove(); } // Split inline elements so HTML will be inserted with its own styles. path = range.startPath(); if ( ( node = path.contains( isInline, false, 1 ) ) ) { range.splitElement( node ); that.inlineStylesRoot = node; that.inlineStylesPeak = path.lastElement; } // Record inline merging candidates for later cleanup in place. bm = range.createBookmark(); // 1. Inline siblings. node = bm.startNode.getPrevious( isNotEmpty ); node && checkIfElement( node ) && isInline( node ) && mergeCandidates.push( node ); node = bm.startNode.getNext( isNotEmpty ); node && checkIfElement( node ) && isInline( node ) && mergeCandidates.push( node ); // 2. Inline parents. node = bm.startNode; while ( ( node = node.getParent() ) && isInline( node ) ) mergeCandidates.push( node ); range.moveToBookmark( bm ); }
javascript
function prepareRangeToDataInsertion( that ) { var range = that.range, mergeCandidates = that.mergeCandidates, node, marker, path, startPath, endPath, previous, bm; // If range starts in inline element then insert a marker, so empty // inline elements won't be removed while range.deleteContents // and we will be able to move range back into this element. // E.g. 'aa<b>[bb</b>]cc' -> (after deleting) 'aa<b><span/></b>cc' if ( that.type == 'text' && range.shrink( CKEDITOR.SHRINK_ELEMENT, true, false ) ) { marker = CKEDITOR.dom.element.createFromHtml( '<span>&nbsp;</span>', range.document ); range.insertNode( marker ); range.setStartAfter( marker ); } // By using path we can recover in which element was startContainer // before deleting contents. // Start and endPathElements will be used to squash selected blocks, after removing // selection contents. See rule 5. startPath = new CKEDITOR.dom.elementPath( range.startContainer ); that.endPath = endPath = new CKEDITOR.dom.elementPath( range.endContainer ); if ( !range.collapsed ) { // Anticipate the possibly empty block at the end of range after deletion. node = endPath.block || endPath.blockLimit; var ancestor = range.getCommonAncestor(); if ( node && !( node.equals( ancestor ) || node.contains( ancestor ) ) && range.checkEndOfBlock() ) { that.zombies.push( node ); } range.deleteContents(); } // Rule 4. // Move range into the previous block. while ( ( previous = getRangePrevious( range ) ) && checkIfElement( previous ) && previous.isBlockBoundary() && // Check if previousNode was parent of range's startContainer before deleteContents. startPath.contains( previous ) ) range.moveToPosition( previous, CKEDITOR.POSITION_BEFORE_END ); // Rule 5. mergeAncestorElementsOfSelectionEnds( range, that.blockLimit, startPath, endPath ); // Rule 1. if ( marker ) { // If marker was created then move collapsed range into its place. range.setEndBefore( marker ); range.collapse(); marker.remove(); } // Split inline elements so HTML will be inserted with its own styles. path = range.startPath(); if ( ( node = path.contains( isInline, false, 1 ) ) ) { range.splitElement( node ); that.inlineStylesRoot = node; that.inlineStylesPeak = path.lastElement; } // Record inline merging candidates for later cleanup in place. bm = range.createBookmark(); // 1. Inline siblings. node = bm.startNode.getPrevious( isNotEmpty ); node && checkIfElement( node ) && isInline( node ) && mergeCandidates.push( node ); node = bm.startNode.getNext( isNotEmpty ); node && checkIfElement( node ) && isInline( node ) && mergeCandidates.push( node ); // 2. Inline parents. node = bm.startNode; while ( ( node = node.getParent() ) && isInline( node ) ) mergeCandidates.push( node ); range.moveToBookmark( bm ); }
[ "function", "prepareRangeToDataInsertion", "(", "that", ")", "{", "var", "range", "=", "that", ".", "range", ",", "mergeCandidates", "=", "that", ".", "mergeCandidates", ",", "node", ",", "marker", ",", "path", ",", "startPath", ",", "endPath", ",", "previous", ",", "bm", ";", "if", "(", "that", ".", "type", "==", "'text'", "&&", "range", ".", "shrink", "(", "CKEDITOR", ".", "SHRINK_ELEMENT", ",", "true", ",", "false", ")", ")", "{", "marker", "=", "CKEDITOR", ".", "dom", ".", "element", ".", "createFromHtml", "(", "'<span>&nbsp;</span>'", ",", "range", ".", "document", ")", ";", "range", ".", "insertNode", "(", "marker", ")", ";", "range", ".", "setStartAfter", "(", "marker", ")", ";", "}", "startPath", "=", "new", "CKEDITOR", ".", "dom", ".", "elementPath", "(", "range", ".", "startContainer", ")", ";", "that", ".", "endPath", "=", "endPath", "=", "new", "CKEDITOR", ".", "dom", ".", "elementPath", "(", "range", ".", "endContainer", ")", ";", "if", "(", "!", "range", ".", "collapsed", ")", "{", "node", "=", "endPath", ".", "block", "||", "endPath", ".", "blockLimit", ";", "var", "ancestor", "=", "range", ".", "getCommonAncestor", "(", ")", ";", "if", "(", "node", "&&", "!", "(", "node", ".", "equals", "(", "ancestor", ")", "||", "node", ".", "contains", "(", "ancestor", ")", ")", "&&", "range", ".", "checkEndOfBlock", "(", ")", ")", "{", "that", ".", "zombies", ".", "push", "(", "node", ")", ";", "}", "range", ".", "deleteContents", "(", ")", ";", "}", "while", "(", "(", "previous", "=", "getRangePrevious", "(", "range", ")", ")", "&&", "checkIfElement", "(", "previous", ")", "&&", "previous", ".", "isBlockBoundary", "(", ")", "&&", "startPath", ".", "contains", "(", "previous", ")", ")", "range", ".", "moveToPosition", "(", "previous", ",", "CKEDITOR", ".", "POSITION_BEFORE_END", ")", ";", "mergeAncestorElementsOfSelectionEnds", "(", "range", ",", "that", ".", "blockLimit", ",", "startPath", ",", "endPath", ")", ";", "if", "(", "marker", ")", "{", "range", ".", "setEndBefore", "(", "marker", ")", ";", "range", ".", "collapse", "(", ")", ";", "marker", ".", "remove", "(", ")", ";", "}", "path", "=", "range", ".", "startPath", "(", ")", ";", "if", "(", "(", "node", "=", "path", ".", "contains", "(", "isInline", ",", "false", ",", "1", ")", ")", ")", "{", "range", ".", "splitElement", "(", "node", ")", ";", "that", ".", "inlineStylesRoot", "=", "node", ";", "that", ".", "inlineStylesPeak", "=", "path", ".", "lastElement", ";", "}", "bm", "=", "range", ".", "createBookmark", "(", ")", ";", "node", "=", "bm", ".", "startNode", ".", "getPrevious", "(", "isNotEmpty", ")", ";", "node", "&&", "checkIfElement", "(", "node", ")", "&&", "isInline", "(", "node", ")", "&&", "mergeCandidates", ".", "push", "(", "node", ")", ";", "node", "=", "bm", ".", "startNode", ".", "getNext", "(", "isNotEmpty", ")", ";", "node", "&&", "checkIfElement", "(", "node", ")", "&&", "isInline", "(", "node", ")", "&&", "mergeCandidates", ".", "push", "(", "node", ")", ";", "node", "=", "bm", ".", "startNode", ";", "while", "(", "(", "node", "=", "node", ".", "getParent", "(", ")", ")", "&&", "isInline", "(", "node", ")", ")", "mergeCandidates", ".", "push", "(", "node", ")", ";", "range", ".", "moveToBookmark", "(", "bm", ")", ";", "}" ]
Prepare range to its data deletion. Delete its contents. Prepare it to insertion.
[ "Prepare", "range", "to", "its", "data", "deletion", ".", "Delete", "its", "contents", ".", "Prepare", "it", "to", "insertion", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L1259-L1335
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/editable.js
stripBlockTagIfSingleLine
function stripBlockTagIfSingleLine( dataWrapper ) { var block, children; if ( dataWrapper.getChildCount() == 1 && // Only one node bein inserted. checkIfElement( block = dataWrapper.getFirst() ) && // And it's an element. block.is( stripSingleBlockTags ) ) // That's <p> or <div> or header. { // Check children not containing block. children = block.getElementsByTag( '*' ); for ( var i = 0, child, count = children.count(); i < count; i++ ) { child = children.getItem( i ); if ( !child.is( inlineButNotBr ) ) return; } block.moveChildren( block.getParent( 1 ) ); block.remove(); } }
javascript
function stripBlockTagIfSingleLine( dataWrapper ) { var block, children; if ( dataWrapper.getChildCount() == 1 && // Only one node bein inserted. checkIfElement( block = dataWrapper.getFirst() ) && // And it's an element. block.is( stripSingleBlockTags ) ) // That's <p> or <div> or header. { // Check children not containing block. children = block.getElementsByTag( '*' ); for ( var i = 0, child, count = children.count(); i < count; i++ ) { child = children.getItem( i ); if ( !child.is( inlineButNotBr ) ) return; } block.moveChildren( block.getParent( 1 ) ); block.remove(); } }
[ "function", "stripBlockTagIfSingleLine", "(", "dataWrapper", ")", "{", "var", "block", ",", "children", ";", "if", "(", "dataWrapper", ".", "getChildCount", "(", ")", "==", "1", "&&", "checkIfElement", "(", "block", "=", "dataWrapper", ".", "getFirst", "(", ")", ")", "&&", "block", ".", "is", "(", "stripSingleBlockTags", ")", ")", "{", "children", "=", "block", ".", "getElementsByTag", "(", "'*'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "child", ",", "count", "=", "children", ".", "count", "(", ")", ";", "i", "<", "count", ";", "i", "++", ")", "{", "child", "=", "children", ".", "getItem", "(", "i", ")", ";", "if", "(", "!", "child", ".", "is", "(", "inlineButNotBr", ")", ")", "return", ";", "}", "block", ".", "moveChildren", "(", "block", ".", "getParent", "(", "1", ")", ")", ";", "block", ".", "remove", "(", ")", ";", "}", "}" ]
Rule 7.
[ "Rule", "7", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L1829-L1847
train
mnichols/ankh
lib/kernel.js
Kernel
function Kernel(){ this.registrations = new Registrations() this.decorators = new Decorators() this.resolvers = {} this.activators = {} this._inflight = new Inflight(this.decorators) registerSystemServices.call(this) }
javascript
function Kernel(){ this.registrations = new Registrations() this.decorators = new Decorators() this.resolvers = {} this.activators = {} this._inflight = new Inflight(this.decorators) registerSystemServices.call(this) }
[ "function", "Kernel", "(", ")", "{", "this", ".", "registrations", "=", "new", "Registrations", "(", ")", "this", ".", "decorators", "=", "new", "Decorators", "(", ")", "this", ".", "resolvers", "=", "{", "}", "this", ".", "activators", "=", "{", "}", "this", ".", "_inflight", "=", "new", "Inflight", "(", "this", ".", "decorators", ")", "registerSystemServices", ".", "call", "(", "this", ")", "}" ]
The workhorse for resolving dependencies @class Kernel
[ "The", "workhorse", "for", "resolving", "dependencies" ]
b5f6eae24b2dece4025b4f11cea7f1560d3b345f
https://github.com/mnichols/ankh/blob/b5f6eae24b2dece4025b4f11cea7f1560d3b345f/lib/kernel.js#L91-L98
train
vanng822/pstarter
lib/pstarter.js
forkWorkers
function forkWorkers(numWorkers, env) { var workers = []; env = env || {}; for(var i = 0; i < numWorkers; i++) { worker = cluster.fork(env); console.info("Start worker: " + worker.process.pid + ' at ' + (new Date()).toISOString()); workers.push(worker); } return workers; }
javascript
function forkWorkers(numWorkers, env) { var workers = []; env = env || {}; for(var i = 0; i < numWorkers; i++) { worker = cluster.fork(env); console.info("Start worker: " + worker.process.pid + ' at ' + (new Date()).toISOString()); workers.push(worker); } return workers; }
[ "function", "forkWorkers", "(", "numWorkers", ",", "env", ")", "{", "var", "workers", "=", "[", "]", ";", "env", "=", "env", "||", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numWorkers", ";", "i", "++", ")", "{", "worker", "=", "cluster", ".", "fork", "(", "env", ")", ";", "console", ".", "info", "(", "\"Start worker: \"", "+", "worker", ".", "process", ".", "pid", "+", "' at '", "+", "(", "new", "Date", "(", ")", ")", ".", "toISOString", "(", ")", ")", ";", "workers", ".", "push", "(", "worker", ")", ";", "}", "return", "workers", ";", "}" ]
Fork workers.
[ "Fork", "workers", "." ]
2f6bc2eae3906f5270e38a6a2613a472aabf8af6
https://github.com/vanng822/pstarter/blob/2f6bc2eae3906f5270e38a6a2613a472aabf8af6/lib/pstarter.js#L171-L180
train
karlpatrickespiritu/args-checker-js
samples/sample.js
run
function run(booleanOrString, anyDataType, functionOrObject, aNumber, anArray) { /* * if expectations aren't met, args checker will throw appropriate exceptions * notifying the user regarding the errors of the arguments. * */ args.expect(arguments, ['boolean|string', '*', 'function|object', 'number', 'array']); // do something here... console.log("\n\nfunction `run` arguments passed!"); }
javascript
function run(booleanOrString, anyDataType, functionOrObject, aNumber, anArray) { /* * if expectations aren't met, args checker will throw appropriate exceptions * notifying the user regarding the errors of the arguments. * */ args.expect(arguments, ['boolean|string', '*', 'function|object', 'number', 'array']); // do something here... console.log("\n\nfunction `run` arguments passed!"); }
[ "function", "run", "(", "booleanOrString", ",", "anyDataType", ",", "functionOrObject", ",", "aNumber", ",", "anArray", ")", "{", "args", ".", "expect", "(", "arguments", ",", "[", "'boolean|string'", ",", "'*'", ",", "'function|object'", ",", "'number'", ",", "'array'", "]", ")", ";", "console", ".", "log", "(", "\"\\n\\nfunction `run` arguments passed!\"", ")", ";", "}" ]
sample method. @param {boolean/string} @param {mixed/optional} @param {function/object} @param {number}
[ "sample", "method", "." ]
7c46f20ae3e8854ef16c6cd7794f60a6b570ca31
https://github.com/karlpatrickespiritu/args-checker-js/blob/7c46f20ae3e8854ef16c6cd7794f60a6b570ca31/samples/sample.js#L12-L21
train
xStorage/xS-js-libp2p-mplex
src/muxer.js
catchError
function catchError (stream) { return { source: pull( stream.source, pullCatch((err) => { if (err.message === 'Channel destroyed') { return } return false }) ), sink: stream.sink } }
javascript
function catchError (stream) { return { source: pull( stream.source, pullCatch((err) => { if (err.message === 'Channel destroyed') { return } return false }) ), sink: stream.sink } }
[ "function", "catchError", "(", "stream", ")", "{", "return", "{", "source", ":", "pull", "(", "stream", ".", "source", ",", "pullCatch", "(", "(", "err", ")", "=>", "{", "if", "(", "err", ".", "message", "===", "'Channel destroyed'", ")", "{", "return", "}", "return", "false", "}", ")", ")", ",", "sink", ":", "stream", ".", "sink", "}", "}" ]
Catch error makes sure that even though we get the "Channel destroyed" error from when closing streams, that it's not leaking through since it's not really an error for us, channels shoul close cleanly.
[ "Catch", "error", "makes", "sure", "that", "even", "though", "we", "get", "the", "Channel", "destroyed", "error", "from", "when", "closing", "streams", "that", "it", "s", "not", "leaking", "through", "since", "it", "s", "not", "really", "an", "error", "for", "us", "channels", "shoul", "close", "cleanly", "." ]
99616ac226e3f119c1f2b72524e4c7e61a346ba7
https://github.com/xStorage/xS-js-libp2p-mplex/blob/99616ac226e3f119c1f2b72524e4c7e61a346ba7/src/muxer.js#L17-L30
train
yoshuawuyts/dates-of-today
index.js
datesOfToday
function datesOfToday () { const ret = {} ret.year = String(new Date().getFullYear()) ret.month = prefix(String(new Date().getMonth())) ret.day = prefix(String(new Date().getDate())) ret.date = [ret.year, ret.month, ret.day].join('-') return ret }
javascript
function datesOfToday () { const ret = {} ret.year = String(new Date().getFullYear()) ret.month = prefix(String(new Date().getMonth())) ret.day = prefix(String(new Date().getDate())) ret.date = [ret.year, ret.month, ret.day].join('-') return ret }
[ "function", "datesOfToday", "(", ")", "{", "const", "ret", "=", "{", "}", "ret", ".", "year", "=", "String", "(", "new", "Date", "(", ")", ".", "getFullYear", "(", ")", ")", "ret", ".", "month", "=", "prefix", "(", "String", "(", "new", "Date", "(", ")", ".", "getMonth", "(", ")", ")", ")", "ret", ".", "day", "=", "prefix", "(", "String", "(", "new", "Date", "(", ")", ".", "getDate", "(", ")", ")", ")", "ret", ".", "date", "=", "[", "ret", ".", "year", ",", "ret", ".", "month", ",", "ret", ".", "day", "]", ".", "join", "(", "'-'", ")", "return", "ret", "}" ]
get today's date null -> null
[ "get", "today", "s", "date", "null", "-", ">", "null" ]
77a67ac8e443f3c0c01798aba6be11cdccda2c25
https://github.com/yoshuawuyts/dates-of-today/blob/77a67ac8e443f3c0c01798aba6be11cdccda2c25/index.js#L5-L14
train
char1e5/ot-webdriverjs
_base.js
closureRequire
function closureRequire(symbol) { closure.goog.require(symbol); return closure.goog.getObjectByName(symbol); }
javascript
function closureRequire(symbol) { closure.goog.require(symbol); return closure.goog.getObjectByName(symbol); }
[ "function", "closureRequire", "(", "symbol", ")", "{", "closure", ".", "goog", ".", "require", "(", "symbol", ")", ";", "return", "closure", ".", "goog", ".", "getObjectByName", "(", "symbol", ")", ";", "}" ]
Loads a symbol by name from the protected Closure context. @param {string} symbol The symbol to load. @return {?} The loaded symbol, or {@code null} if not found. @throws {Error} If the symbol has not been defined.
[ "Loads", "a", "symbol", "by", "name", "from", "the", "protected", "Closure", "context", "." ]
5fc8cabcb481602673f1d47cdf544d681c35f784
https://github.com/char1e5/ot-webdriverjs/blob/5fc8cabcb481602673f1d47cdf544d681c35f784/_base.js#L125-L128
train
7ictor/gulp-couchapp
index.js
buildURL
function buildURL(dbName, opts) { var authentication opts.scheme = opts.scheme || 'http' opts.host = opts.host || '127.0.0.1' opts.port = opts.port || '5984' if (has(opts, 'auth')) { if (typeof opts.auth === 'object') { authentication = opts.auth.username + ':' + opts.auth.password + '@' } } return opts.scheme + '://' + authentication + opts.host + ':' + opts.port + '/' + dbName }
javascript
function buildURL(dbName, opts) { var authentication opts.scheme = opts.scheme || 'http' opts.host = opts.host || '127.0.0.1' opts.port = opts.port || '5984' if (has(opts, 'auth')) { if (typeof opts.auth === 'object') { authentication = opts.auth.username + ':' + opts.auth.password + '@' } } return opts.scheme + '://' + authentication + opts.host + ':' + opts.port + '/' + dbName }
[ "function", "buildURL", "(", "dbName", ",", "opts", ")", "{", "var", "authentication", "opts", ".", "scheme", "=", "opts", ".", "scheme", "||", "'http'", "opts", ".", "host", "=", "opts", ".", "host", "||", "'127.0.0.1'", "opts", ".", "port", "=", "opts", ".", "port", "||", "'5984'", "if", "(", "has", "(", "opts", ",", "'auth'", ")", ")", "{", "if", "(", "typeof", "opts", ".", "auth", "===", "'object'", ")", "{", "authentication", "=", "opts", ".", "auth", ".", "username", "+", "':'", "+", "opts", ".", "auth", ".", "password", "+", "'@'", "}", "}", "return", "opts", ".", "scheme", "+", "'://'", "+", "authentication", "+", "opts", ".", "host", "+", "':'", "+", "opts", ".", "port", "+", "'/'", "+", "dbName", "}" ]
Build the URL to push CouchApp. @param {String} dbName @param {Object} opts @return {String}
[ "Build", "the", "URL", "to", "push", "CouchApp", "." ]
01269cdce8f176fb71212f8e475afc44842b2cc1
https://github.com/7ictor/gulp-couchapp/blob/01269cdce8f176fb71212f8e475afc44842b2cc1/index.js#L31-L44
train
7ictor/gulp-couchapp
index.js
pushCouchapp
function pushCouchapp(dbName, opts) { opts = opts || {} if (!dbName && typeof dbName !== 'string') { throw new PluginError(PLUGIN_NAME, 'Missing database name.'); } return through.obj(function (file, enc, cb) { var ddocObj = require(file.path) var url = /^https?:\/\//.test(dbName) ? dbName : buildURL(dbName, opts); if (file.isNull()) { return cb(null, file) } if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported.')) return cb(null, file) } if (path.extname(file.path) !== '.js') { this.emit('error', new PluginError(PLUGIN_NAME, 'File extension not supported.')) return cb(null, file) } if (has(opts, 'attachments')) { var attachmentsPath = path.join(process.cwd(), path.normalize(opts.attachments)) couchapp.loadAttachments(ddocObj, attachmentsPath) } couchapp.createApp(ddocObj, url, function (app) { app.push(function () { gutil.log(PLUGIN_NAME, 'Couchapp pushed!') return cb(null, file) }) }) }) }
javascript
function pushCouchapp(dbName, opts) { opts = opts || {} if (!dbName && typeof dbName !== 'string') { throw new PluginError(PLUGIN_NAME, 'Missing database name.'); } return through.obj(function (file, enc, cb) { var ddocObj = require(file.path) var url = /^https?:\/\//.test(dbName) ? dbName : buildURL(dbName, opts); if (file.isNull()) { return cb(null, file) } if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported.')) return cb(null, file) } if (path.extname(file.path) !== '.js') { this.emit('error', new PluginError(PLUGIN_NAME, 'File extension not supported.')) return cb(null, file) } if (has(opts, 'attachments')) { var attachmentsPath = path.join(process.cwd(), path.normalize(opts.attachments)) couchapp.loadAttachments(ddocObj, attachmentsPath) } couchapp.createApp(ddocObj, url, function (app) { app.push(function () { gutil.log(PLUGIN_NAME, 'Couchapp pushed!') return cb(null, file) }) }) }) }
[ "function", "pushCouchapp", "(", "dbName", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", "if", "(", "!", "dbName", "&&", "typeof", "dbName", "!==", "'string'", ")", "{", "throw", "new", "PluginError", "(", "PLUGIN_NAME", ",", "'Missing database name.'", ")", ";", "}", "return", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "var", "ddocObj", "=", "require", "(", "file", ".", "path", ")", "var", "url", "=", "/", "^https?:\\/\\/", "/", ".", "test", "(", "dbName", ")", "?", "dbName", ":", "buildURL", "(", "dbName", ",", "opts", ")", ";", "if", "(", "file", ".", "isNull", "(", ")", ")", "{", "return", "cb", "(", "null", ",", "file", ")", "}", "if", "(", "file", ".", "isStream", "(", ")", ")", "{", "this", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "PLUGIN_NAME", ",", "'Streaming not supported.'", ")", ")", "return", "cb", "(", "null", ",", "file", ")", "}", "if", "(", "path", ".", "extname", "(", "file", ".", "path", ")", "!==", "'.js'", ")", "{", "this", ".", "emit", "(", "'error'", ",", "new", "PluginError", "(", "PLUGIN_NAME", ",", "'File extension not supported.'", ")", ")", "return", "cb", "(", "null", ",", "file", ")", "}", "if", "(", "has", "(", "opts", ",", "'attachments'", ")", ")", "{", "var", "attachmentsPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "path", ".", "normalize", "(", "opts", ".", "attachments", ")", ")", "couchapp", ".", "loadAttachments", "(", "ddocObj", ",", "attachmentsPath", ")", "}", "couchapp", ".", "createApp", "(", "ddocObj", ",", "url", ",", "function", "(", "app", ")", "{", "app", ".", "push", "(", "function", "(", ")", "{", "gutil", ".", "log", "(", "PLUGIN_NAME", ",", "'Couchapp pushed!'", ")", "return", "cb", "(", "null", ",", "file", ")", "}", ")", "}", ")", "}", ")", "}" ]
Push a CouchApp to a CouchDB database. @param {String} db @param {Object} opts @return {Stream}
[ "Push", "a", "CouchApp", "to", "a", "CouchDB", "database", "." ]
01269cdce8f176fb71212f8e475afc44842b2cc1
https://github.com/7ictor/gulp-couchapp/blob/01269cdce8f176fb71212f8e475afc44842b2cc1/index.js#L53-L90
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/colordialog/dialogs/colordialog.js
whiteOrBlack
function whiteOrBlack( color ) { color = color.replace( /^#/, '' ); for ( var i = 0, rgb = []; i <= 2; i++ ) rgb[ i ] = parseInt( color.substr( i * 2, 2 ), 16 ); var luma = ( 0.2126 * rgb[ 0 ] ) + ( 0.7152 * rgb[ 1 ] ) + ( 0.0722 * rgb[ 2 ] ); return '#' + ( luma >= 165 ? '000' : 'fff' ); }
javascript
function whiteOrBlack( color ) { color = color.replace( /^#/, '' ); for ( var i = 0, rgb = []; i <= 2; i++ ) rgb[ i ] = parseInt( color.substr( i * 2, 2 ), 16 ); var luma = ( 0.2126 * rgb[ 0 ] ) + ( 0.7152 * rgb[ 1 ] ) + ( 0.0722 * rgb[ 2 ] ); return '#' + ( luma >= 165 ? '000' : 'fff' ); }
[ "function", "whiteOrBlack", "(", "color", ")", "{", "color", "=", "color", ".", "replace", "(", "/", "^#", "/", ",", "''", ")", ";", "for", "(", "var", "i", "=", "0", ",", "rgb", "=", "[", "]", ";", "i", "<=", "2", ";", "i", "++", ")", "rgb", "[", "i", "]", "=", "parseInt", "(", "color", ".", "substr", "(", "i", "*", "2", ",", "2", ")", ",", "16", ")", ";", "var", "luma", "=", "(", "0.2126", "*", "rgb", "[", "0", "]", ")", "+", "(", "0.7152", "*", "rgb", "[", "1", "]", ")", "+", "(", "0.0722", "*", "rgb", "[", "2", "]", ")", ";", "return", "'#'", "+", "(", "luma", ">=", "165", "?", "'000'", ":", "'fff'", ")", ";", "}" ]
Basing black-white decision off of luma scheme using the Rec. 709 version
[ "Basing", "black", "-", "white", "decision", "off", "of", "luma", "scheme", "using", "the", "Rec", ".", "709", "version" ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/colordialog/dialogs/colordialog.js#L41-L47
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/colordialog/dialogs/colordialog.js
updateHighlight
function updateHighlight( event ) { // Convert to event. !event.name && ( event = new CKEDITOR.event( event ) ); var isFocus = !( /mouse/ ).test( event.name ), target = event.data.getTarget(), color; if ( target.getName() == 'td' && ( color = target.getChild( 0 ).getHtml() ) ) { removeHighlight( event ); isFocus ? focused = target : hovered = target; // Apply outline style to show focus. if ( isFocus ) { target.setStyle( 'border-color', whiteOrBlack( color ) ); target.setStyle( 'border-style', 'dotted' ); } $doc.getById( hicolorId ).setStyle( 'background-color', color ); $doc.getById( hicolorTextId ).setHtml( color ); } }
javascript
function updateHighlight( event ) { // Convert to event. !event.name && ( event = new CKEDITOR.event( event ) ); var isFocus = !( /mouse/ ).test( event.name ), target = event.data.getTarget(), color; if ( target.getName() == 'td' && ( color = target.getChild( 0 ).getHtml() ) ) { removeHighlight( event ); isFocus ? focused = target : hovered = target; // Apply outline style to show focus. if ( isFocus ) { target.setStyle( 'border-color', whiteOrBlack( color ) ); target.setStyle( 'border-style', 'dotted' ); } $doc.getById( hicolorId ).setStyle( 'background-color', color ); $doc.getById( hicolorTextId ).setHtml( color ); } }
[ "function", "updateHighlight", "(", "event", ")", "{", "!", "event", ".", "name", "&&", "(", "event", "=", "new", "CKEDITOR", ".", "event", "(", "event", ")", ")", ";", "var", "isFocus", "=", "!", "(", "/", "mouse", "/", ")", ".", "test", "(", "event", ".", "name", ")", ",", "target", "=", "event", ".", "data", ".", "getTarget", "(", ")", ",", "color", ";", "if", "(", "target", ".", "getName", "(", ")", "==", "'td'", "&&", "(", "color", "=", "target", ".", "getChild", "(", "0", ")", ".", "getHtml", "(", ")", ")", ")", "{", "removeHighlight", "(", "event", ")", ";", "isFocus", "?", "focused", "=", "target", ":", "hovered", "=", "target", ";", "if", "(", "isFocus", ")", "{", "target", ".", "setStyle", "(", "'border-color'", ",", "whiteOrBlack", "(", "color", ")", ")", ";", "target", ".", "setStyle", "(", "'border-style'", ",", "'dotted'", ")", ";", "}", "$doc", ".", "getById", "(", "hicolorId", ")", ".", "setStyle", "(", "'background-color'", ",", "color", ")", ";", "$doc", ".", "getById", "(", "hicolorTextId", ")", ".", "setHtml", "(", "color", ")", ";", "}", "}" ]
Apply highlight style.
[ "Apply", "highlight", "style", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/colordialog/dialogs/colordialog.js#L53-L75
train
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/colordialog/dialogs/colordialog.js
removeHighlight
function removeHighlight( event ) { var isFocus = !( /mouse/ ).test( event.name ), target = isFocus && focused; if ( target ) { var color = target.getChild( 0 ).getHtml(); target.setStyle( 'border-color', color ); target.setStyle( 'border-style', 'solid' ); } if ( !( focused || hovered ) ) { $doc.getById( hicolorId ).removeStyle( 'background-color' ); $doc.getById( hicolorTextId ).setHtml( '&nbsp;' ); } }
javascript
function removeHighlight( event ) { var isFocus = !( /mouse/ ).test( event.name ), target = isFocus && focused; if ( target ) { var color = target.getChild( 0 ).getHtml(); target.setStyle( 'border-color', color ); target.setStyle( 'border-style', 'solid' ); } if ( !( focused || hovered ) ) { $doc.getById( hicolorId ).removeStyle( 'background-color' ); $doc.getById( hicolorTextId ).setHtml( '&nbsp;' ); } }
[ "function", "removeHighlight", "(", "event", ")", "{", "var", "isFocus", "=", "!", "(", "/", "mouse", "/", ")", ".", "test", "(", "event", ".", "name", ")", ",", "target", "=", "isFocus", "&&", "focused", ";", "if", "(", "target", ")", "{", "var", "color", "=", "target", ".", "getChild", "(", "0", ")", ".", "getHtml", "(", ")", ";", "target", ".", "setStyle", "(", "'border-color'", ",", "color", ")", ";", "target", ".", "setStyle", "(", "'border-style'", ",", "'solid'", ")", ";", "}", "if", "(", "!", "(", "focused", "||", "hovered", ")", ")", "{", "$doc", ".", "getById", "(", "hicolorId", ")", ".", "removeStyle", "(", "'background-color'", ")", ";", "$doc", ".", "getById", "(", "hicolorTextId", ")", ".", "setHtml", "(", "'&nbsp;'", ")", ";", "}", "}" ]
Remove previously focused style.
[ "Remove", "previously", "focused", "style", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/colordialog/dialogs/colordialog.js#L87-L101
train
redisjs/jsr-validate
lib/validators/type.js
num
function num(type, value) { var val; if(type === NUMERIC.INTEGER) { val = utils.strtoint(value); if(isNaN(val)) throw IntegerRange; }else{ val = utils.strtofloat(value); if(isNaN(val)) throw InvalidFloat; } return val; }
javascript
function num(type, value) { var val; if(type === NUMERIC.INTEGER) { val = utils.strtoint(value); if(isNaN(val)) throw IntegerRange; }else{ val = utils.strtofloat(value); if(isNaN(val)) throw InvalidFloat; } return val; }
[ "function", "num", "(", "type", ",", "value", ")", "{", "var", "val", ";", "if", "(", "type", "===", "NUMERIC", ".", "INTEGER", ")", "{", "val", "=", "utils", ".", "strtoint", "(", "value", ")", ";", "if", "(", "isNaN", "(", "val", ")", ")", "throw", "IntegerRange", ";", "}", "else", "{", "val", "=", "utils", ".", "strtofloat", "(", "value", ")", ";", "if", "(", "isNaN", "(", "val", ")", ")", "throw", "InvalidFloat", ";", "}", "return", "val", ";", "}" ]
Helper for testing numeric types. Throws an error if the coerced type is NaN. @param type The type constant. @param value The value to test. @return The coerced value.
[ "Helper", "for", "testing", "numeric", "types", "." ]
2e0dddafb32c019ef9293a35b96cdd78dd8e4ae5
https://github.com/redisjs/jsr-validate/blob/2e0dddafb32c019ef9293a35b96cdd78dd8e4ae5/lib/validators/type.js#L21-L31
train
redisjs/jsr-validate
lib/validators/type.js
type
function type(cmd, args, info) { // definition provided by earlier command validation /* istanbul ignore next: currently subcommands do not type validate */ var def = info.command.sub ? info.command.sub.def : info.command.def // expected type of the value based on the supplied command , expected = TYPES[cmd] , numeric = NUMERIC[cmd] , margs = args.slice(0) // extract keys from the args list , keys = def.getKeys(args) // build up value list, when validation // passes this can be re-used by calling code , values = {} , i, k, v, nv; // numeric argument validation if(numeric && numeric.pos) { numeric.pos.forEach(function(pos) { //console.error('got value for arg at pos %s (%s)', pos, args[pos]); var val = num(numeric.type, args[pos]); margs[pos] = val; args[pos] = val; }) } // command does not operate on a type or has no keys // nothing to be done. first part of the conditional // should never match, if it does it represents a misconfiguration // of the constants, however we need to ensure we have some keys // to iterate over if(!keys || !TYPES[cmd]) return null; for(i = 0;i < keys.length;i++) { k = keys[i]; v = nv = info.db.getKey(k, {}); //console.dir(v); // numeric value validation if(numeric) { if(expected === TYPE_NAMES.STRING && numeric.value) { // update the value, allows // calling code to skip coercion // on successful validation v = num(numeric.type, v); // should have a hash // need to dig deeper to get the real // value for complex types }else if(v && expected === TYPE_NAMES.HASH && numeric.value) { nv = v.getValues(cmd, args, def); //console.error('got validate value: %s', nv); num(numeric.type, nv); } } // got an existing value if(v !== undefined) { //console.dir(v); switch(expected) { case TYPE_NAMES.STRING: // the store is allowed to save string values as // numbers and coerce to strings on get() if(typeof v !== 'string' && typeof v !== 'number' && !(v instanceof Buffer)) { throw WrongType; } break; case TYPE_NAMES.HASH: case TYPE_NAMES.LIST: case TYPE_NAMES.SET: case TYPE_NAMES.ZSET: if(v.rtype !== expected) throw WrongType; break; } } // always store regardless of whether a value is defined values[k] = v; } return {keys: keys, values: values, args: margs}; }
javascript
function type(cmd, args, info) { // definition provided by earlier command validation /* istanbul ignore next: currently subcommands do not type validate */ var def = info.command.sub ? info.command.sub.def : info.command.def // expected type of the value based on the supplied command , expected = TYPES[cmd] , numeric = NUMERIC[cmd] , margs = args.slice(0) // extract keys from the args list , keys = def.getKeys(args) // build up value list, when validation // passes this can be re-used by calling code , values = {} , i, k, v, nv; // numeric argument validation if(numeric && numeric.pos) { numeric.pos.forEach(function(pos) { //console.error('got value for arg at pos %s (%s)', pos, args[pos]); var val = num(numeric.type, args[pos]); margs[pos] = val; args[pos] = val; }) } // command does not operate on a type or has no keys // nothing to be done. first part of the conditional // should never match, if it does it represents a misconfiguration // of the constants, however we need to ensure we have some keys // to iterate over if(!keys || !TYPES[cmd]) return null; for(i = 0;i < keys.length;i++) { k = keys[i]; v = nv = info.db.getKey(k, {}); //console.dir(v); // numeric value validation if(numeric) { if(expected === TYPE_NAMES.STRING && numeric.value) { // update the value, allows // calling code to skip coercion // on successful validation v = num(numeric.type, v); // should have a hash // need to dig deeper to get the real // value for complex types }else if(v && expected === TYPE_NAMES.HASH && numeric.value) { nv = v.getValues(cmd, args, def); //console.error('got validate value: %s', nv); num(numeric.type, nv); } } // got an existing value if(v !== undefined) { //console.dir(v); switch(expected) { case TYPE_NAMES.STRING: // the store is allowed to save string values as // numbers and coerce to strings on get() if(typeof v !== 'string' && typeof v !== 'number' && !(v instanceof Buffer)) { throw WrongType; } break; case TYPE_NAMES.HASH: case TYPE_NAMES.LIST: case TYPE_NAMES.SET: case TYPE_NAMES.ZSET: if(v.rtype !== expected) throw WrongType; break; } } // always store regardless of whether a value is defined values[k] = v; } return {keys: keys, values: values, args: margs}; }
[ "function", "type", "(", "cmd", ",", "args", ",", "info", ")", "{", "var", "def", "=", "info", ".", "command", ".", "sub", "?", "info", ".", "command", ".", "sub", ".", "def", ":", "info", ".", "command", ".", "def", ",", "expected", "=", "TYPES", "[", "cmd", "]", ",", "numeric", "=", "NUMERIC", "[", "cmd", "]", ",", "margs", "=", "args", ".", "slice", "(", "0", ")", ",", "keys", "=", "def", ".", "getKeys", "(", "args", ")", ",", "values", "=", "{", "}", ",", "i", ",", "k", ",", "v", ",", "nv", ";", "if", "(", "numeric", "&&", "numeric", ".", "pos", ")", "{", "numeric", ".", "pos", ".", "forEach", "(", "function", "(", "pos", ")", "{", "var", "val", "=", "num", "(", "numeric", ".", "type", ",", "args", "[", "pos", "]", ")", ";", "margs", "[", "pos", "]", "=", "val", ";", "args", "[", "pos", "]", "=", "val", ";", "}", ")", "}", "if", "(", "!", "keys", "||", "!", "TYPES", "[", "cmd", "]", ")", "return", "null", ";", "for", "(", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "k", "=", "keys", "[", "i", "]", ";", "v", "=", "nv", "=", "info", ".", "db", ".", "getKey", "(", "k", ",", "{", "}", ")", ";", "if", "(", "numeric", ")", "{", "if", "(", "expected", "===", "TYPE_NAMES", ".", "STRING", "&&", "numeric", ".", "value", ")", "{", "v", "=", "num", "(", "numeric", ".", "type", ",", "v", ")", ";", "}", "else", "if", "(", "v", "&&", "expected", "===", "TYPE_NAMES", ".", "HASH", "&&", "numeric", ".", "value", ")", "{", "nv", "=", "v", ".", "getValues", "(", "cmd", ",", "args", ",", "def", ")", ";", "num", "(", "numeric", ".", "type", ",", "nv", ")", ";", "}", "}", "if", "(", "v", "!==", "undefined", ")", "{", "switch", "(", "expected", ")", "{", "case", "TYPE_NAMES", ".", "STRING", ":", "if", "(", "typeof", "v", "!==", "'string'", "&&", "typeof", "v", "!==", "'number'", "&&", "!", "(", "v", "instanceof", "Buffer", ")", ")", "{", "throw", "WrongType", ";", "}", "break", ";", "case", "TYPE_NAMES", ".", "HASH", ":", "case", "TYPE_NAMES", ".", "LIST", ":", "case", "TYPE_NAMES", ".", "SET", ":", "case", "TYPE_NAMES", ".", "ZSET", ":", "if", "(", "v", ".", "rtype", "!==", "expected", ")", "throw", "WrongType", ";", "break", ";", "}", "}", "values", "[", "k", "]", "=", "v", ";", "}", "return", "{", "keys", ":", "keys", ",", "values", ":", "values", ",", "args", ":", "margs", "}", ";", "}" ]
Validate whether a command is operating on the correct type. @param cmd The command name (lowercase). @param args The command arguments, must be an array. @param info The server information.
[ "Validate", "whether", "a", "command", "is", "operating", "on", "the", "correct", "type", "." ]
2e0dddafb32c019ef9293a35b96cdd78dd8e4ae5
https://github.com/redisjs/jsr-validate/blob/2e0dddafb32c019ef9293a35b96cdd78dd8e4ae5/lib/validators/type.js#L40-L126
train
oskarhagberg/gbgcity
lib/airquality.js
getMeasurements
function getMeasurements(startDate, endDate, params, callback) { params = params || {}; if(!startDate && !endDate) { startDate = new Date(); startDate.setHours(startDate.getHours() - 24); startDate = formatDate(startDate); endDate = new Date(); endDate = formatDate(endDate); } params.startdate = startDate; params.endDate = endDate; core.callApi('/AirQualityService/v1.0/Measurements', params, callback); }
javascript
function getMeasurements(startDate, endDate, params, callback) { params = params || {}; if(!startDate && !endDate) { startDate = new Date(); startDate.setHours(startDate.getHours() - 24); startDate = formatDate(startDate); endDate = new Date(); endDate = formatDate(endDate); } params.startdate = startDate; params.endDate = endDate; core.callApi('/AirQualityService/v1.0/Measurements', params, callback); }
[ "function", "getMeasurements", "(", "startDate", ",", "endDate", ",", "params", ",", "callback", ")", "{", "params", "=", "params", "||", "{", "}", ";", "if", "(", "!", "startDate", "&&", "!", "endDate", ")", "{", "startDate", "=", "new", "Date", "(", ")", ";", "startDate", ".", "setHours", "(", "startDate", ".", "getHours", "(", ")", "-", "24", ")", ";", "startDate", "=", "formatDate", "(", "startDate", ")", ";", "endDate", "=", "new", "Date", "(", ")", ";", "endDate", "=", "formatDate", "(", "endDate", ")", ";", "}", "params", ".", "startdate", "=", "startDate", ";", "params", ".", "endDate", "=", "endDate", ";", "core", ".", "callApi", "(", "'/AirQualityService/v1.0/Measurements'", ",", "params", ",", "callback", ")", ";", "}" ]
Returns a list of measurements @memberof module:gbgcity/AirQuality @param {Date} startDate From when to get measurements @param {Date} endDate To when to get measurements @param {Object} [params] An object containing additional parameters. @param {Function} callback The function to call with results, function({Error} error, {Object} results)/ @see http://data.goteborg.se/AirQualityService/v1.0/help/operations/GetLatestMeasurements
[ "Returns", "a", "list", "of", "measurements" ]
d2de903b2fba83cc953ae218905380fef080cb2d
https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/airquality.js#L37-L49
train
cliffano/eggtart
lib/validator.js
validate
function validate(rules, args, cb) { try { _known(rules, args); _required(rules, args); Object.keys(args).forEach(function (arg) { var value = args[arg], ruleSet = rules[arg]; try { ruleSet.forEach(function (rule) { if (rule !== 'required') { exports.checks[rule](value || ''); } }); } catch (e) { throw new Error(util.format( 'Validation error - arg: %s, value: %s, desc: %s', arg, value, e.message)); } }); cb(); } catch (e) { cb(e); } }
javascript
function validate(rules, args, cb) { try { _known(rules, args); _required(rules, args); Object.keys(args).forEach(function (arg) { var value = args[arg], ruleSet = rules[arg]; try { ruleSet.forEach(function (rule) { if (rule !== 'required') { exports.checks[rule](value || ''); } }); } catch (e) { throw new Error(util.format( 'Validation error - arg: %s, value: %s, desc: %s', arg, value, e.message)); } }); cb(); } catch (e) { cb(e); } }
[ "function", "validate", "(", "rules", ",", "args", ",", "cb", ")", "{", "try", "{", "_known", "(", "rules", ",", "args", ")", ";", "_required", "(", "rules", ",", "args", ")", ";", "Object", ".", "keys", "(", "args", ")", ".", "forEach", "(", "function", "(", "arg", ")", "{", "var", "value", "=", "args", "[", "arg", "]", ",", "ruleSet", "=", "rules", "[", "arg", "]", ";", "try", "{", "ruleSet", ".", "forEach", "(", "function", "(", "rule", ")", "{", "if", "(", "rule", "!==", "'required'", ")", "{", "exports", ".", "checks", "[", "rule", "]", "(", "value", "||", "''", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'Validation error - arg: %s, value: %s, desc: %s'", ",", "arg", ",", "value", ",", "e", ".", "message", ")", ")", ";", "}", "}", ")", ";", "cb", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "cb", "(", "e", ")", ";", "}", "}" ]
Validate arguments against a set of rules. @param {Object} rules: argument name-ruleset pair, ruleset is an array of check functions @param {Object} args: argument name-value pair @param {Function} cb: standard cb(err, result) callback
[ "Validate", "arguments", "against", "a", "set", "of", "rules", "." ]
12b33ea12c5f5bdcdf8559260e46bc5b5137526f
https://github.com/cliffano/eggtart/blob/12b33ea12c5f5bdcdf8559260e46bc5b5137526f/lib/validator.js#L11-L37
train
yoshuawuyts/object-join
index.js
clone
function clone(obj1, obj2, index) { index = index || 0; for (var i in obj2) { if ('object' == typeof i) obj1[i] = recursiveMerge(obj1[i], obj2[i], index++); else obj1[i] = obj2[i]; } return obj1; }
javascript
function clone(obj1, obj2, index) { index = index || 0; for (var i in obj2) { if ('object' == typeof i) obj1[i] = recursiveMerge(obj1[i], obj2[i], index++); else obj1[i] = obj2[i]; } return obj1; }
[ "function", "clone", "(", "obj1", ",", "obj2", ",", "index", ")", "{", "index", "=", "index", "||", "0", ";", "for", "(", "var", "i", "in", "obj2", ")", "{", "if", "(", "'object'", "==", "typeof", "i", ")", "obj1", "[", "i", "]", "=", "recursiveMerge", "(", "obj1", "[", "i", "]", ",", "obj2", "[", "i", "]", ",", "index", "++", ")", ";", "else", "obj1", "[", "i", "]", "=", "obj2", "[", "i", "]", ";", "}", "return", "obj1", ";", "}" ]
Merge the properties from one object to another object. If duplicate keys exist on the same level, obj2 takes presedence over obj1. @param {Object} obj1 @param {Object} obj2 @param {Number} index @return {Object} @api private
[ "Merge", "the", "properties", "from", "one", "object", "to", "another", "object", ".", "If", "duplicate", "keys", "exist", "on", "the", "same", "level", "obj2", "takes", "presedence", "over", "obj1", "." ]
74cb333080c687e233757f67d930135ae8c809a3
https://github.com/yoshuawuyts/object-join/blob/74cb333080c687e233757f67d930135ae8c809a3/index.js#L35-L42
train
papandreou/node-fsplusgit
lib/FsPlusGit.js
addContentsDirectoryToReaddirResultAndCallOriginalCallback
function addContentsDirectoryToReaddirResultAndCallOriginalCallback(err, entryNames) { if (!err && Array.isArray(entryNames)) { entryNames = ['gitFakeFs'].concat(entryNames); } cb.call(this, err, entryNames); }
javascript
function addContentsDirectoryToReaddirResultAndCallOriginalCallback(err, entryNames) { if (!err && Array.isArray(entryNames)) { entryNames = ['gitFakeFs'].concat(entryNames); } cb.call(this, err, entryNames); }
[ "function", "addContentsDirectoryToReaddirResultAndCallOriginalCallback", "(", "err", ",", "entryNames", ")", "{", "if", "(", "!", "err", "&&", "Array", ".", "isArray", "(", "entryNames", ")", ")", "{", "entryNames", "=", "[", "'gitFakeFs'", "]", ".", "concat", "(", "entryNames", ")", ";", "}", "cb", ".", "call", "(", "this", ",", "err", ",", "entryNames", ")", ";", "}" ]
Intercept the result and add the 'gitFakeFs' dir
[ "Intercept", "the", "result", "and", "add", "the", "gitFakeFs", "dir" ]
3445dcdb4c92f267acf009bf7c4156e014788cfb
https://github.com/papandreou/node-fsplusgit/blob/3445dcdb4c92f267acf009bf7c4156e014788cfb/lib/FsPlusGit.js#L121-L126
train
kallaspriit/html-literal
build/src/index.js
html
function html(template) { var expressions = []; for (var _i = 1; _i < arguments.length; _i++) { expressions[_i - 1] = arguments[_i]; } var result = ""; var i = 0; // resolve each expression and build the result string for (var _a = 0, template_1 = template; _a < template_1.length; _a++) { var part = template_1[_a]; var expression = expressions[i++ - 1]; // this might be an array var resolvedExpression = resolveExpression(expression); result += "" + resolvedExpression + part; } // strip indentation and trim the result return strip_indent_1.default(result).trim(); }
javascript
function html(template) { var expressions = []; for (var _i = 1; _i < arguments.length; _i++) { expressions[_i - 1] = arguments[_i]; } var result = ""; var i = 0; // resolve each expression and build the result string for (var _a = 0, template_1 = template; _a < template_1.length; _a++) { var part = template_1[_a]; var expression = expressions[i++ - 1]; // this might be an array var resolvedExpression = resolveExpression(expression); result += "" + resolvedExpression + part; } // strip indentation and trim the result return strip_indent_1.default(result).trim(); }
[ "function", "html", "(", "template", ")", "{", "var", "expressions", "=", "[", "]", ";", "for", "(", "var", "_i", "=", "1", ";", "_i", "<", "arguments", ".", "length", ";", "_i", "++", ")", "{", "expressions", "[", "_i", "-", "1", "]", "=", "arguments", "[", "_i", "]", ";", "}", "var", "result", "=", "\"\"", ";", "var", "i", "=", "0", ";", "for", "(", "var", "_a", "=", "0", ",", "template_1", "=", "template", ";", "_a", "<", "template_1", ".", "length", ";", "_a", "++", ")", "{", "var", "part", "=", "template_1", "[", "_a", "]", ";", "var", "expression", "=", "expressions", "[", "i", "++", "-", "1", "]", ";", "var", "resolvedExpression", "=", "resolveExpression", "(", "expression", ")", ";", "result", "+=", "\"\"", "+", "resolvedExpression", "+", "part", ";", "}", "return", "strip_indent_1", ".", "default", "(", "result", ")", ".", "trim", "(", ")", ";", "}" ]
html tag function, accepts simple values, arrays, promises
[ "html", "tag", "function", "accepts", "simple", "values", "arrays", "promises" ]
8965f39dfdc5a63a25a20f2a8cbc1dbfc9ecfdc3
https://github.com/kallaspriit/html-literal/blob/8965f39dfdc5a63a25a20f2a8cbc1dbfc9ecfdc3/build/src/index.js#L9-L25
train
posttool/currentcms
lib/public/js/lib/ck/plugins/table/dialogs/table.js
validatorNum
function validatorNum( msg ) { return function() { var value = this.getValue(), pass = !!( CKEDITOR.dialog.validate.integer()( value ) && value > 0 ); if ( !pass ) { alert( msg ); this.select(); } return pass; }; }
javascript
function validatorNum( msg ) { return function() { var value = this.getValue(), pass = !!( CKEDITOR.dialog.validate.integer()( value ) && value > 0 ); if ( !pass ) { alert( msg ); this.select(); } return pass; }; }
[ "function", "validatorNum", "(", "msg", ")", "{", "return", "function", "(", ")", "{", "var", "value", "=", "this", ".", "getValue", "(", ")", ",", "pass", "=", "!", "!", "(", "CKEDITOR", ".", "dialog", ".", "validate", ".", "integer", "(", ")", "(", "value", ")", "&&", "value", ">", "0", ")", ";", "if", "(", "!", "pass", ")", "{", "alert", "(", "msg", ")", ";", "this", ".", "select", "(", ")", ";", "}", "return", "pass", ";", "}", ";", "}" ]
Whole-positive-integer validator.
[ "Whole", "-", "positive", "-", "integer", "validator", "." ]
9afc9f907bad3b018d961af66c3abb33cd82b051
https://github.com/posttool/currentcms/blob/9afc9f907bad3b018d961af66c3abb33cd82b051/lib/public/js/lib/ck/plugins/table/dialogs/table.js#L34-L46
train
lorenwest/monitor-min
lib/Router.js
function(monitor, callback) { callback = callback || function(){}; var t = this, monitorJSON = monitor.toMonitorJSON(), probeJSON = null, probeClass = monitorJSON.probeClass, startTime = Date.now(), monitorStr = probeClass + '.' + monitor.toServerString().replace(/:/g, '.'); // Class name must be set if (!probeClass) { var errStr = 'probeClass must be set'; log.error('connectMonitor', errStr); return callback(errStr); } // Determine the connection (or internal), and listen for change events t.determineConnection(monitorJSON, true, function(err, connection) { if (err) {return callback(err);} // Function to run on connection (internal or external) var onConnect = function(error, probe) { if (error) {return callback(error);} probeJSON = probe.toJSON(); probeJSON.probeId = probeJSON.id; delete probeJSON.id; monitor.probe = probe; // Perform the initial set silently. This assures the initial // probe contents are available on the connect event, // but doesn't fire a change event before connect. monitor.set(probeJSON, {silent:true}); // Watch the probe for changes. monitor.probeChange = function(){ monitor.set(probe.changedAttributes()); log.info('probeChange', {probeId: probeJSON.probeId, changed: probe.changedAttributes()}); }; probe.on('change', monitor.probeChange); // Call the callback. This calls the original caller, issues // the connect event, then fires the initial change event. callback(null); }; // Connect internally or externally if (connection) { t.connectExternal(monitorJSON, connection, onConnect); } else { t.connectInternal(monitorJSON, onConnect); } }); }
javascript
function(monitor, callback) { callback = callback || function(){}; var t = this, monitorJSON = monitor.toMonitorJSON(), probeJSON = null, probeClass = monitorJSON.probeClass, startTime = Date.now(), monitorStr = probeClass + '.' + monitor.toServerString().replace(/:/g, '.'); // Class name must be set if (!probeClass) { var errStr = 'probeClass must be set'; log.error('connectMonitor', errStr); return callback(errStr); } // Determine the connection (or internal), and listen for change events t.determineConnection(monitorJSON, true, function(err, connection) { if (err) {return callback(err);} // Function to run on connection (internal or external) var onConnect = function(error, probe) { if (error) {return callback(error);} probeJSON = probe.toJSON(); probeJSON.probeId = probeJSON.id; delete probeJSON.id; monitor.probe = probe; // Perform the initial set silently. This assures the initial // probe contents are available on the connect event, // but doesn't fire a change event before connect. monitor.set(probeJSON, {silent:true}); // Watch the probe for changes. monitor.probeChange = function(){ monitor.set(probe.changedAttributes()); log.info('probeChange', {probeId: probeJSON.probeId, changed: probe.changedAttributes()}); }; probe.on('change', monitor.probeChange); // Call the callback. This calls the original caller, issues // the connect event, then fires the initial change event. callback(null); }; // Connect internally or externally if (connection) { t.connectExternal(monitorJSON, connection, onConnect); } else { t.connectInternal(monitorJSON, onConnect); } }); }
[ "function", "(", "monitor", ",", "callback", ")", "{", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "var", "t", "=", "this", ",", "monitorJSON", "=", "monitor", ".", "toMonitorJSON", "(", ")", ",", "probeJSON", "=", "null", ",", "probeClass", "=", "monitorJSON", ".", "probeClass", ",", "startTime", "=", "Date", ".", "now", "(", ")", ",", "monitorStr", "=", "probeClass", "+", "'.'", "+", "monitor", ".", "toServerString", "(", ")", ".", "replace", "(", "/", ":", "/", "g", ",", "'.'", ")", ";", "if", "(", "!", "probeClass", ")", "{", "var", "errStr", "=", "'probeClass must be set'", ";", "log", ".", "error", "(", "'connectMonitor'", ",", "errStr", ")", ";", "return", "callback", "(", "errStr", ")", ";", "}", "t", ".", "determineConnection", "(", "monitorJSON", ",", "true", ",", "function", "(", "err", ",", "connection", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "var", "onConnect", "=", "function", "(", "error", ",", "probe", ")", "{", "if", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "probeJSON", "=", "probe", ".", "toJSON", "(", ")", ";", "probeJSON", ".", "probeId", "=", "probeJSON", ".", "id", ";", "delete", "probeJSON", ".", "id", ";", "monitor", ".", "probe", "=", "probe", ";", "monitor", ".", "set", "(", "probeJSON", ",", "{", "silent", ":", "true", "}", ")", ";", "monitor", ".", "probeChange", "=", "function", "(", ")", "{", "monitor", ".", "set", "(", "probe", ".", "changedAttributes", "(", ")", ")", ";", "log", ".", "info", "(", "'probeChange'", ",", "{", "probeId", ":", "probeJSON", ".", "probeId", ",", "changed", ":", "probe", ".", "changedAttributes", "(", ")", "}", ")", ";", "}", ";", "probe", ".", "on", "(", "'change'", ",", "monitor", ".", "probeChange", ")", ";", "callback", "(", "null", ")", ";", "}", ";", "if", "(", "connection", ")", "{", "t", ".", "connectExternal", "(", "monitorJSON", ",", "connection", ",", "onConnect", ")", ";", "}", "else", "{", "t", ".", "connectInternal", "(", "monitorJSON", ",", "onConnect", ")", ";", "}", "}", ")", ";", "}" ]
Connect a Monitor object to a remote Probe This accepts an instance of a Monitor and figures out how to connect it to a running Probe. Upon callback the probe data is set into the monitor (unless an error occurred) @method connectMonitor @protected @param monitor {Monitor} - The monitor requesting to connect with the probe @param callback {Function(error)} - (optional) Called when connected
[ "Connect", "a", "Monitor", "object", "to", "a", "remote", "Probe" ]
859ba34a121498dc1cb98577ae24abd825407fca
https://github.com/lorenwest/monitor-min/blob/859ba34a121498dc1cb98577ae24abd825407fca/lib/Router.js#L238-L290
train
lorenwest/monitor-min
lib/Router.js
function(monitorJSON, callback) { // Build a key for this probe from the probeClass and initParams var t = this, probeKey = t.buildProbeKey(monitorJSON), probeClass = monitorJSON.probeClass, initParams = monitorJSON.initParams, probeImpl = null; var whenDone = function(error) { // Wait one tick before firing the callback. This simulates a remote // connection, making the client callback order consistent, regardless // of a local or remote connection. setTimeout(function() { // Dont connect the probe on error if (error) { if (probeImpl) { delete t.runningProbesByKey[probeKey]; delete t.runningProbesById[probeImpl.id]; try { // This may fail depending on how many resources were created // by the probe before failure. Ignore errors. probeImpl.release(); } catch (e){} } log.error('connectInternal', {error: error, probeKey: probeKey}); return callback(error); } // Probes are released based on reference count probeImpl.refCount++; log.info('connectInternal', {probeKey: probeKey, probeId: probeImpl.id}); callback(null, probeImpl); }, 0); }; // Get the probe instance probeImpl = t.runningProbesByKey[probeKey]; if (!probeImpl) { // Instantiate the probe var ProbeClass = Probe.classes[probeClass]; if (!ProbeClass) { return whenDone({msg:'Probe not available: ' + probeClass}); } var initOptions = {asyncInit: false, callback: whenDone}; try { // Deep copy the init params, because Backbone mutates them. This // is bad if the init params came in from defaults of another object, // because those defaults will get mutated. var paramCopy = Monitor.deepCopy(initParams); // Instantiate a new probe probeImpl = new ProbeClass(paramCopy, initOptions); probeImpl.set({id: Monitor.generateUniqueId()}); probeImpl.refCount = 0; probeImpl.probeKey = probeKey; t.runningProbesByKey[probeKey] = probeImpl; t.runningProbesById[probeImpl.id] = probeImpl; } catch (e) { var error = {msg: 'Error instantiating probe ' + probeClass, error: e.message}; log.error('connect', error); return whenDone(error); } // Return early if the probe constructor transferred responsibility // for calling the callback. if (initOptions.asyncInit) { return; } } // The probe impl is found, and instantiated if necessary whenDone(); }
javascript
function(monitorJSON, callback) { // Build a key for this probe from the probeClass and initParams var t = this, probeKey = t.buildProbeKey(monitorJSON), probeClass = monitorJSON.probeClass, initParams = monitorJSON.initParams, probeImpl = null; var whenDone = function(error) { // Wait one tick before firing the callback. This simulates a remote // connection, making the client callback order consistent, regardless // of a local or remote connection. setTimeout(function() { // Dont connect the probe on error if (error) { if (probeImpl) { delete t.runningProbesByKey[probeKey]; delete t.runningProbesById[probeImpl.id]; try { // This may fail depending on how many resources were created // by the probe before failure. Ignore errors. probeImpl.release(); } catch (e){} } log.error('connectInternal', {error: error, probeKey: probeKey}); return callback(error); } // Probes are released based on reference count probeImpl.refCount++; log.info('connectInternal', {probeKey: probeKey, probeId: probeImpl.id}); callback(null, probeImpl); }, 0); }; // Get the probe instance probeImpl = t.runningProbesByKey[probeKey]; if (!probeImpl) { // Instantiate the probe var ProbeClass = Probe.classes[probeClass]; if (!ProbeClass) { return whenDone({msg:'Probe not available: ' + probeClass}); } var initOptions = {asyncInit: false, callback: whenDone}; try { // Deep copy the init params, because Backbone mutates them. This // is bad if the init params came in from defaults of another object, // because those defaults will get mutated. var paramCopy = Monitor.deepCopy(initParams); // Instantiate a new probe probeImpl = new ProbeClass(paramCopy, initOptions); probeImpl.set({id: Monitor.generateUniqueId()}); probeImpl.refCount = 0; probeImpl.probeKey = probeKey; t.runningProbesByKey[probeKey] = probeImpl; t.runningProbesById[probeImpl.id] = probeImpl; } catch (e) { var error = {msg: 'Error instantiating probe ' + probeClass, error: e.message}; log.error('connect', error); return whenDone(error); } // Return early if the probe constructor transferred responsibility // for calling the callback. if (initOptions.asyncInit) { return; } } // The probe impl is found, and instantiated if necessary whenDone(); }
[ "function", "(", "monitorJSON", ",", "callback", ")", "{", "var", "t", "=", "this", ",", "probeKey", "=", "t", ".", "buildProbeKey", "(", "monitorJSON", ")", ",", "probeClass", "=", "monitorJSON", ".", "probeClass", ",", "initParams", "=", "monitorJSON", ".", "initParams", ",", "probeImpl", "=", "null", ";", "var", "whenDone", "=", "function", "(", "error", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "error", ")", "{", "if", "(", "probeImpl", ")", "{", "delete", "t", ".", "runningProbesByKey", "[", "probeKey", "]", ";", "delete", "t", ".", "runningProbesById", "[", "probeImpl", ".", "id", "]", ";", "try", "{", "probeImpl", ".", "release", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "log", ".", "error", "(", "'connectInternal'", ",", "{", "error", ":", "error", ",", "probeKey", ":", "probeKey", "}", ")", ";", "return", "callback", "(", "error", ")", ";", "}", "probeImpl", ".", "refCount", "++", ";", "log", ".", "info", "(", "'connectInternal'", ",", "{", "probeKey", ":", "probeKey", ",", "probeId", ":", "probeImpl", ".", "id", "}", ")", ";", "callback", "(", "null", ",", "probeImpl", ")", ";", "}", ",", "0", ")", ";", "}", ";", "probeImpl", "=", "t", ".", "runningProbesByKey", "[", "probeKey", "]", ";", "if", "(", "!", "probeImpl", ")", "{", "var", "ProbeClass", "=", "Probe", ".", "classes", "[", "probeClass", "]", ";", "if", "(", "!", "ProbeClass", ")", "{", "return", "whenDone", "(", "{", "msg", ":", "'Probe not available: '", "+", "probeClass", "}", ")", ";", "}", "var", "initOptions", "=", "{", "asyncInit", ":", "false", ",", "callback", ":", "whenDone", "}", ";", "try", "{", "var", "paramCopy", "=", "Monitor", ".", "deepCopy", "(", "initParams", ")", ";", "probeImpl", "=", "new", "ProbeClass", "(", "paramCopy", ",", "initOptions", ")", ";", "probeImpl", ".", "set", "(", "{", "id", ":", "Monitor", ".", "generateUniqueId", "(", ")", "}", ")", ";", "probeImpl", ".", "refCount", "=", "0", ";", "probeImpl", ".", "probeKey", "=", "probeKey", ";", "t", ".", "runningProbesByKey", "[", "probeKey", "]", "=", "probeImpl", ";", "t", ".", "runningProbesById", "[", "probeImpl", ".", "id", "]", "=", "probeImpl", ";", "}", "catch", "(", "e", ")", "{", "var", "error", "=", "{", "msg", ":", "'Error instantiating probe '", "+", "probeClass", ",", "error", ":", "e", ".", "message", "}", ";", "log", ".", "error", "(", "'connect'", ",", "error", ")", ";", "return", "whenDone", "(", "error", ")", ";", "}", "if", "(", "initOptions", ".", "asyncInit", ")", "{", "return", ";", "}", "}", "whenDone", "(", ")", ";", "}" ]
Connect to an internal probe implementation This connects with a probe running in this process. It will instantiate the probe if it isn't currently running. @method connectInternal @protected @param monitorJSON {Object} - The monitor toJSON data. Containing: @param monitorJSON.probeClass {String} - The probe class name to connect with (required) @param monitorJSON.initParams {Object} - Probe initialization parameters. @param callback {Function(error, probeImpl)} - Called when connected
[ "Connect", "to", "an", "internal", "probe", "implementation" ]
859ba34a121498dc1cb98577ae24abd825407fca
https://github.com/lorenwest/monitor-min/blob/859ba34a121498dc1cb98577ae24abd825407fca/lib/Router.js#L645-L721
train
Nichejs/Seminarjs
private/lib/core/connect.js
connect
function connect() { // detect type of each argument for (var i = 0; i < arguments.length; i++) { if (arguments[i].constructor.name === 'Mongoose') { // detected Mongoose this.mongoose = arguments[i]; } else if (arguments[i].name === 'app') { // detected Express app this.app = arguments[i]; } } return this; }
javascript
function connect() { // detect type of each argument for (var i = 0; i < arguments.length; i++) { if (arguments[i].constructor.name === 'Mongoose') { // detected Mongoose this.mongoose = arguments[i]; } else if (arguments[i].name === 'app') { // detected Express app this.app = arguments[i]; } } return this; }
[ "function", "connect", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "if", "(", "arguments", "[", "i", "]", ".", "constructor", ".", "name", "===", "'Mongoose'", ")", "{", "this", ".", "mongoose", "=", "arguments", "[", "i", "]", ";", "}", "else", "if", "(", "arguments", "[", "i", "]", ".", "name", "===", "'app'", ")", "{", "this", ".", "app", "=", "arguments", "[", "i", "]", ";", "}", "}", "return", "this", ";", "}" ]
Connects Seminarjs to the application's mongoose instance. ####Example: var mongoose = require('mongoose'); seminarjs.connect(mongoose); @param {Object} connections @api public
[ "Connects", "Seminarjs", "to", "the", "application", "s", "mongoose", "instance", "." ]
53c4c1d5c33ffbf6320b10f25679bf181cbf853e
https://github.com/Nichejs/Seminarjs/blob/53c4c1d5c33ffbf6320b10f25679bf181cbf853e/private/lib/core/connect.js#L14-L26
train
dominictarr/math-buffer
mod.js
mod
function mod(A, B) { var C = 1, D = 0 var _B = B if (B > A) return A //shift B right until it it's just smaller than A. while(B < A) { B<<=1; C<<=1 } //now, shift B back, while subtracting. do { B>>=1; C>>=1 //mark the bits where you could subtract. //this becomes the quotent! if(B < A) { D |= C; A = A - B } console.log('=', D.toString(2)) } while(B > _B) console.log(D, D.toString(2)) return A }
javascript
function mod(A, B) { var C = 1, D = 0 var _B = B if (B > A) return A //shift B right until it it's just smaller than A. while(B < A) { B<<=1; C<<=1 } //now, shift B back, while subtracting. do { B>>=1; C>>=1 //mark the bits where you could subtract. //this becomes the quotent! if(B < A) { D |= C; A = A - B } console.log('=', D.toString(2)) } while(B > _B) console.log(D, D.toString(2)) return A }
[ "function", "mod", "(", "A", ",", "B", ")", "{", "var", "C", "=", "1", ",", "D", "=", "0", "var", "_B", "=", "B", "if", "(", "B", ">", "A", ")", "return", "A", "while", "(", "B", "<", "A", ")", "{", "B", "<<=", "1", ";", "C", "<<=", "1", "}", "do", "{", "B", ">>=", "1", ";", "C", ">>=", "1", "if", "(", "B", "<", "A", ")", "{", "D", "|=", "C", ";", "A", "=", "A", "-", "B", "}", "console", ".", "log", "(", "'='", ",", "D", ".", "toString", "(", "2", ")", ")", "}", "while", "(", "B", ">", "_B", ")", "console", ".", "log", "(", "D", ",", "D", ".", "toString", "(", "2", ")", ")", "return", "A", "}" ]
calculate A % B
[ "calculate", "A", "%", "B" ]
0c646cddd2f23aa76a9e7182bad3cacfe21aa3d6
https://github.com/dominictarr/math-buffer/blob/0c646cddd2f23aa76a9e7182bad3cacfe21aa3d6/mod.js#L4-L26
train
vkiding/jud-styler
index.js
validate
function validate(json, done) { var log = [] var err try { json = JSON.parse(JSON.stringify(json)) } catch (e) { err = e json = {} } Object.keys(json).forEach(function (selector) { var declarations = json[selector] Object.keys(declarations).forEach(function (name) { var value = declarations[name] var result = validateItem(name, value) if (typeof result.value === 'number' || typeof result.value === 'string') { declarations[name] = result.value } else { delete declarations[name] } if (result.log) { log.push(result.log) } }) }) done(err, { jsonStyle: json, log: log }) }
javascript
function validate(json, done) { var log = [] var err try { json = JSON.parse(JSON.stringify(json)) } catch (e) { err = e json = {} } Object.keys(json).forEach(function (selector) { var declarations = json[selector] Object.keys(declarations).forEach(function (name) { var value = declarations[name] var result = validateItem(name, value) if (typeof result.value === 'number' || typeof result.value === 'string') { declarations[name] = result.value } else { delete declarations[name] } if (result.log) { log.push(result.log) } }) }) done(err, { jsonStyle: json, log: log }) }
[ "function", "validate", "(", "json", ",", "done", ")", "{", "var", "log", "=", "[", "]", "var", "err", "try", "{", "json", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "json", ")", ")", "}", "catch", "(", "e", ")", "{", "err", "=", "e", "json", "=", "{", "}", "}", "Object", ".", "keys", "(", "json", ")", ".", "forEach", "(", "function", "(", "selector", ")", "{", "var", "declarations", "=", "json", "[", "selector", "]", "Object", ".", "keys", "(", "declarations", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "value", "=", "declarations", "[", "name", "]", "var", "result", "=", "validateItem", "(", "name", ",", "value", ")", "if", "(", "typeof", "result", ".", "value", "===", "'number'", "||", "typeof", "result", ".", "value", "===", "'string'", ")", "{", "declarations", "[", "name", "]", "=", "result", ".", "value", "}", "else", "{", "delete", "declarations", "[", "name", "]", "}", "if", "(", "result", ".", "log", ")", "{", "log", ".", "push", "(", "result", ".", "log", ")", "}", "}", ")", "}", ")", "done", "(", "err", ",", "{", "jsonStyle", ":", "json", ",", "log", ":", "log", "}", ")", "}" ]
Validate a JSON Object and log errors & warnings @param {object} json @param {function} done which will be called with - err:Error - data.jsonStyle{}: `classname.propname.value`-like object - data.log[{reason}]
[ "Validate", "a", "JSON", "Object", "and", "log", "errors", "&", "warnings" ]
1563f84b9acd649bd546a8859e9a9226689ef1dc
https://github.com/vkiding/jud-styler/blob/1563f84b9acd649bd546a8859e9a9226689ef1dc/index.js#L166-L202
train
jivesoftware/jive-persistence-sqlite
sqlite-schema-syncer.js
qParallel
function qParallel(funcs, count) { var length = funcs.length; if (!length) { return q([]); } if (count == null) { count = Infinity; } count = Math.max(count, 1); count = Math.min(count, funcs.length); var promises = []; var values = []; for (var i = 0; i < count; ++i) { var promise = funcs[i](); promise = promise.then(next(i)); promises.push(promise); } return q.all(promises).then(function () { return values; }); function next(i) { return function (value) { if (i == null) { i = count++; } if (i < length) { values[i] = value; } if (count < length) { return funcs[count]().then(next()) } } } }
javascript
function qParallel(funcs, count) { var length = funcs.length; if (!length) { return q([]); } if (count == null) { count = Infinity; } count = Math.max(count, 1); count = Math.min(count, funcs.length); var promises = []; var values = []; for (var i = 0; i < count; ++i) { var promise = funcs[i](); promise = promise.then(next(i)); promises.push(promise); } return q.all(promises).then(function () { return values; }); function next(i) { return function (value) { if (i == null) { i = count++; } if (i < length) { values[i] = value; } if (count < length) { return funcs[count]().then(next()) } } } }
[ "function", "qParallel", "(", "funcs", ",", "count", ")", "{", "var", "length", "=", "funcs", ".", "length", ";", "if", "(", "!", "length", ")", "{", "return", "q", "(", "[", "]", ")", ";", "}", "if", "(", "count", "==", "null", ")", "{", "count", "=", "Infinity", ";", "}", "count", "=", "Math", ".", "max", "(", "count", ",", "1", ")", ";", "count", "=", "Math", ".", "min", "(", "count", ",", "funcs", ".", "length", ")", ";", "var", "promises", "=", "[", "]", ";", "var", "values", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "count", ";", "++", "i", ")", "{", "var", "promise", "=", "funcs", "[", "i", "]", "(", ")", ";", "promise", "=", "promise", ".", "then", "(", "next", "(", "i", ")", ")", ";", "promises", ".", "push", "(", "promise", ")", ";", "}", "return", "q", ".", "all", "(", "promises", ")", ".", "then", "(", "function", "(", ")", "{", "return", "values", ";", "}", ")", ";", "function", "next", "(", "i", ")", "{", "return", "function", "(", "value", ")", "{", "if", "(", "i", "==", "null", ")", "{", "i", "=", "count", "++", ";", "}", "if", "(", "i", "<", "length", ")", "{", "values", "[", "i", "]", "=", "value", ";", "}", "if", "(", "count", "<", "length", ")", "{", "return", "funcs", "[", "count", "]", "(", ")", ".", "then", "(", "next", "(", ")", ")", "}", "}", "}", "}" ]
Runs at most 'count' number of promise producing functions in parallel. @param funcs @param count @returns {*}
[ "Runs", "at", "most", "count", "number", "of", "promise", "producing", "functions", "in", "parallel", "." ]
e61374ba629159d69e0239e1fe7f609c8654dc32
https://github.com/jivesoftware/jive-persistence-sqlite/blob/e61374ba629159d69e0239e1fe7f609c8654dc32/sqlite-schema-syncer.js#L456-L496
train
jacobp100/color-forge
index.js
Color
function Color(values, spaceAlpha, space) { this.values = values; this.alpha = 1; this.space = 'rgb'; this.originalColor = null; if (space !== undefined) { this.alpha = spaceAlpha; this.space = space; } else if (spaceAlpha !== undefined) { if (typeof spaceAlpha === 'number') { this.alpha = spaceAlpha; } else { this.space = spaceAlpha; } } }
javascript
function Color(values, spaceAlpha, space) { this.values = values; this.alpha = 1; this.space = 'rgb'; this.originalColor = null; if (space !== undefined) { this.alpha = spaceAlpha; this.space = space; } else if (spaceAlpha !== undefined) { if (typeof spaceAlpha === 'number') { this.alpha = spaceAlpha; } else { this.space = spaceAlpha; } } }
[ "function", "Color", "(", "values", ",", "spaceAlpha", ",", "space", ")", "{", "this", ".", "values", "=", "values", ";", "this", ".", "alpha", "=", "1", ";", "this", ".", "space", "=", "'rgb'", ";", "this", ".", "originalColor", "=", "null", ";", "if", "(", "space", "!==", "undefined", ")", "{", "this", ".", "alpha", "=", "spaceAlpha", ";", "this", ".", "space", "=", "space", ";", "}", "else", "if", "(", "spaceAlpha", "!==", "undefined", ")", "{", "if", "(", "typeof", "spaceAlpha", "===", "'number'", ")", "{", "this", ".", "alpha", "=", "spaceAlpha", ";", "}", "else", "{", "this", ".", "space", "=", "spaceAlpha", ";", "}", "}", "}" ]
Shorthand for creation of a new color object. @name ColorShorthand @function @param {Array} values - Values in the corresponding color space @param {number} [alpha = 1] - Alpha of the color Color instance @constructor @param {Array} values - Values in the corresponding color space @param {number} [alpha=1] - Alpha of the color @param {Color.spaces} [space='rgb'] - Space corresponding to the values @property {Array} values - Values in given color space @property {string} space - Current color space @property {number} alpha - Alpha of tho color @property {Color} originalColor - The color this was converted from (if applicable)
[ "Shorthand", "for", "creation", "of", "a", "new", "color", "object", "." ]
b9b561eda2ac932aae6e9bd512e84e72075da2a5
https://github.com/jacobp100/color-forge/blob/b9b561eda2ac932aae6e9bd512e84e72075da2a5/index.js#L34-L50
train
mrjoelkemp/ya
settings/scss-settings.js
isCompassInstalled
function isCompassInstalled() { var deferred = q.defer(), cmd = 'compass'; exec(cmd, function (err) { deferred.resolve(! err); }); return deferred.promise; }
javascript
function isCompassInstalled() { var deferred = q.defer(), cmd = 'compass'; exec(cmd, function (err) { deferred.resolve(! err); }); return deferred.promise; }
[ "function", "isCompassInstalled", "(", ")", "{", "var", "deferred", "=", "q", ".", "defer", "(", ")", ",", "cmd", "=", "'compass'", ";", "exec", "(", "cmd", ",", "function", "(", "err", ")", "{", "deferred", ".", "resolve", "(", "!", "err", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Resolves with whether or not the Compass gem is installed
[ "Resolves", "with", "whether", "or", "not", "the", "Compass", "gem", "is", "installed" ]
6cb44f31902daaed32b2d72168b15eebfb7fbfbb
https://github.com/mrjoelkemp/ya/blob/6cb44f31902daaed32b2d72168b15eebfb7fbfbb/settings/scss-settings.js#L37-L46
train
swashcap/scino
index.js
scino
function scino (num, precision, options) { if (typeof precision === 'object') { options = precision precision = undefined } if (typeof num !== 'number') { return num } var parsed = parse(num, precision) var opts = getValidOptions(options) var coefficient = parsed.coefficient var exponent = parsed.exponent.toString() var superscriptExponent = '' if (typeof coefficient === 'number' && isNaN(coefficient)) { return num } for (var i = 0; i < exponent.length; i++) { superscriptExponent += SUPERSCRIPTS[exponent[i]] } return opts.beforeCoefficient + coefficient + opts.afterCoefficient + opts.beforeMultiplicationSign + opts.multiplicationSign + opts.afterMultiplicationSign + opts.beforeBase + opts.base + opts.afterBase + opts.beforeExponent + superscriptExponent + opts.afterExponent }
javascript
function scino (num, precision, options) { if (typeof precision === 'object') { options = precision precision = undefined } if (typeof num !== 'number') { return num } var parsed = parse(num, precision) var opts = getValidOptions(options) var coefficient = parsed.coefficient var exponent = parsed.exponent.toString() var superscriptExponent = '' if (typeof coefficient === 'number' && isNaN(coefficient)) { return num } for (var i = 0; i < exponent.length; i++) { superscriptExponent += SUPERSCRIPTS[exponent[i]] } return opts.beforeCoefficient + coefficient + opts.afterCoefficient + opts.beforeMultiplicationSign + opts.multiplicationSign + opts.afterMultiplicationSign + opts.beforeBase + opts.base + opts.afterBase + opts.beforeExponent + superscriptExponent + opts.afterExponent }
[ "function", "scino", "(", "num", ",", "precision", ",", "options", ")", "{", "if", "(", "typeof", "precision", "===", "'object'", ")", "{", "options", "=", "precision", "precision", "=", "undefined", "}", "if", "(", "typeof", "num", "!==", "'number'", ")", "{", "return", "num", "}", "var", "parsed", "=", "parse", "(", "num", ",", "precision", ")", "var", "opts", "=", "getValidOptions", "(", "options", ")", "var", "coefficient", "=", "parsed", ".", "coefficient", "var", "exponent", "=", "parsed", ".", "exponent", ".", "toString", "(", ")", "var", "superscriptExponent", "=", "''", "if", "(", "typeof", "coefficient", "===", "'number'", "&&", "isNaN", "(", "coefficient", ")", ")", "{", "return", "num", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "exponent", ".", "length", ";", "i", "++", ")", "{", "superscriptExponent", "+=", "SUPERSCRIPTS", "[", "exponent", "[", "i", "]", "]", "}", "return", "opts", ".", "beforeCoefficient", "+", "coefficient", "+", "opts", ".", "afterCoefficient", "+", "opts", ".", "beforeMultiplicationSign", "+", "opts", ".", "multiplicationSign", "+", "opts", ".", "afterMultiplicationSign", "+", "opts", ".", "beforeBase", "+", "opts", ".", "base", "+", "opts", ".", "afterBase", "+", "opts", ".", "beforeExponent", "+", "superscriptExponent", "+", "opts", ".", "afterExponent", "}" ]
Format a number using scientific notation. @param {number} num @param {number} [precision] @param {Object} [options] Formatting options @returns {string} Formatted number
[ "Format", "a", "number", "using", "scientific", "notation", "." ]
654a0025b9018e52186b9462ce967983fca8cf05
https://github.com/swashcap/scino/blob/654a0025b9018e52186b9462ce967983fca8cf05/index.js#L16-L44
train
swashcap/scino
index.js
parse
function parse (num, precision) { var exponent = Math.floor(Math.log10(Math.abs(num))) var coefficient = new Decimal(num) .mul(new Decimal(Math.pow(10, -1 * exponent))) return { coefficient: typeof precision === 'number' ? coefficient.toSD(precision).toNumber() : coefficient.toNumber(), exponent: exponent } }
javascript
function parse (num, precision) { var exponent = Math.floor(Math.log10(Math.abs(num))) var coefficient = new Decimal(num) .mul(new Decimal(Math.pow(10, -1 * exponent))) return { coefficient: typeof precision === 'number' ? coefficient.toSD(precision).toNumber() : coefficient.toNumber(), exponent: exponent } }
[ "function", "parse", "(", "num", ",", "precision", ")", "{", "var", "exponent", "=", "Math", ".", "floor", "(", "Math", ".", "log10", "(", "Math", ".", "abs", "(", "num", ")", ")", ")", "var", "coefficient", "=", "new", "Decimal", "(", "num", ")", ".", "mul", "(", "new", "Decimal", "(", "Math", ".", "pow", "(", "10", ",", "-", "1", "*", "exponent", ")", ")", ")", "return", "{", "coefficient", ":", "typeof", "precision", "===", "'number'", "?", "coefficient", ".", "toSD", "(", "precision", ")", ".", "toNumber", "(", ")", ":", "coefficient", ".", "toNumber", "(", ")", ",", "exponent", ":", "exponent", "}", "}" ]
Parse a number into its base and exponent. {@link http://mikemcl.github.io/decimal.js/#toSD} @param {number} num @param {number} [precision] @returns {Object} @property {number} coefficient @property {number} exponent
[ "Parse", "a", "number", "into", "its", "base", "and", "exponent", "." ]
654a0025b9018e52186b9462ce967983fca8cf05
https://github.com/swashcap/scino/blob/654a0025b9018e52186b9462ce967983fca8cf05/index.js#L57-L68
train
bredele/grout
index.js
render
function render(content, store) { var type = typeof content; var node = content; if(type === 'function') node = render(content(), store); else if(type === 'string') { node = document.createTextNode(''); bind(content, function(data) { node.nodeValue = data; }, store); } else if(content instanceof Array) node = fragment(content, store); return node; }
javascript
function render(content, store) { var type = typeof content; var node = content; if(type === 'function') node = render(content(), store); else if(type === 'string') { node = document.createTextNode(''); bind(content, function(data) { node.nodeValue = data; }, store); } else if(content instanceof Array) node = fragment(content, store); return node; }
[ "function", "render", "(", "content", ",", "store", ")", "{", "var", "type", "=", "typeof", "content", ";", "var", "node", "=", "content", ";", "if", "(", "type", "===", "'function'", ")", "node", "=", "render", "(", "content", "(", ")", ",", "store", ")", ";", "else", "if", "(", "type", "===", "'string'", ")", "{", "node", "=", "document", ".", "createTextNode", "(", "''", ")", ";", "bind", "(", "content", ",", "function", "(", "data", ")", "{", "node", ".", "nodeValue", "=", "data", ";", "}", ",", "store", ")", ";", "}", "else", "if", "(", "content", "instanceof", "Array", ")", "node", "=", "fragment", "(", "content", ",", "store", ")", ";", "return", "node", ";", "}" ]
Render virtual dom content. @param {String|Array|Element} content @param {DataStore?} store @return {Element} @api private
[ "Render", "virtual", "dom", "content", "." ]
0cc8658cac07a27bab3287475b83deb0564b4b2e
https://github.com/bredele/grout/blob/0cc8658cac07a27bab3287475b83deb0564b4b2e/index.js#L54-L66
train
bredele/grout
index.js
bind
function bind(text, fn, store) { var data = store.data; var tmpl = mouth(text, store.data); var cb = tmpl[0]; var keys = tmpl[1]; fn(cb(store.data)); for(var l = keys.length; l--;) { store.on('change ' + keys[l], function() { fn(cb(store.data)); }); } }
javascript
function bind(text, fn, store) { var data = store.data; var tmpl = mouth(text, store.data); var cb = tmpl[0]; var keys = tmpl[1]; fn(cb(store.data)); for(var l = keys.length; l--;) { store.on('change ' + keys[l], function() { fn(cb(store.data)); }); } }
[ "function", "bind", "(", "text", ",", "fn", ",", "store", ")", "{", "var", "data", "=", "store", ".", "data", ";", "var", "tmpl", "=", "mouth", "(", "text", ",", "store", ".", "data", ")", ";", "var", "cb", "=", "tmpl", "[", "0", "]", ";", "var", "keys", "=", "tmpl", "[", "1", "]", ";", "fn", "(", "cb", "(", "store", ".", "data", ")", ")", ";", "for", "(", "var", "l", "=", "keys", ".", "length", ";", "l", "--", ";", ")", "{", "store", ".", "on", "(", "'change '", "+", "keys", "[", "l", "]", ",", "function", "(", ")", "{", "fn", "(", "cb", "(", "store", ".", "data", ")", ")", ";", "}", ")", ";", "}", "}" ]
Bind virtual dom with data store. @param {String} text @param {Function} fn @param {DataStore} store @api private
[ "Bind", "virtual", "dom", "with", "data", "store", "." ]
0cc8658cac07a27bab3287475b83deb0564b4b2e
https://github.com/bredele/grout/blob/0cc8658cac07a27bab3287475b83deb0564b4b2e/index.js#L78-L89
train
bredele/grout
index.js
fragment
function fragment(arr, store) { var el = document.createDocumentFragment(); for(var i = 0, l = arr.length; i < l; i++) { el.appendChild(render(arr[i], store)); } return el; }
javascript
function fragment(arr, store) { var el = document.createDocumentFragment(); for(var i = 0, l = arr.length; i < l; i++) { el.appendChild(render(arr[i], store)); } return el; }
[ "function", "fragment", "(", "arr", ",", "store", ")", "{", "var", "el", "=", "document", ".", "createDocumentFragment", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "arr", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "el", ".", "appendChild", "(", "render", "(", "arr", "[", "i", "]", ",", "store", ")", ")", ";", "}", "return", "el", ";", "}" ]
Render fragment of virtual dom. @param {Array} arr @param {DataStore} store @return {DocumentFragment} @api private
[ "Render", "fragment", "of", "virtual", "dom", "." ]
0cc8658cac07a27bab3287475b83deb0564b4b2e
https://github.com/bredele/grout/blob/0cc8658cac07a27bab3287475b83deb0564b4b2e/index.js#L101-L107
train
bredele/grout
index.js
attributes
function attributes(el, attrs, store) { for(var key in attrs) { var value = attrs[key]; if(typeof value === 'object') value = styles(value); else if(typeof value === 'function') { var bool = key.substring(0, 2) === 'on'; if(bool) el.addEventListener(key.slice(2), value); else el.setAttribute(key, value.call(store.data)); // @not we should compute the function if it's not an event break; } bind(value, function(data) { // @note should refactor with render (too bad attribute can't append text node anymore) el.setAttribute(this, data); }.bind(key), store); } }
javascript
function attributes(el, attrs, store) { for(var key in attrs) { var value = attrs[key]; if(typeof value === 'object') value = styles(value); else if(typeof value === 'function') { var bool = key.substring(0, 2) === 'on'; if(bool) el.addEventListener(key.slice(2), value); else el.setAttribute(key, value.call(store.data)); // @not we should compute the function if it's not an event break; } bind(value, function(data) { // @note should refactor with render (too bad attribute can't append text node anymore) el.setAttribute(this, data); }.bind(key), store); } }
[ "function", "attributes", "(", "el", ",", "attrs", ",", "store", ")", "{", "for", "(", "var", "key", "in", "attrs", ")", "{", "var", "value", "=", "attrs", "[", "key", "]", ";", "if", "(", "typeof", "value", "===", "'object'", ")", "value", "=", "styles", "(", "value", ")", ";", "else", "if", "(", "typeof", "value", "===", "'function'", ")", "{", "var", "bool", "=", "key", ".", "substring", "(", "0", ",", "2", ")", "===", "'on'", ";", "if", "(", "bool", ")", "el", ".", "addEventListener", "(", "key", ".", "slice", "(", "2", ")", ",", "value", ")", ";", "else", "el", ".", "setAttribute", "(", "key", ",", "value", ".", "call", "(", "store", ".", "data", ")", ")", ";", "break", ";", "}", "bind", "(", "value", ",", "function", "(", "data", ")", "{", "el", ".", "setAttribute", "(", "this", ",", "data", ")", ";", "}", ".", "bind", "(", "key", ")", ",", "store", ")", ";", "}", "}" ]
Render virtual dom attributes. @param {Element} el @param {Object} attrs @param {DataStore} store @api private
[ "Render", "virtual", "dom", "attributes", "." ]
0cc8658cac07a27bab3287475b83deb0564b4b2e
https://github.com/bredele/grout/blob/0cc8658cac07a27bab3287475b83deb0564b4b2e/index.js#L119-L136
train
bredele/grout
index.js
styles
function styles(obj) { var str = ''; for(var key in obj) { str += key + ':' + obj[key] + ';'; } return str; }
javascript
function styles(obj) { var str = ''; for(var key in obj) { str += key + ':' + obj[key] + ';'; } return str; }
[ "function", "styles", "(", "obj", ")", "{", "var", "str", "=", "''", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "str", "+=", "key", "+", "':'", "+", "obj", "[", "key", "]", "+", "';'", ";", "}", "return", "str", ";", "}" ]
Render virtual dom styles. @param {Object} obj @return {String} @api private
[ "Render", "virtual", "dom", "styles", "." ]
0cc8658cac07a27bab3287475b83deb0564b4b2e
https://github.com/bredele/grout/blob/0cc8658cac07a27bab3287475b83deb0564b4b2e/index.js#L148-L154
train
frozzare/gulp-phpcpd
index.js
buildCommand
function buildCommand(options, dir) { var cmd = options.bin; if (options.reportFile) { cmd += ' --log-pmd ' + options.reportFile; } cmd += ' --min-lines ' + options.minLines; cmd += ' --min-tokens ' + options.minTokens; if (options.exclude instanceof Array) { for (var i = 0, l = options.exclude; i < l; i++) { cmd += ' --exclude ' + options.exclude[i]; } } else { cmd += ' --exclude ' + options.exclude; } cmd += ' --names \"' + options.names + '\"'; if (options.namesExclude) { cmd += ' --names-exclude \"' + options.namesExclude + '\"'; } if (options.quiet) { cmd += ' --quiet'; } if (options.verbose) { cmd += ' --verbose'; } return cmd + ' ' + dir; }
javascript
function buildCommand(options, dir) { var cmd = options.bin; if (options.reportFile) { cmd += ' --log-pmd ' + options.reportFile; } cmd += ' --min-lines ' + options.minLines; cmd += ' --min-tokens ' + options.minTokens; if (options.exclude instanceof Array) { for (var i = 0, l = options.exclude; i < l; i++) { cmd += ' --exclude ' + options.exclude[i]; } } else { cmd += ' --exclude ' + options.exclude; } cmd += ' --names \"' + options.names + '\"'; if (options.namesExclude) { cmd += ' --names-exclude \"' + options.namesExclude + '\"'; } if (options.quiet) { cmd += ' --quiet'; } if (options.verbose) { cmd += ' --verbose'; } return cmd + ' ' + dir; }
[ "function", "buildCommand", "(", "options", ",", "dir", ")", "{", "var", "cmd", "=", "options", ".", "bin", ";", "if", "(", "options", ".", "reportFile", ")", "{", "cmd", "+=", "' --log-pmd '", "+", "options", ".", "reportFile", ";", "}", "cmd", "+=", "' --min-lines '", "+", "options", ".", "minLines", ";", "cmd", "+=", "' --min-tokens '", "+", "options", ".", "minTokens", ";", "if", "(", "options", ".", "exclude", "instanceof", "Array", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "options", ".", "exclude", ";", "i", "<", "l", ";", "i", "++", ")", "{", "cmd", "+=", "' --exclude '", "+", "options", ".", "exclude", "[", "i", "]", ";", "}", "}", "else", "{", "cmd", "+=", "' --exclude '", "+", "options", ".", "exclude", ";", "}", "cmd", "+=", "' --names \\\"'", "+", "\\\"", "+", "options", ".", "names", ";", "'\\\"'", "\\\"", "if", "(", "options", ".", "namesExclude", ")", "{", "cmd", "+=", "' --names-exclude \\\"'", "+", "\\\"", "+", "options", ".", "namesExclude", ";", "}", "'\\\"'", "}" ]
Build command. @param {object} options @param {string} dir @return string
[ "Build", "command", "." ]
6c67e259943c7e4dc3e13ac48e240c51dd288c2f
https://github.com/frozzare/gulp-phpcpd/blob/6c67e259943c7e4dc3e13ac48e240c51dd288c2f/index.js#L37-L70
train
mongodb-js/mj
commands/check.js
function(args, done) { debug('checking required files with args', args); var dir = path.resolve(args['<directory>']); var tasks = [ 'README*', 'LICENSE', '.travis.yml', '.gitignore' ].map(function requireFileExists(pattern) { return function(cb) { glob(pattern, { cwd: dir }, function(err, files) { debug('resolved %s for `%s`', files, pattern); if (err) { return cb(err); } if (files.length === 0) { return done(new Error('missing required file matching ' + pattern)); } if (files.length > 1) { return done(new Error('more than one file matched ' + pattern)); } fs.exists(files[0], function(exists) { if (!exists) { return done(new Error('missing required file matching ' + files[0])); } return cb(null, files[0]); }); }); }; }); async.parallel(tasks, done); }
javascript
function(args, done) { debug('checking required files with args', args); var dir = path.resolve(args['<directory>']); var tasks = [ 'README*', 'LICENSE', '.travis.yml', '.gitignore' ].map(function requireFileExists(pattern) { return function(cb) { glob(pattern, { cwd: dir }, function(err, files) { debug('resolved %s for `%s`', files, pattern); if (err) { return cb(err); } if (files.length === 0) { return done(new Error('missing required file matching ' + pattern)); } if (files.length > 1) { return done(new Error('more than one file matched ' + pattern)); } fs.exists(files[0], function(exists) { if (!exists) { return done(new Error('missing required file matching ' + files[0])); } return cb(null, files[0]); }); }); }; }); async.parallel(tasks, done); }
[ "function", "(", "args", ",", "done", ")", "{", "debug", "(", "'checking required files with args'", ",", "args", ")", ";", "var", "dir", "=", "path", ".", "resolve", "(", "args", "[", "'<directory>'", "]", ")", ";", "var", "tasks", "=", "[", "'README*'", ",", "'LICENSE'", ",", "'.travis.yml'", ",", "'.gitignore'", "]", ".", "map", "(", "function", "requireFileExists", "(", "pattern", ")", "{", "return", "function", "(", "cb", ")", "{", "glob", "(", "pattern", ",", "{", "cwd", ":", "dir", "}", ",", "function", "(", "err", ",", "files", ")", "{", "debug", "(", "'resolved %s for `%s`'", ",", "files", ",", "pattern", ")", ";", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "files", ".", "length", "===", "0", ")", "{", "return", "done", "(", "new", "Error", "(", "'missing required file matching '", "+", "pattern", ")", ")", ";", "}", "if", "(", "files", ".", "length", ">", "1", ")", "{", "return", "done", "(", "new", "Error", "(", "'more than one file matched '", "+", "pattern", ")", ")", ";", "}", "fs", ".", "exists", "(", "files", "[", "0", "]", ",", "function", "(", "exists", ")", "{", "if", "(", "!", "exists", ")", "{", "return", "done", "(", "new", "Error", "(", "'missing required file matching '", "+", "files", "[", "0", "]", ")", ")", ";", "}", "return", "cb", "(", "null", ",", "files", "[", "0", "]", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "}", ")", ";", "async", ".", "parallel", "(", "tasks", ",", "done", ")", ";", "}" ]
Checks for required files
[ "Checks", "for", "required", "files" ]
a643970372c74baf8cfc7087cda80d3f6001fe7b
https://github.com/mongodb-js/mj/blob/a643970372c74baf8cfc7087cda80d3f6001fe7b/commands/check.js#L12-L47
train
mongodb-js/mj
commands/check.js
function(args, done) { var dir = path.resolve(args['<directory>']); var pkg = require(path.join(dir, 'package.json')); var schema = Joi.object().keys({ name: Joi.string().min(1).max(30).regex(/^[a-zA-Z0-9][a-zA-Z0-9\.\-_]*$/).required(), version: Joi.string().regex(/^[0-9]+\.[0-9]+[0-9+a-zA-Z\.\-]+$/).required(), description: Joi.string().max(80).required(), license: Joi.string().max(20).required(), homepage: Joi.string().uri({ scheme: ['http', 'https'] }).required(), main: Joi.string().optional(), repository: Joi.object().keys({ type: Joi.string().valid('git').required(), url: Joi.string().uri({ scheme: ['git', 'https'] }).regex(/mongodb-js\/[a-zA-Z0-9\.\-_]+/).required() }), bin: Joi.object().optional(), scripts: Joi.object().optional(), bugs: Joi.alternatives().try(Joi.string(), Joi.object()).required(), author: Joi.string().required(), dependencies: Joi.object().required(), devDependencies: Joi.object().required() }); Joi.validate(pkg, schema, { abortEarly: false, allowUnknown: true }, done); }
javascript
function(args, done) { var dir = path.resolve(args['<directory>']); var pkg = require(path.join(dir, 'package.json')); var schema = Joi.object().keys({ name: Joi.string().min(1).max(30).regex(/^[a-zA-Z0-9][a-zA-Z0-9\.\-_]*$/).required(), version: Joi.string().regex(/^[0-9]+\.[0-9]+[0-9+a-zA-Z\.\-]+$/).required(), description: Joi.string().max(80).required(), license: Joi.string().max(20).required(), homepage: Joi.string().uri({ scheme: ['http', 'https'] }).required(), main: Joi.string().optional(), repository: Joi.object().keys({ type: Joi.string().valid('git').required(), url: Joi.string().uri({ scheme: ['git', 'https'] }).regex(/mongodb-js\/[a-zA-Z0-9\.\-_]+/).required() }), bin: Joi.object().optional(), scripts: Joi.object().optional(), bugs: Joi.alternatives().try(Joi.string(), Joi.object()).required(), author: Joi.string().required(), dependencies: Joi.object().required(), devDependencies: Joi.object().required() }); Joi.validate(pkg, schema, { abortEarly: false, allowUnknown: true }, done); }
[ "function", "(", "args", ",", "done", ")", "{", "var", "dir", "=", "path", ".", "resolve", "(", "args", "[", "'<directory>'", "]", ")", ";", "var", "pkg", "=", "require", "(", "path", ".", "join", "(", "dir", ",", "'package.json'", ")", ")", ";", "var", "schema", "=", "Joi", ".", "object", "(", ")", ".", "keys", "(", "{", "name", ":", "Joi", ".", "string", "(", ")", ".", "min", "(", "1", ")", ".", "max", "(", "30", ")", ".", "regex", "(", "/", "^[a-zA-Z0-9][a-zA-Z0-9\\.\\-_]*$", "/", ")", ".", "required", "(", ")", ",", "version", ":", "Joi", ".", "string", "(", ")", ".", "regex", "(", "/", "^[0-9]+\\.[0-9]+[0-9+a-zA-Z\\.\\-]+$", "/", ")", ".", "required", "(", ")", ",", "description", ":", "Joi", ".", "string", "(", ")", ".", "max", "(", "80", ")", ".", "required", "(", ")", ",", "license", ":", "Joi", ".", "string", "(", ")", ".", "max", "(", "20", ")", ".", "required", "(", ")", ",", "homepage", ":", "Joi", ".", "string", "(", ")", ".", "uri", "(", "{", "scheme", ":", "[", "'http'", ",", "'https'", "]", "}", ")", ".", "required", "(", ")", ",", "main", ":", "Joi", ".", "string", "(", ")", ".", "optional", "(", ")", ",", "repository", ":", "Joi", ".", "object", "(", ")", ".", "keys", "(", "{", "type", ":", "Joi", ".", "string", "(", ")", ".", "valid", "(", "'git'", ")", ".", "required", "(", ")", ",", "url", ":", "Joi", ".", "string", "(", ")", ".", "uri", "(", "{", "scheme", ":", "[", "'git'", ",", "'https'", "]", "}", ")", ".", "regex", "(", "/", "mongodb-js\\/[a-zA-Z0-9\\.\\-_]+", "/", ")", ".", "required", "(", ")", "}", ")", ",", "bin", ":", "Joi", ".", "object", "(", ")", ".", "optional", "(", ")", ",", "scripts", ":", "Joi", ".", "object", "(", ")", ".", "optional", "(", ")", ",", "bugs", ":", "Joi", ".", "alternatives", "(", ")", ".", "try", "(", "Joi", ".", "string", "(", ")", ",", "Joi", ".", "object", "(", ")", ")", ".", "required", "(", ")", ",", "author", ":", "Joi", ".", "string", "(", ")", ".", "required", "(", ")", ",", "dependencies", ":", "Joi", ".", "object", "(", ")", ".", "required", "(", ")", ",", "devDependencies", ":", "Joi", ".", "object", "(", ")", ".", "required", "(", ")", "}", ")", ";", "Joi", ".", "validate", "(", "pkg", ",", "schema", ",", "{", "abortEarly", ":", "false", ",", "allowUnknown", ":", "true", "}", ",", "done", ")", ";", "}" ]
Check package.json conforms
[ "Check", "package", ".", "json", "conforms" ]
a643970372c74baf8cfc7087cda80d3f6001fe7b
https://github.com/mongodb-js/mj/blob/a643970372c74baf8cfc7087cda80d3f6001fe7b/commands/check.js#L50-L79
train
mongodb-js/mj
commands/check.js
function(args, done) { function run(cmd) { return function(cb) { debug('testing `%s`', cmd); var parts = cmd.split(' '); var bin = parts.shift(); var args = parts; var completed = false; var child = spawn(bin, args, { cwd: args['<directory>'] }) .on('error', function(err) { completed = true; done(new Error(cmd + ' failed: ' + err.message)); }); child.stderr.pipe(process.stderr); if (cmd === 'npm start') { setTimeout(function() { if (completed) { return; } completed = true; child.kill('SIGKILL'); done(); }, 5000); } child.on('close', function(code) { if (completed) { return; } completed = true; if (code === 0) { done(); return; } cb(new Error(cmd + ' failed')); }); }; } debug('checking first run'); var dir = path.resolve(args['<directory>']); var pkg = require(path.join(dir, 'package.json')); debug('clearing local node_modules to make sure install works'); rimraf(dir + '/node_modules/**/*', function(err) { if (err) { return done(err); } var tasks = [ run('npm install'), run('npm test') ]; if (pkg.scripts.start) { tasks.push(run('npm start')); } async.series(tasks, function(err, results) { if (err) { return done(err); } done(null, results); }); }); }
javascript
function(args, done) { function run(cmd) { return function(cb) { debug('testing `%s`', cmd); var parts = cmd.split(' '); var bin = parts.shift(); var args = parts; var completed = false; var child = spawn(bin, args, { cwd: args['<directory>'] }) .on('error', function(err) { completed = true; done(new Error(cmd + ' failed: ' + err.message)); }); child.stderr.pipe(process.stderr); if (cmd === 'npm start') { setTimeout(function() { if (completed) { return; } completed = true; child.kill('SIGKILL'); done(); }, 5000); } child.on('close', function(code) { if (completed) { return; } completed = true; if (code === 0) { done(); return; } cb(new Error(cmd + ' failed')); }); }; } debug('checking first run'); var dir = path.resolve(args['<directory>']); var pkg = require(path.join(dir, 'package.json')); debug('clearing local node_modules to make sure install works'); rimraf(dir + '/node_modules/**/*', function(err) { if (err) { return done(err); } var tasks = [ run('npm install'), run('npm test') ]; if (pkg.scripts.start) { tasks.push(run('npm start')); } async.series(tasks, function(err, results) { if (err) { return done(err); } done(null, results); }); }); }
[ "function", "(", "args", ",", "done", ")", "{", "function", "run", "(", "cmd", ")", "{", "return", "function", "(", "cb", ")", "{", "debug", "(", "'testing `%s`'", ",", "cmd", ")", ";", "var", "parts", "=", "cmd", ".", "split", "(", "' '", ")", ";", "var", "bin", "=", "parts", ".", "shift", "(", ")", ";", "var", "args", "=", "parts", ";", "var", "completed", "=", "false", ";", "var", "child", "=", "spawn", "(", "bin", ",", "args", ",", "{", "cwd", ":", "args", "[", "'<directory>'", "]", "}", ")", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "completed", "=", "true", ";", "done", "(", "new", "Error", "(", "cmd", "+", "' failed: '", "+", "err", ".", "message", ")", ")", ";", "}", ")", ";", "child", ".", "stderr", ".", "pipe", "(", "process", ".", "stderr", ")", ";", "if", "(", "cmd", "===", "'npm start'", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "completed", ")", "{", "return", ";", "}", "completed", "=", "true", ";", "child", ".", "kill", "(", "'SIGKILL'", ")", ";", "done", "(", ")", ";", "}", ",", "5000", ")", ";", "}", "child", ".", "on", "(", "'close'", ",", "function", "(", "code", ")", "{", "if", "(", "completed", ")", "{", "return", ";", "}", "completed", "=", "true", ";", "if", "(", "code", "===", "0", ")", "{", "done", "(", ")", ";", "return", ";", "}", "cb", "(", "new", "Error", "(", "cmd", "+", "' failed'", ")", ")", ";", "}", ")", ";", "}", ";", "}", "debug", "(", "'checking first run'", ")", ";", "var", "dir", "=", "path", ".", "resolve", "(", "args", "[", "'<directory>'", "]", ")", ";", "var", "pkg", "=", "require", "(", "path", ".", "join", "(", "dir", ",", "'package.json'", ")", ")", ";", "debug", "(", "'clearing local node_modules to make sure install works'", ")", ";", "rimraf", "(", "dir", "+", "'/node_modules/**/*'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "var", "tasks", "=", "[", "run", "(", "'npm install'", ")", ",", "run", "(", "'npm test'", ")", "]", ";", "if", "(", "pkg", ".", "scripts", ".", "start", ")", "{", "tasks", ".", "push", "(", "run", "(", "'npm start'", ")", ")", ";", "}", "async", ".", "series", "(", "tasks", ",", "function", "(", "err", ",", "results", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "done", "(", "null", ",", "results", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
If I clone this repo and run `npm install && npm test` does it work? If there is an `npm start`, run that as well and make sure it stays up for 5 seconds and doesn't return an error.
[ "If", "I", "clone", "this", "repo", "and", "run", "npm", "install", "&&", "npm", "test", "does", "it", "work?", "If", "there", "is", "an", "npm", "start", "run", "that", "as", "well", "and", "make", "sure", "it", "stays", "up", "for", "5", "seconds", "and", "doesn", "t", "return", "an", "error", "." ]
a643970372c74baf8cfc7087cda80d3f6001fe7b
https://github.com/mongodb-js/mj/blob/a643970372c74baf8cfc7087cda80d3f6001fe7b/commands/check.js#L84-L160
train
iolo/node-toybox
utils.js
toBoolean
function toBoolean(str, fallback) { if (typeof str === 'boolean') { return str; } if (REGEXP_TRUE.test(str)) { return true; } if (REGEXP_FALSE.test(str)) { return false; } return fallback; }
javascript
function toBoolean(str, fallback) { if (typeof str === 'boolean') { return str; } if (REGEXP_TRUE.test(str)) { return true; } if (REGEXP_FALSE.test(str)) { return false; } return fallback; }
[ "function", "toBoolean", "(", "str", ",", "fallback", ")", "{", "if", "(", "typeof", "str", "===", "'boolean'", ")", "{", "return", "str", ";", "}", "if", "(", "REGEXP_TRUE", ".", "test", "(", "str", ")", ")", "{", "return", "true", ";", "}", "if", "(", "REGEXP_FALSE", ".", "test", "(", "str", ")", ")", "{", "return", "false", ";", "}", "return", "fallback", ";", "}" ]
convert string to strict boolean. @param {string|boolean} str @param {boolean} [fallback] @returns {boolean}
[ "convert", "string", "to", "strict", "boolean", "." ]
d03e48b5e4b3deb022688fee59dd33a2b71819d0
https://github.com/iolo/node-toybox/blob/d03e48b5e4b3deb022688fee59dd33a2b71819d0/utils.js#L57-L68
train
iolo/node-toybox
utils.js
hashCode
function hashCode(str) { var hash = 0xdeadbeef; for (var i = str.length; i >= 0; --i) { hash = (hash * 33) ^ str.charCodeAt(--i); } // turn to unsigned 32bit int return hash >>> 0; }
javascript
function hashCode(str) { var hash = 0xdeadbeef; for (var i = str.length; i >= 0; --i) { hash = (hash * 33) ^ str.charCodeAt(--i); } // turn to unsigned 32bit int return hash >>> 0; }
[ "function", "hashCode", "(", "str", ")", "{", "var", "hash", "=", "0xdeadbeef", ";", "for", "(", "var", "i", "=", "str", ".", "length", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "hash", "=", "(", "hash", "*", "33", ")", "^", "str", ".", "charCodeAt", "(", "--", "i", ")", ";", "}", "return", "hash", ">>>", "0", ";", "}" ]
get a non-crypto hash code from a string. @param {string} str @returns {number} unsigned 32bit hash code @see http://www.cse.yorku.ca/~oz/hash.html
[ "get", "a", "non", "-", "crypto", "hash", "code", "from", "a", "string", "." ]
d03e48b5e4b3deb022688fee59dd33a2b71819d0
https://github.com/iolo/node-toybox/blob/d03e48b5e4b3deb022688fee59dd33a2b71819d0/utils.js#L77-L84
train
iolo/node-toybox
utils.js
gravatarUrl
function gravatarUrl(email, size) { var url = 'http://www.gravatar.com/avatar/'; if (email) { url += crypto.createHash('md5').update(email.toLowerCase()).digest('hex'); } if (size) { url += '?s=' + size; } return url; }
javascript
function gravatarUrl(email, size) { var url = 'http://www.gravatar.com/avatar/'; if (email) { url += crypto.createHash('md5').update(email.toLowerCase()).digest('hex'); } if (size) { url += '?s=' + size; } return url; }
[ "function", "gravatarUrl", "(", "email", ",", "size", ")", "{", "var", "url", "=", "'http://www.gravatar.com/avatar/'", ";", "if", "(", "email", ")", "{", "url", "+=", "crypto", ".", "createHash", "(", "'md5'", ")", ".", "update", "(", "email", ".", "toLowerCase", "(", ")", ")", ".", "digest", "(", "'hex'", ")", ";", "}", "if", "(", "size", ")", "{", "url", "+=", "'?s='", "+", "size", ";", "}", "return", "url", ";", "}" ]
get gravatar url. @param {String} email @param {Number} [size] @return {String} gravatar url
[ "get", "gravatar", "url", "." ]
d03e48b5e4b3deb022688fee59dd33a2b71819d0
https://github.com/iolo/node-toybox/blob/d03e48b5e4b3deb022688fee59dd33a2b71819d0/utils.js#L93-L102
train
iolo/node-toybox
utils.js
placeholderUrl
function placeholderUrl(width, height, text) { var url = 'http://placehold.it/' + width; if (height) { url += 'x' + height; } if (text) { url += '&text=' + encodeURIComponent(text); } return url; }
javascript
function placeholderUrl(width, height, text) { var url = 'http://placehold.it/' + width; if (height) { url += 'x' + height; } if (text) { url += '&text=' + encodeURIComponent(text); } return url; }
[ "function", "placeholderUrl", "(", "width", ",", "height", ",", "text", ")", "{", "var", "url", "=", "'http://placehold.it/'", "+", "width", ";", "if", "(", "height", ")", "{", "url", "+=", "'x'", "+", "height", ";", "}", "if", "(", "text", ")", "{", "url", "+=", "'&text='", "+", "encodeURIComponent", "(", "text", ")", ";", "}", "return", "url", ";", "}" ]
get placeholder image url. @param {number} width @param {number} [height=width] @param {string} [text] @returns {string} placeholder image url
[ "get", "placeholder", "image", "url", "." ]
d03e48b5e4b3deb022688fee59dd33a2b71819d0
https://github.com/iolo/node-toybox/blob/d03e48b5e4b3deb022688fee59dd33a2b71819d0/utils.js#L112-L121
train
iolo/node-toybox
utils.js
digestPassword
function digestPassword(password, salt, algorithm, encoding) { var hash = (salt) ? crypto.createHmac(algorithm || 'sha1', salt) : crypto.createHash(algorithm || 'sha1'); return hash.update(password).digest(encoding || 'hex'); }
javascript
function digestPassword(password, salt, algorithm, encoding) { var hash = (salt) ? crypto.createHmac(algorithm || 'sha1', salt) : crypto.createHash(algorithm || 'sha1'); return hash.update(password).digest(encoding || 'hex'); }
[ "function", "digestPassword", "(", "password", ",", "salt", ",", "algorithm", ",", "encoding", ")", "{", "var", "hash", "=", "(", "salt", ")", "?", "crypto", ".", "createHmac", "(", "algorithm", "||", "'sha1'", ",", "salt", ")", ":", "crypto", ".", "createHash", "(", "algorithm", "||", "'sha1'", ")", ";", "return", "hash", ".", "update", "(", "password", ")", ".", "digest", "(", "encoding", "||", "'hex'", ")", ";", "}" ]
digest password string with optional salt. @param {String} password @param {String} [salt] @param {String} [algorithm='sha1'] 'sha1', 'md5', 'sha256', 'sha512'... @param {String} [encoding='hex'] 'hex', 'binary' or 'base64' @return {String} digested password string
[ "digest", "password", "string", "with", "optional", "salt", "." ]
d03e48b5e4b3deb022688fee59dd33a2b71819d0
https://github.com/iolo/node-toybox/blob/d03e48b5e4b3deb022688fee59dd33a2b71819d0/utils.js#L142-L145
train
iolo/node-toybox
utils.js
digestFile
function digestFile(file, algorithm, encoding) { return crypto.createHash(algorithm || 'md5').update(fs.readFileSync(file)).digest(encoding || 'hex'); }
javascript
function digestFile(file, algorithm, encoding) { return crypto.createHash(algorithm || 'md5').update(fs.readFileSync(file)).digest(encoding || 'hex'); }
[ "function", "digestFile", "(", "file", ",", "algorithm", ",", "encoding", ")", "{", "return", "crypto", ".", "createHash", "(", "algorithm", "||", "'md5'", ")", ".", "update", "(", "fs", ".", "readFileSync", "(", "file", ")", ")", ".", "digest", "(", "encoding", "||", "'hex'", ")", ";", "}" ]
digest file content. @param {String} file @param {String} [algorithm='md5'] 'sha1', 'md5', 'sha256', 'sha512'... @param {String} [encoding='hex'] 'hex', 'binary' or 'base64' @return {String} digest string
[ "digest", "file", "content", "." ]
d03e48b5e4b3deb022688fee59dd33a2b71819d0
https://github.com/iolo/node-toybox/blob/d03e48b5e4b3deb022688fee59dd33a2b71819d0/utils.js#L155-L157
train
samsonjs/batteries
lib/array.js
flatten
function flatten(a) { return a.reduce(function(flat, val) { if (val && typeof val.flatten === 'function') { flat = flat.concat(val.flatten()); } else if (Array.isArray(val)) { flat = flat.concat(flatten(val)); } else { flat.push(val); } return flat; }); }
javascript
function flatten(a) { return a.reduce(function(flat, val) { if (val && typeof val.flatten === 'function') { flat = flat.concat(val.flatten()); } else if (Array.isArray(val)) { flat = flat.concat(flatten(val)); } else { flat.push(val); } return flat; }); }
[ "function", "flatten", "(", "a", ")", "{", "return", "a", ".", "reduce", "(", "function", "(", "flat", ",", "val", ")", "{", "if", "(", "val", "&&", "typeof", "val", ".", "flatten", "===", "'function'", ")", "{", "flat", "=", "flat", ".", "concat", "(", "val", ".", "flatten", "(", ")", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "val", ")", ")", "{", "flat", "=", "flat", ".", "concat", "(", "flatten", "(", "val", ")", ")", ";", "}", "else", "{", "flat", ".", "push", "(", "val", ")", ";", "}", "return", "flat", ";", "}", ")", ";", "}" ]
Based on underscore.js's flatten
[ "Based", "on", "underscore", ".", "js", "s", "flatten" ]
48ca583338a89a9ec344cda7011da92dfc2f6d03
https://github.com/samsonjs/batteries/blob/48ca583338a89a9ec344cda7011da92dfc2f6d03/lib/array.js#L51-L64
train
Livefyre/stream-client
src/StreamClient.js
StreamClient
function StreamClient(options) { EventEmitter.call(this); SockJS = options.SockJS || SockJS; // Facilitate testing this.options = extend({}, options); // Clone this.options.debug = this.options.debug || false; this.options.retry = this.options.retry || 10; // Try to (re)connect 10 times before giving up this.options.retryTimeout = this.options.retryTimeout !== undefined ? this.options.retryTimeout : 500; this.options.protocol = this.options.protocol || window.location.protocol; if (this.options.protocol.slice(-1) !== ':') { this.options.protocol += ':'; } this.options.port = Number(this.options.port); if (!this.options.port) { if (this.options.protocol === "http:") { this.options.port = 80 } else if (this.options.protocol === "https:") { this.options.port = 443 } else { throw new Error("Invalid protocol and port"); } } this.options.endpoint = this.options.endpoint || '/stream'; if (!this.options.hostname && options.environment) { this.options.hostname = environments[options.environment]; } if (!this.options.hostname) { throw new Error("Stream Hostname is required"); } // SockJS - Stream Connection this.lfToken = null; this.conn = null; this.lastError = null; this.retryCount = 0; this.rebalancedTo = null; this.allProtocols = Object.keys(SockJS.getUtils().probeProtocols()); this.allProtocolsWithoutWS = this.allProtocols.slice(); this.allProtocolsWithoutWS.splice(this.allProtocols.indexOf("websocket"),1); this.streams = {}; // Stream State this.States = States; // Make accessible for testing this.state = new State(States.DISCONNECTED); this.state.on("change", this._stateChangeHandler.bind(this)); }
javascript
function StreamClient(options) { EventEmitter.call(this); SockJS = options.SockJS || SockJS; // Facilitate testing this.options = extend({}, options); // Clone this.options.debug = this.options.debug || false; this.options.retry = this.options.retry || 10; // Try to (re)connect 10 times before giving up this.options.retryTimeout = this.options.retryTimeout !== undefined ? this.options.retryTimeout : 500; this.options.protocol = this.options.protocol || window.location.protocol; if (this.options.protocol.slice(-1) !== ':') { this.options.protocol += ':'; } this.options.port = Number(this.options.port); if (!this.options.port) { if (this.options.protocol === "http:") { this.options.port = 80 } else if (this.options.protocol === "https:") { this.options.port = 443 } else { throw new Error("Invalid protocol and port"); } } this.options.endpoint = this.options.endpoint || '/stream'; if (!this.options.hostname && options.environment) { this.options.hostname = environments[options.environment]; } if (!this.options.hostname) { throw new Error("Stream Hostname is required"); } // SockJS - Stream Connection this.lfToken = null; this.conn = null; this.lastError = null; this.retryCount = 0; this.rebalancedTo = null; this.allProtocols = Object.keys(SockJS.getUtils().probeProtocols()); this.allProtocolsWithoutWS = this.allProtocols.slice(); this.allProtocolsWithoutWS.splice(this.allProtocols.indexOf("websocket"),1); this.streams = {}; // Stream State this.States = States; // Make accessible for testing this.state = new State(States.DISCONNECTED); this.state.on("change", this._stateChangeHandler.bind(this)); }
[ "function", "StreamClient", "(", "options", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "SockJS", "=", "options", ".", "SockJS", "||", "SockJS", ";", "this", ".", "options", "=", "extend", "(", "{", "}", ",", "options", ")", ";", "this", ".", "options", ".", "debug", "=", "this", ".", "options", ".", "debug", "||", "false", ";", "this", ".", "options", ".", "retry", "=", "this", ".", "options", ".", "retry", "||", "10", ";", "this", ".", "options", ".", "retryTimeout", "=", "this", ".", "options", ".", "retryTimeout", "!==", "undefined", "?", "this", ".", "options", ".", "retryTimeout", ":", "500", ";", "this", ".", "options", ".", "protocol", "=", "this", ".", "options", ".", "protocol", "||", "window", ".", "location", ".", "protocol", ";", "if", "(", "this", ".", "options", ".", "protocol", ".", "slice", "(", "-", "1", ")", "!==", "':'", ")", "{", "this", ".", "options", ".", "protocol", "+=", "':'", ";", "}", "this", ".", "options", ".", "port", "=", "Number", "(", "this", ".", "options", ".", "port", ")", ";", "if", "(", "!", "this", ".", "options", ".", "port", ")", "{", "if", "(", "this", ".", "options", ".", "protocol", "===", "\"http:\"", ")", "{", "this", ".", "options", ".", "port", "=", "80", "}", "else", "if", "(", "this", ".", "options", ".", "protocol", "===", "\"https:\"", ")", "{", "this", ".", "options", ".", "port", "=", "443", "}", "else", "{", "throw", "new", "Error", "(", "\"Invalid protocol and port\"", ")", ";", "}", "}", "this", ".", "options", ".", "endpoint", "=", "this", ".", "options", ".", "endpoint", "||", "'/stream'", ";", "if", "(", "!", "this", ".", "options", ".", "hostname", "&&", "options", ".", "environment", ")", "{", "this", ".", "options", ".", "hostname", "=", "environments", "[", "options", ".", "environment", "]", ";", "}", "if", "(", "!", "this", ".", "options", ".", "hostname", ")", "{", "throw", "new", "Error", "(", "\"Stream Hostname is required\"", ")", ";", "}", "this", ".", "lfToken", "=", "null", ";", "this", ".", "conn", "=", "null", ";", "this", ".", "lastError", "=", "null", ";", "this", ".", "retryCount", "=", "0", ";", "this", ".", "rebalancedTo", "=", "null", ";", "this", ".", "allProtocols", "=", "Object", ".", "keys", "(", "SockJS", ".", "getUtils", "(", ")", ".", "probeProtocols", "(", ")", ")", ";", "this", ".", "allProtocolsWithoutWS", "=", "this", ".", "allProtocols", ".", "slice", "(", ")", ";", "this", ".", "allProtocolsWithoutWS", ".", "splice", "(", "this", ".", "allProtocols", ".", "indexOf", "(", "\"websocket\"", ")", ",", "1", ")", ";", "this", ".", "streams", "=", "{", "}", ";", "this", ".", "States", "=", "States", ";", "this", ".", "state", "=", "new", "State", "(", "States", ".", "DISCONNECTED", ")", ";", "this", ".", "state", ".", "on", "(", "\"change\"", ",", "this", ".", "_stateChangeHandler", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Instantiates a Stream v4 client that is responsible for service discovery, login, connecting and streaming events for a given stream. The client will emit messages 'start', 'data', 'end', 'close', 'error'. @param options - Map containing hostname and optionally protocol, port and endpoint; retry and retryTimeout; debug @constructor
[ "Instantiates", "a", "Stream", "v4", "client", "that", "is", "responsible", "for", "service", "discovery", "login", "connecting", "and", "streaming", "events", "for", "a", "given", "stream", ".", "The", "client", "will", "emit", "messages", "start", "data", "end", "close", "error", "." ]
61638ab22723b9cacbc6fbb8790d650760f8252f
https://github.com/Livefyre/stream-client/blob/61638ab22723b9cacbc6fbb8790d650760f8252f/src/StreamClient.js#L77-L120
train
aliaksandr-master/node-verifier-schema
lib/loader.js
function (Schema, key) { if (!this.KEY_SCHEMA_REG_EXP.test(key)) { throw new Error('invalid schema key format. must be match with ' + this.KEY_SCHEMA_REG_EXP.source); } var schema = new Schema(); key.replace(this.KEY_SCHEMA_REG_EXP, this._patchFormat(schema)); return schema; }
javascript
function (Schema, key) { if (!this.KEY_SCHEMA_REG_EXP.test(key)) { throw new Error('invalid schema key format. must be match with ' + this.KEY_SCHEMA_REG_EXP.source); } var schema = new Schema(); key.replace(this.KEY_SCHEMA_REG_EXP, this._patchFormat(schema)); return schema; }
[ "function", "(", "Schema", ",", "key", ")", "{", "if", "(", "!", "this", ".", "KEY_SCHEMA_REG_EXP", ".", "test", "(", "key", ")", ")", "{", "throw", "new", "Error", "(", "'invalid schema key format. must be match with '", "+", "this", ".", "KEY_SCHEMA_REG_EXP", ".", "source", ")", ";", "}", "var", "schema", "=", "new", "Schema", "(", ")", ";", "key", ".", "replace", "(", "this", ".", "KEY_SCHEMA_REG_EXP", ",", "this", ".", "_patchFormat", "(", "schema", ")", ")", ";", "return", "schema", ";", "}" ]
parse schema hash key @method @private @param {Schema#constructor} Schema @param {String} key @returns {Schema}
[ "parse", "schema", "hash", "key" ]
dc49df3c4703928bcfd7447a59cdd70bafac21b0
https://github.com/aliaksandr-master/node-verifier-schema/blob/dc49df3c4703928bcfd7447a59cdd70bafac21b0/lib/loader.js#L23-L33
train
aliaksandr-master/node-verifier-schema
lib/loader.js
function (Schema, fieldName, parent) { var schema = new Schema(); var name = fieldName.replace(this.KEY_FIELD_REG_EXP, this._patchFormat(schema)); return parent.field(name).like(schema); }
javascript
function (Schema, fieldName, parent) { var schema = new Schema(); var name = fieldName.replace(this.KEY_FIELD_REG_EXP, this._patchFormat(schema)); return parent.field(name).like(schema); }
[ "function", "(", "Schema", ",", "fieldName", ",", "parent", ")", "{", "var", "schema", "=", "new", "Schema", "(", ")", ";", "var", "name", "=", "fieldName", ".", "replace", "(", "this", ".", "KEY_FIELD_REG_EXP", ",", "this", ".", "_patchFormat", "(", "schema", ")", ")", ";", "return", "parent", ".", "field", "(", "name", ")", ".", "like", "(", "schema", ")", ";", "}" ]
parse fieldKey to field schema. add field schema to parent schema @method @private @param {String#constructor} Schema @param {String} fieldName @param {Schema} parent @returns {Schema} child field schema
[ "parse", "fieldKey", "to", "field", "schema", ".", "add", "field", "schema", "to", "parent", "schema" ]
dc49df3c4703928bcfd7447a59cdd70bafac21b0
https://github.com/aliaksandr-master/node-verifier-schema/blob/dc49df3c4703928bcfd7447a59cdd70bafac21b0/lib/loader.js#L77-L82
train
deathcap/block-models
demo.js
function(gl, vertices, uv) { var verticesBuf = createBuffer(gl, new Float32Array(vertices)) var uvBuf = createBuffer(gl, new Float32Array(uv)) var mesh = createVAO(gl, [ { buffer: verticesBuf, size: 3 }, { buffer: uvBuf, size: 2 } ]) mesh.length = vertices.length/3 return mesh }
javascript
function(gl, vertices, uv) { var verticesBuf = createBuffer(gl, new Float32Array(vertices)) var uvBuf = createBuffer(gl, new Float32Array(uv)) var mesh = createVAO(gl, [ { buffer: verticesBuf, size: 3 }, { buffer: uvBuf, size: 2 } ]) mesh.length = vertices.length/3 return mesh }
[ "function", "(", "gl", ",", "vertices", ",", "uv", ")", "{", "var", "verticesBuf", "=", "createBuffer", "(", "gl", ",", "new", "Float32Array", "(", "vertices", ")", ")", "var", "uvBuf", "=", "createBuffer", "(", "gl", ",", "new", "Float32Array", "(", "uv", ")", ")", "var", "mesh", "=", "createVAO", "(", "gl", ",", "[", "{", "buffer", ":", "verticesBuf", ",", "size", ":", "3", "}", ",", "{", "buffer", ":", "uvBuf", ",", "size", ":", "2", "}", "]", ")", "mesh", ".", "length", "=", "vertices", ".", "length", "/", "3", "return", "mesh", "}" ]
create a mesh ready for rendering
[ "create", "a", "mesh", "ready", "for", "rendering" ]
70e9c3becfcbf367e31e5b158ea8766c2ffafb5e
https://github.com/deathcap/block-models/blob/70e9c3becfcbf367e31e5b158ea8766c2ffafb5e/demo.js#L54-L70
train
Industryswarm/isnode-mod-data
lib/mongodb/mongodb-core/lib/uri_parser.js
parseQueryString
function parseQueryString(query, options) { const result = {}; let parsedQueryString = qs.parse(query); for (const key in parsedQueryString) { const value = parsedQueryString[key]; if (value === '' || value == null) { throw new MongoParseError('Incomplete key value pair for option'); } const normalizedKey = key.toLowerCase(); const parsedValue = parseQueryStringItemValue(normalizedKey, value); applyConnectionStringOption(result, normalizedKey, parsedValue, options); } // special cases for known deprecated options if (result.wtimeout && result.wtimeoutms) { delete result.wtimeout; console.warn('Unsupported option `wtimeout` specified'); } return Object.keys(result).length ? result : null; }
javascript
function parseQueryString(query, options) { const result = {}; let parsedQueryString = qs.parse(query); for (const key in parsedQueryString) { const value = parsedQueryString[key]; if (value === '' || value == null) { throw new MongoParseError('Incomplete key value pair for option'); } const normalizedKey = key.toLowerCase(); const parsedValue = parseQueryStringItemValue(normalizedKey, value); applyConnectionStringOption(result, normalizedKey, parsedValue, options); } // special cases for known deprecated options if (result.wtimeout && result.wtimeoutms) { delete result.wtimeout; console.warn('Unsupported option `wtimeout` specified'); } return Object.keys(result).length ? result : null; }
[ "function", "parseQueryString", "(", "query", ",", "options", ")", "{", "const", "result", "=", "{", "}", ";", "let", "parsedQueryString", "=", "qs", ".", "parse", "(", "query", ")", ";", "for", "(", "const", "key", "in", "parsedQueryString", ")", "{", "const", "value", "=", "parsedQueryString", "[", "key", "]", ";", "if", "(", "value", "===", "''", "||", "value", "==", "null", ")", "{", "throw", "new", "MongoParseError", "(", "'Incomplete key value pair for option'", ")", ";", "}", "const", "normalizedKey", "=", "key", ".", "toLowerCase", "(", ")", ";", "const", "parsedValue", "=", "parseQueryStringItemValue", "(", "normalizedKey", ",", "value", ")", ";", "applyConnectionStringOption", "(", "result", ",", "normalizedKey", ",", "parsedValue", ",", "options", ")", ";", "}", "if", "(", "result", ".", "wtimeout", "&&", "result", ".", "wtimeoutms", ")", "{", "delete", "result", ".", "wtimeout", ";", "console", ".", "warn", "(", "'Unsupported option `wtimeout` specified'", ")", ";", "}", "return", "Object", ".", "keys", "(", "result", ")", ".", "length", "?", "result", ":", "null", ";", "}" ]
Parses a query string according the connection string spec. @param {String} query The query string to parse @param {object} [options] The options used for options parsing @return {Object|Error} The parsed query string as an object, or an error if one was encountered
[ "Parses", "a", "query", "string", "according", "the", "connection", "string", "spec", "." ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/uri_parser.js#L363-L385
train
darrencruse/sugarlisp-match
matchexpr-gentab.js
varMatchingAny
function varMatchingAny(varnameAtom) { return sl.list(sl.atom("::", {token: varnameAtom}), varnameAtom, sl.str("any")); }
javascript
function varMatchingAny(varnameAtom) { return sl.list(sl.atom("::", {token: varnameAtom}), varnameAtom, sl.str("any")); }
[ "function", "varMatchingAny", "(", "varnameAtom", ")", "{", "return", "sl", ".", "list", "(", "sl", ".", "atom", "(", "\"::\"", ",", "{", "token", ":", "varnameAtom", "}", ")", ",", "varnameAtom", ",", "sl", ".", "str", "(", "\"any\"", ")", ")", ";", "}" ]
return forms for a var matching anything
[ "return", "forms", "for", "a", "var", "matching", "anything" ]
72073f96af040b4cae4a1649a6d0c4c96ec301cb
https://github.com/darrencruse/sugarlisp-match/blob/72073f96af040b4cae4a1649a6d0c4c96ec301cb/matchexpr-gentab.js#L102-L104
train
kirchrath/tpaxx
client/packages/local/tpaxx-core/.sencha/package/Boot.js
function (url) { // *WARNING WARNING WARNING* // This method yields the most correct result we can get but it is EXPENSIVE! // In ALL browsers! When called multiple times in a sequence, as if when // we resolve dependencies for entries, it will cause garbage collection events // and overall painful slowness. This is why we try to avoid it as much as we can. // // @TODO - see if we need this fallback logic // http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue resolverEl.href = url; var ret = resolverEl.href, dc = _config.disableCachingParam, pos = dc ? ret.indexOf(dc + '=') : -1, c, end; // If we have a _dc query parameter we need to remove it from the canonical // URL. if (pos > 0 && ((c = ret.charAt(pos - 1)) === '?' || c === '&')) { end = ret.indexOf('&', pos); end = (end < 0) ? '' : ret.substring(end); if (end && c === '?') { ++pos; // keep the '?' end = end.substring(1); // remove the '&' } ret = ret.substring(0, pos - 1) + end; } return ret; }
javascript
function (url) { // *WARNING WARNING WARNING* // This method yields the most correct result we can get but it is EXPENSIVE! // In ALL browsers! When called multiple times in a sequence, as if when // we resolve dependencies for entries, it will cause garbage collection events // and overall painful slowness. This is why we try to avoid it as much as we can. // // @TODO - see if we need this fallback logic // http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue resolverEl.href = url; var ret = resolverEl.href, dc = _config.disableCachingParam, pos = dc ? ret.indexOf(dc + '=') : -1, c, end; // If we have a _dc query parameter we need to remove it from the canonical // URL. if (pos > 0 && ((c = ret.charAt(pos - 1)) === '?' || c === '&')) { end = ret.indexOf('&', pos); end = (end < 0) ? '' : ret.substring(end); if (end && c === '?') { ++pos; // keep the '?' end = end.substring(1); // remove the '&' } ret = ret.substring(0, pos - 1) + end; } return ret; }
[ "function", "(", "url", ")", "{", "resolverEl", ".", "href", "=", "url", ";", "var", "ret", "=", "resolverEl", ".", "href", ",", "dc", "=", "_config", ".", "disableCachingParam", ",", "pos", "=", "dc", "?", "ret", ".", "indexOf", "(", "dc", "+", "'='", ")", ":", "-", "1", ",", "c", ",", "end", ";", "if", "(", "pos", ">", "0", "&&", "(", "(", "c", "=", "ret", ".", "charAt", "(", "pos", "-", "1", ")", ")", "===", "'?'", "||", "c", "===", "'&'", ")", ")", "{", "end", "=", "ret", ".", "indexOf", "(", "'&'", ",", "pos", ")", ";", "end", "=", "(", "end", "<", "0", ")", "?", "''", ":", "ret", ".", "substring", "(", "end", ")", ";", "if", "(", "end", "&&", "c", "===", "'?'", ")", "{", "++", "pos", ";", "end", "=", "end", ".", "substring", "(", "1", ")", ";", "}", "ret", "=", "ret", ".", "substring", "(", "0", ",", "pos", "-", "1", ")", "+", "end", ";", "}", "return", "ret", ";", "}" ]
This method returns a canonical URL for the given URL. For example, the following all produce the same canonical URL (which is the last one): http://foo.com/bar/baz/zoo/derp/../../goo/Thing.js?_dc=12345 http://foo.com/bar/baz/zoo/derp/../../goo/Thing.js http://foo.com/bar/baz/zoo/derp/../jazz/../../goo/Thing.js http://foo.com/bar/baz/zoo/../goo/Thing.js http://foo.com/bar/baz/goo/Thing.js @private
[ "This", "method", "returns", "a", "canonical", "URL", "for", "the", "given", "URL", "." ]
3ccc5b77459d093e823d740ddc53feefb12a9344
https://github.com/kirchrath/tpaxx/blob/3ccc5b77459d093e823d740ddc53feefb12a9344/client/packages/local/tpaxx-core/.sencha/package/Boot.js#L623-L652
train
kirchrath/tpaxx
client/packages/local/tpaxx-core/.sencha/package/Boot.js
function (name, value) { if (typeof name === 'string') { Boot.config[name] = value; } else { for (var s in name) { Boot.setConfig(s, name[s]); } } return Boot; }
javascript
function (name, value) { if (typeof name === 'string') { Boot.config[name] = value; } else { for (var s in name) { Boot.setConfig(s, name[s]); } } return Boot; }
[ "function", "(", "name", ",", "value", ")", "{", "if", "(", "typeof", "name", "===", "'string'", ")", "{", "Boot", ".", "config", "[", "name", "]", "=", "value", ";", "}", "else", "{", "for", "(", "var", "s", "in", "name", ")", "{", "Boot", ".", "setConfig", "(", "s", ",", "name", "[", "s", "]", ")", ";", "}", "}", "return", "Boot", ";", "}" ]
Set the configuration. @param {Object} config The config object to override the default values. @return {Ext.Boot} this
[ "Set", "the", "configuration", "." ]
3ccc5b77459d093e823d740ddc53feefb12a9344
https://github.com/kirchrath/tpaxx/blob/3ccc5b77459d093e823d740ddc53feefb12a9344/client/packages/local/tpaxx-core/.sencha/package/Boot.js#L668-L677
train
kirchrath/tpaxx
client/packages/local/tpaxx-core/.sencha/package/Boot.js
function (indexMap, loadOrder) { // In older versions indexMap was an object instead of a sparse array if (!('length' in indexMap)) { var indexArray = [], index; for (index in indexMap) { if (!isNaN(+index)) { indexArray[+index] = indexMap[index]; } } indexMap = indexArray; } return Request.prototype.getPathsFromIndexes(indexMap, loadOrder); }
javascript
function (indexMap, loadOrder) { // In older versions indexMap was an object instead of a sparse array if (!('length' in indexMap)) { var indexArray = [], index; for (index in indexMap) { if (!isNaN(+index)) { indexArray[+index] = indexMap[index]; } } indexMap = indexArray; } return Request.prototype.getPathsFromIndexes(indexMap, loadOrder); }
[ "function", "(", "indexMap", ",", "loadOrder", ")", "{", "if", "(", "!", "(", "'length'", "in", "indexMap", ")", ")", "{", "var", "indexArray", "=", "[", "]", ",", "index", ";", "for", "(", "index", "in", "indexMap", ")", "{", "if", "(", "!", "isNaN", "(", "+", "index", ")", ")", "{", "indexArray", "[", "+", "index", "]", "=", "indexMap", "[", "index", "]", ";", "}", "}", "indexMap", "=", "indexArray", ";", "}", "return", "Request", ".", "prototype", ".", "getPathsFromIndexes", "(", "indexMap", ",", "loadOrder", ")", ";", "}" ]
this is a helper function used by Ext.Loader to flush out 'uses' arrays for classes in some Ext versions
[ "this", "is", "a", "helper", "function", "used", "by", "Ext", ".", "Loader", "to", "flush", "out", "uses", "arrays", "for", "classes", "in", "some", "Ext", "versions" ]
3ccc5b77459d093e823d740ddc53feefb12a9344
https://github.com/kirchrath/tpaxx/blob/3ccc5b77459d093e823d740ddc53feefb12a9344/client/packages/local/tpaxx-core/.sencha/package/Boot.js#L821-L837
train
findhit/findhit-promise
lib/class.js
function ( fn, context ) { // Initialize variables this.state = Promise.STATE.INITIALIZED; this.handlers = []; this.value = fn; // Rebind control functions to be run always on this promise this.resolve = this.resolve.bind( this ); this.fulfill = this.fulfill.bind( this ); this.reject = this.reject.bind( this ); // Set fn and context if ( fn ) { if ( typeof fn !== 'function' ) throw new TypeError("fn is not a function"); this.fn = fn; this.context = context || this; this.run(); } return this; }
javascript
function ( fn, context ) { // Initialize variables this.state = Promise.STATE.INITIALIZED; this.handlers = []; this.value = fn; // Rebind control functions to be run always on this promise this.resolve = this.resolve.bind( this ); this.fulfill = this.fulfill.bind( this ); this.reject = this.reject.bind( this ); // Set fn and context if ( fn ) { if ( typeof fn !== 'function' ) throw new TypeError("fn is not a function"); this.fn = fn; this.context = context || this; this.run(); } return this; }
[ "function", "(", "fn", ",", "context", ")", "{", "this", ".", "state", "=", "Promise", ".", "STATE", ".", "INITIALIZED", ";", "this", ".", "handlers", "=", "[", "]", ";", "this", ".", "value", "=", "fn", ";", "this", ".", "resolve", "=", "this", ".", "resolve", ".", "bind", "(", "this", ")", ";", "this", ".", "fulfill", "=", "this", ".", "fulfill", ".", "bind", "(", "this", ")", ";", "this", ".", "reject", "=", "this", ".", "reject", ".", "bind", "(", "this", ")", ";", "if", "(", "fn", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "\"fn is not a function\"", ")", ";", "this", ".", "fn", "=", "fn", ";", "this", ".", "context", "=", "context", "||", "this", ";", "this", ".", "run", "(", ")", ";", "}", "return", "this", ";", "}" ]
INITIALIZE AND DESTROY METHODS
[ "INITIALIZE", "AND", "DESTROY", "METHODS" ]
828ccc151dfce8bdce673296f967e2ad8cd965e9
https://github.com/findhit/findhit-promise/blob/828ccc151dfce8bdce673296f967e2ad8cd965e9/lib/class.js#L26-L50
train
findhit/findhit-promise
lib/class.js
function ( x ) { if ( Util.is.Error( x ) ) { return this.reject( x ); } // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure try { if ( x === this ) { throw new TypeError('A promise cannot be resolved with itself.'); } if ( Util.is.Promise( x ) || ( x !== null && Util.is.Object( x ) && Util.is.Function( x.then ) ) ) { Promise.doResolve( x.then.bind( x ), this.resolve, this.reject ); return this; } if ( Util.is.Function( x ) ) { Promise.doResolve( x, this.resolve, this.reject ); return this; } this.fulfill( x ); } catch ( error ) { return this.reject( error ); } return this; }
javascript
function ( x ) { if ( Util.is.Error( x ) ) { return this.reject( x ); } // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure try { if ( x === this ) { throw new TypeError('A promise cannot be resolved with itself.'); } if ( Util.is.Promise( x ) || ( x !== null && Util.is.Object( x ) && Util.is.Function( x.then ) ) ) { Promise.doResolve( x.then.bind( x ), this.resolve, this.reject ); return this; } if ( Util.is.Function( x ) ) { Promise.doResolve( x, this.resolve, this.reject ); return this; } this.fulfill( x ); } catch ( error ) { return this.reject( error ); } return this; }
[ "function", "(", "x", ")", "{", "if", "(", "Util", ".", "is", ".", "Error", "(", "x", ")", ")", "{", "return", "this", ".", "reject", "(", "x", ")", ";", "}", "try", "{", "if", "(", "x", "===", "this", ")", "{", "throw", "new", "TypeError", "(", "'A promise cannot be resolved with itself.'", ")", ";", "}", "if", "(", "Util", ".", "is", ".", "Promise", "(", "x", ")", "||", "(", "x", "!==", "null", "&&", "Util", ".", "is", ".", "Object", "(", "x", ")", "&&", "Util", ".", "is", ".", "Function", "(", "x", ".", "then", ")", ")", ")", "{", "Promise", ".", "doResolve", "(", "x", ".", "then", ".", "bind", "(", "x", ")", ",", "this", ".", "resolve", ",", "this", ".", "reject", ")", ";", "return", "this", ";", "}", "if", "(", "Util", ".", "is", ".", "Function", "(", "x", ")", ")", "{", "Promise", ".", "doResolve", "(", "x", ",", "this", ".", "resolve", ",", "this", ".", "reject", ")", ";", "return", "this", ";", "}", "this", ".", "fulfill", "(", "x", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "this", ".", "reject", "(", "error", ")", ";", "}", "return", "this", ";", "}" ]
INNER API METHODS
[ "INNER", "API", "METHODS" ]
828ccc151dfce8bdce673296f967e2ad8cd965e9
https://github.com/findhit/findhit-promise/blob/828ccc151dfce8bdce673296f967e2ad8cd965e9/lib/class.js#L56-L88
train
findhit/findhit-promise
lib/class.js
function ( onRejected ) { if ( onRejected && typeof onRejected !== 'function' ) throw new TypeError("onFulfilled is not a function"); var promise = this, handler = new Promise.Handler({ onRejected: onRejected, }); // Catch on entire promise chain while( promise ) { handler.handle( promise ); promise = promise.parent; } return this; }
javascript
function ( onRejected ) { if ( onRejected && typeof onRejected !== 'function' ) throw new TypeError("onFulfilled is not a function"); var promise = this, handler = new Promise.Handler({ onRejected: onRejected, }); // Catch on entire promise chain while( promise ) { handler.handle( promise ); promise = promise.parent; } return this; }
[ "function", "(", "onRejected", ")", "{", "if", "(", "onRejected", "&&", "typeof", "onRejected", "!==", "'function'", ")", "throw", "new", "TypeError", "(", "\"onFulfilled is not a function\"", ")", ";", "var", "promise", "=", "this", ",", "handler", "=", "new", "Promise", ".", "Handler", "(", "{", "onRejected", ":", "onRejected", ",", "}", ")", ";", "while", "(", "promise", ")", "{", "handler", ".", "handle", "(", "promise", ")", ";", "promise", "=", "promise", ".", "parent", ";", "}", "return", "this", ";", "}" ]
OUTER API METHODS
[ "OUTER", "API", "METHODS" ]
828ccc151dfce8bdce673296f967e2ad8cd965e9
https://github.com/findhit/findhit-promise/blob/828ccc151dfce8bdce673296f967e2ad8cd965e9/lib/class.js#L246-L261
train
nachos/native-builder
lib/index.js
resolve
function resolve() { return whichNativeNodish('..') .then(function (results) { var nwVersion = results.nwVersion; var asVersion = results.asVersion; debug('which-native-nodish output: %j', results); var prefix = ''; var target = ''; var debugArg = process.env.BUILD_DEBUG ? ' --debug' : ''; var builder = 'node-gyp'; var distUrl = ''; if (asVersion) { prefix = (process.platform === 'win32' ? 'SET USERPROFILE=%USERPROFILE%\\.electron-gyp&&' : 'HOME=~/.electron-gyp'); target = '--target=' + asVersion; distUrl = '--dist-url=https://atom.io/download/atom-shell'; } else if (nwVersion) { builder = 'nw-gyp'; target = '--target=' + nwVersion; } builder = '"' + path.resolve(__dirname, '..', 'node_modules', '.bin', builder) + '"'; return [prefix, builder, 'rebuild', target, debugArg, distUrl] .join(' ').trim(); }); }
javascript
function resolve() { return whichNativeNodish('..') .then(function (results) { var nwVersion = results.nwVersion; var asVersion = results.asVersion; debug('which-native-nodish output: %j', results); var prefix = ''; var target = ''; var debugArg = process.env.BUILD_DEBUG ? ' --debug' : ''; var builder = 'node-gyp'; var distUrl = ''; if (asVersion) { prefix = (process.platform === 'win32' ? 'SET USERPROFILE=%USERPROFILE%\\.electron-gyp&&' : 'HOME=~/.electron-gyp'); target = '--target=' + asVersion; distUrl = '--dist-url=https://atom.io/download/atom-shell'; } else if (nwVersion) { builder = 'nw-gyp'; target = '--target=' + nwVersion; } builder = '"' + path.resolve(__dirname, '..', 'node_modules', '.bin', builder) + '"'; return [prefix, builder, 'rebuild', target, debugArg, distUrl] .join(' ').trim(); }); }
[ "function", "resolve", "(", ")", "{", "return", "whichNativeNodish", "(", "'..'", ")", ".", "then", "(", "function", "(", "results", ")", "{", "var", "nwVersion", "=", "results", ".", "nwVersion", ";", "var", "asVersion", "=", "results", ".", "asVersion", ";", "debug", "(", "'which-native-nodish output: %j'", ",", "results", ")", ";", "var", "prefix", "=", "''", ";", "var", "target", "=", "''", ";", "var", "debugArg", "=", "process", ".", "env", ".", "BUILD_DEBUG", "?", "' --debug'", ":", "''", ";", "var", "builder", "=", "'node-gyp'", ";", "var", "distUrl", "=", "''", ";", "if", "(", "asVersion", ")", "{", "prefix", "=", "(", "process", ".", "platform", "===", "'win32'", "?", "'SET USERPROFILE=%USERPROFILE%\\\\.electron-gyp&&'", ":", "\\\\", ")", ";", "'HOME=~/.electron-gyp'", "target", "=", "'--target='", "+", "asVersion", ";", "}", "else", "distUrl", "=", "'--dist-url=https://atom.io/download/atom-shell'", ";", "if", "(", "nwVersion", ")", "{", "builder", "=", "'nw-gyp'", ";", "target", "=", "'--target='", "+", "nwVersion", ";", "}", "builder", "=", "'\"'", "+", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ",", "'node_modules'", ",", "'.bin'", ",", "builder", ")", "+", "'\"'", ";", "}", ")", ";", "}" ]
Resolve the build command @returns {Q.promise} The build command
[ "Resolve", "the", "build", "command" ]
2ce8ed7485066f4d3ead1d7d5df0ae59e410fde3
https://github.com/nachos/native-builder/blob/2ce8ed7485066f4d3ead1d7d5df0ae59e410fde3/lib/index.js#L13-L45
train
BurntCaramel/react-sow
rgba.js
rgba
function rgba(r, g, b, a) { return new RGBA(r, g, b, a); }
javascript
function rgba(r, g, b, a) { return new RGBA(r, g, b, a); }
[ "function", "rgba", "(", "r", ",", "g", ",", "b", ",", "a", ")", "{", "return", "new", "RGBA", "(", "r", ",", "g", ",", "b", ",", "a", ")", ";", "}" ]
We want the underlying RGBA type to be an implementation detail
[ "We", "want", "the", "underlying", "RGBA", "type", "to", "be", "an", "implementation", "detail" ]
1eee1227460deb058035f3d3a22cdafead600492
https://github.com/BurntCaramel/react-sow/blob/1eee1227460deb058035f3d3a22cdafead600492/rgba.js#L36-L38
train
leolmi/install-here
util.js
function(cb) { cb = cb || _.noop; const self = this; self._step = 0; if (self._stack.length<=0) return cb(); (function next() { const step = _getStep(self); if (!step) { cb(); } else if (_.isFunction(step)) { step.call(self, next); } else if (_.isFunction(step[self._exec])) { step[self._exec](next); } })(); }
javascript
function(cb) { cb = cb || _.noop; const self = this; self._step = 0; if (self._stack.length<=0) return cb(); (function next() { const step = _getStep(self); if (!step) { cb(); } else if (_.isFunction(step)) { step.call(self, next); } else if (_.isFunction(step[self._exec])) { step[self._exec](next); } })(); }
[ "function", "(", "cb", ")", "{", "cb", "=", "cb", "||", "_", ".", "noop", ";", "const", "self", "=", "this", ";", "self", ".", "_step", "=", "0", ";", "if", "(", "self", ".", "_stack", ".", "length", "<=", "0", ")", "return", "cb", "(", ")", ";", "(", "function", "next", "(", ")", "{", "const", "step", "=", "_getStep", "(", "self", ")", ";", "if", "(", "!", "step", ")", "{", "cb", "(", ")", ";", "}", "else", "if", "(", "_", ".", "isFunction", "(", "step", ")", ")", "{", "step", ".", "call", "(", "self", ",", "next", ")", ";", "}", "else", "if", "(", "_", ".", "isFunction", "(", "step", "[", "self", ".", "_exec", "]", ")", ")", "{", "step", "[", "self", ".", "_exec", "]", "(", "next", ")", ";", "}", "}", ")", "(", ")", ";", "}" ]
Avvia lo stack di elementi @param {function} [cb] @returns {*}
[ "Avvia", "lo", "stack", "di", "elementi" ]
ef6532c711737e295753f47b202a5ad3b05b34f3
https://github.com/leolmi/install-here/blob/ef6532c711737e295753f47b202a5ad3b05b34f3/util.js#L33-L48
train
YannickBochatay/JSYG.Menu
JSYG.Menu.js
Menu
function Menu(arg,opt) { if ($.isPlainObject(arg) || Array.isArray(arg)) { opt = arg; arg = null; } /** * Conteneur du menu contextuel */ if (!arg) arg = document.createElement('ul'); if (arg) this.container = $(arg)[0]; /** * Tableau d'objets MenuItem définissant la liste des éléments du menu */ this.list = []; /** * Liste des séparateurs d'éléments */ this.dividers = []; this.keyboardCtrls = new KeyboardCtrls(this); if (opt) this.set(opt); }
javascript
function Menu(arg,opt) { if ($.isPlainObject(arg) || Array.isArray(arg)) { opt = arg; arg = null; } /** * Conteneur du menu contextuel */ if (!arg) arg = document.createElement('ul'); if (arg) this.container = $(arg)[0]; /** * Tableau d'objets MenuItem définissant la liste des éléments du menu */ this.list = []; /** * Liste des séparateurs d'éléments */ this.dividers = []; this.keyboardCtrls = new KeyboardCtrls(this); if (opt) this.set(opt); }
[ "function", "Menu", "(", "arg", ",", "opt", ")", "{", "if", "(", "$", ".", "isPlainObject", "(", "arg", ")", "||", "Array", ".", "isArray", "(", "arg", ")", ")", "{", "opt", "=", "arg", ";", "arg", "=", "null", ";", "}", "if", "(", "!", "arg", ")", "arg", "=", "document", ".", "createElement", "(", "'ul'", ")", ";", "if", "(", "arg", ")", "this", ".", "container", "=", "$", "(", "arg", ")", "[", "0", "]", ";", "this", ".", "list", "=", "[", "]", ";", "this", ".", "dividers", "=", "[", "]", ";", "this", ".", "keyboardCtrls", "=", "new", "KeyboardCtrls", "(", "this", ")", ";", "if", "(", "opt", ")", "this", ".", "set", "(", "opt", ")", ";", "}" ]
Constructeur de menus @param {Object} opt optionnel, objet définissant les options. Si défini, le menu est activé implicitement. @returns {Menu}
[ "Constructeur", "de", "menus" ]
39cd640f9b1d8c1c5ff01a54eb1b0de1f8fd6c11
https://github.com/YannickBochatay/JSYG.Menu/blob/39cd640f9b1d8c1c5ff01a54eb1b0de1f8fd6c11/JSYG.Menu.js#L152-L174
train
jeremyosborne/llogger
llogger.js
function() { var currentIndent = []; var i; for (i = 0; i < this._currentIndent; i++) { currentIndent[i] = this._singleIndent; } return currentIndent.join(""); }
javascript
function() { var currentIndent = []; var i; for (i = 0; i < this._currentIndent; i++) { currentIndent[i] = this._singleIndent; } return currentIndent.join(""); }
[ "function", "(", ")", "{", "var", "currentIndent", "=", "[", "]", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "_currentIndent", ";", "i", "++", ")", "{", "currentIndent", "[", "i", "]", "=", "this", ".", "_singleIndent", ";", "}", "return", "currentIndent", ".", "join", "(", "\"\"", ")", ";", "}" ]
Return the current amount of indentation. @return {String} The current indentation. @private
[ "Return", "the", "current", "amount", "of", "indentation", "." ]
e0d820215de9b84e815ffba8e78b18bb84f58ec7
https://github.com/jeremyosborne/llogger/blob/e0d820215de9b84e815ffba8e78b18bb84f58ec7/llogger.js#L75-L82
train
jeremyosborne/llogger
llogger.js
function() { if (!this.quiet()) { var prefix = this._callerInfo() + this._getIndent() + "#".magenta.bold; var args = argsToArray(arguments).map(function(a) { if (typeof a != "string") { a = util.inspect(a); } return a.toUpperCase().magenta.bold.inverse; }).join(" "); console.log.call(console, prefix, args); } }
javascript
function() { if (!this.quiet()) { var prefix = this._callerInfo() + this._getIndent() + "#".magenta.bold; var args = argsToArray(arguments).map(function(a) { if (typeof a != "string") { a = util.inspect(a); } return a.toUpperCase().magenta.bold.inverse; }).join(" "); console.log.call(console, prefix, args); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "quiet", "(", ")", ")", "{", "var", "prefix", "=", "this", ".", "_callerInfo", "(", ")", "+", "this", ".", "_getIndent", "(", ")", "+", "\"#\"", ".", "magenta", ".", "bold", ";", "var", "args", "=", "argsToArray", "(", "arguments", ")", ".", "map", "(", "function", "(", "a", ")", "{", "if", "(", "typeof", "a", "!=", "\"string\"", ")", "{", "a", "=", "util", ".", "inspect", "(", "a", ")", ";", "}", "return", "a", ".", "toUpperCase", "(", ")", ".", "magenta", ".", "bold", ".", "inverse", ";", "}", ")", ".", "join", "(", "\" \"", ")", ";", "console", ".", "log", ".", "call", "(", "console", ",", "prefix", ",", "args", ")", ";", "}", "}" ]
Print message as a stylized diagnostic section header.
[ "Print", "message", "as", "a", "stylized", "diagnostic", "section", "header", "." ]
e0d820215de9b84e815ffba8e78b18bb84f58ec7
https://github.com/jeremyosborne/llogger/blob/e0d820215de9b84e815ffba8e78b18bb84f58ec7/llogger.js#L111-L122
train
jeremyosborne/llogger
llogger.js
function() { if (!this.quiet()) { var hr = []; for (var i = 0; i < 79; i++) { hr[i] = "-"; } console.log(this._callerInfo() + this._getIndent() + hr.join("").green); } }
javascript
function() { if (!this.quiet()) { var hr = []; for (var i = 0; i < 79; i++) { hr[i] = "-"; } console.log(this._callerInfo() + this._getIndent() + hr.join("").green); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "quiet", "(", ")", ")", "{", "var", "hr", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "79", ";", "i", "++", ")", "{", "hr", "[", "i", "]", "=", "\"-\"", ";", "}", "console", ".", "log", "(", "this", ".", "_callerInfo", "(", ")", "+", "this", ".", "_getIndent", "(", ")", "+", "hr", ".", "join", "(", "\"\"", ")", ".", "green", ")", ";", "}", "}" ]
Prints out an 80 character horizontal rule.
[ "Prints", "out", "an", "80", "character", "horizontal", "rule", "." ]
e0d820215de9b84e815ffba8e78b18bb84f58ec7
https://github.com/jeremyosborne/llogger/blob/e0d820215de9b84e815ffba8e78b18bb84f58ec7/llogger.js#L217-L225
train
greggman/hft-sample-ui
src/hft/scripts/misc/input.js
function(keyDownFn, keyUpFn) { var g_keyState = {}; var g_oldKeyState = {}; var updateKey = function(keyCode, state) { g_keyState[keyCode] = state; if (g_oldKeyState !== g_keyState) { g_oldKeyState = state; if (state) { keyDownFn(keyCode); } else { keyUpFn(keyCode); } } }; var keyUp = function(event) { updateKey(event.keyCode, false); }; var keyDown = function(event) { updateKey(event.keyCode, true); }; window.addEventListener("keyup", keyUp, false); window.addEventListener("keydown", keyDown, false); }
javascript
function(keyDownFn, keyUpFn) { var g_keyState = {}; var g_oldKeyState = {}; var updateKey = function(keyCode, state) { g_keyState[keyCode] = state; if (g_oldKeyState !== g_keyState) { g_oldKeyState = state; if (state) { keyDownFn(keyCode); } else { keyUpFn(keyCode); } } }; var keyUp = function(event) { updateKey(event.keyCode, false); }; var keyDown = function(event) { updateKey(event.keyCode, true); }; window.addEventListener("keyup", keyUp, false); window.addEventListener("keydown", keyDown, false); }
[ "function", "(", "keyDownFn", ",", "keyUpFn", ")", "{", "var", "g_keyState", "=", "{", "}", ";", "var", "g_oldKeyState", "=", "{", "}", ";", "var", "updateKey", "=", "function", "(", "keyCode", ",", "state", ")", "{", "g_keyState", "[", "keyCode", "]", "=", "state", ";", "if", "(", "g_oldKeyState", "!==", "g_keyState", ")", "{", "g_oldKeyState", "=", "state", ";", "if", "(", "state", ")", "{", "keyDownFn", "(", "keyCode", ")", ";", "}", "else", "{", "keyUpFn", "(", "keyCode", ")", ";", "}", "}", "}", ";", "var", "keyUp", "=", "function", "(", "event", ")", "{", "updateKey", "(", "event", ".", "keyCode", ",", "false", ")", ";", "}", ";", "var", "keyDown", "=", "function", "(", "event", ")", "{", "updateKey", "(", "event", ".", "keyCode", ",", "true", ")", ";", "}", ";", "window", ".", "addEventListener", "(", "\"keyup\"", ",", "keyUp", ",", "false", ")", ";", "window", ".", "addEventListener", "(", "\"keydown\"", ",", "keyDown", ",", "false", ")", ";", "}" ]
Sets up controller key functions @param {callback(code, down)} keyDownFn a function to be called when a key is pressed. It's passed the keycode and true. @param {callback(code, down)} keyUpFn a function to be called when a key is released. It's passed the keycode and false. @memberOf module:Input
[ "Sets", "up", "controller", "key", "functions" ]
b9e20afd5183db73522bcfae48225c87e01f68c0
https://github.com/greggman/hft-sample-ui/blob/b9e20afd5183db73522bcfae48225c87e01f68c0/src/hft/scripts/misc/input.js#L216-L242
train
codeactual/sinon-doublist
lib/sinon-doublist/index.js
sinonDoublist
function sinonDoublist(sinon, test, disableAutoSandbox) { if (typeof test === 'string') { adapters[test](sinon, disableAutoSandbox); return; } Object.keys(mixin).forEach(function forEachKey(method) { test[method] = mixin[method].bind(test); }); if (!disableAutoSandbox) { test.createSandbox(sinon); } }
javascript
function sinonDoublist(sinon, test, disableAutoSandbox) { if (typeof test === 'string') { adapters[test](sinon, disableAutoSandbox); return; } Object.keys(mixin).forEach(function forEachKey(method) { test[method] = mixin[method].bind(test); }); if (!disableAutoSandbox) { test.createSandbox(sinon); } }
[ "function", "sinonDoublist", "(", "sinon", ",", "test", ",", "disableAutoSandbox", ")", "{", "if", "(", "typeof", "test", "===", "'string'", ")", "{", "adapters", "[", "test", "]", "(", "sinon", ",", "disableAutoSandbox", ")", ";", "return", ";", "}", "Object", ".", "keys", "(", "mixin", ")", ".", "forEach", "(", "function", "forEachKey", "(", "method", ")", "{", "test", "[", "method", "]", "=", "mixin", "[", "method", "]", ".", "bind", "(", "test", ")", ";", "}", ")", ";", "if", "(", "!", "disableAutoSandbox", ")", "{", "test", ".", "createSandbox", "(", "sinon", ")", ";", "}", "}" ]
Init sandbox and add its properties to the current context. @param {object} sinon @param {string|object} test - `{object}` Current test context, ex. `this` inside a 'before each' hook, to receive the sandbox/mixins - `{string}` Name of supported adapter which will automatically set up and tear down the sandbox/mixins - Adapters: 'mocha' @param {boolean} [disableAutoSandbox=false] - `true`: Manually augment `test` later via `test.createSandbox()` - `false`: Immediate augment `test` with `spy`, `stub`, etc.
[ "Init", "sandbox", "and", "add", "its", "properties", "to", "the", "current", "context", "." ]
e262b3525fb6debbac5a37ea8057df2c1c8b95fb
https://github.com/codeactual/sinon-doublist/blob/e262b3525fb6debbac5a37ea8057df2c1c8b95fb/lib/sinon-doublist/index.js#L27-L39
train