id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
57,000 | pmh/espresso | lib/ometa/ometa/ometa.js | cached | function cached(grammar_file) {
var fs = require('fs'),
path = require('path'),
change = fs.statSync(grammar_file).mtime.valueOf(),
cache = [cache_path,'/', path.basename(grammar_file), '.', change, '.js'].join('');
if(!fs.existsSync(cache_path))
fs.mkdirSync(cache_path);
if(fs.existsSync(cache))
return fs.readFileSync(cache, 'utf8');
var result = load(grammar_file);
fs.writeFileSync(cache, result);
return result;
} | javascript | function cached(grammar_file) {
var fs = require('fs'),
path = require('path'),
change = fs.statSync(grammar_file).mtime.valueOf(),
cache = [cache_path,'/', path.basename(grammar_file), '.', change, '.js'].join('');
if(!fs.existsSync(cache_path))
fs.mkdirSync(cache_path);
if(fs.existsSync(cache))
return fs.readFileSync(cache, 'utf8');
var result = load(grammar_file);
fs.writeFileSync(cache, result);
return result;
} | [
"function",
"cached",
"(",
"grammar_file",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"'fs'",
")",
",",
"path",
"=",
"require",
"(",
"'path'",
")",
",",
"change",
"=",
"fs",
".",
"statSync",
"(",
"grammar_file",
")",
".",
"mtime",
".",
"valueOf",
"(",
")",
",",
"cache",
"=",
"[",
"cache_path",
",",
"'/'",
",",
"path",
".",
"basename",
"(",
"grammar_file",
")",
",",
"'.'",
",",
"change",
",",
"'.js'",
"]",
".",
"join",
"(",
"''",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"cache_path",
")",
")",
"fs",
".",
"mkdirSync",
"(",
"cache_path",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"cache",
")",
")",
"return",
"fs",
".",
"readFileSync",
"(",
"cache",
",",
"'utf8'",
")",
";",
"var",
"result",
"=",
"load",
"(",
"grammar_file",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"cache",
",",
"result",
")",
";",
"return",
"result",
";",
"}"
] | Internal function to cache grammars. Creates a `.cache` directory in the current
working path. | [
"Internal",
"function",
"to",
"cache",
"grammars",
".",
"Creates",
"a",
".",
"cache",
"directory",
"in",
"the",
"current",
"working",
"path",
"."
] | 26d7b2089a2098344aaaf32ec7eb942e91a7edf5 | https://github.com/pmh/espresso/blob/26d7b2089a2098344aaaf32ec7eb942e91a7edf5/lib/ometa/ometa/ometa.js#L8-L23 |
57,001 | pmh/espresso | lib/ometa/ometa/ometa.js | load | function load(grammar_file) {
var fs = require('fs'),
grammar = fs.readFileSync(grammar_file, 'utf-8');
return compile(grammar)
} | javascript | function load(grammar_file) {
var fs = require('fs'),
grammar = fs.readFileSync(grammar_file, 'utf-8');
return compile(grammar)
} | [
"function",
"load",
"(",
"grammar_file",
")",
"{",
"var",
"fs",
"=",
"require",
"(",
"'fs'",
")",
",",
"grammar",
"=",
"fs",
".",
"readFileSync",
"(",
"grammar_file",
",",
"'utf-8'",
")",
";",
"return",
"compile",
"(",
"grammar",
")",
"}"
] | Loads the specified grammar file and returns the generated grammar JavaScript
code for it. Evaling this code in your module will create the grammar objects
in the global module namespace. | [
"Loads",
"the",
"specified",
"grammar",
"file",
"and",
"returns",
"the",
"generated",
"grammar",
"JavaScript",
"code",
"for",
"it",
".",
"Evaling",
"this",
"code",
"in",
"your",
"module",
"will",
"create",
"the",
"grammar",
"objects",
"in",
"the",
"global",
"module",
"namespace",
"."
] | 26d7b2089a2098344aaaf32ec7eb942e91a7edf5 | https://github.com/pmh/espresso/blob/26d7b2089a2098344aaaf32ec7eb942e91a7edf5/lib/ometa/ometa/ometa.js#L30-L34 |
57,002 | pmh/espresso | lib/ometa/ometa/ometa.js | run | function run(grammar, module, filename) {
// this is used to bind OMeta to runtime. It can be used also (lateron) to dynamically
// inject other environment-variables.
// {a:1,b:2,c:3,d:4} -> function(a,b,c,d) {...}.call(1,2,3,4)
// this is better than `with`, since it offers full control
var source = [
"module.grammar = (function(OMeta) {",
grammar,
"});"
].join('');
module._compile(source, filename);
module.grammar.call(module, ometa);
return module.exports;
} | javascript | function run(grammar, module, filename) {
// this is used to bind OMeta to runtime. It can be used also (lateron) to dynamically
// inject other environment-variables.
// {a:1,b:2,c:3,d:4} -> function(a,b,c,d) {...}.call(1,2,3,4)
// this is better than `with`, since it offers full control
var source = [
"module.grammar = (function(OMeta) {",
grammar,
"});"
].join('');
module._compile(source, filename);
module.grammar.call(module, ometa);
return module.exports;
} | [
"function",
"run",
"(",
"grammar",
",",
"module",
",",
"filename",
")",
"{",
"// this is used to bind OMeta to runtime. It can be used also (lateron) to dynamically",
"// inject other environment-variables. ",
"// {a:1,b:2,c:3,d:4} -> function(a,b,c,d) {...}.call(1,2,3,4)",
"// this is better than `with`, since it offers full control",
"var",
"source",
"=",
"[",
"\"module.grammar = (function(OMeta) {\"",
",",
"grammar",
",",
"\"});\"",
"]",
".",
"join",
"(",
"''",
")",
";",
"module",
".",
"_compile",
"(",
"source",
",",
"filename",
")",
";",
"module",
".",
"grammar",
".",
"call",
"(",
"module",
",",
"ometa",
")",
";",
"return",
"module",
".",
"exports",
";",
"}"
] | Evaluates the grammar-module and returns the exports of that module | [
"Evaluates",
"the",
"grammar",
"-",
"module",
"and",
"returns",
"the",
"exports",
"of",
"that",
"module"
] | 26d7b2089a2098344aaaf32ec7eb942e91a7edf5 | https://github.com/pmh/espresso/blob/26d7b2089a2098344aaaf32ec7eb942e91a7edf5/lib/ometa/ometa/ometa.js#L50-L65 |
57,003 | torworx/well | function.js | _apply | function _apply(func, thisArg, promisedArgs) {
return well.all(promisedArgs || []).then(function(args) {
return func.apply(thisArg, args);
});
} | javascript | function _apply(func, thisArg, promisedArgs) {
return well.all(promisedArgs || []).then(function(args) {
return func.apply(thisArg, args);
});
} | [
"function",
"_apply",
"(",
"func",
",",
"thisArg",
",",
"promisedArgs",
")",
"{",
"return",
"well",
".",
"all",
"(",
"promisedArgs",
"||",
"[",
"]",
")",
".",
"then",
"(",
"function",
"(",
"args",
")",
"{",
"return",
"func",
".",
"apply",
"(",
"thisArg",
",",
"args",
")",
";",
"}",
")",
";",
"}"
] | Apply helper that allows specifying thisArg
@private | [
"Apply",
"helper",
"that",
"allows",
"specifying",
"thisArg"
] | 45a1724a0a4192628c80b3c4ae541d6de28ac7da | https://github.com/torworx/well/blob/45a1724a0a4192628c80b3c4ae541d6de28ac7da/function.js#L59-L63 |
57,004 | torworx/well | function.js | lift | function lift(func /*, args... */) {
var args = slice.call(arguments, 1);
return function() {
return _apply(func, this, args.concat(slice.call(arguments)));
};
} | javascript | function lift(func /*, args... */) {
var args = slice.call(arguments, 1);
return function() {
return _apply(func, this, args.concat(slice.call(arguments)));
};
} | [
"function",
"lift",
"(",
"func",
"/*, args... */",
")",
"{",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"return",
"function",
"(",
")",
"{",
"return",
"_apply",
"(",
"func",
",",
"this",
",",
"args",
".",
"concat",
"(",
"slice",
".",
"call",
"(",
"arguments",
")",
")",
")",
";",
"}",
";",
"}"
] | Takes a 'regular' function and returns a version of that function that
returns a promise instead of a plain value, and handles thrown errors by
returning a rejected promise. Also accepts a list of arguments to be
prepended to the new function, as does Function.prototype.bind.
The resulting function is promise-aware, in the sense that it accepts
promise arguments, and waits for their resolution.
@example
function mayThrowError(n) {
if(n % 2 === 1) { // Normally this wouldn't be so deterministic :)
throw new Error("I don't like odd numbers");
} else {
return n;
}
}
var lifted = fn.lift(mayThrowError);
// Logs "I don't like odd numbers"
lifted(1).then(console.log, console.error);
// Logs '6'
lifted(6).then(console.log, console.error);
@example
function sumTwoNumbers(x, y) {
return x + y;
}
var sumWithFive = fn.lifted(sumTwoNumbers, 5);
// Logs '15'
sumWithFive(10).then(console.log, console.error);
@param {Function} func function to be bound
@param {...*} [args] arguments to be prepended for the new function
@returns {Function} a promise-returning function | [
"Takes",
"a",
"regular",
"function",
"and",
"returns",
"a",
"version",
"of",
"that",
"function",
"that",
"returns",
"a",
"promise",
"instead",
"of",
"a",
"plain",
"value",
"and",
"handles",
"thrown",
"errors",
"by",
"returning",
"a",
"rejected",
"promise",
".",
"Also",
"accepts",
"a",
"list",
"of",
"arguments",
"to",
"be",
"prepended",
"to",
"the",
"new",
"function",
"as",
"does",
"Function",
".",
"prototype",
".",
"bind",
"."
] | 45a1724a0a4192628c80b3c4ae541d6de28ac7da | https://github.com/torworx/well/blob/45a1724a0a4192628c80b3c4ae541d6de28ac7da/function.js#L133-L138 |
57,005 | camshaft/pack-n-stack | lib/stack.js | createStack | function createStack(app) {
if (!app) {
throw new Error("Pack-n-stack requires an express/connect app");
};
app = utils.merge(app, proto);
Object.defineProperty(app, "count", {
get: function() {
return app.stack.length;
}
});
return app;
} | javascript | function createStack(app) {
if (!app) {
throw new Error("Pack-n-stack requires an express/connect app");
};
app = utils.merge(app, proto);
Object.defineProperty(app, "count", {
get: function() {
return app.stack.length;
}
});
return app;
} | [
"function",
"createStack",
"(",
"app",
")",
"{",
"if",
"(",
"!",
"app",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Pack-n-stack requires an express/connect app\"",
")",
";",
"}",
";",
"app",
"=",
"utils",
".",
"merge",
"(",
"app",
",",
"proto",
")",
";",
"Object",
".",
"defineProperty",
"(",
"app",
",",
"\"count\"",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"app",
".",
"stack",
".",
"length",
";",
"}",
"}",
")",
";",
"return",
"app",
";",
"}"
] | Create a new stack.
@return {Function}
@api public | [
"Create",
"a",
"new",
"stack",
"."
] | ec5fe9a4cb9895b89e137e966a4eaffb7931881c | https://github.com/camshaft/pack-n-stack/blob/ec5fe9a4cb9895b89e137e966a4eaffb7931881c/lib/stack.js#L29-L43 |
57,006 | dggriffin/mitto | lib/index.js | loadConfig | function loadConfig(filename) {
//Does our consumer have a valid .mitto?
var mittoObject = _loadMitto();
//Is it in a valid format?
mittoObject = _validateMitto(mittoObject);
//Does our consumer's consumer have a config of 'filename'?
var configObject = _findFile(filename);
//Is it in a valid format as prescribed by our consumer's .mitto?
return _validateConfig(configObject, mittoObject);
} | javascript | function loadConfig(filename) {
//Does our consumer have a valid .mitto?
var mittoObject = _loadMitto();
//Is it in a valid format?
mittoObject = _validateMitto(mittoObject);
//Does our consumer's consumer have a config of 'filename'?
var configObject = _findFile(filename);
//Is it in a valid format as prescribed by our consumer's .mitto?
return _validateConfig(configObject, mittoObject);
} | [
"function",
"loadConfig",
"(",
"filename",
")",
"{",
"//Does our consumer have a valid .mitto?",
"var",
"mittoObject",
"=",
"_loadMitto",
"(",
")",
";",
"//Is it in a valid format?",
"mittoObject",
"=",
"_validateMitto",
"(",
"mittoObject",
")",
";",
"//Does our consumer's consumer have a config of 'filename'?",
"var",
"configObject",
"=",
"_findFile",
"(",
"filename",
")",
";",
"//Is it in a valid format as prescribed by our consumer's .mitto?",
"return",
"_validateConfig",
"(",
"configObject",
",",
"mittoObject",
")",
";",
"}"
] | Find JSON configuration given a filename
Applies .mitto constraints if your package has a .mitto package present
@return {json converted to Object} | [
"Find",
"JSON",
"configuration",
"given",
"a",
"filename",
"Applies",
".",
"mitto",
"constraints",
"if",
"your",
"package",
"has",
"a",
".",
"mitto",
"package",
"present"
] | a58cd439b67b626522078b8003a82a348103a66c | https://github.com/dggriffin/mitto/blob/a58cd439b67b626522078b8003a82a348103a66c/lib/index.js#L28-L38 |
57,007 | dggriffin/mitto | lib/index.js | _findFile | function _findFile(filename) {
var cwd = process.cwd();
var parts = cwd.split(_path2.default.sep);
do {
var loc = parts.join(_path2.default.sep);
if (!loc) break;
var file = _path2.default.join(loc, filename);
if (_fs2.default.existsSync(file)) {
var fileObj = undefined;
try {
fileObj = require(file);
} catch (e) {
fileObj = _loadJSON(file);
}
return fileObj;
}
parts.pop();
} while (parts.length);
return null;
} | javascript | function _findFile(filename) {
var cwd = process.cwd();
var parts = cwd.split(_path2.default.sep);
do {
var loc = parts.join(_path2.default.sep);
if (!loc) break;
var file = _path2.default.join(loc, filename);
if (_fs2.default.existsSync(file)) {
var fileObj = undefined;
try {
fileObj = require(file);
} catch (e) {
fileObj = _loadJSON(file);
}
return fileObj;
}
parts.pop();
} while (parts.length);
return null;
} | [
"function",
"_findFile",
"(",
"filename",
")",
"{",
"var",
"cwd",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"var",
"parts",
"=",
"cwd",
".",
"split",
"(",
"_path2",
".",
"default",
".",
"sep",
")",
";",
"do",
"{",
"var",
"loc",
"=",
"parts",
".",
"join",
"(",
"_path2",
".",
"default",
".",
"sep",
")",
";",
"if",
"(",
"!",
"loc",
")",
"break",
";",
"var",
"file",
"=",
"_path2",
".",
"default",
".",
"join",
"(",
"loc",
",",
"filename",
")",
";",
"if",
"(",
"_fs2",
".",
"default",
".",
"existsSync",
"(",
"file",
")",
")",
"{",
"var",
"fileObj",
"=",
"undefined",
";",
"try",
"{",
"fileObj",
"=",
"require",
"(",
"file",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"fileObj",
"=",
"_loadJSON",
"(",
"file",
")",
";",
"}",
"return",
"fileObj",
";",
"}",
"parts",
".",
"pop",
"(",
")",
";",
"}",
"while",
"(",
"parts",
".",
"length",
")",
";",
"return",
"null",
";",
"}"
] | PRIVATE HELPER FUNCTIONS
Find a "require" a JSON configuration given the filename | [
"PRIVATE",
"HELPER",
"FUNCTIONS",
"Find",
"a",
"require",
"a",
"JSON",
"configuration",
"given",
"the",
"filename"
] | a58cd439b67b626522078b8003a82a348103a66c | https://github.com/dggriffin/mitto/blob/a58cd439b67b626522078b8003a82a348103a66c/lib/index.js#L45-L67 |
57,008 | dggriffin/mitto | lib/index.js | _validateMitto | function _validateMitto(mittoObject) {
if (!mittoObject) {
return null;
}
if (!mittoObject.hasOwnProperty("name")) {
throw new Error("\"name\" property is missing from your .mitto and is required.");
}
if (mittoObject.hasOwnProperty("required")) {
for (var key in mittoObject.required) {
if (mittoObject.required[key].hasOwnProperty("type")) {
if (DATA_TYPES.indexOf(mittoObject.required[key].type) === -1) {
throw new Error(mittoObject.required[key].type + " is not a valid data type. Expected: \"undefined\", \"object\", \"boolean\", \"number\", \"string\", \"symbol\", or \"function\"");
}
} else {
throw new Error("\"type\" property is missing from your .mitto's required parameter \"" + key + "\"");
}
if (mittoObject.required[key].hasOwnProperty("description") && typeof mittoObject.required[key].description !== "string") {
throw new Error("\"description\" property of your .mitto's required parameter " + key + " must be of type \"string\"");
}
}
}
if (mittoObject.hasOwnProperty("optional")) {
for (var key in mittoObject.optional) {
if (mittoObject.optional[key].hasOwnProperty("type")) {
if (DATA_TYPES.indexOf(mittoObject.optional[key].type) === -1) {
throw new Error(mittoObject.optional[key].type + " is not a valid data type. Expected: \"undefined\", \"object\", \"boolean\", \"number\", \"string\", \"symbol\", or \"function\"");
}
} else {
throw new Error("\"type\" property is missing from your .mitto's optional parameter " + key);
}
if (mittoObject.optional[key].hasOwnProperty("description") && typeof mittoObject.optional[key].description !== "string") {
throw new Error("\"description\" property of your .mitto's optional parameter " + key + " must be of type \"string\"");
}
if (mittoObject.optional[key].hasOwnProperty("default") && _typeof(mittoObject.optional[key].default) !== mittoObject.optional[key].type) {
throw new Error("\"default\" property of your .mitto's optional parameter " + key + " must be a " + mittoObject.optional[key].type + ", as specified by \"type\"");
} else if (mittoObject.optional[key].hasOwnProperty("default")) {
mittoObject.hasDefault = true;
}
}
}
return mittoObject;
} | javascript | function _validateMitto(mittoObject) {
if (!mittoObject) {
return null;
}
if (!mittoObject.hasOwnProperty("name")) {
throw new Error("\"name\" property is missing from your .mitto and is required.");
}
if (mittoObject.hasOwnProperty("required")) {
for (var key in mittoObject.required) {
if (mittoObject.required[key].hasOwnProperty("type")) {
if (DATA_TYPES.indexOf(mittoObject.required[key].type) === -1) {
throw new Error(mittoObject.required[key].type + " is not a valid data type. Expected: \"undefined\", \"object\", \"boolean\", \"number\", \"string\", \"symbol\", or \"function\"");
}
} else {
throw new Error("\"type\" property is missing from your .mitto's required parameter \"" + key + "\"");
}
if (mittoObject.required[key].hasOwnProperty("description") && typeof mittoObject.required[key].description !== "string") {
throw new Error("\"description\" property of your .mitto's required parameter " + key + " must be of type \"string\"");
}
}
}
if (mittoObject.hasOwnProperty("optional")) {
for (var key in mittoObject.optional) {
if (mittoObject.optional[key].hasOwnProperty("type")) {
if (DATA_TYPES.indexOf(mittoObject.optional[key].type) === -1) {
throw new Error(mittoObject.optional[key].type + " is not a valid data type. Expected: \"undefined\", \"object\", \"boolean\", \"number\", \"string\", \"symbol\", or \"function\"");
}
} else {
throw new Error("\"type\" property is missing from your .mitto's optional parameter " + key);
}
if (mittoObject.optional[key].hasOwnProperty("description") && typeof mittoObject.optional[key].description !== "string") {
throw new Error("\"description\" property of your .mitto's optional parameter " + key + " must be of type \"string\"");
}
if (mittoObject.optional[key].hasOwnProperty("default") && _typeof(mittoObject.optional[key].default) !== mittoObject.optional[key].type) {
throw new Error("\"default\" property of your .mitto's optional parameter " + key + " must be a " + mittoObject.optional[key].type + ", as specified by \"type\"");
} else if (mittoObject.optional[key].hasOwnProperty("default")) {
mittoObject.hasDefault = true;
}
}
}
return mittoObject;
} | [
"function",
"_validateMitto",
"(",
"mittoObject",
")",
"{",
"if",
"(",
"!",
"mittoObject",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"mittoObject",
".",
"hasOwnProperty",
"(",
"\"name\"",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"\\\"name\\\" property is missing from your .mitto and is required.\"",
")",
";",
"}",
"if",
"(",
"mittoObject",
".",
"hasOwnProperty",
"(",
"\"required\"",
")",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"mittoObject",
".",
"required",
")",
"{",
"if",
"(",
"mittoObject",
".",
"required",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"type\"",
")",
")",
"{",
"if",
"(",
"DATA_TYPES",
".",
"indexOf",
"(",
"mittoObject",
".",
"required",
"[",
"key",
"]",
".",
"type",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"mittoObject",
".",
"required",
"[",
"key",
"]",
".",
"type",
"+",
"\" is not a valid data type. Expected: \\\"undefined\\\", \\\"object\\\", \\\"boolean\\\", \\\"number\\\", \\\"string\\\", \\\"symbol\\\", or \\\"function\\\"\"",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"\\\"type\\\" property is missing from your .mitto's required parameter \\\"\"",
"+",
"key",
"+",
"\"\\\"\"",
")",
";",
"}",
"if",
"(",
"mittoObject",
".",
"required",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"description\"",
")",
"&&",
"typeof",
"mittoObject",
".",
"required",
"[",
"key",
"]",
".",
"description",
"!==",
"\"string\"",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"\\\"description\\\" property of your .mitto's required parameter \"",
"+",
"key",
"+",
"\" must be of type \\\"string\\\"\"",
")",
";",
"}",
"}",
"}",
"if",
"(",
"mittoObject",
".",
"hasOwnProperty",
"(",
"\"optional\"",
")",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"mittoObject",
".",
"optional",
")",
"{",
"if",
"(",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"type\"",
")",
")",
"{",
"if",
"(",
"DATA_TYPES",
".",
"indexOf",
"(",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"type",
")",
"===",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"type",
"+",
"\" is not a valid data type. Expected: \\\"undefined\\\", \\\"object\\\", \\\"boolean\\\", \\\"number\\\", \\\"string\\\", \\\"symbol\\\", or \\\"function\\\"\"",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"\\\"type\\\" property is missing from your .mitto's optional parameter \"",
"+",
"key",
")",
";",
"}",
"if",
"(",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"description\"",
")",
"&&",
"typeof",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"description",
"!==",
"\"string\"",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"\\\"description\\\" property of your .mitto's optional parameter \"",
"+",
"key",
"+",
"\" must be of type \\\"string\\\"\"",
")",
";",
"}",
"if",
"(",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"default\"",
")",
"&&",
"_typeof",
"(",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"default",
")",
"!==",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"type",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"\\\"default\\\" property of your .mitto's optional parameter \"",
"+",
"key",
"+",
"\" must be a \"",
"+",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"type",
"+",
"\", as specified by \\\"type\\\"\"",
")",
";",
"}",
"else",
"if",
"(",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"hasOwnProperty",
"(",
"\"default\"",
")",
")",
"{",
"mittoObject",
".",
"hasDefault",
"=",
"true",
";",
"}",
"}",
"}",
"return",
"mittoObject",
";",
"}"
] | Validate .mitto object handed off to function to ensure it is syntatical correct | [
"Validate",
".",
"mitto",
"object",
"handed",
"off",
"to",
"function",
"to",
"ensure",
"it",
"is",
"syntatical",
"correct"
] | a58cd439b67b626522078b8003a82a348103a66c | https://github.com/dggriffin/mitto/blob/a58cd439b67b626522078b8003a82a348103a66c/lib/index.js#L75-L123 |
57,009 | dggriffin/mitto | lib/index.js | _validateConfig | function _validateConfig(configObject, mittoObject) {
var packageObject = _findFile('package.json');
if (!mittoObject) {
return configObject;
}
if (!configObject && mittoObject.required && Object.keys(mittoObject.required).length) {
throw new Error(mittoObject.name + " configuration file not found, and is required by " + packageObject.name);
} else if (!configObject && mittoObject.hasDefault) {
return _addOnDefaults({}, mittoObject);
} else if (!configObject) {
return configObject;
}
for (var key in mittoObject.required) {
if (!configObject.hasOwnProperty(key)) {
throw new Error("Required property " + key + " not found in " + mittoObject.name);
} else if (_typeof(configObject[key]) !== mittoObject.required[key].type) {
throw new Error("Required property " + key + " expected to be of type " + mittoObject.required[key].type);
}
}
for (var key in mittoObject.optional) {
if (configObject[key] && _typeof(configObject[key]) !== mittoObject.optional[key].type) {
throw new Error("Optional property " + key + " is type " + _typeof(configObject[key]) + " and expected to be of type " + mittoObject.optional[key].type);
}
}
if (mittoObject.hasDefault) {
return _addOnDefaults(configObject, mittoObject);
}
return configObject;
} | javascript | function _validateConfig(configObject, mittoObject) {
var packageObject = _findFile('package.json');
if (!mittoObject) {
return configObject;
}
if (!configObject && mittoObject.required && Object.keys(mittoObject.required).length) {
throw new Error(mittoObject.name + " configuration file not found, and is required by " + packageObject.name);
} else if (!configObject && mittoObject.hasDefault) {
return _addOnDefaults({}, mittoObject);
} else if (!configObject) {
return configObject;
}
for (var key in mittoObject.required) {
if (!configObject.hasOwnProperty(key)) {
throw new Error("Required property " + key + " not found in " + mittoObject.name);
} else if (_typeof(configObject[key]) !== mittoObject.required[key].type) {
throw new Error("Required property " + key + " expected to be of type " + mittoObject.required[key].type);
}
}
for (var key in mittoObject.optional) {
if (configObject[key] && _typeof(configObject[key]) !== mittoObject.optional[key].type) {
throw new Error("Optional property " + key + " is type " + _typeof(configObject[key]) + " and expected to be of type " + mittoObject.optional[key].type);
}
}
if (mittoObject.hasDefault) {
return _addOnDefaults(configObject, mittoObject);
}
return configObject;
} | [
"function",
"_validateConfig",
"(",
"configObject",
",",
"mittoObject",
")",
"{",
"var",
"packageObject",
"=",
"_findFile",
"(",
"'package.json'",
")",
";",
"if",
"(",
"!",
"mittoObject",
")",
"{",
"return",
"configObject",
";",
"}",
"if",
"(",
"!",
"configObject",
"&&",
"mittoObject",
".",
"required",
"&&",
"Object",
".",
"keys",
"(",
"mittoObject",
".",
"required",
")",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"mittoObject",
".",
"name",
"+",
"\" configuration file not found, and is required by \"",
"+",
"packageObject",
".",
"name",
")",
";",
"}",
"else",
"if",
"(",
"!",
"configObject",
"&&",
"mittoObject",
".",
"hasDefault",
")",
"{",
"return",
"_addOnDefaults",
"(",
"{",
"}",
",",
"mittoObject",
")",
";",
"}",
"else",
"if",
"(",
"!",
"configObject",
")",
"{",
"return",
"configObject",
";",
"}",
"for",
"(",
"var",
"key",
"in",
"mittoObject",
".",
"required",
")",
"{",
"if",
"(",
"!",
"configObject",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Required property \"",
"+",
"key",
"+",
"\" not found in \"",
"+",
"mittoObject",
".",
"name",
")",
";",
"}",
"else",
"if",
"(",
"_typeof",
"(",
"configObject",
"[",
"key",
"]",
")",
"!==",
"mittoObject",
".",
"required",
"[",
"key",
"]",
".",
"type",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Required property \"",
"+",
"key",
"+",
"\" expected to be of type \"",
"+",
"mittoObject",
".",
"required",
"[",
"key",
"]",
".",
"type",
")",
";",
"}",
"}",
"for",
"(",
"var",
"key",
"in",
"mittoObject",
".",
"optional",
")",
"{",
"if",
"(",
"configObject",
"[",
"key",
"]",
"&&",
"_typeof",
"(",
"configObject",
"[",
"key",
"]",
")",
"!==",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"type",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Optional property \"",
"+",
"key",
"+",
"\" is type \"",
"+",
"_typeof",
"(",
"configObject",
"[",
"key",
"]",
")",
"+",
"\" and expected to be of type \"",
"+",
"mittoObject",
".",
"optional",
"[",
"key",
"]",
".",
"type",
")",
";",
"}",
"}",
"if",
"(",
"mittoObject",
".",
"hasDefault",
")",
"{",
"return",
"_addOnDefaults",
"(",
"configObject",
",",
"mittoObject",
")",
";",
"}",
"return",
"configObject",
";",
"}"
] | Validate the consuming user's present config to ensure it meets the product producer's .mitto syntatical specifications | [
"Validate",
"the",
"consuming",
"user",
"s",
"present",
"config",
"to",
"ensure",
"it",
"meets",
"the",
"product",
"producer",
"s",
".",
"mitto",
"syntatical",
"specifications"
] | a58cd439b67b626522078b8003a82a348103a66c | https://github.com/dggriffin/mitto/blob/a58cd439b67b626522078b8003a82a348103a66c/lib/index.js#L126-L159 |
57,010 | yoshuawuyts/urit | index.js | parse | function parse (tmpl) {
tmpl = tmpl || ''
const parser = uritemplate.parse(tmpl)
return function expand (params) {
params = params || {}
return parser.expand(params)
}
} | javascript | function parse (tmpl) {
tmpl = tmpl || ''
const parser = uritemplate.parse(tmpl)
return function expand (params) {
params = params || {}
return parser.expand(params)
}
} | [
"function",
"parse",
"(",
"tmpl",
")",
"{",
"tmpl",
"=",
"tmpl",
"||",
"''",
"const",
"parser",
"=",
"uritemplate",
".",
"parse",
"(",
"tmpl",
")",
"return",
"function",
"expand",
"(",
"params",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
"return",
"parser",
".",
"expand",
"(",
"params",
")",
"}",
"}"
] | parse a uri template str -> str | [
"parse",
"a",
"uri",
"template",
"str",
"-",
">",
"str"
] | 9f3c9a06a93c509189d9bf9876c5f4d77ee2776e | https://github.com/yoshuawuyts/urit/blob/9f3c9a06a93c509189d9bf9876c5f4d77ee2776e/index.js#L7-L15 |
57,011 | imlucas/node-stor | stores/localstorage.js | prostrate | function prostrate(source){
return function(method, transform){
transform = transform || {};
return function(){
var args = Array.prototype.slice.call(arguments, 0),
fn = args.pop(),
res,
last;
if(args[0] && ['removeItem', 'getItem', 'setItem'].indexOf(method) > -1){
var id = args[0];
id = id.toString();
if(id.indexOf(module.exports.ns) === -1){
id = module.exports.ns + id;
}
args[0] = id;
}
if(args.length == 2 && transform.before){
args[1] = transform.before(args[1]);
}
if(method === 'key'){
assert(typeof args[0] === 'number', args[0] + ' must be a number');
}
if(!source[method]){
throw new Error('Unknown localstorage method ' + method);
}
else{
if(source[method].apply){
res = source[method].apply(source, args);
debug('result for ' + method, '(', args, ')', res);
}
else {
res = source[method];
}
}
try{
if(transform.after){
res = transform.after(res);
}
}
catch(e){}
fn(null, res);
};
};
} | javascript | function prostrate(source){
return function(method, transform){
transform = transform || {};
return function(){
var args = Array.prototype.slice.call(arguments, 0),
fn = args.pop(),
res,
last;
if(args[0] && ['removeItem', 'getItem', 'setItem'].indexOf(method) > -1){
var id = args[0];
id = id.toString();
if(id.indexOf(module.exports.ns) === -1){
id = module.exports.ns + id;
}
args[0] = id;
}
if(args.length == 2 && transform.before){
args[1] = transform.before(args[1]);
}
if(method === 'key'){
assert(typeof args[0] === 'number', args[0] + ' must be a number');
}
if(!source[method]){
throw new Error('Unknown localstorage method ' + method);
}
else{
if(source[method].apply){
res = source[method].apply(source, args);
debug('result for ' + method, '(', args, ')', res);
}
else {
res = source[method];
}
}
try{
if(transform.after){
res = transform.after(res);
}
}
catch(e){}
fn(null, res);
};
};
} | [
"function",
"prostrate",
"(",
"source",
")",
"{",
"return",
"function",
"(",
"method",
",",
"transform",
")",
"{",
"transform",
"=",
"transform",
"||",
"{",
"}",
";",
"return",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
",",
"fn",
"=",
"args",
".",
"pop",
"(",
")",
",",
"res",
",",
"last",
";",
"if",
"(",
"args",
"[",
"0",
"]",
"&&",
"[",
"'removeItem'",
",",
"'getItem'",
",",
"'setItem'",
"]",
".",
"indexOf",
"(",
"method",
")",
">",
"-",
"1",
")",
"{",
"var",
"id",
"=",
"args",
"[",
"0",
"]",
";",
"id",
"=",
"id",
".",
"toString",
"(",
")",
";",
"if",
"(",
"id",
".",
"indexOf",
"(",
"module",
".",
"exports",
".",
"ns",
")",
"===",
"-",
"1",
")",
"{",
"id",
"=",
"module",
".",
"exports",
".",
"ns",
"+",
"id",
";",
"}",
"args",
"[",
"0",
"]",
"=",
"id",
";",
"}",
"if",
"(",
"args",
".",
"length",
"==",
"2",
"&&",
"transform",
".",
"before",
")",
"{",
"args",
"[",
"1",
"]",
"=",
"transform",
".",
"before",
"(",
"args",
"[",
"1",
"]",
")",
";",
"}",
"if",
"(",
"method",
"===",
"'key'",
")",
"{",
"assert",
"(",
"typeof",
"args",
"[",
"0",
"]",
"===",
"'number'",
",",
"args",
"[",
"0",
"]",
"+",
"' must be a number'",
")",
";",
"}",
"if",
"(",
"!",
"source",
"[",
"method",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown localstorage method '",
"+",
"method",
")",
";",
"}",
"else",
"{",
"if",
"(",
"source",
"[",
"method",
"]",
".",
"apply",
")",
"{",
"res",
"=",
"source",
"[",
"method",
"]",
".",
"apply",
"(",
"source",
",",
"args",
")",
";",
"debug",
"(",
"'result for '",
"+",
"method",
",",
"'('",
",",
"args",
",",
"')'",
",",
"res",
")",
";",
"}",
"else",
"{",
"res",
"=",
"source",
"[",
"method",
"]",
";",
"}",
"}",
"try",
"{",
"if",
"(",
"transform",
".",
"after",
")",
"{",
"res",
"=",
"transform",
".",
"after",
"(",
"res",
")",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"fn",
"(",
"null",
",",
"res",
")",
";",
"}",
";",
"}",
";",
"}"
] | Make local storage async, get and set JSON-ify. | [
"Make",
"local",
"storage",
"async",
"get",
"and",
"set",
"JSON",
"-",
"ify",
"."
] | 6b74af52bf160873658bc3570db716d44c33f335 | https://github.com/imlucas/node-stor/blob/6b74af52bf160873658bc3570db716d44c33f335/stores/localstorage.js#L5-L50 |
57,012 | ayecue/node-klass | src/klass/Logger.js | function(args){
return forEach(args,function(_,item){
var messages = this.result,
type = typeof item;
if (type == 'string') {
messages.push('%s');
} else if (type == 'number') {
messages.push('%d');
} else if (type == 'boolean') {
messages.push('%s');
} else {
messages.push('%O');
}
},[]);
} | javascript | function(args){
return forEach(args,function(_,item){
var messages = this.result,
type = typeof item;
if (type == 'string') {
messages.push('%s');
} else if (type == 'number') {
messages.push('%d');
} else if (type == 'boolean') {
messages.push('%s');
} else {
messages.push('%O');
}
},[]);
} | [
"function",
"(",
"args",
")",
"{",
"return",
"forEach",
"(",
"args",
",",
"function",
"(",
"_",
",",
"item",
")",
"{",
"var",
"messages",
"=",
"this",
".",
"result",
",",
"type",
"=",
"typeof",
"item",
";",
"if",
"(",
"type",
"==",
"'string'",
")",
"{",
"messages",
".",
"push",
"(",
"'%s'",
")",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'number'",
")",
"{",
"messages",
".",
"push",
"(",
"'%d'",
")",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'boolean'",
")",
"{",
"messages",
".",
"push",
"(",
"'%s'",
")",
";",
"}",
"else",
"{",
"messages",
".",
"push",
"(",
"'%O'",
")",
";",
"}",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Generating console message templates | [
"Generating",
"console",
"message",
"templates"
] | d0583db943bfc6186e45d205735bebd88828e117 | https://github.com/ayecue/node-klass/blob/d0583db943bfc6186e45d205735bebd88828e117/src/klass/Logger.js#L57-L72 |
|
57,013 | ayecue/node-klass | src/klass/Logger.js | function(context,args,error,color){
var me = this,
base = context.getCalledKlass(),
contextName = base ? base.getName() : CONSTANTS.LOGGER.UNKNOWN_NAME,
methodName = context.getCalledName() || CONSTANTS.LOGGER.ANONYMOUS_NAME,
messages = me.toMessages(args);
color = color || (error ? CONSTANTS.LOGGER.EXCEPTION_COLOR : CONSTANTS.LOGGER.SUCCESS_COLOR);
if (context) {
if (context.deepLoggingLevel || methodName == CONSTANTS.LOGGER.ANONYMOUS_NAME) {
var deepTrace = me.analyze(context);
console.groupCollapsed.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args));
console.log(('[node-klass-logger] ' + deepTrace)[color]);
console.groupEnd();
} else {
console.log.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args));
}
} else {
console.log.apply(console,[('[node-klass-logger]' + messages.join(' '))[color]].concat(args));
}
} | javascript | function(context,args,error,color){
var me = this,
base = context.getCalledKlass(),
contextName = base ? base.getName() : CONSTANTS.LOGGER.UNKNOWN_NAME,
methodName = context.getCalledName() || CONSTANTS.LOGGER.ANONYMOUS_NAME,
messages = me.toMessages(args);
color = color || (error ? CONSTANTS.LOGGER.EXCEPTION_COLOR : CONSTANTS.LOGGER.SUCCESS_COLOR);
if (context) {
if (context.deepLoggingLevel || methodName == CONSTANTS.LOGGER.ANONYMOUS_NAME) {
var deepTrace = me.analyze(context);
console.groupCollapsed.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args));
console.log(('[node-klass-logger] ' + deepTrace)[color]);
console.groupEnd();
} else {
console.log.apply(console,[('[node-klass-logger] ' + contextName + '.' + methodName + messages.join(' '))[color]].concat(args));
}
} else {
console.log.apply(console,[('[node-klass-logger]' + messages.join(' '))[color]].concat(args));
}
} | [
"function",
"(",
"context",
",",
"args",
",",
"error",
",",
"color",
")",
"{",
"var",
"me",
"=",
"this",
",",
"base",
"=",
"context",
".",
"getCalledKlass",
"(",
")",
",",
"contextName",
"=",
"base",
"?",
"base",
".",
"getName",
"(",
")",
":",
"CONSTANTS",
".",
"LOGGER",
".",
"UNKNOWN_NAME",
",",
"methodName",
"=",
"context",
".",
"getCalledName",
"(",
")",
"||",
"CONSTANTS",
".",
"LOGGER",
".",
"ANONYMOUS_NAME",
",",
"messages",
"=",
"me",
".",
"toMessages",
"(",
"args",
")",
";",
"color",
"=",
"color",
"||",
"(",
"error",
"?",
"CONSTANTS",
".",
"LOGGER",
".",
"EXCEPTION_COLOR",
":",
"CONSTANTS",
".",
"LOGGER",
".",
"SUCCESS_COLOR",
")",
";",
"if",
"(",
"context",
")",
"{",
"if",
"(",
"context",
".",
"deepLoggingLevel",
"||",
"methodName",
"==",
"CONSTANTS",
".",
"LOGGER",
".",
"ANONYMOUS_NAME",
")",
"{",
"var",
"deepTrace",
"=",
"me",
".",
"analyze",
"(",
"context",
")",
";",
"console",
".",
"groupCollapsed",
".",
"apply",
"(",
"console",
",",
"[",
"(",
"'[node-klass-logger] '",
"+",
"contextName",
"+",
"'.'",
"+",
"methodName",
"+",
"messages",
".",
"join",
"(",
"' '",
")",
")",
"[",
"color",
"]",
"]",
".",
"concat",
"(",
"args",
")",
")",
";",
"console",
".",
"log",
"(",
"(",
"'[node-klass-logger] '",
"+",
"deepTrace",
")",
"[",
"color",
"]",
")",
";",
"console",
".",
"groupEnd",
"(",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
".",
"apply",
"(",
"console",
",",
"[",
"(",
"'[node-klass-logger] '",
"+",
"contextName",
"+",
"'.'",
"+",
"methodName",
"+",
"messages",
".",
"join",
"(",
"' '",
")",
")",
"[",
"color",
"]",
"]",
".",
"concat",
"(",
"args",
")",
")",
";",
"}",
"}",
"else",
"{",
"console",
".",
"log",
".",
"apply",
"(",
"console",
",",
"[",
"(",
"'[node-klass-logger]'",
"+",
"messages",
".",
"join",
"(",
"' '",
")",
")",
"[",
"color",
"]",
"]",
".",
"concat",
"(",
"args",
")",
")",
";",
"}",
"}"
] | Default print function to show context messages | [
"Default",
"print",
"function",
"to",
"show",
"context",
"messages"
] | d0583db943bfc6186e45d205735bebd88828e117 | https://github.com/ayecue/node-klass/blob/d0583db943bfc6186e45d205735bebd88828e117/src/klass/Logger.js#L77-L99 |
|
57,014 | taf2/tiamat | lib/tiamat/server.js | resetWorker | function resetWorker() {
sigqueue = [];
mastersigs.forEach(process.removeAllListeners.bind(process));
process.removeAllListeners('exit');
process.env.TIAMAT = '1';
} | javascript | function resetWorker() {
sigqueue = [];
mastersigs.forEach(process.removeAllListeners.bind(process));
process.removeAllListeners('exit');
process.env.TIAMAT = '1';
} | [
"function",
"resetWorker",
"(",
")",
"{",
"sigqueue",
"=",
"[",
"]",
";",
"mastersigs",
".",
"forEach",
"(",
"process",
".",
"removeAllListeners",
".",
"bind",
"(",
"process",
")",
")",
";",
"process",
".",
"removeAllListeners",
"(",
"'exit'",
")",
";",
"process",
".",
"env",
".",
"TIAMAT",
"=",
"'1'",
";",
"}"
] | unregister events setup by master | [
"unregister",
"events",
"setup",
"by",
"master"
] | f51a33bb94897bc5c9e1849990b418d0bfe49e48 | https://github.com/taf2/tiamat/blob/f51a33bb94897bc5c9e1849990b418d0bfe49e48/lib/tiamat/server.js#L227-L232 |
57,015 | chrisenytc/gngb-api | lib/gngb-api.js | function (res, name, version) {
//Options
var imgPath, width;
//RegExp
var re = /^\d\.\d.\d$/;
//Test version
if (re.test(version)) {
imgPath = path.join(dir, name + '.png');
width = 76;
} else if (version.length === 6) {
imgPath = path.join(dir, name + '-larger.png');
width = 80;
} else if (version.length === 7) {
imgPath = path.join(dir, name + '-larger.png');
width = 77;
} else {
imgPath = path.join(dir, name + '-larger.png');
width = 74;
}
//Create Image
var base = gm(imgPath)
.font(path.join(__dirname, 'fonts', 'Arial.ttf'))
.fontSize(10)
.fill('#ffffff')
.drawText(width, 12, version);
//Write Stream and send to client
write(base, res);
} | javascript | function (res, name, version) {
//Options
var imgPath, width;
//RegExp
var re = /^\d\.\d.\d$/;
//Test version
if (re.test(version)) {
imgPath = path.join(dir, name + '.png');
width = 76;
} else if (version.length === 6) {
imgPath = path.join(dir, name + '-larger.png');
width = 80;
} else if (version.length === 7) {
imgPath = path.join(dir, name + '-larger.png');
width = 77;
} else {
imgPath = path.join(dir, name + '-larger.png');
width = 74;
}
//Create Image
var base = gm(imgPath)
.font(path.join(__dirname, 'fonts', 'Arial.ttf'))
.fontSize(10)
.fill('#ffffff')
.drawText(width, 12, version);
//Write Stream and send to client
write(base, res);
} | [
"function",
"(",
"res",
",",
"name",
",",
"version",
")",
"{",
"//Options",
"var",
"imgPath",
",",
"width",
";",
"//RegExp",
"var",
"re",
"=",
"/",
"^\\d\\.\\d.\\d$",
"/",
";",
"//Test version",
"if",
"(",
"re",
".",
"test",
"(",
"version",
")",
")",
"{",
"imgPath",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"name",
"+",
"'.png'",
")",
";",
"width",
"=",
"76",
";",
"}",
"else",
"if",
"(",
"version",
".",
"length",
"===",
"6",
")",
"{",
"imgPath",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"name",
"+",
"'-larger.png'",
")",
";",
"width",
"=",
"80",
";",
"}",
"else",
"if",
"(",
"version",
".",
"length",
"===",
"7",
")",
"{",
"imgPath",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"name",
"+",
"'-larger.png'",
")",
";",
"width",
"=",
"77",
";",
"}",
"else",
"{",
"imgPath",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"name",
"+",
"'-larger.png'",
")",
";",
"width",
"=",
"74",
";",
"}",
"//Create Image",
"var",
"base",
"=",
"gm",
"(",
"imgPath",
")",
".",
"font",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'fonts'",
",",
"'Arial.ttf'",
")",
")",
".",
"fontSize",
"(",
"10",
")",
".",
"fill",
"(",
"'#ffffff'",
")",
".",
"drawText",
"(",
"width",
",",
"12",
",",
"version",
")",
";",
"//Write Stream and send to client",
"write",
"(",
"base",
",",
"res",
")",
";",
"}"
] | Create version badge | [
"Create",
"version",
"badge"
] | 020e8c9cb899fb3df0da452151d7afb5e6be78f5 | https://github.com/chrisenytc/gngb-api/blob/020e8c9cb899fb3df0da452151d7afb5e6be78f5/lib/gngb-api.js#L43-L71 |
|
57,016 | chrisenytc/gngb-api | lib/gngb-api.js | function (service, name, user) {
//
var services = [];
//
services['gh'] = 'https://api.github.com/repos/:user/:name/releases';
services['npm'] = 'http://registry.npmjs.org/:name/latest';
services['gem'] = 'https://rubygems.org/api/v1/gems/:name.json';
services['bower'] = 'https://api.github.com/repos/:user/:name/releases';
var str = services[service].replace(':name', name).replace(':user', user);
//
return str;
} | javascript | function (service, name, user) {
//
var services = [];
//
services['gh'] = 'https://api.github.com/repos/:user/:name/releases';
services['npm'] = 'http://registry.npmjs.org/:name/latest';
services['gem'] = 'https://rubygems.org/api/v1/gems/:name.json';
services['bower'] = 'https://api.github.com/repos/:user/:name/releases';
var str = services[service].replace(':name', name).replace(':user', user);
//
return str;
} | [
"function",
"(",
"service",
",",
"name",
",",
"user",
")",
"{",
"//",
"var",
"services",
"=",
"[",
"]",
";",
"//",
"services",
"[",
"'gh'",
"]",
"=",
"'https://api.github.com/repos/:user/:name/releases'",
";",
"services",
"[",
"'npm'",
"]",
"=",
"'http://registry.npmjs.org/:name/latest'",
";",
"services",
"[",
"'gem'",
"]",
"=",
"'https://rubygems.org/api/v1/gems/:name.json'",
";",
"services",
"[",
"'bower'",
"]",
"=",
"'https://api.github.com/repos/:user/:name/releases'",
";",
"var",
"str",
"=",
"services",
"[",
"service",
"]",
".",
"replace",
"(",
"':name'",
",",
"name",
")",
".",
"replace",
"(",
"':user'",
",",
"user",
")",
";",
"//",
"return",
"str",
";",
"}"
] | Get formated service url | [
"Get",
"formated",
"service",
"url"
] | 020e8c9cb899fb3df0da452151d7afb5e6be78f5 | https://github.com/chrisenytc/gngb-api/blob/020e8c9cb899fb3df0da452151d7afb5e6be78f5/lib/gngb-api.js#L74-L87 |
|
57,017 | chrisenytc/gngb-api | lib/gngb-api.js | function (service, data) {
switch (service) {
case 'gh':
return data[0].tag_name.replace(/^v/, '');
case 'npm':
return data.version;
case 'gem':
return data.version;
case 'bower':
return data[0].tag_name.replace(/^v/, '');
default:
console.log(service + 'not found!');
break;
}
} | javascript | function (service, data) {
switch (service) {
case 'gh':
return data[0].tag_name.replace(/^v/, '');
case 'npm':
return data.version;
case 'gem':
return data.version;
case 'bower':
return data[0].tag_name.replace(/^v/, '');
default:
console.log(service + 'not found!');
break;
}
} | [
"function",
"(",
"service",
",",
"data",
")",
"{",
"switch",
"(",
"service",
")",
"{",
"case",
"'gh'",
":",
"return",
"data",
"[",
"0",
"]",
".",
"tag_name",
".",
"replace",
"(",
"/",
"^v",
"/",
",",
"''",
")",
";",
"case",
"'npm'",
":",
"return",
"data",
".",
"version",
";",
"case",
"'gem'",
":",
"return",
"data",
".",
"version",
";",
"case",
"'bower'",
":",
"return",
"data",
"[",
"0",
"]",
".",
"tag_name",
".",
"replace",
"(",
"/",
"^v",
"/",
",",
"''",
")",
";",
"default",
":",
"console",
".",
"log",
"(",
"service",
"+",
"'not found!'",
")",
";",
"break",
";",
"}",
"}"
] | Get data and format version | [
"Get",
"data",
"and",
"format",
"version"
] | 020e8c9cb899fb3df0da452151d7afb5e6be78f5 | https://github.com/chrisenytc/gngb-api/blob/020e8c9cb899fb3df0da452151d7afb5e6be78f5/lib/gngb-api.js#L90-L104 |
|
57,018 | skerit/alchemy-styleboost | public/ckeditor/4.4dev/core/resourcemanager.js | function( names, callback, scope ) {
// Ensure that we have an array of names.
if ( !CKEDITOR.tools.isArray( names ) )
names = names ? [ names ] : [];
var loaded = this.loaded,
registered = this.registered,
urls = [],
urlsNames = {},
resources = {};
// Loop through all names.
for ( var i = 0; i < names.length; i++ ) {
var name = names[ i ];
if ( !name )
continue;
// If not available yet.
if ( !loaded[ name ] && !registered[ name ] ) {
var url = this.getFilePath( name );
urls.push( url );
if ( !( url in urlsNames ) )
urlsNames[ url ] = [];
urlsNames[ url ].push( name );
} else {
resources[ name ] = this.get( name );
}
}
CKEDITOR.scriptLoader.load( urls, function( completed, failed ) {
if ( failed.length ) {
throw '[CKEDITOR.resourceManager.load] Resource name "' + urlsNames[ failed[ 0 ] ].join( ',' ) +
'" was not found at "' + failed[ 0 ] + '".';
}
for ( var i = 0; i < completed.length; i++ ) {
var nameList = urlsNames[ completed[ i ] ];
for ( var j = 0; j < nameList.length; j++ ) {
var name = nameList[ j ];
resources[ name ] = this.get( name );
loaded[ name ] = 1;
}
}
callback.call( scope, resources );
}, this );
} | javascript | function( names, callback, scope ) {
// Ensure that we have an array of names.
if ( !CKEDITOR.tools.isArray( names ) )
names = names ? [ names ] : [];
var loaded = this.loaded,
registered = this.registered,
urls = [],
urlsNames = {},
resources = {};
// Loop through all names.
for ( var i = 0; i < names.length; i++ ) {
var name = names[ i ];
if ( !name )
continue;
// If not available yet.
if ( !loaded[ name ] && !registered[ name ] ) {
var url = this.getFilePath( name );
urls.push( url );
if ( !( url in urlsNames ) )
urlsNames[ url ] = [];
urlsNames[ url ].push( name );
} else {
resources[ name ] = this.get( name );
}
}
CKEDITOR.scriptLoader.load( urls, function( completed, failed ) {
if ( failed.length ) {
throw '[CKEDITOR.resourceManager.load] Resource name "' + urlsNames[ failed[ 0 ] ].join( ',' ) +
'" was not found at "' + failed[ 0 ] + '".';
}
for ( var i = 0; i < completed.length; i++ ) {
var nameList = urlsNames[ completed[ i ] ];
for ( var j = 0; j < nameList.length; j++ ) {
var name = nameList[ j ];
resources[ name ] = this.get( name );
loaded[ name ] = 1;
}
}
callback.call( scope, resources );
}, this );
} | [
"function",
"(",
"names",
",",
"callback",
",",
"scope",
")",
"{",
"// Ensure that we have an array of names.",
"if",
"(",
"!",
"CKEDITOR",
".",
"tools",
".",
"isArray",
"(",
"names",
")",
")",
"names",
"=",
"names",
"?",
"[",
"names",
"]",
":",
"[",
"]",
";",
"var",
"loaded",
"=",
"this",
".",
"loaded",
",",
"registered",
"=",
"this",
".",
"registered",
",",
"urls",
"=",
"[",
"]",
",",
"urlsNames",
"=",
"{",
"}",
",",
"resources",
"=",
"{",
"}",
";",
"// Loop through all names.",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"names",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"name",
"=",
"names",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"name",
")",
"continue",
";",
"// If not available yet.",
"if",
"(",
"!",
"loaded",
"[",
"name",
"]",
"&&",
"!",
"registered",
"[",
"name",
"]",
")",
"{",
"var",
"url",
"=",
"this",
".",
"getFilePath",
"(",
"name",
")",
";",
"urls",
".",
"push",
"(",
"url",
")",
";",
"if",
"(",
"!",
"(",
"url",
"in",
"urlsNames",
")",
")",
"urlsNames",
"[",
"url",
"]",
"=",
"[",
"]",
";",
"urlsNames",
"[",
"url",
"]",
".",
"push",
"(",
"name",
")",
";",
"}",
"else",
"{",
"resources",
"[",
"name",
"]",
"=",
"this",
".",
"get",
"(",
"name",
")",
";",
"}",
"}",
"CKEDITOR",
".",
"scriptLoader",
".",
"load",
"(",
"urls",
",",
"function",
"(",
"completed",
",",
"failed",
")",
"{",
"if",
"(",
"failed",
".",
"length",
")",
"{",
"throw",
"'[CKEDITOR.resourceManager.load] Resource name \"'",
"+",
"urlsNames",
"[",
"failed",
"[",
"0",
"]",
"]",
".",
"join",
"(",
"','",
")",
"+",
"'\" was not found at \"'",
"+",
"failed",
"[",
"0",
"]",
"+",
"'\".'",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"completed",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"nameList",
"=",
"urlsNames",
"[",
"completed",
"[",
"i",
"]",
"]",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"nameList",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"name",
"=",
"nameList",
"[",
"j",
"]",
";",
"resources",
"[",
"name",
"]",
"=",
"this",
".",
"get",
"(",
"name",
")",
";",
"loaded",
"[",
"name",
"]",
"=",
"1",
";",
"}",
"}",
"callback",
".",
"call",
"(",
"scope",
",",
"resources",
")",
";",
"}",
",",
"this",
")",
";",
"}"
] | Loads one or more resources.
CKEDITOR.plugins.load( 'myplugin', function( plugins ) {
alert( plugins[ 'myplugin' ] ); // object
} );
@param {String/Array} name The name of the resource to load. It may be a
string with a single resource name, or an array with several names.
@param {Function} callback A function to be called when all resources
are loaded. The callback will receive an array containing all loaded names.
@param {Object} [scope] The scope object to be used for the callback call. | [
"Loads",
"one",
"or",
"more",
"resources",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/resourcemanager.js#L179-L227 |
|
57,019 | bengreenier/lconf | Parser.js | load | function load(file) {
if (path.extname(file) === ".yaml" || path.extname(file) === ".yml") {
return yaml.safeLoad(fs.readFileSync(file));
} else if (path.extname(file) === ".json") {
var r = JSON.parse(fs.readFileSync(file));
return r;
} else if (path.extname(file) === ".js") {
var obj = require(file);
if (typeof(obj) !== "object") {
throw {error: "needs to export object, not "+typeof(obj), file: file};
} else {
return clone(obj);
}
} else {
throw {error: path+" has invalid extension: "+path.extname(file)};
}
} | javascript | function load(file) {
if (path.extname(file) === ".yaml" || path.extname(file) === ".yml") {
return yaml.safeLoad(fs.readFileSync(file));
} else if (path.extname(file) === ".json") {
var r = JSON.parse(fs.readFileSync(file));
return r;
} else if (path.extname(file) === ".js") {
var obj = require(file);
if (typeof(obj) !== "object") {
throw {error: "needs to export object, not "+typeof(obj), file: file};
} else {
return clone(obj);
}
} else {
throw {error: path+" has invalid extension: "+path.extname(file)};
}
} | [
"function",
"load",
"(",
"file",
")",
"{",
"if",
"(",
"path",
".",
"extname",
"(",
"file",
")",
"===",
"\".yaml\"",
"||",
"path",
".",
"extname",
"(",
"file",
")",
"===",
"\".yml\"",
")",
"{",
"return",
"yaml",
".",
"safeLoad",
"(",
"fs",
".",
"readFileSync",
"(",
"file",
")",
")",
";",
"}",
"else",
"if",
"(",
"path",
".",
"extname",
"(",
"file",
")",
"===",
"\".json\"",
")",
"{",
"var",
"r",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"file",
")",
")",
";",
"return",
"r",
";",
"}",
"else",
"if",
"(",
"path",
".",
"extname",
"(",
"file",
")",
"===",
"\".js\"",
")",
"{",
"var",
"obj",
"=",
"require",
"(",
"file",
")",
";",
"if",
"(",
"typeof",
"(",
"obj",
")",
"!==",
"\"object\"",
")",
"{",
"throw",
"{",
"error",
":",
"\"needs to export object, not \"",
"+",
"typeof",
"(",
"obj",
")",
",",
"file",
":",
"file",
"}",
";",
"}",
"else",
"{",
"return",
"clone",
"(",
"obj",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"{",
"error",
":",
"path",
"+",
"\" has invalid extension: \"",
"+",
"path",
".",
"extname",
"(",
"file",
")",
"}",
";",
"}",
"}"
] | Does the actual file parsing | [
"Does",
"the",
"actual",
"file",
"parsing"
] | 212b7e15dc18585be99600a505b35fe94f9758ea | https://github.com/bengreenier/lconf/blob/212b7e15dc18585be99600a505b35fe94f9758ea/Parser.js#L59-L79 |
57,020 | bjnortier/triptych | build/events/EventGenerator.js | addOffset | function addOffset(element, event) {
event.offsetX = Math.round(event.pageX - element.offset().left);
event.offsetY = Math.round(event.pageY - element.offset().top);
return event;
} | javascript | function addOffset(element, event) {
event.offsetX = Math.round(event.pageX - element.offset().left);
event.offsetY = Math.round(event.pageY - element.offset().top);
return event;
} | [
"function",
"addOffset",
"(",
"element",
",",
"event",
")",
"{",
"event",
".",
"offsetX",
"=",
"Math",
".",
"round",
"(",
"event",
".",
"pageX",
"-",
"element",
".",
"offset",
"(",
")",
".",
"left",
")",
";",
"event",
".",
"offsetY",
"=",
"Math",
".",
"round",
"(",
"event",
".",
"pageY",
"-",
"element",
".",
"offset",
"(",
")",
".",
"top",
")",
";",
"return",
"event",
";",
"}"
] | Add offset support to all browsers | [
"Add",
"offset",
"support",
"to",
"all",
"browsers"
] | 3f61ac1b74842ac48d8a1eaef9e71becbcfb1e8a | https://github.com/bjnortier/triptych/blob/3f61ac1b74842ac48d8a1eaef9e71becbcfb1e8a/build/events/EventGenerator.js#L9-L13 |
57,021 | oskarhagberg/gbgcity | lib/traveltime.js | getRoute | function getRoute(id, params, callback) {
params = params || {};
core.callApiWithPathSegment('/TravelTimesService/v1.0/Routes', id, params, callback);
} | javascript | function getRoute(id, params, callback) {
params = params || {};
core.callApiWithPathSegment('/TravelTimesService/v1.0/Routes', id, params, callback);
} | [
"function",
"getRoute",
"(",
"id",
",",
"params",
",",
"callback",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"core",
".",
"callApiWithPathSegment",
"(",
"'/TravelTimesService/v1.0/Routes'",
",",
"id",
",",
"params",
",",
"callback",
")",
";",
"}"
] | Returns a route
@memberof module:gbgcity/TravelTime
@param {String} id The id of the route
@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/TravelTimesService/v1.0/help/operations/GetRoute | [
"Returns",
"a",
"route"
] | d2de903b2fba83cc953ae218905380fef080cb2d | https://github.com/oskarhagberg/gbgcity/blob/d2de903b2fba83cc953ae218905380fef080cb2d/lib/traveltime.js#L27-L30 |
57,022 | scazan/taskengine | taskengine.js | readTasks | function readTasks(err, data, callback) {
this.tasks = JSON.parse(data);
var sortedTasks = _.sortBy(this.tasks, function(task) { return parseInt(task.id, 10); });
largestID = sortedTasks[sortedTasks.length-1].id;
if(callback) {
callback(err, this);
}
} | javascript | function readTasks(err, data, callback) {
this.tasks = JSON.parse(data);
var sortedTasks = _.sortBy(this.tasks, function(task) { return parseInt(task.id, 10); });
largestID = sortedTasks[sortedTasks.length-1].id;
if(callback) {
callback(err, this);
}
} | [
"function",
"readTasks",
"(",
"err",
",",
"data",
",",
"callback",
")",
"{",
"this",
".",
"tasks",
"=",
"JSON",
".",
"parse",
"(",
"data",
")",
";",
"var",
"sortedTasks",
"=",
"_",
".",
"sortBy",
"(",
"this",
".",
"tasks",
",",
"function",
"(",
"task",
")",
"{",
"return",
"parseInt",
"(",
"task",
".",
"id",
",",
"10",
")",
";",
"}",
")",
";",
"largestID",
"=",
"sortedTasks",
"[",
"sortedTasks",
".",
"length",
"-",
"1",
"]",
".",
"id",
";",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"err",
",",
"this",
")",
";",
"}",
"}"
] | Parse the tasks from a string and set the global tasks array
@param err
@param {String} data
@param {function} callback
@return {undefined} | [
"Parse",
"the",
"tasks",
"from",
"a",
"string",
"and",
"set",
"the",
"global",
"tasks",
"array"
] | 0fa7d67f8d33f03fdc10174561110660963a52db | https://github.com/scazan/taskengine/blob/0fa7d67f8d33f03fdc10174561110660963a52db/taskengine.js#L56-L65 |
57,023 | scazan/taskengine | taskengine.js | addTask | function addTask(taskData, subTaskData) {
var subTaskList,
parsedData,
subTask = false;
if(taskData !== undefined) {
if(parseInt(taskData,10) > -1) {
subTaskList = this.getTaskByID(parseInt(taskData,10)).subTasks;
parsedData = this.parseInputData(subTaskData);
subTask = true;
}
else {
parsedData = this.parseInputData(taskData);
}
var newTask = _.clone(defaultTask)
_.extend(newTask, parsedData);
newTask.dateAdded = Date.now();
newTask.id = largestID + 1;
newTask.subTask = subTask;
this.tasks.unshift( newTask );
if(subTask) {
subTaskList.push(newTask.id);
}
console.log('Added:');
return newTask;
}
else {
console.log('no task name given');
return false;
}
} | javascript | function addTask(taskData, subTaskData) {
var subTaskList,
parsedData,
subTask = false;
if(taskData !== undefined) {
if(parseInt(taskData,10) > -1) {
subTaskList = this.getTaskByID(parseInt(taskData,10)).subTasks;
parsedData = this.parseInputData(subTaskData);
subTask = true;
}
else {
parsedData = this.parseInputData(taskData);
}
var newTask = _.clone(defaultTask)
_.extend(newTask, parsedData);
newTask.dateAdded = Date.now();
newTask.id = largestID + 1;
newTask.subTask = subTask;
this.tasks.unshift( newTask );
if(subTask) {
subTaskList.push(newTask.id);
}
console.log('Added:');
return newTask;
}
else {
console.log('no task name given');
return false;
}
} | [
"function",
"addTask",
"(",
"taskData",
",",
"subTaskData",
")",
"{",
"var",
"subTaskList",
",",
"parsedData",
",",
"subTask",
"=",
"false",
";",
"if",
"(",
"taskData",
"!==",
"undefined",
")",
"{",
"if",
"(",
"parseInt",
"(",
"taskData",
",",
"10",
")",
">",
"-",
"1",
")",
"{",
"subTaskList",
"=",
"this",
".",
"getTaskByID",
"(",
"parseInt",
"(",
"taskData",
",",
"10",
")",
")",
".",
"subTasks",
";",
"parsedData",
"=",
"this",
".",
"parseInputData",
"(",
"subTaskData",
")",
";",
"subTask",
"=",
"true",
";",
"}",
"else",
"{",
"parsedData",
"=",
"this",
".",
"parseInputData",
"(",
"taskData",
")",
";",
"}",
"var",
"newTask",
"=",
"_",
".",
"clone",
"(",
"defaultTask",
")",
"_",
".",
"extend",
"(",
"newTask",
",",
"parsedData",
")",
";",
"newTask",
".",
"dateAdded",
"=",
"Date",
".",
"now",
"(",
")",
";",
"newTask",
".",
"id",
"=",
"largestID",
"+",
"1",
";",
"newTask",
".",
"subTask",
"=",
"subTask",
";",
"this",
".",
"tasks",
".",
"unshift",
"(",
"newTask",
")",
";",
"if",
"(",
"subTask",
")",
"{",
"subTaskList",
".",
"push",
"(",
"newTask",
".",
"id",
")",
";",
"}",
"console",
".",
"log",
"(",
"'Added:'",
")",
";",
"return",
"newTask",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'no task name given'",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Add the given task to our array
@param taskData
@param callback
@return {undefined} | [
"Add",
"the",
"given",
"task",
"to",
"our",
"array"
] | 0fa7d67f8d33f03fdc10174561110660963a52db | https://github.com/scazan/taskengine/blob/0fa7d67f8d33f03fdc10174561110660963a52db/taskengine.js#L124-L162 |
57,024 | scazan/taskengine | taskengine.js | closeTask | function closeTask(taskID) {
taskID = parseInt(taskID, 10);
var task = this.getTaskByID(taskID);
if(task) {
task.open = false;
console.log('closing:');
return task;
}
else {
return false;
}
} | javascript | function closeTask(taskID) {
taskID = parseInt(taskID, 10);
var task = this.getTaskByID(taskID);
if(task) {
task.open = false;
console.log('closing:');
return task;
}
else {
return false;
}
} | [
"function",
"closeTask",
"(",
"taskID",
")",
"{",
"taskID",
"=",
"parseInt",
"(",
"taskID",
",",
"10",
")",
";",
"var",
"task",
"=",
"this",
".",
"getTaskByID",
"(",
"taskID",
")",
";",
"if",
"(",
"task",
")",
"{",
"task",
".",
"open",
"=",
"false",
";",
"console",
".",
"log",
"(",
"'closing:'",
")",
";",
"return",
"task",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Set a task as "done" or "closed"
@return {undefined} | [
"Set",
"a",
"task",
"as",
"done",
"or",
"closed"
] | 0fa7d67f8d33f03fdc10174561110660963a52db | https://github.com/scazan/taskengine/blob/0fa7d67f8d33f03fdc10174561110660963a52db/taskengine.js#L214-L228 |
57,025 | sigmaframeworks/sigma-libs | src/phonelib.js | getExample | function getExample(countryCode, numberType, national) {
try {
var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
var numberObj = phoneUtil.getExampleNumberForType(countryCode, numberType);
var format = (national) ? i18n.phonenumbers.PhoneNumberFormat.NATIONAL : i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL;
return phoneUtil.format(numberObj, format);
} catch (e) {
return "";
}
} | javascript | function getExample(countryCode, numberType, national) {
try {
var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
var numberObj = phoneUtil.getExampleNumberForType(countryCode, numberType);
var format = (national) ? i18n.phonenumbers.PhoneNumberFormat.NATIONAL : i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL;
return phoneUtil.format(numberObj, format);
} catch (e) {
return "";
}
} | [
"function",
"getExample",
"(",
"countryCode",
",",
"numberType",
",",
"national",
")",
"{",
"try",
"{",
"var",
"phoneUtil",
"=",
"i18n",
".",
"phonenumbers",
".",
"PhoneNumberUtil",
".",
"getInstance",
"(",
")",
";",
"var",
"numberObj",
"=",
"phoneUtil",
".",
"getExampleNumberForType",
"(",
"countryCode",
",",
"numberType",
")",
";",
"var",
"format",
"=",
"(",
"national",
")",
"?",
"i18n",
".",
"phonenumbers",
".",
"PhoneNumberFormat",
".",
"NATIONAL",
":",
"i18n",
".",
"phonenumbers",
".",
"PhoneNumberFormat",
".",
"INTERNATIONAL",
";",
"return",
"phoneUtil",
".",
"format",
"(",
"numberObj",
",",
"format",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"\"\"",
";",
"}",
"}"
] | get an example number for the given country code | [
"get",
"an",
"example",
"number",
"for",
"the",
"given",
"country",
"code"
] | a2a835bad8f9e08d32a9d4541a14b13a3fed4055 | https://github.com/sigmaframeworks/sigma-libs/blob/a2a835bad8f9e08d32a9d4541a14b13a3fed4055/src/phonelib.js#L18-L27 |
57,026 | sigmaframeworks/sigma-libs | src/phonelib.js | format | function format(number, countryCode, type) {
try {
var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode || '');
type = (typeof type == "undefined") ? i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL : type;
if (type == 0) {
return phoneUtil.format(numberObj, i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL).replace(/[\-\(\)\s\.]/g, '').replace('ext', ',');
}
return phoneUtil.format(numberObj, type);
} catch (e) {
return "";
}
} | javascript | function format(number, countryCode, type) {
try {
var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode || '');
type = (typeof type == "undefined") ? i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL : type;
if (type == 0) {
return phoneUtil.format(numberObj, i18n.phonenumbers.PhoneNumberFormat.INTERNATIONAL).replace(/[\-\(\)\s\.]/g, '').replace('ext', ',');
}
return phoneUtil.format(numberObj, type);
} catch (e) {
return "";
}
} | [
"function",
"format",
"(",
"number",
",",
"countryCode",
",",
"type",
")",
"{",
"try",
"{",
"var",
"phoneUtil",
"=",
"i18n",
".",
"phonenumbers",
".",
"PhoneNumberUtil",
".",
"getInstance",
"(",
")",
";",
"var",
"numberObj",
"=",
"phoneUtil",
".",
"parseAndKeepRawInput",
"(",
"number",
",",
"countryCode",
"||",
"''",
")",
";",
"type",
"=",
"(",
"typeof",
"type",
"==",
"\"undefined\"",
")",
"?",
"i18n",
".",
"phonenumbers",
".",
"PhoneNumberFormat",
".",
"INTERNATIONAL",
":",
"type",
";",
"if",
"(",
"type",
"==",
"0",
")",
"{",
"return",
"phoneUtil",
".",
"format",
"(",
"numberObj",
",",
"i18n",
".",
"phonenumbers",
".",
"PhoneNumberFormat",
".",
"INTERNATIONAL",
")",
".",
"replace",
"(",
"/",
"[\\-\\(\\)\\s\\.]",
"/",
"g",
",",
"''",
")",
".",
"replace",
"(",
"'ext'",
",",
"','",
")",
";",
"}",
"return",
"phoneUtil",
".",
"format",
"(",
"numberObj",
",",
"type",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"\"\"",
";",
"}",
"}"
] | format the given number to the given type | [
"format",
"the",
"given",
"number",
"to",
"the",
"given",
"type"
] | a2a835bad8f9e08d32a9d4541a14b13a3fed4055 | https://github.com/sigmaframeworks/sigma-libs/blob/a2a835bad8f9e08d32a9d4541a14b13a3fed4055/src/phonelib.js#L31-L43 |
57,027 | sigmaframeworks/sigma-libs | src/phonelib.js | isValid | function isValid(number, countryCode) {
try {
var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode);
return phoneUtil.isValidNumber(numberObj);
} catch (e) {
return false;
}
} | javascript | function isValid(number, countryCode) {
try {
var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
var numberObj = phoneUtil.parseAndKeepRawInput(number, countryCode);
return phoneUtil.isValidNumber(numberObj);
} catch (e) {
return false;
}
} | [
"function",
"isValid",
"(",
"number",
",",
"countryCode",
")",
"{",
"try",
"{",
"var",
"phoneUtil",
"=",
"i18n",
".",
"phonenumbers",
".",
"PhoneNumberUtil",
".",
"getInstance",
"(",
")",
";",
"var",
"numberObj",
"=",
"phoneUtil",
".",
"parseAndKeepRawInput",
"(",
"number",
",",
"countryCode",
")",
";",
"return",
"phoneUtil",
".",
"isValidNumber",
"(",
"numberObj",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | check if given number is valid | [
"check",
"if",
"given",
"number",
"is",
"valid"
] | a2a835bad8f9e08d32a9d4541a14b13a3fed4055 | https://github.com/sigmaframeworks/sigma-libs/blob/a2a835bad8f9e08d32a9d4541a14b13a3fed4055/src/phonelib.js#L109-L117 |
57,028 | raincatcher-beta/raincatcher-file-angular | lib/file-client/index.js | create | function create(fileToCreate) {
//Creating a unique channel to get the response
var topicUid = shortid.generate();
var topicParams = {topicUid: topicUid, itemToCreate: fileToCreate};
var donePromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE, CONSTANTS.DONE_PREFIX, topicUid));
var errorPromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE, CONSTANTS.ERROR_PREFIX, topicUid));
mediator.publish(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE), topicParams);
return getTopicPromises(donePromise, errorPromise);
} | javascript | function create(fileToCreate) {
//Creating a unique channel to get the response
var topicUid = shortid.generate();
var topicParams = {topicUid: topicUid, itemToCreate: fileToCreate};
var donePromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE, CONSTANTS.DONE_PREFIX, topicUid));
var errorPromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE, CONSTANTS.ERROR_PREFIX, topicUid));
mediator.publish(fileSubscribers.getTopic(CONSTANTS.TOPICS.CREATE), topicParams);
return getTopicPromises(donePromise, errorPromise);
} | [
"function",
"create",
"(",
"fileToCreate",
")",
"{",
"//Creating a unique channel to get the response",
"var",
"topicUid",
"=",
"shortid",
".",
"generate",
"(",
")",
";",
"var",
"topicParams",
"=",
"{",
"topicUid",
":",
"topicUid",
",",
"itemToCreate",
":",
"fileToCreate",
"}",
";",
"var",
"donePromise",
"=",
"mediator",
".",
"promise",
"(",
"fileSubscribers",
".",
"getTopic",
"(",
"CONSTANTS",
".",
"TOPICS",
".",
"CREATE",
",",
"CONSTANTS",
".",
"DONE_PREFIX",
",",
"topicUid",
")",
")",
";",
"var",
"errorPromise",
"=",
"mediator",
".",
"promise",
"(",
"fileSubscribers",
".",
"getTopic",
"(",
"CONSTANTS",
".",
"TOPICS",
".",
"CREATE",
",",
"CONSTANTS",
".",
"ERROR_PREFIX",
",",
"topicUid",
")",
")",
";",
"mediator",
".",
"publish",
"(",
"fileSubscribers",
".",
"getTopic",
"(",
"CONSTANTS",
".",
"TOPICS",
".",
"CREATE",
")",
",",
"topicParams",
")",
";",
"return",
"getTopicPromises",
"(",
"donePromise",
",",
"errorPromise",
")",
";",
"}"
] | Creating a new file.
@param {object} fileToCreate - The File to create. | [
"Creating",
"a",
"new",
"file",
"."
] | a76d406ca62d6c29da3caf94cc9db75f343ec797 | https://github.com/raincatcher-beta/raincatcher-file-angular/blob/a76d406ca62d6c29da3caf94cc9db75f343ec797/lib/file-client/index.js#L40-L49 |
57,029 | raincatcher-beta/raincatcher-file-angular | lib/file-client/index.js | list | function list() {
var donePromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST, CONSTANTS.DONE_PREFIX));
var errorPromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST, CONSTANTS.ERROR_PREFIX));
mediator.publish(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST));
return getTopicPromises(donePromise, errorPromise);
} | javascript | function list() {
var donePromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST, CONSTANTS.DONE_PREFIX));
var errorPromise = mediator.promise(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST, CONSTANTS.ERROR_PREFIX));
mediator.publish(fileSubscribers.getTopic(CONSTANTS.TOPICS.LIST));
return getTopicPromises(donePromise, errorPromise);
} | [
"function",
"list",
"(",
")",
"{",
"var",
"donePromise",
"=",
"mediator",
".",
"promise",
"(",
"fileSubscribers",
".",
"getTopic",
"(",
"CONSTANTS",
".",
"TOPICS",
".",
"LIST",
",",
"CONSTANTS",
".",
"DONE_PREFIX",
")",
")",
";",
"var",
"errorPromise",
"=",
"mediator",
".",
"promise",
"(",
"fileSubscribers",
".",
"getTopic",
"(",
"CONSTANTS",
".",
"TOPICS",
".",
"LIST",
",",
"CONSTANTS",
".",
"ERROR_PREFIX",
")",
")",
";",
"mediator",
".",
"publish",
"(",
"fileSubscribers",
".",
"getTopic",
"(",
"CONSTANTS",
".",
"TOPICS",
".",
"LIST",
")",
")",
";",
"return",
"getTopicPromises",
"(",
"donePromise",
",",
"errorPromise",
")",
";",
"}"
] | Listing All Files | [
"Listing",
"All",
"Files"
] | a76d406ca62d6c29da3caf94cc9db75f343ec797 | https://github.com/raincatcher-beta/raincatcher-file-angular/blob/a76d406ca62d6c29da3caf94cc9db75f343ec797/lib/file-client/index.js#L54-L60 |
57,030 | thomasmodeneis/soundcloudnodejs | soundcloudnodejs.js | addTrack | function addTrack(options) {
return new Promise(function (resolve, reject) {
var form = new FormData();
form.append('format', 'json');
if (!options.title) {
reject('Error while addTrack track options.title is required but is null');
} else {
form.append('track[title]', options.title);
}
if (!options.description) {
reject('Error while addTrack track options.description is required but is null');
} else {
form.append('track[description]', options.description);
}
if (!options.genre) {
reject('Error while addTrack track options.genre is required but is null');
} else {
form.append('track[genre]', options.genre);
}
var exist_artwork_data = fs.existsSync(options.artwork_data);
if (exist_artwork_data) {
form.append('track[artwork_data]', fs.createReadStream(options.artwork_data));
}
if (options.tag_list) {
form.append('track[tag_list]', options.tag_list);
}
form.append('track[sharing]', options.sharing);
if (!options.oauth_token) {
reject('Error while addTrack track oauth_token is required but is null');
} else {
form.append('oauth_token', options.oauth_token);
}
if (!options.asset_data) {
reject('Error while addTrack track options.asset_data is required but is null');
} else {
var exist_asset_data = fs.existsSync(options.asset_data);
if (DEBUG_MODE_ON) {
console.log("addTrack, exist_asset_data, ", exist_asset_data);
}
if (exist_asset_data) {
form.append('track[asset_data]', fs.createReadStream(options.asset_data));
} else {
reject('Error addTrack could not find options.asset_data --> fs.createReadStream(options.asset_data): ' + exist_asset_data);
}
}
form.getLength(function (err, length) {
fetch('https://api.soundcloud.com/tracks', {
method: 'POST',
body: form,
headers: {'content-length': length}
}).then(function (res) {
return res.json();
}).then(function (json) {
if (DEBUG_MODE_ON) {
console.log('addTrack successful');
}
resolve(json);
}).catch(function (e) {
reject(e);
});
});
});
} | javascript | function addTrack(options) {
return new Promise(function (resolve, reject) {
var form = new FormData();
form.append('format', 'json');
if (!options.title) {
reject('Error while addTrack track options.title is required but is null');
} else {
form.append('track[title]', options.title);
}
if (!options.description) {
reject('Error while addTrack track options.description is required but is null');
} else {
form.append('track[description]', options.description);
}
if (!options.genre) {
reject('Error while addTrack track options.genre is required but is null');
} else {
form.append('track[genre]', options.genre);
}
var exist_artwork_data = fs.existsSync(options.artwork_data);
if (exist_artwork_data) {
form.append('track[artwork_data]', fs.createReadStream(options.artwork_data));
}
if (options.tag_list) {
form.append('track[tag_list]', options.tag_list);
}
form.append('track[sharing]', options.sharing);
if (!options.oauth_token) {
reject('Error while addTrack track oauth_token is required but is null');
} else {
form.append('oauth_token', options.oauth_token);
}
if (!options.asset_data) {
reject('Error while addTrack track options.asset_data is required but is null');
} else {
var exist_asset_data = fs.existsSync(options.asset_data);
if (DEBUG_MODE_ON) {
console.log("addTrack, exist_asset_data, ", exist_asset_data);
}
if (exist_asset_data) {
form.append('track[asset_data]', fs.createReadStream(options.asset_data));
} else {
reject('Error addTrack could not find options.asset_data --> fs.createReadStream(options.asset_data): ' + exist_asset_data);
}
}
form.getLength(function (err, length) {
fetch('https://api.soundcloud.com/tracks', {
method: 'POST',
body: form,
headers: {'content-length': length}
}).then(function (res) {
return res.json();
}).then(function (json) {
if (DEBUG_MODE_ON) {
console.log('addTrack successful');
}
resolve(json);
}).catch(function (e) {
reject(e);
});
});
});
} | [
"function",
"addTrack",
"(",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"form",
"=",
"new",
"FormData",
"(",
")",
";",
"form",
".",
"append",
"(",
"'format'",
",",
"'json'",
")",
";",
"if",
"(",
"!",
"options",
".",
"title",
")",
"{",
"reject",
"(",
"'Error while addTrack track options.title is required but is null'",
")",
";",
"}",
"else",
"{",
"form",
".",
"append",
"(",
"'track[title]'",
",",
"options",
".",
"title",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"description",
")",
"{",
"reject",
"(",
"'Error while addTrack track options.description is required but is null'",
")",
";",
"}",
"else",
"{",
"form",
".",
"append",
"(",
"'track[description]'",
",",
"options",
".",
"description",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"genre",
")",
"{",
"reject",
"(",
"'Error while addTrack track options.genre is required but is null'",
")",
";",
"}",
"else",
"{",
"form",
".",
"append",
"(",
"'track[genre]'",
",",
"options",
".",
"genre",
")",
";",
"}",
"var",
"exist_artwork_data",
"=",
"fs",
".",
"existsSync",
"(",
"options",
".",
"artwork_data",
")",
";",
"if",
"(",
"exist_artwork_data",
")",
"{",
"form",
".",
"append",
"(",
"'track[artwork_data]'",
",",
"fs",
".",
"createReadStream",
"(",
"options",
".",
"artwork_data",
")",
")",
";",
"}",
"if",
"(",
"options",
".",
"tag_list",
")",
"{",
"form",
".",
"append",
"(",
"'track[tag_list]'",
",",
"options",
".",
"tag_list",
")",
";",
"}",
"form",
".",
"append",
"(",
"'track[sharing]'",
",",
"options",
".",
"sharing",
")",
";",
"if",
"(",
"!",
"options",
".",
"oauth_token",
")",
"{",
"reject",
"(",
"'Error while addTrack track oauth_token is required but is null'",
")",
";",
"}",
"else",
"{",
"form",
".",
"append",
"(",
"'oauth_token'",
",",
"options",
".",
"oauth_token",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"asset_data",
")",
"{",
"reject",
"(",
"'Error while addTrack track options.asset_data is required but is null'",
")",
";",
"}",
"else",
"{",
"var",
"exist_asset_data",
"=",
"fs",
".",
"existsSync",
"(",
"options",
".",
"asset_data",
")",
";",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"\"addTrack, exist_asset_data, \"",
",",
"exist_asset_data",
")",
";",
"}",
"if",
"(",
"exist_asset_data",
")",
"{",
"form",
".",
"append",
"(",
"'track[asset_data]'",
",",
"fs",
".",
"createReadStream",
"(",
"options",
".",
"asset_data",
")",
")",
";",
"}",
"else",
"{",
"reject",
"(",
"'Error addTrack could not find options.asset_data --> fs.createReadStream(options.asset_data): '",
"+",
"exist_asset_data",
")",
";",
"}",
"}",
"form",
".",
"getLength",
"(",
"function",
"(",
"err",
",",
"length",
")",
"{",
"fetch",
"(",
"'https://api.soundcloud.com/tracks'",
",",
"{",
"method",
":",
"'POST'",
",",
"body",
":",
"form",
",",
"headers",
":",
"{",
"'content-length'",
":",
"length",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"res",
".",
"json",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"json",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'addTrack successful'",
")",
";",
"}",
"resolve",
"(",
"json",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"reject",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Add a new track
@param options
@param cb
@returns {*} | [
"Add",
"a",
"new",
"track"
] | b52461cdb6cafbe84c3b7ff367196fb03ad27afd | https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L28-L104 |
57,031 | thomasmodeneis/soundcloudnodejs | soundcloudnodejs.js | removeAllTracks | function removeAllTracks(tracks, token, count, callback) {
var track = tracks[count];
if (!track) {
return callback('done');
}
var options = {
id: track.id,
oauth_token: token.oauth_token
};
removeTrack(options).then(function (track) {
if (DEBUG_MODE_ON) {
console.log('removeTrack, ', track);
}
count = count + 1;
removeAllTracks(tracks, token, count, callback)
}).catch(function (err) {
console.log('ERROR: removeTrack, ', err);
count = count + 1;
removeAllTracks(tracks, token, count, callback)
})
} | javascript | function removeAllTracks(tracks, token, count, callback) {
var track = tracks[count];
if (!track) {
return callback('done');
}
var options = {
id: track.id,
oauth_token: token.oauth_token
};
removeTrack(options).then(function (track) {
if (DEBUG_MODE_ON) {
console.log('removeTrack, ', track);
}
count = count + 1;
removeAllTracks(tracks, token, count, callback)
}).catch(function (err) {
console.log('ERROR: removeTrack, ', err);
count = count + 1;
removeAllTracks(tracks, token, count, callback)
})
} | [
"function",
"removeAllTracks",
"(",
"tracks",
",",
"token",
",",
"count",
",",
"callback",
")",
"{",
"var",
"track",
"=",
"tracks",
"[",
"count",
"]",
";",
"if",
"(",
"!",
"track",
")",
"{",
"return",
"callback",
"(",
"'done'",
")",
";",
"}",
"var",
"options",
"=",
"{",
"id",
":",
"track",
".",
"id",
",",
"oauth_token",
":",
"token",
".",
"oauth_token",
"}",
";",
"removeTrack",
"(",
"options",
")",
".",
"then",
"(",
"function",
"(",
"track",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'removeTrack, '",
",",
"track",
")",
";",
"}",
"count",
"=",
"count",
"+",
"1",
";",
"removeAllTracks",
"(",
"tracks",
",",
"token",
",",
"count",
",",
"callback",
")",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"'ERROR: removeTrack, '",
",",
"err",
")",
";",
"count",
"=",
"count",
"+",
"1",
";",
"removeAllTracks",
"(",
"tracks",
",",
"token",
",",
"count",
",",
"callback",
")",
"}",
")",
"}"
] | Remove all tracks for a account.
@param tracks
@param token
@param count
@param callback | [
"Remove",
"all",
"tracks",
"for",
"a",
"account",
"."
] | b52461cdb6cafbe84c3b7ff367196fb03ad27afd | https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L147-L170 |
57,032 | thomasmodeneis/soundcloudnodejs | soundcloudnodejs.js | searchTrack_q | function searchTrack_q(options) {
return new Promise(function (resolve, reject) {
if (!options.oauth_token) {
reject(new Error('Error searchTrack_q oauth_token is required and is null '));
} else {
if (!options.q) {
reject(new Error('Error searchTrack_q options.q is required and is null'));
} else {
var uri = 'https://api.soundcloud.com/me/tracks?format=json&oauth_token=' + options.oauth_token + '&q=' + options.q;
if (DEBUG_MODE_ON) {
console.log("searchTrack_q URI, ", uri);
}
request.getAsync(uri, {timeout: 10000}).spread(function (response, body) {
//console.log('searchTrack_q successful',body);
try {
//console.log(body.toString('utf8'))
resolve(JSON.parse(body.toString('utf8')));
} catch (e) {
if (DEBUG_MODE_ON) {
console.log('Error while searchTrack_q track: ', e);
}
reject(e);
}
}).catch(function (e) {
if (DEBUG_MODE_ON) {
console.log('Error while searchTrack_q track: ', e);
}
reject(e);
});
}
}
});
} | javascript | function searchTrack_q(options) {
return new Promise(function (resolve, reject) {
if (!options.oauth_token) {
reject(new Error('Error searchTrack_q oauth_token is required and is null '));
} else {
if (!options.q) {
reject(new Error('Error searchTrack_q options.q is required and is null'));
} else {
var uri = 'https://api.soundcloud.com/me/tracks?format=json&oauth_token=' + options.oauth_token + '&q=' + options.q;
if (DEBUG_MODE_ON) {
console.log("searchTrack_q URI, ", uri);
}
request.getAsync(uri, {timeout: 10000}).spread(function (response, body) {
//console.log('searchTrack_q successful',body);
try {
//console.log(body.toString('utf8'))
resolve(JSON.parse(body.toString('utf8')));
} catch (e) {
if (DEBUG_MODE_ON) {
console.log('Error while searchTrack_q track: ', e);
}
reject(e);
}
}).catch(function (e) {
if (DEBUG_MODE_ON) {
console.log('Error while searchTrack_q track: ', e);
}
reject(e);
});
}
}
});
} | [
"function",
"searchTrack_q",
"(",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"!",
"options",
".",
"oauth_token",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Error searchTrack_q oauth_token is required and is null '",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"options",
".",
"q",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Error searchTrack_q options.q is required and is null'",
")",
")",
";",
"}",
"else",
"{",
"var",
"uri",
"=",
"'https://api.soundcloud.com/me/tracks?format=json&oauth_token='",
"+",
"options",
".",
"oauth_token",
"+",
"'&q='",
"+",
"options",
".",
"q",
";",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"\"searchTrack_q URI, \"",
",",
"uri",
")",
";",
"}",
"request",
".",
"getAsync",
"(",
"uri",
",",
"{",
"timeout",
":",
"10000",
"}",
")",
".",
"spread",
"(",
"function",
"(",
"response",
",",
"body",
")",
"{",
"//console.log('searchTrack_q successful',body);",
"try",
"{",
"//console.log(body.toString('utf8'))",
"resolve",
"(",
"JSON",
".",
"parse",
"(",
"body",
".",
"toString",
"(",
"'utf8'",
")",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'Error while searchTrack_q track: '",
",",
"e",
")",
";",
"}",
"reject",
"(",
"e",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'Error while searchTrack_q track: '",
",",
"e",
")",
";",
"}",
"reject",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Search for a track
@param options
@returns {bluebird|exports|module.exports} | [
"Search",
"for",
"a",
"track"
] | b52461cdb6cafbe84c3b7ff367196fb03ad27afd | https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L213-L247 |
57,033 | thomasmodeneis/soundcloudnodejs | soundcloudnodejs.js | resolveUri | function resolveUri(options) {
return new Promise(function (resolve, reject) {
if (!options.client_id) {
reject(new Error('Error resolveUri options.client_id is required but is null'));
} else {
if (!options.uri) {
throw new Error('Error resolveUri options.uri is required and is: ' + options.uri);
} else {
var uri = 'http://api.soundcloud.com/resolve.json?url=' + options.uri + '&client_id=' + options.client_id;
request.getAsync(uri, {timeout: 10000}).spread(function (response) {
if (!response.body || response.body.indexOf('404') !== -1) {
if (DEBUG_MODE_ON) {
console.log('Error while resolveUri track: ');
}
reject(new Error('Error while resolveUri track: '));
} else {
if (DEBUG_MODE_ON) {
console.log('resolveUri successful');
}
try {
resolve(JSON.parse(response.body.toString('utf8')));
} catch (e) {
if (DEBUG_MODE_ON) {
console.log('Error while resolveUri track: ' + e);
}
reject(new Error('Error while resolveUri track: ' + e));
}
}
}).catch(function (e) {
if (DEBUG_MODE_ON) {
console.log('Error while resolveUri track: ', e);
}
reject(e);
});
}
}
});
} | javascript | function resolveUri(options) {
return new Promise(function (resolve, reject) {
if (!options.client_id) {
reject(new Error('Error resolveUri options.client_id is required but is null'));
} else {
if (!options.uri) {
throw new Error('Error resolveUri options.uri is required and is: ' + options.uri);
} else {
var uri = 'http://api.soundcloud.com/resolve.json?url=' + options.uri + '&client_id=' + options.client_id;
request.getAsync(uri, {timeout: 10000}).spread(function (response) {
if (!response.body || response.body.indexOf('404') !== -1) {
if (DEBUG_MODE_ON) {
console.log('Error while resolveUri track: ');
}
reject(new Error('Error while resolveUri track: '));
} else {
if (DEBUG_MODE_ON) {
console.log('resolveUri successful');
}
try {
resolve(JSON.parse(response.body.toString('utf8')));
} catch (e) {
if (DEBUG_MODE_ON) {
console.log('Error while resolveUri track: ' + e);
}
reject(new Error('Error while resolveUri track: ' + e));
}
}
}).catch(function (e) {
if (DEBUG_MODE_ON) {
console.log('Error while resolveUri track: ', e);
}
reject(e);
});
}
}
});
} | [
"function",
"resolveUri",
"(",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"!",
"options",
".",
"client_id",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Error resolveUri options.client_id is required but is null'",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"options",
".",
"uri",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Error resolveUri options.uri is required and is: '",
"+",
"options",
".",
"uri",
")",
";",
"}",
"else",
"{",
"var",
"uri",
"=",
"'http://api.soundcloud.com/resolve.json?url='",
"+",
"options",
".",
"uri",
"+",
"'&client_id='",
"+",
"options",
".",
"client_id",
";",
"request",
".",
"getAsync",
"(",
"uri",
",",
"{",
"timeout",
":",
"10000",
"}",
")",
".",
"spread",
"(",
"function",
"(",
"response",
")",
"{",
"if",
"(",
"!",
"response",
".",
"body",
"||",
"response",
".",
"body",
".",
"indexOf",
"(",
"'404'",
")",
"!==",
"-",
"1",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'Error while resolveUri track: '",
")",
";",
"}",
"reject",
"(",
"new",
"Error",
"(",
"'Error while resolveUri track: '",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'resolveUri successful'",
")",
";",
"}",
"try",
"{",
"resolve",
"(",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
".",
"toString",
"(",
"'utf8'",
")",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'Error while resolveUri track: '",
"+",
"e",
")",
";",
"}",
"reject",
"(",
"new",
"Error",
"(",
"'Error while resolveUri track: '",
"+",
"e",
")",
")",
";",
"}",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'Error while resolveUri track: '",
",",
"e",
")",
";",
"}",
"reject",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Resolve a URI
@param options
@returns {bluebird|exports|module.exports} | [
"Resolve",
"a",
"URI"
] | b52461cdb6cafbe84c3b7ff367196fb03ad27afd | https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L254-L295 |
57,034 | thomasmodeneis/soundcloudnodejs | soundcloudnodejs.js | addTrackToNewPlaylist | function addTrackToNewPlaylist(options) {
return new Promise(function (resolve, reject) {
var form = new FormData();
form.append('format', 'json');
if (!options.tracks) {
return reject('Error while addTrackToNewPlaylist options.tracks is null');
} else {
_.each(options.tracks, function (track) {
form.append('playlist[tracks][][id]', track.id);
});
}
if (!options.title) {
return reject('Error while addTrackToNewPlaylist options.title is null');
} else {
form.append('playlist[title]', options.title);
}
if (!options.sharing) {
return reject('Error while addTrackToNewPlaylist options.sharing is null');
} else {
form.append('playlist[sharing]', options.sharing);
}
if (!options.oauth_token) {
return reject('Error while addTrackToNewPlaylist options.oauth_token is null');
} else {
form.append('oauth_token', options.oauth_token);
}
form.getLength(function (err, length) {
fetch(`https://api.soundcloud.com/playlists?oauth_token=${options.oauth_token}`, {
method: 'POST',
body: form,
headers: {'content-length': length}
}).then(function (res) {
if (res.status === 201) {
if (DEBUG_MODE_ON) {
console.log(`INFO: addTrackToNewPlaylist, OK -> ${res.statusCode}.`);
}
return res.json();
} else {
return null;
}
}).then(function (json) {
if (!json) {
reject();
} else {
if (DEBUG_MODE_ON) {
console.log('INFO: addTrack successful');
}
resolve(json);
}
}).catch(function (e) {
reject(e);
});
});
});
} | javascript | function addTrackToNewPlaylist(options) {
return new Promise(function (resolve, reject) {
var form = new FormData();
form.append('format', 'json');
if (!options.tracks) {
return reject('Error while addTrackToNewPlaylist options.tracks is null');
} else {
_.each(options.tracks, function (track) {
form.append('playlist[tracks][][id]', track.id);
});
}
if (!options.title) {
return reject('Error while addTrackToNewPlaylist options.title is null');
} else {
form.append('playlist[title]', options.title);
}
if (!options.sharing) {
return reject('Error while addTrackToNewPlaylist options.sharing is null');
} else {
form.append('playlist[sharing]', options.sharing);
}
if (!options.oauth_token) {
return reject('Error while addTrackToNewPlaylist options.oauth_token is null');
} else {
form.append('oauth_token', options.oauth_token);
}
form.getLength(function (err, length) {
fetch(`https://api.soundcloud.com/playlists?oauth_token=${options.oauth_token}`, {
method: 'POST',
body: form,
headers: {'content-length': length}
}).then(function (res) {
if (res.status === 201) {
if (DEBUG_MODE_ON) {
console.log(`INFO: addTrackToNewPlaylist, OK -> ${res.statusCode}.`);
}
return res.json();
} else {
return null;
}
}).then(function (json) {
if (!json) {
reject();
} else {
if (DEBUG_MODE_ON) {
console.log('INFO: addTrack successful');
}
resolve(json);
}
}).catch(function (e) {
reject(e);
});
});
});
} | [
"function",
"addTrackToNewPlaylist",
"(",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"var",
"form",
"=",
"new",
"FormData",
"(",
")",
";",
"form",
".",
"append",
"(",
"'format'",
",",
"'json'",
")",
";",
"if",
"(",
"!",
"options",
".",
"tracks",
")",
"{",
"return",
"reject",
"(",
"'Error while addTrackToNewPlaylist options.tracks is null'",
")",
";",
"}",
"else",
"{",
"_",
".",
"each",
"(",
"options",
".",
"tracks",
",",
"function",
"(",
"track",
")",
"{",
"form",
".",
"append",
"(",
"'playlist[tracks][][id]'",
",",
"track",
".",
"id",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"title",
")",
"{",
"return",
"reject",
"(",
"'Error while addTrackToNewPlaylist options.title is null'",
")",
";",
"}",
"else",
"{",
"form",
".",
"append",
"(",
"'playlist[title]'",
",",
"options",
".",
"title",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"sharing",
")",
"{",
"return",
"reject",
"(",
"'Error while addTrackToNewPlaylist options.sharing is null'",
")",
";",
"}",
"else",
"{",
"form",
".",
"append",
"(",
"'playlist[sharing]'",
",",
"options",
".",
"sharing",
")",
";",
"}",
"if",
"(",
"!",
"options",
".",
"oauth_token",
")",
"{",
"return",
"reject",
"(",
"'Error while addTrackToNewPlaylist options.oauth_token is null'",
")",
";",
"}",
"else",
"{",
"form",
".",
"append",
"(",
"'oauth_token'",
",",
"options",
".",
"oauth_token",
")",
";",
"}",
"form",
".",
"getLength",
"(",
"function",
"(",
"err",
",",
"length",
")",
"{",
"fetch",
"(",
"`",
"${",
"options",
".",
"oauth_token",
"}",
"`",
",",
"{",
"method",
":",
"'POST'",
",",
"body",
":",
"form",
",",
"headers",
":",
"{",
"'content-length'",
":",
"length",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"if",
"(",
"res",
".",
"status",
"===",
"201",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"res",
".",
"statusCode",
"}",
"`",
")",
";",
"}",
"return",
"res",
".",
"json",
"(",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"json",
")",
"{",
"reject",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'INFO: addTrack successful'",
")",
";",
"}",
"resolve",
"(",
"json",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"reject",
"(",
"e",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Add track to new playlist
@param options
@param cb
@returns {*} | [
"Add",
"track",
"to",
"new",
"playlist"
] | b52461cdb6cafbe84c3b7ff367196fb03ad27afd | https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L377-L436 |
57,035 | thomasmodeneis/soundcloudnodejs | soundcloudnodejs.js | getPlaylist | function getPlaylist(options) {
return new Promise(function (resolve, reject) {
if (!options.oauth_token) {
reject(new Error('Error oauth_token is required, but is null'));
} else {
var uri = 'https://api.soundcloud.com/me/playlists?format=json&oauth_token=' + options.oauth_token;
request.getAsync(uri, {timeout: 10000}).spread(function (response, body) {
try {
var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) {
return track;
});
if (DEBUG_MODE_ON) {
console.log('getPlaylist successful');
}
resolve(tracks);
} catch (e) {
if (DEBUG_MODE_ON) {
console.log('Error while getPlaylist track: ', e);
}
reject(e);
}
}).catch(function (e) {
if (DEBUG_MODE_ON) {
console.log('Error while getPlaylist track: ' + e);
}
reject(e);
})
}
});
} | javascript | function getPlaylist(options) {
return new Promise(function (resolve, reject) {
if (!options.oauth_token) {
reject(new Error('Error oauth_token is required, but is null'));
} else {
var uri = 'https://api.soundcloud.com/me/playlists?format=json&oauth_token=' + options.oauth_token;
request.getAsync(uri, {timeout: 10000}).spread(function (response, body) {
try {
var tracks = _.map(JSON.parse(body.toString('utf8')), function (track) {
return track;
});
if (DEBUG_MODE_ON) {
console.log('getPlaylist successful');
}
resolve(tracks);
} catch (e) {
if (DEBUG_MODE_ON) {
console.log('Error while getPlaylist track: ', e);
}
reject(e);
}
}).catch(function (e) {
if (DEBUG_MODE_ON) {
console.log('Error while getPlaylist track: ' + e);
}
reject(e);
})
}
});
} | [
"function",
"getPlaylist",
"(",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"!",
"options",
".",
"oauth_token",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Error oauth_token is required, but is null'",
")",
")",
";",
"}",
"else",
"{",
"var",
"uri",
"=",
"'https://api.soundcloud.com/me/playlists?format=json&oauth_token='",
"+",
"options",
".",
"oauth_token",
";",
"request",
".",
"getAsync",
"(",
"uri",
",",
"{",
"timeout",
":",
"10000",
"}",
")",
".",
"spread",
"(",
"function",
"(",
"response",
",",
"body",
")",
"{",
"try",
"{",
"var",
"tracks",
"=",
"_",
".",
"map",
"(",
"JSON",
".",
"parse",
"(",
"body",
".",
"toString",
"(",
"'utf8'",
")",
")",
",",
"function",
"(",
"track",
")",
"{",
"return",
"track",
";",
"}",
")",
";",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'getPlaylist successful'",
")",
";",
"}",
"resolve",
"(",
"tracks",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'Error while getPlaylist track: '",
",",
"e",
")",
";",
"}",
"reject",
"(",
"e",
")",
";",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"'Error while getPlaylist track: '",
"+",
"e",
")",
";",
"}",
"reject",
"(",
"e",
")",
";",
"}",
")",
"}",
"}",
")",
";",
"}"
] | Get a playlist
@param options
@returns {bluebird|exports|module.exports} | [
"Get",
"a",
"playlist"
] | b52461cdb6cafbe84c3b7ff367196fb03ad27afd | https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L443-L473 |
57,036 | thomasmodeneis/soundcloudnodejs | soundcloudnodejs.js | getToken | function getToken(options) {
return new Promise(function (resolve) {
var curl_options = {
'url': 'https://api.soundcloud.com/oauth2/token',
'method': 'POST',
verbose: true,
encoding: 'utf8',
data: options,
timeout: 10000
};
curlrequest.request(curl_options, function (err, data, meta) {
if (err) {
if (DEBUG_MODE_ON) {
console.log("Error: getToken, ", err, data, meta);
}
resolve(null);
} else if (!data) {
if (DEBUG_MODE_ON) {
console.log("Error: getToken, data is null ", data, meta);
}
resolve(null);
} else {
try {
resolve(JSON.parse(data), meta);
} catch (e) {
if (DEBUG_MODE_ON) {
console.log("Error: getToken, catch, ", e, data, meta);
}
resolve(null);
}
}
});
});
} | javascript | function getToken(options) {
return new Promise(function (resolve) {
var curl_options = {
'url': 'https://api.soundcloud.com/oauth2/token',
'method': 'POST',
verbose: true,
encoding: 'utf8',
data: options,
timeout: 10000
};
curlrequest.request(curl_options, function (err, data, meta) {
if (err) {
if (DEBUG_MODE_ON) {
console.log("Error: getToken, ", err, data, meta);
}
resolve(null);
} else if (!data) {
if (DEBUG_MODE_ON) {
console.log("Error: getToken, data is null ", data, meta);
}
resolve(null);
} else {
try {
resolve(JSON.parse(data), meta);
} catch (e) {
if (DEBUG_MODE_ON) {
console.log("Error: getToken, catch, ", e, data, meta);
}
resolve(null);
}
}
});
});
} | [
"function",
"getToken",
"(",
"options",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
")",
"{",
"var",
"curl_options",
"=",
"{",
"'url'",
":",
"'https://api.soundcloud.com/oauth2/token'",
",",
"'method'",
":",
"'POST'",
",",
"verbose",
":",
"true",
",",
"encoding",
":",
"'utf8'",
",",
"data",
":",
"options",
",",
"timeout",
":",
"10000",
"}",
";",
"curlrequest",
".",
"request",
"(",
"curl_options",
",",
"function",
"(",
"err",
",",
"data",
",",
"meta",
")",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"\"Error: getToken, \"",
",",
"err",
",",
"data",
",",
"meta",
")",
";",
"}",
"resolve",
"(",
"null",
")",
";",
"}",
"else",
"if",
"(",
"!",
"data",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"\"Error: getToken, data is null \"",
",",
"data",
",",
"meta",
")",
";",
"}",
"resolve",
"(",
"null",
")",
";",
"}",
"else",
"{",
"try",
"{",
"resolve",
"(",
"JSON",
".",
"parse",
"(",
"data",
")",
",",
"meta",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"DEBUG_MODE_ON",
")",
"{",
"console",
".",
"log",
"(",
"\"Error: getToken, catch, \"",
",",
"e",
",",
"data",
",",
"meta",
")",
";",
"}",
"resolve",
"(",
"null",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | Get a fresh token, need to be use with caution as SoundCloud will allow you to get very few tokens
Its smart to save your tokens and re-use it along your code
@param options
@returns {bluebird|exports|module.exports} | [
"Get",
"a",
"fresh",
"token",
"need",
"to",
"be",
"use",
"with",
"caution",
"as",
"SoundCloud",
"will",
"allow",
"you",
"to",
"get",
"very",
"few",
"tokens",
"Its",
"smart",
"to",
"save",
"your",
"tokens",
"and",
"re",
"-",
"use",
"it",
"along",
"your",
"code"
] | b52461cdb6cafbe84c3b7ff367196fb03ad27afd | https://github.com/thomasmodeneis/soundcloudnodejs/blob/b52461cdb6cafbe84c3b7ff367196fb03ad27afd/soundcloudnodejs.js#L558-L593 |
57,037 | thanhpk/vue2-strap | dist/dropdownhover.js | DropdownHover | function DropdownHover($elem, options) {
var args = arguments;
// Is the first parameter an object (options), or was omitted,
// instantiate a new instance of the plugin.
if (options === undefined || typeof options === 'object') {
// This allows the plugin to be called with $.fn.bootstrapDropdownHover();
if (!$.contains(document, $($elem)[0])) {
$('[data-toggle="dropdown"]').each(function (index, item) {
// For each nested select, instantiate the plugin
console.log(item, $elem);
$(item).bootstrapDropdownHover(options);
});
}
return $elem.each(function () {
// If this is not a select
if (!$(this).hasClass('dropdown-toggle') || $(this).data('toggle') !== 'dropdown') {
$('[data-toggle="dropdown"]', this).each(function (index, item) {
// For each nested select, instantiate the plugin
DropdownHover($(item), options);
});
} else if (!$.data(this, 'plugin_' + pluginName)) {
// Only allow the plugin to be instantiated once so we check
// that the element has no plugin instantiation yet
// if it has no instance, create a new one, pass options to our
// plugin constructor,
// and store the plugin instance in the elements jQuery data object.
$.data(this, 'plugin_' + pluginName, new BootstrapDropdownHover(this, options));
}
});
// If the first parameter is a string and it doesn't start
// with an underscore or "contains" the `init`-function,
// treat this as a call to a public method.
} else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
// Cache the method call to make it possible to return a value
var returns;
$elem.each(function () {
var instance = $.data(this, 'plugin_' + pluginName);
// Tests that there's already a plugin-instance and checks that
// the requested public method exists
if (instance instanceof BootstrapDropdownHover && typeof instance[options] === 'function') {
// Call the method of our plugin instance, and pass
// it the supplied arguments.
returns = instance[options]
.apply(instance, Array.prototype.slice.call(args, 1));
}
});
// If the earlier cached method gives a value back return the value,
// otherwise return this to preserve chainability.
return returns !== undefined ? returns : this;
}
return undefined;
} | javascript | function DropdownHover($elem, options) {
var args = arguments;
// Is the first parameter an object (options), or was omitted,
// instantiate a new instance of the plugin.
if (options === undefined || typeof options === 'object') {
// This allows the plugin to be called with $.fn.bootstrapDropdownHover();
if (!$.contains(document, $($elem)[0])) {
$('[data-toggle="dropdown"]').each(function (index, item) {
// For each nested select, instantiate the plugin
console.log(item, $elem);
$(item).bootstrapDropdownHover(options);
});
}
return $elem.each(function () {
// If this is not a select
if (!$(this).hasClass('dropdown-toggle') || $(this).data('toggle') !== 'dropdown') {
$('[data-toggle="dropdown"]', this).each(function (index, item) {
// For each nested select, instantiate the plugin
DropdownHover($(item), options);
});
} else if (!$.data(this, 'plugin_' + pluginName)) {
// Only allow the plugin to be instantiated once so we check
// that the element has no plugin instantiation yet
// if it has no instance, create a new one, pass options to our
// plugin constructor,
// and store the plugin instance in the elements jQuery data object.
$.data(this, 'plugin_' + pluginName, new BootstrapDropdownHover(this, options));
}
});
// If the first parameter is a string and it doesn't start
// with an underscore or "contains" the `init`-function,
// treat this as a call to a public method.
} else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
// Cache the method call to make it possible to return a value
var returns;
$elem.each(function () {
var instance = $.data(this, 'plugin_' + pluginName);
// Tests that there's already a plugin-instance and checks that
// the requested public method exists
if (instance instanceof BootstrapDropdownHover && typeof instance[options] === 'function') {
// Call the method of our plugin instance, and pass
// it the supplied arguments.
returns = instance[options]
.apply(instance, Array.prototype.slice.call(args, 1));
}
});
// If the earlier cached method gives a value back return the value,
// otherwise return this to preserve chainability.
return returns !== undefined ? returns : this;
}
return undefined;
} | [
"function",
"DropdownHover",
"(",
"$elem",
",",
"options",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"// Is the first parameter an object (options), or was omitted,",
"// instantiate a new instance of the plugin.",
"if",
"(",
"options",
"===",
"undefined",
"||",
"typeof",
"options",
"===",
"'object'",
")",
"{",
"// This allows the plugin to be called with $.fn.bootstrapDropdownHover();",
"if",
"(",
"!",
"$",
".",
"contains",
"(",
"document",
",",
"$",
"(",
"$elem",
")",
"[",
"0",
"]",
")",
")",
"{",
"$",
"(",
"'[data-toggle=\"dropdown\"]'",
")",
".",
"each",
"(",
"function",
"(",
"index",
",",
"item",
")",
"{",
"// For each nested select, instantiate the plugin",
"console",
".",
"log",
"(",
"item",
",",
"$elem",
")",
";",
"$",
"(",
"item",
")",
".",
"bootstrapDropdownHover",
"(",
"options",
")",
";",
"}",
")",
";",
"}",
"return",
"$elem",
".",
"each",
"(",
"function",
"(",
")",
"{",
"// If this is not a select",
"if",
"(",
"!",
"$",
"(",
"this",
")",
".",
"hasClass",
"(",
"'dropdown-toggle'",
")",
"||",
"$",
"(",
"this",
")",
".",
"data",
"(",
"'toggle'",
")",
"!==",
"'dropdown'",
")",
"{",
"$",
"(",
"'[data-toggle=\"dropdown\"]'",
",",
"this",
")",
".",
"each",
"(",
"function",
"(",
"index",
",",
"item",
")",
"{",
"// For each nested select, instantiate the plugin",
"DropdownHover",
"(",
"$",
"(",
"item",
")",
",",
"options",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"!",
"$",
".",
"data",
"(",
"this",
",",
"'plugin_'",
"+",
"pluginName",
")",
")",
"{",
"// Only allow the plugin to be instantiated once so we check",
"// that the element has no plugin instantiation yet",
"// if it has no instance, create a new one, pass options to our",
"// plugin constructor,",
"// and store the plugin instance in the elements jQuery data object.",
"$",
".",
"data",
"(",
"this",
",",
"'plugin_'",
"+",
"pluginName",
",",
"new",
"BootstrapDropdownHover",
"(",
"this",
",",
"options",
")",
")",
";",
"}",
"}",
")",
";",
"// If the first parameter is a string and it doesn't start",
"// with an underscore or \"contains\" the `init`-function,",
"// treat this as a call to a public method.",
"}",
"else",
"if",
"(",
"typeof",
"options",
"===",
"'string'",
"&&",
"options",
"[",
"0",
"]",
"!==",
"'_'",
"&&",
"options",
"!==",
"'init'",
")",
"{",
"// Cache the method call to make it possible to return a value",
"var",
"returns",
";",
"$elem",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"instance",
"=",
"$",
".",
"data",
"(",
"this",
",",
"'plugin_'",
"+",
"pluginName",
")",
";",
"// Tests that there's already a plugin-instance and checks that",
"// the requested public method exists",
"if",
"(",
"instance",
"instanceof",
"BootstrapDropdownHover",
"&&",
"typeof",
"instance",
"[",
"options",
"]",
"===",
"'function'",
")",
"{",
"// Call the method of our plugin instance, and pass",
"// it the supplied arguments.",
"returns",
"=",
"instance",
"[",
"options",
"]",
".",
"apply",
"(",
"instance",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"args",
",",
"1",
")",
")",
";",
"}",
"}",
")",
";",
"// If the earlier cached method gives a value back return the value,",
"// otherwise return this to preserve chainability.",
"return",
"returns",
"!==",
"undefined",
"?",
"returns",
":",
"this",
";",
"}",
"return",
"undefined",
";",
"}"
] | A really lightweight plugin wrapper around the constructor, preventing against multiple instantiations | [
"A",
"really",
"lightweight",
"plugin",
"wrapper",
"around",
"the",
"constructor",
"preventing",
"against",
"multiple",
"instantiations"
] | 44e93ce3c985b31aa7ccb11f67842914ddb6013f | https://github.com/thanhpk/vue2-strap/blob/44e93ce3c985b31aa7ccb11f67842914ddb6013f/dist/dropdownhover.js#L162-L220 |
57,038 | Barandis/xduce | src/modules/reduction.js | init | function init(collection) {
switch (true) {
case isImplemented(collection, 'init'):
return collection[p.init];
case isString(collection):
return () => '';
case isArray(collection):
return () => [];
case isObject(collection):
return () => ({});
case isFunction(collection):
return () => {
throw Error('init not available');
};
default:
return null;
}
} | javascript | function init(collection) {
switch (true) {
case isImplemented(collection, 'init'):
return collection[p.init];
case isString(collection):
return () => '';
case isArray(collection):
return () => [];
case isObject(collection):
return () => ({});
case isFunction(collection):
return () => {
throw Error('init not available');
};
default:
return null;
}
} | [
"function",
"init",
"(",
"collection",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"isImplemented",
"(",
"collection",
",",
"'init'",
")",
":",
"return",
"collection",
"[",
"p",
".",
"init",
"]",
";",
"case",
"isString",
"(",
"collection",
")",
":",
"return",
"(",
")",
"=>",
"''",
";",
"case",
"isArray",
"(",
"collection",
")",
":",
"return",
"(",
")",
"=>",
"[",
"]",
";",
"case",
"isObject",
"(",
"collection",
")",
":",
"return",
"(",
")",
"=>",
"(",
"{",
"}",
")",
";",
"case",
"isFunction",
"(",
"collection",
")",
":",
"return",
"(",
")",
"=>",
"{",
"throw",
"Error",
"(",
"'init not available'",
")",
";",
"}",
";",
"default",
":",
"return",
"null",
";",
"}",
"}"
] | Returns an init function for a collection. This is a function that returns a new, empty instance of the collection in
question. If the collection doesn't support reduction, `null` is returned. This makes conditionals a bit easier to
work with.
In order to support the conversion of functions into reducers, function support is also provided.
@private
@param {*} collection A collection to create an init function for. This can be anything that supports the ES2015
iteration protocol, a plain object, a pre-ES2015 string or array, or a function.
@return {module:xduce~init} A function that, when called, returns an initial version of the provided collection. If
the provided collection is not iterable, then `null` is returned. | [
"Returns",
"an",
"init",
"function",
"for",
"a",
"collection",
".",
"This",
"is",
"a",
"function",
"that",
"returns",
"a",
"new",
"empty",
"instance",
"of",
"the",
"collection",
"in",
"question",
".",
"If",
"the",
"collection",
"doesn",
"t",
"support",
"reduction",
"null",
"is",
"returned",
".",
"This",
"makes",
"conditionals",
"a",
"bit",
"easier",
"to",
"work",
"with",
"."
] | b454f154f7663475670d4802e28e98ade8c468e7 | https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/reduction.js#L49-L66 |
57,039 | Barandis/xduce | src/modules/reduction.js | step | function step(collection) {
switch (true) {
case isImplemented(collection, 'step'):
return collection[p.step];
case isString(collection):
return (acc, input) => {
const value = isKvFormObject(input) ? input.v : input;
return acc + value;
};
case isArray(collection):
return (acc, input) => {
const value = isKvFormObject(input) ? { [input.k]: input.v } : input;
acc.push(value);
return acc;
};
case isObject(collection):
return (acc, input) => {
let value = input;
if (isKvFormObject(input)) {
// if the object is kv-form, change the object from { k: key, v: value } to { key: value }
value = { [input.k]: input.v };
} else if (!isObject(input)) {
// if the input isn't an object at all, turn it into an object with a key based on what's already in the
// accumulator
let max = -1;
for (const k1 in acc) {
const knum = parseInt(k1);
if (knum > max) {
max = knum;
}
}
value = { [max + 1]: input };
}
for (const k2 in value) {
if (value.hasOwnProperty(k2)) {
acc[k2] = value[k2];
}
}
return acc;
};
case isFunction(collection):
return (acc, input) => collection(acc, input);
default:
return null;
}
} | javascript | function step(collection) {
switch (true) {
case isImplemented(collection, 'step'):
return collection[p.step];
case isString(collection):
return (acc, input) => {
const value = isKvFormObject(input) ? input.v : input;
return acc + value;
};
case isArray(collection):
return (acc, input) => {
const value = isKvFormObject(input) ? { [input.k]: input.v } : input;
acc.push(value);
return acc;
};
case isObject(collection):
return (acc, input) => {
let value = input;
if (isKvFormObject(input)) {
// if the object is kv-form, change the object from { k: key, v: value } to { key: value }
value = { [input.k]: input.v };
} else if (!isObject(input)) {
// if the input isn't an object at all, turn it into an object with a key based on what's already in the
// accumulator
let max = -1;
for (const k1 in acc) {
const knum = parseInt(k1);
if (knum > max) {
max = knum;
}
}
value = { [max + 1]: input };
}
for (const k2 in value) {
if (value.hasOwnProperty(k2)) {
acc[k2] = value[k2];
}
}
return acc;
};
case isFunction(collection):
return (acc, input) => collection(acc, input);
default:
return null;
}
} | [
"function",
"step",
"(",
"collection",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"isImplemented",
"(",
"collection",
",",
"'step'",
")",
":",
"return",
"collection",
"[",
"p",
".",
"step",
"]",
";",
"case",
"isString",
"(",
"collection",
")",
":",
"return",
"(",
"acc",
",",
"input",
")",
"=>",
"{",
"const",
"value",
"=",
"isKvFormObject",
"(",
"input",
")",
"?",
"input",
".",
"v",
":",
"input",
";",
"return",
"acc",
"+",
"value",
";",
"}",
";",
"case",
"isArray",
"(",
"collection",
")",
":",
"return",
"(",
"acc",
",",
"input",
")",
"=>",
"{",
"const",
"value",
"=",
"isKvFormObject",
"(",
"input",
")",
"?",
"{",
"[",
"input",
".",
"k",
"]",
":",
"input",
".",
"v",
"}",
":",
"input",
";",
"acc",
".",
"push",
"(",
"value",
")",
";",
"return",
"acc",
";",
"}",
";",
"case",
"isObject",
"(",
"collection",
")",
":",
"return",
"(",
"acc",
",",
"input",
")",
"=>",
"{",
"let",
"value",
"=",
"input",
";",
"if",
"(",
"isKvFormObject",
"(",
"input",
")",
")",
"{",
"// if the object is kv-form, change the object from { k: key, v: value } to { key: value }",
"value",
"=",
"{",
"[",
"input",
".",
"k",
"]",
":",
"input",
".",
"v",
"}",
";",
"}",
"else",
"if",
"(",
"!",
"isObject",
"(",
"input",
")",
")",
"{",
"// if the input isn't an object at all, turn it into an object with a key based on what's already in the",
"// accumulator",
"let",
"max",
"=",
"-",
"1",
";",
"for",
"(",
"const",
"k1",
"in",
"acc",
")",
"{",
"const",
"knum",
"=",
"parseInt",
"(",
"k1",
")",
";",
"if",
"(",
"knum",
">",
"max",
")",
"{",
"max",
"=",
"knum",
";",
"}",
"}",
"value",
"=",
"{",
"[",
"max",
"+",
"1",
"]",
":",
"input",
"}",
";",
"}",
"for",
"(",
"const",
"k2",
"in",
"value",
")",
"{",
"if",
"(",
"value",
".",
"hasOwnProperty",
"(",
"k2",
")",
")",
"{",
"acc",
"[",
"k2",
"]",
"=",
"value",
"[",
"k2",
"]",
";",
"}",
"}",
"return",
"acc",
";",
"}",
";",
"case",
"isFunction",
"(",
"collection",
")",
":",
"return",
"(",
"acc",
",",
"input",
")",
"=>",
"collection",
"(",
"acc",
",",
"input",
")",
";",
"default",
":",
"return",
"null",
";",
"}",
"}"
] | Returns a step function for a collection. This is a function that takes an accumulator and a value and returns the
result of reducing the value into the accumulator. If the collection doesn't support reduction, `null` is returned.
The returned function itself simply reduces the input into the target collection without modifying it.
In order to support the conversion of functions into reducers, function support is also provided.
@private
@param {*} collection A collection to create a step function for. This can be anything that supports the ES2015
iteration protocol, a plain object, a pre-ES2015 string or array, or a function.
@return {module:xduce~step} A reduction function for the provided collection that simply adds an element to the
target collection without modifying it. If the provided collection is not iterable, `null` is returned. | [
"Returns",
"a",
"step",
"function",
"for",
"a",
"collection",
".",
"This",
"is",
"a",
"function",
"that",
"takes",
"an",
"accumulator",
"and",
"a",
"value",
"and",
"returns",
"the",
"result",
"of",
"reducing",
"the",
"value",
"into",
"the",
"accumulator",
".",
"If",
"the",
"collection",
"doesn",
"t",
"support",
"reduction",
"null",
"is",
"returned",
".",
"The",
"returned",
"function",
"itself",
"simply",
"reduces",
"the",
"input",
"into",
"the",
"target",
"collection",
"without",
"modifying",
"it",
"."
] | b454f154f7663475670d4802e28e98ade8c468e7 | https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/reduction.js#L82-L134 |
57,040 | Barandis/xduce | src/modules/reduction.js | result | function result(collection) {
switch (true) {
case isImplemented(collection, 'result'):
return collection[p.result];
case isString(collection):
case isArray(collection):
case isObject(collection):
case isFunction(collection):
return value => value;
default:
return null;
}
} | javascript | function result(collection) {
switch (true) {
case isImplemented(collection, 'result'):
return collection[p.result];
case isString(collection):
case isArray(collection):
case isObject(collection):
case isFunction(collection):
return value => value;
default:
return null;
}
} | [
"function",
"result",
"(",
"collection",
")",
"{",
"switch",
"(",
"true",
")",
"{",
"case",
"isImplemented",
"(",
"collection",
",",
"'result'",
")",
":",
"return",
"collection",
"[",
"p",
".",
"result",
"]",
";",
"case",
"isString",
"(",
"collection",
")",
":",
"case",
"isArray",
"(",
"collection",
")",
":",
"case",
"isObject",
"(",
"collection",
")",
":",
"case",
"isFunction",
"(",
"collection",
")",
":",
"return",
"value",
"=>",
"value",
";",
"default",
":",
"return",
"null",
";",
"}",
"}"
] | Returns a result function for a collection. This is a function that performs any final processing that should be done
on the result of a reduction. If the collection doesn't support reduction, `null` is returned.
In order to support the conversion of functions into reducers, function support is also provided.
@private
@param {*} collection A collection to create a step function for. This can be anything that supports the ES2015
iteration protocol, a plain object, a pre-ES2015 string or array, or a function.
@return {module:xduce~result} A function that, when given a reduced collection, produces the final output. If the
provided collection is not iterable, `null` will be returned. | [
"Returns",
"a",
"result",
"function",
"for",
"a",
"collection",
".",
"This",
"is",
"a",
"function",
"that",
"performs",
"any",
"final",
"processing",
"that",
"should",
"be",
"done",
"on",
"the",
"result",
"of",
"a",
"reduction",
".",
"If",
"the",
"collection",
"doesn",
"t",
"support",
"reduction",
"null",
"is",
"returned",
"."
] | b454f154f7663475670d4802e28e98ade8c468e7 | https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/reduction.js#L149-L161 |
57,041 | theodoreb/jquarry | lib/target/scan-jquery-use.js | quickCheckMethods | function quickCheckMethods(tokens, JQAPI) {
var JQMethods = _.pluck(JQAPI, 'method');
var identifiers = _.where(tokens, {type: 'Identifier'});
return !!_.intersection(JQMethods, _.pluck(identifiers, 'value')).length;
} | javascript | function quickCheckMethods(tokens, JQAPI) {
var JQMethods = _.pluck(JQAPI, 'method');
var identifiers = _.where(tokens, {type: 'Identifier'});
return !!_.intersection(JQMethods, _.pluck(identifiers, 'value')).length;
} | [
"function",
"quickCheckMethods",
"(",
"tokens",
",",
"JQAPI",
")",
"{",
"var",
"JQMethods",
"=",
"_",
".",
"pluck",
"(",
"JQAPI",
",",
"'method'",
")",
";",
"var",
"identifiers",
"=",
"_",
".",
"where",
"(",
"tokens",
",",
"{",
"type",
":",
"'Identifier'",
"}",
")",
";",
"return",
"!",
"!",
"_",
".",
"intersection",
"(",
"JQMethods",
",",
"_",
".",
"pluck",
"(",
"identifiers",
",",
"'value'",
")",
")",
".",
"length",
";",
"}"
] | Check any jQuery method appears in the code.
@param tokens
@param JQAPI
@returns {boolean} | [
"Check",
"any",
"jQuery",
"method",
"appears",
"in",
"the",
"code",
"."
] | 7066617e592e9c8ae3acb23cc0f1a3847654a6c0 | https://github.com/theodoreb/jquarry/blob/7066617e592e9c8ae3acb23cc0f1a3847654a6c0/lib/target/scan-jquery-use.js#L26-L30 |
57,042 | fritbot/fb-opt-quotes | import_quotes.js | checkFinished | function checkFinished() {
if ((import_count + dupe_count) % 100 === 0) {
console.log('Imported', import_count + dupe_count, '/', quote_count);
}
// Once we're done, show the stats and tell the bot to shutdown.
// Since the bot is fully async-aware itself, it won't shut down unless explicitly told to.
if (finished_reading && quote_count === import_count + dupe_count) {
console.log('\nQuotes in file:', quote_count);
console.log('Quotes imported:', import_count);
console.log('Duplicate quotes:', dupe_count);
bot.shutdown();
}
} | javascript | function checkFinished() {
if ((import_count + dupe_count) % 100 === 0) {
console.log('Imported', import_count + dupe_count, '/', quote_count);
}
// Once we're done, show the stats and tell the bot to shutdown.
// Since the bot is fully async-aware itself, it won't shut down unless explicitly told to.
if (finished_reading && quote_count === import_count + dupe_count) {
console.log('\nQuotes in file:', quote_count);
console.log('Quotes imported:', import_count);
console.log('Duplicate quotes:', dupe_count);
bot.shutdown();
}
} | [
"function",
"checkFinished",
"(",
")",
"{",
"if",
"(",
"(",
"import_count",
"+",
"dupe_count",
")",
"%",
"100",
"===",
"0",
")",
"{",
"console",
".",
"log",
"(",
"'Imported'",
",",
"import_count",
"+",
"dupe_count",
",",
"'/'",
",",
"quote_count",
")",
";",
"}",
"// Once we're done, show the stats and tell the bot to shutdown.",
"// Since the bot is fully async-aware itself, it won't shut down unless explicitly told to.",
"if",
"(",
"finished_reading",
"&&",
"quote_count",
"===",
"import_count",
"+",
"dupe_count",
")",
"{",
"console",
".",
"log",
"(",
"'\\nQuotes in file:'",
",",
"quote_count",
")",
";",
"console",
".",
"log",
"(",
"'Quotes imported:'",
",",
"import_count",
")",
";",
"console",
".",
"log",
"(",
"'Duplicate quotes:'",
",",
"dupe_count",
")",
";",
"bot",
".",
"shutdown",
"(",
")",
";",
"}",
"}"
] | Check if all async DB calls have finished. Output if so. | [
"Check",
"if",
"all",
"async",
"DB",
"calls",
"have",
"finished",
".",
"Output",
"if",
"so",
"."
] | f5cc97d95b3a2bfbe619c026fa70b61556dc9757 | https://github.com/fritbot/fb-opt-quotes/blob/f5cc97d95b3a2bfbe619c026fa70b61556dc9757/import_quotes.js#L58-L71 |
57,043 | rxaviers/builder-amd-css | bower_components/require-css/normalize.js | absoluteURI | function absoluteURI(uri, base) {
if (uri.substr(0, 2) == './')
uri = uri.substr(2);
// absolute urls are left in tact
if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
return uri;
var baseParts = base.split('/');
var uriParts = uri.split('/');
baseParts.pop();
while (curPart = uriParts.shift())
if (curPart == '..')
baseParts.pop();
else
baseParts.push(curPart);
return baseParts.join('/');
} | javascript | function absoluteURI(uri, base) {
if (uri.substr(0, 2) == './')
uri = uri.substr(2);
// absolute urls are left in tact
if (uri.match(absUrlRegEx) || uri.match(protocolRegEx))
return uri;
var baseParts = base.split('/');
var uriParts = uri.split('/');
baseParts.pop();
while (curPart = uriParts.shift())
if (curPart == '..')
baseParts.pop();
else
baseParts.push(curPart);
return baseParts.join('/');
} | [
"function",
"absoluteURI",
"(",
"uri",
",",
"base",
")",
"{",
"if",
"(",
"uri",
".",
"substr",
"(",
"0",
",",
"2",
")",
"==",
"'./'",
")",
"uri",
"=",
"uri",
".",
"substr",
"(",
"2",
")",
";",
"// absolute urls are left in tact",
"if",
"(",
"uri",
".",
"match",
"(",
"absUrlRegEx",
")",
"||",
"uri",
".",
"match",
"(",
"protocolRegEx",
")",
")",
"return",
"uri",
";",
"var",
"baseParts",
"=",
"base",
".",
"split",
"(",
"'/'",
")",
";",
"var",
"uriParts",
"=",
"uri",
".",
"split",
"(",
"'/'",
")",
";",
"baseParts",
".",
"pop",
"(",
")",
";",
"while",
"(",
"curPart",
"=",
"uriParts",
".",
"shift",
"(",
")",
")",
"if",
"(",
"curPart",
"==",
"'..'",
")",
"baseParts",
".",
"pop",
"(",
")",
";",
"else",
"baseParts",
".",
"push",
"(",
"curPart",
")",
";",
"return",
"baseParts",
".",
"join",
"(",
"'/'",
")",
";",
"}"
] | given a relative URI, calculate the absolute URI | [
"given",
"a",
"relative",
"URI",
"calculate",
"the",
"absolute",
"URI"
] | ad225d76285a68c5fa750fdc31e2f2c7365aa8b3 | https://github.com/rxaviers/builder-amd-css/blob/ad225d76285a68c5fa750fdc31e2f2c7365aa8b3/bower_components/require-css/normalize.js#L63-L83 |
57,044 | 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",
")",
"{",
"// 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",
")",
";",
"}"
] | 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 |
57,045 | 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",
"/* 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",
")",
")",
";",
"}",
";",
"}"
] | 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 |
57,046 | 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 |
57,047 | 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 |
|
57,048 | 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 |
|
57,049 | 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 |
|
57,050 | 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",
";",
"// 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",
")",
";",
"}"
] | Create a CanaryStore | [
"Create",
"a",
"CanaryStore"
] | dd4f2eb33ed5146136c2d233dd2ba4fa5b59aafc | https://github.com/camshaft/canary-store/blob/dd4f2eb33ed5146136c2d233dd2ba4fa5b59aafc/index.js#L23-L42 |
57,051 | 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 |
57,052 | 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",
"=>",
"{",
"// 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",
"}",
")",
"}"
] | 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 |
57,053 | 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 |
|
57,054 | 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 |
|
57,055 | 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 |
|
57,056 | 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 |
57,057 | 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 |
57,058 | 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 |
57,059 | 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",
")",
"{",
"/** Generate each client as described. */",
"config",
".",
"clients",
".",
"forEach",
"(",
"function",
"(",
"client",
")",
"{",
"if",
"(",
"client",
".",
"type",
"===",
"'node'",
")",
"{",
"/** Fork a new node process. */",
"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 |
57,060 | 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",
")",
";",
"}",
"// 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",
")",
")",
";",
"}"
] | 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 |
57,061 | 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 |
|
57,062 | 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 |
|
57,063 | 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 |
57,064 | 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 |
57,065 | 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 |
57,066 | 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 |
57,067 | 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 |
|
57,068 | 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 |
|
57,069 | 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 |
|
57,070 | 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** – the initial state. The editable's instance was created but
* is not fully loaded (in particular it has no data).
* * **ready** – the editable is fully initialized. The `ready` status is set after
* the first {@link CKEDITOR.editor#method-setData} is called.
* * **detached** – 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** – the initial state. The editable's instance was created but
* is not fully loaded (in particular it has no data).
* * **ready** – the editable is fully initialized. The `ready` status is set after
* the first {@link CKEDITOR.editor#method-setData} is called.
* * **detached** – 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",
")",
"{",
"// Transform the element into a CKEDITOR.dom.element instance.",
"this",
".",
"base",
"(",
"element",
".",
"$",
"||",
"element",
")",
";",
"this",
".",
"editor",
"=",
"editor",
";",
"/**\n\t\t\t * Indicates the initialization status of the editable element. The following statuses are available:\n\t\t\t *\n\t\t\t *\t* **unloaded** – the initial state. The editable's instance was created but\n\t\t\t *\tis not fully loaded (in particular it has no data).\n\t\t\t *\t* **ready** – the editable is fully initialized. The `ready` status is set after\n\t\t\t *\tthe first {@link CKEDITOR.editor#method-setData} is called.\n\t\t\t *\t* **detached** – the editable was detached.\n\t\t\t *\n\t\t\t * @since 4.3.3\n\t\t\t * @readonly\n\t\t\t * @property {String}\n\t\t\t */",
"this",
".",
"status",
"=",
"'unloaded'",
";",
"/**\n\t\t\t * Indicates whether the editable element gained focus.\n\t\t\t *\n\t\t\t * @property {Boolean} hasFocus\n\t\t\t */",
"this",
".",
"hasFocus",
"=",
"false",
";",
"// The bootstrapping logic.",
"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 |
|
57,071 | 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 |
|
57,072 | 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",
"=",
"{",
"}",
")",
";",
"// Saved the original attribute val.",
"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 |
|
57,073 | 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",
";",
"// 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",
";",
"}"
] | 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 |
|
57,074 | 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",
")",
"{",
"// 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",
")",
";",
"}"
] | 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 |
|
57,075 | 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",
")",
"{",
"// 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",
";",
"}"
] | 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 |
57,076 | 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> </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> </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 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> </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",
")",
";",
"}"
] | 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 |
57,077 | 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",
"&&",
"// 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",
"(",
")",
";",
"}",
"}"
] | Rule 7. | [
"Rule",
"7",
"."
] | 2b90b8a6afc9f065f785651292fb193940021d90 | https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/editable.js#L1829-L1847 |
57,078 | 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 |
57,079 | 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 |
57,080 | 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",
")",
"{",
"/*\n * if expectations aren't met, args checker will throw appropriate exceptions\n * notifying the user regarding the errors of the arguments.\n * */",
"args",
".",
"expect",
"(",
"arguments",
",",
"[",
"'boolean|string'",
",",
"'*'",
",",
"'function|object'",
",",
"'number'",
",",
"'array'",
"]",
")",
";",
"// do something here...",
"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 |
57,081 | 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 |
57,082 | 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 |
57,083 | 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 |
57,084 | 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 |
57,085 | 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 |
57,086 | 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 |
57,087 | 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",
")",
"{",
"// Convert to event.\r",
"!",
"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.\r",
"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 |
57,088 | 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( ' ' );
}
} | 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( ' ' );
}
} | [
"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",
"(",
"' '",
")",
";",
"}",
"}"
] | 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 |
57,089 | 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 |
57,090 | 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",
")",
"{",
"// 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",
"}",
";",
"}"
] | 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 |
57,091 | 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 |
57,092 | 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 |
57,093 | 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 |
57,094 | 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 |
57,095 | 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",
";",
"// 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",
"(",
")",
";",
"}"
] | 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 |
57,096 | 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 |
57,097 | 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",
",",
"'.'",
")",
";",
"// 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",
")",
";",
"}",
"}",
")",
";",
"}"
] | 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 |
|
57,098 | 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",
")",
"{",
"// 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",
"(",
")",
";",
"}"
] | 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 |
|
57,099 | 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",
"(",
")",
"{",
"// 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",
";",
"}"
] | 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 |
Subsets and Splits