id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
47,100 | gwtw/js-binomial-heap | index.js | mergeHeaps | function mergeHeaps(a, b) {
if (typeof a.head === 'undefined') {
return b.head;
}
if (typeof b.head === 'undefined') {
return a.head;
}
var head;
var aNext = a.head;
var bNext = b.head;
if (a.head.degree <= b.head.degree) {
head = a.head;
aNext = aNext.sibling;
} else {
head = b.head;
bNext = bNext.sibling;
}
var tail = head;
while (aNext && bNext) {
if (aNext.degree <= bNext.degree) {
tail.sibling = aNext;
aNext = aNext.sibling;
} else {
tail.sibling = bNext;
bNext = bNext.sibling;
}
tail = tail.sibling;
}
tail.sibling = aNext ? aNext : bNext;
return head;
} | javascript | function mergeHeaps(a, b) {
if (typeof a.head === 'undefined') {
return b.head;
}
if (typeof b.head === 'undefined') {
return a.head;
}
var head;
var aNext = a.head;
var bNext = b.head;
if (a.head.degree <= b.head.degree) {
head = a.head;
aNext = aNext.sibling;
} else {
head = b.head;
bNext = bNext.sibling;
}
var tail = head;
while (aNext && bNext) {
if (aNext.degree <= bNext.degree) {
tail.sibling = aNext;
aNext = aNext.sibling;
} else {
tail.sibling = bNext;
bNext = bNext.sibling;
}
tail = tail.sibling;
}
tail.sibling = aNext ? aNext : bNext;
return head;
} | [
"function",
"mergeHeaps",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"typeof",
"a",
".",
"head",
"===",
"'undefined'",
")",
"{",
"return",
"b",
".",
"head",
";",
"}",
"if",
"(",
"typeof",
"b",
".",
"head",
"===",
"'undefined'",
")",
"{",
"return",
"a",
".",
"head",
";",
"}",
"var",
"head",
";",
"var",
"aNext",
"=",
"a",
".",
"head",
";",
"var",
"bNext",
"=",
"b",
".",
"head",
";",
"if",
"(",
"a",
".",
"head",
".",
"degree",
"<=",
"b",
".",
"head",
".",
"degree",
")",
"{",
"head",
"=",
"a",
".",
"head",
";",
"aNext",
"=",
"aNext",
".",
"sibling",
";",
"}",
"else",
"{",
"head",
"=",
"b",
".",
"head",
";",
"bNext",
"=",
"bNext",
".",
"sibling",
";",
"}",
"var",
"tail",
"=",
"head",
";",
"while",
"(",
"aNext",
"&&",
"bNext",
")",
"{",
"if",
"(",
"aNext",
".",
"degree",
"<=",
"bNext",
".",
"degree",
")",
"{",
"tail",
".",
"sibling",
"=",
"aNext",
";",
"aNext",
"=",
"aNext",
".",
"sibling",
";",
"}",
"else",
"{",
"tail",
".",
"sibling",
"=",
"bNext",
";",
"bNext",
"=",
"bNext",
".",
"sibling",
";",
"}",
"tail",
"=",
"tail",
".",
"sibling",
";",
"}",
"tail",
".",
"sibling",
"=",
"aNext",
"?",
"aNext",
":",
"bNext",
";",
"return",
"head",
";",
"}"
]
| Merges two heaps together.
@private
@param {Node} a The head of the first heap to merge.
@param {Node} b The head of the second heap to merge.
@return {Node} The head of the merged heap. | [
"Merges",
"two",
"heaps",
"together",
"."
]
| 75af9ee02d0089fdbaa54a2c5aa0bc6eb1d059b3 | https://github.com/gwtw/js-binomial-heap/blob/75af9ee02d0089fdbaa54a2c5aa0bc6eb1d059b3/index.js#L184-L221 |
47,101 | gwtw/js-binomial-heap | index.js | Node | function Node(key, value) {
this.key = key;
this.value = value;
this.degree = 0;
this.parent = undefined;
this.child = undefined;
this.sibling = undefined;
} | javascript | function Node(key, value) {
this.key = key;
this.value = value;
this.degree = 0;
this.parent = undefined;
this.child = undefined;
this.sibling = undefined;
} | [
"function",
"Node",
"(",
"key",
",",
"value",
")",
"{",
"this",
".",
"key",
"=",
"key",
";",
"this",
".",
"value",
"=",
"value",
";",
"this",
".",
"degree",
"=",
"0",
";",
"this",
".",
"parent",
"=",
"undefined",
";",
"this",
".",
"child",
"=",
"undefined",
";",
"this",
".",
"sibling",
"=",
"undefined",
";",
"}"
]
| Creates a Binomial Heap node.
@constructor
@param {Object} key The key of the new node.
@param {Object} value The value of the new node. | [
"Creates",
"a",
"Binomial",
"Heap",
"node",
"."
]
| 75af9ee02d0089fdbaa54a2c5aa0bc6eb1d059b3 | https://github.com/gwtw/js-binomial-heap/blob/75af9ee02d0089fdbaa54a2c5aa0bc6eb1d059b3/index.js#L275-L282 |
47,102 | petarov/translitbg.js | src/translitbg.js | function() {
var result = new StringBuffer();
var array = this._input.split('');
// var prev = null;
for (var i = 0; i < array.length; i++) {
var cur = array[i];
var next = array[i + 1];
if (typeof next !== 'undefined') {
var curToken = cur + next;
if (this._mode.tokens.ia[curToken]) {
var nextNext = array[i + 2];
if (typeof nextNext === 'undefined' || /^[-\s]$/.test(nextNext)) {
result.append(this._mode.tokens.ia[curToken]);
i++;
continue;
}
}
}
if (this._mode.cyr2lat[cur]) {
result.append(this._mode.cyr2lat[cur]);
} else {
result.append(cur);
}
// prev = cur;
}
return result.toString();
} | javascript | function() {
var result = new StringBuffer();
var array = this._input.split('');
// var prev = null;
for (var i = 0; i < array.length; i++) {
var cur = array[i];
var next = array[i + 1];
if (typeof next !== 'undefined') {
var curToken = cur + next;
if (this._mode.tokens.ia[curToken]) {
var nextNext = array[i + 2];
if (typeof nextNext === 'undefined' || /^[-\s]$/.test(nextNext)) {
result.append(this._mode.tokens.ia[curToken]);
i++;
continue;
}
}
}
if (this._mode.cyr2lat[cur]) {
result.append(this._mode.cyr2lat[cur]);
} else {
result.append(cur);
}
// prev = cur;
}
return result.toString();
} | [
"function",
"(",
")",
"{",
"var",
"result",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"var",
"array",
"=",
"this",
".",
"_input",
".",
"split",
"(",
"''",
")",
";",
"// var prev = null;\r",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"cur",
"=",
"array",
"[",
"i",
"]",
";",
"var",
"next",
"=",
"array",
"[",
"i",
"+",
"1",
"]",
";",
"if",
"(",
"typeof",
"next",
"!==",
"'undefined'",
")",
"{",
"var",
"curToken",
"=",
"cur",
"+",
"next",
";",
"if",
"(",
"this",
".",
"_mode",
".",
"tokens",
".",
"ia",
"[",
"curToken",
"]",
")",
"{",
"var",
"nextNext",
"=",
"array",
"[",
"i",
"+",
"2",
"]",
";",
"if",
"(",
"typeof",
"nextNext",
"===",
"'undefined'",
"||",
"/",
"^[-\\s]$",
"/",
".",
"test",
"(",
"nextNext",
")",
")",
"{",
"result",
".",
"append",
"(",
"this",
".",
"_mode",
".",
"tokens",
".",
"ia",
"[",
"curToken",
"]",
")",
";",
"i",
"++",
";",
"continue",
";",
"}",
"}",
"}",
"if",
"(",
"this",
".",
"_mode",
".",
"cyr2lat",
"[",
"cur",
"]",
")",
"{",
"result",
".",
"append",
"(",
"this",
".",
"_mode",
".",
"cyr2lat",
"[",
"cur",
"]",
")",
";",
"}",
"else",
"{",
"result",
".",
"append",
"(",
"cur",
")",
";",
"}",
"// prev = cur;\r",
"}",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}"
]
| Transforms Cyrillic to Latin characters.
@return {string} Transliterated text | [
"Transforms",
"Cyrillic",
"to",
"Latin",
"characters",
"."
]
| 003e81703efd098ae0ea4bb711d1e70c9aa989db | https://github.com/petarov/translitbg.js/blob/003e81703efd098ae0ea4bb711d1e70c9aa989db/src/translitbg.js#L153-L185 |
|
47,103 | toddself/jsondom | index.js | _regExpOrGTFO | function _regExpOrGTFO(expr){
var exp;
if(typeof expr === 'string'){
exp = new RegExp('^'+expr+'$');
} else if (expr instanceof RegExp){
exp = expr;
} else {
throw new Error('Needle must be either a string or a RegExp');
}
return exp;
} | javascript | function _regExpOrGTFO(expr){
var exp;
if(typeof expr === 'string'){
exp = new RegExp('^'+expr+'$');
} else if (expr instanceof RegExp){
exp = expr;
} else {
throw new Error('Needle must be either a string or a RegExp');
}
return exp;
} | [
"function",
"_regExpOrGTFO",
"(",
"expr",
")",
"{",
"var",
"exp",
";",
"if",
"(",
"typeof",
"expr",
"===",
"'string'",
")",
"{",
"exp",
"=",
"new",
"RegExp",
"(",
"'^'",
"+",
"expr",
"+",
"'$'",
")",
";",
"}",
"else",
"if",
"(",
"expr",
"instanceof",
"RegExp",
")",
"{",
"exp",
"=",
"expr",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Needle must be either a string or a RegExp'",
")",
";",
"}",
"return",
"exp",
";",
"}"
]
| Cohearses `expr` into a RegExp or throws an error if it can't
@private
@param {Mixed} expr RegExp or string.
@return {Object} Strict Regular Expression version of string | [
"Cohearses",
"expr",
"into",
"a",
"RegExp",
"or",
"throws",
"an",
"error",
"if",
"it",
"can",
"t"
]
| d71d3ce355ab9a925bdf7a4754642e45c9678282 | https://github.com/toddself/jsondom/blob/d71d3ce355ab9a925bdf7a4754642e45c9678282/index.js#L33-L45 |
47,104 | 3rd-Eden/shrinkwrap | index.js | Shrinkwrap | function Shrinkwrap(options) {
this.fuse();
options = options || {};
options.registry = 'registry' in options
? options.registry
: 'http://registry.nodejitsu.com/';
options.production = 'production' in options
? options.production
: process.NODE_ENV === 'production';
options.optimize = 'optimize' in options
? options.optimize
: true;
options.limit = 'limit' in options
? options.limit
: 10;
options.mirrors = 'mirrors' in options
? options.mirrors
: false;
this.registry = 'string' !== typeof options.registry
? options.registry
: new Registry({
registry: options.registry || Registry.mirrors.nodejitsu,
githulk: options.githulk,
mirrors: options.mirrors
});
this.production = options.production; // Don't include devDependencies.
this.limit = options.limit; // Maximum concurrency.
this.cache = Object.create(null); // Dependency cache.
} | javascript | function Shrinkwrap(options) {
this.fuse();
options = options || {};
options.registry = 'registry' in options
? options.registry
: 'http://registry.nodejitsu.com/';
options.production = 'production' in options
? options.production
: process.NODE_ENV === 'production';
options.optimize = 'optimize' in options
? options.optimize
: true;
options.limit = 'limit' in options
? options.limit
: 10;
options.mirrors = 'mirrors' in options
? options.mirrors
: false;
this.registry = 'string' !== typeof options.registry
? options.registry
: new Registry({
registry: options.registry || Registry.mirrors.nodejitsu,
githulk: options.githulk,
mirrors: options.mirrors
});
this.production = options.production; // Don't include devDependencies.
this.limit = options.limit; // Maximum concurrency.
this.cache = Object.create(null); // Dependency cache.
} | [
"function",
"Shrinkwrap",
"(",
"options",
")",
"{",
"this",
".",
"fuse",
"(",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"registry",
"=",
"'registry'",
"in",
"options",
"?",
"options",
".",
"registry",
":",
"'http://registry.nodejitsu.com/'",
";",
"options",
".",
"production",
"=",
"'production'",
"in",
"options",
"?",
"options",
".",
"production",
":",
"process",
".",
"NODE_ENV",
"===",
"'production'",
";",
"options",
".",
"optimize",
"=",
"'optimize'",
"in",
"options",
"?",
"options",
".",
"optimize",
":",
"true",
";",
"options",
".",
"limit",
"=",
"'limit'",
"in",
"options",
"?",
"options",
".",
"limit",
":",
"10",
";",
"options",
".",
"mirrors",
"=",
"'mirrors'",
"in",
"options",
"?",
"options",
".",
"mirrors",
":",
"false",
";",
"this",
".",
"registry",
"=",
"'string'",
"!==",
"typeof",
"options",
".",
"registry",
"?",
"options",
".",
"registry",
":",
"new",
"Registry",
"(",
"{",
"registry",
":",
"options",
".",
"registry",
"||",
"Registry",
".",
"mirrors",
".",
"nodejitsu",
",",
"githulk",
":",
"options",
".",
"githulk",
",",
"mirrors",
":",
"options",
".",
"mirrors",
"}",
")",
";",
"this",
".",
"production",
"=",
"options",
".",
"production",
";",
"// Don't include devDependencies.",
"this",
".",
"limit",
"=",
"options",
".",
"limit",
";",
"// Maximum concurrency.",
"this",
".",
"cache",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"// Dependency cache.",
"}"
]
| Generate a new Shrinkwrap from a given package or module.
Options:
- registry: URL of the npm registry we should use to read package information.
- production: Should we only include production packages.
- limit: Amount of parallel processing tasks we could use to retrieve data.
- optimize: Should we attempt to optimize the data structure in the same way
that npm would have done it.
- mirrors: A list of npm mirrors to be used with our registry.
- githulk: Optional preconfigured GitHulk.
@constructor
@param {Object} options Options.
@api public | [
"Generate",
"a",
"new",
"Shrinkwrap",
"from",
"a",
"given",
"package",
"or",
"module",
"."
]
| 60e0004e4092896e9ba6bd0d83bdc22a973812da | https://github.com/3rd-Eden/shrinkwrap/blob/60e0004e4092896e9ba6bd0d83bdc22a973812da/index.js#L43-L79 |
47,105 | 3rd-Eden/shrinkwrap | index.js | queue | function queue(packages, ref, depth) {
packages = shrinkwrap.dedupe(packages);
Shrinkwrap.dependencies.forEach(function each(key) {
if (this.production && 'devDependencies' === key) return;
if ('object' !== this.type(packages[key])) return;
Object.keys(packages[key]).forEach(function each(name) {
var range = packages[key][name]
, _id = name +'@'+ range;
ref.dependencies = ref.dependencies || {};
queue.push({
name: name, // Name of the module
range: range, // Semver range
_id: _id, // Semi unique id.
parents: [ref], // Reference to the parent module.
depth: depth // The depth of the reference.
});
});
}, shrinkwrap);
return queue;
} | javascript | function queue(packages, ref, depth) {
packages = shrinkwrap.dedupe(packages);
Shrinkwrap.dependencies.forEach(function each(key) {
if (this.production && 'devDependencies' === key) return;
if ('object' !== this.type(packages[key])) return;
Object.keys(packages[key]).forEach(function each(name) {
var range = packages[key][name]
, _id = name +'@'+ range;
ref.dependencies = ref.dependencies || {};
queue.push({
name: name, // Name of the module
range: range, // Semver range
_id: _id, // Semi unique id.
parents: [ref], // Reference to the parent module.
depth: depth // The depth of the reference.
});
});
}, shrinkwrap);
return queue;
} | [
"function",
"queue",
"(",
"packages",
",",
"ref",
",",
"depth",
")",
"{",
"packages",
"=",
"shrinkwrap",
".",
"dedupe",
"(",
"packages",
")",
";",
"Shrinkwrap",
".",
"dependencies",
".",
"forEach",
"(",
"function",
"each",
"(",
"key",
")",
"{",
"if",
"(",
"this",
".",
"production",
"&&",
"'devDependencies'",
"===",
"key",
")",
"return",
";",
"if",
"(",
"'object'",
"!==",
"this",
".",
"type",
"(",
"packages",
"[",
"key",
"]",
")",
")",
"return",
";",
"Object",
".",
"keys",
"(",
"packages",
"[",
"key",
"]",
")",
".",
"forEach",
"(",
"function",
"each",
"(",
"name",
")",
"{",
"var",
"range",
"=",
"packages",
"[",
"key",
"]",
"[",
"name",
"]",
",",
"_id",
"=",
"name",
"+",
"'@'",
"+",
"range",
";",
"ref",
".",
"dependencies",
"=",
"ref",
".",
"dependencies",
"||",
"{",
"}",
";",
"queue",
".",
"push",
"(",
"{",
"name",
":",
"name",
",",
"// Name of the module",
"range",
":",
"range",
",",
"// Semver range",
"_id",
":",
"_id",
",",
"// Semi unique id.",
"parents",
":",
"[",
"ref",
"]",
",",
"// Reference to the parent module.",
"depth",
":",
"depth",
"// The depth of the reference.",
"}",
")",
";",
"}",
")",
";",
"}",
",",
"shrinkwrap",
")",
";",
"return",
"queue",
";",
"}"
]
| Scan the given package.json like structure for possible dependency
locations which will be automatically queued for fetching and processing.
@param {Object} packages The packages.json body.
@param {Object} ref The location of the new packages in the tree.
@param {Number} depth How deep was this package nested
@api private | [
"Scan",
"the",
"given",
"package",
".",
"json",
"like",
"structure",
"for",
"possible",
"dependency",
"locations",
"which",
"will",
"be",
"automatically",
"queued",
"for",
"fetching",
"and",
"processing",
"."
]
| 60e0004e4092896e9ba6bd0d83bdc22a973812da | https://github.com/3rd-Eden/shrinkwrap/blob/60e0004e4092896e9ba6bd0d83bdc22a973812da/index.js#L139-L162 |
47,106 | 3rd-Eden/shrinkwrap | index.js | parent | function parent(dependent) {
var node = dependent
, result = [];
while (node.parent) {
if (!available(node.parent)) break;
result.push(node.parent);
node = node.parent;
}
return result;
} | javascript | function parent(dependent) {
var node = dependent
, result = [];
while (node.parent) {
if (!available(node.parent)) break;
result.push(node.parent);
node = node.parent;
}
return result;
} | [
"function",
"parent",
"(",
"dependent",
")",
"{",
"var",
"node",
"=",
"dependent",
",",
"result",
"=",
"[",
"]",
";",
"while",
"(",
"node",
".",
"parent",
")",
"{",
"if",
"(",
"!",
"available",
"(",
"node",
".",
"parent",
")",
")",
"break",
";",
"result",
".",
"push",
"(",
"node",
".",
"parent",
")",
";",
"node",
"=",
"node",
".",
"parent",
";",
"}",
"return",
"result",
";",
"}"
]
| Find suitable parent nodes which can hold this module without creating
a possible conflict because there two different versions of the module in
the dependency tree.
@param {Object} dependent A dependent of a module.
@returns {Array} parents.
@api private | [
"Find",
"suitable",
"parent",
"nodes",
"which",
"can",
"hold",
"this",
"module",
"without",
"creating",
"a",
"possible",
"conflict",
"because",
"there",
"two",
"different",
"versions",
"of",
"the",
"module",
"in",
"the",
"dependency",
"tree",
"."
]
| 60e0004e4092896e9ba6bd0d83bdc22a973812da | https://github.com/3rd-Eden/shrinkwrap/blob/60e0004e4092896e9ba6bd0d83bdc22a973812da/index.js#L384-L396 |
47,107 | 3rd-Eden/shrinkwrap | index.js | available | function available(dependencies) {
if (!dependencies) return false;
return Object.keys(dependencies).every(function every(key) {
var dependency = dependencies[key];
if (!dependency) return false;
if (dependency.name !== name) return true;
if (dependency.version === version) return true;
return false;
});
} | javascript | function available(dependencies) {
if (!dependencies) return false;
return Object.keys(dependencies).every(function every(key) {
var dependency = dependencies[key];
if (!dependency) return false;
if (dependency.name !== name) return true;
if (dependency.version === version) return true;
return false;
});
} | [
"function",
"available",
"(",
"dependencies",
")",
"{",
"if",
"(",
"!",
"dependencies",
")",
"return",
"false",
";",
"return",
"Object",
".",
"keys",
"(",
"dependencies",
")",
".",
"every",
"(",
"function",
"every",
"(",
"key",
")",
"{",
"var",
"dependency",
"=",
"dependencies",
"[",
"key",
"]",
";",
"if",
"(",
"!",
"dependency",
")",
"return",
"false",
";",
"if",
"(",
"dependency",
".",
"name",
"!==",
"name",
")",
"return",
"true",
";",
"if",
"(",
"dependency",
".",
"version",
"===",
"version",
")",
"return",
"true",
";",
"return",
"false",
";",
"}",
")",
";",
"}"
]
| Checks if the dependency tree does not already contain a different version
of this module.
@param {Object} dependencies The dependencies of a module.
@returns {Boolean} Available as module location.
@api private | [
"Checks",
"if",
"the",
"dependency",
"tree",
"does",
"not",
"already",
"contain",
"a",
"different",
"version",
"of",
"this",
"module",
"."
]
| 60e0004e4092896e9ba6bd0d83bdc22a973812da | https://github.com/3rd-Eden/shrinkwrap/blob/60e0004e4092896e9ba6bd0d83bdc22a973812da/index.js#L406-L419 |
47,108 | oscmejia/libs | lib/libs/string.js | randomString | function randomString(_string_length, _mode) {
var string_length = _string_length;
if(string_length < 3)
string_length = 2;
var chars = chars_all;
if(_mode === 'lower_case') chars = chars_lower;
else if(_mode === 'upper_case') chars = chars_upper;
else if(_mode === 'nums_oly') chars = chars_nums;
else if(_mode === 'especials') chars = chars_all + chars_spec;
var str = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
str += chars.substring(rnum,rnum+1);
}
return str;
} | javascript | function randomString(_string_length, _mode) {
var string_length = _string_length;
if(string_length < 3)
string_length = 2;
var chars = chars_all;
if(_mode === 'lower_case') chars = chars_lower;
else if(_mode === 'upper_case') chars = chars_upper;
else if(_mode === 'nums_oly') chars = chars_nums;
else if(_mode === 'especials') chars = chars_all + chars_spec;
var str = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
str += chars.substring(rnum,rnum+1);
}
return str;
} | [
"function",
"randomString",
"(",
"_string_length",
",",
"_mode",
")",
"{",
"var",
"string_length",
"=",
"_string_length",
";",
"if",
"(",
"string_length",
"<",
"3",
")",
"string_length",
"=",
"2",
";",
"var",
"chars",
"=",
"chars_all",
";",
"if",
"(",
"_mode",
"===",
"'lower_case'",
")",
"chars",
"=",
"chars_lower",
";",
"else",
"if",
"(",
"_mode",
"===",
"'upper_case'",
")",
"chars",
"=",
"chars_upper",
";",
"else",
"if",
"(",
"_mode",
"===",
"'nums_oly'",
")",
"chars",
"=",
"chars_nums",
";",
"else",
"if",
"(",
"_mode",
"===",
"'especials'",
")",
"chars",
"=",
"chars_all",
"+",
"chars_spec",
";",
"var",
"str",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"string_length",
";",
"i",
"++",
")",
"{",
"var",
"rnum",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"chars",
".",
"length",
")",
";",
"str",
"+=",
"chars",
".",
"substring",
"(",
"rnum",
",",
"rnum",
"+",
"1",
")",
";",
"}",
"return",
"str",
";",
"}"
]
| Generates a random string of the provided length, and including only
the required characters.
@param {int} _string_length
@param {String} _mode
@api public | [
"Generates",
"a",
"random",
"string",
"of",
"the",
"provided",
"length",
"and",
"including",
"only",
"the",
"required",
"characters",
"."
]
| 81f8654af6ee922963e6cc3f6cda96ffa75142cf | https://github.com/oscmejia/libs/blob/81f8654af6ee922963e6cc3f6cda96ffa75142cf/lib/libs/string.js#L15-L35 |
47,109 | oscmejia/libs | lib/libs/string.js | randomKey | function randomKey(_numOfBlocks, _blockLength, _mode, _timestamp) {
var numOfBlocks = _numOfBlocks;
var blockLength = _blockLength;
if(numOfBlocks === undefined || numOfBlocks < 3) numOfBlocks = 2;
if(blockLength === undefined || blockLength < 3) blockLength = 2;
var key = "";
for (var i=0; i<numOfBlocks; i++) {
if(key.length == 0)
key = randomString(blockLength, _mode);
else
key = key + "-" + randomString(blockLength, _mode);
}
if(_timestamp !== undefined && _timestamp === true)
key = new Date().getTime() + '-' + key;
return key;
} | javascript | function randomKey(_numOfBlocks, _blockLength, _mode, _timestamp) {
var numOfBlocks = _numOfBlocks;
var blockLength = _blockLength;
if(numOfBlocks === undefined || numOfBlocks < 3) numOfBlocks = 2;
if(blockLength === undefined || blockLength < 3) blockLength = 2;
var key = "";
for (var i=0; i<numOfBlocks; i++) {
if(key.length == 0)
key = randomString(blockLength, _mode);
else
key = key + "-" + randomString(blockLength, _mode);
}
if(_timestamp !== undefined && _timestamp === true)
key = new Date().getTime() + '-' + key;
return key;
} | [
"function",
"randomKey",
"(",
"_numOfBlocks",
",",
"_blockLength",
",",
"_mode",
",",
"_timestamp",
")",
"{",
"var",
"numOfBlocks",
"=",
"_numOfBlocks",
";",
"var",
"blockLength",
"=",
"_blockLength",
";",
"if",
"(",
"numOfBlocks",
"===",
"undefined",
"||",
"numOfBlocks",
"<",
"3",
")",
"numOfBlocks",
"=",
"2",
";",
"if",
"(",
"blockLength",
"===",
"undefined",
"||",
"blockLength",
"<",
"3",
")",
"blockLength",
"=",
"2",
";",
"var",
"key",
"=",
"\"\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numOfBlocks",
";",
"i",
"++",
")",
"{",
"if",
"(",
"key",
".",
"length",
"==",
"0",
")",
"key",
"=",
"randomString",
"(",
"blockLength",
",",
"_mode",
")",
";",
"else",
"key",
"=",
"key",
"+",
"\"-\"",
"+",
"randomString",
"(",
"blockLength",
",",
"_mode",
")",
";",
"}",
"if",
"(",
"_timestamp",
"!==",
"undefined",
"&&",
"_timestamp",
"===",
"true",
")",
"key",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
"+",
"'-'",
"+",
"key",
";",
"return",
"key",
";",
"}"
]
| Generates a random key of the provided length, and including only
the required characters.
A key is separated by `-`.
Also has the option to timestamp the resulting string at the begining.
@param {int} _numOfBlocks
@param {int} _blockLength
@param {String} _mode
@param {Boolean} _timestamp
@api public | [
"Generates",
"a",
"random",
"key",
"of",
"the",
"provided",
"length",
"and",
"including",
"only",
"the",
"required",
"characters",
".",
"A",
"key",
"is",
"separated",
"by",
"-",
".",
"Also",
"has",
"the",
"option",
"to",
"timestamp",
"the",
"resulting",
"string",
"at",
"the",
"begining",
"."
]
| 81f8654af6ee922963e6cc3f6cda96ffa75142cf | https://github.com/oscmejia/libs/blob/81f8654af6ee922963e6cc3f6cda96ffa75142cf/lib/libs/string.js#L50-L70 |
47,110 | jiridudekusy/uu5-to-markdown | src/converters/md2uu5/section.js | section | function section(state, startLine, endLine, silent) {
var ch,
level,
tmp,
pos = state.bMarks[startLine] + state.tShift[startLine],
max = state.eMarks[startLine];
if (pos >= max) {
return false;
}
ch = state.src.charCodeAt(pos);
if (ch !== 0x23 /* # */ || pos >= max) {
return false;
}
// count heading level
level = 1;
ch = state.src.charCodeAt(++pos);
while (ch === 0x23 /* # */ && pos < max && level <= 6) {
level++;
ch = state.src.charCodeAt(++pos);
}
if (level > 6 || (pos < max && ch !== 0x20) /* space */) {
return false;
}
pos++;
let posibleMarker = state.src.substring(pos, pos + SECTION_MARKER.length);
if (posibleMarker !== SECTION_MARKER) {
return false;
}
pos = pos + SECTION_MARKER.length;
// Let's cut tails like ' ### ' from the end of string
max = state.skipCharsBack(max, 0x20, pos); // space
tmp = state.skipCharsBack(max, 0x23, pos); // #
if (tmp > pos && state.src.charCodeAt(tmp - 1) === 0x20 /* space */) {
max = tmp;
}
state.line = startLine + 1;
let sectionHeader = state.src.slice(pos, max).trim();
let nextLine = startLine + 1;
let endRecoginzed = false;
let contentEndLine;
let innerSectionCounter = 0;
for (; nextLine < endLine; nextLine++) {
let line = state.getLines(nextLine, nextLine + 1, 0, false);
if (SECTION_OPEN_REGEXP.test(line)) {
innerSectionCounter++;
}
if (line === SECTION_MARKER) {
// skip inner sections
if (innerSectionCounter > 0) {
innerSectionCounter--;
continue;
}
contentEndLine = nextLine - 1;
endRecoginzed = true;
break;
}
}
if (!endRecoginzed) {
return false;
}
if (silent) {
return true;
}
state.line = contentEndLine + 2;
state.tokens.push({
type: "section_open",
hLevel: level,
lines: [startLine, state.line],
level: state.level,
header: sectionHeader
});
state.line = startLine + 1;
state.parser.tokenize(state, startLine + 1, contentEndLine, false);
state.tokens.push({
type: "section_close",
hLevel: level,
level: state.level
});
state.line = contentEndLine + 2;
return true;
} | javascript | function section(state, startLine, endLine, silent) {
var ch,
level,
tmp,
pos = state.bMarks[startLine] + state.tShift[startLine],
max = state.eMarks[startLine];
if (pos >= max) {
return false;
}
ch = state.src.charCodeAt(pos);
if (ch !== 0x23 /* # */ || pos >= max) {
return false;
}
// count heading level
level = 1;
ch = state.src.charCodeAt(++pos);
while (ch === 0x23 /* # */ && pos < max && level <= 6) {
level++;
ch = state.src.charCodeAt(++pos);
}
if (level > 6 || (pos < max && ch !== 0x20) /* space */) {
return false;
}
pos++;
let posibleMarker = state.src.substring(pos, pos + SECTION_MARKER.length);
if (posibleMarker !== SECTION_MARKER) {
return false;
}
pos = pos + SECTION_MARKER.length;
// Let's cut tails like ' ### ' from the end of string
max = state.skipCharsBack(max, 0x20, pos); // space
tmp = state.skipCharsBack(max, 0x23, pos); // #
if (tmp > pos && state.src.charCodeAt(tmp - 1) === 0x20 /* space */) {
max = tmp;
}
state.line = startLine + 1;
let sectionHeader = state.src.slice(pos, max).trim();
let nextLine = startLine + 1;
let endRecoginzed = false;
let contentEndLine;
let innerSectionCounter = 0;
for (; nextLine < endLine; nextLine++) {
let line = state.getLines(nextLine, nextLine + 1, 0, false);
if (SECTION_OPEN_REGEXP.test(line)) {
innerSectionCounter++;
}
if (line === SECTION_MARKER) {
// skip inner sections
if (innerSectionCounter > 0) {
innerSectionCounter--;
continue;
}
contentEndLine = nextLine - 1;
endRecoginzed = true;
break;
}
}
if (!endRecoginzed) {
return false;
}
if (silent) {
return true;
}
state.line = contentEndLine + 2;
state.tokens.push({
type: "section_open",
hLevel: level,
lines: [startLine, state.line],
level: state.level,
header: sectionHeader
});
state.line = startLine + 1;
state.parser.tokenize(state, startLine + 1, contentEndLine, false);
state.tokens.push({
type: "section_close",
hLevel: level,
level: state.level
});
state.line = contentEndLine + 2;
return true;
} | [
"function",
"section",
"(",
"state",
",",
"startLine",
",",
"endLine",
",",
"silent",
")",
"{",
"var",
"ch",
",",
"level",
",",
"tmp",
",",
"pos",
"=",
"state",
".",
"bMarks",
"[",
"startLine",
"]",
"+",
"state",
".",
"tShift",
"[",
"startLine",
"]",
",",
"max",
"=",
"state",
".",
"eMarks",
"[",
"startLine",
"]",
";",
"if",
"(",
"pos",
">=",
"max",
")",
"{",
"return",
"false",
";",
"}",
"ch",
"=",
"state",
".",
"src",
".",
"charCodeAt",
"(",
"pos",
")",
";",
"if",
"(",
"ch",
"!==",
"0x23",
"/* # */",
"||",
"pos",
">=",
"max",
")",
"{",
"return",
"false",
";",
"}",
"// count heading level",
"level",
"=",
"1",
";",
"ch",
"=",
"state",
".",
"src",
".",
"charCodeAt",
"(",
"++",
"pos",
")",
";",
"while",
"(",
"ch",
"===",
"0x23",
"/* # */",
"&&",
"pos",
"<",
"max",
"&&",
"level",
"<=",
"6",
")",
"{",
"level",
"++",
";",
"ch",
"=",
"state",
".",
"src",
".",
"charCodeAt",
"(",
"++",
"pos",
")",
";",
"}",
"if",
"(",
"level",
">",
"6",
"||",
"(",
"pos",
"<",
"max",
"&&",
"ch",
"!==",
"0x20",
")",
"/* space */",
")",
"{",
"return",
"false",
";",
"}",
"pos",
"++",
";",
"let",
"posibleMarker",
"=",
"state",
".",
"src",
".",
"substring",
"(",
"pos",
",",
"pos",
"+",
"SECTION_MARKER",
".",
"length",
")",
";",
"if",
"(",
"posibleMarker",
"!==",
"SECTION_MARKER",
")",
"{",
"return",
"false",
";",
"}",
"pos",
"=",
"pos",
"+",
"SECTION_MARKER",
".",
"length",
";",
"// Let's cut tails like ' ### ' from the end of string",
"max",
"=",
"state",
".",
"skipCharsBack",
"(",
"max",
",",
"0x20",
",",
"pos",
")",
";",
"// space",
"tmp",
"=",
"state",
".",
"skipCharsBack",
"(",
"max",
",",
"0x23",
",",
"pos",
")",
";",
"// #",
"if",
"(",
"tmp",
">",
"pos",
"&&",
"state",
".",
"src",
".",
"charCodeAt",
"(",
"tmp",
"-",
"1",
")",
"===",
"0x20",
"/* space */",
")",
"{",
"max",
"=",
"tmp",
";",
"}",
"state",
".",
"line",
"=",
"startLine",
"+",
"1",
";",
"let",
"sectionHeader",
"=",
"state",
".",
"src",
".",
"slice",
"(",
"pos",
",",
"max",
")",
".",
"trim",
"(",
")",
";",
"let",
"nextLine",
"=",
"startLine",
"+",
"1",
";",
"let",
"endRecoginzed",
"=",
"false",
";",
"let",
"contentEndLine",
";",
"let",
"innerSectionCounter",
"=",
"0",
";",
"for",
"(",
";",
"nextLine",
"<",
"endLine",
";",
"nextLine",
"++",
")",
"{",
"let",
"line",
"=",
"state",
".",
"getLines",
"(",
"nextLine",
",",
"nextLine",
"+",
"1",
",",
"0",
",",
"false",
")",
";",
"if",
"(",
"SECTION_OPEN_REGEXP",
".",
"test",
"(",
"line",
")",
")",
"{",
"innerSectionCounter",
"++",
";",
"}",
"if",
"(",
"line",
"===",
"SECTION_MARKER",
")",
"{",
"// skip inner sections",
"if",
"(",
"innerSectionCounter",
">",
"0",
")",
"{",
"innerSectionCounter",
"--",
";",
"continue",
";",
"}",
"contentEndLine",
"=",
"nextLine",
"-",
"1",
";",
"endRecoginzed",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"endRecoginzed",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"silent",
")",
"{",
"return",
"true",
";",
"}",
"state",
".",
"line",
"=",
"contentEndLine",
"+",
"2",
";",
"state",
".",
"tokens",
".",
"push",
"(",
"{",
"type",
":",
"\"section_open\"",
",",
"hLevel",
":",
"level",
",",
"lines",
":",
"[",
"startLine",
",",
"state",
".",
"line",
"]",
",",
"level",
":",
"state",
".",
"level",
",",
"header",
":",
"sectionHeader",
"}",
")",
";",
"state",
".",
"line",
"=",
"startLine",
"+",
"1",
";",
"state",
".",
"parser",
".",
"tokenize",
"(",
"state",
",",
"startLine",
"+",
"1",
",",
"contentEndLine",
",",
"false",
")",
";",
"state",
".",
"tokens",
".",
"push",
"(",
"{",
"type",
":",
"\"section_close\"",
",",
"hLevel",
":",
"level",
",",
"level",
":",
"state",
".",
"level",
"}",
")",
";",
"state",
".",
"line",
"=",
"contentEndLine",
"+",
"2",
";",
"return",
"true",
";",
"}"
]
| Block parser for UU5.Bricks.Section .
The section is defined similar to the header:
# {section} Section title
...section content...
{section}
@param state
@param startLine
@param endLine
@param silent
@returns {boolean} | [
"Block",
"parser",
"for",
"UU5",
".",
"Bricks",
".",
"Section",
"."
]
| 559163aa8a4184e1a94888c4fc6d4302acbd857d | https://github.com/jiridudekusy/uu5-to-markdown/blob/559163aa8a4184e1a94888c4fc6d4302acbd857d/src/converters/md2uu5/section.js#L20-L121 |
47,111 | Heymdall/cron-to-text | src/cron-to-text.js | numberToDateName | function numberToDateName(value, type) {
if (type == 'dow') {
return locale.DOW[value - 1];
} else if (type == 'mon') {
return locale.MONTH[value - 1];
}
} | javascript | function numberToDateName(value, type) {
if (type == 'dow') {
return locale.DOW[value - 1];
} else if (type == 'mon') {
return locale.MONTH[value - 1];
}
} | [
"function",
"numberToDateName",
"(",
"value",
",",
"type",
")",
"{",
"if",
"(",
"type",
"==",
"'dow'",
")",
"{",
"return",
"locale",
".",
"DOW",
"[",
"value",
"-",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'mon'",
")",
"{",
"return",
"locale",
".",
"MONTH",
"[",
"value",
"-",
"1",
"]",
";",
"}",
"}"
]
| Parse a number into day of week, or a month name;
used in dateList below.
@param {Number|String} value
@param {String} type
@returns {String} | [
"Parse",
"a",
"number",
"into",
"day",
"of",
"week",
"or",
"a",
"month",
"name",
";",
"used",
"in",
"dateList",
"below",
"."
]
| a6a0ae74a4b98bb951a4ae0fa68778a3c7ab9978 | https://github.com/Heymdall/cron-to-text/blob/a6a0ae74a4b98bb951a4ae0fa68778a3c7ab9978/src/cron-to-text.js#L108-L114 |
47,112 | VisionistInc/jibe | public/js/share-codemirror-json.js | applyToShareJS | function applyToShareJS(cm, change) {
// CodeMirror changes give a text replacement.
var startPos = 0; // Get character position from # of chars in each line.
var i = 0; // i goes through all lines.
while (i < change.from.line) {
startPos += cm.lineInfo(i).text.length + 1; // Add 1 for '\n'
i++;
}
startPos += change.from.ch;
// sharejs json path to the location of the change
var textPath = ['text', startPos];
// array of operations that will be submitted
var ops = [];
// object to keep track of lines that were deleted
var deletedLines = {};
// get an updated document
var doc = ctx.get();
if (change.to.line == change.from.line && change.to.ch == change.from.ch) {
// nothing was removed.
} else {
// change in lines (deleted lines)
if(change.to.line !== change.from.line){
for (i = change.to.line; i > change.from.line; i--) {
if(doc.lines[i] !== undefined){
ops.push({p:['lines', i], ld: doc.lines[i]});
deletedLines[i] = true;
}
}
}
// change in text (deletion)
ops.push({p:textPath, sd: change.removed.join('\n')});
}
if (change.text) {
// change in text (insertion)
ops.push({p:textPath, si: change.text.join('\n')});
// new lines and pasting
if ((change.from.line === change.to.line && change.text.length > 1) || change.origin === 'paste') {
// figure out if there should also be an included line insertion
// // if the change was just to add a new line character, do a replace
// // on that line and then do an insert for the next
if (change.text.join('\n') === '\n') {
ops.push({p:['lines', change.from.line+1], li: {
client: timestamps.client,
timestamp: new Date ()
}});
} else {
/*
* For the following values of change.origin, we know what we want to happen.
* - null - this is a programmatic insertion
* - paste, redo, undo - cm detected the indicated behavior
*
* For others, they'll have to fall through and be handled accordingly.
* Not having this conditional here leads to things breaking...
*/
if (change.origin && change.origin !== 'paste' && change.origin !== 'redo' && change.origin !== 'undo') {
console.warn('not sure what to do in this case', change);
} else {
if (newTimestamp !== doc.lines[change.from.line].timestamp ||
timestamps.client !== doc.lines[change.from.line].client) {
// replace (delete and insert) the line with updated values
ops.push({p:['lines', change.from.line], ld: doc.lines[change.from.line], li: {
client: timestamps.client,
timestamp: new Date ()
}});
}
for (i = 1; i < change.text.length; i++) {
ops.push({p:['lines', change.from.line+1], li: {
client: timestamps.client,
timestamp: new Date ()
}});
}
}
}
} else {
// change in lines (replace + insertion)
for (var changeTextIndex = 0; changeTextIndex < change.text.length; changeTextIndex++) {
var lineChange = change.text[changeTextIndex];
var lineIndex = change.from.line + changeTextIndex;
if (doc.lines[lineIndex]) {
// if this line was just deleted, we don't want to submit any
// updates for it ... we have already updated the text appropriately,
// updating this now will update the wrong line.
var newTimestamp = new Date ();
// the line metadata has changed (new author or new date)
if (newTimestamp !== doc.lines[lineIndex].timestamp ||
timestamps.client !== doc.lines[lineIndex].client) {
// replace (delete and insert) the line with updated values
ops.push({p:['lines', lineIndex], ld: doc.lines[lineIndex], li: {
client: timestamps.client,
timestamp: newTimestamp
}});
}
} else {
// the line doesn't currently exist, so insert a new line
ops.push({p:['lines', lineIndex], li: {
client: timestamps.client,
timestamp: new Date ()
}});
}
}
}
}
// submit the complete list of changes
ctx.submitOp(ops);
// call the function again on the next change, if there is one
if (change.next) {
applyToShareJS(cm, change.next);
}
} | javascript | function applyToShareJS(cm, change) {
// CodeMirror changes give a text replacement.
var startPos = 0; // Get character position from # of chars in each line.
var i = 0; // i goes through all lines.
while (i < change.from.line) {
startPos += cm.lineInfo(i).text.length + 1; // Add 1 for '\n'
i++;
}
startPos += change.from.ch;
// sharejs json path to the location of the change
var textPath = ['text', startPos];
// array of operations that will be submitted
var ops = [];
// object to keep track of lines that were deleted
var deletedLines = {};
// get an updated document
var doc = ctx.get();
if (change.to.line == change.from.line && change.to.ch == change.from.ch) {
// nothing was removed.
} else {
// change in lines (deleted lines)
if(change.to.line !== change.from.line){
for (i = change.to.line; i > change.from.line; i--) {
if(doc.lines[i] !== undefined){
ops.push({p:['lines', i], ld: doc.lines[i]});
deletedLines[i] = true;
}
}
}
// change in text (deletion)
ops.push({p:textPath, sd: change.removed.join('\n')});
}
if (change.text) {
// change in text (insertion)
ops.push({p:textPath, si: change.text.join('\n')});
// new lines and pasting
if ((change.from.line === change.to.line && change.text.length > 1) || change.origin === 'paste') {
// figure out if there should also be an included line insertion
// // if the change was just to add a new line character, do a replace
// // on that line and then do an insert for the next
if (change.text.join('\n') === '\n') {
ops.push({p:['lines', change.from.line+1], li: {
client: timestamps.client,
timestamp: new Date ()
}});
} else {
/*
* For the following values of change.origin, we know what we want to happen.
* - null - this is a programmatic insertion
* - paste, redo, undo - cm detected the indicated behavior
*
* For others, they'll have to fall through and be handled accordingly.
* Not having this conditional here leads to things breaking...
*/
if (change.origin && change.origin !== 'paste' && change.origin !== 'redo' && change.origin !== 'undo') {
console.warn('not sure what to do in this case', change);
} else {
if (newTimestamp !== doc.lines[change.from.line].timestamp ||
timestamps.client !== doc.lines[change.from.line].client) {
// replace (delete and insert) the line with updated values
ops.push({p:['lines', change.from.line], ld: doc.lines[change.from.line], li: {
client: timestamps.client,
timestamp: new Date ()
}});
}
for (i = 1; i < change.text.length; i++) {
ops.push({p:['lines', change.from.line+1], li: {
client: timestamps.client,
timestamp: new Date ()
}});
}
}
}
} else {
// change in lines (replace + insertion)
for (var changeTextIndex = 0; changeTextIndex < change.text.length; changeTextIndex++) {
var lineChange = change.text[changeTextIndex];
var lineIndex = change.from.line + changeTextIndex;
if (doc.lines[lineIndex]) {
// if this line was just deleted, we don't want to submit any
// updates for it ... we have already updated the text appropriately,
// updating this now will update the wrong line.
var newTimestamp = new Date ();
// the line metadata has changed (new author or new date)
if (newTimestamp !== doc.lines[lineIndex].timestamp ||
timestamps.client !== doc.lines[lineIndex].client) {
// replace (delete and insert) the line with updated values
ops.push({p:['lines', lineIndex], ld: doc.lines[lineIndex], li: {
client: timestamps.client,
timestamp: newTimestamp
}});
}
} else {
// the line doesn't currently exist, so insert a new line
ops.push({p:['lines', lineIndex], li: {
client: timestamps.client,
timestamp: new Date ()
}});
}
}
}
}
// submit the complete list of changes
ctx.submitOp(ops);
// call the function again on the next change, if there is one
if (change.next) {
applyToShareJS(cm, change.next);
}
} | [
"function",
"applyToShareJS",
"(",
"cm",
",",
"change",
")",
"{",
"// CodeMirror changes give a text replacement.",
"var",
"startPos",
"=",
"0",
";",
"// Get character position from # of chars in each line.",
"var",
"i",
"=",
"0",
";",
"// i goes through all lines.",
"while",
"(",
"i",
"<",
"change",
".",
"from",
".",
"line",
")",
"{",
"startPos",
"+=",
"cm",
".",
"lineInfo",
"(",
"i",
")",
".",
"text",
".",
"length",
"+",
"1",
";",
"// Add 1 for '\\n'",
"i",
"++",
";",
"}",
"startPos",
"+=",
"change",
".",
"from",
".",
"ch",
";",
"// sharejs json path to the location of the change",
"var",
"textPath",
"=",
"[",
"'text'",
",",
"startPos",
"]",
";",
"// array of operations that will be submitted",
"var",
"ops",
"=",
"[",
"]",
";",
"// object to keep track of lines that were deleted",
"var",
"deletedLines",
"=",
"{",
"}",
";",
"// get an updated document",
"var",
"doc",
"=",
"ctx",
".",
"get",
"(",
")",
";",
"if",
"(",
"change",
".",
"to",
".",
"line",
"==",
"change",
".",
"from",
".",
"line",
"&&",
"change",
".",
"to",
".",
"ch",
"==",
"change",
".",
"from",
".",
"ch",
")",
"{",
"// nothing was removed.",
"}",
"else",
"{",
"// change in lines (deleted lines)",
"if",
"(",
"change",
".",
"to",
".",
"line",
"!==",
"change",
".",
"from",
".",
"line",
")",
"{",
"for",
"(",
"i",
"=",
"change",
".",
"to",
".",
"line",
";",
"i",
">",
"change",
".",
"from",
".",
"line",
";",
"i",
"--",
")",
"{",
"if",
"(",
"doc",
".",
"lines",
"[",
"i",
"]",
"!==",
"undefined",
")",
"{",
"ops",
".",
"push",
"(",
"{",
"p",
":",
"[",
"'lines'",
",",
"i",
"]",
",",
"ld",
":",
"doc",
".",
"lines",
"[",
"i",
"]",
"}",
")",
";",
"deletedLines",
"[",
"i",
"]",
"=",
"true",
";",
"}",
"}",
"}",
"// change in text (deletion)",
"ops",
".",
"push",
"(",
"{",
"p",
":",
"textPath",
",",
"sd",
":",
"change",
".",
"removed",
".",
"join",
"(",
"'\\n'",
")",
"}",
")",
";",
"}",
"if",
"(",
"change",
".",
"text",
")",
"{",
"// change in text (insertion)",
"ops",
".",
"push",
"(",
"{",
"p",
":",
"textPath",
",",
"si",
":",
"change",
".",
"text",
".",
"join",
"(",
"'\\n'",
")",
"}",
")",
";",
"// new lines and pasting",
"if",
"(",
"(",
"change",
".",
"from",
".",
"line",
"===",
"change",
".",
"to",
".",
"line",
"&&",
"change",
".",
"text",
".",
"length",
">",
"1",
")",
"||",
"change",
".",
"origin",
"===",
"'paste'",
")",
"{",
"// figure out if there should also be an included line insertion",
"// // if the change was just to add a new line character, do a replace",
"// // on that line and then do an insert for the next",
"if",
"(",
"change",
".",
"text",
".",
"join",
"(",
"'\\n'",
")",
"===",
"'\\n'",
")",
"{",
"ops",
".",
"push",
"(",
"{",
"p",
":",
"[",
"'lines'",
",",
"change",
".",
"from",
".",
"line",
"+",
"1",
"]",
",",
"li",
":",
"{",
"client",
":",
"timestamps",
".",
"client",
",",
"timestamp",
":",
"new",
"Date",
"(",
")",
"}",
"}",
")",
";",
"}",
"else",
"{",
"/*\n * For the following values of change.origin, we know what we want to happen.\n * - null - this is a programmatic insertion\n * - paste, redo, undo - cm detected the indicated behavior\n *\n * For others, they'll have to fall through and be handled accordingly.\n * Not having this conditional here leads to things breaking...\n */",
"if",
"(",
"change",
".",
"origin",
"&&",
"change",
".",
"origin",
"!==",
"'paste'",
"&&",
"change",
".",
"origin",
"!==",
"'redo'",
"&&",
"change",
".",
"origin",
"!==",
"'undo'",
")",
"{",
"console",
".",
"warn",
"(",
"'not sure what to do in this case'",
",",
"change",
")",
";",
"}",
"else",
"{",
"if",
"(",
"newTimestamp",
"!==",
"doc",
".",
"lines",
"[",
"change",
".",
"from",
".",
"line",
"]",
".",
"timestamp",
"||",
"timestamps",
".",
"client",
"!==",
"doc",
".",
"lines",
"[",
"change",
".",
"from",
".",
"line",
"]",
".",
"client",
")",
"{",
"// replace (delete and insert) the line with updated values",
"ops",
".",
"push",
"(",
"{",
"p",
":",
"[",
"'lines'",
",",
"change",
".",
"from",
".",
"line",
"]",
",",
"ld",
":",
"doc",
".",
"lines",
"[",
"change",
".",
"from",
".",
"line",
"]",
",",
"li",
":",
"{",
"client",
":",
"timestamps",
".",
"client",
",",
"timestamp",
":",
"new",
"Date",
"(",
")",
"}",
"}",
")",
";",
"}",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<",
"change",
".",
"text",
".",
"length",
";",
"i",
"++",
")",
"{",
"ops",
".",
"push",
"(",
"{",
"p",
":",
"[",
"'lines'",
",",
"change",
".",
"from",
".",
"line",
"+",
"1",
"]",
",",
"li",
":",
"{",
"client",
":",
"timestamps",
".",
"client",
",",
"timestamp",
":",
"new",
"Date",
"(",
")",
"}",
"}",
")",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"// change in lines (replace + insertion)",
"for",
"(",
"var",
"changeTextIndex",
"=",
"0",
";",
"changeTextIndex",
"<",
"change",
".",
"text",
".",
"length",
";",
"changeTextIndex",
"++",
")",
"{",
"var",
"lineChange",
"=",
"change",
".",
"text",
"[",
"changeTextIndex",
"]",
";",
"var",
"lineIndex",
"=",
"change",
".",
"from",
".",
"line",
"+",
"changeTextIndex",
";",
"if",
"(",
"doc",
".",
"lines",
"[",
"lineIndex",
"]",
")",
"{",
"// if this line was just deleted, we don't want to submit any",
"// updates for it ... we have already updated the text appropriately,",
"// updating this now will update the wrong line.",
"var",
"newTimestamp",
"=",
"new",
"Date",
"(",
")",
";",
"// the line metadata has changed (new author or new date)",
"if",
"(",
"newTimestamp",
"!==",
"doc",
".",
"lines",
"[",
"lineIndex",
"]",
".",
"timestamp",
"||",
"timestamps",
".",
"client",
"!==",
"doc",
".",
"lines",
"[",
"lineIndex",
"]",
".",
"client",
")",
"{",
"// replace (delete and insert) the line with updated values",
"ops",
".",
"push",
"(",
"{",
"p",
":",
"[",
"'lines'",
",",
"lineIndex",
"]",
",",
"ld",
":",
"doc",
".",
"lines",
"[",
"lineIndex",
"]",
",",
"li",
":",
"{",
"client",
":",
"timestamps",
".",
"client",
",",
"timestamp",
":",
"newTimestamp",
"}",
"}",
")",
";",
"}",
"}",
"else",
"{",
"// the line doesn't currently exist, so insert a new line",
"ops",
".",
"push",
"(",
"{",
"p",
":",
"[",
"'lines'",
",",
"lineIndex",
"]",
",",
"li",
":",
"{",
"client",
":",
"timestamps",
".",
"client",
",",
"timestamp",
":",
"new",
"Date",
"(",
")",
"}",
"}",
")",
";",
"}",
"}",
"}",
"}",
"// submit the complete list of changes",
"ctx",
".",
"submitOp",
"(",
"ops",
")",
";",
"// call the function again on the next change, if there is one",
"if",
"(",
"change",
".",
"next",
")",
"{",
"applyToShareJS",
"(",
"cm",
",",
"change",
".",
"next",
")",
";",
"}",
"}"
]
| Convert a CodeMirror change into an op understood by share.js | [
"Convert",
"a",
"CodeMirror",
"change",
"into",
"an",
"op",
"understood",
"by",
"share",
".",
"js"
]
| 3a154c0d86a3bcf8980c5104daec099ec738a4e0 | https://github.com/VisionistInc/jibe/blob/3a154c0d86a3bcf8980c5104daec099ec738a4e0/public/js/share-codemirror-json.js#L101-L236 |
47,113 | quorrajs/Positron | lib/foundation/start.js | start | function start(CB, env) {
var app = this;
/*
|--------------------------------------------------------------------------
| Register The Environment Variables
|--------------------------------------------------------------------------
|
| Here we will register all of the ENV variables into the
| process so that they're globally available configuration options so
| sensitive configuration information can be swept out of the code.
|
*/
(new EnvironmentVariables(app.getEnvironmentVariablesLoader())).load(env);
/*
|--------------------------------------------------------------------------
| Register The Configuration Repository
|--------------------------------------------------------------------------
|
| The configuration repository is used to lazily load in the options for
| this application from the configuration files. The files are easily
| separated by their concerns so they do not become really crowded.
|
*/
app.config = new Config(
app.getConfigLoader(), env
);
// Set additional configurations
app.config.set('cache.etagFn', utils.compileETag(app.config.get('cache').etag));
app.config.set('middleware.queryParserFn', utils.compileQueryParser(app.config.get('middleware').queryParser));
app.config.set('request.trustProxyFn', utils.compileTrust(app.config.get('request').trustProxy));
// Expose use method globally
global.use = app.use.bind(app);
// Register user aliases for Positron modules
app.alias(app.config.get('app.aliases', {}));
/*
|--------------------------------------------------------------------------
| Register Booted Start Files & Expose Globals
|--------------------------------------------------------------------------
|
| Once the application has been booted we will expose app globals as per
| user configuration. Also there are several "start" files
| we will want to include. We'll register our "booted" handler here
| so the files are included after the application gets booted up.
|
*/
app.booted(function() {
// expose app globals
app.exposeGlobals();
/*
|--------------------------------------------------------------------------
| Load The Application Start Script
|--------------------------------------------------------------------------
|
| The start scripts gives this application the opportunity to do things
| that should be done right after application has booted like configure
| application logger, load filters etc. We'll load it here.
|
*/
var appStartScript = app.path.app + "/start/global.js";
/*
|--------------------------------------------------------------------------
| Load The Environment Start Script
|--------------------------------------------------------------------------
|
| The environment start script is only loaded if it exists for the app
| environment currently active, which allows some actions to happen
| in one environment while not in the other, keeping things clean.
|
*/
var envStartScript = app.path.app + "/start/" + env + ".js";
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| The Application routes are kept separate from the application starting
| just to keep the file a little cleaner. We'll go ahead and load in
| all of the routes now and return the application to the callers.
|
*/
var routes = app.path.app + "/routes.js";
async.filter([appStartScript, envStartScript, routes], fs.exists, function (results) {
results.forEach(function (path) {
require(path);
});
CB(app);
});
});
/*
|--------------------------------------------------------------------------
| Register The Core Service Providers
|--------------------------------------------------------------------------
|
| The Positron core service providers register all of the core pieces
| of the Positron framework including session, auth, encryption
| and more. It's simply a convenient wrapper for the registration.
|
*/
var providers = app.config.get('app').providers;
app.getProviderRepository().load(providers, function() {
/*
|--------------------------------------------------------------------------
| Boot The Application
|--------------------------------------------------------------------------
|
| Once all service providers are loaded we will call the boot method on
| application which will boot all service provider's and eventually boot the
| positron application.
|
*/
app.boot();
});
} | javascript | function start(CB, env) {
var app = this;
/*
|--------------------------------------------------------------------------
| Register The Environment Variables
|--------------------------------------------------------------------------
|
| Here we will register all of the ENV variables into the
| process so that they're globally available configuration options so
| sensitive configuration information can be swept out of the code.
|
*/
(new EnvironmentVariables(app.getEnvironmentVariablesLoader())).load(env);
/*
|--------------------------------------------------------------------------
| Register The Configuration Repository
|--------------------------------------------------------------------------
|
| The configuration repository is used to lazily load in the options for
| this application from the configuration files. The files are easily
| separated by their concerns so they do not become really crowded.
|
*/
app.config = new Config(
app.getConfigLoader(), env
);
// Set additional configurations
app.config.set('cache.etagFn', utils.compileETag(app.config.get('cache').etag));
app.config.set('middleware.queryParserFn', utils.compileQueryParser(app.config.get('middleware').queryParser));
app.config.set('request.trustProxyFn', utils.compileTrust(app.config.get('request').trustProxy));
// Expose use method globally
global.use = app.use.bind(app);
// Register user aliases for Positron modules
app.alias(app.config.get('app.aliases', {}));
/*
|--------------------------------------------------------------------------
| Register Booted Start Files & Expose Globals
|--------------------------------------------------------------------------
|
| Once the application has been booted we will expose app globals as per
| user configuration. Also there are several "start" files
| we will want to include. We'll register our "booted" handler here
| so the files are included after the application gets booted up.
|
*/
app.booted(function() {
// expose app globals
app.exposeGlobals();
/*
|--------------------------------------------------------------------------
| Load The Application Start Script
|--------------------------------------------------------------------------
|
| The start scripts gives this application the opportunity to do things
| that should be done right after application has booted like configure
| application logger, load filters etc. We'll load it here.
|
*/
var appStartScript = app.path.app + "/start/global.js";
/*
|--------------------------------------------------------------------------
| Load The Environment Start Script
|--------------------------------------------------------------------------
|
| The environment start script is only loaded if it exists for the app
| environment currently active, which allows some actions to happen
| in one environment while not in the other, keeping things clean.
|
*/
var envStartScript = app.path.app + "/start/" + env + ".js";
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| The Application routes are kept separate from the application starting
| just to keep the file a little cleaner. We'll go ahead and load in
| all of the routes now and return the application to the callers.
|
*/
var routes = app.path.app + "/routes.js";
async.filter([appStartScript, envStartScript, routes], fs.exists, function (results) {
results.forEach(function (path) {
require(path);
});
CB(app);
});
});
/*
|--------------------------------------------------------------------------
| Register The Core Service Providers
|--------------------------------------------------------------------------
|
| The Positron core service providers register all of the core pieces
| of the Positron framework including session, auth, encryption
| and more. It's simply a convenient wrapper for the registration.
|
*/
var providers = app.config.get('app').providers;
app.getProviderRepository().load(providers, function() {
/*
|--------------------------------------------------------------------------
| Boot The Application
|--------------------------------------------------------------------------
|
| Once all service providers are loaded we will call the boot method on
| application which will boot all service provider's and eventually boot the
| positron application.
|
*/
app.boot();
});
} | [
"function",
"start",
"(",
"CB",
",",
"env",
")",
"{",
"var",
"app",
"=",
"this",
";",
"/*\n |--------------------------------------------------------------------------\n | Register The Environment Variables\n |--------------------------------------------------------------------------\n |\n | Here we will register all of the ENV variables into the\n | process so that they're globally available configuration options so\n | sensitive configuration information can be swept out of the code.\n |\n */",
"(",
"new",
"EnvironmentVariables",
"(",
"app",
".",
"getEnvironmentVariablesLoader",
"(",
")",
")",
")",
".",
"load",
"(",
"env",
")",
";",
"/*\n |--------------------------------------------------------------------------\n | Register The Configuration Repository\n |--------------------------------------------------------------------------\n |\n | The configuration repository is used to lazily load in the options for\n | this application from the configuration files. The files are easily\n | separated by their concerns so they do not become really crowded.\n |\n */",
"app",
".",
"config",
"=",
"new",
"Config",
"(",
"app",
".",
"getConfigLoader",
"(",
")",
",",
"env",
")",
";",
"// Set additional configurations",
"app",
".",
"config",
".",
"set",
"(",
"'cache.etagFn'",
",",
"utils",
".",
"compileETag",
"(",
"app",
".",
"config",
".",
"get",
"(",
"'cache'",
")",
".",
"etag",
")",
")",
";",
"app",
".",
"config",
".",
"set",
"(",
"'middleware.queryParserFn'",
",",
"utils",
".",
"compileQueryParser",
"(",
"app",
".",
"config",
".",
"get",
"(",
"'middleware'",
")",
".",
"queryParser",
")",
")",
";",
"app",
".",
"config",
".",
"set",
"(",
"'request.trustProxyFn'",
",",
"utils",
".",
"compileTrust",
"(",
"app",
".",
"config",
".",
"get",
"(",
"'request'",
")",
".",
"trustProxy",
")",
")",
";",
"// Expose use method globally",
"global",
".",
"use",
"=",
"app",
".",
"use",
".",
"bind",
"(",
"app",
")",
";",
"// Register user aliases for Positron modules",
"app",
".",
"alias",
"(",
"app",
".",
"config",
".",
"get",
"(",
"'app.aliases'",
",",
"{",
"}",
")",
")",
";",
"/*\n |--------------------------------------------------------------------------\n | Register Booted Start Files & Expose Globals\n |--------------------------------------------------------------------------\n |\n | Once the application has been booted we will expose app globals as per\n | user configuration. Also there are several \"start\" files\n | we will want to include. We'll register our \"booted\" handler here\n | so the files are included after the application gets booted up.\n |\n */",
"app",
".",
"booted",
"(",
"function",
"(",
")",
"{",
"// expose app globals",
"app",
".",
"exposeGlobals",
"(",
")",
";",
"/*\n |--------------------------------------------------------------------------\n | Load The Application Start Script\n |--------------------------------------------------------------------------\n |\n | The start scripts gives this application the opportunity to do things\n | that should be done right after application has booted like configure\n | application logger, load filters etc. We'll load it here.\n |\n */",
"var",
"appStartScript",
"=",
"app",
".",
"path",
".",
"app",
"+",
"\"/start/global.js\"",
";",
"/*\n |--------------------------------------------------------------------------\n | Load The Environment Start Script\n |--------------------------------------------------------------------------\n |\n | The environment start script is only loaded if it exists for the app\n | environment currently active, which allows some actions to happen\n | in one environment while not in the other, keeping things clean.\n |\n */",
"var",
"envStartScript",
"=",
"app",
".",
"path",
".",
"app",
"+",
"\"/start/\"",
"+",
"env",
"+",
"\".js\"",
";",
"/*\n |--------------------------------------------------------------------------\n | Load The Application Routes\n |--------------------------------------------------------------------------\n |\n | The Application routes are kept separate from the application starting\n | just to keep the file a little cleaner. We'll go ahead and load in\n | all of the routes now and return the application to the callers.\n |\n */",
"var",
"routes",
"=",
"app",
".",
"path",
".",
"app",
"+",
"\"/routes.js\"",
";",
"async",
".",
"filter",
"(",
"[",
"appStartScript",
",",
"envStartScript",
",",
"routes",
"]",
",",
"fs",
".",
"exists",
",",
"function",
"(",
"results",
")",
"{",
"results",
".",
"forEach",
"(",
"function",
"(",
"path",
")",
"{",
"require",
"(",
"path",
")",
";",
"}",
")",
";",
"CB",
"(",
"app",
")",
";",
"}",
")",
";",
"}",
")",
";",
"/*\n |--------------------------------------------------------------------------\n | Register The Core Service Providers\n |--------------------------------------------------------------------------\n |\n | The Positron core service providers register all of the core pieces\n | of the Positron framework including session, auth, encryption\n | and more. It's simply a convenient wrapper for the registration.\n |\n */",
"var",
"providers",
"=",
"app",
".",
"config",
".",
"get",
"(",
"'app'",
")",
".",
"providers",
";",
"app",
".",
"getProviderRepository",
"(",
")",
".",
"load",
"(",
"providers",
",",
"function",
"(",
")",
"{",
"/*\n |--------------------------------------------------------------------------\n | Boot The Application\n |--------------------------------------------------------------------------\n |\n | Once all service providers are loaded we will call the boot method on\n | application which will boot all service provider's and eventually boot the\n | positron application.\n |\n */",
"app",
".",
"boot",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Application.prototype.start
@param CB
@param env | [
"Application",
".",
"prototype",
".",
"start"
]
| a4bad5a5f581743d1885405c11ae26600fb957af | https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/foundation/start.js#L22-L152 |
47,114 | edloidas/roll-parser | src/complex/parse.js | parse | function parse( roll ) {
const result = parseAny( roll );
const type = result ? result.type : '';
switch ( type ) {
case Type.simple:
return mapToRoll( result );
case Type.classic:
return mapToRoll( result );
case Type.wod:
return mapToWodRoll( result );
default:
return null;
}
} | javascript | function parse( roll ) {
const result = parseAny( roll );
const type = result ? result.type : '';
switch ( type ) {
case Type.simple:
return mapToRoll( result );
case Type.classic:
return mapToRoll( result );
case Type.wod:
return mapToWodRoll( result );
default:
return null;
}
} | [
"function",
"parse",
"(",
"roll",
")",
"{",
"const",
"result",
"=",
"parseAny",
"(",
"roll",
")",
";",
"const",
"type",
"=",
"result",
"?",
"result",
".",
"type",
":",
"''",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"Type",
".",
"simple",
":",
"return",
"mapToRoll",
"(",
"result",
")",
";",
"case",
"Type",
".",
"classic",
":",
"return",
"mapToRoll",
"(",
"result",
")",
";",
"case",
"Type",
".",
"wod",
":",
"return",
"mapToWodRoll",
"(",
"result",
")",
";",
"default",
":",
"return",
"null",
";",
"}",
"}"
]
| Parses simplified, classic or WoD roll notation.
@func
@since v2.0.0
@param {String} roll
@return {Roll|WodRoll|null}
@see parseSimpleRoll
@see parseClassicRoll
@see parseWodRoll
@example
parse('2 10 -1'); //=> { dice: 10, count: 2, modifier: -1 }
parse('2d10+1'); //=> { dice: 10, count: 2, modifier: 1 }
parse('4d10!>8f1'); //=> { dice: 10, count: 4, again: true, success: 8, fail: 1 }
parse('xyz'); //=> null | [
"Parses",
"simplified",
"classic",
"or",
"WoD",
"roll",
"notation",
"."
]
| 38912b298edb0a4d67ba1c796d7ac159ebaf7901 | https://github.com/edloidas/roll-parser/blob/38912b298edb0a4d67ba1c796d7ac159ebaf7901/src/complex/parse.js#L21-L35 |
47,115 | IonicaBizau/git-status | lib/index.js | gitStatus | function gitStatus (options, cb) {
if (typeof options === "function") {
cb = options;
options = {};
}
spawno("git", ["status", "--porcelain", "-z"], options, (err, stdout, stderr) => {
if (err || stderr) { return cb(err || stderr, stdout); }
cb(null, parse(stdout));
});
} | javascript | function gitStatus (options, cb) {
if (typeof options === "function") {
cb = options;
options = {};
}
spawno("git", ["status", "--porcelain", "-z"], options, (err, stdout, stderr) => {
if (err || stderr) { return cb(err || stderr, stdout); }
cb(null, parse(stdout));
});
} | [
"function",
"gitStatus",
"(",
"options",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"\"function\"",
")",
"{",
"cb",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"spawno",
"(",
"\"git\"",
",",
"[",
"\"status\"",
",",
"\"--porcelain\"",
",",
"\"-z\"",
"]",
",",
"options",
",",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"=>",
"{",
"if",
"(",
"err",
"||",
"stderr",
")",
"{",
"return",
"cb",
"(",
"err",
"||",
"stderr",
",",
"stdout",
")",
";",
"}",
"cb",
"(",
"null",
",",
"parse",
"(",
"stdout",
")",
")",
";",
"}",
")",
";",
"}"
]
| gitStatus
A git-status wrapper.
[`parse-git-status`](https://github.com/jamestalmage/parse-git-status) is used to parse the output.
@name gitStatus
@function
@param {Object} options The `spawno` options.
@param {Function} cb The callback function. | [
"gitStatus",
"A",
"git",
"-",
"status",
"wrapper",
"."
]
| b0298a14cbac920952e6a137177aa3a701d94441 | https://github.com/IonicaBizau/git-status/blob/b0298a14cbac920952e6a137177aa3a701d94441/lib/index.js#L19-L29 |
47,116 | Heymdall/cron-to-text | src/parseCron.js | getValue | function getValue(value, offset = 0, max = 9999) {
return isNaN(value) ? NAMES[value] || null : Math.min(+value + (offset), max);
} | javascript | function getValue(value, offset = 0, max = 9999) {
return isNaN(value) ? NAMES[value] || null : Math.min(+value + (offset), max);
} | [
"function",
"getValue",
"(",
"value",
",",
"offset",
"=",
"0",
",",
"max",
"=",
"9999",
")",
"{",
"return",
"isNaN",
"(",
"value",
")",
"?",
"NAMES",
"[",
"value",
"]",
"||",
"null",
":",
"Math",
".",
"min",
"(",
"+",
"value",
"+",
"(",
"offset",
")",
",",
"max",
")",
";",
"}"
]
| Returns the value + offset if value is a number, otherwise it
attempts to look up the value in the NAMES table and returns
that result instead.
@param {Number,String} value: The value that should be parsed
@param {Number=} offset: Any offset that must be added to the value
@param {Number=} max
@returns {Number|null} | [
"Returns",
"the",
"value",
"+",
"offset",
"if",
"value",
"is",
"a",
"number",
"otherwise",
"it",
"attempts",
"to",
"look",
"up",
"the",
"value",
"in",
"the",
"NAMES",
"table",
"and",
"returns",
"that",
"result",
"instead",
"."
]
| a6a0ae74a4b98bb951a4ae0fa68778a3c7ab9978 | https://github.com/Heymdall/cron-to-text/blob/a6a0ae74a4b98bb951a4ae0fa68778a3c7ab9978/src/parseCron.js#L40-L42 |
47,117 | diosney/json2pot | index.js | setDefaultOptions | function setDefaultOptions(options) {
const defaultOptions = {
src : [
'**/*.i18n.json',
'**/i18n/*.json',
'!node_modules'
],
destFile : 'translations.pot',
headers : {
'X-Poedit-Basepath' : '..',
'X-Poedit-SourceCharset': 'UTF-8',
'X-Poedit-SearchPath-0' : '.'
},
defaultHeaders: true,
writeFile : true
};
if (options.headers === false) {
options.defaultHeaders = false;
}
options = Object.assign({}, defaultOptions, options);
if (!options.package) {
options.package = options.domain || 'unnamed project';
}
return options;
} | javascript | function setDefaultOptions(options) {
const defaultOptions = {
src : [
'**/*.i18n.json',
'**/i18n/*.json',
'!node_modules'
],
destFile : 'translations.pot',
headers : {
'X-Poedit-Basepath' : '..',
'X-Poedit-SourceCharset': 'UTF-8',
'X-Poedit-SearchPath-0' : '.'
},
defaultHeaders: true,
writeFile : true
};
if (options.headers === false) {
options.defaultHeaders = false;
}
options = Object.assign({}, defaultOptions, options);
if (!options.package) {
options.package = options.domain || 'unnamed project';
}
return options;
} | [
"function",
"setDefaultOptions",
"(",
"options",
")",
"{",
"const",
"defaultOptions",
"=",
"{",
"src",
":",
"[",
"'**/*.i18n.json'",
",",
"'**/i18n/*.json'",
",",
"'!node_modules'",
"]",
",",
"destFile",
":",
"'translations.pot'",
",",
"headers",
":",
"{",
"'X-Poedit-Basepath'",
":",
"'..'",
",",
"'X-Poedit-SourceCharset'",
":",
"'UTF-8'",
",",
"'X-Poedit-SearchPath-0'",
":",
"'.'",
"}",
",",
"defaultHeaders",
":",
"true",
",",
"writeFile",
":",
"true",
"}",
";",
"if",
"(",
"options",
".",
"headers",
"===",
"false",
")",
"{",
"options",
".",
"defaultHeaders",
"=",
"false",
";",
"}",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"defaultOptions",
",",
"options",
")",
";",
"if",
"(",
"!",
"options",
".",
"package",
")",
"{",
"options",
".",
"package",
"=",
"options",
".",
"domain",
"||",
"'unnamed project'",
";",
"}",
"return",
"options",
";",
"}"
]
| Set default options.
@param {Object} options
@return {Object} | [
"Set",
"default",
"options",
"."
]
| a46c8dc0f479141824d05330d7b31cf72a5e8aa1 | https://github.com/diosney/json2pot/blob/a46c8dc0f479141824d05330d7b31cf72a5e8aa1/index.js#L17-L45 |
47,118 | marksmccann/boost-js | src/boost.js | function( str ) {
return str
// Replaces any - or _ characters with a space
.replace( /[-_]+/g, ' ')
// Removes any non alphanumeric characters
.replace( /[^\w\s]/g, '')
// Uppercases the first character in each group
// immediately following a space (delimited by spaces)
.replace( / (.)/g, function($1) { return $1.toUpperCase(); })
// Removes spaces
.replace( / /g, '' );
} | javascript | function( str ) {
return str
// Replaces any - or _ characters with a space
.replace( /[-_]+/g, ' ')
// Removes any non alphanumeric characters
.replace( /[^\w\s]/g, '')
// Uppercases the first character in each group
// immediately following a space (delimited by spaces)
.replace( / (.)/g, function($1) { return $1.toUpperCase(); })
// Removes spaces
.replace( / /g, '' );
} | [
"function",
"(",
"str",
")",
"{",
"return",
"str",
"// Replaces any - or _ characters with a space",
".",
"replace",
"(",
"/",
"[-_]+",
"/",
"g",
",",
"' '",
")",
"// Removes any non alphanumeric characters",
".",
"replace",
"(",
"/",
"[^\\w\\s]",
"/",
"g",
",",
"''",
")",
"// Uppercases the first character in each group",
"// immediately following a space (delimited by spaces)",
".",
"replace",
"(",
"/",
" (.)",
"/",
"g",
",",
"function",
"(",
"$1",
")",
"{",
"return",
"$1",
".",
"toUpperCase",
"(",
")",
";",
"}",
")",
"// Removes spaces",
".",
"replace",
"(",
"/",
" ",
"/",
"g",
",",
"''",
")",
";",
"}"
]
| Converts any string into a "javascript-friendly" version.
@param {string} str
@return {string} camelized | [
"Converts",
"any",
"string",
"into",
"a",
"javascript",
"-",
"friendly",
"version",
"."
]
| 0ed0972c4f1ca07f45d5a74f70378007c1e625cd | https://github.com/marksmccann/boost-js/blob/0ed0972c4f1ca07f45d5a74f70378007c1e625cd/src/boost.js#L17-L28 |
|
47,119 | marksmccann/boost-js | src/boost.js | function( str ) {
// if whole numbers, convert to integer
if( /^\d+$/.test(str) ) return parseInt( str );
// if decimal, convert to float
if( /^\d*\.\d+$/.test(str) ) return parseFloat( str );
// if "true" or "false", return boolean
if( /^true$/.test(str) ) return true;
if( /^false$/.test(str) ) return false;
// else, return original string
return str;
} | javascript | function( str ) {
// if whole numbers, convert to integer
if( /^\d+$/.test(str) ) return parseInt( str );
// if decimal, convert to float
if( /^\d*\.\d+$/.test(str) ) return parseFloat( str );
// if "true" or "false", return boolean
if( /^true$/.test(str) ) return true;
if( /^false$/.test(str) ) return false;
// else, return original string
return str;
} | [
"function",
"(",
"str",
")",
"{",
"// if whole numbers, convert to integer",
"if",
"(",
"/",
"^\\d+$",
"/",
".",
"test",
"(",
"str",
")",
")",
"return",
"parseInt",
"(",
"str",
")",
";",
"// if decimal, convert to float",
"if",
"(",
"/",
"^\\d*\\.\\d+$",
"/",
".",
"test",
"(",
"str",
")",
")",
"return",
"parseFloat",
"(",
"str",
")",
";",
"// if \"true\" or \"false\", return boolean",
"if",
"(",
"/",
"^true$",
"/",
".",
"test",
"(",
"str",
")",
")",
"return",
"true",
";",
"if",
"(",
"/",
"^false$",
"/",
".",
"test",
"(",
"str",
")",
")",
"return",
"false",
";",
"// else, return original string",
"return",
"str",
";",
"}"
]
| Intelligently converts a string to integer or boolean.
@param {string} str
@return {multi} str string|integer|boolean | [
"Intelligently",
"converts",
"a",
"string",
"to",
"integer",
"or",
"boolean",
"."
]
| 0ed0972c4f1ca07f45d5a74f70378007c1e625cd | https://github.com/marksmccann/boost-js/blob/0ed0972c4f1ca07f45d5a74f70378007c1e625cd/src/boost.js#L36-L46 |
|
47,120 | marksmccann/boost-js | src/boost.js | function( MyPlugin, defaults ) {
// make sure a function has been passed in to
// create a plugin from.
if (typeof MyPlugin === 'function') {
/**
* the plugin object, inherits all attributes and methods
* from the base plugin and the user's plugin
*
* @param {object} element
* @param {object} options
* @return {object} instance
*/
var Plugin = function( element, options ) {
Boilerplate.call( this, element, options || {}, defaults || {} );
MyPlugin.call( this, element, options );
return this;
}
// inherit prototype methods from MyPlugin
Plugin.prototype = MyPlugin.prototype;
// set constructor method to Plugin
Plugin.prototype.constructor = Plugin;
// set a couple static variables
Plugin.init = Boilerplate.init;
Plugin.instances = {};
Plugin.defaults = defaults || {};
/**
* An externalized object used to initialize the plugin and
* provides external access to plugin.
*
* @param {object} options
* @return {object} instance
*/
var Boost = function( options ) {
return Plugin.init.call( Plugin, this, options );
}
// externalize a couple vars by attaching them to obj
Boost.init = function( elems, options ) {
return Plugin.init.call( Plugin, elems, options );
}
Boost.instances = Plugin.instances;
Boost.defaults = Plugin.defaults;
// return the Boost object
return Boost;
} else {
throw '\'Boost JS\' requires a function as first paramater.';
}
} | javascript | function( MyPlugin, defaults ) {
// make sure a function has been passed in to
// create a plugin from.
if (typeof MyPlugin === 'function') {
/**
* the plugin object, inherits all attributes and methods
* from the base plugin and the user's plugin
*
* @param {object} element
* @param {object} options
* @return {object} instance
*/
var Plugin = function( element, options ) {
Boilerplate.call( this, element, options || {}, defaults || {} );
MyPlugin.call( this, element, options );
return this;
}
// inherit prototype methods from MyPlugin
Plugin.prototype = MyPlugin.prototype;
// set constructor method to Plugin
Plugin.prototype.constructor = Plugin;
// set a couple static variables
Plugin.init = Boilerplate.init;
Plugin.instances = {};
Plugin.defaults = defaults || {};
/**
* An externalized object used to initialize the plugin and
* provides external access to plugin.
*
* @param {object} options
* @return {object} instance
*/
var Boost = function( options ) {
return Plugin.init.call( Plugin, this, options );
}
// externalize a couple vars by attaching them to obj
Boost.init = function( elems, options ) {
return Plugin.init.call( Plugin, elems, options );
}
Boost.instances = Plugin.instances;
Boost.defaults = Plugin.defaults;
// return the Boost object
return Boost;
} else {
throw '\'Boost JS\' requires a function as first paramater.';
}
} | [
"function",
"(",
"MyPlugin",
",",
"defaults",
")",
"{",
"// make sure a function has been passed in to",
"// create a plugin from.",
"if",
"(",
"typeof",
"MyPlugin",
"===",
"'function'",
")",
"{",
"/**\n * the plugin object, inherits all attributes and methods\n * from the base plugin and the user's plugin\n *\n * @param {object} element\n * @param {object} options\n * @return {object} instance\n */",
"var",
"Plugin",
"=",
"function",
"(",
"element",
",",
"options",
")",
"{",
"Boilerplate",
".",
"call",
"(",
"this",
",",
"element",
",",
"options",
"||",
"{",
"}",
",",
"defaults",
"||",
"{",
"}",
")",
";",
"MyPlugin",
".",
"call",
"(",
"this",
",",
"element",
",",
"options",
")",
";",
"return",
"this",
";",
"}",
"// inherit prototype methods from MyPlugin",
"Plugin",
".",
"prototype",
"=",
"MyPlugin",
".",
"prototype",
";",
"// set constructor method to Plugin",
"Plugin",
".",
"prototype",
".",
"constructor",
"=",
"Plugin",
";",
"// set a couple static variables",
"Plugin",
".",
"init",
"=",
"Boilerplate",
".",
"init",
";",
"Plugin",
".",
"instances",
"=",
"{",
"}",
";",
"Plugin",
".",
"defaults",
"=",
"defaults",
"||",
"{",
"}",
";",
"/**\n * An externalized object used to initialize the plugin and\n * provides external access to plugin.\n *\n * @param {object} options\n * @return {object} instance\n */",
"var",
"Boost",
"=",
"function",
"(",
"options",
")",
"{",
"return",
"Plugin",
".",
"init",
".",
"call",
"(",
"Plugin",
",",
"this",
",",
"options",
")",
";",
"}",
"// externalize a couple vars by attaching them to obj",
"Boost",
".",
"init",
"=",
"function",
"(",
"elems",
",",
"options",
")",
"{",
"return",
"Plugin",
".",
"init",
".",
"call",
"(",
"Plugin",
",",
"elems",
",",
"options",
")",
";",
"}",
"Boost",
".",
"instances",
"=",
"Plugin",
".",
"instances",
";",
"Boost",
".",
"defaults",
"=",
"Plugin",
".",
"defaults",
";",
"// return the Boost object",
"return",
"Boost",
";",
"}",
"else",
"{",
"throw",
"'\\'Boost JS\\' requires a function as first paramater.'",
";",
"}",
"}"
]
| Creates a new plugin
@param {object} MyPlugin Class from which plugin will be created
@param {object} defaults Default settings for this plugin
@return {object} instance | [
"Creates",
"a",
"new",
"plugin"
]
| 0ed0972c4f1ca07f45d5a74f70378007c1e625cd | https://github.com/marksmccann/boost-js/blob/0ed0972c4f1ca07f45d5a74f70378007c1e625cd/src/boost.js#L140-L194 |
|
47,121 | marksmccann/boost-js | src/boost.js | function( element, options ) {
Boilerplate.call( this, element, options || {}, defaults || {} );
MyPlugin.call( this, element, options );
return this;
} | javascript | function( element, options ) {
Boilerplate.call( this, element, options || {}, defaults || {} );
MyPlugin.call( this, element, options );
return this;
} | [
"function",
"(",
"element",
",",
"options",
")",
"{",
"Boilerplate",
".",
"call",
"(",
"this",
",",
"element",
",",
"options",
"||",
"{",
"}",
",",
"defaults",
"||",
"{",
"}",
")",
";",
"MyPlugin",
".",
"call",
"(",
"this",
",",
"element",
",",
"options",
")",
";",
"return",
"this",
";",
"}"
]
| the plugin object, inherits all attributes and methods
from the base plugin and the user's plugin
@param {object} element
@param {object} options
@return {object} instance | [
"the",
"plugin",
"object",
"inherits",
"all",
"attributes",
"and",
"methods",
"from",
"the",
"base",
"plugin",
"and",
"the",
"user",
"s",
"plugin"
]
| 0ed0972c4f1ca07f45d5a74f70378007c1e625cd | https://github.com/marksmccann/boost-js/blob/0ed0972c4f1ca07f45d5a74f70378007c1e625cd/src/boost.js#L154-L158 |
|
47,122 | kengz/poly-socketio | src/start-io.js | ioServer | function ioServer(port = 6466, clientCount = 1, timeoutMs = 100000) {
if (global.io) {
// if already started
return Promise.resolve()
}
log.info(`Starting poly-socketio server on port: ${port}, expecting ${clientCount} IO clients`)
global.io = socketIO(server)
var count = clientCount
global.ioPromise = new Promise((resolve, reject) => {
global.io.sockets.on('connection', (socket) => {
// serialize for direct communication by using join room
socket.on('join', (id) => {
socket.join(id)
count--
log.info(`${id} ${socket.id} joined, ${count} remains`)
if (count <= 0) {
log.info(`All ${clientCount} IO clients have joined`)
resolve(server) // resolve with the server
}
})
socket.on('disconnect', () => { log.info(socket.id, 'left') })
})
})
.timeout(timeoutMs)
.catch((err) => {
log.error(err.message)
log.error("Expected number of IO clients failed to join in time")
process.exit(1)
})
global.io.on('connection', (socket) => {
// generic pass to other script
socket.on('pass', (msg, fn) => {
log.debug(`IO on pass, msg: ${JSON.stringify(msg, null, 2)} fn: ${fn}`)
try {
// e.g. split 'hello.py' into ['hello', 'py']
// lang = 'py', module = 'hello'
var tokens = msg.to.split('.'),
lang = tokens.pop(),
module = _.join(tokens, '.')
// reset of <to> for easy calling. May be empty if just passing to client.<lang>
msg.to = module
global.io.sockets.in(lang).emit('take', msg)
} catch (e) { log.error(e.message) }
})
})
return new Promise((resolve, reject) => {
server.listen(port, () => {
resolve()
})
})
} | javascript | function ioServer(port = 6466, clientCount = 1, timeoutMs = 100000) {
if (global.io) {
// if already started
return Promise.resolve()
}
log.info(`Starting poly-socketio server on port: ${port}, expecting ${clientCount} IO clients`)
global.io = socketIO(server)
var count = clientCount
global.ioPromise = new Promise((resolve, reject) => {
global.io.sockets.on('connection', (socket) => {
// serialize for direct communication by using join room
socket.on('join', (id) => {
socket.join(id)
count--
log.info(`${id} ${socket.id} joined, ${count} remains`)
if (count <= 0) {
log.info(`All ${clientCount} IO clients have joined`)
resolve(server) // resolve with the server
}
})
socket.on('disconnect', () => { log.info(socket.id, 'left') })
})
})
.timeout(timeoutMs)
.catch((err) => {
log.error(err.message)
log.error("Expected number of IO clients failed to join in time")
process.exit(1)
})
global.io.on('connection', (socket) => {
// generic pass to other script
socket.on('pass', (msg, fn) => {
log.debug(`IO on pass, msg: ${JSON.stringify(msg, null, 2)} fn: ${fn}`)
try {
// e.g. split 'hello.py' into ['hello', 'py']
// lang = 'py', module = 'hello'
var tokens = msg.to.split('.'),
lang = tokens.pop(),
module = _.join(tokens, '.')
// reset of <to> for easy calling. May be empty if just passing to client.<lang>
msg.to = module
global.io.sockets.in(lang).emit('take', msg)
} catch (e) { log.error(e.message) }
})
})
return new Promise((resolve, reject) => {
server.listen(port, () => {
resolve()
})
})
} | [
"function",
"ioServer",
"(",
"port",
"=",
"6466",
",",
"clientCount",
"=",
"1",
",",
"timeoutMs",
"=",
"100000",
")",
"{",
"if",
"(",
"global",
".",
"io",
")",
"{",
"// if already started",
"return",
"Promise",
".",
"resolve",
"(",
")",
"}",
"log",
".",
"info",
"(",
"`",
"${",
"port",
"}",
"${",
"clientCount",
"}",
"`",
")",
"global",
".",
"io",
"=",
"socketIO",
"(",
"server",
")",
"var",
"count",
"=",
"clientCount",
"global",
".",
"ioPromise",
"=",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"global",
".",
"io",
".",
"sockets",
".",
"on",
"(",
"'connection'",
",",
"(",
"socket",
")",
"=>",
"{",
"// serialize for direct communication by using join room",
"socket",
".",
"on",
"(",
"'join'",
",",
"(",
"id",
")",
"=>",
"{",
"socket",
".",
"join",
"(",
"id",
")",
"count",
"--",
"log",
".",
"info",
"(",
"`",
"${",
"id",
"}",
"${",
"socket",
".",
"id",
"}",
"${",
"count",
"}",
"`",
")",
"if",
"(",
"count",
"<=",
"0",
")",
"{",
"log",
".",
"info",
"(",
"`",
"${",
"clientCount",
"}",
"`",
")",
"resolve",
"(",
"server",
")",
"// resolve with the server",
"}",
"}",
")",
"socket",
".",
"on",
"(",
"'disconnect'",
",",
"(",
")",
"=>",
"{",
"log",
".",
"info",
"(",
"socket",
".",
"id",
",",
"'left'",
")",
"}",
")",
"}",
")",
"}",
")",
".",
"timeout",
"(",
"timeoutMs",
")",
".",
"catch",
"(",
"(",
"err",
")",
"=>",
"{",
"log",
".",
"error",
"(",
"err",
".",
"message",
")",
"log",
".",
"error",
"(",
"\"Expected number of IO clients failed to join in time\"",
")",
"process",
".",
"exit",
"(",
"1",
")",
"}",
")",
"global",
".",
"io",
".",
"on",
"(",
"'connection'",
",",
"(",
"socket",
")",
"=>",
"{",
"// generic pass to other script",
"socket",
".",
"on",
"(",
"'pass'",
",",
"(",
"msg",
",",
"fn",
")",
"=>",
"{",
"log",
".",
"debug",
"(",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"msg",
",",
"null",
",",
"2",
")",
"}",
"${",
"fn",
"}",
"`",
")",
"try",
"{",
"// e.g. split 'hello.py' into ['hello', 'py']",
"// lang = 'py', module = 'hello'",
"var",
"tokens",
"=",
"msg",
".",
"to",
".",
"split",
"(",
"'.'",
")",
",",
"lang",
"=",
"tokens",
".",
"pop",
"(",
")",
",",
"module",
"=",
"_",
".",
"join",
"(",
"tokens",
",",
"'.'",
")",
"// reset of <to> for easy calling. May be empty if just passing to client.<lang>",
"msg",
".",
"to",
"=",
"module",
"global",
".",
"io",
".",
"sockets",
".",
"in",
"(",
"lang",
")",
".",
"emit",
"(",
"'take'",
",",
"msg",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"log",
".",
"error",
"(",
"e",
".",
"message",
")",
"}",
"}",
")",
"}",
")",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"server",
".",
"listen",
"(",
"port",
",",
"(",
")",
"=>",
"{",
"resolve",
"(",
")",
"}",
")",
"}",
")",
"}"
]
| Start a Socket IO server connecting to a brand new Express server for use in dev. Sets global.io too.
Has a failsafe for not starting multiple times even when called repeatedly by accident in the same thread.
@param {*} robot The hubot object
@return {server} server
/* istanbul ignore next | [
"Start",
"a",
"Socket",
"IO",
"server",
"connecting",
"to",
"a",
"brand",
"new",
"Express",
"server",
"for",
"use",
"in",
"dev",
".",
"Sets",
"global",
".",
"io",
"too",
".",
"Has",
"a",
"failsafe",
"for",
"not",
"starting",
"multiple",
"times",
"even",
"when",
"called",
"repeatedly",
"by",
"accident",
"in",
"the",
"same",
"thread",
"."
]
| 261f84d3b4267a6d1a36eadd6526ddb45369973e | https://github.com/kengz/poly-socketio/blob/261f84d3b4267a6d1a36eadd6526ddb45369973e/src/start-io.js#L21-L74 |
47,123 | YR/clock | src/index.js | run | function run() {
const current = now();
const queue = timeoutQueue.slice();
let interval = INTERVAL_MAX;
timeoutQueue.length = 0;
// Reset
if (runRafId > 0 || runTimeoutId > 0) {
stop();
}
for (let i = queue.length - 1; i >= 0; i--) {
const item = queue[i];
if (!item.cancelled) {
const duration = item.time - current;
if (duration <= 0) {
if (isDev) {
debug('timeout triggered for "%s" at %s', item.id, new Date().toLocaleTimeString());
}
item.fn.apply(item.fn, item.args);
} else {
// Store smallest duration
if (duration < interval) {
interval = duration;
}
timeoutQueue.push(item);
}
}
}
// Loop
if (timeoutQueue.length > 0) {
// Use raf if requested interval is less than cutoff
if (interval < INTERVAL_CUTOFF) {
runRafId = raf(run);
} else {
runTimeoutId = setTimeout(run, interval);
}
}
} | javascript | function run() {
const current = now();
const queue = timeoutQueue.slice();
let interval = INTERVAL_MAX;
timeoutQueue.length = 0;
// Reset
if (runRafId > 0 || runTimeoutId > 0) {
stop();
}
for (let i = queue.length - 1; i >= 0; i--) {
const item = queue[i];
if (!item.cancelled) {
const duration = item.time - current;
if (duration <= 0) {
if (isDev) {
debug('timeout triggered for "%s" at %s', item.id, new Date().toLocaleTimeString());
}
item.fn.apply(item.fn, item.args);
} else {
// Store smallest duration
if (duration < interval) {
interval = duration;
}
timeoutQueue.push(item);
}
}
}
// Loop
if (timeoutQueue.length > 0) {
// Use raf if requested interval is less than cutoff
if (interval < INTERVAL_CUTOFF) {
runRafId = raf(run);
} else {
runTimeoutId = setTimeout(run, interval);
}
}
} | [
"function",
"run",
"(",
")",
"{",
"const",
"current",
"=",
"now",
"(",
")",
";",
"const",
"queue",
"=",
"timeoutQueue",
".",
"slice",
"(",
")",
";",
"let",
"interval",
"=",
"INTERVAL_MAX",
";",
"timeoutQueue",
".",
"length",
"=",
"0",
";",
"// Reset",
"if",
"(",
"runRafId",
">",
"0",
"||",
"runTimeoutId",
">",
"0",
")",
"{",
"stop",
"(",
")",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"queue",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"const",
"item",
"=",
"queue",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"item",
".",
"cancelled",
")",
"{",
"const",
"duration",
"=",
"item",
".",
"time",
"-",
"current",
";",
"if",
"(",
"duration",
"<=",
"0",
")",
"{",
"if",
"(",
"isDev",
")",
"{",
"debug",
"(",
"'timeout triggered for \"%s\" at %s'",
",",
"item",
".",
"id",
",",
"new",
"Date",
"(",
")",
".",
"toLocaleTimeString",
"(",
")",
")",
";",
"}",
"item",
".",
"fn",
".",
"apply",
"(",
"item",
".",
"fn",
",",
"item",
".",
"args",
")",
";",
"}",
"else",
"{",
"// Store smallest duration",
"if",
"(",
"duration",
"<",
"interval",
")",
"{",
"interval",
"=",
"duration",
";",
"}",
"timeoutQueue",
".",
"push",
"(",
"item",
")",
";",
"}",
"}",
"}",
"// Loop",
"if",
"(",
"timeoutQueue",
".",
"length",
">",
"0",
")",
"{",
"// Use raf if requested interval is less than cutoff",
"if",
"(",
"interval",
"<",
"INTERVAL_CUTOFF",
")",
"{",
"runRafId",
"=",
"raf",
"(",
"run",
")",
";",
"}",
"else",
"{",
"runTimeoutId",
"=",
"setTimeout",
"(",
"run",
",",
"interval",
")",
";",
"}",
"}",
"}"
]
| Process outstanding queue items | [
"Process",
"outstanding",
"queue",
"items"
]
| 015badf5fdaef050b708b3a01e7f000afd76ab40 | https://github.com/YR/clock/blob/015badf5fdaef050b708b3a01e7f000afd76ab40/src/index.js#L141-L183 |
47,124 | YR/clock | src/index.js | onVisibilityChangeFactory | function onVisibilityChangeFactory(hidden) {
return function onVisibilityChange(evt) {
if (document[hidden]) {
debug('disable while hidden');
stop();
} else {
debug('enable while visible');
if (process.env.NODE_ENV === 'development') {
const current = now();
for (let i = 0, n = timeoutQueue.length; i < n; i++) {
const item = timeoutQueue[i];
if (item.time <= current) {
debug('timeout should trigger for "%s"', item.id);
} else {
const date = new Date();
date.setMilliseconds(date.getMilliseconds() + item.time - current);
debug('timeout for "%s" expected at %s', item.id, date.toLocaleTimeString());
}
}
}
run();
}
};
} | javascript | function onVisibilityChangeFactory(hidden) {
return function onVisibilityChange(evt) {
if (document[hidden]) {
debug('disable while hidden');
stop();
} else {
debug('enable while visible');
if (process.env.NODE_ENV === 'development') {
const current = now();
for (let i = 0, n = timeoutQueue.length; i < n; i++) {
const item = timeoutQueue[i];
if (item.time <= current) {
debug('timeout should trigger for "%s"', item.id);
} else {
const date = new Date();
date.setMilliseconds(date.getMilliseconds() + item.time - current);
debug('timeout for "%s" expected at %s', item.id, date.toLocaleTimeString());
}
}
}
run();
}
};
} | [
"function",
"onVisibilityChangeFactory",
"(",
"hidden",
")",
"{",
"return",
"function",
"onVisibilityChange",
"(",
"evt",
")",
"{",
"if",
"(",
"document",
"[",
"hidden",
"]",
")",
"{",
"debug",
"(",
"'disable while hidden'",
")",
";",
"stop",
"(",
")",
";",
"}",
"else",
"{",
"debug",
"(",
"'enable while visible'",
")",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"'development'",
")",
"{",
"const",
"current",
"=",
"now",
"(",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"n",
"=",
"timeoutQueue",
".",
"length",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"const",
"item",
"=",
"timeoutQueue",
"[",
"i",
"]",
";",
"if",
"(",
"item",
".",
"time",
"<=",
"current",
")",
"{",
"debug",
"(",
"'timeout should trigger for \"%s\"'",
",",
"item",
".",
"id",
")",
";",
"}",
"else",
"{",
"const",
"date",
"=",
"new",
"Date",
"(",
")",
";",
"date",
".",
"setMilliseconds",
"(",
"date",
".",
"getMilliseconds",
"(",
")",
"+",
"item",
".",
"time",
"-",
"current",
")",
";",
"debug",
"(",
"'timeout for \"%s\" expected at %s'",
",",
"item",
".",
"id",
",",
"date",
".",
"toLocaleTimeString",
"(",
")",
")",
";",
"}",
"}",
"}",
"run",
"(",
")",
";",
"}",
"}",
";",
"}"
]
| Generate visibilityChange handler
@param {String} hidden
@returns {Function} | [
"Generate",
"visibilityChange",
"handler"
]
| 015badf5fdaef050b708b3a01e7f000afd76ab40 | https://github.com/YR/clock/blob/015badf5fdaef050b708b3a01e7f000afd76ab40/src/index.js#L203-L229 |
47,125 | justinhelmer/npm-publish-release | index.js | publishToNpm | function publishToNpm() {
return new Promise(function(resolve, reject) {
_spork('npm', ['publish'], done, _.partial(reject, new Error('failed to publish to npm')));
function done() {
if (!options.quiet) {
gutil.log('Published to \'' + chalk.cyan('npm') + '\'');
}
resolve();
}
});
} | javascript | function publishToNpm() {
return new Promise(function(resolve, reject) {
_spork('npm', ['publish'], done, _.partial(reject, new Error('failed to publish to npm')));
function done() {
if (!options.quiet) {
gutil.log('Published to \'' + chalk.cyan('npm') + '\'');
}
resolve();
}
});
} | [
"function",
"publishToNpm",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"_spork",
"(",
"'npm'",
",",
"[",
"'publish'",
"]",
",",
"done",
",",
"_",
".",
"partial",
"(",
"reject",
",",
"new",
"Error",
"(",
"'failed to publish to npm'",
")",
")",
")",
";",
"function",
"done",
"(",
")",
"{",
"if",
"(",
"!",
"options",
".",
"quiet",
")",
"{",
"gutil",
".",
"log",
"(",
"'Published to \\''",
"+",
"chalk",
".",
"cyan",
"(",
"'npm'",
")",
"+",
"'\\''",
")",
";",
"}",
"resolve",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Publish the current codebase to npm.
@return {Bluebird promise} - Resolves or rejects (with nothing) based on the status of the `git` commands. | [
"Publish",
"the",
"current",
"codebase",
"to",
"npm",
"."
]
| 9536354c2012097c77ca63f3ef6e0f394d3784e4 | https://github.com/justinhelmer/npm-publish-release/blob/9536354c2012097c77ca63f3ef6e0f394d3784e4/index.js#L168-L180 |
47,126 | justinhelmer/npm-publish-release | index.js | _spork | function _spork(command, args, resolve, reject) {
spork(command, args, {exit: false, quiet: true})
.on('exit:code', function(code) {
if (code === 0) {
resolve();
} else {
reject();
}
});
} | javascript | function _spork(command, args, resolve, reject) {
spork(command, args, {exit: false, quiet: true})
.on('exit:code', function(code) {
if (code === 0) {
resolve();
} else {
reject();
}
});
} | [
"function",
"_spork",
"(",
"command",
",",
"args",
",",
"resolve",
",",
"reject",
")",
"{",
"spork",
"(",
"command",
",",
"args",
",",
"{",
"exit",
":",
"false",
",",
"quiet",
":",
"true",
"}",
")",
".",
"on",
"(",
"'exit:code'",
",",
"function",
"(",
"code",
")",
"{",
"if",
"(",
"code",
"===",
"0",
")",
"{",
"resolve",
"(",
")",
";",
"}",
"else",
"{",
"reject",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Wrapper around spork to shorthand common behavior | [
"Wrapper",
"around",
"spork",
"to",
"shorthand",
"common",
"behavior"
]
| 9536354c2012097c77ca63f3ef6e0f394d3784e4 | https://github.com/justinhelmer/npm-publish-release/blob/9536354c2012097c77ca63f3ef6e0f394d3784e4/index.js#L204-L213 |
47,127 | edus44/express-deliver | lib/loader/main.js | wrapMethod | function wrapMethod(app,fn){
//Override original express method
return function(){
let args = Array.prototype.slice.call(arguments)
//Check if any middleware argument is a generator function
for( let i=0; i<args.length; i++ ){
//Wrap this if necessary
args[i] = controllerWrapper(args[i])
}
//Call original method handler
return fn.apply(app,args)
}
} | javascript | function wrapMethod(app,fn){
//Override original express method
return function(){
let args = Array.prototype.slice.call(arguments)
//Check if any middleware argument is a generator function
for( let i=0; i<args.length; i++ ){
//Wrap this if necessary
args[i] = controllerWrapper(args[i])
}
//Call original method handler
return fn.apply(app,args)
}
} | [
"function",
"wrapMethod",
"(",
"app",
",",
"fn",
")",
"{",
"//Override original express method",
"return",
"function",
"(",
")",
"{",
"let",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
"//Check if any middleware argument is a generator function",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"length",
";",
"i",
"++",
")",
"{",
"//Wrap this if necessary",
"args",
"[",
"i",
"]",
"=",
"controllerWrapper",
"(",
"args",
"[",
"i",
"]",
")",
"}",
"//Call original method handler",
"return",
"fn",
".",
"apply",
"(",
"app",
",",
"args",
")",
"}",
"}"
]
| Wrap an express method handler
@param {ExpressApp} app
@param {Function} fn
@returns {Function} | [
"Wrap",
"an",
"express",
"method",
"handler"
]
| 895abfaf2e5e48a00b4fef943dccaffcbf244780 | https://github.com/edus44/express-deliver/blob/895abfaf2e5e48a00b4fef943dccaffcbf244780/lib/loader/main.js#L69-L82 |
47,128 | chjj/rondo | lib/dom.js | function(el, deep) {
var sub = document.createElement(el.nodeName)
, attr = el.attributes
, i = attr.length;
while (i--) {
if (attr[i].nodeValue) {
sub.setAttribute(attr[i].name, attr[i].value);
}
}
if (el.namespaceURI) {
sub.namespaceURI = el.namespaceURI;
}
if (el.baseURI) {
sub.baseURI = el.baseURI;
}
if (deep) {
DOM.setContent(sub, DOM.getContent(el));
}
return clone;
} | javascript | function(el, deep) {
var sub = document.createElement(el.nodeName)
, attr = el.attributes
, i = attr.length;
while (i--) {
if (attr[i].nodeValue) {
sub.setAttribute(attr[i].name, attr[i].value);
}
}
if (el.namespaceURI) {
sub.namespaceURI = el.namespaceURI;
}
if (el.baseURI) {
sub.baseURI = el.baseURI;
}
if (deep) {
DOM.setContent(sub, DOM.getContent(el));
}
return clone;
} | [
"function",
"(",
"el",
",",
"deep",
")",
"{",
"var",
"sub",
"=",
"document",
".",
"createElement",
"(",
"el",
".",
"nodeName",
")",
",",
"attr",
"=",
"el",
".",
"attributes",
",",
"i",
"=",
"attr",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"{",
"if",
"(",
"attr",
"[",
"i",
"]",
".",
"nodeValue",
")",
"{",
"sub",
".",
"setAttribute",
"(",
"attr",
"[",
"i",
"]",
".",
"name",
",",
"attr",
"[",
"i",
"]",
".",
"value",
")",
";",
"}",
"}",
"if",
"(",
"el",
".",
"namespaceURI",
")",
"{",
"sub",
".",
"namespaceURI",
"=",
"el",
".",
"namespaceURI",
";",
"}",
"if",
"(",
"el",
".",
"baseURI",
")",
"{",
"sub",
".",
"baseURI",
"=",
"el",
".",
"baseURI",
";",
"}",
"if",
"(",
"deep",
")",
"{",
"DOM",
".",
"setContent",
"(",
"sub",
",",
"DOM",
".",
"getContent",
"(",
"el",
")",
")",
";",
"}",
"return",
"clone",
";",
"}"
]
| this gives a clean "userspace" clone with no events or data. .cloneNode is so damn buggy i dont even want to touch it. | [
"this",
"gives",
"a",
"clean",
"userspace",
"clone",
"with",
"no",
"events",
"or",
"data",
".",
".",
"cloneNode",
"is",
"so",
"damn",
"buggy",
"i",
"dont",
"even",
"want",
"to",
"touch",
"it",
"."
]
| 5a0643a2e4ce74e25240517e1cf423df5a188008 | https://github.com/chjj/rondo/blob/5a0643a2e4ce74e25240517e1cf423df5a188008/lib/dom.js#L380-L404 |
|
47,129 | chjj/rondo | lib/dom.js | function(el, sub) {
sub = normalize(sub);
DOM.removeAllListeners(el);
DOM.clearData(el);
DOM.clean(el);
//el.parentNode.replaceChild(sub, el);
el.parentNode.insertBefore(sub, el);
el.parentNode.removeChild(el);
return sub;
} | javascript | function(el, sub) {
sub = normalize(sub);
DOM.removeAllListeners(el);
DOM.clearData(el);
DOM.clean(el);
//el.parentNode.replaceChild(sub, el);
el.parentNode.insertBefore(sub, el);
el.parentNode.removeChild(el);
return sub;
} | [
"function",
"(",
"el",
",",
"sub",
")",
"{",
"sub",
"=",
"normalize",
"(",
"sub",
")",
";",
"DOM",
".",
"removeAllListeners",
"(",
"el",
")",
";",
"DOM",
".",
"clearData",
"(",
"el",
")",
";",
"DOM",
".",
"clean",
"(",
"el",
")",
";",
"//el.parentNode.replaceChild(sub, el);",
"el",
".",
"parentNode",
".",
"insertBefore",
"(",
"sub",
",",
"el",
")",
";",
"el",
".",
"parentNode",
".",
"removeChild",
"(",
"el",
")",
";",
"return",
"sub",
";",
"}"
]
| "replace this with that" | [
"replace",
"this",
"with",
"that"
]
| 5a0643a2e4ce74e25240517e1cf423df5a188008 | https://github.com/chjj/rondo/blob/5a0643a2e4ce74e25240517e1cf423df5a188008/lib/dom.js#L559-L571 |
|
47,130 | chjj/rondo | lib/dom.js | function(el, sub) {
sub = normalize(sub);
el.parentNode.insertBefore(sub, el);
return sub;
} | javascript | function(el, sub) {
sub = normalize(sub);
el.parentNode.insertBefore(sub, el);
return sub;
} | [
"function",
"(",
"el",
",",
"sub",
")",
"{",
"sub",
"=",
"normalize",
"(",
"sub",
")",
";",
"el",
".",
"parentNode",
".",
"insertBefore",
"(",
"sub",
",",
"el",
")",
";",
"return",
"sub",
";",
"}"
]
| "insert that before this" | [
"insert",
"that",
"before",
"this"
]
| 5a0643a2e4ce74e25240517e1cf423df5a188008 | https://github.com/chjj/rondo/blob/5a0643a2e4ce74e25240517e1cf423df5a188008/lib/dom.js#L576-L581 |
|
47,131 | quorrajs/Positron | lib/config/Repository.js | Repository | function Repository(loader, environment) {
/**
* The loader implementation.
*
* @var {FileLoader}
* @protected
*/
this.__loader = loader;
/**
* The current environment.
*
* @var {string}
* @protected
*/
this.__environment = environment;
/**
* All of the configuration items.
*
* @var {Array}
* @protected
*/
this.__items = [];
/**
* The after load callbacks for namespaces.
*
* @var {Array}
* @protected
*/
this.__afterLoad = [];
// call super class constructor
Repository.super_.call(this);
} | javascript | function Repository(loader, environment) {
/**
* The loader implementation.
*
* @var {FileLoader}
* @protected
*/
this.__loader = loader;
/**
* The current environment.
*
* @var {string}
* @protected
*/
this.__environment = environment;
/**
* All of the configuration items.
*
* @var {Array}
* @protected
*/
this.__items = [];
/**
* The after load callbacks for namespaces.
*
* @var {Array}
* @protected
*/
this.__afterLoad = [];
// call super class constructor
Repository.super_.call(this);
} | [
"function",
"Repository",
"(",
"loader",
",",
"environment",
")",
"{",
"/**\n * The loader implementation.\n *\n * @var {FileLoader}\n * @protected\n */",
"this",
".",
"__loader",
"=",
"loader",
";",
"/**\n * The current environment.\n *\n * @var {string}\n * @protected\n */",
"this",
".",
"__environment",
"=",
"environment",
";",
"/**\n * All of the configuration items.\n *\n * @var {Array}\n * @protected\n */",
"this",
".",
"__items",
"=",
"[",
"]",
";",
"/**\n * The after load callbacks for namespaces.\n *\n * @var {Array}\n * @protected\n */",
"this",
".",
"__afterLoad",
"=",
"[",
"]",
";",
"// call super class constructor",
"Repository",
".",
"super_",
".",
"call",
"(",
"this",
")",
";",
"}"
]
| Create a new configuration repository.
@param {FileLoader} loader
@param {string} environment
@inherits NamespacedItemResolver
@return void | [
"Create",
"a",
"new",
"configuration",
"repository",
"."
]
| a4bad5a5f581743d1885405c11ae26600fb957af | https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/config/Repository.js#L20-L57 |
47,132 | SamyPesse/parse-changelog | index.js | function() {
if (!version) return;
if (note) version.notes.push(note);
version.rawNote = normText(
_.chain(version.notes)
.map(function(note) {
return '* '+note.trim();
})
.value()
.join('\n')
);
version.notes = _.map(version.notes, normText);
changelog.versions.push(version);
note = "";
version = null;
} | javascript | function() {
if (!version) return;
if (note) version.notes.push(note);
version.rawNote = normText(
_.chain(version.notes)
.map(function(note) {
return '* '+note.trim();
})
.value()
.join('\n')
);
version.notes = _.map(version.notes, normText);
changelog.versions.push(version);
note = "";
version = null;
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"version",
")",
"return",
";",
"if",
"(",
"note",
")",
"version",
".",
"notes",
".",
"push",
"(",
"note",
")",
";",
"version",
".",
"rawNote",
"=",
"normText",
"(",
"_",
".",
"chain",
"(",
"version",
".",
"notes",
")",
".",
"map",
"(",
"function",
"(",
"note",
")",
"{",
"return",
"'* '",
"+",
"note",
".",
"trim",
"(",
")",
";",
"}",
")",
".",
"value",
"(",
")",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"version",
".",
"notes",
"=",
"_",
".",
"map",
"(",
"version",
".",
"notes",
",",
"normText",
")",
";",
"changelog",
".",
"versions",
".",
"push",
"(",
"version",
")",
";",
"note",
"=",
"\"\"",
";",
"version",
"=",
"null",
";",
"}"
]
| Push a new version and normalize notes | [
"Push",
"a",
"new",
"version",
"and",
"normalize",
"notes"
]
| 2c4f5fb0c9d265aa6e39bed60c7d01d867cf07db | https://github.com/SamyPesse/parse-changelog/blob/2c4f5fb0c9d265aa6e39bed60c7d01d867cf07db/index.js#L32-L49 |
|
47,133 | sdgluck/sw-register | index.js | register | function register (options, __mockSelf) {
var _self = __mockSelf || self
var navigator = _self.navigator
if (!('serviceWorker' in navigator)) {
return Promise.reject(new Error('Service Workers unsupported'))
}
var serviceWorker = navigator.serviceWorker.controller
return Promise.resolve()
.then(function () {
// Get existing service worker or get registration promise
if (serviceWorker) return serviceWorker
else if (!options) return navigator.serviceWorker.ready
})
.then(function (registration) {
if (registration) {
// Take this service worker that the registration returned
serviceWorker = registration
} else if (!registration && options) {
// No registration but we have options to register one
return navigator.serviceWorker
.register(options.url, options)
.then(function (registration) {
options.forceUpdate && registration.update()
})
} else if (!registration && !options) {
// No existing worker,
// no registration that returned one,
// no options to register one
throw new Error('no active service worker or configuration passed to install one')
}
})
.then(function () {
return serviceWorker
})
} | javascript | function register (options, __mockSelf) {
var _self = __mockSelf || self
var navigator = _self.navigator
if (!('serviceWorker' in navigator)) {
return Promise.reject(new Error('Service Workers unsupported'))
}
var serviceWorker = navigator.serviceWorker.controller
return Promise.resolve()
.then(function () {
// Get existing service worker or get registration promise
if (serviceWorker) return serviceWorker
else if (!options) return navigator.serviceWorker.ready
})
.then(function (registration) {
if (registration) {
// Take this service worker that the registration returned
serviceWorker = registration
} else if (!registration && options) {
// No registration but we have options to register one
return navigator.serviceWorker
.register(options.url, options)
.then(function (registration) {
options.forceUpdate && registration.update()
})
} else if (!registration && !options) {
// No existing worker,
// no registration that returned one,
// no options to register one
throw new Error('no active service worker or configuration passed to install one')
}
})
.then(function () {
return serviceWorker
})
} | [
"function",
"register",
"(",
"options",
",",
"__mockSelf",
")",
"{",
"var",
"_self",
"=",
"__mockSelf",
"||",
"self",
"var",
"navigator",
"=",
"_self",
".",
"navigator",
"if",
"(",
"!",
"(",
"'serviceWorker'",
"in",
"navigator",
")",
")",
"{",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'Service Workers unsupported'",
")",
")",
"}",
"var",
"serviceWorker",
"=",
"navigator",
".",
"serviceWorker",
".",
"controller",
"return",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"// Get existing service worker or get registration promise",
"if",
"(",
"serviceWorker",
")",
"return",
"serviceWorker",
"else",
"if",
"(",
"!",
"options",
")",
"return",
"navigator",
".",
"serviceWorker",
".",
"ready",
"}",
")",
".",
"then",
"(",
"function",
"(",
"registration",
")",
"{",
"if",
"(",
"registration",
")",
"{",
"// Take this service worker that the registration returned",
"serviceWorker",
"=",
"registration",
"}",
"else",
"if",
"(",
"!",
"registration",
"&&",
"options",
")",
"{",
"// No registration but we have options to register one",
"return",
"navigator",
".",
"serviceWorker",
".",
"register",
"(",
"options",
".",
"url",
",",
"options",
")",
".",
"then",
"(",
"function",
"(",
"registration",
")",
"{",
"options",
".",
"forceUpdate",
"&&",
"registration",
".",
"update",
"(",
")",
"}",
")",
"}",
"else",
"if",
"(",
"!",
"registration",
"&&",
"!",
"options",
")",
"{",
"// No existing worker,",
"// no registration that returned one,",
"// no options to register one",
"throw",
"new",
"Error",
"(",
"'no active service worker or configuration passed to install one'",
")",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"serviceWorker",
"}",
")",
"}"
]
| Register or retrieve a Service Worker that controls the page.
@param {Object} options
@returns {Promise} | [
"Register",
"or",
"retrieve",
"a",
"Service",
"Worker",
"that",
"controls",
"the",
"page",
"."
]
| 294873c5d3c0a7df143401e5f14de51e2771704d | https://github.com/sdgluck/sw-register/blob/294873c5d3c0a7df143401e5f14de51e2771704d/index.js#L18-L55 |
47,134 | agneta/platform | pages/scripts/helpers/debug.js | inspectObject | function inspectObject(object, options) {
var result = util.inspect(object, options);
console.log(result);
return result;
} | javascript | function inspectObject(object, options) {
var result = util.inspect(object, options);
console.log(result);
return result;
} | [
"function",
"inspectObject",
"(",
"object",
",",
"options",
")",
"{",
"var",
"result",
"=",
"util",
".",
"inspect",
"(",
"object",
",",
"options",
")",
";",
"console",
".",
"log",
"(",
"result",
")",
";",
"return",
"result",
";",
"}"
]
| this solves circular reference in object | [
"this",
"solves",
"circular",
"reference",
"in",
"object"
]
| 9364b03b06b91b64f786d0439a32b08bb018606f | https://github.com/agneta/platform/blob/9364b03b06b91b64f786d0439a32b08bb018606f/pages/scripts/helpers/debug.js#L24-L28 |
47,135 | arboleya/ways | lib/ways.js | Ways | function Ways(pattern, runner, destroyer, dependency){
if(flow && arguments.length < 3)
throw new Error('In `flow` mode you must to pass at least 3 args.');
var route = new Way(pattern, runner, destroyer, dependency);
routes.push(route);
return route;
} | javascript | function Ways(pattern, runner, destroyer, dependency){
if(flow && arguments.length < 3)
throw new Error('In `flow` mode you must to pass at least 3 args.');
var route = new Way(pattern, runner, destroyer, dependency);
routes.push(route);
return route;
} | [
"function",
"Ways",
"(",
"pattern",
",",
"runner",
",",
"destroyer",
",",
"dependency",
")",
"{",
"if",
"(",
"flow",
"&&",
"arguments",
".",
"length",
"<",
"3",
")",
"throw",
"new",
"Error",
"(",
"'In `flow` mode you must to pass at least 3 args.'",
")",
";",
"var",
"route",
"=",
"new",
"Way",
"(",
"pattern",
",",
"runner",
",",
"destroyer",
",",
"dependency",
")",
";",
"routes",
".",
"push",
"(",
"route",
")",
";",
"return",
"route",
";",
"}"
]
| Sets up a new route
@param {String} pattern Pattern string
@param {Function} runner Route's action runner
@param {Function} destroyer Optional, Route's action destroyer (flow mode)
@param {String} dependency Optional, specifies a dependency by pattern | [
"Sets",
"up",
"a",
"new",
"route"
]
| 01a91066de320aa045a5301b2a905ba5f8f141f4 | https://github.com/arboleya/ways/blob/01a91066de320aa045a5301b2a905ba5f8f141f4/lib/ways.js#L38-L47 |
47,136 | feedhenry-raincatcher/raincatcher-angularjs | packages/angularjs-workorder/lib/workorder-detail/workorder-detail-controller.js | WorkorderDetailController | function WorkorderDetailController($state, WORKORDER_CONFIG, workorderStatusService) {
var self = this;
self.adminMode = WORKORDER_CONFIG.adminMode;
self.getColorIcon = function(status) {
return workorderStatusService.getStatusIconColor(status).statusColor;
};
} | javascript | function WorkorderDetailController($state, WORKORDER_CONFIG, workorderStatusService) {
var self = this;
self.adminMode = WORKORDER_CONFIG.adminMode;
self.getColorIcon = function(status) {
return workorderStatusService.getStatusIconColor(status).statusColor;
};
} | [
"function",
"WorkorderDetailController",
"(",
"$state",
",",
"WORKORDER_CONFIG",
",",
"workorderStatusService",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"adminMode",
"=",
"WORKORDER_CONFIG",
".",
"adminMode",
";",
"self",
".",
"getColorIcon",
"=",
"function",
"(",
"status",
")",
"{",
"return",
"workorderStatusService",
".",
"getStatusIconColor",
"(",
"status",
")",
".",
"statusColor",
";",
"}",
";",
"}"
]
| Controller for displaying workorder details to the user.
@param WORKORDER_CONFIG
@constructor | [
"Controller",
"for",
"displaying",
"workorder",
"details",
"to",
"the",
"user",
"."
]
| b394689227901e18871ad9edd0ec226c5e6839e1 | https://github.com/feedhenry-raincatcher/raincatcher-angularjs/blob/b394689227901e18871ad9edd0ec226c5e6839e1/packages/angularjs-workorder/lib/workorder-detail/workorder-detail-controller.js#L9-L17 |
47,137 | jiridudekusy/uu5-to-markdown | src/converters/md2uu5/richText/richText.js | richtext | function richtext(state, startLine, endLine, silent, opts) {
let pos = state.bMarks[startLine] + state.tShift[startLine],
max = state.eMarks[startLine],
contentEndLine;
if (pos >= max) {
return false;
}
let line = state.getLines(startLine, startLine + 1, 0, false);
if (!line.startsWith(RICHTEXT_OPEN_MARKER)) {
return false;
}
if (silent) {
return true;
}
let nextLine = startLine + 1;
let content = "";
for (; nextLine < endLine; nextLine++) {
let line = state.getLines(nextLine, nextLine + 1, 0, false);
if (line.trim() === RICHTEXT_CLOSE_MARKER) {
contentEndLine = nextLine - 1;
break;
}
content += line + "\n";
}
state.line = contentEndLine + 2;
// convert md subcontent to uu5string
let uu5content = opts.markdownToUu5.render(content, state.env);
state.tokens.push({
type: "UU5.RichText.Block",
uu5string: uu5content
});
return true;
} | javascript | function richtext(state, startLine, endLine, silent, opts) {
let pos = state.bMarks[startLine] + state.tShift[startLine],
max = state.eMarks[startLine],
contentEndLine;
if (pos >= max) {
return false;
}
let line = state.getLines(startLine, startLine + 1, 0, false);
if (!line.startsWith(RICHTEXT_OPEN_MARKER)) {
return false;
}
if (silent) {
return true;
}
let nextLine = startLine + 1;
let content = "";
for (; nextLine < endLine; nextLine++) {
let line = state.getLines(nextLine, nextLine + 1, 0, false);
if (line.trim() === RICHTEXT_CLOSE_MARKER) {
contentEndLine = nextLine - 1;
break;
}
content += line + "\n";
}
state.line = contentEndLine + 2;
// convert md subcontent to uu5string
let uu5content = opts.markdownToUu5.render(content, state.env);
state.tokens.push({
type: "UU5.RichText.Block",
uu5string: uu5content
});
return true;
} | [
"function",
"richtext",
"(",
"state",
",",
"startLine",
",",
"endLine",
",",
"silent",
",",
"opts",
")",
"{",
"let",
"pos",
"=",
"state",
".",
"bMarks",
"[",
"startLine",
"]",
"+",
"state",
".",
"tShift",
"[",
"startLine",
"]",
",",
"max",
"=",
"state",
".",
"eMarks",
"[",
"startLine",
"]",
",",
"contentEndLine",
";",
"if",
"(",
"pos",
">=",
"max",
")",
"{",
"return",
"false",
";",
"}",
"let",
"line",
"=",
"state",
".",
"getLines",
"(",
"startLine",
",",
"startLine",
"+",
"1",
",",
"0",
",",
"false",
")",
";",
"if",
"(",
"!",
"line",
".",
"startsWith",
"(",
"RICHTEXT_OPEN_MARKER",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"silent",
")",
"{",
"return",
"true",
";",
"}",
"let",
"nextLine",
"=",
"startLine",
"+",
"1",
";",
"let",
"content",
"=",
"\"\"",
";",
"for",
"(",
";",
"nextLine",
"<",
"endLine",
";",
"nextLine",
"++",
")",
"{",
"let",
"line",
"=",
"state",
".",
"getLines",
"(",
"nextLine",
",",
"nextLine",
"+",
"1",
",",
"0",
",",
"false",
")",
";",
"if",
"(",
"line",
".",
"trim",
"(",
")",
"===",
"RICHTEXT_CLOSE_MARKER",
")",
"{",
"contentEndLine",
"=",
"nextLine",
"-",
"1",
";",
"break",
";",
"}",
"content",
"+=",
"line",
"+",
"\"\\n\"",
";",
"}",
"state",
".",
"line",
"=",
"contentEndLine",
"+",
"2",
";",
"// convert md subcontent to uu5string",
"let",
"uu5content",
"=",
"opts",
".",
"markdownToUu5",
".",
"render",
"(",
"content",
",",
"state",
".",
"env",
")",
";",
"state",
".",
"tokens",
".",
"push",
"(",
"{",
"type",
":",
"\"UU5.RichText.Block\"",
",",
"uu5string",
":",
"uu5content",
"}",
")",
";",
"return",
"true",
";",
"}"
]
| Block parser for UU5.RichText.Block .
The rich text block is using following signature:
{richtext}
...richtext content...
{/richtext}
@param state
@param startLine
@param endLine
@param silent
@returns {boolean} | [
"Block",
"parser",
"for",
"UU5",
".",
"RichText",
".",
"Block",
"."
]
| 559163aa8a4184e1a94888c4fc6d4302acbd857d | https://github.com/jiridudekusy/uu5-to-markdown/blob/559163aa8a4184e1a94888c4fc6d4302acbd857d/src/converters/md2uu5/richText/richText.js#L20-L62 |
47,138 | fti-technology/node-skytap | lib/rest.js | apiRequest | function apiRequest(args, next) {
var deferred = Q.defer()
, opts;
opts = {
json: true,
headers: headers,
};
if(args.version === 'v2') {
opts.headers.Accept = 'application/vnd.skytap.api.v2+json';
}
opts = arghelper.combine(opts, args);
opts = arghelper.convertAuth(opts);
opts = arghelper.convertUrlParams(opts);
opts = arghelper.convertReqParams(opts);
debug('apiRequest: %j', opts);
// check for valid required arguments
if(!(opts.url && opts.method && opts.auth && opts.auth.user && opts.auth.pass)) {
var error = new Error('url, method, auth.user, and auth.pass are required arguments');
deferred.reject(error);
if(next) return next(error);
}
// make the request
request(opts, function(err, res, data) {
// handle exception
if(err) {
deferred.reject(err);
if(next) next(err);
}
// handle non-200 response
else if (res.statusCode !== 200) {
deferred.reject(data);
if(next) next(data);
}
// handle success
else {
deferred.resolve(data);
if(next) next(null, data);
}
});
return deferred.promise;
} | javascript | function apiRequest(args, next) {
var deferred = Q.defer()
, opts;
opts = {
json: true,
headers: headers,
};
if(args.version === 'v2') {
opts.headers.Accept = 'application/vnd.skytap.api.v2+json';
}
opts = arghelper.combine(opts, args);
opts = arghelper.convertAuth(opts);
opts = arghelper.convertUrlParams(opts);
opts = arghelper.convertReqParams(opts);
debug('apiRequest: %j', opts);
// check for valid required arguments
if(!(opts.url && opts.method && opts.auth && opts.auth.user && opts.auth.pass)) {
var error = new Error('url, method, auth.user, and auth.pass are required arguments');
deferred.reject(error);
if(next) return next(error);
}
// make the request
request(opts, function(err, res, data) {
// handle exception
if(err) {
deferred.reject(err);
if(next) next(err);
}
// handle non-200 response
else if (res.statusCode !== 200) {
deferred.reject(data);
if(next) next(data);
}
// handle success
else {
deferred.resolve(data);
if(next) next(null, data);
}
});
return deferred.promise;
} | [
"function",
"apiRequest",
"(",
"args",
",",
"next",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
",",
"opts",
";",
"opts",
"=",
"{",
"json",
":",
"true",
",",
"headers",
":",
"headers",
",",
"}",
";",
"if",
"(",
"args",
".",
"version",
"===",
"'v2'",
")",
"{",
"opts",
".",
"headers",
".",
"Accept",
"=",
"'application/vnd.skytap.api.v2+json'",
";",
"}",
"opts",
"=",
"arghelper",
".",
"combine",
"(",
"opts",
",",
"args",
")",
";",
"opts",
"=",
"arghelper",
".",
"convertAuth",
"(",
"opts",
")",
";",
"opts",
"=",
"arghelper",
".",
"convertUrlParams",
"(",
"opts",
")",
";",
"opts",
"=",
"arghelper",
".",
"convertReqParams",
"(",
"opts",
")",
";",
"debug",
"(",
"'apiRequest: %j'",
",",
"opts",
")",
";",
"// check for valid required arguments\r",
"if",
"(",
"!",
"(",
"opts",
".",
"url",
"&&",
"opts",
".",
"method",
"&&",
"opts",
".",
"auth",
"&&",
"opts",
".",
"auth",
".",
"user",
"&&",
"opts",
".",
"auth",
".",
"pass",
")",
")",
"{",
"var",
"error",
"=",
"new",
"Error",
"(",
"'url, method, auth.user, and auth.pass are required arguments'",
")",
";",
"deferred",
".",
"reject",
"(",
"error",
")",
";",
"if",
"(",
"next",
")",
"return",
"next",
"(",
"error",
")",
";",
"}",
"// make the request\r",
"request",
"(",
"opts",
",",
"function",
"(",
"err",
",",
"res",
",",
"data",
")",
"{",
"// handle exception\r",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"if",
"(",
"next",
")",
"next",
"(",
"err",
")",
";",
"}",
"// handle non-200 response \r",
"else",
"if",
"(",
"res",
".",
"statusCode",
"!==",
"200",
")",
"{",
"deferred",
".",
"reject",
"(",
"data",
")",
";",
"if",
"(",
"next",
")",
"next",
"(",
"data",
")",
";",
"}",
"// handle success\r",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"data",
")",
";",
"if",
"(",
"next",
")",
"next",
"(",
"null",
",",
"data",
")",
";",
"}",
"}",
")",
";",
"return",
"deferred",
".",
"promise",
";",
"}"
]
| Performs the api request based on the supplied arguments
@param {Object} args
@config {String} url - required
@config {String} method - required
@config {Object} auth - required
@config {String} auth.user - required
@config {String} auth.pass - required
@config {Object} body
@callback next
@return {Promise}
@api private | [
"Performs",
"the",
"api",
"request",
"based",
"on",
"the",
"supplied",
"arguments"
]
| 1d5af43ee26aabfebe52627ea09f291c99923a49 | https://github.com/fti-technology/node-skytap/blob/1d5af43ee26aabfebe52627ea09f291c99923a49/lib/rest.js#L47-L100 |
47,139 | alexyoung/pop | lib/helpers.js | function(template, options) {
options = options || {};
options.pretty = true;
var fn = jade.compile(template, options);
return fn(options.locals);
} | javascript | function(template, options) {
options = options || {};
options.pretty = true;
var fn = jade.compile(template, options);
return fn(options.locals);
} | [
"function",
"(",
"template",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"pretty",
"=",
"true",
";",
"var",
"fn",
"=",
"jade",
".",
"compile",
"(",
"template",
",",
"options",
")",
";",
"return",
"fn",
"(",
"options",
".",
"locals",
")",
";",
"}"
]
| Renders a Jade template
@param {String} A Jade template
@param {Object} Options passed to Jade
@return {String} | [
"Renders",
"a",
"Jade",
"template"
]
| 8a0b3f2605cb58e8ae6b34f1373dde00610e9858 | https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/helpers.js#L25-L30 |
|
47,140 | alexyoung/pop | lib/helpers.js | function(paginator) {
var template = '';
template += '.pages\n';
template += ' - if (paginator.previousPage)\n';
template += ' span.prev_next\n';
template += ' - if (paginator.previousPage === 1)\n';
template += ' span ←\n';
template += ' a.previous(href="/") Previous\n';
template += ' - else\n';
template += ' span ←\n';
template += ' a.previous(href="/page" + paginator.previousPage + "/") Previous\n';
template += ' - if (paginator.pages > 1)\n';
template += ' span.prev_next\n';
template += ' - for (var i = 1; i <= paginator.pages; i++)\n';
template += ' - if (i === paginator.page)\n';
template += ' strong.page #{i}\n';
template += ' - else if (i !== 1)\n';
template += ' a.page(href="/page" + i + "/") #{i}\n';
template += ' - else\n';
template += ' a.page(href="/") 1\n';
template += ' - if (paginator.nextPage <= paginator.pages)\n';
template += ' a.next(href="/page" + paginator.nextPage + "/") Next\n';
template += ' span →\n';
return helpers.render(template, { locals: { paginator: paginator } });
} | javascript | function(paginator) {
var template = '';
template += '.pages\n';
template += ' - if (paginator.previousPage)\n';
template += ' span.prev_next\n';
template += ' - if (paginator.previousPage === 1)\n';
template += ' span ←\n';
template += ' a.previous(href="/") Previous\n';
template += ' - else\n';
template += ' span ←\n';
template += ' a.previous(href="/page" + paginator.previousPage + "/") Previous\n';
template += ' - if (paginator.pages > 1)\n';
template += ' span.prev_next\n';
template += ' - for (var i = 1; i <= paginator.pages; i++)\n';
template += ' - if (i === paginator.page)\n';
template += ' strong.page #{i}\n';
template += ' - else if (i !== 1)\n';
template += ' a.page(href="/page" + i + "/") #{i}\n';
template += ' - else\n';
template += ' a.page(href="/") 1\n';
template += ' - if (paginator.nextPage <= paginator.pages)\n';
template += ' a.next(href="/page" + paginator.nextPage + "/") Next\n';
template += ' span →\n';
return helpers.render(template, { locals: { paginator: paginator } });
} | [
"function",
"(",
"paginator",
")",
"{",
"var",
"template",
"=",
"''",
";",
"template",
"+=",
"'.pages\\n'",
";",
"template",
"+=",
"' - if (paginator.previousPage)\\n'",
";",
"template",
"+=",
"' span.prev_next\\n'",
";",
"template",
"+=",
"' - if (paginator.previousPage === 1)\\n'",
";",
"template",
"+=",
"' span ←\\n'",
";",
"template",
"+=",
"' a.previous(href=\"/\") Previous\\n'",
";",
"template",
"+=",
"' - else\\n'",
";",
"template",
"+=",
"' span ←\\n'",
";",
"template",
"+=",
"' a.previous(href=\"/page\" + paginator.previousPage + \"/\") Previous\\n'",
";",
"template",
"+=",
"' - if (paginator.pages > 1)\\n'",
";",
"template",
"+=",
"' span.prev_next\\n'",
";",
"template",
"+=",
"' - for (var i = 1; i <= paginator.pages; i++)\\n'",
";",
"template",
"+=",
"' - if (i === paginator.page)\\n'",
";",
"template",
"+=",
"' strong.page #{i}\\n'",
";",
"template",
"+=",
"' - else if (i !== 1)\\n'",
";",
"template",
"+=",
"' a.page(href=\"/page\" + i + \"/\") #{i}\\n'",
";",
"template",
"+=",
"' - else\\n'",
";",
"template",
"+=",
"' a.page(href=\"/\") 1\\n'",
";",
"template",
"+=",
"' - if (paginator.nextPage <= paginator.pages)\\n'",
";",
"template",
"+=",
"' a.next(href=\"/page\" + paginator.nextPage + \"/\") Next\\n'",
";",
"template",
"+=",
"' span →\\n'",
";",
"return",
"helpers",
".",
"render",
"(",
"template",
",",
"{",
"locals",
":",
"{",
"paginator",
":",
"paginator",
"}",
"}",
")",
";",
"}"
]
| Pagination links.
@param {Object} Paginator object
@return {String} | [
"Pagination",
"links",
"."
]
| 8a0b3f2605cb58e8ae6b34f1373dde00610e9858 | https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/helpers.js#L38-L62 |
|
47,141 | alexyoung/pop | lib/helpers.js | function() {
var template
, site = this;
template = ''
+ '- for (var i = 0; i < paginator.items.length; i++)\n'
+ ' !{hNews(paginator.items[i], true)}\n';
return helpers.render(template, { locals: site.applyHelpers({ paginator: site.paginator }) });
} | javascript | function() {
var template
, site = this;
template = ''
+ '- for (var i = 0; i < paginator.items.length; i++)\n'
+ ' !{hNews(paginator.items[i], true)}\n';
return helpers.render(template, { locals: site.applyHelpers({ paginator: site.paginator }) });
} | [
"function",
"(",
")",
"{",
"var",
"template",
",",
"site",
"=",
"this",
";",
"template",
"=",
"''",
"+",
"'- for (var i = 0; i < paginator.items.length; i++)\\n'",
"+",
"' !{hNews(paginator.items[i], true)}\\n'",
";",
"return",
"helpers",
".",
"render",
"(",
"template",
",",
"{",
"locals",
":",
"site",
".",
"applyHelpers",
"(",
"{",
"paginator",
":",
"site",
".",
"paginator",
"}",
")",
"}",
")",
";",
"}"
]
| Generates paginated blog posts, suitable for use on an index page.
@return {String} | [
"Generates",
"paginated",
"blog",
"posts",
"suitable",
"for",
"use",
"on",
"an",
"index",
"page",
"."
]
| 8a0b3f2605cb58e8ae6b34f1373dde00610e9858 | https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/helpers.js#L69-L77 |
|
47,142 | alexyoung/pop | lib/helpers.js | function(feed, summarise) {
var template = ''
, url = this.config.url
, title = this.config.title
, perPage = this.config.perPage
, posts = this.posts.slice(0, perPage)
, site = this;
summarise = typeof summarise === 'boolean' && summarise ? 3 : summarise;
perPage = site.posts.length < perPage ? site.posts.length : perPage;
template += '!!!xml\n';
template += 'feed(xmlns="http://www.w3.org/2005/Atom")\n';
template += ' title #{title}\n';
template += ' link(href=feed, rel="self")\n';
template += ' link(href=url)\n';
if (posts.length > 0)
template += ' updated #{dx(posts[0].date)}\n';
template += ' id #{url}\n';
template += ' author\n';
template += ' name #{title}\n';
template += ' - for (var i = 0, post = posts[i]; i < ' + perPage + '; i++, post = posts[i])\n';
template += ' entry\n';
template += ' title #{post.title}\n';
template += ' link(href=url + post.url)\n';
template += ' updated #{dx(post.date)}\n';
template += ' id #{url.replace(/\\/$/, "")}#{post.url}\n';
if (summarise)
template += ' content(type="html") !{h(truncateParagraphs(post.content, summarise, ""))}\n';
else
template += ' content(type="html") !{h(post.content)}\n';
return helpers.render(template, { locals: site.applyHelpers({
paginator: site.paginator
, posts: posts
, title: title
, url: url
, feed: feed
, summarise: summarise
})});
} | javascript | function(feed, summarise) {
var template = ''
, url = this.config.url
, title = this.config.title
, perPage = this.config.perPage
, posts = this.posts.slice(0, perPage)
, site = this;
summarise = typeof summarise === 'boolean' && summarise ? 3 : summarise;
perPage = site.posts.length < perPage ? site.posts.length : perPage;
template += '!!!xml\n';
template += 'feed(xmlns="http://www.w3.org/2005/Atom")\n';
template += ' title #{title}\n';
template += ' link(href=feed, rel="self")\n';
template += ' link(href=url)\n';
if (posts.length > 0)
template += ' updated #{dx(posts[0].date)}\n';
template += ' id #{url}\n';
template += ' author\n';
template += ' name #{title}\n';
template += ' - for (var i = 0, post = posts[i]; i < ' + perPage + '; i++, post = posts[i])\n';
template += ' entry\n';
template += ' title #{post.title}\n';
template += ' link(href=url + post.url)\n';
template += ' updated #{dx(post.date)}\n';
template += ' id #{url.replace(/\\/$/, "")}#{post.url}\n';
if (summarise)
template += ' content(type="html") !{h(truncateParagraphs(post.content, summarise, ""))}\n';
else
template += ' content(type="html") !{h(post.content)}\n';
return helpers.render(template, { locals: site.applyHelpers({
paginator: site.paginator
, posts: posts
, title: title
, url: url
, feed: feed
, summarise: summarise
})});
} | [
"function",
"(",
"feed",
",",
"summarise",
")",
"{",
"var",
"template",
"=",
"''",
",",
"url",
"=",
"this",
".",
"config",
".",
"url",
",",
"title",
"=",
"this",
".",
"config",
".",
"title",
",",
"perPage",
"=",
"this",
".",
"config",
".",
"perPage",
",",
"posts",
"=",
"this",
".",
"posts",
".",
"slice",
"(",
"0",
",",
"perPage",
")",
",",
"site",
"=",
"this",
";",
"summarise",
"=",
"typeof",
"summarise",
"===",
"'boolean'",
"&&",
"summarise",
"?",
"3",
":",
"summarise",
";",
"perPage",
"=",
"site",
".",
"posts",
".",
"length",
"<",
"perPage",
"?",
"site",
".",
"posts",
".",
"length",
":",
"perPage",
";",
"template",
"+=",
"'!!!xml\\n'",
";",
"template",
"+=",
"'feed(xmlns=\"http://www.w3.org/2005/Atom\")\\n'",
";",
"template",
"+=",
"' title #{title}\\n'",
";",
"template",
"+=",
"' link(href=feed, rel=\"self\")\\n'",
";",
"template",
"+=",
"' link(href=url)\\n'",
";",
"if",
"(",
"posts",
".",
"length",
">",
"0",
")",
"template",
"+=",
"' updated #{dx(posts[0].date)}\\n'",
";",
"template",
"+=",
"' id #{url}\\n'",
";",
"template",
"+=",
"' author\\n'",
";",
"template",
"+=",
"' name #{title}\\n'",
";",
"template",
"+=",
"' - for (var i = 0, post = posts[i]; i < '",
"+",
"perPage",
"+",
"'; i++, post = posts[i])\\n'",
";",
"template",
"+=",
"' entry\\n'",
";",
"template",
"+=",
"' title #{post.title}\\n'",
";",
"template",
"+=",
"' link(href=url + post.url)\\n'",
";",
"template",
"+=",
"' updated #{dx(post.date)}\\n'",
";",
"template",
"+=",
"' id #{url.replace(/\\\\/$/, \"\")}#{post.url}\\n'",
";",
"if",
"(",
"summarise",
")",
"template",
"+=",
"' content(type=\"html\") !{h(truncateParagraphs(post.content, summarise, \"\"))}\\n'",
";",
"else",
"template",
"+=",
"' content(type=\"html\") !{h(post.content)}\\n'",
";",
"return",
"helpers",
".",
"render",
"(",
"template",
",",
"{",
"locals",
":",
"site",
".",
"applyHelpers",
"(",
"{",
"paginator",
":",
"site",
".",
"paginator",
",",
"posts",
":",
"posts",
",",
"title",
":",
"title",
",",
"url",
":",
"url",
",",
"feed",
":",
"feed",
",",
"summarise",
":",
"summarise",
"}",
")",
"}",
")",
";",
"}"
]
| Atom Jade template.
@param {String} Feed URL
@param {Integer} Number of paragraphs to summarise
@return {String} | [
"Atom",
"Jade",
"template",
"."
]
| 8a0b3f2605cb58e8ae6b34f1373dde00610e9858 | https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/helpers.js#L87-L130 |
|
47,143 | alexyoung/pop | lib/helpers.js | function() {
var allTags = [];
for (var key in this.posts) {
if (this.posts[key].tags) {
for (var i = 0; i < this.posts[key].tags.length; i++) {
var tag = this.posts[key].tags[i];
if (allTags.indexOf(tag) === -1) allTags.push(tag);
}
}
}
allTags.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
return allTags;
} | javascript | function() {
var allTags = [];
for (var key in this.posts) {
if (this.posts[key].tags) {
for (var i = 0; i < this.posts[key].tags.length; i++) {
var tag = this.posts[key].tags[i];
if (allTags.indexOf(tag) === -1) allTags.push(tag);
}
}
}
allTags.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
return allTags;
} | [
"function",
"(",
")",
"{",
"var",
"allTags",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"this",
".",
"posts",
")",
"{",
"if",
"(",
"this",
".",
"posts",
"[",
"key",
"]",
".",
"tags",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"posts",
"[",
"key",
"]",
".",
"tags",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"tag",
"=",
"this",
".",
"posts",
"[",
"key",
"]",
".",
"tags",
"[",
"i",
"]",
";",
"if",
"(",
"allTags",
".",
"indexOf",
"(",
"tag",
")",
"===",
"-",
"1",
")",
"allTags",
".",
"push",
"(",
"tag",
")",
";",
"}",
"}",
"}",
"allTags",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"a",
"=",
"a",
".",
"toLowerCase",
"(",
")",
";",
"b",
"=",
"b",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"a",
"<",
"b",
")",
"return",
"-",
"1",
";",
"if",
"(",
"a",
">",
"b",
")",
"return",
"1",
";",
"return",
"0",
";",
"}",
")",
";",
"return",
"allTags",
";",
"}"
]
| Returns unique sorted tags for every post.
@return {Array} | [
"Returns",
"unique",
"sorted",
"tags",
"for",
"every",
"post",
"."
]
| 8a0b3f2605cb58e8ae6b34f1373dde00610e9858 | https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/helpers.js#L196-L217 |
|
47,144 | alexyoung/pop | lib/helpers.js | function(tag) {
var posts = [];
for (var key in this.posts) {
if (this.posts[key].tags && this.posts[key].tags.indexOf(tag) !== -1) {
posts.push(this.posts[key]);
}
}
return posts;
} | javascript | function(tag) {
var posts = [];
for (var key in this.posts) {
if (this.posts[key].tags && this.posts[key].tags.indexOf(tag) !== -1) {
posts.push(this.posts[key]);
}
}
return posts;
} | [
"function",
"(",
"tag",
")",
"{",
"var",
"posts",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"key",
"in",
"this",
".",
"posts",
")",
"{",
"if",
"(",
"this",
".",
"posts",
"[",
"key",
"]",
".",
"tags",
"&&",
"this",
".",
"posts",
"[",
"key",
"]",
".",
"tags",
".",
"indexOf",
"(",
"tag",
")",
"!==",
"-",
"1",
")",
"{",
"posts",
".",
"push",
"(",
"this",
".",
"posts",
"[",
"key",
"]",
")",
";",
"}",
"}",
"return",
"posts",
";",
"}"
]
| Get a set of posts for a tag.
@param {String} Tag name
@return {Array} | [
"Get",
"a",
"set",
"of",
"posts",
"for",
"a",
"tag",
"."
]
| 8a0b3f2605cb58e8ae6b34f1373dde00610e9858 | https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/helpers.js#L225-L233 |
|
47,145 | alexyoung/pop | lib/helpers.js | function(text, length, moreText) {
var t = text.split('</p>');
return t.length < length ? text : t.slice(0, length).join('</p>') + '</p>' + moreText;
} | javascript | function(text, length, moreText) {
var t = text.split('</p>');
return t.length < length ? text : t.slice(0, length).join('</p>') + '</p>' + moreText;
} | [
"function",
"(",
"text",
",",
"length",
",",
"moreText",
")",
"{",
"var",
"t",
"=",
"text",
".",
"split",
"(",
"'</p>'",
")",
";",
"return",
"t",
".",
"length",
"<",
"length",
"?",
"text",
":",
"t",
".",
"slice",
"(",
"0",
",",
"length",
")",
".",
"join",
"(",
"'</p>'",
")",
"+",
"'</p>'",
"+",
"moreText",
";",
"}"
]
| Truncates HTML based on paragraph counts.
@param {String} Text to truncate
@param {Integer} Number of paragraphs
@param {String} Text to append when truncated
@return {String} | [
"Truncates",
"HTML",
"based",
"on",
"paragraph",
"counts",
"."
]
| 8a0b3f2605cb58e8ae6b34f1373dde00610e9858 | https://github.com/alexyoung/pop/blob/8a0b3f2605cb58e8ae6b34f1373dde00610e9858/lib/helpers.js#L341-L344 |
|
47,146 | parsnick/laravel-elixir-bowerbundle | index.js | function(paths) {
return (
gulp
.src(paths.src.path)
.pipe(rework(
reworkUrl(function (url) {
return isRelative(url) ? path.basename(url) : url;
})
))
.pipe($.if(config.sourcemaps, $.sourcemaps.init({ loadMaps: true })))
.pipe($.concat(paths.changeExtension(paths.output.name, '.css')))
.pipe($.if(config.production, $.cssnano(config.css.cssnano.pluginOptions)))
.pipe($.if(config.sourcemaps, $.sourcemaps.write('.')))
.pipe(gulp.dest(paths.output.baseDir))
);
} | javascript | function(paths) {
return (
gulp
.src(paths.src.path)
.pipe(rework(
reworkUrl(function (url) {
return isRelative(url) ? path.basename(url) : url;
})
))
.pipe($.if(config.sourcemaps, $.sourcemaps.init({ loadMaps: true })))
.pipe($.concat(paths.changeExtension(paths.output.name, '.css')))
.pipe($.if(config.production, $.cssnano(config.css.cssnano.pluginOptions)))
.pipe($.if(config.sourcemaps, $.sourcemaps.write('.')))
.pipe(gulp.dest(paths.output.baseDir))
);
} | [
"function",
"(",
"paths",
")",
"{",
"return",
"(",
"gulp",
".",
"src",
"(",
"paths",
".",
"src",
".",
"path",
")",
".",
"pipe",
"(",
"rework",
"(",
"reworkUrl",
"(",
"function",
"(",
"url",
")",
"{",
"return",
"isRelative",
"(",
"url",
")",
"?",
"path",
".",
"basename",
"(",
"url",
")",
":",
"url",
";",
"}",
")",
")",
")",
".",
"pipe",
"(",
"$",
".",
"if",
"(",
"config",
".",
"sourcemaps",
",",
"$",
".",
"sourcemaps",
".",
"init",
"(",
"{",
"loadMaps",
":",
"true",
"}",
")",
")",
")",
".",
"pipe",
"(",
"$",
".",
"concat",
"(",
"paths",
".",
"changeExtension",
"(",
"paths",
".",
"output",
".",
"name",
",",
"'.css'",
")",
")",
")",
".",
"pipe",
"(",
"$",
".",
"if",
"(",
"config",
".",
"production",
",",
"$",
".",
"cssnano",
"(",
"config",
".",
"css",
".",
"cssnano",
".",
"pluginOptions",
")",
")",
")",
".",
"pipe",
"(",
"$",
".",
"if",
"(",
"config",
".",
"sourcemaps",
",",
"$",
".",
"sourcemaps",
".",
"write",
"(",
"'.'",
")",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"paths",
".",
"output",
".",
"baseDir",
")",
")",
")",
";",
"}"
]
| Combine stylesheets.
@param {GulpPaths} paths
@return {stream} | [
"Combine",
"stylesheets",
"."
]
| f6e7df503b4abec1c721a8b56b508162f714dd71 | https://github.com/parsnick/laravel-elixir-bowerbundle/blob/f6e7df503b4abec1c721a8b56b508162f714dd71/index.js#L107-L122 |
|
47,147 | parsnick/laravel-elixir-bowerbundle | index.js | logMissingPackages | function logMissingPackages(bundle)
{
var missing = _(bundle.packages).reject('installed')
.map('name').uniq().value();
if ( ! missing.length) return;
console.log('')
console.log(
colors.black.bgRed('!!! ' + bundle.name + ' is missing ' + colors.bold(missing.length) + ' package(s)')
);
_.forEach(missing, function (name) {
console.log(' - ' + name);
});
console.log(' Try running ' + colors.cyan('bower install ' + missing.join(' ')));
console.log('');
} | javascript | function logMissingPackages(bundle)
{
var missing = _(bundle.packages).reject('installed')
.map('name').uniq().value();
if ( ! missing.length) return;
console.log('')
console.log(
colors.black.bgRed('!!! ' + bundle.name + ' is missing ' + colors.bold(missing.length) + ' package(s)')
);
_.forEach(missing, function (name) {
console.log(' - ' + name);
});
console.log(' Try running ' + colors.cyan('bower install ' + missing.join(' ')));
console.log('');
} | [
"function",
"logMissingPackages",
"(",
"bundle",
")",
"{",
"var",
"missing",
"=",
"_",
"(",
"bundle",
".",
"packages",
")",
".",
"reject",
"(",
"'installed'",
")",
".",
"map",
"(",
"'name'",
")",
".",
"uniq",
"(",
")",
".",
"value",
"(",
")",
";",
"if",
"(",
"!",
"missing",
".",
"length",
")",
"return",
";",
"console",
".",
"log",
"(",
"''",
")",
"console",
".",
"log",
"(",
"colors",
".",
"black",
".",
"bgRed",
"(",
"'!!! '",
"+",
"bundle",
".",
"name",
"+",
"' is missing '",
"+",
"colors",
".",
"bold",
"(",
"missing",
".",
"length",
")",
"+",
"' package(s)'",
")",
")",
";",
"_",
".",
"forEach",
"(",
"missing",
",",
"function",
"(",
"name",
")",
"{",
"console",
".",
"log",
"(",
"' - '",
"+",
"name",
")",
";",
"}",
")",
";",
"console",
".",
"log",
"(",
"' Try running '",
"+",
"colors",
".",
"cyan",
"(",
"'bower install '",
"+",
"missing",
".",
"join",
"(",
"' '",
")",
")",
")",
";",
"console",
".",
"log",
"(",
"''",
")",
";",
"}"
]
| Log to console any packages that were requested but not installed.
@param {Bundle} bundle | [
"Log",
"to",
"console",
"any",
"packages",
"that",
"were",
"requested",
"but",
"not",
"installed",
"."
]
| f6e7df503b4abec1c721a8b56b508162f714dd71 | https://github.com/parsnick/laravel-elixir-bowerbundle/blob/f6e7df503b4abec1c721a8b56b508162f714dd71/index.js#L193-L209 |
47,148 | goliney/coderoom | lib/coderoom.js | buildRooms | function buildRooms(baseRoom, dir, depth, attachments) {
depth++;
// group attachments
attachments = _.chain(attachments)
.clone()
.concat(baseRoom.getMedia(false).map(file => path.join('media', path.relative(commonFolder, file))))
.uniq()
.value();
baseRoom.items.forEach((room, i) => {
let itemPath = path.join(dir, i.toString());
fs.ensureDirSync(itemPath);
if (!room.hasFiles) {
buildRooms(room, itemPath, depth, attachments);
} else {
const roomsFiles = room.parsedFiles.map(file => {
file.destination = path.join(itemPath, 'files', file.parse.base);
file.content = fs.readFileSync(file.file, 'utf8');
file.mode = file.parse.ext.replace('.', '');
fs.copySync(file.file, file.destination);
return file;
});
// room attachments
attachments = _.chain(attachments)
.clone()
.concat(room.getMedia(false).map(file => path.join('media', path.relative(commonFolder, file))))
.uniq()
.value();
const css_paths = _.chain(attachments)
.concat(roomsFiles.map(file => path.relative(targetDir, file.destination)))
.filter(file => _.endsWith(file, '.css'))
.map(file => normalizePath(file, false))
.value();
const js_paths = _.chain(attachments)
.concat(roomsFiles.map(file => path.relative(targetDir, file.destination)))
.filter(file => _.endsWith(file, '.js'))
.map(file => normalizePath(file, false))
.value();
// iframe.html
fs.writeFileSync(
path.join(itemPath, 'iframe.html'),
handlebars.compile(iframe)({
depth,
css_paths,
js_paths,
html: roomsFiles[0],
})
);
// index.html
fs.writeFileSync(
path.join(itemPath, 'index.html'),
handlebars.compile(index)({
depth,
roomsFiles,
settings,
root,
room,
css_paths,
js_paths,
hasCSS: css_paths.length > 0,
hasJS: js_paths.length > 0,
})
);
}
});
} | javascript | function buildRooms(baseRoom, dir, depth, attachments) {
depth++;
// group attachments
attachments = _.chain(attachments)
.clone()
.concat(baseRoom.getMedia(false).map(file => path.join('media', path.relative(commonFolder, file))))
.uniq()
.value();
baseRoom.items.forEach((room, i) => {
let itemPath = path.join(dir, i.toString());
fs.ensureDirSync(itemPath);
if (!room.hasFiles) {
buildRooms(room, itemPath, depth, attachments);
} else {
const roomsFiles = room.parsedFiles.map(file => {
file.destination = path.join(itemPath, 'files', file.parse.base);
file.content = fs.readFileSync(file.file, 'utf8');
file.mode = file.parse.ext.replace('.', '');
fs.copySync(file.file, file.destination);
return file;
});
// room attachments
attachments = _.chain(attachments)
.clone()
.concat(room.getMedia(false).map(file => path.join('media', path.relative(commonFolder, file))))
.uniq()
.value();
const css_paths = _.chain(attachments)
.concat(roomsFiles.map(file => path.relative(targetDir, file.destination)))
.filter(file => _.endsWith(file, '.css'))
.map(file => normalizePath(file, false))
.value();
const js_paths = _.chain(attachments)
.concat(roomsFiles.map(file => path.relative(targetDir, file.destination)))
.filter(file => _.endsWith(file, '.js'))
.map(file => normalizePath(file, false))
.value();
// iframe.html
fs.writeFileSync(
path.join(itemPath, 'iframe.html'),
handlebars.compile(iframe)({
depth,
css_paths,
js_paths,
html: roomsFiles[0],
})
);
// index.html
fs.writeFileSync(
path.join(itemPath, 'index.html'),
handlebars.compile(index)({
depth,
roomsFiles,
settings,
root,
room,
css_paths,
js_paths,
hasCSS: css_paths.length > 0,
hasJS: js_paths.length > 0,
})
);
}
});
} | [
"function",
"buildRooms",
"(",
"baseRoom",
",",
"dir",
",",
"depth",
",",
"attachments",
")",
"{",
"depth",
"++",
";",
"// group attachments",
"attachments",
"=",
"_",
".",
"chain",
"(",
"attachments",
")",
".",
"clone",
"(",
")",
".",
"concat",
"(",
"baseRoom",
".",
"getMedia",
"(",
"false",
")",
".",
"map",
"(",
"file",
"=>",
"path",
".",
"join",
"(",
"'media'",
",",
"path",
".",
"relative",
"(",
"commonFolder",
",",
"file",
")",
")",
")",
")",
".",
"uniq",
"(",
")",
".",
"value",
"(",
")",
";",
"baseRoom",
".",
"items",
".",
"forEach",
"(",
"(",
"room",
",",
"i",
")",
"=>",
"{",
"let",
"itemPath",
"=",
"path",
".",
"join",
"(",
"dir",
",",
"i",
".",
"toString",
"(",
")",
")",
";",
"fs",
".",
"ensureDirSync",
"(",
"itemPath",
")",
";",
"if",
"(",
"!",
"room",
".",
"hasFiles",
")",
"{",
"buildRooms",
"(",
"room",
",",
"itemPath",
",",
"depth",
",",
"attachments",
")",
";",
"}",
"else",
"{",
"const",
"roomsFiles",
"=",
"room",
".",
"parsedFiles",
".",
"map",
"(",
"file",
"=>",
"{",
"file",
".",
"destination",
"=",
"path",
".",
"join",
"(",
"itemPath",
",",
"'files'",
",",
"file",
".",
"parse",
".",
"base",
")",
";",
"file",
".",
"content",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
".",
"file",
",",
"'utf8'",
")",
";",
"file",
".",
"mode",
"=",
"file",
".",
"parse",
".",
"ext",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
";",
"fs",
".",
"copySync",
"(",
"file",
".",
"file",
",",
"file",
".",
"destination",
")",
";",
"return",
"file",
";",
"}",
")",
";",
"// room attachments",
"attachments",
"=",
"_",
".",
"chain",
"(",
"attachments",
")",
".",
"clone",
"(",
")",
".",
"concat",
"(",
"room",
".",
"getMedia",
"(",
"false",
")",
".",
"map",
"(",
"file",
"=>",
"path",
".",
"join",
"(",
"'media'",
",",
"path",
".",
"relative",
"(",
"commonFolder",
",",
"file",
")",
")",
")",
")",
".",
"uniq",
"(",
")",
".",
"value",
"(",
")",
";",
"const",
"css_paths",
"=",
"_",
".",
"chain",
"(",
"attachments",
")",
".",
"concat",
"(",
"roomsFiles",
".",
"map",
"(",
"file",
"=>",
"path",
".",
"relative",
"(",
"targetDir",
",",
"file",
".",
"destination",
")",
")",
")",
".",
"filter",
"(",
"file",
"=>",
"_",
".",
"endsWith",
"(",
"file",
",",
"'.css'",
")",
")",
".",
"map",
"(",
"file",
"=>",
"normalizePath",
"(",
"file",
",",
"false",
")",
")",
".",
"value",
"(",
")",
";",
"const",
"js_paths",
"=",
"_",
".",
"chain",
"(",
"attachments",
")",
".",
"concat",
"(",
"roomsFiles",
".",
"map",
"(",
"file",
"=>",
"path",
".",
"relative",
"(",
"targetDir",
",",
"file",
".",
"destination",
")",
")",
")",
".",
"filter",
"(",
"file",
"=>",
"_",
".",
"endsWith",
"(",
"file",
",",
"'.js'",
")",
")",
".",
"map",
"(",
"file",
"=>",
"normalizePath",
"(",
"file",
",",
"false",
")",
")",
".",
"value",
"(",
")",
";",
"// iframe.html",
"fs",
".",
"writeFileSync",
"(",
"path",
".",
"join",
"(",
"itemPath",
",",
"'iframe.html'",
")",
",",
"handlebars",
".",
"compile",
"(",
"iframe",
")",
"(",
"{",
"depth",
",",
"css_paths",
",",
"js_paths",
",",
"html",
":",
"roomsFiles",
"[",
"0",
"]",
",",
"}",
")",
")",
";",
"// index.html",
"fs",
".",
"writeFileSync",
"(",
"path",
".",
"join",
"(",
"itemPath",
",",
"'index.html'",
")",
",",
"handlebars",
".",
"compile",
"(",
"index",
")",
"(",
"{",
"depth",
",",
"roomsFiles",
",",
"settings",
",",
"root",
",",
"room",
",",
"css_paths",
",",
"js_paths",
",",
"hasCSS",
":",
"css_paths",
".",
"length",
">",
"0",
",",
"hasJS",
":",
"js_paths",
".",
"length",
">",
"0",
",",
"}",
")",
")",
";",
"}",
"}",
")",
";",
"}"
]
| depth=2, fixes path to targetDir | [
"depth",
"=",
"2",
"fixes",
"path",
"to",
"targetDir"
]
| a8c30d45ae724dfc87348ffba5474cf62c10911c | https://github.com/goliney/coderoom/blob/a8c30d45ae724dfc87348ffba5474cf62c10911c/lib/coderoom.js#L103-L175 |
47,149 | theThings/jailed-node | sandbox/sandbox.js | function(url) {
var done = _onImportScript(url)
loadScript(
url,
function runScript(err, code) {
if (err) return done(err)
executeNormal(code, url, done)
}
)
} | javascript | function(url) {
var done = _onImportScript(url)
loadScript(
url,
function runScript(err, code) {
if (err) return done(err)
executeNormal(code, url, done)
}
)
} | [
"function",
"(",
"url",
")",
"{",
"var",
"done",
"=",
"_onImportScript",
"(",
"url",
")",
"loadScript",
"(",
"url",
",",
"function",
"runScript",
"(",
"err",
",",
"code",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
"executeNormal",
"(",
"code",
",",
"url",
",",
"done",
")",
"}",
")",
"}"
]
| Loads and executes the JavaScript file with the given url
@param {String} url of the script to load | [
"Loads",
"and",
"executes",
"the",
"JavaScript",
"file",
"with",
"the",
"given",
"url"
]
| 6e453d97e74fbd1c0b27b982084f6fd7c1aa0173 | https://github.com/theThings/jailed-node/blob/6e453d97e74fbd1c0b27b982084f6fd7c1aa0173/sandbox/sandbox.js#L72-L81 |
|
47,150 | theThings/jailed-node | sandbox/sandbox.js | function(url) {
var done = _onImportScript(url)
loadScript(
url,
function runScript(err, code) {
if (err) return done(err)
executeJailed(code, url, done)
}
)
} | javascript | function(url) {
var done = _onImportScript(url)
loadScript(
url,
function runScript(err, code) {
if (err) return done(err)
executeJailed(code, url, done)
}
)
} | [
"function",
"(",
"url",
")",
"{",
"var",
"done",
"=",
"_onImportScript",
"(",
"url",
")",
"loadScript",
"(",
"url",
",",
"function",
"runScript",
"(",
"err",
",",
"code",
")",
"{",
"if",
"(",
"err",
")",
"return",
"done",
"(",
"err",
")",
"executeJailed",
"(",
"code",
",",
"url",
",",
"done",
")",
"}",
")",
"}"
]
| Loads and executes the JavaScript file with the given url in a
jailed environment
@param {String} url of the script to load | [
"Loads",
"and",
"executes",
"the",
"JavaScript",
"file",
"with",
"the",
"given",
"url",
"in",
"a",
"jailed",
"environment"
]
| 6e453d97e74fbd1c0b27b982084f6fd7c1aa0173 | https://github.com/theThings/jailed-node/blob/6e453d97e74fbd1c0b27b982084f6fd7c1aa0173/sandbox/sandbox.js#L89-L98 |
|
47,151 | theThings/jailed-node | sandbox/sandbox.js | function(code, url, done) {
var vm = require('vm')
var sandbox = {}
var expose = [
'application',
'setTimeout',
'setInterval',
'clearTimeout',
'clearInterval'
]
for (var i = 0; i < expose.length; i++) {
sandbox[expose[i]] = global[expose[i]]
}
code = '"use strict";\n' + code
try {
vm.runInNewContext(code, vm.createContext(sandbox), url)
done()
} catch (e) {
done(e)
}
} | javascript | function(code, url, done) {
var vm = require('vm')
var sandbox = {}
var expose = [
'application',
'setTimeout',
'setInterval',
'clearTimeout',
'clearInterval'
]
for (var i = 0; i < expose.length; i++) {
sandbox[expose[i]] = global[expose[i]]
}
code = '"use strict";\n' + code
try {
vm.runInNewContext(code, vm.createContext(sandbox), url)
done()
} catch (e) {
done(e)
}
} | [
"function",
"(",
"code",
",",
"url",
",",
"done",
")",
"{",
"var",
"vm",
"=",
"require",
"(",
"'vm'",
")",
"var",
"sandbox",
"=",
"{",
"}",
"var",
"expose",
"=",
"[",
"'application'",
",",
"'setTimeout'",
",",
"'setInterval'",
",",
"'clearTimeout'",
",",
"'clearInterval'",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"expose",
".",
"length",
";",
"i",
"++",
")",
"{",
"sandbox",
"[",
"expose",
"[",
"i",
"]",
"]",
"=",
"global",
"[",
"expose",
"[",
"i",
"]",
"]",
"}",
"code",
"=",
"'\"use strict\";\\n'",
"+",
"code",
"try",
"{",
"vm",
".",
"runInNewContext",
"(",
"code",
",",
"vm",
".",
"createContext",
"(",
"sandbox",
")",
",",
"url",
")",
"done",
"(",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"done",
"(",
"e",
")",
"}",
"}"
]
| Executes the given code in a jailed environment, runs the
corresponding callback when done
@param {String} code to execute
@param {String} url of the script (for displaying the stack) | [
"Executes",
"the",
"given",
"code",
"in",
"a",
"jailed",
"environment",
"runs",
"the",
"corresponding",
"callback",
"when",
"done"
]
| 6e453d97e74fbd1c0b27b982084f6fd7c1aa0173 | https://github.com/theThings/jailed-node/blob/6e453d97e74fbd1c0b27b982084f6fd7c1aa0173/sandbox/sandbox.js#L134-L156 |
|
47,152 | theThings/jailed-node | sandbox/sandbox.js | function(url, done) {
var receive = function(res) {
if (res.statusCode != 200) {
var msg = 'Failed to load ' + url + '\n' +
'HTTP responce status code: ' + res.statusCode
printError(msg)
done(new Error(msg))
} else {
var content = ''
res
.on('end', function() {
done(null, content)
})
.on('readable', function() {
var chunk = res.read()
content += chunk.toString()
})
}
}
try {
require(url.indexOf('https') === 0 ? 'https' : 'http').get(url, receive).on('error', done)
} catch (e) {
done(e)
}
} | javascript | function(url, done) {
var receive = function(res) {
if (res.statusCode != 200) {
var msg = 'Failed to load ' + url + '\n' +
'HTTP responce status code: ' + res.statusCode
printError(msg)
done(new Error(msg))
} else {
var content = ''
res
.on('end', function() {
done(null, content)
})
.on('readable', function() {
var chunk = res.read()
content += chunk.toString()
})
}
}
try {
require(url.indexOf('https') === 0 ? 'https' : 'http').get(url, receive).on('error', done)
} catch (e) {
done(e)
}
} | [
"function",
"(",
"url",
",",
"done",
")",
"{",
"var",
"receive",
"=",
"function",
"(",
"res",
")",
"{",
"if",
"(",
"res",
".",
"statusCode",
"!=",
"200",
")",
"{",
"var",
"msg",
"=",
"'Failed to load '",
"+",
"url",
"+",
"'\\n'",
"+",
"'HTTP responce status code: '",
"+",
"res",
".",
"statusCode",
"printError",
"(",
"msg",
")",
"done",
"(",
"new",
"Error",
"(",
"msg",
")",
")",
"}",
"else",
"{",
"var",
"content",
"=",
"''",
"res",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"done",
"(",
"null",
",",
"content",
")",
"}",
")",
".",
"on",
"(",
"'readable'",
",",
"function",
"(",
")",
"{",
"var",
"chunk",
"=",
"res",
".",
"read",
"(",
")",
"content",
"+=",
"chunk",
".",
"toString",
"(",
")",
"}",
")",
"}",
"}",
"try",
"{",
"require",
"(",
"url",
".",
"indexOf",
"(",
"'https'",
")",
"===",
"0",
"?",
"'https'",
":",
"'http'",
")",
".",
"get",
"(",
"url",
",",
"receive",
")",
".",
"on",
"(",
"'error'",
",",
"done",
")",
"}",
"catch",
"(",
"e",
")",
"{",
"done",
"(",
"e",
")",
"}",
"}"
]
| Downloads the script by remote url and provides its content as a
string to the callback
@param {String} url of the remote module to load
@param {Function} sCb success callback
@param {Function} fCb failure callback | [
"Downloads",
"the",
"script",
"by",
"remote",
"url",
"and",
"provides",
"its",
"content",
"as",
"a",
"string",
"to",
"the",
"callback"
]
| 6e453d97e74fbd1c0b27b982084f6fd7c1aa0173 | https://github.com/theThings/jailed-node/blob/6e453d97e74fbd1c0b27b982084f6fd7c1aa0173/sandbox/sandbox.js#L220-L245 |
|
47,153 | theThings/jailed-node | sandbox/sandbox.js | printError | function printError() {
var _log = [new Date().toGMTString().concat(' jailed:sandbox')].concat([].slice.call(arguments))
console.error.apply(null, _log)
} | javascript | function printError() {
var _log = [new Date().toGMTString().concat(' jailed:sandbox')].concat([].slice.call(arguments))
console.error.apply(null, _log)
} | [
"function",
"printError",
"(",
")",
"{",
"var",
"_log",
"=",
"[",
"new",
"Date",
"(",
")",
".",
"toGMTString",
"(",
")",
".",
"concat",
"(",
"' jailed:sandbox'",
")",
"]",
".",
"concat",
"(",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
")",
"console",
".",
"error",
".",
"apply",
"(",
"null",
",",
"_log",
")",
"}"
]
| Prints error message and its stack
@param {Object} msg stack provided by error.stack or a message | [
"Prints",
"error",
"message",
"and",
"its",
"stack"
]
| 6e453d97e74fbd1c0b27b982084f6fd7c1aa0173 | https://github.com/theThings/jailed-node/blob/6e453d97e74fbd1c0b27b982084f6fd7c1aa0173/sandbox/sandbox.js#L267-L270 |
47,154 | oscmejia/libs | lib/libs/number.js | random | function random(_length) {
var string_length = _length;
if(string_length < 0)
string_length = 1;
var chars = "0123456789";
var num = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
num += chars.substring(rnum,rnum+1);
}
return num*1;
} | javascript | function random(_length) {
var string_length = _length;
if(string_length < 0)
string_length = 1;
var chars = "0123456789";
var num = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
num += chars.substring(rnum,rnum+1);
}
return num*1;
} | [
"function",
"random",
"(",
"_length",
")",
"{",
"var",
"string_length",
"=",
"_length",
";",
"if",
"(",
"string_length",
"<",
"0",
")",
"string_length",
"=",
"1",
";",
"var",
"chars",
"=",
"\"0123456789\"",
";",
"var",
"num",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"string_length",
";",
"i",
"++",
")",
"{",
"var",
"rnum",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"chars",
".",
"length",
")",
";",
"num",
"+=",
"chars",
".",
"substring",
"(",
"rnum",
",",
"rnum",
"+",
"1",
")",
";",
"}",
"return",
"num",
"*",
"1",
";",
"}"
]
| Generates a random number of the provided length
@param {int} _length
@api public | [
"Generates",
"a",
"random",
"number",
"of",
"the",
"provided",
"length"
]
| 81f8654af6ee922963e6cc3f6cda96ffa75142cf | https://github.com/oscmejia/libs/blob/81f8654af6ee922963e6cc3f6cda96ffa75142cf/lib/libs/number.js#L7-L21 |
47,155 | oscmejia/libs | lib/libs/number.js | randomBetween | function randomBetween(_min, _max) {
var max, min;
if(_min > _max){
min = _max;
max = _min;
}
else if(_min === _max){
return _min;
}
else{
max = _max;
min = _min;
}
var r = Math.floor(Math.random() * max) + min;
if(r > max)
return max;
if(r < min)
return min;
else
return r;
} | javascript | function randomBetween(_min, _max) {
var max, min;
if(_min > _max){
min = _max;
max = _min;
}
else if(_min === _max){
return _min;
}
else{
max = _max;
min = _min;
}
var r = Math.floor(Math.random() * max) + min;
if(r > max)
return max;
if(r < min)
return min;
else
return r;
} | [
"function",
"randomBetween",
"(",
"_min",
",",
"_max",
")",
"{",
"var",
"max",
",",
"min",
";",
"if",
"(",
"_min",
">",
"_max",
")",
"{",
"min",
"=",
"_max",
";",
"max",
"=",
"_min",
";",
"}",
"else",
"if",
"(",
"_min",
"===",
"_max",
")",
"{",
"return",
"_min",
";",
"}",
"else",
"{",
"max",
"=",
"_max",
";",
"min",
"=",
"_min",
";",
"}",
"var",
"r",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"max",
")",
"+",
"min",
";",
"if",
"(",
"r",
">",
"max",
")",
"return",
"max",
";",
"if",
"(",
"r",
"<",
"min",
")",
"return",
"min",
";",
"else",
"return",
"r",
";",
"}"
]
| Generates a random number between two numbers
@param {int} _min
@param {int} _max
@api public | [
"Generates",
"a",
"random",
"number",
"between",
"two",
"numbers"
]
| 81f8654af6ee922963e6cc3f6cda96ffa75142cf | https://github.com/oscmejia/libs/blob/81f8654af6ee922963e6cc3f6cda96ffa75142cf/lib/libs/number.js#L30-L53 |
47,156 | brewster/imagine | lib/imagine/statsd.js | function (data) {
if (this.silent) {
return;
}
data = this.prefix ? this.prefix + '.' + data : data;
var buffer = new Buffer(data);
this.client.send(buffer, 0, buffer.length, this.port, this.host);
} | javascript | function (data) {
if (this.silent) {
return;
}
data = this.prefix ? this.prefix + '.' + data : data;
var buffer = new Buffer(data);
this.client.send(buffer, 0, buffer.length, this.port, this.host);
} | [
"function",
"(",
"data",
")",
"{",
"if",
"(",
"this",
".",
"silent",
")",
"{",
"return",
";",
"}",
"data",
"=",
"this",
".",
"prefix",
"?",
"this",
".",
"prefix",
"+",
"'.'",
"+",
"data",
":",
"data",
";",
"var",
"buffer",
"=",
"new",
"Buffer",
"(",
"data",
")",
";",
"this",
".",
"client",
".",
"send",
"(",
"buffer",
",",
"0",
",",
"buffer",
".",
"length",
",",
"this",
".",
"port",
",",
"this",
".",
"host",
")",
";",
"}"
]
| Send a request Do nothing if we've been silenced | [
"Send",
"a",
"request",
"Do",
"nothing",
"if",
"we",
"ve",
"been",
"silenced"
]
| 42782ff6365f225f1fb9d90d3a654791286ef023 | https://github.com/brewster/imagine/blob/42782ff6365f225f1fb9d90d3a654791286ef023/lib/imagine/statsd.js#L44-L51 |
|
47,157 | bjnortier/lathe | lib/bsp.js | function(obj) {
if (obj instanceof Cell) {
return {
inside: obj.inside
};
} else {
return {
back : serialize(obj.back),
front : serialize(obj.front),
plane: obj.plane,
shp: obj.shp,
complemented: obj.complemented,
};
}
} | javascript | function(obj) {
if (obj instanceof Cell) {
return {
inside: obj.inside
};
} else {
return {
back : serialize(obj.back),
front : serialize(obj.front),
plane: obj.plane,
shp: obj.shp,
complemented: obj.complemented,
};
}
} | [
"function",
"(",
"obj",
")",
"{",
"if",
"(",
"obj",
"instanceof",
"Cell",
")",
"{",
"return",
"{",
"inside",
":",
"obj",
".",
"inside",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"back",
":",
"serialize",
"(",
"obj",
".",
"back",
")",
",",
"front",
":",
"serialize",
"(",
"obj",
".",
"front",
")",
",",
"plane",
":",
"obj",
".",
"plane",
",",
"shp",
":",
"obj",
".",
"shp",
",",
"complemented",
":",
"obj",
".",
"complemented",
",",
"}",
";",
"}",
"}"
]
| Serialize to a non-circular Javascript object | [
"Serialize",
"to",
"a",
"non",
"-",
"circular",
"Javascript",
"object"
]
| dca3ff6662fed9160f7b0ac82adad1af254b1147 | https://github.com/bjnortier/lathe/blob/dca3ff6662fed9160f7b0ac82adad1af254b1147/lib/bsp.js#L372-L386 |
|
47,158 | zlash/kwyjibo | js/controller.js | Middleware | function Middleware(...middleware) {
return (ctr) => {
if (middleware != undefined) {
let c = exports.globalKCState.getOrInsertController(ctr);
c.middleware = middleware.concat(c.middleware);
}
};
} | javascript | function Middleware(...middleware) {
return (ctr) => {
if (middleware != undefined) {
let c = exports.globalKCState.getOrInsertController(ctr);
c.middleware = middleware.concat(c.middleware);
}
};
} | [
"function",
"Middleware",
"(",
"...",
"middleware",
")",
"{",
"return",
"(",
"ctr",
")",
"=>",
"{",
"if",
"(",
"middleware",
"!=",
"undefined",
")",
"{",
"let",
"c",
"=",
"exports",
".",
"globalKCState",
".",
"getOrInsertController",
"(",
"ctr",
")",
";",
"c",
".",
"middleware",
"=",
"middleware",
".",
"concat",
"(",
"c",
".",
"middleware",
")",
";",
"}",
"}",
";",
"}"
]
| Adds express middleware to run before mounting the controller
@param { Express.RequestHandler[] } middleware - Array of middleware to add. | [
"Adds",
"express",
"middleware",
"to",
"run",
"before",
"mounting",
"the",
"controller"
]
| 466da0e0445f04b48e0e0ff83ecaaa0554114c64 | https://github.com/zlash/kwyjibo/blob/466da0e0445f04b48e0e0ff83ecaaa0554114c64/js/controller.js#L157-L164 |
47,159 | zlash/kwyjibo | js/controller.js | ActionMiddleware | function ActionMiddleware(...middleware) {
return function (target, propertyKey, descriptor) {
if (middleware != undefined) {
let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
m.middleware = middleware.concat(m.middleware);
}
};
} | javascript | function ActionMiddleware(...middleware) {
return function (target, propertyKey, descriptor) {
if (middleware != undefined) {
let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
m.middleware = middleware.concat(m.middleware);
}
};
} | [
"function",
"ActionMiddleware",
"(",
"...",
"middleware",
")",
"{",
"return",
"function",
"(",
"target",
",",
"propertyKey",
",",
"descriptor",
")",
"{",
"if",
"(",
"middleware",
"!=",
"undefined",
")",
"{",
"let",
"m",
"=",
"exports",
".",
"globalKCState",
".",
"getOrInsertController",
"(",
"target",
".",
"constructor",
")",
".",
"getOrInsertMethod",
"(",
"propertyKey",
")",
";",
"m",
".",
"middleware",
"=",
"middleware",
".",
"concat",
"(",
"m",
".",
"middleware",
")",
";",
"}",
"}",
";",
"}"
]
| Adds express middleware to run before the method
@param { Express.RequestHandler[] } middleware - Array of middleware to add. | [
"Adds",
"express",
"middleware",
"to",
"run",
"before",
"the",
"method"
]
| 466da0e0445f04b48e0e0ff83ecaaa0554114c64 | https://github.com/zlash/kwyjibo/blob/466da0e0445f04b48e0e0ff83ecaaa0554114c64/js/controller.js#L239-L246 |
47,160 | zlash/kwyjibo | js/controller.js | DocAction | function DocAction(docStr) {
return function (target, propertyKey, descriptor) {
let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
m.docString = docStr;
};
} | javascript | function DocAction(docStr) {
return function (target, propertyKey, descriptor) {
let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
m.docString = docStr;
};
} | [
"function",
"DocAction",
"(",
"docStr",
")",
"{",
"return",
"function",
"(",
"target",
",",
"propertyKey",
",",
"descriptor",
")",
"{",
"let",
"m",
"=",
"exports",
".",
"globalKCState",
".",
"getOrInsertController",
"(",
"target",
".",
"constructor",
")",
".",
"getOrInsertMethod",
"(",
"propertyKey",
")",
";",
"m",
".",
"docString",
"=",
"docStr",
";",
"}",
";",
"}"
]
| Attach a documentation string to the method
@param {string} docStr - The documentation string. | [
"Attach",
"a",
"documentation",
"string",
"to",
"the",
"method"
]
| 466da0e0445f04b48e0e0ff83ecaaa0554114c64 | https://github.com/zlash/kwyjibo/blob/466da0e0445f04b48e0e0ff83ecaaa0554114c64/js/controller.js#L262-L267 |
47,161 | zlash/kwyjibo | js/controller.js | OpenApiResponse | function OpenApiResponse(httpCode, description, type) {
return function (target, propertyKey, descriptor) {
let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
httpCode = httpCode.toString();
m.openApiResponses[httpCode] = { description: description, type: type };
};
} | javascript | function OpenApiResponse(httpCode, description, type) {
return function (target, propertyKey, descriptor) {
let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
httpCode = httpCode.toString();
m.openApiResponses[httpCode] = { description: description, type: type };
};
} | [
"function",
"OpenApiResponse",
"(",
"httpCode",
",",
"description",
",",
"type",
")",
"{",
"return",
"function",
"(",
"target",
",",
"propertyKey",
",",
"descriptor",
")",
"{",
"let",
"m",
"=",
"exports",
".",
"globalKCState",
".",
"getOrInsertController",
"(",
"target",
".",
"constructor",
")",
".",
"getOrInsertMethod",
"(",
"propertyKey",
")",
";",
"httpCode",
"=",
"httpCode",
".",
"toString",
"(",
")",
";",
"m",
".",
"openApiResponses",
"[",
"httpCode",
"]",
"=",
"{",
"description",
":",
"description",
",",
"type",
":",
"type",
"}",
";",
"}",
";",
"}"
]
| Attach a OpenApi Response to the method
@param {number|string} httpCode - The http code used for the response
@param {string} description - Response description
@param {string} type - The Open Api defined type. | [
"Attach",
"a",
"OpenApi",
"Response",
"to",
"the",
"method"
]
| 466da0e0445f04b48e0e0ff83ecaaa0554114c64 | https://github.com/zlash/kwyjibo/blob/466da0e0445f04b48e0e0ff83ecaaa0554114c64/js/controller.js#L275-L281 |
47,162 | amobiz/json-normalizer | lib/normalize.js | async | function async(schema, values, optionalOptions, callbackFn) {
var options, callback;
options = optionalOptions || {};
callback = callbackFn || optionalOptions;
process.nextTick(_async);
function _async() {
deref(schema, options, function (err, derefSchema) {
var result;
if (err) {
callback(err);
} else {
result = normalize(derefSchema, values, options);
callback(null, result);
}
});
}
} | javascript | function async(schema, values, optionalOptions, callbackFn) {
var options, callback;
options = optionalOptions || {};
callback = callbackFn || optionalOptions;
process.nextTick(_async);
function _async() {
deref(schema, options, function (err, derefSchema) {
var result;
if (err) {
callback(err);
} else {
result = normalize(derefSchema, values, options);
callback(null, result);
}
});
}
} | [
"function",
"async",
"(",
"schema",
",",
"values",
",",
"optionalOptions",
",",
"callbackFn",
")",
"{",
"var",
"options",
",",
"callback",
";",
"options",
"=",
"optionalOptions",
"||",
"{",
"}",
";",
"callback",
"=",
"callbackFn",
"||",
"optionalOptions",
";",
"process",
".",
"nextTick",
"(",
"_async",
")",
";",
"function",
"_async",
"(",
")",
"{",
"deref",
"(",
"schema",
",",
"options",
",",
"function",
"(",
"err",
",",
"derefSchema",
")",
"{",
"var",
"result",
";",
"if",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
"else",
"{",
"result",
"=",
"normalize",
"(",
"derefSchema",
",",
"values",
",",
"options",
")",
";",
"callback",
"(",
"null",
",",
"result",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Normalizes a loose json data object to a strict json-schema data object.
@context Don't care.
@param schema The schema used to normalize the given JSON data object.
@param data The JSON data object.
@param options Optional. Currently only accepts loader or array of loaders.
@param options.loader | options.loaders A loader or an array of loaders
that help loading remote schemas. Loaders are tested in the order listed.
@param callback The callback function with `function(err, detail)` signature
that the normalizer delivers the normalized JSON object to. Called with null context.
@return No return value. | [
"Normalizes",
"a",
"loose",
"json",
"data",
"object",
"to",
"a",
"strict",
"json",
"-",
"schema",
"data",
"object",
"."
]
| 76a8ab1db2da4600dbd28c5c6c7fd11e43c0dd55 | https://github.com/amobiz/json-normalizer/blob/76a8ab1db2da4600dbd28c5c6c7fd11e43c0dd55/lib/normalize.js#L19-L38 |
47,163 | kevva/squeak | index.js | Squeak | function Squeak(opts) {
if (!(this instanceof Squeak)) {
return new Squeak(opts);
}
EventEmitter.call(this);
this.opts = opts || {};
this.align = this.opts.align !== false;
this.indent = this.opts.indent || 2;
this.separator = this.opts.separator || ' : ';
this.stream = this.opts.stream || process.stderr || consoleStream();
this.types = [];
} | javascript | function Squeak(opts) {
if (!(this instanceof Squeak)) {
return new Squeak(opts);
}
EventEmitter.call(this);
this.opts = opts || {};
this.align = this.opts.align !== false;
this.indent = this.opts.indent || 2;
this.separator = this.opts.separator || ' : ';
this.stream = this.opts.stream || process.stderr || consoleStream();
this.types = [];
} | [
"function",
"Squeak",
"(",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Squeak",
")",
")",
"{",
"return",
"new",
"Squeak",
"(",
"opts",
")",
";",
"}",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"align",
"=",
"this",
".",
"opts",
".",
"align",
"!==",
"false",
";",
"this",
".",
"indent",
"=",
"this",
".",
"opts",
".",
"indent",
"||",
"2",
";",
"this",
".",
"separator",
"=",
"this",
".",
"opts",
".",
"separator",
"||",
"' : '",
";",
"this",
".",
"stream",
"=",
"this",
".",
"opts",
".",
"stream",
"||",
"process",
".",
"stderr",
"||",
"consoleStream",
"(",
")",
";",
"this",
".",
"types",
"=",
"[",
"]",
";",
"}"
]
| Initialize a new `Squeak`
@param {Object} opts
@api public | [
"Initialize",
"a",
"new",
"Squeak"
]
| 5fd68a6e256015bc2bed80a89047629fb6ebfd41 | https://github.com/kevva/squeak/blob/5fd68a6e256015bc2bed80a89047629fb6ebfd41/index.js#L16-L29 |
47,164 | amida-tech/cms-fhir | lib/cmsTxtToIntObj.js | hook | function hook(cps, section) {
var i, len;
if (section["section header"] === "empty") {
if (section["data"]) {
// Guess it's a claim
len = section["data"].length;
for (i = 0; i < len; i++) {
if (section["data"][i]["claim number"]) {
section["section header"] = "claim summary";
if (!section["claim number"]) {
section["claim number"] = section["data"][i]["claim number"];
}
break;
}
}
}
}
if (section["section header"] === "claim" || section["section header"] === "claim summary") {
if (!section["claim number"]) {
if (section["data"]) {
len = section["data"].length;
for (i = 0; i < len; i++) {
if (section["data"][i]["claim number"]) {
section["claim number"] = section["data"][i]["claim number"];
break;
}
}
}
}
}
} | javascript | function hook(cps, section) {
var i, len;
if (section["section header"] === "empty") {
if (section["data"]) {
// Guess it's a claim
len = section["data"].length;
for (i = 0; i < len; i++) {
if (section["data"][i]["claim number"]) {
section["section header"] = "claim summary";
if (!section["claim number"]) {
section["claim number"] = section["data"][i]["claim number"];
}
break;
}
}
}
}
if (section["section header"] === "claim" || section["section header"] === "claim summary") {
if (!section["claim number"]) {
if (section["data"]) {
len = section["data"].length;
for (i = 0; i < len; i++) {
if (section["data"][i]["claim number"]) {
section["claim number"] = section["data"][i]["claim number"];
break;
}
}
}
}
}
} | [
"function",
"hook",
"(",
"cps",
",",
"section",
")",
"{",
"var",
"i",
",",
"len",
";",
"if",
"(",
"section",
"[",
"\"section header\"",
"]",
"===",
"\"empty\"",
")",
"{",
"if",
"(",
"section",
"[",
"\"data\"",
"]",
")",
"{",
"// Guess it's a claim",
"len",
"=",
"section",
"[",
"\"data\"",
"]",
".",
"length",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"section",
"[",
"\"data\"",
"]",
"[",
"i",
"]",
"[",
"\"claim number\"",
"]",
")",
"{",
"section",
"[",
"\"section header\"",
"]",
"=",
"\"claim summary\"",
";",
"if",
"(",
"!",
"section",
"[",
"\"claim number\"",
"]",
")",
"{",
"section",
"[",
"\"claim number\"",
"]",
"=",
"section",
"[",
"\"data\"",
"]",
"[",
"i",
"]",
"[",
"\"claim number\"",
"]",
";",
"}",
"break",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"section",
"[",
"\"section header\"",
"]",
"===",
"\"claim\"",
"||",
"section",
"[",
"\"section header\"",
"]",
"===",
"\"claim summary\"",
")",
"{",
"if",
"(",
"!",
"section",
"[",
"\"claim number\"",
"]",
")",
"{",
"if",
"(",
"section",
"[",
"\"data\"",
"]",
")",
"{",
"len",
"=",
"section",
"[",
"\"data\"",
"]",
".",
"length",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"section",
"[",
"\"data\"",
"]",
"[",
"i",
"]",
"[",
"\"claim number\"",
"]",
")",
"{",
"section",
"[",
"\"claim number\"",
"]",
"=",
"section",
"[",
"\"data\"",
"]",
"[",
"i",
"]",
"[",
"\"claim number\"",
"]",
";",
"break",
";",
"}",
"}",
"}",
"}",
"}",
"}"
]
| Massage each section trying to restore a broken structure if any | [
"Massage",
"each",
"section",
"trying",
"to",
"restore",
"a",
"broken",
"structure",
"if",
"any"
]
| 34404ea5d9c3c3582ae72b877d9febd703b57d56 | https://github.com/amida-tech/cms-fhir/blob/34404ea5d9c3c3582ae72b877d9febd703b57d56/lib/cmsTxtToIntObj.js#L19-L51 |
47,165 | quorrajs/Positron | lib/view/helpers.js | elixir | function elixir(file, buildDirectory) {
if (!buildDirectory) {
buildDirectory = 'build';
}
var manifestPath = path.join(publicPath(buildDirectory), 'rev-manifest.json');
var manifest = require(manifestPath);
if (isset(manifest[file])) {
return '/'+ str.trim(buildDirectory + '/' + manifest[file], '/');
}
throw new Error("File " + file + " not defined in asset manifest.");
} | javascript | function elixir(file, buildDirectory) {
if (!buildDirectory) {
buildDirectory = 'build';
}
var manifestPath = path.join(publicPath(buildDirectory), 'rev-manifest.json');
var manifest = require(manifestPath);
if (isset(manifest[file])) {
return '/'+ str.trim(buildDirectory + '/' + manifest[file], '/');
}
throw new Error("File " + file + " not defined in asset manifest.");
} | [
"function",
"elixir",
"(",
"file",
",",
"buildDirectory",
")",
"{",
"if",
"(",
"!",
"buildDirectory",
")",
"{",
"buildDirectory",
"=",
"'build'",
";",
"}",
"var",
"manifestPath",
"=",
"path",
".",
"join",
"(",
"publicPath",
"(",
"buildDirectory",
")",
",",
"'rev-manifest.json'",
")",
";",
"var",
"manifest",
"=",
"require",
"(",
"manifestPath",
")",
";",
"if",
"(",
"isset",
"(",
"manifest",
"[",
"file",
"]",
")",
")",
"{",
"return",
"'/'",
"+",
"str",
".",
"trim",
"(",
"buildDirectory",
"+",
"'/'",
"+",
"manifest",
"[",
"file",
"]",
",",
"'/'",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"\"File \"",
"+",
"file",
"+",
"\" not defined in asset manifest.\"",
")",
";",
"}"
]
| Get the path to a versioned Elixir file.
@param {String} file
@param {String} buildDirectory
@return {String}
@throws Error | [
"Get",
"the",
"path",
"to",
"a",
"versioned",
"Elixir",
"file",
"."
]
| a4bad5a5f581743d1885405c11ae26600fb957af | https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/view/helpers.js#L22-L37 |
47,166 | Jam3/f1 | lib/parsers/getParser.js | function(states, targets, transitions) {
initMethods.forEach( function(method) {
method(states, targets, transitions);
});
} | javascript | function(states, targets, transitions) {
initMethods.forEach( function(method) {
method(states, targets, transitions);
});
} | [
"function",
"(",
"states",
",",
"targets",
",",
"transitions",
")",
"{",
"initMethods",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"method",
"(",
"states",
",",
"targets",
",",
"transitions",
")",
";",
"}",
")",
";",
"}"
]
| This will be called when the `f1` instance is initialized.
@param {Object} states states the `f1` instance currently is using
@param {Object} targets targets the `f1` instance currently is using
@param {Array} transitions transitions the `f1` instance currently is using | [
"This",
"will",
"be",
"called",
"when",
"the",
"f1",
"instance",
"is",
"initialized",
"."
]
| 31bf0f9f4491f08d8b453aff744ba22ceab94607 | https://github.com/Jam3/f1/blob/31bf0f9f4491f08d8b453aff744ba22ceab94607/lib/parsers/getParser.js#L38-L44 |
|
47,167 | jaymell/nodeCf | src/config.js | parseExtraVars | function parseExtraVars(extraVars) {
if (!(_.isString(extraVars))) {
return undefined;
}
const myVars = _.split(extraVars, ' ').map(it => {
const v = _.split(it, '=');
if ( v.length != 2 )
throw new Error("Can't parse variable");
return v;
});
return _.fromPairs(myVars);
} | javascript | function parseExtraVars(extraVars) {
if (!(_.isString(extraVars))) {
return undefined;
}
const myVars = _.split(extraVars, ' ').map(it => {
const v = _.split(it, '=');
if ( v.length != 2 )
throw new Error("Can't parse variable");
return v;
});
return _.fromPairs(myVars);
} | [
"function",
"parseExtraVars",
"(",
"extraVars",
")",
"{",
"if",
"(",
"!",
"(",
"_",
".",
"isString",
"(",
"extraVars",
")",
")",
")",
"{",
"return",
"undefined",
";",
"}",
"const",
"myVars",
"=",
"_",
".",
"split",
"(",
"extraVars",
",",
"' '",
")",
".",
"map",
"(",
"it",
"=>",
"{",
"const",
"v",
"=",
"_",
".",
"split",
"(",
"it",
",",
"'='",
")",
";",
"if",
"(",
"v",
".",
"length",
"!=",
"2",
")",
"throw",
"new",
"Error",
"(",
"\"Can't parse variable\"",
")",
";",
"return",
"v",
";",
"}",
")",
";",
"return",
"_",
".",
"fromPairs",
"(",
"myVars",
")",
";",
"}"
]
| given a string of one or more key-value pairs separated by '=', convert and return object | [
"given",
"a",
"string",
"of",
"one",
"or",
"more",
"key",
"-",
"value",
"pairs",
"separated",
"by",
"=",
"convert",
"and",
"return",
"object"
]
| d0f499a1b0adf5c810c33698a66ef16db6bc590d | https://github.com/jaymell/nodeCf/blob/d0f499a1b0adf5c810c33698a66ef16db6bc590d/src/config.js#L102-L113 |
47,168 | jaymell/nodeCf | src/config.js | parseArgs | function parseArgs(argv) {
debug('parseArgs argv: ', argv);
// default action
var action = 'deploy';
if ( argv['_'].length >= 1 ) {
action = argv['_'][0];
}
failIfEmpty('e', 'environment', argv);
failIfAbsent('e', 'environment', argv);
if ('s' in argv || 'stacks' in argv) failIfEmpty('s', 'stacks', argv);
return {
environment: argv['e'] || argv['environment'],
extraVars: parseExtraVars(argv['x'] || argv['extraVars']),
action: action,
region: argv['r'] || argv['region'],
profile: argv['p'],
cfg: argv['c'] || argv['config'],
stackFilters: argv['s'] || argv['stacks'] || undefined
};
} | javascript | function parseArgs(argv) {
debug('parseArgs argv: ', argv);
// default action
var action = 'deploy';
if ( argv['_'].length >= 1 ) {
action = argv['_'][0];
}
failIfEmpty('e', 'environment', argv);
failIfAbsent('e', 'environment', argv);
if ('s' in argv || 'stacks' in argv) failIfEmpty('s', 'stacks', argv);
return {
environment: argv['e'] || argv['environment'],
extraVars: parseExtraVars(argv['x'] || argv['extraVars']),
action: action,
region: argv['r'] || argv['region'],
profile: argv['p'],
cfg: argv['c'] || argv['config'],
stackFilters: argv['s'] || argv['stacks'] || undefined
};
} | [
"function",
"parseArgs",
"(",
"argv",
")",
"{",
"debug",
"(",
"'parseArgs argv: '",
",",
"argv",
")",
";",
"// default action",
"var",
"action",
"=",
"'deploy'",
";",
"if",
"(",
"argv",
"[",
"'_'",
"]",
".",
"length",
">=",
"1",
")",
"{",
"action",
"=",
"argv",
"[",
"'_'",
"]",
"[",
"0",
"]",
";",
"}",
"failIfEmpty",
"(",
"'e'",
",",
"'environment'",
",",
"argv",
")",
";",
"failIfAbsent",
"(",
"'e'",
",",
"'environment'",
",",
"argv",
")",
";",
"if",
"(",
"'s'",
"in",
"argv",
"||",
"'stacks'",
"in",
"argv",
")",
"failIfEmpty",
"(",
"'s'",
",",
"'stacks'",
",",
"argv",
")",
";",
"return",
"{",
"environment",
":",
"argv",
"[",
"'e'",
"]",
"||",
"argv",
"[",
"'environment'",
"]",
",",
"extraVars",
":",
"parseExtraVars",
"(",
"argv",
"[",
"'x'",
"]",
"||",
"argv",
"[",
"'extraVars'",
"]",
")",
",",
"action",
":",
"action",
",",
"region",
":",
"argv",
"[",
"'r'",
"]",
"||",
"argv",
"[",
"'region'",
"]",
",",
"profile",
":",
"argv",
"[",
"'p'",
"]",
",",
"cfg",
":",
"argv",
"[",
"'c'",
"]",
"||",
"argv",
"[",
"'config'",
"]",
",",
"stackFilters",
":",
"argv",
"[",
"'s'",
"]",
"||",
"argv",
"[",
"'stacks'",
"]",
"||",
"undefined",
"}",
";",
"}"
]
| validate command line arguments | [
"validate",
"command",
"line",
"arguments"
]
| d0f499a1b0adf5c810c33698a66ef16db6bc590d | https://github.com/jaymell/nodeCf/blob/d0f499a1b0adf5c810c33698a66ef16db6bc590d/src/config.js#L138-L159 |
47,169 | jaymell/nodeCf | src/config.js | loadConfigFile | async function loadConfigFile(filePath) {
const f = await Promise.any(
_.map(['.yml', '.yaml', '.json', ''], async(ext) =>
await utils.fileExists(`${filePath}${ext}`)));
if (f) {
return loadYaml(await fs.readFileAsync(f));
}
return undefined;
} | javascript | async function loadConfigFile(filePath) {
const f = await Promise.any(
_.map(['.yml', '.yaml', '.json', ''], async(ext) =>
await utils.fileExists(`${filePath}${ext}`)));
if (f) {
return loadYaml(await fs.readFileAsync(f));
}
return undefined;
} | [
"async",
"function",
"loadConfigFile",
"(",
"filePath",
")",
"{",
"const",
"f",
"=",
"await",
"Promise",
".",
"any",
"(",
"_",
".",
"map",
"(",
"[",
"'.yml'",
",",
"'.yaml'",
",",
"'.json'",
",",
"''",
"]",
",",
"async",
"(",
"ext",
")",
"=>",
"await",
"utils",
".",
"fileExists",
"(",
"`",
"${",
"filePath",
"}",
"${",
"ext",
"}",
"`",
")",
")",
")",
";",
"if",
"(",
"f",
")",
"{",
"return",
"loadYaml",
"(",
"await",
"fs",
".",
"readFileAsync",
"(",
"f",
")",
")",
";",
"}",
"return",
"undefined",
";",
"}"
]
| if file exists, load it, else return undefined. Iterate through various possible file extensions in attempt to find file. | [
"if",
"file",
"exists",
"load",
"it",
"else",
"return",
"undefined",
".",
"Iterate",
"through",
"various",
"possible",
"file",
"extensions",
"in",
"attempt",
"to",
"find",
"file",
"."
]
| d0f499a1b0adf5c810c33698a66ef16db6bc590d | https://github.com/jaymell/nodeCf/blob/d0f499a1b0adf5c810c33698a66ef16db6bc590d/src/config.js#L192-L200 |
47,170 | feedhenry-raincatcher/raincatcher-angularjs | packages/angularjs-auth-keycloak/lib/profileData.js | extractAttributeFields | function extractAttributeFields(attributeFields) {
var attributes = {};
if (attributeFields) {
for (var field in attributeFields) {
if (attributeFields[field].length > 0) {
attributes[field] = attributeFields[field][0];
}
}
}
return attributes;
} | javascript | function extractAttributeFields(attributeFields) {
var attributes = {};
if (attributeFields) {
for (var field in attributeFields) {
if (attributeFields[field].length > 0) {
attributes[field] = attributeFields[field][0];
}
}
}
return attributes;
} | [
"function",
"extractAttributeFields",
"(",
"attributeFields",
")",
"{",
"var",
"attributes",
"=",
"{",
"}",
";",
"if",
"(",
"attributeFields",
")",
"{",
"for",
"(",
"var",
"field",
"in",
"attributeFields",
")",
"{",
"if",
"(",
"attributeFields",
"[",
"field",
"]",
".",
"length",
">",
"0",
")",
"{",
"attributes",
"[",
"field",
"]",
"=",
"attributeFields",
"[",
"field",
"]",
"[",
"0",
"]",
";",
"}",
"}",
"}",
"return",
"attributes",
";",
"}"
]
| Extract attribute fields from the profile data returned by Keycloak
@param attributeFields - Object which contains all the attributes of a user | [
"Extract",
"attribute",
"fields",
"from",
"the",
"profile",
"data",
"returned",
"by",
"Keycloak"
]
| b394689227901e18871ad9edd0ec226c5e6839e1 | https://github.com/feedhenry-raincatcher/raincatcher-angularjs/blob/b394689227901e18871ad9edd0ec226c5e6839e1/packages/angularjs-auth-keycloak/lib/profileData.js#L5-L15 |
47,171 | feedhenry-raincatcher/raincatcher-angularjs | packages/angularjs-auth-keycloak/lib/profileData.js | formatProfileData | function formatProfileData(profileData) {
var profile;
if (profileData) {
profile = extractAttributeFields(profileData.attributes);
profile.username = profileData.username;
profile.email = profileData.email;
}
return profile;
} | javascript | function formatProfileData(profileData) {
var profile;
if (profileData) {
profile = extractAttributeFields(profileData.attributes);
profile.username = profileData.username;
profile.email = profileData.email;
}
return profile;
} | [
"function",
"formatProfileData",
"(",
"profileData",
")",
"{",
"var",
"profile",
";",
"if",
"(",
"profileData",
")",
"{",
"profile",
"=",
"extractAttributeFields",
"(",
"profileData",
".",
"attributes",
")",
";",
"profile",
".",
"username",
"=",
"profileData",
".",
"username",
";",
"profile",
".",
"email",
"=",
"profileData",
".",
"email",
";",
"}",
"return",
"profile",
";",
"}"
]
| Formats profile data as expected by the application
@param profileData - Object which contains the profile data of a user | [
"Formats",
"profile",
"data",
"as",
"expected",
"by",
"the",
"application"
]
| b394689227901e18871ad9edd0ec226c5e6839e1 | https://github.com/feedhenry-raincatcher/raincatcher-angularjs/blob/b394689227901e18871ad9edd0ec226c5e6839e1/packages/angularjs-auth-keycloak/lib/profileData.js#L21-L29 |
47,172 | Jam3/f1 | index.js | f1 | function f1(settings) {
if(!(this instanceof f1)) {
return new f1(settings);
}
settings = settings || {};
var emitter = this;
var onUpdate = settings.onUpdate || noop;
var onState = settings.onState || noop;
// this is used to generate a "name" for an f1 instance if one isn't given
numInstances++;
this.onState = function() {
emitter.emit.apply(emitter, getEventArgs('state', arguments));
if(onState) {
onState.apply(undefined, arguments);
}
};
this.onUpdate = function() {
emitter.emit.apply(emitter, getEventArgs('update', arguments));
if(onUpdate) {
onUpdate.apply(undefined, arguments);
}
};
this.name = settings.name || 'ui_' + numInstances;
this.isInitialized = false;
this.data = null; // current animation data
this.defTargets = null;
this.defStates = null;
this.defTransitions = null;
this.parser = null;
if(settings.transitions) {
this.transitions(settings.transitions);
}
if(settings.states) {
this.states(settings.states);
}
if(settings.targets) {
this.targets(settings.targets);
}
if(settings.parsers) {
this.parsers(settings.parsers);
}
// kimi is the man who does all the work under the hood
this.driver = kimi( {
manualStep: settings.autoUpdate === undefined ? false : !settings.autoUpdate,
onState: _onState.bind(this),
onUpdate: _onUpdate.bind(this)
});
} | javascript | function f1(settings) {
if(!(this instanceof f1)) {
return new f1(settings);
}
settings = settings || {};
var emitter = this;
var onUpdate = settings.onUpdate || noop;
var onState = settings.onState || noop;
// this is used to generate a "name" for an f1 instance if one isn't given
numInstances++;
this.onState = function() {
emitter.emit.apply(emitter, getEventArgs('state', arguments));
if(onState) {
onState.apply(undefined, arguments);
}
};
this.onUpdate = function() {
emitter.emit.apply(emitter, getEventArgs('update', arguments));
if(onUpdate) {
onUpdate.apply(undefined, arguments);
}
};
this.name = settings.name || 'ui_' + numInstances;
this.isInitialized = false;
this.data = null; // current animation data
this.defTargets = null;
this.defStates = null;
this.defTransitions = null;
this.parser = null;
if(settings.transitions) {
this.transitions(settings.transitions);
}
if(settings.states) {
this.states(settings.states);
}
if(settings.targets) {
this.targets(settings.targets);
}
if(settings.parsers) {
this.parsers(settings.parsers);
}
// kimi is the man who does all the work under the hood
this.driver = kimi( {
manualStep: settings.autoUpdate === undefined ? false : !settings.autoUpdate,
onState: _onState.bind(this),
onUpdate: _onUpdate.bind(this)
});
} | [
"function",
"f1",
"(",
"settings",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"f1",
")",
")",
"{",
"return",
"new",
"f1",
"(",
"settings",
")",
";",
"}",
"settings",
"=",
"settings",
"||",
"{",
"}",
";",
"var",
"emitter",
"=",
"this",
";",
"var",
"onUpdate",
"=",
"settings",
".",
"onUpdate",
"||",
"noop",
";",
"var",
"onState",
"=",
"settings",
".",
"onState",
"||",
"noop",
";",
"// this is used to generate a \"name\" for an f1 instance if one isn't given",
"numInstances",
"++",
";",
"this",
".",
"onState",
"=",
"function",
"(",
")",
"{",
"emitter",
".",
"emit",
".",
"apply",
"(",
"emitter",
",",
"getEventArgs",
"(",
"'state'",
",",
"arguments",
")",
")",
";",
"if",
"(",
"onState",
")",
"{",
"onState",
".",
"apply",
"(",
"undefined",
",",
"arguments",
")",
";",
"}",
"}",
";",
"this",
".",
"onUpdate",
"=",
"function",
"(",
")",
"{",
"emitter",
".",
"emit",
".",
"apply",
"(",
"emitter",
",",
"getEventArgs",
"(",
"'update'",
",",
"arguments",
")",
")",
";",
"if",
"(",
"onUpdate",
")",
"{",
"onUpdate",
".",
"apply",
"(",
"undefined",
",",
"arguments",
")",
";",
"}",
"}",
";",
"this",
".",
"name",
"=",
"settings",
".",
"name",
"||",
"'ui_'",
"+",
"numInstances",
";",
"this",
".",
"isInitialized",
"=",
"false",
";",
"this",
".",
"data",
"=",
"null",
";",
"// current animation data",
"this",
".",
"defTargets",
"=",
"null",
";",
"this",
".",
"defStates",
"=",
"null",
";",
"this",
".",
"defTransitions",
"=",
"null",
";",
"this",
".",
"parser",
"=",
"null",
";",
"if",
"(",
"settings",
".",
"transitions",
")",
"{",
"this",
".",
"transitions",
"(",
"settings",
".",
"transitions",
")",
";",
"}",
"if",
"(",
"settings",
".",
"states",
")",
"{",
"this",
".",
"states",
"(",
"settings",
".",
"states",
")",
";",
"}",
"if",
"(",
"settings",
".",
"targets",
")",
"{",
"this",
".",
"targets",
"(",
"settings",
".",
"targets",
")",
";",
"}",
"if",
"(",
"settings",
".",
"parsers",
")",
"{",
"this",
".",
"parsers",
"(",
"settings",
".",
"parsers",
")",
";",
"}",
"// kimi is the man who does all the work under the hood",
"this",
".",
"driver",
"=",
"kimi",
"(",
"{",
"manualStep",
":",
"settings",
".",
"autoUpdate",
"===",
"undefined",
"?",
"false",
":",
"!",
"settings",
".",
"autoUpdate",
",",
"onState",
":",
"_onState",
".",
"bind",
"(",
"this",
")",
",",
"onUpdate",
":",
"_onUpdate",
".",
"bind",
"(",
"this",
")",
"}",
")",
";",
"}"
]
| To construct a new `f1` instance you can do it in two ways.
```javascript
ui = f1([ settigns ]);
```
or
```javascript
ui = new f1([ settings ]);
```
To construct an `f1` instance you can pass in an optional settings object. The following are properties you can pass in settings:
```javascript
{
onState: listenerState, // this callback will be called whenever f1 reaches a state
onUpdate: listenerUpdater, // this callback will be called whenever f1 is updating
// you can pass a name for the ui. This is useful when you're using an external tool or want
// to differentiate between f1 instances
name: 'someNameForTheUI',
// this is an object which contains all elements/items that you will be animating
targets: {
bg: bgElement
},
// all states for the ui
// states are the top level object and anything after that are the properties
// for that state
states: {
out: {
bg: { alpha: 0 }
},
idle: {
bg: { alpha: 1 }
}
},
// an array which defines the transitions for the ui
transitions: [
'out', 'idle', // this ui can go from out to idle
'idle', 'out' // and idle to out
],
// an Object contains init and update functions. These will be used
// to initialize your ui elements and apply state to targets during update
parsers: {
init: [ initPosition ],
update: [ applyPosition ]
}
}
```
@param {Object} [settings] An optional settings Object described above
@chainable | [
"To",
"construct",
"a",
"new",
"f1",
"instance",
"you",
"can",
"do",
"it",
"in",
"two",
"ways",
"."
]
| 31bf0f9f4491f08d8b453aff744ba22ceab94607 | https://github.com/Jam3/f1/blob/31bf0f9f4491f08d8b453aff744ba22ceab94607/index.js#L75-L138 |
47,173 | Jam3/f1 | index.js | function(transitions) {
this.defTransitions = Array.isArray(transitions) ? transitions : Array.prototype.slice.apply(arguments);
return this;
} | javascript | function(transitions) {
this.defTransitions = Array.isArray(transitions) ? transitions : Array.prototype.slice.apply(arguments);
return this;
} | [
"function",
"(",
"transitions",
")",
"{",
"this",
".",
"defTransitions",
"=",
"Array",
".",
"isArray",
"(",
"transitions",
")",
"?",
"transitions",
":",
"Array",
".",
"prototype",
".",
"slice",
".",
"apply",
"(",
"arguments",
")",
";",
"return",
"this",
";",
"}"
]
| defines how this `f1` instance can move between states.
For instance if we had two states out and idle you could define your transitions
like this:
```javascript
var ui = require('f1')();
ui.transitions( [
'out', 'idle', // defines that you can go from the out state to the idle state
'idle', 'out' // defines that you can go from the idle state to the out state
]);
```
Note that transitions are not bi-directional.
If you simply just defined state names a default animation would be applied between
states. This default transition will have a duration of 0.5 seconds and use no ease.
If you want to modify the animation duration and ease you can define your transitions
like this:
```javascript
var eases = require('eases');
var ui = require('f1')();
ui.transitions( [
'out', 'idle', { duration: 1, ease: eases.expoOut },
'idle', 'out', { duration: 0.5, ease: eases.expoIn }
]);
```
Defining your transitions using the above syntax will cause all properties to animate
using the duration and ease defined.
Ease functions should take a time property between 0-1 and return a modified value between
0-1.
You can also animate properties individually. Here passing a delay maybe sometimes
userful:
```javascript
var eases = require('eases');
var ui = require('f1')();
ui.transitions( [
'out', 'idle', {
duration: 1, ease: eases.expoOut,
position: { duration: 0.5, delay: 0.5, ease: eases.quadOut },
alpha: { duration: 0.5 }
},
'idle', 'out', { duration: 0.5, ease: eases.expoIn }
]);
```
In that example every property besides `position` and `alpha` will have a duration of one second
using the `eases.quadOut` ease equation. `position` will have a duration of 0.5 seconds and will
be delayed 0.5 seconds and will use the `eases.quadOut` easing function. `alpha` will simply have
a duration of 0.5 seconds.
For advanced transitions you can pass in a function instead like so:
```javascript
ui.transitions( [
'out', 'idle', {
duration: 1, ease: eases.expoOut,
position: { duration: 0.5, delay: 0.5, ease: eases.quadOut },
alpha: function(time, start, end) {
return (end - start) * time + start;
}
},
'idle', 'out', { duration: 0.5, ease: eases.expoIn }
]);
```
There the animation is the same as in the previous example however `alpha` will be calculated using
a custom transition function.
@param {Array} transitions An array which descriptes transitions
@chainable | [
"defines",
"how",
"this",
"f1",
"instance",
"can",
"move",
"between",
"states",
"."
]
| 31bf0f9f4491f08d8b453aff744ba22ceab94607 | https://github.com/Jam3/f1/blob/31bf0f9f4491f08d8b453aff744ba22ceab94607/index.js#L344-L349 |
|
47,174 | Jam3/f1 | index.js | function(parsersDefinitions) {
// check that the parsersDefinitions is an object
if(typeof parsersDefinitions !== 'object' || Array.isArray(parsersDefinitions)) {
throw new Error('parsers should be an Object that contains arrays of functions under init and update');
}
this.parser = this.parser || getParser();
this.parser.add(parsersDefinitions);
return this;
} | javascript | function(parsersDefinitions) {
// check that the parsersDefinitions is an object
if(typeof parsersDefinitions !== 'object' || Array.isArray(parsersDefinitions)) {
throw new Error('parsers should be an Object that contains arrays of functions under init and update');
}
this.parser = this.parser || getParser();
this.parser.add(parsersDefinitions);
return this;
} | [
"function",
"(",
"parsersDefinitions",
")",
"{",
"// check that the parsersDefinitions is an object",
"if",
"(",
"typeof",
"parsersDefinitions",
"!==",
"'object'",
"||",
"Array",
".",
"isArray",
"(",
"parsersDefinitions",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'parsers should be an Object that contains arrays of functions under init and update'",
")",
";",
"}",
"this",
".",
"parser",
"=",
"this",
".",
"parser",
"||",
"getParser",
"(",
")",
";",
"this",
".",
"parser",
".",
"add",
"(",
"parsersDefinitions",
")",
";",
"return",
"this",
";",
"}"
]
| `f1` can target many different platforms. How it does this is by using parsers which
can target different platforms. Parsers apply calculated state objects to targets.
If working with the dom for instance your state could define values which will be applied
by the parser to the dom elements style object.
When calling parsers pass in an Object that can contain variables init, and update. Both should contain
an Array's of functions which will be used to either init or update ui.
init's functions will receive: states definition, targets definition, and transitions definition.
update functions will receive: target and state. Where target could be for instance a dom element and
state is the currently calculated state.
@param {Object} parsersDefinitions an Object which may define arrays of init and update functions
@chainable | [
"f1",
"can",
"target",
"many",
"different",
"platforms",
".",
"How",
"it",
"does",
"this",
"is",
"by",
"using",
"parsers",
"which",
"can",
"target",
"different",
"platforms",
".",
"Parsers",
"apply",
"calculated",
"state",
"objects",
"to",
"targets",
"."
]
| 31bf0f9f4491f08d8b453aff744ba22ceab94607 | https://github.com/Jam3/f1/blob/31bf0f9f4491f08d8b453aff744ba22ceab94607/index.js#L368-L380 |
|
47,175 | Jam3/f1 | index.js | function(initState) {
if(!this.isInitialized) {
this.isInitialized = true;
var driver = this.driver;
if(!this.defStates) {
throw new Error('You must define states before attempting to call init');
} else if(!this.defTransitions) {
throw new Error('You must define transitions before attempting to call init');
} else if(!this.parser) {
throw new Error('You must define parsers before attempting to call init');
} else if(!this.defTargets) {
throw new Error('You must define targets before attempting to call init');
} else {
parseStates(driver, this.defStates);
parseTransitions(driver, this.defStates, this.defTransitions);
this.parser.init(this.defStates, this.defTargets, this.defTransitions);
driver.init(initState);
}
if(global.__f1__) {
global.__f1__.init(this);
}
}
return this;
} | javascript | function(initState) {
if(!this.isInitialized) {
this.isInitialized = true;
var driver = this.driver;
if(!this.defStates) {
throw new Error('You must define states before attempting to call init');
} else if(!this.defTransitions) {
throw new Error('You must define transitions before attempting to call init');
} else if(!this.parser) {
throw new Error('You must define parsers before attempting to call init');
} else if(!this.defTargets) {
throw new Error('You must define targets before attempting to call init');
} else {
parseStates(driver, this.defStates);
parseTransitions(driver, this.defStates, this.defTransitions);
this.parser.init(this.defStates, this.defTargets, this.defTransitions);
driver.init(initState);
}
if(global.__f1__) {
global.__f1__.init(this);
}
}
return this;
} | [
"function",
"(",
"initState",
")",
"{",
"if",
"(",
"!",
"this",
".",
"isInitialized",
")",
"{",
"this",
".",
"isInitialized",
"=",
"true",
";",
"var",
"driver",
"=",
"this",
".",
"driver",
";",
"if",
"(",
"!",
"this",
".",
"defStates",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You must define states before attempting to call init'",
")",
";",
"}",
"else",
"if",
"(",
"!",
"this",
".",
"defTransitions",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You must define transitions before attempting to call init'",
")",
";",
"}",
"else",
"if",
"(",
"!",
"this",
".",
"parser",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You must define parsers before attempting to call init'",
")",
";",
"}",
"else",
"if",
"(",
"!",
"this",
".",
"defTargets",
")",
"{",
"throw",
"new",
"Error",
"(",
"'You must define targets before attempting to call init'",
")",
";",
"}",
"else",
"{",
"parseStates",
"(",
"driver",
",",
"this",
".",
"defStates",
")",
";",
"parseTransitions",
"(",
"driver",
",",
"this",
".",
"defStates",
",",
"this",
".",
"defTransitions",
")",
";",
"this",
".",
"parser",
".",
"init",
"(",
"this",
".",
"defStates",
",",
"this",
".",
"defTargets",
",",
"this",
".",
"defTransitions",
")",
";",
"driver",
".",
"init",
"(",
"initState",
")",
";",
"}",
"if",
"(",
"global",
".",
"__f1__",
")",
"{",
"global",
".",
"__f1__",
".",
"init",
"(",
"this",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
]
| Initializes `f1`. `init` will throw errors if required parameters such as
states and transitions are missing. The initial state for the `f1` instance
should be passed in.
@param {String} Initial state for the `f1` instance
@chainable | [
"Initializes",
"f1",
".",
"init",
"will",
"throw",
"errors",
"if",
"required",
"parameters",
"such",
"as",
"states",
"and",
"transitions",
"are",
"missing",
".",
"The",
"initial",
"state",
"for",
"the",
"f1",
"instance",
"should",
"be",
"passed",
"in",
"."
]
| 31bf0f9f4491f08d8b453aff744ba22ceab94607 | https://github.com/Jam3/f1/blob/31bf0f9f4491f08d8b453aff744ba22ceab94607/index.js#L390-L425 |
|
47,176 | Jam3/f1 | index.js | function(pathToTarget, target, parserDefinition) {
var data = this.data;
var parser = this.parser;
var animationData;
// if parse functions were passed in then create a new parser
if(parserDefinition) {
parser = new getParser(parserDefinition);
}
// if we have a parser then apply the parsers (parsers set css etc)
if(parser) {
if(typeof pathToTarget === 'string') {
pathToTarget = pathToTarget.split('.');
}
animationData = data[ pathToTarget[ 0 ] ];
for(var i = 1, len = pathToTarget.length; i < len; i++) {
animationData = animationData[ pathToTarget[ i ] ];
}
parser.update(target, animationData);
}
} | javascript | function(pathToTarget, target, parserDefinition) {
var data = this.data;
var parser = this.parser;
var animationData;
// if parse functions were passed in then create a new parser
if(parserDefinition) {
parser = new getParser(parserDefinition);
}
// if we have a parser then apply the parsers (parsers set css etc)
if(parser) {
if(typeof pathToTarget === 'string') {
pathToTarget = pathToTarget.split('.');
}
animationData = data[ pathToTarget[ 0 ] ];
for(var i = 1, len = pathToTarget.length; i < len; i++) {
animationData = animationData[ pathToTarget[ i ] ];
}
parser.update(target, animationData);
}
} | [
"function",
"(",
"pathToTarget",
",",
"target",
",",
"parserDefinition",
")",
"{",
"var",
"data",
"=",
"this",
".",
"data",
";",
"var",
"parser",
"=",
"this",
".",
"parser",
";",
"var",
"animationData",
";",
"// if parse functions were passed in then create a new parser",
"if",
"(",
"parserDefinition",
")",
"{",
"parser",
"=",
"new",
"getParser",
"(",
"parserDefinition",
")",
";",
"}",
"// if we have a parser then apply the parsers (parsers set css etc)",
"if",
"(",
"parser",
")",
"{",
"if",
"(",
"typeof",
"pathToTarget",
"===",
"'string'",
")",
"{",
"pathToTarget",
"=",
"pathToTarget",
".",
"split",
"(",
"'.'",
")",
";",
"}",
"animationData",
"=",
"data",
"[",
"pathToTarget",
"[",
"0",
"]",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"1",
",",
"len",
"=",
"pathToTarget",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"animationData",
"=",
"animationData",
"[",
"pathToTarget",
"[",
"i",
"]",
"]",
";",
"}",
"parser",
".",
"update",
"(",
"target",
",",
"animationData",
")",
";",
"}",
"}"
]
| An advanced method where you can apply the current state f1
has calculated to any object.
Basically allows you to have one f1 object control multiple objects
or manually apply animations to objects.
@param {String} pathToTarget A path in the current state to the object you'd like to apply. The path should
be defined using dot notation. So if your state had an object named `thing` and it
contained another object you'd like to apply called `data`. Your `pathToTarget`
would be `'thing.data'`
@param {Object} target The object you'd like to apply the currently calculated state to. For instance target
could be an html element.
@param {Object} [parserDefinition] An optional Object which defines init and update functions for a parser. | [
"An",
"advanced",
"method",
"where",
"you",
"can",
"apply",
"the",
"current",
"state",
"f1",
"has",
"calculated",
"to",
"any",
"object",
"."
]
| 31bf0f9f4491f08d8b453aff744ba22ceab94607 | https://github.com/Jam3/f1/blob/31bf0f9f4491f08d8b453aff744ba22ceab94607/index.js#L510-L539 |
|
47,177 | freshout-dev/thulium | etc/EJS/EJS.js | function(options){
this.type = options.type || EJS.type;
this.cache = options.cache != null ? options.cache : EJS.cache;
this.text = options.text || null;
this.name = options.name || null;
this.ext = options.ext || EJS.ext;
this.extMatch = new RegExp(this.ext.replace(/\./, '\.'));
} | javascript | function(options){
this.type = options.type || EJS.type;
this.cache = options.cache != null ? options.cache : EJS.cache;
this.text = options.text || null;
this.name = options.name || null;
this.ext = options.ext || EJS.ext;
this.extMatch = new RegExp(this.ext.replace(/\./, '\.'));
} | [
"function",
"(",
"options",
")",
"{",
"this",
".",
"type",
"=",
"options",
".",
"type",
"||",
"EJS",
".",
"type",
";",
"this",
".",
"cache",
"=",
"options",
".",
"cache",
"!=",
"null",
"?",
"options",
".",
"cache",
":",
"EJS",
".",
"cache",
";",
"this",
".",
"text",
"=",
"options",
".",
"text",
"||",
"null",
";",
"this",
".",
"name",
"=",
"options",
".",
"name",
"||",
"null",
";",
"this",
".",
"ext",
"=",
"options",
".",
"ext",
"||",
"EJS",
".",
"ext",
";",
"this",
".",
"extMatch",
"=",
"new",
"RegExp",
"(",
"this",
".",
"ext",
".",
"replace",
"(",
"/",
"\\.",
"/",
",",
"'\\.'",
")",
")",
";",
"}"
]
| Sets options on this view to be rendered with.
@param {Object} options | [
"Sets",
"options",
"on",
"this",
"view",
"to",
"be",
"rendered",
"with",
"."
]
| ba3173e700fbe810ce13063e7ad46e9b05bb49e7 | https://github.com/freshout-dev/thulium/blob/ba3173e700fbe810ce13063e7ad46e9b05bb49e7/etc/EJS/EJS.js#L128-L135 |
|
47,178 | chjj/rondo | lib/ev.js | function(el, type, event) {
if (!el) {
// emit for ALL elements
el = document.getElementsByTagName('*');
var i = el.length;
while (i--) if (el[i].nodeType === 1) {
emit(el[i], type, event);
}
return;
}
event = event || {};
event.target = event.target || el;
event.type = event.type || type;
// simulate bubbling
while (el) {
var data = DOM.getData(el, 'events')
, handle = data && data[type];
if (handle) {
event.currentTarget = el;
var ret = handle.call(el, event);
if (ret === false || event.cancelBubble) break;
}
el = el.parentNode
|| el.ownerDocument
|| el.defaultView
|| el.parentWindow;
}
} | javascript | function(el, type, event) {
if (!el) {
// emit for ALL elements
el = document.getElementsByTagName('*');
var i = el.length;
while (i--) if (el[i].nodeType === 1) {
emit(el[i], type, event);
}
return;
}
event = event || {};
event.target = event.target || el;
event.type = event.type || type;
// simulate bubbling
while (el) {
var data = DOM.getData(el, 'events')
, handle = data && data[type];
if (handle) {
event.currentTarget = el;
var ret = handle.call(el, event);
if (ret === false || event.cancelBubble) break;
}
el = el.parentNode
|| el.ownerDocument
|| el.defaultView
|| el.parentWindow;
}
} | [
"function",
"(",
"el",
",",
"type",
",",
"event",
")",
"{",
"if",
"(",
"!",
"el",
")",
"{",
"// emit for ALL elements",
"el",
"=",
"document",
".",
"getElementsByTagName",
"(",
"'*'",
")",
";",
"var",
"i",
"=",
"el",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"if",
"(",
"el",
"[",
"i",
"]",
".",
"nodeType",
"===",
"1",
")",
"{",
"emit",
"(",
"el",
"[",
"i",
"]",
",",
"type",
",",
"event",
")",
";",
"}",
"return",
";",
"}",
"event",
"=",
"event",
"||",
"{",
"}",
";",
"event",
".",
"target",
"=",
"event",
".",
"target",
"||",
"el",
";",
"event",
".",
"type",
"=",
"event",
".",
"type",
"||",
"type",
";",
"// simulate bubbling",
"while",
"(",
"el",
")",
"{",
"var",
"data",
"=",
"DOM",
".",
"getData",
"(",
"el",
",",
"'events'",
")",
",",
"handle",
"=",
"data",
"&&",
"data",
"[",
"type",
"]",
";",
"if",
"(",
"handle",
")",
"{",
"event",
".",
"currentTarget",
"=",
"el",
";",
"var",
"ret",
"=",
"handle",
".",
"call",
"(",
"el",
",",
"event",
")",
";",
"if",
"(",
"ret",
"===",
"false",
"||",
"event",
".",
"cancelBubble",
")",
"break",
";",
"}",
"el",
"=",
"el",
".",
"parentNode",
"||",
"el",
".",
"ownerDocument",
"||",
"el",
".",
"defaultView",
"||",
"el",
".",
"parentWindow",
";",
"}",
"}"
]
| emit a custom or native event, simulate bubbling | [
"emit",
"a",
"custom",
"or",
"native",
"event",
"simulate",
"bubbling"
]
| 5a0643a2e4ce74e25240517e1cf423df5a188008 | https://github.com/chjj/rondo/blob/5a0643a2e4ce74e25240517e1cf423df5a188008/lib/ev.js#L366-L397 |
|
47,179 | parsnick/laravel-elixir-bowerbundle | src/Package.js | Package | function Package(name)
{
var dotBowerJson = Package._readBowerJson(name) || {};
var overrides = globalOverrides[name] || {};
this.name = name;
this.installed = !! dotBowerJson.name;
this.main = overrides.main || dotBowerJson.main || [];
this.dependencies = overrides.dependencies || dotBowerJson.dependencies || [];
} | javascript | function Package(name)
{
var dotBowerJson = Package._readBowerJson(name) || {};
var overrides = globalOverrides[name] || {};
this.name = name;
this.installed = !! dotBowerJson.name;
this.main = overrides.main || dotBowerJson.main || [];
this.dependencies = overrides.dependencies || dotBowerJson.dependencies || [];
} | [
"function",
"Package",
"(",
"name",
")",
"{",
"var",
"dotBowerJson",
"=",
"Package",
".",
"_readBowerJson",
"(",
"name",
")",
"||",
"{",
"}",
";",
"var",
"overrides",
"=",
"globalOverrides",
"[",
"name",
"]",
"||",
"{",
"}",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"installed",
"=",
"!",
"!",
"dotBowerJson",
".",
"name",
";",
"this",
".",
"main",
"=",
"overrides",
".",
"main",
"||",
"dotBowerJson",
".",
"main",
"||",
"[",
"]",
";",
"this",
".",
"dependencies",
"=",
"overrides",
".",
"dependencies",
"||",
"dotBowerJson",
".",
"dependencies",
"||",
"[",
"]",
";",
"}"
]
| Constructor for Package
@param {string} name | [
"Constructor",
"for",
"Package"
]
| f6e7df503b4abec1c721a8b56b508162f714dd71 | https://github.com/parsnick/laravel-elixir-bowerbundle/blob/f6e7df503b4abec1c721a8b56b508162f714dd71/src/Package.js#L13-L22 |
47,180 | quorrajs/Positron | lib/http/SessionMiddleware.js | StartSession | function StartSession(app, next) {
this.__app = app;
this.__next = next;
/**
* Session config
*/
this.__config = this.__app.config.get('session');
this.sessionHandler = app.sessionHandler;
} | javascript | function StartSession(app, next) {
this.__app = app;
this.__next = next;
/**
* Session config
*/
this.__config = this.__app.config.get('session');
this.sessionHandler = app.sessionHandler;
} | [
"function",
"StartSession",
"(",
"app",
",",
"next",
")",
"{",
"this",
".",
"__app",
"=",
"app",
";",
"this",
".",
"__next",
"=",
"next",
";",
"/**\n * Session config\n */",
"this",
".",
"__config",
"=",
"this",
".",
"__app",
".",
"config",
".",
"get",
"(",
"'session'",
")",
";",
"this",
".",
"sessionHandler",
"=",
"app",
".",
"sessionHandler",
";",
"}"
]
| SessionMiddleware.js
@author: Harish Anchu <[email protected]>
@copyright Copyright (c) 2015-2016, QuorraJS.
@license See LICENSE.txt | [
"SessionMiddleware",
".",
"js"
]
| a4bad5a5f581743d1885405c11ae26600fb957af | https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/http/SessionMiddleware.js#L9-L19 |
47,181 | feedhenry-raincatcher/raincatcher-angularjs | packages/angularjs-workflow/lib/workflow-process/workflow-process-steps/workflow-process-steps-controller.js | WorkflowProcessStepsController | function WorkflowProcessStepsController($scope, $state, wfmService, $timeout, $stateParams) {
var self = this;
var workorderId = $stateParams.workorderId;
function updateWorkflowState(workorder) {
//If the workflow is complete, then we can switch to the summary view.
if (wfmService.isCompleted(workorder)) {
return $state.go('app.workflowProcess.complete', {
workorderId: workorder.id
});
}
if (!wfmService.isOnStep(workorder)) {
return $state.go('app.workflowProcess.begin', {
workorderId: workorder.id
});
}
$timeout(function() {
self.workorder = workorder;
self.workflow = workorder.workflow;
self.result = workorder.results;
self.stepIndex = wfmService.getCurrentStepIdx(workorder);
self.stepCurrent = wfmService.getCurrentStep(workorder);
});
}
self.back = function() {
wfmService.previousStep(workorderId)
.then(updateWorkflowState)
.catch(console.error);
};
self.triggerCompleteStep = function(submission) {
wfmService.completeStep(workorderId, submission)
.then(updateWorkflowState)
.catch(console.error);
};
self.triggerBackStep = function() {
self.back();
};
wfmService.readWorkOrder(workorderId).then(updateWorkflowState);
} | javascript | function WorkflowProcessStepsController($scope, $state, wfmService, $timeout, $stateParams) {
var self = this;
var workorderId = $stateParams.workorderId;
function updateWorkflowState(workorder) {
//If the workflow is complete, then we can switch to the summary view.
if (wfmService.isCompleted(workorder)) {
return $state.go('app.workflowProcess.complete', {
workorderId: workorder.id
});
}
if (!wfmService.isOnStep(workorder)) {
return $state.go('app.workflowProcess.begin', {
workorderId: workorder.id
});
}
$timeout(function() {
self.workorder = workorder;
self.workflow = workorder.workflow;
self.result = workorder.results;
self.stepIndex = wfmService.getCurrentStepIdx(workorder);
self.stepCurrent = wfmService.getCurrentStep(workorder);
});
}
self.back = function() {
wfmService.previousStep(workorderId)
.then(updateWorkflowState)
.catch(console.error);
};
self.triggerCompleteStep = function(submission) {
wfmService.completeStep(workorderId, submission)
.then(updateWorkflowState)
.catch(console.error);
};
self.triggerBackStep = function() {
self.back();
};
wfmService.readWorkOrder(workorderId).then(updateWorkflowState);
} | [
"function",
"WorkflowProcessStepsController",
"(",
"$scope",
",",
"$state",
",",
"wfmService",
",",
"$timeout",
",",
"$stateParams",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"workorderId",
"=",
"$stateParams",
".",
"workorderId",
";",
"function",
"updateWorkflowState",
"(",
"workorder",
")",
"{",
"//If the workflow is complete, then we can switch to the summary view.",
"if",
"(",
"wfmService",
".",
"isCompleted",
"(",
"workorder",
")",
")",
"{",
"return",
"$state",
".",
"go",
"(",
"'app.workflowProcess.complete'",
",",
"{",
"workorderId",
":",
"workorder",
".",
"id",
"}",
")",
";",
"}",
"if",
"(",
"!",
"wfmService",
".",
"isOnStep",
"(",
"workorder",
")",
")",
"{",
"return",
"$state",
".",
"go",
"(",
"'app.workflowProcess.begin'",
",",
"{",
"workorderId",
":",
"workorder",
".",
"id",
"}",
")",
";",
"}",
"$timeout",
"(",
"function",
"(",
")",
"{",
"self",
".",
"workorder",
"=",
"workorder",
";",
"self",
".",
"workflow",
"=",
"workorder",
".",
"workflow",
";",
"self",
".",
"result",
"=",
"workorder",
".",
"results",
";",
"self",
".",
"stepIndex",
"=",
"wfmService",
".",
"getCurrentStepIdx",
"(",
"workorder",
")",
";",
"self",
".",
"stepCurrent",
"=",
"wfmService",
".",
"getCurrentStep",
"(",
"workorder",
")",
";",
"}",
")",
";",
"}",
"self",
".",
"back",
"=",
"function",
"(",
")",
"{",
"wfmService",
".",
"previousStep",
"(",
"workorderId",
")",
".",
"then",
"(",
"updateWorkflowState",
")",
".",
"catch",
"(",
"console",
".",
"error",
")",
";",
"}",
";",
"self",
".",
"triggerCompleteStep",
"=",
"function",
"(",
"submission",
")",
"{",
"wfmService",
".",
"completeStep",
"(",
"workorderId",
",",
"submission",
")",
".",
"then",
"(",
"updateWorkflowState",
")",
".",
"catch",
"(",
"console",
".",
"error",
")",
";",
"}",
";",
"self",
".",
"triggerBackStep",
"=",
"function",
"(",
")",
"{",
"self",
".",
"back",
"(",
")",
";",
"}",
";",
"wfmService",
".",
"readWorkOrder",
"(",
"workorderId",
")",
".",
"then",
"(",
"updateWorkflowState",
")",
";",
"}"
]
| Lots of this will move to core.
Here, we render the current step of the workflow to the user.
@param $scope
@param $state
@param wfmService
@param $timeout
@param $stateParams
@constructor | [
"Lots",
"of",
"this",
"will",
"move",
"to",
"core",
"."
]
| b394689227901e18871ad9edd0ec226c5e6839e1 | https://github.com/feedhenry-raincatcher/raincatcher-angularjs/blob/b394689227901e18871ad9edd0ec226c5e6839e1/packages/angularjs-workflow/lib/workflow-process/workflow-process-steps/workflow-process-steps-controller.js#L16-L60 |
47,182 | chjj/rondo | lib/zest.js | function(sel) {
var cap, param;
if (typeof sel !== 'string') {
if (sel.length > 1) {
var func = []
, i = 0
, l = sel.length;
for (; i < l; i++) {
func.push(parse(sel[i]));
}
l = func.length;
return function(el) {
for (i = 0; i < l; i++) {
if (!func[i](el)) return;
}
return true;
};
}
// optimization: shortcut
return sel[0] === '*'
? selectors['*']
: selectors.type(sel[0]);
}
switch (sel[0]) {
case '.': return selectors.attr('class', '~=', sel.substring(1));
case '#': return selectors.attr('id', '=', sel.substring(1));
case '[': cap = /^\[([\w-]+)(?:([^\w]?=)([^\]]+))?\]/.exec(sel);
return selectors.attr(cap[1], cap[2] || '-', unquote(cap[3]));
case ':': cap = /^(:[\w-]+)\(([^)]+)\)/.exec(sel);
if (cap) sel = cap[1], param = unquote(cap[2]);
return param ? selectors[sel](param) : selectors[sel];
case '*': return selectors['*'];
default: return selectors.type(sel);
}
} | javascript | function(sel) {
var cap, param;
if (typeof sel !== 'string') {
if (sel.length > 1) {
var func = []
, i = 0
, l = sel.length;
for (; i < l; i++) {
func.push(parse(sel[i]));
}
l = func.length;
return function(el) {
for (i = 0; i < l; i++) {
if (!func[i](el)) return;
}
return true;
};
}
// optimization: shortcut
return sel[0] === '*'
? selectors['*']
: selectors.type(sel[0]);
}
switch (sel[0]) {
case '.': return selectors.attr('class', '~=', sel.substring(1));
case '#': return selectors.attr('id', '=', sel.substring(1));
case '[': cap = /^\[([\w-]+)(?:([^\w]?=)([^\]]+))?\]/.exec(sel);
return selectors.attr(cap[1], cap[2] || '-', unquote(cap[3]));
case ':': cap = /^(:[\w-]+)\(([^)]+)\)/.exec(sel);
if (cap) sel = cap[1], param = unquote(cap[2]);
return param ? selectors[sel](param) : selectors[sel];
case '*': return selectors['*'];
default: return selectors.type(sel);
}
} | [
"function",
"(",
"sel",
")",
"{",
"var",
"cap",
",",
"param",
";",
"if",
"(",
"typeof",
"sel",
"!==",
"'string'",
")",
"{",
"if",
"(",
"sel",
".",
"length",
">",
"1",
")",
"{",
"var",
"func",
"=",
"[",
"]",
",",
"i",
"=",
"0",
",",
"l",
"=",
"sel",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"func",
".",
"push",
"(",
"parse",
"(",
"sel",
"[",
"i",
"]",
")",
")",
";",
"}",
"l",
"=",
"func",
".",
"length",
";",
"return",
"function",
"(",
"el",
")",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"func",
"[",
"i",
"]",
"(",
"el",
")",
")",
"return",
";",
"}",
"return",
"true",
";",
"}",
";",
"}",
"// optimization: shortcut",
"return",
"sel",
"[",
"0",
"]",
"===",
"'*'",
"?",
"selectors",
"[",
"'*'",
"]",
":",
"selectors",
".",
"type",
"(",
"sel",
"[",
"0",
"]",
")",
";",
"}",
"switch",
"(",
"sel",
"[",
"0",
"]",
")",
"{",
"case",
"'.'",
":",
"return",
"selectors",
".",
"attr",
"(",
"'class'",
",",
"'~='",
",",
"sel",
".",
"substring",
"(",
"1",
")",
")",
";",
"case",
"'#'",
":",
"return",
"selectors",
".",
"attr",
"(",
"'id'",
",",
"'='",
",",
"sel",
".",
"substring",
"(",
"1",
")",
")",
";",
"case",
"'['",
":",
"cap",
"=",
"/",
"^\\[([\\w-]+)(?:([^\\w]?=)([^\\]]+))?\\]",
"/",
".",
"exec",
"(",
"sel",
")",
";",
"return",
"selectors",
".",
"attr",
"(",
"cap",
"[",
"1",
"]",
",",
"cap",
"[",
"2",
"]",
"||",
"'-'",
",",
"unquote",
"(",
"cap",
"[",
"3",
"]",
")",
")",
";",
"case",
"':'",
":",
"cap",
"=",
"/",
"^(:[\\w-]+)\\(([^)]+)\\)",
"/",
".",
"exec",
"(",
"sel",
")",
";",
"if",
"(",
"cap",
")",
"sel",
"=",
"cap",
"[",
"1",
"]",
",",
"param",
"=",
"unquote",
"(",
"cap",
"[",
"2",
"]",
")",
";",
"return",
"param",
"?",
"selectors",
"[",
"sel",
"]",
"(",
"param",
")",
":",
"selectors",
"[",
"sel",
"]",
";",
"case",
"'*'",
":",
"return",
"selectors",
"[",
"'*'",
"]",
";",
"default",
":",
"return",
"selectors",
".",
"type",
"(",
"sel",
")",
";",
"}",
"}"
]
| Parsing
parse simple selectors, return a `test` | [
"Parsing",
"parse",
"simple",
"selectors",
"return",
"a",
"test"
]
| 5a0643a2e4ce74e25240517e1cf423df5a188008 | https://github.com/chjj/rondo/blob/5a0643a2e4ce74e25240517e1cf423df5a188008/lib/zest.js#L279-L317 |
|
47,183 | chjj/rondo | lib/zest.js | function(sel) {
var filter = []
, comb = combinators.noop
, qname
, cap
, op
, len;
// add implicit universal selectors
sel = sel.replace(/(^|\s)(:|\[|\.|#)/g, '$1*$2');
while (cap = /\s*((?:\w+|\*)(?:[.#:][^\s]+|\[[^\]]+\])*)\s*$/.exec(sel)) {
len = sel.length - cap[0].length;
cap = cap[1].split(/(?=[\[:.#])/);
if (!qname) qname = cap[0];
filter.push(comb(parse(cap)));
if (len) {
op = sel[len - 1];
// if the combinator doesn't exist,
// assume it was a whitespace.
comb = combinators[op] || combinators[op = ' '];
sel = sel.substring(0, op !== ' ' ? --len : len);
} else {
break;
}
}
// compile to a single function
filter = make(filter);
// optimize the first qname
filter.qname = qname;
return filter;
} | javascript | function(sel) {
var filter = []
, comb = combinators.noop
, qname
, cap
, op
, len;
// add implicit universal selectors
sel = sel.replace(/(^|\s)(:|\[|\.|#)/g, '$1*$2');
while (cap = /\s*((?:\w+|\*)(?:[.#:][^\s]+|\[[^\]]+\])*)\s*$/.exec(sel)) {
len = sel.length - cap[0].length;
cap = cap[1].split(/(?=[\[:.#])/);
if (!qname) qname = cap[0];
filter.push(comb(parse(cap)));
if (len) {
op = sel[len - 1];
// if the combinator doesn't exist,
// assume it was a whitespace.
comb = combinators[op] || combinators[op = ' '];
sel = sel.substring(0, op !== ' ' ? --len : len);
} else {
break;
}
}
// compile to a single function
filter = make(filter);
// optimize the first qname
filter.qname = qname;
return filter;
} | [
"function",
"(",
"sel",
")",
"{",
"var",
"filter",
"=",
"[",
"]",
",",
"comb",
"=",
"combinators",
".",
"noop",
",",
"qname",
",",
"cap",
",",
"op",
",",
"len",
";",
"// add implicit universal selectors",
"sel",
"=",
"sel",
".",
"replace",
"(",
"/",
"(^|\\s)(:|\\[|\\.|#)",
"/",
"g",
",",
"'$1*$2'",
")",
";",
"while",
"(",
"cap",
"=",
"/",
"\\s*((?:\\w+|\\*)(?:[.#:][^\\s]+|\\[[^\\]]+\\])*)\\s*$",
"/",
".",
"exec",
"(",
"sel",
")",
")",
"{",
"len",
"=",
"sel",
".",
"length",
"-",
"cap",
"[",
"0",
"]",
".",
"length",
";",
"cap",
"=",
"cap",
"[",
"1",
"]",
".",
"split",
"(",
"/",
"(?=[\\[:.#])",
"/",
")",
";",
"if",
"(",
"!",
"qname",
")",
"qname",
"=",
"cap",
"[",
"0",
"]",
";",
"filter",
".",
"push",
"(",
"comb",
"(",
"parse",
"(",
"cap",
")",
")",
")",
";",
"if",
"(",
"len",
")",
"{",
"op",
"=",
"sel",
"[",
"len",
"-",
"1",
"]",
";",
"// if the combinator doesn't exist, ",
"// assume it was a whitespace.",
"comb",
"=",
"combinators",
"[",
"op",
"]",
"||",
"combinators",
"[",
"op",
"=",
"' '",
"]",
";",
"sel",
"=",
"sel",
".",
"substring",
"(",
"0",
",",
"op",
"!==",
"' '",
"?",
"--",
"len",
":",
"len",
")",
";",
"}",
"else",
"{",
"break",
";",
"}",
"}",
"// compile to a single function",
"filter",
"=",
"make",
"(",
"filter",
")",
";",
"// optimize the first qname",
"filter",
".",
"qname",
"=",
"qname",
";",
"return",
"filter",
";",
"}"
]
| parse and compile the selector into a single filter function | [
"parse",
"and",
"compile",
"the",
"selector",
"into",
"a",
"single",
"filter",
"function"
]
| 5a0643a2e4ce74e25240517e1cf423df5a188008 | https://github.com/chjj/rondo/blob/5a0643a2e4ce74e25240517e1cf423df5a188008/lib/zest.js#L321-L355 |
|
47,184 | IonicaBizau/node-levenshtein-array | lib/index.js | LevArray | function LevArray (data, str) {
var result = [];
for (var i = 0; i < data.length; ++i) {
var cWord = data[i];
result.push({
l: LevDist(cWord, str)
, w: cWord
});
}
result.sort(function (a, b) {
return a.l > b.l ? 1 : -1;
});
return result;
} | javascript | function LevArray (data, str) {
var result = [];
for (var i = 0; i < data.length; ++i) {
var cWord = data[i];
result.push({
l: LevDist(cWord, str)
, w: cWord
});
}
result.sort(function (a, b) {
return a.l > b.l ? 1 : -1;
});
return result;
} | [
"function",
"LevArray",
"(",
"data",
",",
"str",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"cWord",
"=",
"data",
"[",
"i",
"]",
";",
"result",
".",
"push",
"(",
"{",
"l",
":",
"LevDist",
"(",
"cWord",
",",
"str",
")",
",",
"w",
":",
"cWord",
"}",
")",
";",
"}",
"result",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"a",
".",
"l",
">",
"b",
".",
"l",
"?",
"1",
":",
"-",
"1",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
]
| LevArray
Finds the Levenshtein distance of an array, sorting it then.
@name LevArray
@function
@param {Array} data An array of strings.
@param {String} str The searched string.
@return {Array} An array of objects like this (it's sorted by levdist):
- `l` (Number): The Levenshtein distance value.
- `w` (String): The word. | [
"LevArray",
"Finds",
"the",
"Levenshtein",
"distance",
"of",
"an",
"array",
"sorting",
"it",
"then",
"."
]
| d833b32773934ecc52477bcf7ae4ad2b228d8097 | https://github.com/IonicaBizau/node-levenshtein-array/blob/d833b32773934ecc52477bcf7ae4ad2b228d8097/lib/index.js#L17-L30 |
47,185 | StefanoVollono/angular-select | github-page/main.min.js | function () {
return $http({
method: 'GET',
url: 'https://api.punkapi.com/v2/beers'
}).then(function (response) {
var beerArray = response.data;
var newBeerArray = [];
beerArray.forEach( function (arrayItem) {
newBeerArray.push({
label: arrayItem.name,
value: arrayItem.name
})
});
// return processed items
return newBeerArray;
});
} | javascript | function () {
return $http({
method: 'GET',
url: 'https://api.punkapi.com/v2/beers'
}).then(function (response) {
var beerArray = response.data;
var newBeerArray = [];
beerArray.forEach( function (arrayItem) {
newBeerArray.push({
label: arrayItem.name,
value: arrayItem.name
})
});
// return processed items
return newBeerArray;
});
} | [
"function",
"(",
")",
"{",
"return",
"$http",
"(",
"{",
"method",
":",
"'GET'",
",",
"url",
":",
"'https://api.punkapi.com/v2/beers'",
"}",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"var",
"beerArray",
"=",
"response",
".",
"data",
";",
"var",
"newBeerArray",
"=",
"[",
"]",
";",
"beerArray",
".",
"forEach",
"(",
"function",
"(",
"arrayItem",
")",
"{",
"newBeerArray",
".",
"push",
"(",
"{",
"label",
":",
"arrayItem",
".",
"name",
",",
"value",
":",
"arrayItem",
".",
"name",
"}",
")",
"}",
")",
";",
"// return processed items",
"return",
"newBeerArray",
";",
"}",
")",
";",
"}"
]
| Get beer list from service | [
"Get",
"beer",
"list",
"from",
"service"
]
| b62dc06976b22a39bedadc1b67aa2039b73d8540 | https://github.com/StefanoVollono/angular-select/blob/b62dc06976b22a39bedadc1b67aa2039b73d8540/github-page/main.min.js#L43791-L43810 |
|
47,186 | quorrajs/Positron | lib/routing/routeCompiler.js | findNextSeparator | function findNextSeparator(pattern) {
if ('' == pattern) {
// return empty string if pattern is empty or false (false which can be returned by substr)
return '';
}
// first remove all placeholders from the pattern so we can find the next real static character
pattern = pattern.replace(/\{\w+\}/g, '');
return isset(pattern[0]) && (-1 != SEPARATORS.indexOf(pattern[0])) ? pattern[0] : '';
} | javascript | function findNextSeparator(pattern) {
if ('' == pattern) {
// return empty string if pattern is empty or false (false which can be returned by substr)
return '';
}
// first remove all placeholders from the pattern so we can find the next real static character
pattern = pattern.replace(/\{\w+\}/g, '');
return isset(pattern[0]) && (-1 != SEPARATORS.indexOf(pattern[0])) ? pattern[0] : '';
} | [
"function",
"findNextSeparator",
"(",
"pattern",
")",
"{",
"if",
"(",
"''",
"==",
"pattern",
")",
"{",
"// return empty string if pattern is empty or false (false which can be returned by substr)",
"return",
"''",
";",
"}",
"// first remove all placeholders from the pattern so we can find the next real static character",
"pattern",
"=",
"pattern",
".",
"replace",
"(",
"/",
"\\{\\w+\\}",
"/",
"g",
",",
"''",
")",
";",
"return",
"isset",
"(",
"pattern",
"[",
"0",
"]",
")",
"&&",
"(",
"-",
"1",
"!=",
"SEPARATORS",
".",
"indexOf",
"(",
"pattern",
"[",
"0",
"]",
")",
")",
"?",
"pattern",
"[",
"0",
"]",
":",
"''",
";",
"}"
]
| Returns the next static character in the Route pattern that will serve as a separator.
@param {String} pattern The route pattern
@return string The next static character that functions as separator (or empty string when none available) | [
"Returns",
"the",
"next",
"static",
"character",
"in",
"the",
"Route",
"pattern",
"that",
"will",
"serve",
"as",
"a",
"separator",
"."
]
| a4bad5a5f581743d1885405c11ae26600fb957af | https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/routing/routeCompiler.js#L126-L135 |
47,187 | quorrajs/Positron | lib/routing/routeCompiler.js | computeRegexp | function computeRegexp(tokens, index, firstOptional) {
var token = tokens[index];
if ('text' === token[0]) {
// Text tokens
return str.regexQuote(token[1]);
} else {
// Variable tokens
if (0 === index && 0 === firstOptional) {
// When the only token is an optional variable token, the separator is required
return str.regexQuote(token[1]) + '(?P<' + token[3] + '>' + token[2] + ')?';
} else {
var regexp = str.regexQuote(token[1]) + '(?P<' + token[3] + '>' + token[2] + ')';
if (index >= firstOptional) {
// Enclose each optional token in a subpattern to make it optional.
// "?:" means it is non-capturing, i.e. the portion of the subject string that
// matched the optional subpattern is not passed back.
regexp = "(?:" + regexp;
var nbTokens = tokens.length;
if (nbTokens - 1 == index) {
// Close the optional subpatterns
regexp += ")?".repeat(nbTokens - firstOptional - (0 === firstOptional ? 1 : 0));
}
}
return regexp;
}
}
} | javascript | function computeRegexp(tokens, index, firstOptional) {
var token = tokens[index];
if ('text' === token[0]) {
// Text tokens
return str.regexQuote(token[1]);
} else {
// Variable tokens
if (0 === index && 0 === firstOptional) {
// When the only token is an optional variable token, the separator is required
return str.regexQuote(token[1]) + '(?P<' + token[3] + '>' + token[2] + ')?';
} else {
var regexp = str.regexQuote(token[1]) + '(?P<' + token[3] + '>' + token[2] + ')';
if (index >= firstOptional) {
// Enclose each optional token in a subpattern to make it optional.
// "?:" means it is non-capturing, i.e. the portion of the subject string that
// matched the optional subpattern is not passed back.
regexp = "(?:" + regexp;
var nbTokens = tokens.length;
if (nbTokens - 1 == index) {
// Close the optional subpatterns
regexp += ")?".repeat(nbTokens - firstOptional - (0 === firstOptional ? 1 : 0));
}
}
return regexp;
}
}
} | [
"function",
"computeRegexp",
"(",
"tokens",
",",
"index",
",",
"firstOptional",
")",
"{",
"var",
"token",
"=",
"tokens",
"[",
"index",
"]",
";",
"if",
"(",
"'text'",
"===",
"token",
"[",
"0",
"]",
")",
"{",
"// Text tokens",
"return",
"str",
".",
"regexQuote",
"(",
"token",
"[",
"1",
"]",
")",
";",
"}",
"else",
"{",
"// Variable tokens",
"if",
"(",
"0",
"===",
"index",
"&&",
"0",
"===",
"firstOptional",
")",
"{",
"// When the only token is an optional variable token, the separator is required",
"return",
"str",
".",
"regexQuote",
"(",
"token",
"[",
"1",
"]",
")",
"+",
"'(?P<'",
"+",
"token",
"[",
"3",
"]",
"+",
"'>'",
"+",
"token",
"[",
"2",
"]",
"+",
"')?'",
";",
"}",
"else",
"{",
"var",
"regexp",
"=",
"str",
".",
"regexQuote",
"(",
"token",
"[",
"1",
"]",
")",
"+",
"'(?P<'",
"+",
"token",
"[",
"3",
"]",
"+",
"'>'",
"+",
"token",
"[",
"2",
"]",
"+",
"')'",
";",
"if",
"(",
"index",
">=",
"firstOptional",
")",
"{",
"// Enclose each optional token in a subpattern to make it optional.",
"// \"?:\" means it is non-capturing, i.e. the portion of the subject string that",
"// matched the optional subpattern is not passed back.",
"regexp",
"=",
"\"(?:\"",
"+",
"regexp",
";",
"var",
"nbTokens",
"=",
"tokens",
".",
"length",
";",
"if",
"(",
"nbTokens",
"-",
"1",
"==",
"index",
")",
"{",
"// Close the optional subpatterns",
"regexp",
"+=",
"\")?\"",
".",
"repeat",
"(",
"nbTokens",
"-",
"firstOptional",
"-",
"(",
"0",
"===",
"firstOptional",
"?",
"1",
":",
"0",
")",
")",
";",
"}",
"}",
"return",
"regexp",
";",
"}",
"}",
"}"
]
| Computes the regexp used to match a specific token. It can be static text or a subpattern.
@param {Array} tokens The route tokens
@param {Number} index The index of the current token
@param {Number} firstOptional The index of the first optional token
@return string The regexp pattern for a single token | [
"Computes",
"the",
"regexp",
"used",
"to",
"match",
"a",
"specific",
"token",
".",
"It",
"can",
"be",
"static",
"text",
"or",
"a",
"subpattern",
"."
]
| a4bad5a5f581743d1885405c11ae26600fb957af | https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/routing/routeCompiler.js#L145-L172 |
47,188 | quorrajs/Positron | lib/routing/routeCompiler.js | function (route) {
var staticPrefix = null;
var hostVariables = [];
var pathVariables = [];
var variables = [];
var tokens = [];
var regex = null;
var hostRegex = null;
var hostTokens = [];
var host;
if ('' !== (host = route.domain())) {
var result = compilePattern(route, host, true);
hostVariables = result['variables'];
variables = variables.concat(hostVariables);
hostTokens = result['tokens'];
hostRegex = result['regex'];
}
var path = route.getPath();
result = compilePattern(route, path, false);
staticPrefix = result['staticPrefix'];
pathVariables = result['variables'];
variables = variables.concat(pathVariables);
tokens = result['tokens'];
regex = result['regex'];
return new CompiledRoute(
staticPrefix,
regex,
tokens,
pathVariables,
hostRegex,
hostTokens,
hostVariables,
_.uniq(variables)
);
} | javascript | function (route) {
var staticPrefix = null;
var hostVariables = [];
var pathVariables = [];
var variables = [];
var tokens = [];
var regex = null;
var hostRegex = null;
var hostTokens = [];
var host;
if ('' !== (host = route.domain())) {
var result = compilePattern(route, host, true);
hostVariables = result['variables'];
variables = variables.concat(hostVariables);
hostTokens = result['tokens'];
hostRegex = result['regex'];
}
var path = route.getPath();
result = compilePattern(route, path, false);
staticPrefix = result['staticPrefix'];
pathVariables = result['variables'];
variables = variables.concat(pathVariables);
tokens = result['tokens'];
regex = result['regex'];
return new CompiledRoute(
staticPrefix,
regex,
tokens,
pathVariables,
hostRegex,
hostTokens,
hostVariables,
_.uniq(variables)
);
} | [
"function",
"(",
"route",
")",
"{",
"var",
"staticPrefix",
"=",
"null",
";",
"var",
"hostVariables",
"=",
"[",
"]",
";",
"var",
"pathVariables",
"=",
"[",
"]",
";",
"var",
"variables",
"=",
"[",
"]",
";",
"var",
"tokens",
"=",
"[",
"]",
";",
"var",
"regex",
"=",
"null",
";",
"var",
"hostRegex",
"=",
"null",
";",
"var",
"hostTokens",
"=",
"[",
"]",
";",
"var",
"host",
";",
"if",
"(",
"''",
"!==",
"(",
"host",
"=",
"route",
".",
"domain",
"(",
")",
")",
")",
"{",
"var",
"result",
"=",
"compilePattern",
"(",
"route",
",",
"host",
",",
"true",
")",
";",
"hostVariables",
"=",
"result",
"[",
"'variables'",
"]",
";",
"variables",
"=",
"variables",
".",
"concat",
"(",
"hostVariables",
")",
";",
"hostTokens",
"=",
"result",
"[",
"'tokens'",
"]",
";",
"hostRegex",
"=",
"result",
"[",
"'regex'",
"]",
";",
"}",
"var",
"path",
"=",
"route",
".",
"getPath",
"(",
")",
";",
"result",
"=",
"compilePattern",
"(",
"route",
",",
"path",
",",
"false",
")",
";",
"staticPrefix",
"=",
"result",
"[",
"'staticPrefix'",
"]",
";",
"pathVariables",
"=",
"result",
"[",
"'variables'",
"]",
";",
"variables",
"=",
"variables",
".",
"concat",
"(",
"pathVariables",
")",
";",
"tokens",
"=",
"result",
"[",
"'tokens'",
"]",
";",
"regex",
"=",
"result",
"[",
"'regex'",
"]",
";",
"return",
"new",
"CompiledRoute",
"(",
"staticPrefix",
",",
"regex",
",",
"tokens",
",",
"pathVariables",
",",
"hostRegex",
",",
"hostTokens",
",",
"hostVariables",
",",
"_",
".",
"uniq",
"(",
"variables",
")",
")",
";",
"}"
]
| Compiles the current route instance.
@param route A Route instance
@return CompiledRoute A CompiledRoute instance | [
"Compiles",
"the",
"current",
"route",
"instance",
"."
]
| a4bad5a5f581743d1885405c11ae26600fb957af | https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/routing/routeCompiler.js#L182-L225 |
|
47,189 | quorrajs/Positron | lib/support/utils.js | acceptParams | function acceptParams(str, index) {
var parts = str.split(/ *; */);
var ret = {value: parts[0], quality: 1, params: {}, originalIndex: index};
for (var i = 1; i < parts.length; ++i) {
var pms = parts[i].split(/ *= */);
if ('q' == pms[0]) {
ret.quality = parseFloat(pms[1]);
} else {
ret.params[pms[0]] = pms[1];
}
}
return ret;
} | javascript | function acceptParams(str, index) {
var parts = str.split(/ *; */);
var ret = {value: parts[0], quality: 1, params: {}, originalIndex: index};
for (var i = 1; i < parts.length; ++i) {
var pms = parts[i].split(/ *= */);
if ('q' == pms[0]) {
ret.quality = parseFloat(pms[1]);
} else {
ret.params[pms[0]] = pms[1];
}
}
return ret;
} | [
"function",
"acceptParams",
"(",
"str",
",",
"index",
")",
"{",
"var",
"parts",
"=",
"str",
".",
"split",
"(",
"/",
" *; *",
"/",
")",
";",
"var",
"ret",
"=",
"{",
"value",
":",
"parts",
"[",
"0",
"]",
",",
"quality",
":",
"1",
",",
"params",
":",
"{",
"}",
",",
"originalIndex",
":",
"index",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"parts",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"pms",
"=",
"parts",
"[",
"i",
"]",
".",
"split",
"(",
"/",
" *= *",
"/",
")",
";",
"if",
"(",
"'q'",
"==",
"pms",
"[",
"0",
"]",
")",
"{",
"ret",
".",
"quality",
"=",
"parseFloat",
"(",
"pms",
"[",
"1",
"]",
")",
";",
"}",
"else",
"{",
"ret",
".",
"params",
"[",
"pms",
"[",
"0",
"]",
"]",
"=",
"pms",
"[",
"1",
"]",
";",
"}",
"}",
"return",
"ret",
";",
"}"
]
| Parse accept params `str` returning an
object with `.value`, `.quality` and `.params`.
also includes `.originalIndex` for stable sorting
@param {String} str
@return {Object} | [
"Parse",
"accept",
"params",
"str",
"returning",
"an",
"object",
"with",
".",
"value",
".",
"quality",
"and",
".",
"params",
".",
"also",
"includes",
".",
"originalIndex",
"for",
"stable",
"sorting"
]
| a4bad5a5f581743d1885405c11ae26600fb957af | https://github.com/quorrajs/Positron/blob/a4bad5a5f581743d1885405c11ae26600fb957af/lib/support/utils.js#L282-L296 |
47,190 | smikes/pure-fts | lib/thaw.js | parseJSON | function parseJSON(buf, cb) {
try {
cb(null, JSON.parse(buf));
} catch (err) {
return cb(err);
}
} | javascript | function parseJSON(buf, cb) {
try {
cb(null, JSON.parse(buf));
} catch (err) {
return cb(err);
}
} | [
"function",
"parseJSON",
"(",
"buf",
",",
"cb",
")",
"{",
"try",
"{",
"cb",
"(",
"null",
",",
"JSON",
".",
"parse",
"(",
"buf",
")",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"}"
]
| convert thrown exceptions into callback err | [
"convert",
"thrown",
"exceptions",
"into",
"callback",
"err"
]
| 157db4136d3e99f00e1791a070f7fd64c7eadfb6 | https://github.com/smikes/pure-fts/blob/157db4136d3e99f00e1791a070f7fd64c7eadfb6/lib/thaw.js#L46-L52 |
47,191 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | multiMapSet | function multiMapSet(multimap, key, value) {
if (!multimap.has(key)) {
multimap.set(key, new Set());
}
const values = multimap.get(key);
if (!values.has(value)) {
values.add(value);
return true;
}
return false;
} | javascript | function multiMapSet(multimap, key, value) {
if (!multimap.has(key)) {
multimap.set(key, new Set());
}
const values = multimap.get(key);
if (!values.has(value)) {
values.add(value);
return true;
}
return false;
} | [
"function",
"multiMapSet",
"(",
"multimap",
",",
"key",
",",
"value",
")",
"{",
"if",
"(",
"!",
"multimap",
".",
"has",
"(",
"key",
")",
")",
"{",
"multimap",
".",
"set",
"(",
"key",
",",
"new",
"Set",
"(",
")",
")",
";",
"}",
"const",
"values",
"=",
"multimap",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"!",
"values",
".",
"has",
"(",
"value",
")",
")",
"{",
"values",
".",
"add",
"(",
"value",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
]
| Given a multimap that uses sets to collect values,
adds the value to the set for the given key. | [
"Given",
"a",
"multimap",
"that",
"uses",
"sets",
"to",
"collect",
"values",
"adds",
"the",
"value",
"to",
"the",
"set",
"for",
"the",
"given",
"key",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L41-L51 |
47,192 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | transitiveClosure | function transitiveClosure(nodeLabels, graph) {
let madeProgress = false;
do {
madeProgress = false;
for (const [ src, values ] of Array.from(nodeLabels.entries())) {
const targets = graph[src];
if (targets) {
for (const target of targets) {
for (const value of values) {
madeProgress = multiMapSet(nodeLabels, target, value) || madeProgress;
}
}
}
}
} while (madeProgress);
} | javascript | function transitiveClosure(nodeLabels, graph) {
let madeProgress = false;
do {
madeProgress = false;
for (const [ src, values ] of Array.from(nodeLabels.entries())) {
const targets = graph[src];
if (targets) {
for (const target of targets) {
for (const value of values) {
madeProgress = multiMapSet(nodeLabels, target, value) || madeProgress;
}
}
}
}
} while (madeProgress);
} | [
"function",
"transitiveClosure",
"(",
"nodeLabels",
",",
"graph",
")",
"{",
"let",
"madeProgress",
"=",
"false",
";",
"do",
"{",
"madeProgress",
"=",
"false",
";",
"for",
"(",
"const",
"[",
"src",
",",
"values",
"]",
"of",
"Array",
".",
"from",
"(",
"nodeLabels",
".",
"entries",
"(",
")",
")",
")",
"{",
"const",
"targets",
"=",
"graph",
"[",
"src",
"]",
";",
"if",
"(",
"targets",
")",
"{",
"for",
"(",
"const",
"target",
"of",
"targets",
")",
"{",
"for",
"(",
"const",
"value",
"of",
"values",
")",
"{",
"madeProgress",
"=",
"multiMapSet",
"(",
"nodeLabels",
",",
"target",
",",
"value",
")",
"||",
"madeProgress",
";",
"}",
"}",
"}",
"}",
"}",
"while",
"(",
"madeProgress",
")",
";",
"}"
]
| Given a set of graph nodes to labels, propagates labels to
across edges.
@param nodeLabels a Map of nodes to labels. Modified in place.
@param graph an adjacency table such that graph[src] is a series of targets,
nodes adjacent to src. | [
"Given",
"a",
"set",
"of",
"graph",
"nodes",
"to",
"labels",
"propagates",
"labels",
"to",
"across",
"edges",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L61-L76 |
47,193 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | distrust | function distrust(msg, optAstNode) {
const { filename, line } = optAstNode || policyPath[policyPath.length - 2] || {};
const relfilename = options.basedir ? path.relative(options.basedir, filename) : filename;
report(`${ relfilename }:${ line }: ${ msg }`);
mayTrustOutput = false;
} | javascript | function distrust(msg, optAstNode) {
const { filename, line } = optAstNode || policyPath[policyPath.length - 2] || {};
const relfilename = options.basedir ? path.relative(options.basedir, filename) : filename;
report(`${ relfilename }:${ line }: ${ msg }`);
mayTrustOutput = false;
} | [
"function",
"distrust",
"(",
"msg",
",",
"optAstNode",
")",
"{",
"const",
"{",
"filename",
",",
"line",
"}",
"=",
"optAstNode",
"||",
"policyPath",
"[",
"policyPath",
".",
"length",
"-",
"2",
"]",
"||",
"{",
"}",
";",
"const",
"relfilename",
"=",
"options",
".",
"basedir",
"?",
"path",
".",
"relative",
"(",
"options",
".",
"basedir",
",",
"filename",
")",
":",
"filename",
";",
"report",
"(",
"`",
"${",
"relfilename",
"}",
"${",
"line",
"}",
"${",
"msg",
"}",
"`",
")",
";",
"mayTrustOutput",
"=",
"false",
";",
"}"
]
| Logs a message and flips a bit so that we do not bless the output of this template. | [
"Logs",
"a",
"message",
"and",
"flips",
"a",
"bit",
"so",
"that",
"we",
"do",
"not",
"bless",
"the",
"output",
"of",
"this",
"template",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L150-L155 |
47,194 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | getContainerName | function getContainerName(skip = 0) {
let element = null;
let mixin = null;
for (let i = policyPath.length - (skip * 2); (i -= 2) >= 0;) {
const policyPathElement = policyPath[i];
if (typeof policyPathElement === 'object') {
if (policyPathElement.type === 'Tag') {
element = policyPathElement.name.toLowerCase();
break;
} else if (policyPathElement.type === 'Mixin' && !policyPathElement.call) {
mixin = policyPathElement.name;
break;
}
}
}
return { element, mixin };
} | javascript | function getContainerName(skip = 0) {
let element = null;
let mixin = null;
for (let i = policyPath.length - (skip * 2); (i -= 2) >= 0;) {
const policyPathElement = policyPath[i];
if (typeof policyPathElement === 'object') {
if (policyPathElement.type === 'Tag') {
element = policyPathElement.name.toLowerCase();
break;
} else if (policyPathElement.type === 'Mixin' && !policyPathElement.call) {
mixin = policyPathElement.name;
break;
}
}
}
return { element, mixin };
} | [
"function",
"getContainerName",
"(",
"skip",
"=",
"0",
")",
"{",
"let",
"element",
"=",
"null",
";",
"let",
"mixin",
"=",
"null",
";",
"for",
"(",
"let",
"i",
"=",
"policyPath",
".",
"length",
"-",
"(",
"skip",
"*",
"2",
")",
";",
"(",
"i",
"-=",
"2",
")",
">=",
"0",
";",
")",
"{",
"const",
"policyPathElement",
"=",
"policyPath",
"[",
"i",
"]",
";",
"if",
"(",
"typeof",
"policyPathElement",
"===",
"'object'",
")",
"{",
"if",
"(",
"policyPathElement",
".",
"type",
"===",
"'Tag'",
")",
"{",
"element",
"=",
"policyPathElement",
".",
"name",
".",
"toLowerCase",
"(",
")",
";",
"break",
";",
"}",
"else",
"if",
"(",
"policyPathElement",
".",
"type",
"===",
"'Mixin'",
"&&",
"!",
"policyPathElement",
".",
"call",
")",
"{",
"mixin",
"=",
"policyPathElement",
".",
"name",
";",
"break",
";",
"}",
"}",
"}",
"return",
"{",
"element",
",",
"mixin",
"}",
";",
"}"
]
| Walk upwards to find the enclosing tag and mixin if any. | [
"Walk",
"upwards",
"to",
"find",
"the",
"enclosing",
"tag",
"and",
"mixin",
"if",
"any",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L158-L174 |
47,195 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | addGuard | function addGuard(guard, expr) {
let safeExpr = null;
if (!isWellFormed(expr)) {
expr = '{/*Malformed Expression*/}';
}
needsRuntime = true;
safeExpr = ` rt_${ unpredictableSuffix }.${ guard }(${ expr }) `;
return safeExpr;
} | javascript | function addGuard(guard, expr) {
let safeExpr = null;
if (!isWellFormed(expr)) {
expr = '{/*Malformed Expression*/}';
}
needsRuntime = true;
safeExpr = ` rt_${ unpredictableSuffix }.${ guard }(${ expr }) `;
return safeExpr;
} | [
"function",
"addGuard",
"(",
"guard",
",",
"expr",
")",
"{",
"let",
"safeExpr",
"=",
"null",
";",
"if",
"(",
"!",
"isWellFormed",
"(",
"expr",
")",
")",
"{",
"expr",
"=",
"'{/*Malformed Expression*/}'",
";",
"}",
"needsRuntime",
"=",
"true",
";",
"safeExpr",
"=",
"`",
"${",
"unpredictableSuffix",
"}",
"${",
"guard",
"}",
"${",
"expr",
"}",
"`",
";",
"return",
"safeExpr",
";",
"}"
]
| Decorate expression text with a call to a guard function. | [
"Decorate",
"expression",
"text",
"with",
"a",
"call",
"to",
"a",
"guard",
"function",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L235-L243 |
47,196 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | addScrubber | function addScrubber(scrubber, element, expr) {
let safeExpr = null;
if (!isWellFormed(expr)) {
expr = '{/*Malformed Expression*/}';
}
needsScrubber = true;
safeExpr = ` sc_${ unpredictableSuffix }.${ scrubber }(${ stringify(element || '*') }, ${ expr }) `;
return safeExpr;
} | javascript | function addScrubber(scrubber, element, expr) {
let safeExpr = null;
if (!isWellFormed(expr)) {
expr = '{/*Malformed Expression*/}';
}
needsScrubber = true;
safeExpr = ` sc_${ unpredictableSuffix }.${ scrubber }(${ stringify(element || '*') }, ${ expr }) `;
return safeExpr;
} | [
"function",
"addScrubber",
"(",
"scrubber",
",",
"element",
",",
"expr",
")",
"{",
"let",
"safeExpr",
"=",
"null",
";",
"if",
"(",
"!",
"isWellFormed",
"(",
"expr",
")",
")",
"{",
"expr",
"=",
"'{/*Malformed Expression*/}'",
";",
"}",
"needsScrubber",
"=",
"true",
";",
"safeExpr",
"=",
"`",
"${",
"unpredictableSuffix",
"}",
"${",
"scrubber",
"}",
"${",
"stringify",
"(",
"element",
"||",
"'*'",
")",
"}",
"${",
"expr",
"}",
"`",
";",
"return",
"safeExpr",
";",
"}"
]
| Decorate expression text with a call to a scrubber function that checks an entire attribute bundle at runtime. | [
"Decorate",
"expression",
"text",
"with",
"a",
"call",
"to",
"a",
"scrubber",
"function",
"that",
"checks",
"an",
"entire",
"attribute",
"bundle",
"at",
"runtime",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L247-L255 |
47,197 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | checkCodeDoesNotInterfere | function checkCodeDoesNotInterfere(astNode, exprKey, isExpression) {
let expr = astNode[exprKey];
const seen = new Set();
const type = typeof expr;
if (type !== 'string') {
// expr may be true, not "true".
// This occurs for inferred expressions like valueless attributes.
expr = `${ expr }`;
astNode[exprKey] = expr;
}
let warnedPug = false;
let warnedModule = false;
// Allows check to take into account the context in which a node appears.
// Flattened pairs of [ancestor, keyInAncestorToDescendent].
const jsAstPath = [];
function check(jsAst) {
if (jsAst && typeof jsAst === 'object' && jsAst.type === 'Identifier') {
const { name } = jsAst;
if (/^pug_/.test(name) || name === 'eval') {
if (!warnedPug) {
distrust(`Expression (${ expr }) may interfere with PUG internals ${ jsAst.name }`);
warnedPug = true;
}
} else if (name === 'require' &&
// Allow trusted plugin code to require modules they need.
!(Object.hasOwnProperty.call(astNode, 'mayRequire') && astNode.mayRequire) &&
// Allow require.moduleKeys and require.resolve but not require(moduleId).
!(jsAstPath.length && jsAstPath[jsAstPath.length - 2].type === 'MemberExpression' &&
jsAstPath[jsAstPath.length - 1] === 'object')) {
// Defang expression.
astNode[exprKey] = 'null';
// We trust trusted plugin code and PUG code to use the module's private key
// but not template code.
if (!warnedModule) {
distrust(`Expression (${ expr }) may interfere with module internals ${ jsAst.name }`);
warnedModule = true;
}
}
}
checkChildren(jsAst); // eslint-disable-line no-use-before-define
}
function checkChildren(jsAst) {
if (!seen.has(jsAst)) {
seen.add(jsAst);
const jsAstPathLength = jsAstPath.length;
jsAstPath[jsAstPathLength] = jsAst;
for (const key in jsAst) {
if (Object.hasOwnProperty.call(jsAst, key)) {
jsAstPath[jsAstPathLength + 1] = key;
check(jsAst[key]);
}
}
jsAstPath.length = jsAstPathLength;
}
}
let root = null;
try {
root = isExpression ? parseExpression(expr) : parse(expr);
} catch (exc) {
distrust(`Malformed expression (${ expr })`);
return;
}
check(root);
} | javascript | function checkCodeDoesNotInterfere(astNode, exprKey, isExpression) {
let expr = astNode[exprKey];
const seen = new Set();
const type = typeof expr;
if (type !== 'string') {
// expr may be true, not "true".
// This occurs for inferred expressions like valueless attributes.
expr = `${ expr }`;
astNode[exprKey] = expr;
}
let warnedPug = false;
let warnedModule = false;
// Allows check to take into account the context in which a node appears.
// Flattened pairs of [ancestor, keyInAncestorToDescendent].
const jsAstPath = [];
function check(jsAst) {
if (jsAst && typeof jsAst === 'object' && jsAst.type === 'Identifier') {
const { name } = jsAst;
if (/^pug_/.test(name) || name === 'eval') {
if (!warnedPug) {
distrust(`Expression (${ expr }) may interfere with PUG internals ${ jsAst.name }`);
warnedPug = true;
}
} else if (name === 'require' &&
// Allow trusted plugin code to require modules they need.
!(Object.hasOwnProperty.call(astNode, 'mayRequire') && astNode.mayRequire) &&
// Allow require.moduleKeys and require.resolve but not require(moduleId).
!(jsAstPath.length && jsAstPath[jsAstPath.length - 2].type === 'MemberExpression' &&
jsAstPath[jsAstPath.length - 1] === 'object')) {
// Defang expression.
astNode[exprKey] = 'null';
// We trust trusted plugin code and PUG code to use the module's private key
// but not template code.
if (!warnedModule) {
distrust(`Expression (${ expr }) may interfere with module internals ${ jsAst.name }`);
warnedModule = true;
}
}
}
checkChildren(jsAst); // eslint-disable-line no-use-before-define
}
function checkChildren(jsAst) {
if (!seen.has(jsAst)) {
seen.add(jsAst);
const jsAstPathLength = jsAstPath.length;
jsAstPath[jsAstPathLength] = jsAst;
for (const key in jsAst) {
if (Object.hasOwnProperty.call(jsAst, key)) {
jsAstPath[jsAstPathLength + 1] = key;
check(jsAst[key]);
}
}
jsAstPath.length = jsAstPathLength;
}
}
let root = null;
try {
root = isExpression ? parseExpression(expr) : parse(expr);
} catch (exc) {
distrust(`Malformed expression (${ expr })`);
return;
}
check(root);
} | [
"function",
"checkCodeDoesNotInterfere",
"(",
"astNode",
",",
"exprKey",
",",
"isExpression",
")",
"{",
"let",
"expr",
"=",
"astNode",
"[",
"exprKey",
"]",
";",
"const",
"seen",
"=",
"new",
"Set",
"(",
")",
";",
"const",
"type",
"=",
"typeof",
"expr",
";",
"if",
"(",
"type",
"!==",
"'string'",
")",
"{",
"// expr may be true, not \"true\".",
"// This occurs for inferred expressions like valueless attributes.",
"expr",
"=",
"`",
"${",
"expr",
"}",
"`",
";",
"astNode",
"[",
"exprKey",
"]",
"=",
"expr",
";",
"}",
"let",
"warnedPug",
"=",
"false",
";",
"let",
"warnedModule",
"=",
"false",
";",
"// Allows check to take into account the context in which a node appears.",
"// Flattened pairs of [ancestor, keyInAncestorToDescendent].",
"const",
"jsAstPath",
"=",
"[",
"]",
";",
"function",
"check",
"(",
"jsAst",
")",
"{",
"if",
"(",
"jsAst",
"&&",
"typeof",
"jsAst",
"===",
"'object'",
"&&",
"jsAst",
".",
"type",
"===",
"'Identifier'",
")",
"{",
"const",
"{",
"name",
"}",
"=",
"jsAst",
";",
"if",
"(",
"/",
"^pug_",
"/",
".",
"test",
"(",
"name",
")",
"||",
"name",
"===",
"'eval'",
")",
"{",
"if",
"(",
"!",
"warnedPug",
")",
"{",
"distrust",
"(",
"`",
"${",
"expr",
"}",
"${",
"jsAst",
".",
"name",
"}",
"`",
")",
";",
"warnedPug",
"=",
"true",
";",
"}",
"}",
"else",
"if",
"(",
"name",
"===",
"'require'",
"&&",
"// Allow trusted plugin code to require modules they need.",
"!",
"(",
"Object",
".",
"hasOwnProperty",
".",
"call",
"(",
"astNode",
",",
"'mayRequire'",
")",
"&&",
"astNode",
".",
"mayRequire",
")",
"&&",
"// Allow require.moduleKeys and require.resolve but not require(moduleId).",
"!",
"(",
"jsAstPath",
".",
"length",
"&&",
"jsAstPath",
"[",
"jsAstPath",
".",
"length",
"-",
"2",
"]",
".",
"type",
"===",
"'MemberExpression'",
"&&",
"jsAstPath",
"[",
"jsAstPath",
".",
"length",
"-",
"1",
"]",
"===",
"'object'",
")",
")",
"{",
"// Defang expression.",
"astNode",
"[",
"exprKey",
"]",
"=",
"'null'",
";",
"// We trust trusted plugin code and PUG code to use the module's private key",
"// but not template code.",
"if",
"(",
"!",
"warnedModule",
")",
"{",
"distrust",
"(",
"`",
"${",
"expr",
"}",
"${",
"jsAst",
".",
"name",
"}",
"`",
")",
";",
"warnedModule",
"=",
"true",
";",
"}",
"}",
"}",
"checkChildren",
"(",
"jsAst",
")",
";",
"// eslint-disable-line no-use-before-define",
"}",
"function",
"checkChildren",
"(",
"jsAst",
")",
"{",
"if",
"(",
"!",
"seen",
".",
"has",
"(",
"jsAst",
")",
")",
"{",
"seen",
".",
"add",
"(",
"jsAst",
")",
";",
"const",
"jsAstPathLength",
"=",
"jsAstPath",
".",
"length",
";",
"jsAstPath",
"[",
"jsAstPathLength",
"]",
"=",
"jsAst",
";",
"for",
"(",
"const",
"key",
"in",
"jsAst",
")",
"{",
"if",
"(",
"Object",
".",
"hasOwnProperty",
".",
"call",
"(",
"jsAst",
",",
"key",
")",
")",
"{",
"jsAstPath",
"[",
"jsAstPathLength",
"+",
"1",
"]",
"=",
"key",
";",
"check",
"(",
"jsAst",
"[",
"key",
"]",
")",
";",
"}",
"}",
"jsAstPath",
".",
"length",
"=",
"jsAstPathLength",
";",
"}",
"}",
"let",
"root",
"=",
"null",
";",
"try",
"{",
"root",
"=",
"isExpression",
"?",
"parseExpression",
"(",
"expr",
")",
":",
"parse",
"(",
"expr",
")",
";",
"}",
"catch",
"(",
"exc",
")",
"{",
"distrust",
"(",
"`",
"${",
"expr",
"}",
"`",
")",
";",
"return",
";",
"}",
"check",
"(",
"root",
")",
";",
"}"
]
| If user expressions have free variables like pug_html then don't bless the output because we'd have to statically analyze the generated JS to preserve output integrity. | [
"If",
"user",
"expressions",
"have",
"free",
"variables",
"like",
"pug_html",
"then",
"don",
"t",
"bless",
"the",
"output",
"because",
"we",
"d",
"have",
"to",
"statically",
"analyze",
"the",
"generated",
"JS",
"to",
"preserve",
"output",
"integrity",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L281-L349 |
47,198 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | noncifyAttrs | function noncifyAttrs(element, getValue, attrs) {
if (nonceValueExpression) {
if (element === 'script' || element === 'style' ||
(element === 'link' && (getValue('rel') || '').toLowerCase() === 'stylesheet')) {
if (attrs.findIndex(({ name }) => name === 'nonce') < 0) {
attrs[attrs.length] = {
name: 'nonce',
val: nonceValueExpression,
mustEscape: true,
};
}
}
}
} | javascript | function noncifyAttrs(element, getValue, attrs) {
if (nonceValueExpression) {
if (element === 'script' || element === 'style' ||
(element === 'link' && (getValue('rel') || '').toLowerCase() === 'stylesheet')) {
if (attrs.findIndex(({ name }) => name === 'nonce') < 0) {
attrs[attrs.length] = {
name: 'nonce',
val: nonceValueExpression,
mustEscape: true,
};
}
}
}
} | [
"function",
"noncifyAttrs",
"(",
"element",
",",
"getValue",
",",
"attrs",
")",
"{",
"if",
"(",
"nonceValueExpression",
")",
"{",
"if",
"(",
"element",
"===",
"'script'",
"||",
"element",
"===",
"'style'",
"||",
"(",
"element",
"===",
"'link'",
"&&",
"(",
"getValue",
"(",
"'rel'",
")",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
"===",
"'stylesheet'",
")",
")",
"{",
"if",
"(",
"attrs",
".",
"findIndex",
"(",
"(",
"{",
"name",
"}",
")",
"=>",
"name",
"===",
"'nonce'",
")",
"<",
"0",
")",
"{",
"attrs",
"[",
"attrs",
".",
"length",
"]",
"=",
"{",
"name",
":",
"'nonce'",
",",
"val",
":",
"nonceValueExpression",
",",
"mustEscape",
":",
"true",
",",
"}",
";",
"}",
"}",
"}",
"}"
]
| Add nonce attributes to attribute sets as needed. | [
"Add",
"nonce",
"attributes",
"to",
"attribute",
"sets",
"as",
"needed",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L352-L365 |
47,199 | mikesamuel/pug-plugin-trusted-types | packages/plugin/index.js | noncifyTag | function noncifyTag({ name, block: { nodes } }) {
if (name === 'form' && csrfInputValueExpression) {
nodes.unshift({
type: 'Conditional',
test: csrfInputValueExpression,
consequent: {
type: 'Block',
nodes: [
{
type: 'Tag',
name: 'input',
selfClosing: false,
block: {
type: 'Block',
nodes: [],
},
attrs: [
{
name: 'name',
val: stringify(csrfInputName),
mustEscape: true,
},
{
name: 'type',
val: '\'hidden\'',
mustEscape: true,
},
{
name: 'value',
val: csrfInputValueExpression,
mustEscape: true,
},
],
attributeBlocks: [],
isInline: false,
},
],
},
alternate: null,
});
}
} | javascript | function noncifyTag({ name, block: { nodes } }) {
if (name === 'form' && csrfInputValueExpression) {
nodes.unshift({
type: 'Conditional',
test: csrfInputValueExpression,
consequent: {
type: 'Block',
nodes: [
{
type: 'Tag',
name: 'input',
selfClosing: false,
block: {
type: 'Block',
nodes: [],
},
attrs: [
{
name: 'name',
val: stringify(csrfInputName),
mustEscape: true,
},
{
name: 'type',
val: '\'hidden\'',
mustEscape: true,
},
{
name: 'value',
val: csrfInputValueExpression,
mustEscape: true,
},
],
attributeBlocks: [],
isInline: false,
},
],
},
alternate: null,
});
}
} | [
"function",
"noncifyTag",
"(",
"{",
"name",
",",
"block",
":",
"{",
"nodes",
"}",
"}",
")",
"{",
"if",
"(",
"name",
"===",
"'form'",
"&&",
"csrfInputValueExpression",
")",
"{",
"nodes",
".",
"unshift",
"(",
"{",
"type",
":",
"'Conditional'",
",",
"test",
":",
"csrfInputValueExpression",
",",
"consequent",
":",
"{",
"type",
":",
"'Block'",
",",
"nodes",
":",
"[",
"{",
"type",
":",
"'Tag'",
",",
"name",
":",
"'input'",
",",
"selfClosing",
":",
"false",
",",
"block",
":",
"{",
"type",
":",
"'Block'",
",",
"nodes",
":",
"[",
"]",
",",
"}",
",",
"attrs",
":",
"[",
"{",
"name",
":",
"'name'",
",",
"val",
":",
"stringify",
"(",
"csrfInputName",
")",
",",
"mustEscape",
":",
"true",
",",
"}",
",",
"{",
"name",
":",
"'type'",
",",
"val",
":",
"'\\'hidden\\''",
",",
"mustEscape",
":",
"true",
",",
"}",
",",
"{",
"name",
":",
"'value'",
",",
"val",
":",
"csrfInputValueExpression",
",",
"mustEscape",
":",
"true",
",",
"}",
",",
"]",
",",
"attributeBlocks",
":",
"[",
"]",
",",
"isInline",
":",
"false",
",",
"}",
",",
"]",
",",
"}",
",",
"alternate",
":",
"null",
",",
"}",
")",
";",
"}",
"}"
]
| Add nonce attributes to tags as needed. | [
"Add",
"nonce",
"attributes",
"to",
"tags",
"as",
"needed",
"."
]
| 772c5aa30ca27d46dfddd654d7a60f16fa4519d6 | https://github.com/mikesamuel/pug-plugin-trusted-types/blob/772c5aa30ca27d46dfddd654d7a60f16fa4519d6/packages/plugin/index.js#L368-L409 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.