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
|
---|---|---|---|---|---|---|---|---|---|---|---|
49,900 | nattreid/tracking | assets/nTracker.js | initOnClick | function initOnClick() {
var clicks = document.querySelectorAll('[data-nctr]');
for (var i = 0; i < clicks.length; i++) {
var tag = clicks[i];
if (tag.addEventListener) {
tag.addEventListener("click", clickTrack, false);
} else {
if (tag.attachEvent) {
tag.attachEvent("onclick", clickTrack);
}
}
}
} | javascript | function initOnClick() {
var clicks = document.querySelectorAll('[data-nctr]');
for (var i = 0; i < clicks.length; i++) {
var tag = clicks[i];
if (tag.addEventListener) {
tag.addEventListener("click", clickTrack, false);
} else {
if (tag.attachEvent) {
tag.attachEvent("onclick", clickTrack);
}
}
}
} | [
"function",
"initOnClick",
"(",
")",
"{",
"var",
"clicks",
"=",
"document",
".",
"querySelectorAll",
"(",
"'[data-nctr]'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"clicks",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"tag",
"=",
"clicks",
"[",
"i",
"]",
";",
"if",
"(",
"tag",
".",
"addEventListener",
")",
"{",
"tag",
".",
"addEventListener",
"(",
"\"click\"",
",",
"clickTrack",
",",
"false",
")",
";",
"}",
"else",
"{",
"if",
"(",
"tag",
".",
"attachEvent",
")",
"{",
"tag",
".",
"attachEvent",
"(",
"\"onclick\"",
",",
"clickTrack",
")",
";",
"}",
"}",
"}",
"}"
] | Click Track on click to element | [
"Click",
"Track",
"on",
"click",
"to",
"element"
] | 5fc7c993c08774945405c79a393584ef2ed589f7 | https://github.com/nattreid/tracking/blob/5fc7c993c08774945405c79a393584ef2ed589f7/assets/nTracker.js#L159-L173 |
49,901 | nattreid/tracking | assets/nTracker.js | clickTrack | function clickTrack(event) {
var dataset = getClickDataset(event.path);
var data = [];
data.push('click=' + dataset.nctr);
data.push('browser=' + getBrowser());
if (dataset.ncval !== undefined) {
data.push('value=' + dataset.ncval);
}
if (dataset.average !== undefined) {
data.push('average=' + dataset.average);
}
if (dataset.ncsum !== undefined) {
data.push('sum=' + dataset.ncsum);
}
post(data.join('&'), clickUrl);
} | javascript | function clickTrack(event) {
var dataset = getClickDataset(event.path);
var data = [];
data.push('click=' + dataset.nctr);
data.push('browser=' + getBrowser());
if (dataset.ncval !== undefined) {
data.push('value=' + dataset.ncval);
}
if (dataset.average !== undefined) {
data.push('average=' + dataset.average);
}
if (dataset.ncsum !== undefined) {
data.push('sum=' + dataset.ncsum);
}
post(data.join('&'), clickUrl);
} | [
"function",
"clickTrack",
"(",
"event",
")",
"{",
"var",
"dataset",
"=",
"getClickDataset",
"(",
"event",
".",
"path",
")",
";",
"var",
"data",
"=",
"[",
"]",
";",
"data",
".",
"push",
"(",
"'click='",
"+",
"dataset",
".",
"nctr",
")",
";",
"data",
".",
"push",
"(",
"'browser='",
"+",
"getBrowser",
"(",
")",
")",
";",
"if",
"(",
"dataset",
".",
"ncval",
"!==",
"undefined",
")",
"{",
"data",
".",
"push",
"(",
"'value='",
"+",
"dataset",
".",
"ncval",
")",
";",
"}",
"if",
"(",
"dataset",
".",
"average",
"!==",
"undefined",
")",
"{",
"data",
".",
"push",
"(",
"'average='",
"+",
"dataset",
".",
"average",
")",
";",
"}",
"if",
"(",
"dataset",
".",
"ncsum",
"!==",
"undefined",
")",
"{",
"data",
".",
"push",
"(",
"'sum='",
"+",
"dataset",
".",
"ncsum",
")",
";",
"}",
"post",
"(",
"data",
".",
"join",
"(",
"'&'",
")",
",",
"clickUrl",
")",
";",
"}"
] | Handler for click event
@param event | [
"Handler",
"for",
"click",
"event"
] | 5fc7c993c08774945405c79a393584ef2ed589f7 | https://github.com/nattreid/tracking/blob/5fc7c993c08774945405c79a393584ef2ed589f7/assets/nTracker.js#L179-L196 |
49,902 | eliranmal/npm-package-env | lib/npm-package-env.js | init | function init(obj = {}, prevName = '') {
return new Proxy(obj, {
get (target, name) {
if (typeof name === 'symbol' || deflectedProperties.includes(name)) {
return Reflect.get(target, name);
}
ns.resetTo(prevName);
ns.push(name);
let value = process.env[ns.serialize()];
if (value) {
ns.pop();
return value;
}
return init(target, name);
},
set (target, name, val) {
ns.resetTo(prevName);
ns.push(name);
let value = String(val);
process.env[ns.serialize()] = value;
ns.pop();
return value;
}
});
} | javascript | function init(obj = {}, prevName = '') {
return new Proxy(obj, {
get (target, name) {
if (typeof name === 'symbol' || deflectedProperties.includes(name)) {
return Reflect.get(target, name);
}
ns.resetTo(prevName);
ns.push(name);
let value = process.env[ns.serialize()];
if (value) {
ns.pop();
return value;
}
return init(target, name);
},
set (target, name, val) {
ns.resetTo(prevName);
ns.push(name);
let value = String(val);
process.env[ns.serialize()] = value;
ns.pop();
return value;
}
});
} | [
"function",
"init",
"(",
"obj",
"=",
"{",
"}",
",",
"prevName",
"=",
"''",
")",
"{",
"return",
"new",
"Proxy",
"(",
"obj",
",",
"{",
"get",
"(",
"target",
",",
"name",
")",
"{",
"if",
"(",
"typeof",
"name",
"===",
"'symbol'",
"||",
"deflectedProperties",
".",
"includes",
"(",
"name",
")",
")",
"{",
"return",
"Reflect",
".",
"get",
"(",
"target",
",",
"name",
")",
";",
"}",
"ns",
".",
"resetTo",
"(",
"prevName",
")",
";",
"ns",
".",
"push",
"(",
"name",
")",
";",
"let",
"value",
"=",
"process",
".",
"env",
"[",
"ns",
".",
"serialize",
"(",
")",
"]",
";",
"if",
"(",
"value",
")",
"{",
"ns",
".",
"pop",
"(",
")",
";",
"return",
"value",
";",
"}",
"return",
"init",
"(",
"target",
",",
"name",
")",
";",
"}",
",",
"set",
"(",
"target",
",",
"name",
",",
"val",
")",
"{",
"ns",
".",
"resetTo",
"(",
"prevName",
")",
";",
"ns",
".",
"push",
"(",
"name",
")",
";",
"let",
"value",
"=",
"String",
"(",
"val",
")",
";",
"process",
".",
"env",
"[",
"ns",
".",
"serialize",
"(",
")",
"]",
"=",
"value",
";",
"ns",
".",
"pop",
"(",
")",
";",
"return",
"value",
";",
"}",
"}",
")",
";",
"}"
] | empty prevName indicates the first access in the chain | [
"empty",
"prevName",
"indicates",
"the",
"first",
"access",
"in",
"the",
"chain"
] | 4af33e9e388f72b895b27c00bbbe29407715b7b5 | https://github.com/eliranmal/npm-package-env/blob/4af33e9e388f72b895b27c00bbbe29407715b7b5/lib/npm-package-env.js#L13-L37 |
49,903 | jonschlinkert/digits | index.js | digits | function digits(val, num, ch) {
return pad(val, num - val.length, ch);
} | javascript | function digits(val, num, ch) {
return pad(val, num - val.length, ch);
} | [
"function",
"digits",
"(",
"val",
",",
"num",
",",
"ch",
")",
"{",
"return",
"pad",
"(",
"val",
",",
"num",
"-",
"val",
".",
"length",
",",
"ch",
")",
";",
"}"
] | Left pad the given `value` with the specified `number` of zeros
or alternate `character`.
```js
digits('abc', 10);
//=> '0000000000abc'
digits('abc', 10, '~');
//=> '~~~~~~~~~~abc'
```
@param {String} `value`
@param {String} `number`
@return {String} `character`
@api public | [
"Left",
"pad",
"the",
"given",
"value",
"with",
"the",
"specified",
"number",
"of",
"zeros",
"or",
"alternate",
"character",
"."
] | 81bc93f76999df57fc5da45cb5933fb331d0d8e5 | https://github.com/jonschlinkert/digits/blob/81bc93f76999df57fc5da45cb5933fb331d0d8e5/index.js#L37-L39 |
49,904 | tobkle/create-graphql-server-authorization | src/generator/getCode.js | compile | function compile(templates) {
templates.forEach(partial => {
partials[partial.name] = Handlebars.compile(partial.source);
Handlebars.registerPartial(partial.name, partials[partial.name]);
});
} | javascript | function compile(templates) {
templates.forEach(partial => {
partials[partial.name] = Handlebars.compile(partial.source);
Handlebars.registerPartial(partial.name, partials[partial.name]);
});
} | [
"function",
"compile",
"(",
"templates",
")",
"{",
"templates",
".",
"forEach",
"(",
"partial",
"=>",
"{",
"partials",
"[",
"partial",
".",
"name",
"]",
"=",
"Handlebars",
".",
"compile",
"(",
"partial",
".",
"source",
")",
";",
"Handlebars",
".",
"registerPartial",
"(",
"partial",
".",
"name",
",",
"partials",
"[",
"partial",
".",
"name",
"]",
")",
";",
"}",
")",
";",
"}"
] | define the compiler | [
"define",
"the",
"compiler"
] | d40718907f6d2bfb76fdcb4d2e0ae8ede5701456 | https://github.com/tobkle/create-graphql-server-authorization/blob/d40718907f6d2bfb76fdcb4d2e0ae8ede5701456/src/generator/getCode.js#L76-L81 |
49,905 | tobkle/create-graphql-server-authorization | src/generator/getCode.js | registerHandlebarsHelpers | function registerHandlebarsHelpers() {
Handlebars.registerHelper('foreach', function(arr, options) {
if (options.inverse && !arr.length) {
return options.inverse(this);
}
return arr
.map(function(item, index) {
item.$index = index;
item.$first = index === 0;
item.$last = index === arr.length - 1;
item.$notFirst = index !== 0;
item.$notLast = index !== arr.length - 1;
return options.fn(item);
})
.join('');
});
} | javascript | function registerHandlebarsHelpers() {
Handlebars.registerHelper('foreach', function(arr, options) {
if (options.inverse && !arr.length) {
return options.inverse(this);
}
return arr
.map(function(item, index) {
item.$index = index;
item.$first = index === 0;
item.$last = index === arr.length - 1;
item.$notFirst = index !== 0;
item.$notLast = index !== arr.length - 1;
return options.fn(item);
})
.join('');
});
} | [
"function",
"registerHandlebarsHelpers",
"(",
")",
"{",
"Handlebars",
".",
"registerHelper",
"(",
"'foreach'",
",",
"function",
"(",
"arr",
",",
"options",
")",
"{",
"if",
"(",
"options",
".",
"inverse",
"&&",
"!",
"arr",
".",
"length",
")",
"{",
"return",
"options",
".",
"inverse",
"(",
"this",
")",
";",
"}",
"return",
"arr",
".",
"map",
"(",
"function",
"(",
"item",
",",
"index",
")",
"{",
"item",
".",
"$index",
"=",
"index",
";",
"item",
".",
"$first",
"=",
"index",
"===",
"0",
";",
"item",
".",
"$last",
"=",
"index",
"===",
"arr",
".",
"length",
"-",
"1",
";",
"item",
".",
"$notFirst",
"=",
"index",
"!==",
"0",
";",
"item",
".",
"$notLast",
"=",
"index",
"!==",
"arr",
".",
"length",
"-",
"1",
";",
"return",
"options",
".",
"fn",
"(",
"item",
")",
";",
"}",
")",
".",
"join",
"(",
"''",
")",
";",
"}",
")",
";",
"}"
] | registers a helper, which could be used in the templates
@example
{{#foreach}}
{{#if $last}} console.log('this was the last element') {{/if}}
{{#if $notLast}} console.log('this was not the last one') {{/if}}
{{/foreach}} | [
"registers",
"a",
"helper",
"which",
"could",
"be",
"used",
"in",
"the",
"templates"
] | d40718907f6d2bfb76fdcb4d2e0ae8ede5701456 | https://github.com/tobkle/create-graphql-server-authorization/blob/d40718907f6d2bfb76fdcb4d2e0ae8ede5701456/src/generator/getCode.js#L179-L195 |
49,906 | yoo2001818/r6rs | src/parser.js | wrapData | function wrapData(entry, data, token) {
let symbol = wrapSymbols[entry.special];
if (!symbol) return data;
let symbolVal = new SymbolValue(symbol);
if (token) {
symbolVal.line = token.line;
symbolVal.column = token.column;
}
let result = new PairValue(symbolVal, new PairValue(data));
entry.special = null;
return result;
} | javascript | function wrapData(entry, data, token) {
let symbol = wrapSymbols[entry.special];
if (!symbol) return data;
let symbolVal = new SymbolValue(symbol);
if (token) {
symbolVal.line = token.line;
symbolVal.column = token.column;
}
let result = new PairValue(symbolVal, new PairValue(data));
entry.special = null;
return result;
} | [
"function",
"wrapData",
"(",
"entry",
",",
"data",
",",
"token",
")",
"{",
"let",
"symbol",
"=",
"wrapSymbols",
"[",
"entry",
".",
"special",
"]",
";",
"if",
"(",
"!",
"symbol",
")",
"return",
"data",
";",
"let",
"symbolVal",
"=",
"new",
"SymbolValue",
"(",
"symbol",
")",
";",
"if",
"(",
"token",
")",
"{",
"symbolVal",
".",
"line",
"=",
"token",
".",
"line",
";",
"symbolVal",
".",
"column",
"=",
"token",
".",
"column",
";",
"}",
"let",
"result",
"=",
"new",
"PairValue",
"(",
"symbolVal",
",",
"new",
"PairValue",
"(",
"data",
")",
")",
";",
"entry",
".",
"special",
"=",
"null",
";",
"return",
"result",
";",
"}"
] | Wrap the data if special flag is on. COMMENT_IGNORE should be handled differently, though. | [
"Wrap",
"the",
"data",
"if",
"special",
"flag",
"is",
"on",
".",
"COMMENT_IGNORE",
"should",
"be",
"handled",
"differently",
"though",
"."
] | 11dd18e451f7ccde6fbe31da7eac1825e3e9a439 | https://github.com/yoo2001818/r6rs/blob/11dd18e451f7ccde6fbe31da7eac1825e3e9a439/src/parser.js#L41-L52 |
49,907 | yoo2001818/r6rs | src/parser.js | pushData | function pushData(entry, data, token) {
if (entry.con === 2) {
throw injectError(new Error('Finished pair cannot have more values'),
token);
}
if (token) {
data.line = token.line;
data.column = token.column;
}
let wrappedData = wrapData(entry, data, token);
if (entry.comment) {
entry.comment = false;
return;
}
if (entry.con === 1) {
if (entry.tail == null) {
// Welp, if tail is missing, head is missing too (of course)
// I don't think this will ever be called..
entry.head = entry.tail = new PairValue(null, wrappedData);
} else {
// If not, just attach the value.
entry.tail.cdr = wrappedData;
}
entry.con = 2;
} else {
let pair = new PairValue(wrappedData, null);
if (entry.tail == null) {
// Welp, if tail is missing, head is missing too (of course)
entry.head = entry.tail = pair;
} else {
// If not, just attach the value.
entry.tail.cdr = pair;
entry.tail = pair;
}
}
if (token) {
entry.head.line = token.line;
entry.head.column = token.column;
}
} | javascript | function pushData(entry, data, token) {
if (entry.con === 2) {
throw injectError(new Error('Finished pair cannot have more values'),
token);
}
if (token) {
data.line = token.line;
data.column = token.column;
}
let wrappedData = wrapData(entry, data, token);
if (entry.comment) {
entry.comment = false;
return;
}
if (entry.con === 1) {
if (entry.tail == null) {
// Welp, if tail is missing, head is missing too (of course)
// I don't think this will ever be called..
entry.head = entry.tail = new PairValue(null, wrappedData);
} else {
// If not, just attach the value.
entry.tail.cdr = wrappedData;
}
entry.con = 2;
} else {
let pair = new PairValue(wrappedData, null);
if (entry.tail == null) {
// Welp, if tail is missing, head is missing too (of course)
entry.head = entry.tail = pair;
} else {
// If not, just attach the value.
entry.tail.cdr = pair;
entry.tail = pair;
}
}
if (token) {
entry.head.line = token.line;
entry.head.column = token.column;
}
} | [
"function",
"pushData",
"(",
"entry",
",",
"data",
",",
"token",
")",
"{",
"if",
"(",
"entry",
".",
"con",
"===",
"2",
")",
"{",
"throw",
"injectError",
"(",
"new",
"Error",
"(",
"'Finished pair cannot have more values'",
")",
",",
"token",
")",
";",
"}",
"if",
"(",
"token",
")",
"{",
"data",
".",
"line",
"=",
"token",
".",
"line",
";",
"data",
".",
"column",
"=",
"token",
".",
"column",
";",
"}",
"let",
"wrappedData",
"=",
"wrapData",
"(",
"entry",
",",
"data",
",",
"token",
")",
";",
"if",
"(",
"entry",
".",
"comment",
")",
"{",
"entry",
".",
"comment",
"=",
"false",
";",
"return",
";",
"}",
"if",
"(",
"entry",
".",
"con",
"===",
"1",
")",
"{",
"if",
"(",
"entry",
".",
"tail",
"==",
"null",
")",
"{",
"// Welp, if tail is missing, head is missing too (of course)",
"// I don't think this will ever be called..",
"entry",
".",
"head",
"=",
"entry",
".",
"tail",
"=",
"new",
"PairValue",
"(",
"null",
",",
"wrappedData",
")",
";",
"}",
"else",
"{",
"// If not, just attach the value.",
"entry",
".",
"tail",
".",
"cdr",
"=",
"wrappedData",
";",
"}",
"entry",
".",
"con",
"=",
"2",
";",
"}",
"else",
"{",
"let",
"pair",
"=",
"new",
"PairValue",
"(",
"wrappedData",
",",
"null",
")",
";",
"if",
"(",
"entry",
".",
"tail",
"==",
"null",
")",
"{",
"// Welp, if tail is missing, head is missing too (of course)",
"entry",
".",
"head",
"=",
"entry",
".",
"tail",
"=",
"pair",
";",
"}",
"else",
"{",
"// If not, just attach the value.",
"entry",
".",
"tail",
".",
"cdr",
"=",
"pair",
";",
"entry",
".",
"tail",
"=",
"pair",
";",
"}",
"}",
"if",
"(",
"token",
")",
"{",
"entry",
".",
"head",
".",
"line",
"=",
"token",
".",
"line",
";",
"entry",
".",
"head",
".",
"column",
"=",
"token",
".",
"column",
";",
"}",
"}"
] | Pushes the data into the stack entry. Note that this doesn't push the data into the stack.. | [
"Pushes",
"the",
"data",
"into",
"the",
"stack",
"entry",
".",
"Note",
"that",
"this",
"doesn",
"t",
"push",
"the",
"data",
"into",
"the",
"stack",
".."
] | 11dd18e451f7ccde6fbe31da7eac1825e3e9a439 | https://github.com/yoo2001818/r6rs/blob/11dd18e451f7ccde6fbe31da7eac1825e3e9a439/src/parser.js#L56-L95 |
49,908 | tolokoban/ToloFrameWork | ker/com/x-latex/x-latex.com.js | parseGroup | function parseGroup(tokenizer) {
// Group this functon will return.
var mrow = {tag: 'mrow', children: []};
// Last child of mrow.
var lastItem;
// Current token.
var tkn;
// Current tag.
var tag;
// Macro. This is a function with this prototype: (tokenizer, mrow).
var macro;
for(;;) {
tkn = tokenizer.next();
// End of stream.
if (!tkn) break;
// End of block.
if (tkn.typ == '}') break;
// Deal with msup.
if (tkn.typ == '^') {
if (mrow.children.length == 0) {
mrow.children.push({tag: 'mrow', children: []});
}
lastItem = mrow.children[mrow.children.length - 1];
if (lastItem.msup) {
tokenizer.fatal("Double superscript.", tkn.idx);
}
lastItem.msup = parseItemOrGroup(tokenizer);
}
else if (tkn.typ == '_') {
if (mrow.children.length == 0) {
mrow.children.push({tag: 'mrow', children: []});
}
lastItem = mrow.children[mrow.children.length - 1];
if (lastItem.msub) {
tokenizer.fatal("Double subscript.", tkn.idx);
}
lastItem.msub = parseItemOrGroup(tokenizer);
}
// Prime, double, triple or quadruple prime.
else if (tkn.typ == 'prime') {
lastItem = mrow.children[mrow.children.length - 1];
if (lastItem.msup) {
tokenizer.fatal("Double superscript because of a prime.", tkn.idx);
}
lastItem.msup = {tag: 'mo', children: tkn.txt};
}
// Beginning of a new group.
else if (tkn.typ == '{') {
mrow.children.push( parseGroup(tokenizer) );
}
// Add this leaf in the tree.
else {
tag = tokenToTag(tkn);
if (typeof tag === 'function') {
// This is a macro.
macro = tag;
tag = macro(tokenizer, mrow, tkn.idx);
if (tag) {
mrow.children.push(tag);
}
} else {
mrow.children.push(tag);
}
}
}
return mrow;
} | javascript | function parseGroup(tokenizer) {
// Group this functon will return.
var mrow = {tag: 'mrow', children: []};
// Last child of mrow.
var lastItem;
// Current token.
var tkn;
// Current tag.
var tag;
// Macro. This is a function with this prototype: (tokenizer, mrow).
var macro;
for(;;) {
tkn = tokenizer.next();
// End of stream.
if (!tkn) break;
// End of block.
if (tkn.typ == '}') break;
// Deal with msup.
if (tkn.typ == '^') {
if (mrow.children.length == 0) {
mrow.children.push({tag: 'mrow', children: []});
}
lastItem = mrow.children[mrow.children.length - 1];
if (lastItem.msup) {
tokenizer.fatal("Double superscript.", tkn.idx);
}
lastItem.msup = parseItemOrGroup(tokenizer);
}
else if (tkn.typ == '_') {
if (mrow.children.length == 0) {
mrow.children.push({tag: 'mrow', children: []});
}
lastItem = mrow.children[mrow.children.length - 1];
if (lastItem.msub) {
tokenizer.fatal("Double subscript.", tkn.idx);
}
lastItem.msub = parseItemOrGroup(tokenizer);
}
// Prime, double, triple or quadruple prime.
else if (tkn.typ == 'prime') {
lastItem = mrow.children[mrow.children.length - 1];
if (lastItem.msup) {
tokenizer.fatal("Double superscript because of a prime.", tkn.idx);
}
lastItem.msup = {tag: 'mo', children: tkn.txt};
}
// Beginning of a new group.
else if (tkn.typ == '{') {
mrow.children.push( parseGroup(tokenizer) );
}
// Add this leaf in the tree.
else {
tag = tokenToTag(tkn);
if (typeof tag === 'function') {
// This is a macro.
macro = tag;
tag = macro(tokenizer, mrow, tkn.idx);
if (tag) {
mrow.children.push(tag);
}
} else {
mrow.children.push(tag);
}
}
}
return mrow;
} | [
"function",
"parseGroup",
"(",
"tokenizer",
")",
"{",
"// Group this functon will return.",
"var",
"mrow",
"=",
"{",
"tag",
":",
"'mrow'",
",",
"children",
":",
"[",
"]",
"}",
";",
"// Last child of mrow.",
"var",
"lastItem",
";",
"// Current token.",
"var",
"tkn",
";",
"// Current tag.",
"var",
"tag",
";",
"// Macro. This is a function with this prototype: (tokenizer, mrow).",
"var",
"macro",
";",
"for",
"(",
";",
";",
")",
"{",
"tkn",
"=",
"tokenizer",
".",
"next",
"(",
")",
";",
"// End of stream.",
"if",
"(",
"!",
"tkn",
")",
"break",
";",
"// End of block.",
"if",
"(",
"tkn",
".",
"typ",
"==",
"'}'",
")",
"break",
";",
"// Deal with msup.",
"if",
"(",
"tkn",
".",
"typ",
"==",
"'^'",
")",
"{",
"if",
"(",
"mrow",
".",
"children",
".",
"length",
"==",
"0",
")",
"{",
"mrow",
".",
"children",
".",
"push",
"(",
"{",
"tag",
":",
"'mrow'",
",",
"children",
":",
"[",
"]",
"}",
")",
";",
"}",
"lastItem",
"=",
"mrow",
".",
"children",
"[",
"mrow",
".",
"children",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"lastItem",
".",
"msup",
")",
"{",
"tokenizer",
".",
"fatal",
"(",
"\"Double superscript.\"",
",",
"tkn",
".",
"idx",
")",
";",
"}",
"lastItem",
".",
"msup",
"=",
"parseItemOrGroup",
"(",
"tokenizer",
")",
";",
"}",
"else",
"if",
"(",
"tkn",
".",
"typ",
"==",
"'_'",
")",
"{",
"if",
"(",
"mrow",
".",
"children",
".",
"length",
"==",
"0",
")",
"{",
"mrow",
".",
"children",
".",
"push",
"(",
"{",
"tag",
":",
"'mrow'",
",",
"children",
":",
"[",
"]",
"}",
")",
";",
"}",
"lastItem",
"=",
"mrow",
".",
"children",
"[",
"mrow",
".",
"children",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"lastItem",
".",
"msub",
")",
"{",
"tokenizer",
".",
"fatal",
"(",
"\"Double subscript.\"",
",",
"tkn",
".",
"idx",
")",
";",
"}",
"lastItem",
".",
"msub",
"=",
"parseItemOrGroup",
"(",
"tokenizer",
")",
";",
"}",
"// Prime, double, triple or quadruple prime.",
"else",
"if",
"(",
"tkn",
".",
"typ",
"==",
"'prime'",
")",
"{",
"lastItem",
"=",
"mrow",
".",
"children",
"[",
"mrow",
".",
"children",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"lastItem",
".",
"msup",
")",
"{",
"tokenizer",
".",
"fatal",
"(",
"\"Double superscript because of a prime.\"",
",",
"tkn",
".",
"idx",
")",
";",
"}",
"lastItem",
".",
"msup",
"=",
"{",
"tag",
":",
"'mo'",
",",
"children",
":",
"tkn",
".",
"txt",
"}",
";",
"}",
"// Beginning of a new group.",
"else",
"if",
"(",
"tkn",
".",
"typ",
"==",
"'{'",
")",
"{",
"mrow",
".",
"children",
".",
"push",
"(",
"parseGroup",
"(",
"tokenizer",
")",
")",
";",
"}",
"// Add this leaf in the tree.",
"else",
"{",
"tag",
"=",
"tokenToTag",
"(",
"tkn",
")",
";",
"if",
"(",
"typeof",
"tag",
"===",
"'function'",
")",
"{",
"// This is a macro.",
"macro",
"=",
"tag",
";",
"tag",
"=",
"macro",
"(",
"tokenizer",
",",
"mrow",
",",
"tkn",
".",
"idx",
")",
";",
"if",
"(",
"tag",
")",
"{",
"mrow",
".",
"children",
".",
"push",
"(",
"tag",
")",
";",
"}",
"}",
"else",
"{",
"mrow",
".",
"children",
".",
"push",
"(",
"tag",
")",
";",
"}",
"}",
"}",
"return",
"mrow",
";",
"}"
] | Read tokens from a Tokenizer and return a group.
The end of a group is when ye reach to last token or if we encounter
the char '}'. | [
"Read",
"tokens",
"from",
"a",
"Tokenizer",
"and",
"return",
"a",
"group",
"."
] | 730845a833a9660ebfdb60ad027ebaab5ac871b6 | https://github.com/tolokoban/ToloFrameWork/blob/730845a833a9660ebfdb60ad027ebaab5ac871b6/ker/com/x-latex/x-latex.com.js#L226-L293 |
49,909 | andrewscwei/requiem | src/dom/hasAttribute.js | hasAttribute | function hasAttribute(element, name) {
assertType(element, Node, false, 'Invalid element specified');
let value = element.getAttribute(name);
if (value === '') return true;
return !noval(value);
} | javascript | function hasAttribute(element, name) {
assertType(element, Node, false, 'Invalid element specified');
let value = element.getAttribute(name);
if (value === '') return true;
return !noval(value);
} | [
"function",
"hasAttribute",
"(",
"element",
",",
"name",
")",
"{",
"assertType",
"(",
"element",
",",
"Node",
",",
"false",
",",
"'Invalid element specified'",
")",
";",
"let",
"value",
"=",
"element",
".",
"getAttribute",
"(",
"name",
")",
";",
"if",
"(",
"value",
"===",
"''",
")",
"return",
"true",
";",
"return",
"!",
"noval",
"(",
"value",
")",
";",
"}"
] | Checks to see if an element has the attribute of the specified name.
@param {Node} element - Target element.
@param {string} name - Attribute name.
@return {boolean} True if attribute with said name exists, false otherwise.
@alias module:requiem~dom.hasAttribute | [
"Checks",
"to",
"see",
"if",
"an",
"element",
"has",
"the",
"attribute",
"of",
"the",
"specified",
"name",
"."
] | c4182bfffc9841c6de5718f689ad3c2060511777 | https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/dom/hasAttribute.js#L18-L23 |
49,910 | codekirei/multiline-billboard | lib/index.js | handleStrs | function handleStrs(strs, opts) {
const len = longest(strs)
const text = strs
.map(pad(len, opts.justify))
.map(wrap(opts))
.join('')
return {len, text}
} | javascript | function handleStrs(strs, opts) {
const len = longest(strs)
const text = strs
.map(pad(len, opts.justify))
.map(wrap(opts))
.join('')
return {len, text}
} | [
"function",
"handleStrs",
"(",
"strs",
",",
"opts",
")",
"{",
"const",
"len",
"=",
"longest",
"(",
"strs",
")",
"const",
"text",
"=",
"strs",
".",
"map",
"(",
"pad",
"(",
"len",
",",
"opts",
".",
"justify",
")",
")",
".",
"map",
"(",
"wrap",
"(",
"opts",
")",
")",
".",
"join",
"(",
"''",
")",
"return",
"{",
"len",
",",
"text",
"}",
"}"
] | Builds middle of billboard from an array of strings.
@param {String[]} strs - text to put on billboard
@param {Object} opts - options for this billboard
@returns {String} formatted string for middle of billboard | [
"Builds",
"middle",
"of",
"billboard",
"from",
"an",
"array",
"of",
"strings",
"."
] | 7b1e446993bd76ac26652107c0cf01eb88d5365a | https://github.com/codekirei/multiline-billboard/blob/7b1e446993bd76ac26652107c0cf01eb88d5365a/lib/index.js#L134-L141 |
49,911 | crishernandezmaps/liqen-scrapper | src/parseDom.js | getBodyObject | function getBodyObject ($) {
const container = getContainer($)
// Convert the root element into an array
const children = []
container
.children()
.map((i, el) => {
children.push(convertToNode($(el)[0]))
})
return {
children: children
.filter(child => child !== null),
name: 'div',
attrs: {}
}
} | javascript | function getBodyObject ($) {
const container = getContainer($)
// Convert the root element into an array
const children = []
container
.children()
.map((i, el) => {
children.push(convertToNode($(el)[0]))
})
return {
children: children
.filter(child => child !== null),
name: 'div',
attrs: {}
}
} | [
"function",
"getBodyObject",
"(",
"$",
")",
"{",
"const",
"container",
"=",
"getContainer",
"(",
"$",
")",
"// Convert the root element into an array",
"const",
"children",
"=",
"[",
"]",
"container",
".",
"children",
"(",
")",
".",
"map",
"(",
"(",
"i",
",",
"el",
")",
"=>",
"{",
"children",
".",
"push",
"(",
"convertToNode",
"(",
"$",
"(",
"el",
")",
"[",
"0",
"]",
")",
")",
"}",
")",
"return",
"{",
"children",
":",
"children",
".",
"filter",
"(",
"child",
"=>",
"child",
"!==",
"null",
")",
",",
"name",
":",
"'div'",
",",
"attrs",
":",
"{",
"}",
"}",
"}"
] | Get the Body of the DOM. Return it as plain JS object | [
"Get",
"the",
"Body",
"of",
"the",
"DOM",
".",
"Return",
"it",
"as",
"plain",
"JS",
"object"
] | 0462d25359ed13fc8321e85cb6a0d87abece7218 | https://github.com/crishernandezmaps/liqen-scrapper/blob/0462d25359ed13fc8321e85cb6a0d87abece7218/src/parseDom.js#L4-L21 |
49,912 | crishernandezmaps/liqen-scrapper | src/parseDom.js | getMetadata | function getMetadata ($) {
const image = ($('figure[representativeofpage=true] img').attr('src') ||
$('meta[property="og:image"]').attr('content') ||
'')
const dateStr = ($('meta[property="article:modified_time"]').attr('content') ||
$('meta[property="article:published_time"]').attr('content') ||
$('meta[name="DC.date.issued"]').attr('content') ||
$('meta[property=date]').attr('content') ||
$('.news-body-date time').attr('datetime') ||
'').replace(' ', '')
const publishedDate = new Date(dateStr)
const author = ($('meta[name=author]').attr('content') ||
$('[itemprop=articleBody] .data [itemprop=author] [itemprop=name]').text().trim() ||
$('article .news-author [itemprop=author] [itemprop=name]').text().trim() ||
$('article [itemprop=name]').text().trim() ||
$('.main [itemprop=author]').text().trim() ||
$('.cuerpo-articulo [href^="/autor"]').text().trim() ||
$('.news-info-box-author [itemprop=author]').text().trim() ||
// For ara - Currently not working
// $('#content p.pg-bkn-dateline small').text().trim() ||
// For eldiario.es
$('#content address.dateline small').text().trim() ||
// The following 2 lines are for huffingtonpost
$('article .info .thirdparty-logo').text().trim() ||
$('article .info .name.fn').text().trim() ||
$('.detalleFullTexto .author a').text().trim() ||
'')
const title = ($('meta[property="og:title"]').attr('content') ||
'')
return {
image,
publishedDate,
source: {
author
},
title
}
} | javascript | function getMetadata ($) {
const image = ($('figure[representativeofpage=true] img').attr('src') ||
$('meta[property="og:image"]').attr('content') ||
'')
const dateStr = ($('meta[property="article:modified_time"]').attr('content') ||
$('meta[property="article:published_time"]').attr('content') ||
$('meta[name="DC.date.issued"]').attr('content') ||
$('meta[property=date]').attr('content') ||
$('.news-body-date time').attr('datetime') ||
'').replace(' ', '')
const publishedDate = new Date(dateStr)
const author = ($('meta[name=author]').attr('content') ||
$('[itemprop=articleBody] .data [itemprop=author] [itemprop=name]').text().trim() ||
$('article .news-author [itemprop=author] [itemprop=name]').text().trim() ||
$('article [itemprop=name]').text().trim() ||
$('.main [itemprop=author]').text().trim() ||
$('.cuerpo-articulo [href^="/autor"]').text().trim() ||
$('.news-info-box-author [itemprop=author]').text().trim() ||
// For ara - Currently not working
// $('#content p.pg-bkn-dateline small').text().trim() ||
// For eldiario.es
$('#content address.dateline small').text().trim() ||
// The following 2 lines are for huffingtonpost
$('article .info .thirdparty-logo').text().trim() ||
$('article .info .name.fn').text().trim() ||
$('.detalleFullTexto .author a').text().trim() ||
'')
const title = ($('meta[property="og:title"]').attr('content') ||
'')
return {
image,
publishedDate,
source: {
author
},
title
}
} | [
"function",
"getMetadata",
"(",
"$",
")",
"{",
"const",
"image",
"=",
"(",
"$",
"(",
"'figure[representativeofpage=true] img'",
")",
".",
"attr",
"(",
"'src'",
")",
"||",
"$",
"(",
"'meta[property=\"og:image\"]'",
")",
".",
"attr",
"(",
"'content'",
")",
"||",
"''",
")",
"const",
"dateStr",
"=",
"(",
"$",
"(",
"'meta[property=\"article:modified_time\"]'",
")",
".",
"attr",
"(",
"'content'",
")",
"||",
"$",
"(",
"'meta[property=\"article:published_time\"]'",
")",
".",
"attr",
"(",
"'content'",
")",
"||",
"$",
"(",
"'meta[name=\"DC.date.issued\"]'",
")",
".",
"attr",
"(",
"'content'",
")",
"||",
"$",
"(",
"'meta[property=date]'",
")",
".",
"attr",
"(",
"'content'",
")",
"||",
"$",
"(",
"'.news-body-date time'",
")",
".",
"attr",
"(",
"'datetime'",
")",
"||",
"''",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"const",
"publishedDate",
"=",
"new",
"Date",
"(",
"dateStr",
")",
"const",
"author",
"=",
"(",
"$",
"(",
"'meta[name=author]'",
")",
".",
"attr",
"(",
"'content'",
")",
"||",
"$",
"(",
"'[itemprop=articleBody] .data [itemprop=author] [itemprop=name]'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"$",
"(",
"'article .news-author [itemprop=author] [itemprop=name]'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"$",
"(",
"'article [itemprop=name]'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"$",
"(",
"'.main [itemprop=author]'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"$",
"(",
"'.cuerpo-articulo [href^=\"/autor\"]'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"$",
"(",
"'.news-info-box-author [itemprop=author]'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"// For ara - Currently not working",
"// $('#content p.pg-bkn-dateline small').text().trim() ||",
"// For eldiario.es",
"$",
"(",
"'#content address.dateline small'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"// The following 2 lines are for huffingtonpost",
"$",
"(",
"'article .info .thirdparty-logo'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"$",
"(",
"'article .info .name.fn'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"$",
"(",
"'.detalleFullTexto .author a'",
")",
".",
"text",
"(",
")",
".",
"trim",
"(",
")",
"||",
"''",
")",
"const",
"title",
"=",
"(",
"$",
"(",
"'meta[property=\"og:title\"]'",
")",
".",
"attr",
"(",
"'content'",
")",
"||",
"''",
")",
"return",
"{",
"image",
",",
"publishedDate",
",",
"source",
":",
"{",
"author",
"}",
",",
"title",
"}",
"}"
] | Get the metadata from the DOM. Return it as object | [
"Get",
"the",
"metadata",
"from",
"the",
"DOM",
".",
"Return",
"it",
"as",
"object"
] | 0462d25359ed13fc8321e85cb6a0d87abece7218 | https://github.com/crishernandezmaps/liqen-scrapper/blob/0462d25359ed13fc8321e85cb6a0d87abece7218/src/parseDom.js#L30-L72 |
49,913 | crishernandezmaps/liqen-scrapper | src/parseDom.js | convertToNode | function convertToNode (element) {
switch (element.type) {
case 'tag':
return ['a', 'p', 'strong', 'em', 'b', 'em'].indexOf(element.name) !== -1
? {
name: element.name,
attrs: filterAttributes(element.name, element.attribs),
children: element
.children
.map(child => convertToNode(child))
.filter(child => child !== null)
}
: null
case 'text':
return element.data
default:
return '---'
}
} | javascript | function convertToNode (element) {
switch (element.type) {
case 'tag':
return ['a', 'p', 'strong', 'em', 'b', 'em'].indexOf(element.name) !== -1
? {
name: element.name,
attrs: filterAttributes(element.name, element.attribs),
children: element
.children
.map(child => convertToNode(child))
.filter(child => child !== null)
}
: null
case 'text':
return element.data
default:
return '---'
}
} | [
"function",
"convertToNode",
"(",
"element",
")",
"{",
"switch",
"(",
"element",
".",
"type",
")",
"{",
"case",
"'tag'",
":",
"return",
"[",
"'a'",
",",
"'p'",
",",
"'strong'",
",",
"'em'",
",",
"'b'",
",",
"'em'",
"]",
".",
"indexOf",
"(",
"element",
".",
"name",
")",
"!==",
"-",
"1",
"?",
"{",
"name",
":",
"element",
".",
"name",
",",
"attrs",
":",
"filterAttributes",
"(",
"element",
".",
"name",
",",
"element",
".",
"attribs",
")",
",",
"children",
":",
"element",
".",
"children",
".",
"map",
"(",
"child",
"=>",
"convertToNode",
"(",
"child",
")",
")",
".",
"filter",
"(",
"child",
"=>",
"child",
"!==",
"null",
")",
"}",
":",
"null",
"case",
"'text'",
":",
"return",
"element",
".",
"data",
"default",
":",
"return",
"'---'",
"}",
"}"
] | private convert a cheerio element into a JS object representing a node | [
"private",
"convert",
"a",
"cheerio",
"element",
"into",
"a",
"JS",
"object",
"representing",
"a",
"node"
] | 0462d25359ed13fc8321e85cb6a0d87abece7218 | https://github.com/crishernandezmaps/liqen-scrapper/blob/0462d25359ed13fc8321e85cb6a0d87abece7218/src/parseDom.js#L105-L125 |
49,914 | crishernandezmaps/liqen-scrapper | src/parseDom.js | convertToText | function convertToText (object) {
switch (typeof object) {
case 'string':
return object
case 'object':
const attrs = toPairs(object.attrs)
.map(([name, value]) => `${name}="${value}"`)
const tag = [object.name].concat(attrs)
.join(' ')
const children = object
.children
.map(child => convertToText(child))
.join('')
return `<${tag}>${children}</${object.name}>`
}
return '<' + object.name + '>'
} | javascript | function convertToText (object) {
switch (typeof object) {
case 'string':
return object
case 'object':
const attrs = toPairs(object.attrs)
.map(([name, value]) => `${name}="${value}"`)
const tag = [object.name].concat(attrs)
.join(' ')
const children = object
.children
.map(child => convertToText(child))
.join('')
return `<${tag}>${children}</${object.name}>`
}
return '<' + object.name + '>'
} | [
"function",
"convertToText",
"(",
"object",
")",
"{",
"switch",
"(",
"typeof",
"object",
")",
"{",
"case",
"'string'",
":",
"return",
"object",
"case",
"'object'",
":",
"const",
"attrs",
"=",
"toPairs",
"(",
"object",
".",
"attrs",
")",
".",
"map",
"(",
"(",
"[",
"name",
",",
"value",
"]",
")",
"=>",
"`",
"${",
"name",
"}",
"${",
"value",
"}",
"`",
")",
"const",
"tag",
"=",
"[",
"object",
".",
"name",
"]",
".",
"concat",
"(",
"attrs",
")",
".",
"join",
"(",
"' '",
")",
"const",
"children",
"=",
"object",
".",
"children",
".",
"map",
"(",
"child",
"=>",
"convertToText",
"(",
"child",
")",
")",
".",
"join",
"(",
"''",
")",
"return",
"`",
"${",
"tag",
"}",
"${",
"children",
"}",
"${",
"object",
".",
"name",
"}",
"`",
"}",
"return",
"'<'",
"+",
"object",
".",
"name",
"+",
"'>'",
"}"
] | private convert a JS object node into a text | [
"private",
"convert",
"a",
"JS",
"object",
"node",
"into",
"a",
"text"
] | 0462d25359ed13fc8321e85cb6a0d87abece7218 | https://github.com/crishernandezmaps/liqen-scrapper/blob/0462d25359ed13fc8321e85cb6a0d87abece7218/src/parseDom.js#L129-L149 |
49,915 | crishernandezmaps/liqen-scrapper | src/parseDom.js | filterAttributes | function filterAttributes (name, attributes) {
const filtered = {}
if (attributes.href) {
filtered.href = attributes.href
}
return filtered
} | javascript | function filterAttributes (name, attributes) {
const filtered = {}
if (attributes.href) {
filtered.href = attributes.href
}
return filtered
} | [
"function",
"filterAttributes",
"(",
"name",
",",
"attributes",
")",
"{",
"const",
"filtered",
"=",
"{",
"}",
"if",
"(",
"attributes",
".",
"href",
")",
"{",
"filtered",
".",
"href",
"=",
"attributes",
".",
"href",
"}",
"return",
"filtered",
"}"
] | Filter the html attributes Return only the relevant ones | [
"Filter",
"the",
"html",
"attributes",
"Return",
"only",
"the",
"relevant",
"ones"
] | 0462d25359ed13fc8321e85cb6a0d87abece7218 | https://github.com/crishernandezmaps/liqen-scrapper/blob/0462d25359ed13fc8321e85cb6a0d87abece7218/src/parseDom.js#L153-L161 |
49,916 | contexttesting/reducer | build/lib/index.js | _evaluateContexts | async function _evaluateContexts(contexts = []) {
const c = Array.isArray(contexts) ? contexts : [contexts]
const ep = c.map(evaluateContext)
const res = await Promise.all(ep)
return res
} | javascript | async function _evaluateContexts(contexts = []) {
const c = Array.isArray(contexts) ? contexts : [contexts]
const ep = c.map(evaluateContext)
const res = await Promise.all(ep)
return res
} | [
"async",
"function",
"_evaluateContexts",
"(",
"contexts",
"=",
"[",
"]",
")",
"{",
"const",
"c",
"=",
"Array",
".",
"isArray",
"(",
"contexts",
")",
"?",
"contexts",
":",
"[",
"contexts",
"]",
"const",
"ep",
"=",
"c",
".",
"map",
"(",
"evaluateContext",
")",
"const",
"res",
"=",
"await",
"Promise",
".",
"all",
"(",
"ep",
")",
"return",
"res",
"}"
] | Evaluate a context or contexts in parallel.
@param {!Array<_contextTesting.ContextConstructor>} [contexts] The context constructors (class, function, object). | [
"Evaluate",
"a",
"context",
"or",
"contexts",
"in",
"parallel",
"."
] | cb5a9b80bba38fecbe44d552f2d160e6f7ad29ea | https://github.com/contexttesting/reducer/blob/cb5a9b80bba38fecbe44d552f2d160e6f7ad29ea/build/lib/index.js#L5-L10 |
49,917 | Orgun109uk/sort-by-key | lib/SortByKey.js | arraySortByKey | function arraySortByKey(data, key, reverse) {
data.sort((a, b) => {
const aw = a[key] !== undefined ? (
typeof a[key] === 'function' ?
parseInt(a[key](), 10) :
parseInt(a[key], 10)
) : 0;
const bw = b[key] !== undefined ? (
typeof b[key] === 'function' ?
parseInt(b[key](), 10) :
parseInt(b[key], 10)
) : 0;
if (aw === bw) {
return 0;
}
return reverse !== true && aw < bw ? -1 : 1;
});
} | javascript | function arraySortByKey(data, key, reverse) {
data.sort((a, b) => {
const aw = a[key] !== undefined ? (
typeof a[key] === 'function' ?
parseInt(a[key](), 10) :
parseInt(a[key], 10)
) : 0;
const bw = b[key] !== undefined ? (
typeof b[key] === 'function' ?
parseInt(b[key](), 10) :
parseInt(b[key], 10)
) : 0;
if (aw === bw) {
return 0;
}
return reverse !== true && aw < bw ? -1 : 1;
});
} | [
"function",
"arraySortByKey",
"(",
"data",
",",
"key",
",",
"reverse",
")",
"{",
"data",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"const",
"aw",
"=",
"a",
"[",
"key",
"]",
"!==",
"undefined",
"?",
"(",
"typeof",
"a",
"[",
"key",
"]",
"===",
"'function'",
"?",
"parseInt",
"(",
"a",
"[",
"key",
"]",
"(",
")",
",",
"10",
")",
":",
"parseInt",
"(",
"a",
"[",
"key",
"]",
",",
"10",
")",
")",
":",
"0",
";",
"const",
"bw",
"=",
"b",
"[",
"key",
"]",
"!==",
"undefined",
"?",
"(",
"typeof",
"b",
"[",
"key",
"]",
"===",
"'function'",
"?",
"parseInt",
"(",
"b",
"[",
"key",
"]",
"(",
")",
",",
"10",
")",
":",
"parseInt",
"(",
"b",
"[",
"key",
"]",
",",
"10",
")",
")",
":",
"0",
";",
"if",
"(",
"aw",
"===",
"bw",
")",
"{",
"return",
"0",
";",
"}",
"return",
"reverse",
"!==",
"true",
"&&",
"aw",
"<",
"bw",
"?",
"-",
"1",
":",
"1",
";",
"}",
")",
";",
"}"
] | Sort an array by the provided key.
@param {Array} data The array to sort.
@param {string} key The key to use for sorting.
@param {boolean} [reverse=false] - Reverse the order. | [
"Sort",
"an",
"array",
"by",
"the",
"provided",
"key",
"."
] | 615fe5be9cb7f0af60152e7b5ddef16d69412210 | https://github.com/Orgun109uk/sort-by-key/blob/615fe5be9cb7f0af60152e7b5ddef16d69412210/lib/SortByKey.js#L17-L36 |
49,918 | Orgun109uk/sort-by-key | lib/SortByKey.js | objectSortByKey | function objectSortByKey(data, key, reverse) {
let keys = Object.keys(data);
keys.sort((a, b) => {
const aw = data[a][key] !== undefined ? parseInt(data[a][key], 10) : 0;
const bw = data[b][key] !== undefined ? parseInt(data[b][key], 10) : 0;
if (aw === bw) {
return 0;
}
return reverse !== true && aw < bw ? -1 : 1;
});
keys.forEach((key) => {
const value = data[key];
delete data[key];
data[key] = value;
});
} | javascript | function objectSortByKey(data, key, reverse) {
let keys = Object.keys(data);
keys.sort((a, b) => {
const aw = data[a][key] !== undefined ? parseInt(data[a][key], 10) : 0;
const bw = data[b][key] !== undefined ? parseInt(data[b][key], 10) : 0;
if (aw === bw) {
return 0;
}
return reverse !== true && aw < bw ? -1 : 1;
});
keys.forEach((key) => {
const value = data[key];
delete data[key];
data[key] = value;
});
} | [
"function",
"objectSortByKey",
"(",
"data",
",",
"key",
",",
"reverse",
")",
"{",
"let",
"keys",
"=",
"Object",
".",
"keys",
"(",
"data",
")",
";",
"keys",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"const",
"aw",
"=",
"data",
"[",
"a",
"]",
"[",
"key",
"]",
"!==",
"undefined",
"?",
"parseInt",
"(",
"data",
"[",
"a",
"]",
"[",
"key",
"]",
",",
"10",
")",
":",
"0",
";",
"const",
"bw",
"=",
"data",
"[",
"b",
"]",
"[",
"key",
"]",
"!==",
"undefined",
"?",
"parseInt",
"(",
"data",
"[",
"b",
"]",
"[",
"key",
"]",
",",
"10",
")",
":",
"0",
";",
"if",
"(",
"aw",
"===",
"bw",
")",
"{",
"return",
"0",
";",
"}",
"return",
"reverse",
"!==",
"true",
"&&",
"aw",
"<",
"bw",
"?",
"-",
"1",
":",
"1",
";",
"}",
")",
";",
"keys",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"const",
"value",
"=",
"data",
"[",
"key",
"]",
";",
"delete",
"data",
"[",
"key",
"]",
";",
"data",
"[",
"key",
"]",
"=",
"value",
";",
"}",
")",
";",
"}"
] | Sort an object by the provided key.
@param {Array} data The object to sort.
@param {String} key The key to use for sorting.
@param {boolean} [reverse=false] Reverse the order. | [
"Sort",
"an",
"object",
"by",
"the",
"provided",
"key",
"."
] | 615fe5be9cb7f0af60152e7b5ddef16d69412210 | https://github.com/Orgun109uk/sort-by-key/blob/615fe5be9cb7f0af60152e7b5ddef16d69412210/lib/SortByKey.js#L45-L62 |
49,919 | kevinoid/promised-read | lib/abort-error.js | AbortError | function AbortError(message) {
// Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
if (!(this instanceof AbortError)) { return new AbortError(message); }
Error.captureStackTrace(this, AbortError);
if (message !== undefined) {
Object.defineProperty(this, 'message', {
value: String(message),
configurable: true,
writable: true
});
}
} | javascript | function AbortError(message) {
// Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message
if (!(this instanceof AbortError)) { return new AbortError(message); }
Error.captureStackTrace(this, AbortError);
if (message !== undefined) {
Object.defineProperty(this, 'message', {
value: String(message),
configurable: true,
writable: true
});
}
} | [
"function",
"AbortError",
"(",
"message",
")",
"{",
"// Like http://www.ecma-international.org/ecma-262/6.0/#sec-error-message",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"AbortError",
")",
")",
"{",
"return",
"new",
"AbortError",
"(",
"message",
")",
";",
"}",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"AbortError",
")",
";",
"if",
"(",
"message",
"!==",
"undefined",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'message'",
",",
"{",
"value",
":",
"String",
"(",
"message",
")",
",",
"configurable",
":",
"true",
",",
"writable",
":",
"true",
"}",
")",
";",
"}",
"}"
] | Constructs an AbortError.
@class Represents an error caused by an action being aborted.
@constructor
@param {string=} message Human-readable description of the error. | [
"Constructs",
"an",
"AbortError",
"."
] | c6adf477f4a64d5142363d84f7f83f5f07b8f682 | https://github.com/kevinoid/promised-read/blob/c6adf477f4a64d5142363d84f7f83f5f07b8f682/lib/abort-error.js#L16-L27 |
49,920 | buunguyen/starx | lib/index.js | starx | function starx(obj) {
if (!isGenerator(obj) && !isIterator(obj)) throw new TypeError('obj must be a generator or iterator')
return function executor(done) {
var self = this,
done = once(done || noop),
iterator = isGenerator(obj) ? obj.call(self) : obj
process.nextTick(next)
function next(err, value) {
var res, _next = once(next)
domain.create()
// iterator throws, we're done
.on('error', done)
.run(function() {
res = err ? iterator.throw(err) : iterator.next(value)
})
domain.create()
// yieldable throws, iterator is certainly not yet exhausted, so run next
.on('error', _next)
.run(function() {
wrap.call(self, res.value).call(self, function cb() {
(res.done ? done : _next).apply(null, arguments)
})
})
}
}
} | javascript | function starx(obj) {
if (!isGenerator(obj) && !isIterator(obj)) throw new TypeError('obj must be a generator or iterator')
return function executor(done) {
var self = this,
done = once(done || noop),
iterator = isGenerator(obj) ? obj.call(self) : obj
process.nextTick(next)
function next(err, value) {
var res, _next = once(next)
domain.create()
// iterator throws, we're done
.on('error', done)
.run(function() {
res = err ? iterator.throw(err) : iterator.next(value)
})
domain.create()
// yieldable throws, iterator is certainly not yet exhausted, so run next
.on('error', _next)
.run(function() {
wrap.call(self, res.value).call(self, function cb() {
(res.done ? done : _next).apply(null, arguments)
})
})
}
}
} | [
"function",
"starx",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"isGenerator",
"(",
"obj",
")",
"&&",
"!",
"isIterator",
"(",
"obj",
")",
")",
"throw",
"new",
"TypeError",
"(",
"'obj must be a generator or iterator'",
")",
"return",
"function",
"executor",
"(",
"done",
")",
"{",
"var",
"self",
"=",
"this",
",",
"done",
"=",
"once",
"(",
"done",
"||",
"noop",
")",
",",
"iterator",
"=",
"isGenerator",
"(",
"obj",
")",
"?",
"obj",
".",
"call",
"(",
"self",
")",
":",
"obj",
"process",
".",
"nextTick",
"(",
"next",
")",
"function",
"next",
"(",
"err",
",",
"value",
")",
"{",
"var",
"res",
",",
"_next",
"=",
"once",
"(",
"next",
")",
"domain",
".",
"create",
"(",
")",
"// iterator throws, we're done",
".",
"on",
"(",
"'error'",
",",
"done",
")",
".",
"run",
"(",
"function",
"(",
")",
"{",
"res",
"=",
"err",
"?",
"iterator",
".",
"throw",
"(",
"err",
")",
":",
"iterator",
".",
"next",
"(",
"value",
")",
"}",
")",
"domain",
".",
"create",
"(",
")",
"// yieldable throws, iterator is certainly not yet exhausted, so run next",
".",
"on",
"(",
"'error'",
",",
"_next",
")",
".",
"run",
"(",
"function",
"(",
")",
"{",
"wrap",
".",
"call",
"(",
"self",
",",
"res",
".",
"value",
")",
".",
"call",
"(",
"self",
",",
"function",
"cb",
"(",
")",
"{",
"(",
"res",
".",
"done",
"?",
"done",
":",
"_next",
")",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
"}",
")",
"}",
")",
"}",
"}",
"}"
] | Creates an executor for the provided generator or iterator | [
"Creates",
"an",
"executor",
"for",
"the",
"provided",
"generator",
"or",
"iterator"
] | 015653c93622012a81644dc19c9dcbc4ec897564 | https://github.com/buunguyen/starx/blob/015653c93622012a81644dc19c9dcbc4ec897564/lib/index.js#L10-L39 |
49,921 | shama/willitmerge | lib/willitmerge.js | execSeries | function execSeries(cmds, done) {
var out = [];
async.forEachSeries(cmds, function(cmd, next) {
exec(cmd, function(err, stdout, stderr) {
out.push({
stdout: stdout,
stderr: stderr,
err: err
});
next();
});
}, function() {
done(null, out);
});
} | javascript | function execSeries(cmds, done) {
var out = [];
async.forEachSeries(cmds, function(cmd, next) {
exec(cmd, function(err, stdout, stderr) {
out.push({
stdout: stdout,
stderr: stderr,
err: err
});
next();
});
}, function() {
done(null, out);
});
} | [
"function",
"execSeries",
"(",
"cmds",
",",
"done",
")",
"{",
"var",
"out",
"=",
"[",
"]",
";",
"async",
".",
"forEachSeries",
"(",
"cmds",
",",
"function",
"(",
"cmd",
",",
"next",
")",
"{",
"exec",
"(",
"cmd",
",",
"function",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
"{",
"out",
".",
"push",
"(",
"{",
"stdout",
":",
"stdout",
",",
"stderr",
":",
"stderr",
",",
"err",
":",
"err",
"}",
")",
";",
"next",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
")",
"{",
"done",
"(",
"null",
",",
"out",
")",
";",
"}",
")",
";",
"}"
] | exec commands in a series and retun the results | [
"exec",
"commands",
"in",
"a",
"series",
"and",
"retun",
"the",
"results"
] | 2fe91d05191fb05ac6da685828d109a3a5885028 | https://github.com/shama/willitmerge/blob/2fe91d05191fb05ac6da685828d109a3a5885028/lib/willitmerge.js#L273-L287 |
49,922 | shama/willitmerge | lib/willitmerge.js | parseImpact | function parseImpact(data) {
var impact = /([0-9]+) insertions\(\+\), ([0-9]+) deletions\(\-\)/i.exec(data);
if (impact) {
return Number(impact[1]) + Number(impact[2]);
}
return 0;
} | javascript | function parseImpact(data) {
var impact = /([0-9]+) insertions\(\+\), ([0-9]+) deletions\(\-\)/i.exec(data);
if (impact) {
return Number(impact[1]) + Number(impact[2]);
}
return 0;
} | [
"function",
"parseImpact",
"(",
"data",
")",
"{",
"var",
"impact",
"=",
"/",
"([0-9]+) insertions\\(\\+\\), ([0-9]+) deletions\\(\\-\\)",
"/",
"i",
".",
"exec",
"(",
"data",
")",
";",
"if",
"(",
"impact",
")",
"{",
"return",
"Number",
"(",
"impact",
"[",
"1",
"]",
")",
"+",
"Number",
"(",
"impact",
"[",
"2",
"]",
")",
";",
"}",
"return",
"0",
";",
"}"
] | parse the insertions + deletions | [
"parse",
"the",
"insertions",
"+",
"deletions"
] | 2fe91d05191fb05ac6da685828d109a3a5885028 | https://github.com/shama/willitmerge/blob/2fe91d05191fb05ac6da685828d109a3a5885028/lib/willitmerge.js#L290-L296 |
49,923 | derdesign/protos | storages/mongodb.js | MongoStorage | function MongoStorage(config) {
var self = this;
this.events = new EventEmitter();
config = protos.extend({
host: 'localhost',
port: 27017,
database: 'store',
collection: 'keyvalue',
username: '',
password: '',
safe: true
}, config);
if (typeof config.port != 'number') config.port = parseInt(config.port, 10);
this.config = config;
this.className = this.constructor.name;
app.debug(util.format('Initializing MongoStorage for %s@%s:%s', config.username, config.host, config.port));
var reportError = function(err) {
app.log(util.format("MongoStore [%s:%s] %s", config.host, config.port, err.code));
self.client = err;
}
// Set db
self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: config.safe});
// Add async task
app.addReadyTask();
// Get client
self.db.open(function(err, client) {
if (err) {
reportError(err);
} else {
// Set client
self.client = client;
// Get collection
client.collection(config.collection, function(err, collection) {
// Set collection
self.collection = collection;
// Authenticate
if (config.username && config.password) {
self.db.authenticate(config.username, config.password, function(err, success) {
if (err) {
app.log(util.format('MongoStorage: unable to authenticate %s@%s', config.username, config.host));
throw err;
} else {
// Emit initialization event
self.events.emit('init', self.db, self.client);
}
});
} else {
// Emit initialization event
self.events.emit('init', self.db, self.client);
}
});
}
});
// Flush async task
this.events.on('init', function() {
app.flushReadyTask();
});
// Set enumerable properties
protos.util.onlySetEnumerable(this, ['className', 'db']);
} | javascript | function MongoStorage(config) {
var self = this;
this.events = new EventEmitter();
config = protos.extend({
host: 'localhost',
port: 27017,
database: 'store',
collection: 'keyvalue',
username: '',
password: '',
safe: true
}, config);
if (typeof config.port != 'number') config.port = parseInt(config.port, 10);
this.config = config;
this.className = this.constructor.name;
app.debug(util.format('Initializing MongoStorage for %s@%s:%s', config.username, config.host, config.port));
var reportError = function(err) {
app.log(util.format("MongoStore [%s:%s] %s", config.host, config.port, err.code));
self.client = err;
}
// Set db
self.db = new Db(config.database, new Server(config.host, config.port, {}), {safe: config.safe});
// Add async task
app.addReadyTask();
// Get client
self.db.open(function(err, client) {
if (err) {
reportError(err);
} else {
// Set client
self.client = client;
// Get collection
client.collection(config.collection, function(err, collection) {
// Set collection
self.collection = collection;
// Authenticate
if (config.username && config.password) {
self.db.authenticate(config.username, config.password, function(err, success) {
if (err) {
app.log(util.format('MongoStorage: unable to authenticate %s@%s', config.username, config.host));
throw err;
} else {
// Emit initialization event
self.events.emit('init', self.db, self.client);
}
});
} else {
// Emit initialization event
self.events.emit('init', self.db, self.client);
}
});
}
});
// Flush async task
this.events.on('init', function() {
app.flushReadyTask();
});
// Set enumerable properties
protos.util.onlySetEnumerable(this, ['className', 'db']);
} | [
"function",
"MongoStorage",
"(",
"config",
")",
"{",
"var",
"self",
"=",
"this",
";",
"this",
".",
"events",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"config",
"=",
"protos",
".",
"extend",
"(",
"{",
"host",
":",
"'localhost'",
",",
"port",
":",
"27017",
",",
"database",
":",
"'store'",
",",
"collection",
":",
"'keyvalue'",
",",
"username",
":",
"''",
",",
"password",
":",
"''",
",",
"safe",
":",
"true",
"}",
",",
"config",
")",
";",
"if",
"(",
"typeof",
"config",
".",
"port",
"!=",
"'number'",
")",
"config",
".",
"port",
"=",
"parseInt",
"(",
"config",
".",
"port",
",",
"10",
")",
";",
"this",
".",
"config",
"=",
"config",
";",
"this",
".",
"className",
"=",
"this",
".",
"constructor",
".",
"name",
";",
"app",
".",
"debug",
"(",
"util",
".",
"format",
"(",
"'Initializing MongoStorage for %s@%s:%s'",
",",
"config",
".",
"username",
",",
"config",
".",
"host",
",",
"config",
".",
"port",
")",
")",
";",
"var",
"reportError",
"=",
"function",
"(",
"err",
")",
"{",
"app",
".",
"log",
"(",
"util",
".",
"format",
"(",
"\"MongoStore [%s:%s] %s\"",
",",
"config",
".",
"host",
",",
"config",
".",
"port",
",",
"err",
".",
"code",
")",
")",
";",
"self",
".",
"client",
"=",
"err",
";",
"}",
"// Set db",
"self",
".",
"db",
"=",
"new",
"Db",
"(",
"config",
".",
"database",
",",
"new",
"Server",
"(",
"config",
".",
"host",
",",
"config",
".",
"port",
",",
"{",
"}",
")",
",",
"{",
"safe",
":",
"config",
".",
"safe",
"}",
")",
";",
"// Add async task",
"app",
".",
"addReadyTask",
"(",
")",
";",
"// Get client",
"self",
".",
"db",
".",
"open",
"(",
"function",
"(",
"err",
",",
"client",
")",
"{",
"if",
"(",
"err",
")",
"{",
"reportError",
"(",
"err",
")",
";",
"}",
"else",
"{",
"// Set client",
"self",
".",
"client",
"=",
"client",
";",
"// Get collection",
"client",
".",
"collection",
"(",
"config",
".",
"collection",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"// Set collection",
"self",
".",
"collection",
"=",
"collection",
";",
"// Authenticate",
"if",
"(",
"config",
".",
"username",
"&&",
"config",
".",
"password",
")",
"{",
"self",
".",
"db",
".",
"authenticate",
"(",
"config",
".",
"username",
",",
"config",
".",
"password",
",",
"function",
"(",
"err",
",",
"success",
")",
"{",
"if",
"(",
"err",
")",
"{",
"app",
".",
"log",
"(",
"util",
".",
"format",
"(",
"'MongoStorage: unable to authenticate %s@%s'",
",",
"config",
".",
"username",
",",
"config",
".",
"host",
")",
")",
";",
"throw",
"err",
";",
"}",
"else",
"{",
"// Emit initialization event",
"self",
".",
"events",
".",
"emit",
"(",
"'init'",
",",
"self",
".",
"db",
",",
"self",
".",
"client",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"// Emit initialization event",
"self",
".",
"events",
".",
"emit",
"(",
"'init'",
",",
"self",
".",
"db",
",",
"self",
".",
"client",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
")",
";",
"// Flush async task",
"this",
".",
"events",
".",
"on",
"(",
"'init'",
",",
"function",
"(",
")",
"{",
"app",
".",
"flushReadyTask",
"(",
")",
";",
"}",
")",
";",
"// Set enumerable properties",
"protos",
".",
"util",
".",
"onlySetEnumerable",
"(",
"this",
",",
"[",
"'className'",
",",
"'db'",
"]",
")",
";",
"}"
] | MongoDB Storage class
@class MongoStorage
@extends Storage
@constructor
@param {object} app Application instance
@param {object} config Storage configuration | [
"MongoDB",
"Storage",
"class"
] | 0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9 | https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/storages/mongodb.js#L23-L110 |
49,924 | Mozu/mozu-theme-helpers | lib/utils/compiler/themes.js | getThemeFromPath | function getThemeFromPath(dir, program, cb) {
var configPath = path.resolve(dir, "theme.json");
program.log(2, constants.LOG_SEV_INFO, "Attempting to read " + configPath);
fs.readFile(configPath, { encoding: 'utf-8' }, function (err, data) {
if (err) {
program.log(1, constants.LOG_SEV_ERROR, "Error reading " + configPath);
return cb(err);
}
var config;
try {
config = eval('(' + data + ')');
} catch (e) {
program.log(1, constants.LOG_SEV_ERROR, "Error parsing " + configPath + ".");
program.log(2, constants.LOG_SEV_ERROR, "\n\n" + data);
return cb(e);
}
var themeConf = config.about;
if (!themeConf) {
var errorStr = "No about section found in " + configPath;
program.log(1, constants.LOG_SEV_ERROR, errorStr);
return cb(new Error(errorStr));
}
themeConf.baseDir = dir;
themeConf.program = program;
cb(null, new Theme(themeConf));
});
} | javascript | function getThemeFromPath(dir, program, cb) {
var configPath = path.resolve(dir, "theme.json");
program.log(2, constants.LOG_SEV_INFO, "Attempting to read " + configPath);
fs.readFile(configPath, { encoding: 'utf-8' }, function (err, data) {
if (err) {
program.log(1, constants.LOG_SEV_ERROR, "Error reading " + configPath);
return cb(err);
}
var config;
try {
config = eval('(' + data + ')');
} catch (e) {
program.log(1, constants.LOG_SEV_ERROR, "Error parsing " + configPath + ".");
program.log(2, constants.LOG_SEV_ERROR, "\n\n" + data);
return cb(e);
}
var themeConf = config.about;
if (!themeConf) {
var errorStr = "No about section found in " + configPath;
program.log(1, constants.LOG_SEV_ERROR, errorStr);
return cb(new Error(errorStr));
}
themeConf.baseDir = dir;
themeConf.program = program;
cb(null, new Theme(themeConf));
});
} | [
"function",
"getThemeFromPath",
"(",
"dir",
",",
"program",
",",
"cb",
")",
"{",
"var",
"configPath",
"=",
"path",
".",
"resolve",
"(",
"dir",
",",
"\"theme.json\"",
")",
";",
"program",
".",
"log",
"(",
"2",
",",
"constants",
".",
"LOG_SEV_INFO",
",",
"\"Attempting to read \"",
"+",
"configPath",
")",
";",
"fs",
".",
"readFile",
"(",
"configPath",
",",
"{",
"encoding",
":",
"'utf-8'",
"}",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"program",
".",
"log",
"(",
"1",
",",
"constants",
".",
"LOG_SEV_ERROR",
",",
"\"Error reading \"",
"+",
"configPath",
")",
";",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"var",
"config",
";",
"try",
"{",
"config",
"=",
"eval",
"(",
"'('",
"+",
"data",
"+",
"')'",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"program",
".",
"log",
"(",
"1",
",",
"constants",
".",
"LOG_SEV_ERROR",
",",
"\"Error parsing \"",
"+",
"configPath",
"+",
"\".\"",
")",
";",
"program",
".",
"log",
"(",
"2",
",",
"constants",
".",
"LOG_SEV_ERROR",
",",
"\"\\n\\n\"",
"+",
"data",
")",
";",
"return",
"cb",
"(",
"e",
")",
";",
"}",
"var",
"themeConf",
"=",
"config",
".",
"about",
";",
"if",
"(",
"!",
"themeConf",
")",
"{",
"var",
"errorStr",
"=",
"\"No about section found in \"",
"+",
"configPath",
";",
"program",
".",
"log",
"(",
"1",
",",
"constants",
".",
"LOG_SEV_ERROR",
",",
"errorStr",
")",
";",
"return",
"cb",
"(",
"new",
"Error",
"(",
"errorStr",
")",
")",
";",
"}",
"themeConf",
".",
"baseDir",
"=",
"dir",
";",
"themeConf",
".",
"program",
"=",
"program",
";",
"cb",
"(",
"null",
",",
"new",
"Theme",
"(",
"themeConf",
")",
")",
";",
"}",
")",
";",
"}"
] | requires absolute path | [
"requires",
"absolute",
"path"
] | 2cb42851298d01e668d2d4ffa8f46d52043066c8 | https://github.com/Mozu/mozu-theme-helpers/blob/2cb42851298d01e668d2d4ffa8f46d52043066c8/lib/utils/compiler/themes.js#L48-L74 |
49,925 | redisjs/jsr-server | lib/server.js | Server | function Server(options) {
//TcpServer.call(this, options);
var onError = onFatalError.bind(this);
/* istanbul ignore next: always in test env */
if(process.env.NODE_ENV !== Constants.TEST) {
process
.on('error', onError)
.on('uncaughtException', onError);
}
this._tcp = null;
this._unix = null;
// are we in the daemonized process
this._daemonized = false;
// server state
this._state = new ServerState();
this._state.pubsub.on('publish', this.publish.bind(this));
// map of monitor listener functions keyed by connection id
// we need to clean listeners on disconnect
this._monitor = {};
// list of command exec handlers
this.execs = null;
this.connection = this.connection.bind(this);
// listen for new connections
this.on('connection', this.connection);
this.command = this.command.bind(this);
ScriptManager.on('command', this.command);
// setup signals listener
signals.bind(this)();
} | javascript | function Server(options) {
//TcpServer.call(this, options);
var onError = onFatalError.bind(this);
/* istanbul ignore next: always in test env */
if(process.env.NODE_ENV !== Constants.TEST) {
process
.on('error', onError)
.on('uncaughtException', onError);
}
this._tcp = null;
this._unix = null;
// are we in the daemonized process
this._daemonized = false;
// server state
this._state = new ServerState();
this._state.pubsub.on('publish', this.publish.bind(this));
// map of monitor listener functions keyed by connection id
// we need to clean listeners on disconnect
this._monitor = {};
// list of command exec handlers
this.execs = null;
this.connection = this.connection.bind(this);
// listen for new connections
this.on('connection', this.connection);
this.command = this.command.bind(this);
ScriptManager.on('command', this.command);
// setup signals listener
signals.bind(this)();
} | [
"function",
"Server",
"(",
"options",
")",
"{",
"//TcpServer.call(this, options);",
"var",
"onError",
"=",
"onFatalError",
".",
"bind",
"(",
"this",
")",
";",
"/* istanbul ignore next: always in test env */",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"Constants",
".",
"TEST",
")",
"{",
"process",
".",
"on",
"(",
"'error'",
",",
"onError",
")",
".",
"on",
"(",
"'uncaughtException'",
",",
"onError",
")",
";",
"}",
"this",
".",
"_tcp",
"=",
"null",
";",
"this",
".",
"_unix",
"=",
"null",
";",
"// are we in the daemonized process",
"this",
".",
"_daemonized",
"=",
"false",
";",
"// server state",
"this",
".",
"_state",
"=",
"new",
"ServerState",
"(",
")",
";",
"this",
".",
"_state",
".",
"pubsub",
".",
"on",
"(",
"'publish'",
",",
"this",
".",
"publish",
".",
"bind",
"(",
"this",
")",
")",
";",
"// map of monitor listener functions keyed by connection id",
"// we need to clean listeners on disconnect",
"this",
".",
"_monitor",
"=",
"{",
"}",
";",
"// list of command exec handlers",
"this",
".",
"execs",
"=",
"null",
";",
"this",
".",
"connection",
"=",
"this",
".",
"connection",
".",
"bind",
"(",
"this",
")",
";",
"// listen for new connections",
"this",
".",
"on",
"(",
"'connection'",
",",
"this",
".",
"connection",
")",
";",
"this",
".",
"command",
"=",
"this",
".",
"command",
".",
"bind",
"(",
"this",
")",
";",
"ScriptManager",
".",
"on",
"(",
"'command'",
",",
"this",
".",
"command",
")",
";",
"// setup signals listener",
"signals",
".",
"bind",
"(",
"this",
")",
"(",
")",
";",
"}"
] | Redis server. | [
"Redis",
"server",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L37-L78 |
49,926 | redisjs/jsr-server | lib/server.js | connection | function connection(socket, server) {
var conn = new Connection(socket)
, tcp = (server instanceof TcpServer);
var maxclients = this.conf.get(ConfigKey.MAXCLIENTS);
if(maxclients && (this.state.length + 1 > maxclients)) {
this.state.emit('rejected', conn.client.addr, maxclients);
this.log.debug('rejected %s, exceeds maxclients %s',
conn.client.addr, maxclients);
function onWrite() {
socket.end();
}
return conn.write(MaxClients, onWrite.bind(this));
}
if(tcp) {
this.log.debug('accepted connection from %s', conn.client.addr);
}else if(server) {
this.log.debug('accepted connection to %s', server.name);
}else if(!server) {
this.log.debug('accepted connection in %s', process.pid);
}
var timeout = this.conf.get(ConfigKey.TIMEOUT);
if(typeof timeout === 'number' && timeout) {
this.log.debug('setting idle timeout for client #%s to %ss',
conn.id, timeout);
// config is seconds, socket want milliseconds
socket.setTimeout(timeout * 1000, function onTimeout() {
// TODO: log client connection timeout
socket.destroy();
})
}
conn.once('disconnect', this.disconnect.bind(this));
conn.on('command', this.command);
this._state.addConnection(conn);
} | javascript | function connection(socket, server) {
var conn = new Connection(socket)
, tcp = (server instanceof TcpServer);
var maxclients = this.conf.get(ConfigKey.MAXCLIENTS);
if(maxclients && (this.state.length + 1 > maxclients)) {
this.state.emit('rejected', conn.client.addr, maxclients);
this.log.debug('rejected %s, exceeds maxclients %s',
conn.client.addr, maxclients);
function onWrite() {
socket.end();
}
return conn.write(MaxClients, onWrite.bind(this));
}
if(tcp) {
this.log.debug('accepted connection from %s', conn.client.addr);
}else if(server) {
this.log.debug('accepted connection to %s', server.name);
}else if(!server) {
this.log.debug('accepted connection in %s', process.pid);
}
var timeout = this.conf.get(ConfigKey.TIMEOUT);
if(typeof timeout === 'number' && timeout) {
this.log.debug('setting idle timeout for client #%s to %ss',
conn.id, timeout);
// config is seconds, socket want milliseconds
socket.setTimeout(timeout * 1000, function onTimeout() {
// TODO: log client connection timeout
socket.destroy();
})
}
conn.once('disconnect', this.disconnect.bind(this));
conn.on('command', this.command);
this._state.addConnection(conn);
} | [
"function",
"connection",
"(",
"socket",
",",
"server",
")",
"{",
"var",
"conn",
"=",
"new",
"Connection",
"(",
"socket",
")",
",",
"tcp",
"=",
"(",
"server",
"instanceof",
"TcpServer",
")",
";",
"var",
"maxclients",
"=",
"this",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"MAXCLIENTS",
")",
";",
"if",
"(",
"maxclients",
"&&",
"(",
"this",
".",
"state",
".",
"length",
"+",
"1",
">",
"maxclients",
")",
")",
"{",
"this",
".",
"state",
".",
"emit",
"(",
"'rejected'",
",",
"conn",
".",
"client",
".",
"addr",
",",
"maxclients",
")",
";",
"this",
".",
"log",
".",
"debug",
"(",
"'rejected %s, exceeds maxclients %s'",
",",
"conn",
".",
"client",
".",
"addr",
",",
"maxclients",
")",
";",
"function",
"onWrite",
"(",
")",
"{",
"socket",
".",
"end",
"(",
")",
";",
"}",
"return",
"conn",
".",
"write",
"(",
"MaxClients",
",",
"onWrite",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"if",
"(",
"tcp",
")",
"{",
"this",
".",
"log",
".",
"debug",
"(",
"'accepted connection from %s'",
",",
"conn",
".",
"client",
".",
"addr",
")",
";",
"}",
"else",
"if",
"(",
"server",
")",
"{",
"this",
".",
"log",
".",
"debug",
"(",
"'accepted connection to %s'",
",",
"server",
".",
"name",
")",
";",
"}",
"else",
"if",
"(",
"!",
"server",
")",
"{",
"this",
".",
"log",
".",
"debug",
"(",
"'accepted connection in %s'",
",",
"process",
".",
"pid",
")",
";",
"}",
"var",
"timeout",
"=",
"this",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"TIMEOUT",
")",
";",
"if",
"(",
"typeof",
"timeout",
"===",
"'number'",
"&&",
"timeout",
")",
"{",
"this",
".",
"log",
".",
"debug",
"(",
"'setting idle timeout for client #%s to %ss'",
",",
"conn",
".",
"id",
",",
"timeout",
")",
";",
"// config is seconds, socket want milliseconds",
"socket",
".",
"setTimeout",
"(",
"timeout",
"*",
"1000",
",",
"function",
"onTimeout",
"(",
")",
"{",
"// TODO: log client connection timeout",
"socket",
".",
"destroy",
"(",
")",
";",
"}",
")",
"}",
"conn",
".",
"once",
"(",
"'disconnect'",
",",
"this",
".",
"disconnect",
".",
"bind",
"(",
"this",
")",
")",
";",
"conn",
".",
"on",
"(",
"'command'",
",",
"this",
".",
"command",
")",
";",
"this",
".",
"_state",
".",
"addConnection",
"(",
"conn",
")",
";",
"}"
] | Handle a connection event.
@param socket The underlying client socket.
@param server The TCP or UNIX server. | [
"Handle",
"a",
"connection",
"event",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L88-L129 |
49,927 | redisjs/jsr-server | lib/server.js | monitor | function monitor(req, res) {
var socket = req.conn.socket
, args = [req.cmd].concat(req.args)
, t = systime()
, str;
// quote command and args
args = args.map(function(arg) {
return '"' + arg + '"';
})
// TODO: figure out meaning of ip/host prefix: [0
// build up the monitor simple string response
str = new String(
util.format(Constants.FORMAT.MONITOR,
t.s, t.m,
socket.remoteAddress, socket.remotePort, args.join(' ')));
// emit the event, listening connections will send replies
// to clients registered for monitor
this.emit('monitor', str);
} | javascript | function monitor(req, res) {
var socket = req.conn.socket
, args = [req.cmd].concat(req.args)
, t = systime()
, str;
// quote command and args
args = args.map(function(arg) {
return '"' + arg + '"';
})
// TODO: figure out meaning of ip/host prefix: [0
// build up the monitor simple string response
str = new String(
util.format(Constants.FORMAT.MONITOR,
t.s, t.m,
socket.remoteAddress, socket.remotePort, args.join(' ')));
// emit the event, listening connections will send replies
// to clients registered for monitor
this.emit('monitor', str);
} | [
"function",
"monitor",
"(",
"req",
",",
"res",
")",
"{",
"var",
"socket",
"=",
"req",
".",
"conn",
".",
"socket",
",",
"args",
"=",
"[",
"req",
".",
"cmd",
"]",
".",
"concat",
"(",
"req",
".",
"args",
")",
",",
"t",
"=",
"systime",
"(",
")",
",",
"str",
";",
"// quote command and args",
"args",
"=",
"args",
".",
"map",
"(",
"function",
"(",
"arg",
")",
"{",
"return",
"'\"'",
"+",
"arg",
"+",
"'\"'",
";",
"}",
")",
"// TODO: figure out meaning of ip/host prefix: [0",
"// build up the monitor simple string response",
"str",
"=",
"new",
"String",
"(",
"util",
".",
"format",
"(",
"Constants",
".",
"FORMAT",
".",
"MONITOR",
",",
"t",
".",
"s",
",",
"t",
".",
"m",
",",
"socket",
".",
"remoteAddress",
",",
"socket",
".",
"remotePort",
",",
"args",
".",
"join",
"(",
"' '",
")",
")",
")",
";",
"// emit the event, listening connections will send replies",
"// to clients registered for monitor",
"this",
".",
"emit",
"(",
"'monitor'",
",",
"str",
")",
";",
"}"
] | Emit the monitor event string. | [
"Emit",
"the",
"monitor",
"event",
"string",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L134-L156 |
49,928 | redisjs/jsr-server | lib/server.js | publish | function publish(conn, channel, indices, message) {
var i
, conn;
for(i = 0;i < indices.length;i++) {
conn = this._state.getClient(indices[i]);
if(conn) {
conn.write(message);
}
}
} | javascript | function publish(conn, channel, indices, message) {
var i
, conn;
for(i = 0;i < indices.length;i++) {
conn = this._state.getClient(indices[i]);
if(conn) {
conn.write(message);
}
}
} | [
"function",
"publish",
"(",
"conn",
",",
"channel",
",",
"indices",
",",
"message",
")",
"{",
"var",
"i",
",",
"conn",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"indices",
".",
"length",
";",
"i",
"++",
")",
"{",
"conn",
"=",
"this",
".",
"_state",
".",
"getClient",
"(",
"indices",
"[",
"i",
"]",
")",
";",
"if",
"(",
"conn",
")",
"{",
"conn",
".",
"write",
"(",
"message",
")",
";",
"}",
"}",
"}"
] | Dispatches publish messages to target clients. | [
"Dispatches",
"publish",
"messages",
"to",
"target",
"clients",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L161-L170 |
49,929 | redisjs/jsr-server | lib/server.js | delegate | function delegate(req, res) {
var cmd = req.info.command
, method;
if(!cmd.sub) {
throw new Error('attempt to delegate with no subcommand info');
}
method = req.exec[cmd.sub.cmd];
// subcommand is declared but the command exec handler
// has not declared the method and is attempting to delegate
// we treat this as unknown subcommand which allows partial
// subcommand exec handlers that may call delegate but only
// implement a subset of the declared subcommands
if(typeof method !== 'function') {
return res.send(StoreError.UnknownSubcommand);
}
// rewrite the cmd/args
req.cmd = cmd.sub.cmd;
req.args = cmd.sub.args;
method.call(this, req, res);
} | javascript | function delegate(req, res) {
var cmd = req.info.command
, method;
if(!cmd.sub) {
throw new Error('attempt to delegate with no subcommand info');
}
method = req.exec[cmd.sub.cmd];
// subcommand is declared but the command exec handler
// has not declared the method and is attempting to delegate
// we treat this as unknown subcommand which allows partial
// subcommand exec handlers that may call delegate but only
// implement a subset of the declared subcommands
if(typeof method !== 'function') {
return res.send(StoreError.UnknownSubcommand);
}
// rewrite the cmd/args
req.cmd = cmd.sub.cmd;
req.args = cmd.sub.args;
method.call(this, req, res);
} | [
"function",
"delegate",
"(",
"req",
",",
"res",
")",
"{",
"var",
"cmd",
"=",
"req",
".",
"info",
".",
"command",
",",
"method",
";",
"if",
"(",
"!",
"cmd",
".",
"sub",
")",
"{",
"throw",
"new",
"Error",
"(",
"'attempt to delegate with no subcommand info'",
")",
";",
"}",
"method",
"=",
"req",
".",
"exec",
"[",
"cmd",
".",
"sub",
".",
"cmd",
"]",
";",
"// subcommand is declared but the command exec handler",
"// has not declared the method and is attempting to delegate",
"// we treat this as unknown subcommand which allows partial",
"// subcommand exec handlers that may call delegate but only",
"// implement a subset of the declared subcommands",
"if",
"(",
"typeof",
"method",
"!==",
"'function'",
")",
"{",
"return",
"res",
".",
"send",
"(",
"StoreError",
".",
"UnknownSubcommand",
")",
";",
"}",
"// rewrite the cmd/args",
"req",
".",
"cmd",
"=",
"cmd",
".",
"sub",
".",
"cmd",
";",
"req",
".",
"args",
"=",
"cmd",
".",
"sub",
".",
"args",
";",
"method",
".",
"call",
"(",
"this",
",",
"req",
",",
"res",
")",
";",
"}"
] | Delegate a subcommand to a method declared on the exec instance. | [
"Delegate",
"a",
"subcommand",
"to",
"a",
"method",
"declared",
"on",
"the",
"exec",
"instance",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L175-L198 |
49,930 | redisjs/jsr-server | lib/server.js | command | function command(req, res) {
this.stats.commands++;
//console.dir(this);
// guaranteed to have a string command by connection
var cmd = req.cmd
// guaranteed to have an arguments array by connection
, args = req.args
// select implementation should guarantee a valid db index
// on the connection
, db = this.store.getDatabase(req.conn.db)
// info object used by the validate function
, exec = this.execs[cmd]
, info = {
db: db, conf: this.conf, conn: req.conn, exec: exec, commands: this.execs}
// should we queue this command in a transaction
// of just execute it
, queue = cmd !== DISCARD && cmd !== EXEC
// flag if command is acceptable when busy
, acceptable;
// raw arguments list, before validation
// used so that the slowlog does not show modified arguments
req.raw = args.slice(0);
//console.error('server processing command: %s', cmd);
//console.error('server processing command: %j', args);
//
if(ScriptManager.busy && !req.script) {
// compare on command instances
// in case they have been renamed
acceptable =
(exec === Shutdown
&& ('' + args[0] || '').toLowerCase() === NOSAVE)
|| (exec === Script
&& ('' + args[0] || '').toLowerCase() === KILL);
if(!acceptable) return res.send(StoreError.Busy);
}
if(exec === false) {
return res.send(StoreError.UnknownDisabled);
}else if(!exec) {
return res.send(new UnknownCommand(cmd));
}
try {
exec.validate.call(this, cmd, args, info);
// inject references
req.db = db;
req.conf = this.conf;
req.exec = exec;
// these properties are available on the req
delete info.db;
delete info.conn;
delete info.conf;
// inject the info object which is decorated with
// additional useful information on validation
req.info = info;
// alias the command definition
req.def = req.exec.definition;
}catch(e) {
// let the transaction decide how to proceed on error
if(req.conn.transaction) {
return req.conn.transaction.add(e, req, res);
}
return res.send(e);
}
if(req.conn.transaction && queue) {
return req.conn.transaction.add(null, req, res);
}
this.execute(exec, req, res);
} | javascript | function command(req, res) {
this.stats.commands++;
//console.dir(this);
// guaranteed to have a string command by connection
var cmd = req.cmd
// guaranteed to have an arguments array by connection
, args = req.args
// select implementation should guarantee a valid db index
// on the connection
, db = this.store.getDatabase(req.conn.db)
// info object used by the validate function
, exec = this.execs[cmd]
, info = {
db: db, conf: this.conf, conn: req.conn, exec: exec, commands: this.execs}
// should we queue this command in a transaction
// of just execute it
, queue = cmd !== DISCARD && cmd !== EXEC
// flag if command is acceptable when busy
, acceptable;
// raw arguments list, before validation
// used so that the slowlog does not show modified arguments
req.raw = args.slice(0);
//console.error('server processing command: %s', cmd);
//console.error('server processing command: %j', args);
//
if(ScriptManager.busy && !req.script) {
// compare on command instances
// in case they have been renamed
acceptable =
(exec === Shutdown
&& ('' + args[0] || '').toLowerCase() === NOSAVE)
|| (exec === Script
&& ('' + args[0] || '').toLowerCase() === KILL);
if(!acceptable) return res.send(StoreError.Busy);
}
if(exec === false) {
return res.send(StoreError.UnknownDisabled);
}else if(!exec) {
return res.send(new UnknownCommand(cmd));
}
try {
exec.validate.call(this, cmd, args, info);
// inject references
req.db = db;
req.conf = this.conf;
req.exec = exec;
// these properties are available on the req
delete info.db;
delete info.conn;
delete info.conf;
// inject the info object which is decorated with
// additional useful information on validation
req.info = info;
// alias the command definition
req.def = req.exec.definition;
}catch(e) {
// let the transaction decide how to proceed on error
if(req.conn.transaction) {
return req.conn.transaction.add(e, req, res);
}
return res.send(e);
}
if(req.conn.transaction && queue) {
return req.conn.transaction.add(null, req, res);
}
this.execute(exec, req, res);
} | [
"function",
"command",
"(",
"req",
",",
"res",
")",
"{",
"this",
".",
"stats",
".",
"commands",
"++",
";",
"//console.dir(this);",
"// guaranteed to have a string command by connection",
"var",
"cmd",
"=",
"req",
".",
"cmd",
"// guaranteed to have an arguments array by connection",
",",
"args",
"=",
"req",
".",
"args",
"// select implementation should guarantee a valid db index",
"// on the connection",
",",
"db",
"=",
"this",
".",
"store",
".",
"getDatabase",
"(",
"req",
".",
"conn",
".",
"db",
")",
"// info object used by the validate function",
",",
"exec",
"=",
"this",
".",
"execs",
"[",
"cmd",
"]",
",",
"info",
"=",
"{",
"db",
":",
"db",
",",
"conf",
":",
"this",
".",
"conf",
",",
"conn",
":",
"req",
".",
"conn",
",",
"exec",
":",
"exec",
",",
"commands",
":",
"this",
".",
"execs",
"}",
"// should we queue this command in a transaction",
"// of just execute it",
",",
"queue",
"=",
"cmd",
"!==",
"DISCARD",
"&&",
"cmd",
"!==",
"EXEC",
"// flag if command is acceptable when busy",
",",
"acceptable",
";",
"// raw arguments list, before validation",
"// used so that the slowlog does not show modified arguments",
"req",
".",
"raw",
"=",
"args",
".",
"slice",
"(",
"0",
")",
";",
"//console.error('server processing command: %s', cmd);",
"//console.error('server processing command: %j', args);",
"//",
"if",
"(",
"ScriptManager",
".",
"busy",
"&&",
"!",
"req",
".",
"script",
")",
"{",
"// compare on command instances",
"// in case they have been renamed",
"acceptable",
"=",
"(",
"exec",
"===",
"Shutdown",
"&&",
"(",
"''",
"+",
"args",
"[",
"0",
"]",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
"===",
"NOSAVE",
")",
"||",
"(",
"exec",
"===",
"Script",
"&&",
"(",
"''",
"+",
"args",
"[",
"0",
"]",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
"===",
"KILL",
")",
";",
"if",
"(",
"!",
"acceptable",
")",
"return",
"res",
".",
"send",
"(",
"StoreError",
".",
"Busy",
")",
";",
"}",
"if",
"(",
"exec",
"===",
"false",
")",
"{",
"return",
"res",
".",
"send",
"(",
"StoreError",
".",
"UnknownDisabled",
")",
";",
"}",
"else",
"if",
"(",
"!",
"exec",
")",
"{",
"return",
"res",
".",
"send",
"(",
"new",
"UnknownCommand",
"(",
"cmd",
")",
")",
";",
"}",
"try",
"{",
"exec",
".",
"validate",
".",
"call",
"(",
"this",
",",
"cmd",
",",
"args",
",",
"info",
")",
";",
"// inject references",
"req",
".",
"db",
"=",
"db",
";",
"req",
".",
"conf",
"=",
"this",
".",
"conf",
";",
"req",
".",
"exec",
"=",
"exec",
";",
"// these properties are available on the req",
"delete",
"info",
".",
"db",
";",
"delete",
"info",
".",
"conn",
";",
"delete",
"info",
".",
"conf",
";",
"// inject the info object which is decorated with",
"// additional useful information on validation",
"req",
".",
"info",
"=",
"info",
";",
"// alias the command definition",
"req",
".",
"def",
"=",
"req",
".",
"exec",
".",
"definition",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// let the transaction decide how to proceed on error",
"if",
"(",
"req",
".",
"conn",
".",
"transaction",
")",
"{",
"return",
"req",
".",
"conn",
".",
"transaction",
".",
"add",
"(",
"e",
",",
"req",
",",
"res",
")",
";",
"}",
"return",
"res",
".",
"send",
"(",
"e",
")",
";",
"}",
"if",
"(",
"req",
".",
"conn",
".",
"transaction",
"&&",
"queue",
")",
"{",
"return",
"req",
".",
"conn",
".",
"transaction",
".",
"add",
"(",
"null",
",",
"req",
",",
"res",
")",
";",
"}",
"this",
".",
"execute",
"(",
"exec",
",",
"req",
",",
"res",
")",
";",
"}"
] | Process an incoming command.
@param req The connection request.
@param res The connection response. | [
"Process",
"an",
"incoming",
"command",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L206-L288 |
49,931 | redisjs/jsr-server | lib/server.js | disconnect | function disconnect(conn, socket, err) {
//console.dir('disconnect');
// clean monitor listeners
if(this._monitor[conn.id]) {
this.removeListener('monitor', this._monitor[conn.id]);
delete this._monitor[conn.id];
}
this._state.removeConnection(conn);
} | javascript | function disconnect(conn, socket, err) {
//console.dir('disconnect');
// clean monitor listeners
if(this._monitor[conn.id]) {
this.removeListener('monitor', this._monitor[conn.id]);
delete this._monitor[conn.id];
}
this._state.removeConnection(conn);
} | [
"function",
"disconnect",
"(",
"conn",
",",
"socket",
",",
"err",
")",
"{",
"//console.dir('disconnect');",
"// clean monitor listeners",
"if",
"(",
"this",
".",
"_monitor",
"[",
"conn",
".",
"id",
"]",
")",
"{",
"this",
".",
"removeListener",
"(",
"'monitor'",
",",
"this",
".",
"_monitor",
"[",
"conn",
".",
"id",
"]",
")",
";",
"delete",
"this",
".",
"_monitor",
"[",
"conn",
".",
"id",
"]",
";",
"}",
"this",
".",
"_state",
".",
"removeConnection",
"(",
"conn",
")",
";",
"}"
] | Listener for the connection disconnect event triggered
by the socket close event.
@param conn The connection.
@param socket The underlying socket.
@param err Boolean indicating if a transmission error occured. | [
"Listener",
"for",
"the",
"connection",
"disconnect",
"event",
"triggered",
"by",
"the",
"socket",
"close",
"event",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L335-L345 |
49,932 | redisjs/jsr-server | lib/server.js | load | function load(opts, cb) {
if(typeof opts === 'function') {
cb = opts;
opts = null;
}
var args = opts && opts.args ? opts.args : null
, defaults = path.normalize(path.join(__dirname, 'command'));
opts = opts || argv(args);
if(opts.commands === undefined) {
opts.commands = [defaults];
}else if(Array.isArray(opts.commands) && opts.defaults) {
opts.commands.unshift(defaults);
}
function onConfigError(err) {
//console.dir(err);
console.error(err.message);
if(process.env.NODE_ENV !== Constants.TEST) {
process.exit(1);
}
}
this.conf.once('error', onConfigError.bind(this));
function onConfigLoad() {
// if we loaded ok we are done with fatal config errors
// config set/rewrite need to catch errors now
this.conf.removeAllListeners('error');
this.emit('config', this.conf);
opts.conf = this.conf;
// spawning the daemon process
if(this.conf.get(ConfigKey.DAEMONIZE) && !this._daemonized) {
var pid = daemon(
path.join(__dirname, 'daemonize.js'), this.conf, opts.args);
if(cb) cb(pid);
return;
}
this.log.notice('cwd: %s', process.cwd());
// pass configured timeout to script manager
ScriptManager.timeout = this.conf.get(ConfigKey.LUA_TIME_LIMIT);
// spawn now, makes first script executions faster
// later this should be configurable - allow disabling all
// scripting
ScriptManager.spawn();
// load commands
return loader(opts, onCommandLoad);
}
function onCommandLoad(err, commands) {
if(err) return cb(err);
this.execs = commands;
this.emit('ready', this.execs);
// inject command list so the script manager
// can detect write commands
ScriptManager.commands = commands;
// loading from rdb files breaks the tests
if(process.env.NODE_ENV === Constants.TEST) {
return cb();
}
Persistence.load(this.state.store, this.state.conf, onDatabaseLoad);
}
function onDatabaseLoad(err, time, diff, version) {
// load errors are thrown, will cause
// the process to exit
if(err) throw err;
if(err !== false) {
this.log.notice('db loaded from disk: %s seconds (v%s)', time, version);
this.emit('database', time, diff, version);
}
cb();
}
onConfigLoad = onConfigLoad.bind(this);
onCommandLoad = onCommandLoad.bind(this);
onDatabaseLoad = onDatabaseLoad.bind(this);
// load config
this.conf.load(opts, onConfigLoad);
} | javascript | function load(opts, cb) {
if(typeof opts === 'function') {
cb = opts;
opts = null;
}
var args = opts && opts.args ? opts.args : null
, defaults = path.normalize(path.join(__dirname, 'command'));
opts = opts || argv(args);
if(opts.commands === undefined) {
opts.commands = [defaults];
}else if(Array.isArray(opts.commands) && opts.defaults) {
opts.commands.unshift(defaults);
}
function onConfigError(err) {
//console.dir(err);
console.error(err.message);
if(process.env.NODE_ENV !== Constants.TEST) {
process.exit(1);
}
}
this.conf.once('error', onConfigError.bind(this));
function onConfigLoad() {
// if we loaded ok we are done with fatal config errors
// config set/rewrite need to catch errors now
this.conf.removeAllListeners('error');
this.emit('config', this.conf);
opts.conf = this.conf;
// spawning the daemon process
if(this.conf.get(ConfigKey.DAEMONIZE) && !this._daemonized) {
var pid = daemon(
path.join(__dirname, 'daemonize.js'), this.conf, opts.args);
if(cb) cb(pid);
return;
}
this.log.notice('cwd: %s', process.cwd());
// pass configured timeout to script manager
ScriptManager.timeout = this.conf.get(ConfigKey.LUA_TIME_LIMIT);
// spawn now, makes first script executions faster
// later this should be configurable - allow disabling all
// scripting
ScriptManager.spawn();
// load commands
return loader(opts, onCommandLoad);
}
function onCommandLoad(err, commands) {
if(err) return cb(err);
this.execs = commands;
this.emit('ready', this.execs);
// inject command list so the script manager
// can detect write commands
ScriptManager.commands = commands;
// loading from rdb files breaks the tests
if(process.env.NODE_ENV === Constants.TEST) {
return cb();
}
Persistence.load(this.state.store, this.state.conf, onDatabaseLoad);
}
function onDatabaseLoad(err, time, diff, version) {
// load errors are thrown, will cause
// the process to exit
if(err) throw err;
if(err !== false) {
this.log.notice('db loaded from disk: %s seconds (v%s)', time, version);
this.emit('database', time, diff, version);
}
cb();
}
onConfigLoad = onConfigLoad.bind(this);
onCommandLoad = onCommandLoad.bind(this);
onDatabaseLoad = onDatabaseLoad.bind(this);
// load config
this.conf.load(opts, onConfigLoad);
} | [
"function",
"load",
"(",
"opts",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"opts",
"===",
"'function'",
")",
"{",
"cb",
"=",
"opts",
";",
"opts",
"=",
"null",
";",
"}",
"var",
"args",
"=",
"opts",
"&&",
"opts",
".",
"args",
"?",
"opts",
".",
"args",
":",
"null",
",",
"defaults",
"=",
"path",
".",
"normalize",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'command'",
")",
")",
";",
"opts",
"=",
"opts",
"||",
"argv",
"(",
"args",
")",
";",
"if",
"(",
"opts",
".",
"commands",
"===",
"undefined",
")",
"{",
"opts",
".",
"commands",
"=",
"[",
"defaults",
"]",
";",
"}",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"opts",
".",
"commands",
")",
"&&",
"opts",
".",
"defaults",
")",
"{",
"opts",
".",
"commands",
".",
"unshift",
"(",
"defaults",
")",
";",
"}",
"function",
"onConfigError",
"(",
"err",
")",
"{",
"//console.dir(err);",
"console",
".",
"error",
"(",
"err",
".",
"message",
")",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"Constants",
".",
"TEST",
")",
"{",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}",
"this",
".",
"conf",
".",
"once",
"(",
"'error'",
",",
"onConfigError",
".",
"bind",
"(",
"this",
")",
")",
";",
"function",
"onConfigLoad",
"(",
")",
"{",
"// if we loaded ok we are done with fatal config errors",
"// config set/rewrite need to catch errors now",
"this",
".",
"conf",
".",
"removeAllListeners",
"(",
"'error'",
")",
";",
"this",
".",
"emit",
"(",
"'config'",
",",
"this",
".",
"conf",
")",
";",
"opts",
".",
"conf",
"=",
"this",
".",
"conf",
";",
"// spawning the daemon process",
"if",
"(",
"this",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"DAEMONIZE",
")",
"&&",
"!",
"this",
".",
"_daemonized",
")",
"{",
"var",
"pid",
"=",
"daemon",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"'daemonize.js'",
")",
",",
"this",
".",
"conf",
",",
"opts",
".",
"args",
")",
";",
"if",
"(",
"cb",
")",
"cb",
"(",
"pid",
")",
";",
"return",
";",
"}",
"this",
".",
"log",
".",
"notice",
"(",
"'cwd: %s'",
",",
"process",
".",
"cwd",
"(",
")",
")",
";",
"// pass configured timeout to script manager",
"ScriptManager",
".",
"timeout",
"=",
"this",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"LUA_TIME_LIMIT",
")",
";",
"// spawn now, makes first script executions faster",
"// later this should be configurable - allow disabling all",
"// scripting",
"ScriptManager",
".",
"spawn",
"(",
")",
";",
"// load commands",
"return",
"loader",
"(",
"opts",
",",
"onCommandLoad",
")",
";",
"}",
"function",
"onCommandLoad",
"(",
"err",
",",
"commands",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"this",
".",
"execs",
"=",
"commands",
";",
"this",
".",
"emit",
"(",
"'ready'",
",",
"this",
".",
"execs",
")",
";",
"// inject command list so the script manager",
"// can detect write commands",
"ScriptManager",
".",
"commands",
"=",
"commands",
";",
"// loading from rdb files breaks the tests",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"Constants",
".",
"TEST",
")",
"{",
"return",
"cb",
"(",
")",
";",
"}",
"Persistence",
".",
"load",
"(",
"this",
".",
"state",
".",
"store",
",",
"this",
".",
"state",
".",
"conf",
",",
"onDatabaseLoad",
")",
";",
"}",
"function",
"onDatabaseLoad",
"(",
"err",
",",
"time",
",",
"diff",
",",
"version",
")",
"{",
"// load errors are thrown, will cause",
"// the process to exit",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"if",
"(",
"err",
"!==",
"false",
")",
"{",
"this",
".",
"log",
".",
"notice",
"(",
"'db loaded from disk: %s seconds (v%s)'",
",",
"time",
",",
"version",
")",
";",
"this",
".",
"emit",
"(",
"'database'",
",",
"time",
",",
"diff",
",",
"version",
")",
";",
"}",
"cb",
"(",
")",
";",
"}",
"onConfigLoad",
"=",
"onConfigLoad",
".",
"bind",
"(",
"this",
")",
";",
"onCommandLoad",
"=",
"onCommandLoad",
".",
"bind",
"(",
"this",
")",
";",
"onDatabaseLoad",
"=",
"onDatabaseLoad",
".",
"bind",
"(",
"this",
")",
";",
"// load config",
"this",
".",
"conf",
".",
"load",
"(",
"opts",
",",
"onConfigLoad",
")",
";",
"}"
] | Loads command definitions. | [
"Loads",
"command",
"definitions",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L350-L440 |
49,933 | redisjs/jsr-server | lib/server.js | listen | function listen() {
var args = []
, port = this.conf.get(ConfigKey.PORT)
, socket = this.conf.get(ConfigKey.UNIXSOCKET)
, perm = this.conf.get(ConfigKey.UNIXSOCKETPERM)
, backlog = this.conf.get(ConfigKey.TCP_BACKLOG)
, cb = typeof arguments[arguments.length - 1] === 'function'
? arguments[arguments.length - 1] : null
, tcp
, unix;
if(socket) {
unix = this._unix = new UnixServer(this);
}
// tcp: server.listen(port, [host], [backlog], [callback])
// unix socket: server.listen(path, [callback])
// port zero means don't listen on a tcp port
if(port !== 0) {
tcp = this._tcp = new TcpServer(this);
// port comes first
args.unshift(port);
// backlog is penultimate argument
if(typeof backlog === 'number') {
args.push(backlog);
}
//console.dir(args);
// cb is last argument
if(cb) args.push(cb);
function onListen() {
// for server info, the actual port or socket in use
// stored on the state, null if listen was never called
// or if the bind failed, could also be a unix socket
var addr = tcp.address();
var port = addr.port;
this.state.addr = addr;
// only write pid if we listen
if(this._daemonized) {
daemon.pid.write(this.conf);
}
this.emit('listen', port);
this.log.notice('accepting connections on port %s', port);
// might be listening on a unix socket too
if(unix) unix.listen(socket, perm);
}
tcp.once('listening', onListen.bind(this));
tcp.listen.apply(tcp, args);
// just a unix socket
}else if(unix) {
unix.listen(socket, perm);
}
} | javascript | function listen() {
var args = []
, port = this.conf.get(ConfigKey.PORT)
, socket = this.conf.get(ConfigKey.UNIXSOCKET)
, perm = this.conf.get(ConfigKey.UNIXSOCKETPERM)
, backlog = this.conf.get(ConfigKey.TCP_BACKLOG)
, cb = typeof arguments[arguments.length - 1] === 'function'
? arguments[arguments.length - 1] : null
, tcp
, unix;
if(socket) {
unix = this._unix = new UnixServer(this);
}
// tcp: server.listen(port, [host], [backlog], [callback])
// unix socket: server.listen(path, [callback])
// port zero means don't listen on a tcp port
if(port !== 0) {
tcp = this._tcp = new TcpServer(this);
// port comes first
args.unshift(port);
// backlog is penultimate argument
if(typeof backlog === 'number') {
args.push(backlog);
}
//console.dir(args);
// cb is last argument
if(cb) args.push(cb);
function onListen() {
// for server info, the actual port or socket in use
// stored on the state, null if listen was never called
// or if the bind failed, could also be a unix socket
var addr = tcp.address();
var port = addr.port;
this.state.addr = addr;
// only write pid if we listen
if(this._daemonized) {
daemon.pid.write(this.conf);
}
this.emit('listen', port);
this.log.notice('accepting connections on port %s', port);
// might be listening on a unix socket too
if(unix) unix.listen(socket, perm);
}
tcp.once('listening', onListen.bind(this));
tcp.listen.apply(tcp, args);
// just a unix socket
}else if(unix) {
unix.listen(socket, perm);
}
} | [
"function",
"listen",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"]",
",",
"port",
"=",
"this",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"PORT",
")",
",",
"socket",
"=",
"this",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"UNIXSOCKET",
")",
",",
"perm",
"=",
"this",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"UNIXSOCKETPERM",
")",
",",
"backlog",
"=",
"this",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"TCP_BACKLOG",
")",
",",
"cb",
"=",
"typeof",
"arguments",
"[",
"arguments",
".",
"length",
"-",
"1",
"]",
"===",
"'function'",
"?",
"arguments",
"[",
"arguments",
".",
"length",
"-",
"1",
"]",
":",
"null",
",",
"tcp",
",",
"unix",
";",
"if",
"(",
"socket",
")",
"{",
"unix",
"=",
"this",
".",
"_unix",
"=",
"new",
"UnixServer",
"(",
"this",
")",
";",
"}",
"// tcp: server.listen(port, [host], [backlog], [callback])",
"// unix socket: server.listen(path, [callback])",
"// port zero means don't listen on a tcp port",
"if",
"(",
"port",
"!==",
"0",
")",
"{",
"tcp",
"=",
"this",
".",
"_tcp",
"=",
"new",
"TcpServer",
"(",
"this",
")",
";",
"// port comes first",
"args",
".",
"unshift",
"(",
"port",
")",
";",
"// backlog is penultimate argument",
"if",
"(",
"typeof",
"backlog",
"===",
"'number'",
")",
"{",
"args",
".",
"push",
"(",
"backlog",
")",
";",
"}",
"//console.dir(args);",
"// cb is last argument",
"if",
"(",
"cb",
")",
"args",
".",
"push",
"(",
"cb",
")",
";",
"function",
"onListen",
"(",
")",
"{",
"// for server info, the actual port or socket in use",
"// stored on the state, null if listen was never called",
"// or if the bind failed, could also be a unix socket",
"var",
"addr",
"=",
"tcp",
".",
"address",
"(",
")",
";",
"var",
"port",
"=",
"addr",
".",
"port",
";",
"this",
".",
"state",
".",
"addr",
"=",
"addr",
";",
"// only write pid if we listen",
"if",
"(",
"this",
".",
"_daemonized",
")",
"{",
"daemon",
".",
"pid",
".",
"write",
"(",
"this",
".",
"conf",
")",
";",
"}",
"this",
".",
"emit",
"(",
"'listen'",
",",
"port",
")",
";",
"this",
".",
"log",
".",
"notice",
"(",
"'accepting connections on port %s'",
",",
"port",
")",
";",
"// might be listening on a unix socket too",
"if",
"(",
"unix",
")",
"unix",
".",
"listen",
"(",
"socket",
",",
"perm",
")",
";",
"}",
"tcp",
".",
"once",
"(",
"'listening'",
",",
"onListen",
".",
"bind",
"(",
"this",
")",
")",
";",
"tcp",
".",
"listen",
".",
"apply",
"(",
"tcp",
",",
"args",
")",
";",
"// just a unix socket",
"}",
"else",
"if",
"(",
"unix",
")",
"{",
"unix",
".",
"listen",
"(",
"socket",
",",
"perm",
")",
";",
"}",
"}"
] | Listen on a port or socket. | [
"Listen",
"on",
"a",
"port",
"or",
"socket",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L445-L506 |
49,934 | redisjs/jsr-server | lib/server.js | shutdown | function shutdown(opts, cb) {
if(typeof opts === 'function') {
cb = opts;
opts = null;
}
opts = opts || {};
var code = opts.code || 0
, i = -1
, snapshots = this.state.conf.get(ConfigKey.SAVE)
, save = typeof opts.save === 'boolean' ? opts.save : null;
if(save === null) {
save = snapshots && snapshots.length > 0;
}
/* istanbul ignore next: always in test environment */
if(process.env.NODE_ENV === Constants.TEST) {
save = false;
}
// cannot save a potentially inconsistent data set
if(ScriptManager.busy && ScriptManager.written) {
save = false;
}
if(Persistence.loading && save) {
save = false;
this.log.warning('save skipped while db load in progress');
}
this.state.scheduler.kill();
function iterate() {
var conn = this.state.getClient(++i);
if(!conn) return onClose();
this.log.verbose('terminating client connection %s', conn.client.id);
conn.close(function onClose() {
--i;
iterate();
});
}
function onShutdownComplete() {
if(this._daemonized) {
daemon.pid.remove(this.conf);
}
this.log.notice('ready to exit, ciao');
/* istanbul ignore next: always in test environment */
if(cb === process.exit
&& process.env.NODE_ENV === Constants.TEST
&& !this._daemonized) {
return;
}
cb(code);
}
function onClose() {
// not saving to disc, explicit nosave
// or not snapshotting (no save points)
if(!save) return onShutdownComplete();
this.log.notice('saving the final rdb snapshot before exiting');
Persistence.saveSync(this.state.store, this.state.conf);
onShutdownComplete();
//Persistence.save(this.state.store, this.state.conf, onShutdownComplete);
}
this.log.verbose('not accepting connections')
// TODO: prevent/handle not running error when not listening!
// TODO: can possibly test the output of address() to know if we
// TODO: are listening or not. all logic should be the same just
// TODO: need to skip the call to close()
// the close callback can fire before the disconnect listener
// for the last client connection, so onClose is called when the
// last connection is actually closed, allows us to assert on
// client connection length
if(this._tcp) {
this._tcp.close();
}
if(this._unix) {
this._unix.close();
}
onShutdownComplete = onShutdownComplete.bind(this);
onClose = onClose.bind(this);
iterate = iterate.bind(this);
iterate();
} | javascript | function shutdown(opts, cb) {
if(typeof opts === 'function') {
cb = opts;
opts = null;
}
opts = opts || {};
var code = opts.code || 0
, i = -1
, snapshots = this.state.conf.get(ConfigKey.SAVE)
, save = typeof opts.save === 'boolean' ? opts.save : null;
if(save === null) {
save = snapshots && snapshots.length > 0;
}
/* istanbul ignore next: always in test environment */
if(process.env.NODE_ENV === Constants.TEST) {
save = false;
}
// cannot save a potentially inconsistent data set
if(ScriptManager.busy && ScriptManager.written) {
save = false;
}
if(Persistence.loading && save) {
save = false;
this.log.warning('save skipped while db load in progress');
}
this.state.scheduler.kill();
function iterate() {
var conn = this.state.getClient(++i);
if(!conn) return onClose();
this.log.verbose('terminating client connection %s', conn.client.id);
conn.close(function onClose() {
--i;
iterate();
});
}
function onShutdownComplete() {
if(this._daemonized) {
daemon.pid.remove(this.conf);
}
this.log.notice('ready to exit, ciao');
/* istanbul ignore next: always in test environment */
if(cb === process.exit
&& process.env.NODE_ENV === Constants.TEST
&& !this._daemonized) {
return;
}
cb(code);
}
function onClose() {
// not saving to disc, explicit nosave
// or not snapshotting (no save points)
if(!save) return onShutdownComplete();
this.log.notice('saving the final rdb snapshot before exiting');
Persistence.saveSync(this.state.store, this.state.conf);
onShutdownComplete();
//Persistence.save(this.state.store, this.state.conf, onShutdownComplete);
}
this.log.verbose('not accepting connections')
// TODO: prevent/handle not running error when not listening!
// TODO: can possibly test the output of address() to know if we
// TODO: are listening or not. all logic should be the same just
// TODO: need to skip the call to close()
// the close callback can fire before the disconnect listener
// for the last client connection, so onClose is called when the
// last connection is actually closed, allows us to assert on
// client connection length
if(this._tcp) {
this._tcp.close();
}
if(this._unix) {
this._unix.close();
}
onShutdownComplete = onShutdownComplete.bind(this);
onClose = onClose.bind(this);
iterate = iterate.bind(this);
iterate();
} | [
"function",
"shutdown",
"(",
"opts",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"opts",
"===",
"'function'",
")",
"{",
"cb",
"=",
"opts",
";",
"opts",
"=",
"null",
";",
"}",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"code",
"=",
"opts",
".",
"code",
"||",
"0",
",",
"i",
"=",
"-",
"1",
",",
"snapshots",
"=",
"this",
".",
"state",
".",
"conf",
".",
"get",
"(",
"ConfigKey",
".",
"SAVE",
")",
",",
"save",
"=",
"typeof",
"opts",
".",
"save",
"===",
"'boolean'",
"?",
"opts",
".",
"save",
":",
"null",
";",
"if",
"(",
"save",
"===",
"null",
")",
"{",
"save",
"=",
"snapshots",
"&&",
"snapshots",
".",
"length",
">",
"0",
";",
"}",
"/* istanbul ignore next: always in test environment */",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"Constants",
".",
"TEST",
")",
"{",
"save",
"=",
"false",
";",
"}",
"// cannot save a potentially inconsistent data set",
"if",
"(",
"ScriptManager",
".",
"busy",
"&&",
"ScriptManager",
".",
"written",
")",
"{",
"save",
"=",
"false",
";",
"}",
"if",
"(",
"Persistence",
".",
"loading",
"&&",
"save",
")",
"{",
"save",
"=",
"false",
";",
"this",
".",
"log",
".",
"warning",
"(",
"'save skipped while db load in progress'",
")",
";",
"}",
"this",
".",
"state",
".",
"scheduler",
".",
"kill",
"(",
")",
";",
"function",
"iterate",
"(",
")",
"{",
"var",
"conn",
"=",
"this",
".",
"state",
".",
"getClient",
"(",
"++",
"i",
")",
";",
"if",
"(",
"!",
"conn",
")",
"return",
"onClose",
"(",
")",
";",
"this",
".",
"log",
".",
"verbose",
"(",
"'terminating client connection %s'",
",",
"conn",
".",
"client",
".",
"id",
")",
";",
"conn",
".",
"close",
"(",
"function",
"onClose",
"(",
")",
"{",
"--",
"i",
";",
"iterate",
"(",
")",
";",
"}",
")",
";",
"}",
"function",
"onShutdownComplete",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_daemonized",
")",
"{",
"daemon",
".",
"pid",
".",
"remove",
"(",
"this",
".",
"conf",
")",
";",
"}",
"this",
".",
"log",
".",
"notice",
"(",
"'ready to exit, ciao'",
")",
";",
"/* istanbul ignore next: always in test environment */",
"if",
"(",
"cb",
"===",
"process",
".",
"exit",
"&&",
"process",
".",
"env",
".",
"NODE_ENV",
"===",
"Constants",
".",
"TEST",
"&&",
"!",
"this",
".",
"_daemonized",
")",
"{",
"return",
";",
"}",
"cb",
"(",
"code",
")",
";",
"}",
"function",
"onClose",
"(",
")",
"{",
"// not saving to disc, explicit nosave",
"// or not snapshotting (no save points)",
"if",
"(",
"!",
"save",
")",
"return",
"onShutdownComplete",
"(",
")",
";",
"this",
".",
"log",
".",
"notice",
"(",
"'saving the final rdb snapshot before exiting'",
")",
";",
"Persistence",
".",
"saveSync",
"(",
"this",
".",
"state",
".",
"store",
",",
"this",
".",
"state",
".",
"conf",
")",
";",
"onShutdownComplete",
"(",
")",
";",
"//Persistence.save(this.state.store, this.state.conf, onShutdownComplete);",
"}",
"this",
".",
"log",
".",
"verbose",
"(",
"'not accepting connections'",
")",
"// TODO: prevent/handle not running error when not listening!",
"// TODO: can possibly test the output of address() to know if we",
"// TODO: are listening or not. all logic should be the same just",
"// TODO: need to skip the call to close()",
"// the close callback can fire before the disconnect listener",
"// for the last client connection, so onClose is called when the",
"// last connection is actually closed, allows us to assert on",
"// client connection length",
"if",
"(",
"this",
".",
"_tcp",
")",
"{",
"this",
".",
"_tcp",
".",
"close",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"_unix",
")",
"{",
"this",
".",
"_unix",
".",
"close",
"(",
")",
";",
"}",
"onShutdownComplete",
"=",
"onShutdownComplete",
".",
"bind",
"(",
"this",
")",
";",
"onClose",
"=",
"onClose",
".",
"bind",
"(",
"this",
")",
";",
"iterate",
"=",
"iterate",
".",
"bind",
"(",
"this",
")",
";",
"iterate",
"(",
")",
";",
"}"
] | Graceful shutdown stop accepting new connections. | [
"Graceful",
"shutdown",
"stop",
"accepting",
"new",
"connections",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L511-L600 |
49,935 | redisjs/jsr-server | lib/server.js | createConnection | function createConnection() {
// create the internal socket object
var server = new Socket()
, client = new Socket();
// pair the sockets
client.pair = server;
server.pair = client;
// register the server side so it is wrapped
// in a connection and stored as an active connection
this.connection(server);
// return the client side of the socket
return client;
} | javascript | function createConnection() {
// create the internal socket object
var server = new Socket()
, client = new Socket();
// pair the sockets
client.pair = server;
server.pair = client;
// register the server side so it is wrapped
// in a connection and stored as an active connection
this.connection(server);
// return the client side of the socket
return client;
} | [
"function",
"createConnection",
"(",
")",
"{",
"// create the internal socket object",
"var",
"server",
"=",
"new",
"Socket",
"(",
")",
",",
"client",
"=",
"new",
"Socket",
"(",
")",
";",
"// pair the sockets",
"client",
".",
"pair",
"=",
"server",
";",
"server",
".",
"pair",
"=",
"client",
";",
"// register the server side so it is wrapped",
"// in a connection and stored as an active connection",
"this",
".",
"connection",
"(",
"server",
")",
";",
"// return the client side of the socket",
"return",
"client",
";",
"}"
] | Creates a socket object to be used by a client
within this process. | [
"Creates",
"a",
"socket",
"object",
"to",
"be",
"used",
"by",
"a",
"client",
"within",
"this",
"process",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/server.js#L613-L629 |
49,936 | wshager/xvnode | lib/xvnode.js | serialize | function serialize(node, indent) {
indent = indent || 0;
var type = node._type;
var v;
if (type < 3 || type == 7) {
var name = node.name();
if (type == 1) {
var children = node;
var ret = "";
var attrs = "";
var hasChildNodes = false;
children.forEach(function (child, i) {
var type = child._type;
if (type == 2) {
attrs += " " + serialize(child);
} else {
if (type == 1) hasChildNodes = hasChildNodes || true;
ret += serialize(child, indent + 1);
}
});
var dent = "";
for (var i = 0; i < indent; i++) {
dent += "\t";
}
return "\n" + dent + "<" + name + attrs + (ret === "" ? "/>" : ">") + ret + (ret === "" ? "" : (hasChildNodes ? "\n" + dent : "") + "</" + name + ">");
} else if (type == 7) {
v = node.value();
return "<?" + name + " " + v.replace(/&/g, "&") + "?>";
} else {
v = node.value();
return name + "=\"" + v.replace(/&/g, "&") + "\"";
}
} else if (type == 3 || type == 4 || type == 7 || type == 8) {
v = node.value();
if (type == 4) {
return "<![CDATA[" + v + "]]>";
} else if (type == 8) {
return "<!--" + v + "-->";
} else {
return v.replace(/&/g, "&");
}
} else {
return "";
}
} | javascript | function serialize(node, indent) {
indent = indent || 0;
var type = node._type;
var v;
if (type < 3 || type == 7) {
var name = node.name();
if (type == 1) {
var children = node;
var ret = "";
var attrs = "";
var hasChildNodes = false;
children.forEach(function (child, i) {
var type = child._type;
if (type == 2) {
attrs += " " + serialize(child);
} else {
if (type == 1) hasChildNodes = hasChildNodes || true;
ret += serialize(child, indent + 1);
}
});
var dent = "";
for (var i = 0; i < indent; i++) {
dent += "\t";
}
return "\n" + dent + "<" + name + attrs + (ret === "" ? "/>" : ">") + ret + (ret === "" ? "" : (hasChildNodes ? "\n" + dent : "") + "</" + name + ">");
} else if (type == 7) {
v = node.value();
return "<?" + name + " " + v.replace(/&/g, "&") + "?>";
} else {
v = node.value();
return name + "=\"" + v.replace(/&/g, "&") + "\"";
}
} else if (type == 3 || type == 4 || type == 7 || type == 8) {
v = node.value();
if (type == 4) {
return "<![CDATA[" + v + "]]>";
} else if (type == 8) {
return "<!--" + v + "-->";
} else {
return v.replace(/&/g, "&");
}
} else {
return "";
}
} | [
"function",
"serialize",
"(",
"node",
",",
"indent",
")",
"{",
"indent",
"=",
"indent",
"||",
"0",
";",
"var",
"type",
"=",
"node",
".",
"_type",
";",
"var",
"v",
";",
"if",
"(",
"type",
"<",
"3",
"||",
"type",
"==",
"7",
")",
"{",
"var",
"name",
"=",
"node",
".",
"name",
"(",
")",
";",
"if",
"(",
"type",
"==",
"1",
")",
"{",
"var",
"children",
"=",
"node",
";",
"var",
"ret",
"=",
"\"\"",
";",
"var",
"attrs",
"=",
"\"\"",
";",
"var",
"hasChildNodes",
"=",
"false",
";",
"children",
".",
"forEach",
"(",
"function",
"(",
"child",
",",
"i",
")",
"{",
"var",
"type",
"=",
"child",
".",
"_type",
";",
"if",
"(",
"type",
"==",
"2",
")",
"{",
"attrs",
"+=",
"\" \"",
"+",
"serialize",
"(",
"child",
")",
";",
"}",
"else",
"{",
"if",
"(",
"type",
"==",
"1",
")",
"hasChildNodes",
"=",
"hasChildNodes",
"||",
"true",
";",
"ret",
"+=",
"serialize",
"(",
"child",
",",
"indent",
"+",
"1",
")",
";",
"}",
"}",
")",
";",
"var",
"dent",
"=",
"\"\"",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"indent",
";",
"i",
"++",
")",
"{",
"dent",
"+=",
"\"\\t\"",
";",
"}",
"return",
"\"\\n\"",
"+",
"dent",
"+",
"\"<\"",
"+",
"name",
"+",
"attrs",
"+",
"(",
"ret",
"===",
"\"\"",
"?",
"\"/>\"",
":",
"\">\"",
")",
"+",
"ret",
"+",
"(",
"ret",
"===",
"\"\"",
"?",
"\"\"",
":",
"(",
"hasChildNodes",
"?",
"\"\\n\"",
"+",
"dent",
":",
"\"\"",
")",
"+",
"\"</\"",
"+",
"name",
"+",
"\">\"",
")",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"7",
")",
"{",
"v",
"=",
"node",
".",
"value",
"(",
")",
";",
"return",
"\"<?\"",
"+",
"name",
"+",
"\" \"",
"+",
"v",
".",
"replace",
"(",
"/",
"&",
"/",
"g",
",",
"\"&\"",
")",
"+",
"\"?>\"",
";",
"}",
"else",
"{",
"v",
"=",
"node",
".",
"value",
"(",
")",
";",
"return",
"name",
"+",
"\"=\\\"\"",
"+",
"v",
".",
"replace",
"(",
"/",
"&",
"/",
"g",
",",
"\"&\"",
")",
"+",
"\"\\\"\"",
";",
"}",
"}",
"else",
"if",
"(",
"type",
"==",
"3",
"||",
"type",
"==",
"4",
"||",
"type",
"==",
"7",
"||",
"type",
"==",
"8",
")",
"{",
"v",
"=",
"node",
".",
"value",
"(",
")",
";",
"if",
"(",
"type",
"==",
"4",
")",
"{",
"return",
"\"<![CDATA[\"",
"+",
"v",
"+",
"\"]]>\"",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"8",
")",
"{",
"return",
"\"<!--\"",
"+",
"v",
"+",
"\"-->\"",
";",
"}",
"else",
"{",
"return",
"v",
".",
"replace",
"(",
"/",
"&",
"/",
"g",
",",
"\"&\"",
")",
";",
"}",
"}",
"else",
"{",
"return",
"\"\"",
";",
"}",
"}"
] | children is a no-op because it's equal to the node | [
"children",
"is",
"a",
"no",
"-",
"op",
"because",
"it",
"s",
"equal",
"to",
"the",
"node"
] | 01b1a72da3065da19e4397bcb67a5937bf49fdfc | https://github.com/wshager/xvnode/blob/01b1a72da3065da19e4397bcb67a5937bf49fdfc/lib/xvnode.js#L93-L137 |
49,937 | andrewscwei/requiem | src/utils/getRect.js | getRect | function getRect(element, reference) {
if (element === window) return getViewportRect();
if (!reference) reference = window;
let elements = [].concat(element);
let n = elements.length;
if (n <= 0) return null;
let refRect = getRect(reference);
if (!assert(refRect, 'Cannot determine reference FOV.')) return null;
let winRect = getRect(window);
let rect = {};
for (let i = 0; i < n; i++) {
let e = elements[i];
let c = e.getBoundingClientRect();
let w = c.width;
let h = c.height;
let t = c.top + winRect.top;
if (reference !== window) t -= refRect.top;
let l = c.left + winRect.left;
if (reference !== window) l -= refRect.left;
let b = t + h;
let r = l + w;
rect.left = (rect.left === undefined) ? l : rect.left = Math.min(rect.left, l);
rect.right = (rect.right === undefined) ? r : rect.right = Math.max(rect.right, r);
rect.top = (rect.top === undefined) ? t : rect.top = Math.min(rect.top, t);
rect.bottom = (rect.bottom === undefined) ? b : rect.bottom = Math.max(rect.bottom, b);
}
rect.width = rect.right - rect.left;
rect.height = rect.bottom - rect.top;
return rect;
} | javascript | function getRect(element, reference) {
if (element === window) return getViewportRect();
if (!reference) reference = window;
let elements = [].concat(element);
let n = elements.length;
if (n <= 0) return null;
let refRect = getRect(reference);
if (!assert(refRect, 'Cannot determine reference FOV.')) return null;
let winRect = getRect(window);
let rect = {};
for (let i = 0; i < n; i++) {
let e = elements[i];
let c = e.getBoundingClientRect();
let w = c.width;
let h = c.height;
let t = c.top + winRect.top;
if (reference !== window) t -= refRect.top;
let l = c.left + winRect.left;
if (reference !== window) l -= refRect.left;
let b = t + h;
let r = l + w;
rect.left = (rect.left === undefined) ? l : rect.left = Math.min(rect.left, l);
rect.right = (rect.right === undefined) ? r : rect.right = Math.max(rect.right, r);
rect.top = (rect.top === undefined) ? t : rect.top = Math.min(rect.top, t);
rect.bottom = (rect.bottom === undefined) ? b : rect.bottom = Math.max(rect.bottom, b);
}
rect.width = rect.right - rect.left;
rect.height = rect.bottom - rect.top;
return rect;
} | [
"function",
"getRect",
"(",
"element",
",",
"reference",
")",
"{",
"if",
"(",
"element",
"===",
"window",
")",
"return",
"getViewportRect",
"(",
")",
";",
"if",
"(",
"!",
"reference",
")",
"reference",
"=",
"window",
";",
"let",
"elements",
"=",
"[",
"]",
".",
"concat",
"(",
"element",
")",
";",
"let",
"n",
"=",
"elements",
".",
"length",
";",
"if",
"(",
"n",
"<=",
"0",
")",
"return",
"null",
";",
"let",
"refRect",
"=",
"getRect",
"(",
"reference",
")",
";",
"if",
"(",
"!",
"assert",
"(",
"refRect",
",",
"'Cannot determine reference FOV.'",
")",
")",
"return",
"null",
";",
"let",
"winRect",
"=",
"getRect",
"(",
"window",
")",
";",
"let",
"rect",
"=",
"{",
"}",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"let",
"e",
"=",
"elements",
"[",
"i",
"]",
";",
"let",
"c",
"=",
"e",
".",
"getBoundingClientRect",
"(",
")",
";",
"let",
"w",
"=",
"c",
".",
"width",
";",
"let",
"h",
"=",
"c",
".",
"height",
";",
"let",
"t",
"=",
"c",
".",
"top",
"+",
"winRect",
".",
"top",
";",
"if",
"(",
"reference",
"!==",
"window",
")",
"t",
"-=",
"refRect",
".",
"top",
";",
"let",
"l",
"=",
"c",
".",
"left",
"+",
"winRect",
".",
"left",
";",
"if",
"(",
"reference",
"!==",
"window",
")",
"l",
"-=",
"refRect",
".",
"left",
";",
"let",
"b",
"=",
"t",
"+",
"h",
";",
"let",
"r",
"=",
"l",
"+",
"w",
";",
"rect",
".",
"left",
"=",
"(",
"rect",
".",
"left",
"===",
"undefined",
")",
"?",
"l",
":",
"rect",
".",
"left",
"=",
"Math",
".",
"min",
"(",
"rect",
".",
"left",
",",
"l",
")",
";",
"rect",
".",
"right",
"=",
"(",
"rect",
".",
"right",
"===",
"undefined",
")",
"?",
"r",
":",
"rect",
".",
"right",
"=",
"Math",
".",
"max",
"(",
"rect",
".",
"right",
",",
"r",
")",
";",
"rect",
".",
"top",
"=",
"(",
"rect",
".",
"top",
"===",
"undefined",
")",
"?",
"t",
":",
"rect",
".",
"top",
"=",
"Math",
".",
"min",
"(",
"rect",
".",
"top",
",",
"t",
")",
";",
"rect",
".",
"bottom",
"=",
"(",
"rect",
".",
"bottom",
"===",
"undefined",
")",
"?",
"b",
":",
"rect",
".",
"bottom",
"=",
"Math",
".",
"max",
"(",
"rect",
".",
"bottom",
",",
"b",
")",
";",
"}",
"rect",
".",
"width",
"=",
"rect",
".",
"right",
"-",
"rect",
".",
"left",
";",
"rect",
".",
"height",
"=",
"rect",
".",
"bottom",
"-",
"rect",
".",
"top",
";",
"return",
"rect",
";",
"}"
] | Gets the rect of a given element or the overall rect of an array of elements.
@param {Node|Node[]} element
@param {Object} [reference=window]
@return {Object} Object containing top, left, bottom, right, width, height.
@alias module:requiem~utils.getRect | [
"Gets",
"the",
"rect",
"of",
"a",
"given",
"element",
"or",
"the",
"overall",
"rect",
"of",
"an",
"array",
"of",
"elements",
"."
] | c4182bfffc9841c6de5718f689ad3c2060511777 | https://github.com/andrewscwei/requiem/blob/c4182bfffc9841c6de5718f689ad3c2060511777/src/utils/getRect.js#L18-L58 |
49,938 | Lindurion/closure-pro-build | 3p/closure-library-20130212/closure/goog/result/resultutil.js | function(res) {
var results = /** @type {Array.<!goog.result.Result>} */ (
res.getValue());
if (goog.array.every(results, resolvedSuccessfully)) {
combinedResult.setValue(results);
} else {
combinedResult.setError(results);
}
} | javascript | function(res) {
var results = /** @type {Array.<!goog.result.Result>} */ (
res.getValue());
if (goog.array.every(results, resolvedSuccessfully)) {
combinedResult.setValue(results);
} else {
combinedResult.setError(results);
}
} | [
"function",
"(",
"res",
")",
"{",
"var",
"results",
"=",
"/** @type {Array.<!goog.result.Result>} */",
"(",
"res",
".",
"getValue",
"(",
")",
")",
";",
"if",
"(",
"goog",
".",
"array",
".",
"every",
"(",
"results",
",",
"resolvedSuccessfully",
")",
")",
"{",
"combinedResult",
".",
"setValue",
"(",
"results",
")",
";",
"}",
"else",
"{",
"combinedResult",
".",
"setError",
"(",
"results",
")",
";",
"}",
"}"
] | The combined result never ERRORs | [
"The",
"combined",
"result",
"never",
"ERRORs"
] | c279d0fcc3a65969d2fe965f55e627b074792f1a | https://github.com/Lindurion/closure-pro-build/blob/c279d0fcc3a65969d2fe965f55e627b074792f1a/3p/closure-library-20130212/closure/goog/result/resultutil.js#L451-L459 |
|
49,939 | pupipipu/botbuilder-proxy | Node/core/lib/dialogs/PromptRecognizers.js | matchAll | function matchAll(exp, text) {
exp.lastIndex = 0;
var matches = [];
var match;
while ((match = exp.exec(text)) != null) {
matches.push(match[0]);
}
return matches;
} | javascript | function matchAll(exp, text) {
exp.lastIndex = 0;
var matches = [];
var match;
while ((match = exp.exec(text)) != null) {
matches.push(match[0]);
}
return matches;
} | [
"function",
"matchAll",
"(",
"exp",
",",
"text",
")",
"{",
"exp",
".",
"lastIndex",
"=",
"0",
";",
"var",
"matches",
"=",
"[",
"]",
";",
"var",
"match",
";",
"while",
"(",
"(",
"match",
"=",
"exp",
".",
"exec",
"(",
"text",
")",
")",
"!=",
"null",
")",
"{",
"matches",
".",
"push",
"(",
"match",
"[",
"0",
"]",
")",
";",
"}",
"return",
"matches",
";",
"}"
] | Matches all occurences of an expression in a string. | [
"Matches",
"all",
"occurences",
"of",
"an",
"expression",
"in",
"a",
"string",
"."
] | 4c2e9dddddcd579de98280bbceb011c357bfca1c | https://github.com/pupipipu/botbuilder-proxy/blob/4c2e9dddddcd579de98280bbceb011c357bfca1c/Node/core/lib/dialogs/PromptRecognizers.js#L345-L353 |
49,940 | pupipipu/botbuilder-proxy | Node/core/lib/dialogs/PromptRecognizers.js | tokenize | function tokenize(text) {
var tokens = [];
if (text && text.length > 0) {
var token = '';
for (var i = 0; i < text.length; i++) {
var chr = text[i];
if (breakingChars.indexOf(chr) >= 0) {
if (token.length > 0) {
tokens.push(token);
}
token = '';
}
else {
token += chr;
}
}
if (token.length > 0) {
tokens.push(token);
}
}
return tokens;
} | javascript | function tokenize(text) {
var tokens = [];
if (text && text.length > 0) {
var token = '';
for (var i = 0; i < text.length; i++) {
var chr = text[i];
if (breakingChars.indexOf(chr) >= 0) {
if (token.length > 0) {
tokens.push(token);
}
token = '';
}
else {
token += chr;
}
}
if (token.length > 0) {
tokens.push(token);
}
}
return tokens;
} | [
"function",
"tokenize",
"(",
"text",
")",
"{",
"var",
"tokens",
"=",
"[",
"]",
";",
"if",
"(",
"text",
"&&",
"text",
".",
"length",
">",
"0",
")",
"{",
"var",
"token",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"text",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"chr",
"=",
"text",
"[",
"i",
"]",
";",
"if",
"(",
"breakingChars",
".",
"indexOf",
"(",
"chr",
")",
">=",
"0",
")",
"{",
"if",
"(",
"token",
".",
"length",
">",
"0",
")",
"{",
"tokens",
".",
"push",
"(",
"token",
")",
";",
"}",
"token",
"=",
"''",
";",
"}",
"else",
"{",
"token",
"+=",
"chr",
";",
"}",
"}",
"if",
"(",
"token",
".",
"length",
">",
"0",
")",
"{",
"tokens",
".",
"push",
"(",
"token",
")",
";",
"}",
"}",
"return",
"tokens",
";",
"}"
] | Breaks a string of text into an array of tokens. | [
"Breaks",
"a",
"string",
"of",
"text",
"into",
"an",
"array",
"of",
"tokens",
"."
] | 4c2e9dddddcd579de98280bbceb011c357bfca1c | https://github.com/pupipipu/botbuilder-proxy/blob/4c2e9dddddcd579de98280bbceb011c357bfca1c/Node/core/lib/dialogs/PromptRecognizers.js#L355-L376 |
49,941 | unkelpehr/qbus | lib/index.js | normalizePath | function normalizePath (path) {
// Remove double slashes
if (path.indexOf('//') !== -1) {
path = path.replace(/\/+/g, '/');
}
// Shift slash
if (path[0] === '/') {
path = path.substr(1);
}
// Pop slash
if (path[path.length - 1] === '/') {
path = path.substr(0, path.length - 1);
}
return path;
} | javascript | function normalizePath (path) {
// Remove double slashes
if (path.indexOf('//') !== -1) {
path = path.replace(/\/+/g, '/');
}
// Shift slash
if (path[0] === '/') {
path = path.substr(1);
}
// Pop slash
if (path[path.length - 1] === '/') {
path = path.substr(0, path.length - 1);
}
return path;
} | [
"function",
"normalizePath",
"(",
"path",
")",
"{",
"// Remove double slashes",
"if",
"(",
"path",
".",
"indexOf",
"(",
"'//'",
")",
"!==",
"-",
"1",
")",
"{",
"path",
"=",
"path",
".",
"replace",
"(",
"/",
"\\/+",
"/",
"g",
",",
"'/'",
")",
";",
"}",
"// Shift slash",
"if",
"(",
"path",
"[",
"0",
"]",
"===",
"'/'",
")",
"{",
"path",
"=",
"path",
".",
"substr",
"(",
"1",
")",
";",
"}",
"// Pop slash",
"if",
"(",
"path",
"[",
"path",
".",
"length",
"-",
"1",
"]",
"===",
"'/'",
")",
"{",
"path",
"=",
"path",
".",
"substr",
"(",
"0",
",",
"path",
".",
"length",
"-",
"1",
")",
";",
"}",
"return",
"path",
";",
"}"
] | Normalizes given path by converting double frontslashes to singles
and removing the slashes from the beginning and end of the string.
@param {String} path The path to normalize
@return {String} Normalized path | [
"Normalizes",
"given",
"path",
"by",
"converting",
"double",
"frontslashes",
"to",
"singles",
"and",
"removing",
"the",
"slashes",
"from",
"the",
"beginning",
"and",
"end",
"of",
"the",
"string",
"."
] | 95f1e1a9579ada651608dc84681f15a2f6fd0248 | https://github.com/unkelpehr/qbus/blob/95f1e1a9579ada651608dc84681f15a2f6fd0248/lib/index.js#L14-L31 |
49,942 | unkelpehr/qbus | lib/index.js | execQuery | function execQuery (query) {
var match, i, arr;
if ((match = this.exec(query))) {
arr = new Array(match.length - 1);
for (i = 1; i < match.length; ++i) {
arr[i - 1] = match[i];
}
return arr;
}
return match;
} | javascript | function execQuery (query) {
var match, i, arr;
if ((match = this.exec(query))) {
arr = new Array(match.length - 1);
for (i = 1; i < match.length; ++i) {
arr[i - 1] = match[i];
}
return arr;
}
return match;
} | [
"function",
"execQuery",
"(",
"query",
")",
"{",
"var",
"match",
",",
"i",
",",
"arr",
";",
"if",
"(",
"(",
"match",
"=",
"this",
".",
"exec",
"(",
"query",
")",
")",
")",
"{",
"arr",
"=",
"new",
"Array",
"(",
"match",
".",
"length",
"-",
"1",
")",
";",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<",
"match",
".",
"length",
";",
"++",
"i",
")",
"{",
"arr",
"[",
"i",
"-",
"1",
"]",
"=",
"match",
"[",
"i",
"]",
";",
"}",
"return",
"arr",
";",
"}",
"return",
"match",
";",
"}"
] | Passes given query to 'this.exec' and shifts the first, mandatory, full match.
This function is added as a property to all RegExp-objects that passes Qbus.parse.
@method execQuery
@param {String} query String execute
@return {Null|Array>} Null if it does not match, otherwise Array. | [
"Passes",
"given",
"query",
"to",
"this",
".",
"exec",
"and",
"shifts",
"the",
"first",
"mandatory",
"full",
"match",
".",
"This",
"function",
"is",
"added",
"as",
"a",
"property",
"to",
"all",
"RegExp",
"-",
"objects",
"that",
"passes",
"Qbus",
".",
"parse",
"."
] | 95f1e1a9579ada651608dc84681f15a2f6fd0248 | https://github.com/unkelpehr/qbus/blob/95f1e1a9579ada651608dc84681f15a2f6fd0248/lib/index.js#L64-L78 |
49,943 | unkelpehr/qbus | lib/index.js | parse | function parse (expr) {
var finalRegexp,
strSlashPref;
if (typeof expr !== 'string') {
// Handle RegExp `expr`
if (expr instanceof RegExp) {
finalRegexp = new RegExp(expr);
finalRegexp.query = execQuery;
return finalRegexp;
}
throw new TypeError(
'Usage: qbus.parse(<`query` = String|RegExp>)\n' +
'Got: qbus.parse(<`' + typeof expr + '` = ' + expr + '>)'
);
}
strSlashPref = expr[expr.length - 1] === '/';
// Trim slashes and remove doubles
expr = normalizePath(expr);
// Pass everything from and including possible beginning frontslash
// until and not including the next frontslash, to `parseLevel`.
expr = expr.replace(/\/?[^\/]+?(?=\/|$)/g, function (match, index) {
// Return level if it doesn't contain any modifiers.
// : must be preceeded by / or start of string to count
// ? must be used with valid : to count (so we don't need to check for that)
// * always counts
if (match.indexOf('*') === -1 && (match.length <= 2 || !/(^|\/)+\:+?/.test(match))) {
return match.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var slashSuff = match[0] === '/' ? '/' : '',
slashPref = !!expr[match.length + index] || strSlashPref,
level = slashSuff ? match.substr(1) : match,
firstChar = level[0],
lastChar = level.substr(-1);
// Handle captures
if (firstChar === ':') {
// Handle optional :capture?
if (lastChar === '?') {
// Wrap any preceding slash in the optional capture group
return (slashSuff ? '(?:/([^/]+?))?' : '([^/]+?)?');
}
// Handle mandatory :capture
return slashSuff + '([^/]+?)';
}
// All matches that end with a slash or does not end with * are easy.
// We'll just choose to capture anything except a frontslash.
//
// /some/stuff*/ => /some/stuff([^/]+)?/
// /some/st*ff/ => /some/st([^/]+)?ff/
if (slashPref || lastChar !== '*') {
return slashSuff + level.replace(/\*/g, '([^/]+)?');
}
// Handle all matches that ends with * and are not followd by frontslash; 'stuff*', '*'.
// We'll replace all asterisks except the last with catch-alls. The last one is omitted and replaced with
// a pattern that matches everything up until, but not included, the last frontslash in the string or end-of-string.
//
// /some/stuff* => some/stuff(.*?(?:(?=\/$)|(?=$)))?
// /some/st*ff* => some/st(.*)?ff(.*?(?:(?=\/$)|(?=$)))?
// /* => (.*?(?:(?=\\/$)|(?=$)))?
return slashSuff + level.replace(/\*(?!$)/g, '(.*)?').slice(0, -1) + '(.*?(?:(?=/$)|(?=$)))?';
});
// Create RegExp object from the parsed query
finalRegexp = new RegExp('^/?' + expr + '/?$', 'i');
// Add `execQuery` to it's properties
finalRegexp.query = execQuery;
return finalRegexp;
} | javascript | function parse (expr) {
var finalRegexp,
strSlashPref;
if (typeof expr !== 'string') {
// Handle RegExp `expr`
if (expr instanceof RegExp) {
finalRegexp = new RegExp(expr);
finalRegexp.query = execQuery;
return finalRegexp;
}
throw new TypeError(
'Usage: qbus.parse(<`query` = String|RegExp>)\n' +
'Got: qbus.parse(<`' + typeof expr + '` = ' + expr + '>)'
);
}
strSlashPref = expr[expr.length - 1] === '/';
// Trim slashes and remove doubles
expr = normalizePath(expr);
// Pass everything from and including possible beginning frontslash
// until and not including the next frontslash, to `parseLevel`.
expr = expr.replace(/\/?[^\/]+?(?=\/|$)/g, function (match, index) {
// Return level if it doesn't contain any modifiers.
// : must be preceeded by / or start of string to count
// ? must be used with valid : to count (so we don't need to check for that)
// * always counts
if (match.indexOf('*') === -1 && (match.length <= 2 || !/(^|\/)+\:+?/.test(match))) {
return match.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var slashSuff = match[0] === '/' ? '/' : '',
slashPref = !!expr[match.length + index] || strSlashPref,
level = slashSuff ? match.substr(1) : match,
firstChar = level[0],
lastChar = level.substr(-1);
// Handle captures
if (firstChar === ':') {
// Handle optional :capture?
if (lastChar === '?') {
// Wrap any preceding slash in the optional capture group
return (slashSuff ? '(?:/([^/]+?))?' : '([^/]+?)?');
}
// Handle mandatory :capture
return slashSuff + '([^/]+?)';
}
// All matches that end with a slash or does not end with * are easy.
// We'll just choose to capture anything except a frontslash.
//
// /some/stuff*/ => /some/stuff([^/]+)?/
// /some/st*ff/ => /some/st([^/]+)?ff/
if (slashPref || lastChar !== '*') {
return slashSuff + level.replace(/\*/g, '([^/]+)?');
}
// Handle all matches that ends with * and are not followd by frontslash; 'stuff*', '*'.
// We'll replace all asterisks except the last with catch-alls. The last one is omitted and replaced with
// a pattern that matches everything up until, but not included, the last frontslash in the string or end-of-string.
//
// /some/stuff* => some/stuff(.*?(?:(?=\/$)|(?=$)))?
// /some/st*ff* => some/st(.*)?ff(.*?(?:(?=\/$)|(?=$)))?
// /* => (.*?(?:(?=\\/$)|(?=$)))?
return slashSuff + level.replace(/\*(?!$)/g, '(.*)?').slice(0, -1) + '(.*?(?:(?=/$)|(?=$)))?';
});
// Create RegExp object from the parsed query
finalRegexp = new RegExp('^/?' + expr + '/?$', 'i');
// Add `execQuery` to it's properties
finalRegexp.query = execQuery;
return finalRegexp;
} | [
"function",
"parse",
"(",
"expr",
")",
"{",
"var",
"finalRegexp",
",",
"strSlashPref",
";",
"if",
"(",
"typeof",
"expr",
"!==",
"'string'",
")",
"{",
"// Handle RegExp `expr`",
"if",
"(",
"expr",
"instanceof",
"RegExp",
")",
"{",
"finalRegexp",
"=",
"new",
"RegExp",
"(",
"expr",
")",
";",
"finalRegexp",
".",
"query",
"=",
"execQuery",
";",
"return",
"finalRegexp",
";",
"}",
"throw",
"new",
"TypeError",
"(",
"'Usage: qbus.parse(<`query` = String|RegExp>)\\n'",
"+",
"'Got: qbus.parse(<`'",
"+",
"typeof",
"expr",
"+",
"'` = '",
"+",
"expr",
"+",
"'>)'",
")",
";",
"}",
"strSlashPref",
"=",
"expr",
"[",
"expr",
".",
"length",
"-",
"1",
"]",
"===",
"'/'",
";",
"// Trim slashes and remove doubles",
"expr",
"=",
"normalizePath",
"(",
"expr",
")",
";",
"// Pass everything from and including possible beginning frontslash",
"// until and not including the next frontslash, to `parseLevel`.",
"expr",
"=",
"expr",
".",
"replace",
"(",
"/",
"\\/?[^\\/]+?(?=\\/|$)",
"/",
"g",
",",
"function",
"(",
"match",
",",
"index",
")",
"{",
"// Return level if it doesn't contain any modifiers.",
"// : must be preceeded by / or start of string to count",
"// ? must be used with valid : to count (so we don't need to check for that)",
"// * always counts",
"if",
"(",
"match",
".",
"indexOf",
"(",
"'*'",
")",
"===",
"-",
"1",
"&&",
"(",
"match",
".",
"length",
"<=",
"2",
"||",
"!",
"/",
"(^|\\/)+\\:+?",
"/",
".",
"test",
"(",
"match",
")",
")",
")",
"{",
"return",
"match",
".",
"replace",
"(",
"/",
"[-\\/\\\\^$*+?.()|[\\]{}]",
"/",
"g",
",",
"'\\\\$&'",
")",
";",
"}",
"var",
"slashSuff",
"=",
"match",
"[",
"0",
"]",
"===",
"'/'",
"?",
"'/'",
":",
"''",
",",
"slashPref",
"=",
"!",
"!",
"expr",
"[",
"match",
".",
"length",
"+",
"index",
"]",
"||",
"strSlashPref",
",",
"level",
"=",
"slashSuff",
"?",
"match",
".",
"substr",
"(",
"1",
")",
":",
"match",
",",
"firstChar",
"=",
"level",
"[",
"0",
"]",
",",
"lastChar",
"=",
"level",
".",
"substr",
"(",
"-",
"1",
")",
";",
"// Handle captures",
"if",
"(",
"firstChar",
"===",
"':'",
")",
"{",
"// Handle optional :capture?",
"if",
"(",
"lastChar",
"===",
"'?'",
")",
"{",
"// Wrap any preceding slash in the optional capture group",
"return",
"(",
"slashSuff",
"?",
"'(?:/([^/]+?))?'",
":",
"'([^/]+?)?'",
")",
";",
"}",
"// Handle mandatory :capture",
"return",
"slashSuff",
"+",
"'([^/]+?)'",
";",
"}",
"// All matches that end with a slash or does not end with * are easy.",
"// We'll just choose to capture anything except a frontslash.",
"// ",
"// /some/stuff*/ => /some/stuff([^/]+)?/",
"// /some/st*ff/ => /some/st([^/]+)?ff/",
"if",
"(",
"slashPref",
"||",
"lastChar",
"!==",
"'*'",
")",
"{",
"return",
"slashSuff",
"+",
"level",
".",
"replace",
"(",
"/",
"\\*",
"/",
"g",
",",
"'([^/]+)?'",
")",
";",
"}",
"// Handle all matches that ends with * and are not followd by frontslash; 'stuff*', '*'.",
"// We'll replace all asterisks except the last with catch-alls. The last one is omitted and replaced with",
"// a pattern that matches everything up until, but not included, the last frontslash in the string or end-of-string.",
"// ",
"// /some/stuff* => some/stuff(.*?(?:(?=\\/$)|(?=$)))?",
"// /some/st*ff* => some/st(.*)?ff(.*?(?:(?=\\/$)|(?=$)))?",
"// /* => (.*?(?:(?=\\\\/$)|(?=$)))?",
"return",
"slashSuff",
"+",
"level",
".",
"replace",
"(",
"/",
"\\*(?!$)",
"/",
"g",
",",
"'(.*)?'",
")",
".",
"slice",
"(",
"0",
",",
"-",
"1",
")",
"+",
"'(.*?(?:(?=/$)|(?=$)))?'",
";",
"}",
")",
";",
"// Create RegExp object from the parsed query",
"finalRegexp",
"=",
"new",
"RegExp",
"(",
"'^/?'",
"+",
"expr",
"+",
"'/?$'",
",",
"'i'",
")",
";",
"// Add `execQuery` to it's properties",
"finalRegexp",
".",
"query",
"=",
"execQuery",
";",
"return",
"finalRegexp",
";",
"}"
] | Converts given expression to RegExp.
If a RegExp is given it will copy it and add 'execQuery' to its properties.
@method emit
@param {String|RegExp} expr The string to convert or RegExp to add 'execQuery'.
@return {RegExp} | [
"Converts",
"given",
"expression",
"to",
"RegExp",
".",
"If",
"a",
"RegExp",
"is",
"given",
"it",
"will",
"copy",
"it",
"and",
"add",
"execQuery",
"to",
"its",
"properties",
"."
] | 95f1e1a9579ada651608dc84681f15a2f6fd0248 | https://github.com/unkelpehr/qbus/blob/95f1e1a9579ada651608dc84681f15a2f6fd0248/lib/index.js#L88-L167 |
49,944 | tjmehta/native-types | index.js | isNative | function isNative (val) {
if (isPrimitive(val)) {
return true
}
return natives.some(function (Class) {
return val === Class || directInstanceOf(val, Class)
})
} | javascript | function isNative (val) {
if (isPrimitive(val)) {
return true
}
return natives.some(function (Class) {
return val === Class || directInstanceOf(val, Class)
})
} | [
"function",
"isNative",
"(",
"val",
")",
"{",
"if",
"(",
"isPrimitive",
"(",
"val",
")",
")",
"{",
"return",
"true",
"}",
"return",
"natives",
".",
"some",
"(",
"function",
"(",
"Class",
")",
"{",
"return",
"val",
"===",
"Class",
"||",
"directInstanceOf",
"(",
"val",
",",
"Class",
")",
"}",
")",
"}"
] | returns if a value is an instance of native type
@param ctx.{*} ctx.val ctx.value to check if is native
@return {Boolean} ctx.true if val is native, else false | [
"returns",
"if",
"a",
"value",
"is",
"an",
"instance",
"of",
"native",
"type"
] | 8e100d2b77f530d62817864235577ff9a8cd5db5 | https://github.com/tjmehta/native-types/blob/8e100d2b77f530d62817864235577ff9a8cd5db5/index.js#L98-L105 |
49,945 | tjmehta/native-types | index.js | isPrimitive | function isPrimitive (val) {
if (val === null || val === undefined || val === Infinity || isLiterallyNaN(val)) {
return true
}
return primitives.some(function (Class) {
return val === Class || directInstanceOf(val, Class)
})
} | javascript | function isPrimitive (val) {
if (val === null || val === undefined || val === Infinity || isLiterallyNaN(val)) {
return true
}
return primitives.some(function (Class) {
return val === Class || directInstanceOf(val, Class)
})
} | [
"function",
"isPrimitive",
"(",
"val",
")",
"{",
"if",
"(",
"val",
"===",
"null",
"||",
"val",
"===",
"undefined",
"||",
"val",
"===",
"Infinity",
"||",
"isLiterallyNaN",
"(",
"val",
")",
")",
"{",
"return",
"true",
"}",
"return",
"primitives",
".",
"some",
"(",
"function",
"(",
"Class",
")",
"{",
"return",
"val",
"===",
"Class",
"||",
"directInstanceOf",
"(",
"val",
",",
"Class",
")",
"}",
")",
"}"
] | returns if a value is an instance of a primitive type
@param {*} thing value to check if is primitive
@return {Boolean} true if val is primitive, else false | [
"returns",
"if",
"a",
"value",
"is",
"an",
"instance",
"of",
"a",
"primitive",
"type"
] | 8e100d2b77f530d62817864235577ff9a8cd5db5 | https://github.com/tjmehta/native-types/blob/8e100d2b77f530d62817864235577ff9a8cd5db5/index.js#L112-L119 |
49,946 | base-apps/base-apps-router | dist/index.js | transform | function transform(file, enc, cb, opts) {
if (file.isNull()) {
cb(null, file);
}
if (file.isStream()) {
cb(new PluginError('base-apps-router', 'Streams not supported.'));
}
if (file.isBuffer()) {
var frontMatter = fm(file.contents.toString());
if (frontMatter.frontmatter) {
frontMatter.attributes.path = file.path;
router.addRoute(frontMatter.attributes);
file.contents = new Buffer(frontMatter.body);
}
cb(null, file);
}
} | javascript | function transform(file, enc, cb, opts) {
if (file.isNull()) {
cb(null, file);
}
if (file.isStream()) {
cb(new PluginError('base-apps-router', 'Streams not supported.'));
}
if (file.isBuffer()) {
var frontMatter = fm(file.contents.toString());
if (frontMatter.frontmatter) {
frontMatter.attributes.path = file.path;
router.addRoute(frontMatter.attributes);
file.contents = new Buffer(frontMatter.body);
}
cb(null, file);
}
} | [
"function",
"transform",
"(",
"file",
",",
"enc",
",",
"cb",
",",
"opts",
")",
"{",
"if",
"(",
"file",
".",
"isNull",
"(",
")",
")",
"{",
"cb",
"(",
"null",
",",
"file",
")",
";",
"}",
"if",
"(",
"file",
".",
"isStream",
"(",
")",
")",
"{",
"cb",
"(",
"new",
"PluginError",
"(",
"'base-apps-router'",
",",
"'Streams not supported.'",
")",
")",
";",
"}",
"if",
"(",
"file",
".",
"isBuffer",
"(",
")",
")",
"{",
"var",
"frontMatter",
"=",
"fm",
"(",
"file",
".",
"contents",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"frontMatter",
".",
"frontmatter",
")",
"{",
"frontMatter",
".",
"attributes",
".",
"path",
"=",
"file",
".",
"path",
";",
"router",
".",
"addRoute",
"(",
"frontMatter",
".",
"attributes",
")",
";",
"file",
".",
"contents",
"=",
"new",
"Buffer",
"(",
"frontMatter",
".",
"body",
")",
";",
"}",
"cb",
"(",
"null",
",",
"file",
")",
";",
"}",
"}"
] | Pulls the Front Matter from an HTML file, adds it to the route list, and returns a modified file without the Front Matter.
@prop {File} file - Vinyl file.
@prop {String} enc - File encoding.
@prop {Function} cb - Callback to return modified file or errors.
@prop {PluginOptions} opts - Plugin options. | [
"Pulls",
"the",
"Front",
"Matter",
"from",
"an",
"HTML",
"file",
"adds",
"it",
"to",
"the",
"route",
"list",
"and",
"returns",
"a",
"modified",
"file",
"without",
"the",
"Front",
"Matter",
"."
] | bf5e99987003635fbac0144c0be35d5a863065d9 | https://github.com/base-apps/base-apps-router/blob/bf5e99987003635fbac0144c0be35d5a863065d9/dist/index.js#L43-L61 |
49,947 | goliatone/core.io-data-manager | lib/manager.js | _getIdentityFields | function _getIdentityFields(Model, record, identityFields = []) {
/*
* Definition holds the schema
* inforamtion of your model.
*/
let schema = Model.definition;
let definition;
/*
* Collect all unique keys in schema.
* We can check record and see if we have
* any present that we did not specify in
* our `identityFields`.
* If we do, we are good.
*/
Object.keys(schema).map(key => {
definition = schema[key];
if (definition.unique) {
if (!identityFields.includes(key)) {
identityFields.push(key);
}
}
});
return identityFields;
} | javascript | function _getIdentityFields(Model, record, identityFields = []) {
/*
* Definition holds the schema
* inforamtion of your model.
*/
let schema = Model.definition;
let definition;
/*
* Collect all unique keys in schema.
* We can check record and see if we have
* any present that we did not specify in
* our `identityFields`.
* If we do, we are good.
*/
Object.keys(schema).map(key => {
definition = schema[key];
if (definition.unique) {
if (!identityFields.includes(key)) {
identityFields.push(key);
}
}
});
return identityFields;
} | [
"function",
"_getIdentityFields",
"(",
"Model",
",",
"record",
",",
"identityFields",
"=",
"[",
"]",
")",
"{",
"/*\n * Definition holds the schema\n * inforamtion of your model.\n */",
"let",
"schema",
"=",
"Model",
".",
"definition",
";",
"let",
"definition",
";",
"/*\n * Collect all unique keys in schema.\n * We can check record and see if we have\n * any present that we did not specify in\n * our `identityFields`.\n * If we do, we are good.\n */",
"Object",
".",
"keys",
"(",
"schema",
")",
".",
"map",
"(",
"key",
"=>",
"{",
"definition",
"=",
"schema",
"[",
"key",
"]",
";",
"if",
"(",
"definition",
".",
"unique",
")",
"{",
"if",
"(",
"!",
"identityFields",
".",
"includes",
"(",
"key",
")",
")",
"{",
"identityFields",
".",
"push",
"(",
"key",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"identityFields",
";",
"}"
] | Get the fields from a model attributes that we will use
to make our query's criteria.
@param {Object} Model Waterline collection
@param {Object} record Instance attributes
@param {Array} [identityFields=[]] Default fields
@return {Array} Complete list of identity fields | [
"Get",
"the",
"fields",
"from",
"a",
"model",
"attributes",
"that",
"we",
"will",
"use",
"to",
"make",
"our",
"query",
"s",
"criteria",
"."
] | fec79704249884290f14a2b8690f7e30288f8d55 | https://github.com/goliatone/core.io-data-manager/blob/fec79704249884290f14a2b8690f7e30288f8d55/lib/manager.js#L364-L390 |
49,948 | jloveric/Helper | Base.js | function () {
let usingNode = false;
if (typeof process === 'object') {
if (typeof process.versions === 'object') {
if (typeof process.versions.node !== 'undefined') {
usingNode = true;
}
}
}
return usingNode;
} | javascript | function () {
let usingNode = false;
if (typeof process === 'object') {
if (typeof process.versions === 'object') {
if (typeof process.versions.node !== 'undefined') {
usingNode = true;
}
}
}
return usingNode;
} | [
"function",
"(",
")",
"{",
"let",
"usingNode",
"=",
"false",
";",
"if",
"(",
"typeof",
"process",
"===",
"'object'",
")",
"{",
"if",
"(",
"typeof",
"process",
".",
"versions",
"===",
"'object'",
")",
"{",
"if",
"(",
"typeof",
"process",
".",
"versions",
".",
"node",
"!==",
"'undefined'",
")",
"{",
"usingNode",
"=",
"true",
";",
"}",
"}",
"}",
"return",
"usingNode",
";",
"}"
] | Find out if you are using node or the browser. This approach should work
for both nwjs and node and the browser. | [
"Find",
"out",
"if",
"you",
"are",
"using",
"node",
"or",
"the",
"browser",
".",
"This",
"approach",
"should",
"work",
"for",
"both",
"nwjs",
"and",
"node",
"and",
"the",
"browser",
"."
] | 96afcfa87eb58fffe3078cf573347c3e97dbc57f | https://github.com/jloveric/Helper/blob/96afcfa87eb58fffe3078cf573347c3e97dbc57f/Base.js#L12-L23 |
|
49,949 | nearform/docker-container | lib/docker.js | function() {
var split;
var opts = {};
if (process.env.DOCKER_HOST) {
split = /tcp:\/\/([0-9.]+):([0-9]+)/g.exec(process.env.DOCKER_HOST);
if (process.env.DOCKER_TLS_VERIFY === '1') {
opts.protocol = 'https';
}
else {
opts.protocol = 'http';
}
opts.host = split[1];
if (process.env.DOCKER_CERT_PATH) {
opts.ca = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem'));
opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem'));
opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem'));
}
opts.port = split[2];
}
else {
opts.socketPath = '/var/run/docker.sock';
}
return new Docker(opts);
} | javascript | function() {
var split;
var opts = {};
if (process.env.DOCKER_HOST) {
split = /tcp:\/\/([0-9.]+):([0-9]+)/g.exec(process.env.DOCKER_HOST);
if (process.env.DOCKER_TLS_VERIFY === '1') {
opts.protocol = 'https';
}
else {
opts.protocol = 'http';
}
opts.host = split[1];
if (process.env.DOCKER_CERT_PATH) {
opts.ca = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem'));
opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem'));
opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem'));
}
opts.port = split[2];
}
else {
opts.socketPath = '/var/run/docker.sock';
}
return new Docker(opts);
} | [
"function",
"(",
")",
"{",
"var",
"split",
";",
"var",
"opts",
"=",
"{",
"}",
";",
"if",
"(",
"process",
".",
"env",
".",
"DOCKER_HOST",
")",
"{",
"split",
"=",
"/",
"tcp:\\/\\/([0-9.]+):([0-9]+)",
"/",
"g",
".",
"exec",
"(",
"process",
".",
"env",
".",
"DOCKER_HOST",
")",
";",
"if",
"(",
"process",
".",
"env",
".",
"DOCKER_TLS_VERIFY",
"===",
"'1'",
")",
"{",
"opts",
".",
"protocol",
"=",
"'https'",
";",
"}",
"else",
"{",
"opts",
".",
"protocol",
"=",
"'http'",
";",
"}",
"opts",
".",
"host",
"=",
"split",
"[",
"1",
"]",
";",
"if",
"(",
"process",
".",
"env",
".",
"DOCKER_CERT_PATH",
")",
"{",
"opts",
".",
"ca",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"process",
".",
"env",
".",
"DOCKER_CERT_PATH",
",",
"'ca.pem'",
")",
")",
";",
"opts",
".",
"cert",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"process",
".",
"env",
".",
"DOCKER_CERT_PATH",
",",
"'cert.pem'",
")",
")",
";",
"opts",
".",
"key",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"process",
".",
"env",
".",
"DOCKER_CERT_PATH",
",",
"'key.pem'",
")",
")",
";",
"}",
"opts",
".",
"port",
"=",
"split",
"[",
"2",
"]",
";",
"}",
"else",
"{",
"opts",
".",
"socketPath",
"=",
"'/var/run/docker.sock'",
";",
"}",
"return",
"new",
"Docker",
"(",
"opts",
")",
";",
"}"
] | instantiates dockerode in one of two forms
new Docker({socketPath: '/var/run/docker.sock'}); - for linux hosts
new Docker({host: 'http://192.168.1.10', port: 3000}); - for mac hosts | [
"instantiates",
"dockerode",
"in",
"one",
"of",
"two",
"forms"
] | 724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17 | https://github.com/nearform/docker-container/blob/724ff6a9d8d3c116f9a6b8239594c4b5cd5e8e17/lib/docker.js#L30-L59 |
|
49,950 | chrisns/sails-linking-controllers | lib/index.js | matchPaths | function matchPaths(pageLinks, path) {
let result;
path = _.compact(path.split('/'));
result = _.filter(_.keys(pageLinks), key => {
const path2 = _.compact(key.split('/'));
const noMatch = _.filter(path2, fragment => {
return fragment.substring(0, 1) !== ':' && _.indexOf(path, fragment) !== _.indexOf(path2, fragment);
});
return noMatch.length === 0;
});
return result[0];
} | javascript | function matchPaths(pageLinks, path) {
let result;
path = _.compact(path.split('/'));
result = _.filter(_.keys(pageLinks), key => {
const path2 = _.compact(key.split('/'));
const noMatch = _.filter(path2, fragment => {
return fragment.substring(0, 1) !== ':' && _.indexOf(path, fragment) !== _.indexOf(path2, fragment);
});
return noMatch.length === 0;
});
return result[0];
} | [
"function",
"matchPaths",
"(",
"pageLinks",
",",
"path",
")",
"{",
"let",
"result",
";",
"path",
"=",
"_",
".",
"compact",
"(",
"path",
".",
"split",
"(",
"'/'",
")",
")",
";",
"result",
"=",
"_",
".",
"filter",
"(",
"_",
".",
"keys",
"(",
"pageLinks",
")",
",",
"key",
"=>",
"{",
"const",
"path2",
"=",
"_",
".",
"compact",
"(",
"key",
".",
"split",
"(",
"'/'",
")",
")",
";",
"const",
"noMatch",
"=",
"_",
".",
"filter",
"(",
"path2",
",",
"fragment",
"=>",
"{",
"return",
"fragment",
".",
"substring",
"(",
"0",
",",
"1",
")",
"!==",
"':'",
"&&",
"_",
".",
"indexOf",
"(",
"path",
",",
"fragment",
")",
"!==",
"_",
".",
"indexOf",
"(",
"path2",
",",
"fragment",
")",
";",
"}",
")",
";",
"return",
"noMatch",
".",
"length",
"===",
"0",
";",
"}",
")",
";",
"return",
"result",
"[",
"0",
"]",
";",
"}"
] | Match paths, skipping arguments.
@param path1
@param path2
@returns {boolean} | [
"Match",
"paths",
"skipping",
"arguments",
"."
] | ed4ed5c2baa9b6ea64cf8bcd9f96020149fb2ec5 | https://github.com/chrisns/sails-linking-controllers/blob/ed4ed5c2baa9b6ea64cf8bcd9f96020149fb2ec5/lib/index.js#L36-L47 |
49,951 | chrisns/sails-linking-controllers | lib/index.js | controllerLinks | function controllerLinks(route, controllerAction, reverseRouteService) {
const controllers = sails.controllers;
const controller = _.first(controllerAction.split('.'));
const path = route.path;
const actions = _.get(controllers[controller], '_config.links') || [];
let result = {};
result[path] = [];
_.each(actions, function (action) {
return result[path].push({
rel: action,
link: reverseRouteService({controller: controller + '.' + action, args: []}, false)
});
});
return result;
} | javascript | function controllerLinks(route, controllerAction, reverseRouteService) {
const controllers = sails.controllers;
const controller = _.first(controllerAction.split('.'));
const path = route.path;
const actions = _.get(controllers[controller], '_config.links') || [];
let result = {};
result[path] = [];
_.each(actions, function (action) {
return result[path].push({
rel: action,
link: reverseRouteService({controller: controller + '.' + action, args: []}, false)
});
});
return result;
} | [
"function",
"controllerLinks",
"(",
"route",
",",
"controllerAction",
",",
"reverseRouteService",
")",
"{",
"const",
"controllers",
"=",
"sails",
".",
"controllers",
";",
"const",
"controller",
"=",
"_",
".",
"first",
"(",
"controllerAction",
".",
"split",
"(",
"'.'",
")",
")",
";",
"const",
"path",
"=",
"route",
".",
"path",
";",
"const",
"actions",
"=",
"_",
".",
"get",
"(",
"controllers",
"[",
"controller",
"]",
",",
"'_config.links'",
")",
"||",
"[",
"]",
";",
"let",
"result",
"=",
"{",
"}",
";",
"result",
"[",
"path",
"]",
"=",
"[",
"]",
";",
"_",
".",
"each",
"(",
"actions",
",",
"function",
"(",
"action",
")",
"{",
"return",
"result",
"[",
"path",
"]",
".",
"push",
"(",
"{",
"rel",
":",
"action",
",",
"link",
":",
"reverseRouteService",
"(",
"{",
"controller",
":",
"controller",
"+",
"'.'",
"+",
"action",
",",
"args",
":",
"[",
"]",
"}",
",",
"false",
")",
"}",
")",
";",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Create an array of pagelinks.
@param controllers
@param reverseRoute
@param controllerAction
@returns {Promise.<Function>} | [
"Create",
"an",
"array",
"of",
"pagelinks",
"."
] | ed4ed5c2baa9b6ea64cf8bcd9f96020149fb2ec5 | https://github.com/chrisns/sails-linking-controllers/blob/ed4ed5c2baa9b6ea64cf8bcd9f96020149fb2ec5/lib/index.js#L56-L70 |
49,952 | nearit/Cordova-SDK | hooks/lib.js | function (rootdir, configData, platform) {
var configFiles = lib.getConfigFilesByTargetAndParent(rootdir, platform),
type = 'configFile';
for (var key in configFiles) {
if (configFiles.hasOwnProperty(key)) {
var configFile = configFiles[key];
var keyParts = key.split('|');
var target = keyParts[0];
var parent = keyParts[1];
var items = configData[target] || [];
configFile.getchildren().forEach(function (element) {
items.push({
parent: parent,
type: type,
destination: element.tag,
data: element
});
});
configData[target] = items;
}
}
} | javascript | function (rootdir, configData, platform) {
var configFiles = lib.getConfigFilesByTargetAndParent(rootdir, platform),
type = 'configFile';
for (var key in configFiles) {
if (configFiles.hasOwnProperty(key)) {
var configFile = configFiles[key];
var keyParts = key.split('|');
var target = keyParts[0];
var parent = keyParts[1];
var items = configData[target] || [];
configFile.getchildren().forEach(function (element) {
items.push({
parent: parent,
type: type,
destination: element.tag,
data: element
});
});
configData[target] = items;
}
}
} | [
"function",
"(",
"rootdir",
",",
"configData",
",",
"platform",
")",
"{",
"var",
"configFiles",
"=",
"lib",
".",
"getConfigFilesByTargetAndParent",
"(",
"rootdir",
",",
"platform",
")",
",",
"type",
"=",
"'configFile'",
";",
"for",
"(",
"var",
"key",
"in",
"configFiles",
")",
"{",
"if",
"(",
"configFiles",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"var",
"configFile",
"=",
"configFiles",
"[",
"key",
"]",
";",
"var",
"keyParts",
"=",
"key",
".",
"split",
"(",
"'|'",
")",
";",
"var",
"target",
"=",
"keyParts",
"[",
"0",
"]",
";",
"var",
"parent",
"=",
"keyParts",
"[",
"1",
"]",
";",
"var",
"items",
"=",
"configData",
"[",
"target",
"]",
"||",
"[",
"]",
";",
"configFile",
".",
"getchildren",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"element",
")",
"{",
"items",
".",
"push",
"(",
"{",
"parent",
":",
"parent",
",",
"type",
":",
"type",
",",
"destination",
":",
"element",
".",
"tag",
",",
"data",
":",
"element",
"}",
")",
";",
"}",
")",
";",
"configData",
"[",
"target",
"]",
"=",
"items",
";",
"}",
"}",
"}"
] | Retrieves the config.xml's config-file elements for a given
platform and parses them into JSON data
@param configData
@param platform | [
"Retrieves",
"the",
"config",
".",
"xml",
"s",
"config",
"-",
"file",
"elements",
"for",
"a",
"given",
"platform",
"and",
"parses",
"them",
"into",
"JSON",
"data"
] | f232d7db0afed1c8474eaec6f1d45a5ca6d6b3bd | https://github.com/nearit/Cordova-SDK/blob/f232d7db0afed1c8474eaec6f1d45a5ca6d6b3bd/hooks/lib.js#L160-L185 |
|
49,953 | FriendCode/qplus | index.js | retry | function retry(fn, N, retryTimeout, canContinue) {
if(typeof N === "function" && retryTimeout === canContinue === undefined) {
canContinue = N;
N = retryTimeout = undefined;
}
else if(typeof retryTimeout === "function") {
canContinue = retryTimeout;
retryTimeout = undefined;
}
// Default args
N = ((N === undefined || N < 0) ? 0 : N - 1);
retryTimeout = (retryTimeout === undefined ? 0 : retryTimeout);
canContinue = (canContinue === undefined) ?
function() { return true; } :
canContinue;
return function wrapper() {
// Actual arguments (passed first time)
var args = arguments;
var d = Q.defer();
// Our failure counter (decounter by decrementing)
var remainingTries = N;
// Create function without args
// that calls fn with args
// this makes it easier to wrap
var f = function () {
return fn.apply(null, args);
};
// The function with the try logic
var _try = function _try() {
// Call function
Q.invoke(f)
.then(function(result) {
// Success
d.resolve(result);
}, function(err) {
// Failure
// Decrement
remainingTries -= 1;
// No tries left, so reject promise with last error
if(remainingTries >= 0 && canContinue(err, N - remainingTries)) {
// We have some retries left, so retryTimeout
if(retryTimeout) {
setTimeout(_try, retryTimeout);
} else {
_try();
}
} else {
// Total failure
d.reject(err);
return;
}
}).done();
};
// Start trying
_try();
// Give promise
return d.promise;
};
} | javascript | function retry(fn, N, retryTimeout, canContinue) {
if(typeof N === "function" && retryTimeout === canContinue === undefined) {
canContinue = N;
N = retryTimeout = undefined;
}
else if(typeof retryTimeout === "function") {
canContinue = retryTimeout;
retryTimeout = undefined;
}
// Default args
N = ((N === undefined || N < 0) ? 0 : N - 1);
retryTimeout = (retryTimeout === undefined ? 0 : retryTimeout);
canContinue = (canContinue === undefined) ?
function() { return true; } :
canContinue;
return function wrapper() {
// Actual arguments (passed first time)
var args = arguments;
var d = Q.defer();
// Our failure counter (decounter by decrementing)
var remainingTries = N;
// Create function without args
// that calls fn with args
// this makes it easier to wrap
var f = function () {
return fn.apply(null, args);
};
// The function with the try logic
var _try = function _try() {
// Call function
Q.invoke(f)
.then(function(result) {
// Success
d.resolve(result);
}, function(err) {
// Failure
// Decrement
remainingTries -= 1;
// No tries left, so reject promise with last error
if(remainingTries >= 0 && canContinue(err, N - remainingTries)) {
// We have some retries left, so retryTimeout
if(retryTimeout) {
setTimeout(_try, retryTimeout);
} else {
_try();
}
} else {
// Total failure
d.reject(err);
return;
}
}).done();
};
// Start trying
_try();
// Give promise
return d.promise;
};
} | [
"function",
"retry",
"(",
"fn",
",",
"N",
",",
"retryTimeout",
",",
"canContinue",
")",
"{",
"if",
"(",
"typeof",
"N",
"===",
"\"function\"",
"&&",
"retryTimeout",
"===",
"canContinue",
"===",
"undefined",
")",
"{",
"canContinue",
"=",
"N",
";",
"N",
"=",
"retryTimeout",
"=",
"undefined",
";",
"}",
"else",
"if",
"(",
"typeof",
"retryTimeout",
"===",
"\"function\"",
")",
"{",
"canContinue",
"=",
"retryTimeout",
";",
"retryTimeout",
"=",
"undefined",
";",
"}",
"// Default args",
"N",
"=",
"(",
"(",
"N",
"===",
"undefined",
"||",
"N",
"<",
"0",
")",
"?",
"0",
":",
"N",
"-",
"1",
")",
";",
"retryTimeout",
"=",
"(",
"retryTimeout",
"===",
"undefined",
"?",
"0",
":",
"retryTimeout",
")",
";",
"canContinue",
"=",
"(",
"canContinue",
"===",
"undefined",
")",
"?",
"function",
"(",
")",
"{",
"return",
"true",
";",
"}",
":",
"canContinue",
";",
"return",
"function",
"wrapper",
"(",
")",
"{",
"// Actual arguments (passed first time)",
"var",
"args",
"=",
"arguments",
";",
"var",
"d",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"// Our failure counter (decounter by decrementing)",
"var",
"remainingTries",
"=",
"N",
";",
"// Create function without args",
"// that calls fn with args",
"// this makes it easier to wrap",
"var",
"f",
"=",
"function",
"(",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}",
";",
"// The function with the try logic",
"var",
"_try",
"=",
"function",
"_try",
"(",
")",
"{",
"// Call function",
"Q",
".",
"invoke",
"(",
"f",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"// Success",
"d",
".",
"resolve",
"(",
"result",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"// Failure",
"// Decrement",
"remainingTries",
"-=",
"1",
";",
"// No tries left, so reject promise with last error",
"if",
"(",
"remainingTries",
">=",
"0",
"&&",
"canContinue",
"(",
"err",
",",
"N",
"-",
"remainingTries",
")",
")",
"{",
"// We have some retries left, so retryTimeout",
"if",
"(",
"retryTimeout",
")",
"{",
"setTimeout",
"(",
"_try",
",",
"retryTimeout",
")",
";",
"}",
"else",
"{",
"_try",
"(",
")",
";",
"}",
"}",
"else",
"{",
"// Total failure",
"d",
".",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"}",
")",
".",
"done",
"(",
")",
";",
"}",
";",
"// Start trying",
"_try",
"(",
")",
";",
"// Give promise",
"return",
"d",
".",
"promise",
";",
"}",
";",
"}"
] | Retry a function a maximum of N times the function must use promises and will always be executed once | [
"Retry",
"a",
"function",
"a",
"maximum",
"of",
"N",
"times",
"the",
"function",
"must",
"use",
"promises",
"and",
"will",
"always",
"be",
"executed",
"once"
] | 8325d89c43cbec7df9caf91a7de571e8355d459e | https://github.com/FriendCode/qplus/blob/8325d89c43cbec7df9caf91a7de571e8355d459e/index.js#L6-L74 |
49,954 | FriendCode/qplus | index.js | _try | function _try() {
// Call function
Q.invoke(f)
.then(function(result) {
// Success
d.resolve(result);
}, function(err) {
// Failure
// Decrement
remainingTries -= 1;
// No tries left, so reject promise with last error
if(remainingTries >= 0 && canContinue(err, N - remainingTries)) {
// We have some retries left, so retryTimeout
if(retryTimeout) {
setTimeout(_try, retryTimeout);
} else {
_try();
}
} else {
// Total failure
d.reject(err);
return;
}
}).done();
} | javascript | function _try() {
// Call function
Q.invoke(f)
.then(function(result) {
// Success
d.resolve(result);
}, function(err) {
// Failure
// Decrement
remainingTries -= 1;
// No tries left, so reject promise with last error
if(remainingTries >= 0 && canContinue(err, N - remainingTries)) {
// We have some retries left, so retryTimeout
if(retryTimeout) {
setTimeout(_try, retryTimeout);
} else {
_try();
}
} else {
// Total failure
d.reject(err);
return;
}
}).done();
} | [
"function",
"_try",
"(",
")",
"{",
"// Call function",
"Q",
".",
"invoke",
"(",
"f",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"// Success",
"d",
".",
"resolve",
"(",
"result",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"// Failure",
"// Decrement",
"remainingTries",
"-=",
"1",
";",
"// No tries left, so reject promise with last error",
"if",
"(",
"remainingTries",
">=",
"0",
"&&",
"canContinue",
"(",
"err",
",",
"N",
"-",
"remainingTries",
")",
")",
"{",
"// We have some retries left, so retryTimeout",
"if",
"(",
"retryTimeout",
")",
"{",
"setTimeout",
"(",
"_try",
",",
"retryTimeout",
")",
";",
"}",
"else",
"{",
"_try",
"(",
")",
";",
"}",
"}",
"else",
"{",
"// Total failure",
"d",
".",
"reject",
"(",
"err",
")",
";",
"return",
";",
"}",
"}",
")",
".",
"done",
"(",
")",
";",
"}"
] | The function with the try logic | [
"The",
"function",
"with",
"the",
"try",
"logic"
] | 8325d89c43cbec7df9caf91a7de571e8355d459e | https://github.com/FriendCode/qplus/blob/8325d89c43cbec7df9caf91a7de571e8355d459e/index.js#L39-L66 |
49,955 | francium/highlight-page | dist/highlight-page.js | defaults | function defaults(obj, source) {
obj = obj || {};
for (var prop in source) {
if (source.hasOwnProperty(prop) && obj[prop] === void 0) {
obj[prop] = source[prop];
}
}
return obj;
} | javascript | function defaults(obj, source) {
obj = obj || {};
for (var prop in source) {
if (source.hasOwnProperty(prop) && obj[prop] === void 0) {
obj[prop] = source[prop];
}
}
return obj;
} | [
"function",
"defaults",
"(",
"obj",
",",
"source",
")",
"{",
"obj",
"=",
"obj",
"||",
"{",
"}",
";",
"for",
"(",
"var",
"prop",
"in",
"source",
")",
"{",
"if",
"(",
"source",
".",
"hasOwnProperty",
"(",
"prop",
")",
"&&",
"obj",
"[",
"prop",
"]",
"===",
"void",
"0",
")",
"{",
"obj",
"[",
"prop",
"]",
"=",
"source",
"[",
"prop",
"]",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] | Fills undefined values in obj with default properties with the same name from source object.
@param {object} obj - target object
@param {object} source - source object with default values
@returns {object} | [
"Fills",
"undefined",
"values",
"in",
"obj",
"with",
"default",
"properties",
"with",
"the",
"same",
"name",
"from",
"source",
"object",
"."
] | 4e67fc531321f9987397dc247abba59b9d5ee521 | https://github.com/francium/highlight-page/blob/4e67fc531321f9987397dc247abba59b9d5ee521/dist/highlight-page.js#L48-L58 |
49,956 | francium/highlight-page | dist/highlight-page.js | unique | function unique(arr) {
return arr.filter(function (value, idx, self) {
return self.indexOf(value) === idx;
});
} | javascript | function unique(arr) {
return arr.filter(function (value, idx, self) {
return self.indexOf(value) === idx;
});
} | [
"function",
"unique",
"(",
"arr",
")",
"{",
"return",
"arr",
".",
"filter",
"(",
"function",
"(",
"value",
",",
"idx",
",",
"self",
")",
"{",
"return",
"self",
".",
"indexOf",
"(",
"value",
")",
"===",
"idx",
";",
"}",
")",
";",
"}"
] | Returns array without duplicated values.
@param {Array} arr
@returns {Array} | [
"Returns",
"array",
"without",
"duplicated",
"values",
"."
] | 4e67fc531321f9987397dc247abba59b9d5ee521 | https://github.com/francium/highlight-page/blob/4e67fc531321f9987397dc247abba59b9d5ee521/dist/highlight-page.js#L65-L69 |
49,957 | francium/highlight-page | dist/highlight-page.js | sortByDepth | function sortByDepth(arr, descending) {
arr.sort(function (a, b) {
return dom(descending ? b : a).parents().length - dom(descending ? a : b).parents().length;
});
} | javascript | function sortByDepth(arr, descending) {
arr.sort(function (a, b) {
return dom(descending ? b : a).parents().length - dom(descending ? a : b).parents().length;
});
} | [
"function",
"sortByDepth",
"(",
"arr",
",",
"descending",
")",
"{",
"arr",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"return",
"dom",
"(",
"descending",
"?",
"b",
":",
"a",
")",
".",
"parents",
"(",
")",
".",
"length",
"-",
"dom",
"(",
"descending",
"?",
"a",
":",
"b",
")",
".",
"parents",
"(",
")",
".",
"length",
";",
"}",
")",
";",
"}"
] | Sorts array of DOM elements by its depth in DOM tree.
@param {HTMLElement[]} arr - array to sort.
@param {boolean} descending - order of sort. | [
"Sorts",
"array",
"of",
"DOM",
"elements",
"by",
"its",
"depth",
"in",
"DOM",
"tree",
"."
] | 4e67fc531321f9987397dc247abba59b9d5ee521 | https://github.com/francium/highlight-page/blob/4e67fc531321f9987397dc247abba59b9d5ee521/dist/highlight-page.js#L122-L126 |
49,958 | francium/highlight-page | dist/highlight-page.js | removeClass | function removeClass(className) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + className + '(\\b|$)', 'gi'), ' ');
}
} | javascript | function removeClass(className) {
if (el.classList) {
el.classList.remove(className);
} else {
el.className = el.className.replace(new RegExp('(^|\\b)' + className + '(\\b|$)', 'gi'), ' ');
}
} | [
"function",
"removeClass",
"(",
"className",
")",
"{",
"if",
"(",
"el",
".",
"classList",
")",
"{",
"el",
".",
"classList",
".",
"remove",
"(",
"className",
")",
";",
"}",
"else",
"{",
"el",
".",
"className",
"=",
"el",
".",
"className",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"'(^|\\\\b)'",
"+",
"className",
"+",
"'(\\\\b|$)'",
",",
"'gi'",
")",
",",
"' '",
")",
";",
"}",
"}"
] | Removes class from element.
@param {string} className | [
"Removes",
"class",
"from",
"element",
"."
] | 4e67fc531321f9987397dc247abba59b9d5ee521 | https://github.com/francium/highlight-page/blob/4e67fc531321f9987397dc247abba59b9d5ee521/dist/highlight-page.js#L191-L197 |
49,959 | francium/highlight-page | dist/highlight-page.js | prepend | function prepend(nodesToPrepend) {
var nodes = Array.prototype.slice.call(nodesToPrepend),
i = nodes.length;
while (i--) {
el.insertBefore(nodes[i], el.firstChild);
}
} | javascript | function prepend(nodesToPrepend) {
var nodes = Array.prototype.slice.call(nodesToPrepend),
i = nodes.length;
while (i--) {
el.insertBefore(nodes[i], el.firstChild);
}
} | [
"function",
"prepend",
"(",
"nodesToPrepend",
")",
"{",
"var",
"nodes",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"nodesToPrepend",
")",
",",
"i",
"=",
"nodes",
".",
"length",
";",
"while",
"(",
"i",
"--",
")",
"{",
"el",
".",
"insertBefore",
"(",
"nodes",
"[",
"i",
"]",
",",
"el",
".",
"firstChild",
")",
";",
"}",
"}"
] | Prepends child nodes to base element.
@param {Node[]} nodesToPrepend | [
"Prepends",
"child",
"nodes",
"to",
"base",
"element",
"."
] | 4e67fc531321f9987397dc247abba59b9d5ee521 | https://github.com/francium/highlight-page/blob/4e67fc531321f9987397dc247abba59b9d5ee521/dist/highlight-page.js#L203-L210 |
49,960 | francium/highlight-page | dist/highlight-page.js | unwrap | function unwrap() {
var nodes = Array.prototype.slice.call(el.childNodes),
wrapper = void 0;
nodes.forEach(function (node) {
wrapper = node.parentNode;
dom(node).insertBefore(node.parentNode);
dom(wrapper).remove();
});
return nodes;
} | javascript | function unwrap() {
var nodes = Array.prototype.slice.call(el.childNodes),
wrapper = void 0;
nodes.forEach(function (node) {
wrapper = node.parentNode;
dom(node).insertBefore(node.parentNode);
dom(wrapper).remove();
});
return nodes;
} | [
"function",
"unwrap",
"(",
")",
"{",
"var",
"nodes",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"el",
".",
"childNodes",
")",
",",
"wrapper",
"=",
"void",
"0",
";",
"nodes",
".",
"forEach",
"(",
"function",
"(",
"node",
")",
"{",
"wrapper",
"=",
"node",
".",
"parentNode",
";",
"dom",
"(",
"node",
")",
".",
"insertBefore",
"(",
"node",
".",
"parentNode",
")",
";",
"dom",
"(",
"wrapper",
")",
".",
"remove",
"(",
")",
";",
"}",
")",
";",
"return",
"nodes",
";",
"}"
] | Unwraps base element.
@returns {Node[]} - child nodes of unwrapped element. | [
"Unwraps",
"base",
"element",
"."
] | 4e67fc531321f9987397dc247abba59b9d5ee521 | https://github.com/francium/highlight-page/blob/4e67fc531321f9987397dc247abba59b9d5ee521/dist/highlight-page.js#L277-L288 |
49,961 | francium/highlight-page | dist/highlight-page.js | parents | function parents() {
var parent = void 0,
path = [];
while (!!(parent = el.parentNode)) {
path.push(parent);
el = parent;
}
return path;
} | javascript | function parents() {
var parent = void 0,
path = [];
while (!!(parent = el.parentNode)) {
path.push(parent);
el = parent;
}
return path;
} | [
"function",
"parents",
"(",
")",
"{",
"var",
"parent",
"=",
"void",
"0",
",",
"path",
"=",
"[",
"]",
";",
"while",
"(",
"!",
"!",
"(",
"parent",
"=",
"el",
".",
"parentNode",
")",
")",
"{",
"path",
".",
"push",
"(",
"parent",
")",
";",
"el",
"=",
"parent",
";",
"}",
"return",
"path",
";",
"}"
] | Returns array of base element parents.
@returns {HTMLElement[]} | [
"Returns",
"array",
"of",
"base",
"element",
"parents",
"."
] | 4e67fc531321f9987397dc247abba59b9d5ee521 | https://github.com/francium/highlight-page/blob/4e67fc531321f9987397dc247abba59b9d5ee521/dist/highlight-page.js#L294-L304 |
49,962 | francium/highlight-page | dist/highlight-page.js | fromHTML | function fromHTML(html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.childNodes;
} | javascript | function fromHTML(html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.childNodes;
} | [
"function",
"fromHTML",
"(",
"html",
")",
"{",
"var",
"div",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"div",
".",
"innerHTML",
"=",
"html",
";",
"return",
"div",
".",
"childNodes",
";",
"}"
] | Creates dom element from given html string.
@param {string} html
@returns {NodeList} | [
"Creates",
"dom",
"element",
"from",
"given",
"html",
"string",
"."
] | 4e67fc531321f9987397dc247abba59b9d5ee521 | https://github.com/francium/highlight-page/blob/4e67fc531321f9987397dc247abba59b9d5ee521/dist/highlight-page.js#L340-L344 |
49,963 | gethuman/pancakes-recipe | batch/batch.manager.js | processCommandLine | function processCommandLine() {
if (commander.list) {
listApps();
process.exit(0);
}
if (!commander.app) {
commander.help();
}
commander.endDate = commander.runDate ? moment(commander.runDate, 'MM/DD/YYYY').toDate() : new Date();
commander.startDate = moment(commander.endDate).subtract(commander.runDays, 'days').toDate();
commander.startDate.setHours(0, 0, 0, 0);
} | javascript | function processCommandLine() {
if (commander.list) {
listApps();
process.exit(0);
}
if (!commander.app) {
commander.help();
}
commander.endDate = commander.runDate ? moment(commander.runDate, 'MM/DD/YYYY').toDate() : new Date();
commander.startDate = moment(commander.endDate).subtract(commander.runDays, 'days').toDate();
commander.startDate.setHours(0, 0, 0, 0);
} | [
"function",
"processCommandLine",
"(",
")",
"{",
"if",
"(",
"commander",
".",
"list",
")",
"{",
"listApps",
"(",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
"if",
"(",
"!",
"commander",
".",
"app",
")",
"{",
"commander",
".",
"help",
"(",
")",
";",
"}",
"commander",
".",
"endDate",
"=",
"commander",
".",
"runDate",
"?",
"moment",
"(",
"commander",
".",
"runDate",
",",
"'MM/DD/YYYY'",
")",
".",
"toDate",
"(",
")",
":",
"new",
"Date",
"(",
")",
";",
"commander",
".",
"startDate",
"=",
"moment",
"(",
"commander",
".",
"endDate",
")",
".",
"subtract",
"(",
"commander",
".",
"runDays",
",",
"'days'",
")",
".",
"toDate",
"(",
")",
";",
"commander",
".",
"startDate",
".",
"setHours",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"}"
] | Process the command line using commander | [
"Process",
"the",
"command",
"line",
"using",
"commander"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/batch/batch.manager.js#L34-L47 |
49,964 | gethuman/pancakes-recipe | batch/batch.manager.js | run | function run() {
var startTime = (new Date()).getTime();
// parse the command line using the commander object
processCommandLine();
// leverage the middleware to initialize all our services, adapters, etc. (i.e. connect to mongo, etc.)
mwServiceInit.init({ container: 'batch' })
.then(function () {
var app = pancakes.cook(casing.camelCase(commander.app) + 'Batch');
return app.run(commander);
})
.then(function () {
var endTime = (new Date()).getTime();
var diffTime = (endTime - startTime) / 1000;
log.info(commander.app + ' complete (' + diffTime + 's)');
process.exit(0);
})
.catch(function (err) {
log.error(err);
process.exit(1);
});
} | javascript | function run() {
var startTime = (new Date()).getTime();
// parse the command line using the commander object
processCommandLine();
// leverage the middleware to initialize all our services, adapters, etc. (i.e. connect to mongo, etc.)
mwServiceInit.init({ container: 'batch' })
.then(function () {
var app = pancakes.cook(casing.camelCase(commander.app) + 'Batch');
return app.run(commander);
})
.then(function () {
var endTime = (new Date()).getTime();
var diffTime = (endTime - startTime) / 1000;
log.info(commander.app + ' complete (' + diffTime + 's)');
process.exit(0);
})
.catch(function (err) {
log.error(err);
process.exit(1);
});
} | [
"function",
"run",
"(",
")",
"{",
"var",
"startTime",
"=",
"(",
"new",
"Date",
"(",
")",
")",
".",
"getTime",
"(",
")",
";",
"// parse the command line using the commander object",
"processCommandLine",
"(",
")",
";",
"// leverage the middleware to initialize all our services, adapters, etc. (i.e. connect to mongo, etc.)",
"mwServiceInit",
".",
"init",
"(",
"{",
"container",
":",
"'batch'",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"app",
"=",
"pancakes",
".",
"cook",
"(",
"casing",
".",
"camelCase",
"(",
"commander",
".",
"app",
")",
"+",
"'Batch'",
")",
";",
"return",
"app",
".",
"run",
"(",
"commander",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"endTime",
"=",
"(",
"new",
"Date",
"(",
")",
")",
".",
"getTime",
"(",
")",
";",
"var",
"diffTime",
"=",
"(",
"endTime",
"-",
"startTime",
")",
"/",
"1000",
";",
"log",
".",
"info",
"(",
"commander",
".",
"app",
"+",
"' complete ('",
"+",
"diffTime",
"+",
"'s)'",
")",
";",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"err",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
")",
";",
"}"
] | Run a particular batch program | [
"Run",
"a",
"particular",
"batch",
"program"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/batch/batch.manager.js#L52-L74 |
49,965 | yadirhb/vitruvio | source/res/functions.js | supersede | function supersede(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (hasProp(target, prop)) {
if (deepStringMixin && typeof value === 'object' && value && !isArray(value) && !isFunction(value) && !(value instanceof RegExp)) {
if (!target[prop]) {
target[prop] = {};
}
supersede(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
} | javascript | function supersede(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (hasProp(target, prop)) {
if (deepStringMixin && typeof value === 'object' && value && !isArray(value) && !isFunction(value) && !(value instanceof RegExp)) {
if (!target[prop]) {
target[prop] = {};
}
supersede(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
} | [
"function",
"supersede",
"(",
"target",
",",
"source",
",",
"force",
",",
"deepStringMixin",
")",
"{",
"if",
"(",
"source",
")",
"{",
"eachProp",
"(",
"source",
",",
"function",
"(",
"value",
",",
"prop",
")",
"{",
"if",
"(",
"hasProp",
"(",
"target",
",",
"prop",
")",
")",
"{",
"if",
"(",
"deepStringMixin",
"&&",
"typeof",
"value",
"===",
"'object'",
"&&",
"value",
"&&",
"!",
"isArray",
"(",
"value",
")",
"&&",
"!",
"isFunction",
"(",
"value",
")",
"&&",
"!",
"(",
"value",
"instanceof",
"RegExp",
")",
")",
"{",
"if",
"(",
"!",
"target",
"[",
"prop",
"]",
")",
"{",
"target",
"[",
"prop",
"]",
"=",
"{",
"}",
";",
"}",
"supersede",
"(",
"target",
"[",
"prop",
"]",
",",
"value",
",",
"force",
",",
"deepStringMixin",
")",
";",
"}",
"else",
"{",
"target",
"[",
"prop",
"]",
"=",
"value",
";",
"}",
"}",
"}",
")",
";",
"}",
"return",
"target",
";",
"}"
] | Simple function to make a supersede the properties between two objects.
The properties into the same. | [
"Simple",
"function",
"to",
"make",
"a",
"supersede",
"the",
"properties",
"between",
"two",
"objects",
".",
"The",
"properties",
"into",
"the",
"same",
"."
] | 2cb640e31bedfb554e6766e1e5c61fbb14226b3b | https://github.com/yadirhb/vitruvio/blob/2cb640e31bedfb554e6766e1e5c61fbb14226b3b/source/res/functions.js#L364-L381 |
49,966 | yadirhb/vitruvio | source/res/functions.js | create | function create(type, def, base) {
// empty constructor
type.prototype = base ? typeof base === 'function' ? new base() : base : new Class(); // set base object as prototype
return apply(new type(), def); // return empty object with right [[Prototype]]
} | javascript | function create(type, def, base) {
// empty constructor
type.prototype = base ? typeof base === 'function' ? new base() : base : new Class(); // set base object as prototype
return apply(new type(), def); // return empty object with right [[Prototype]]
} | [
"function",
"create",
"(",
"type",
",",
"def",
",",
"base",
")",
"{",
"// empty constructor",
"type",
".",
"prototype",
"=",
"base",
"?",
"typeof",
"base",
"===",
"'function'",
"?",
"new",
"base",
"(",
")",
":",
"base",
":",
"new",
"Class",
"(",
")",
";",
"// set base object as prototype",
"return",
"apply",
"(",
"new",
"type",
"(",
")",
",",
"def",
")",
";",
"// return empty object with right [[Prototype]]",
"}"
] | Instantiate a specific function, applies values definition properties and assign a proto object.
@param type {Function} | [
"Instantiate",
"a",
"specific",
"function",
"applies",
"values",
"definition",
"properties",
"and",
"assign",
"a",
"proto",
"object",
"."
] | 2cb640e31bedfb554e6766e1e5c61fbb14226b3b | https://github.com/yadirhb/vitruvio/blob/2cb640e31bedfb554e6766e1e5c61fbb14226b3b/source/res/functions.js#L670-L674 |
49,967 | yadirhb/vitruvio | source/res/functions.js | define | function define(type, baseClass, members, statics) {
// empty constructor
type.prototype = baseClass ? typeof baseClass === "function" ? new baseClass() : baseClass : new Class(); // set base object as prototype
type.prototype.constructor = type;
type.prototype = apply(type.prototype, members || {});
return apply(type, statics || {}); // return empty object with right [[Prototype]]
} | javascript | function define(type, baseClass, members, statics) {
// empty constructor
type.prototype = baseClass ? typeof baseClass === "function" ? new baseClass() : baseClass : new Class(); // set base object as prototype
type.prototype.constructor = type;
type.prototype = apply(type.prototype, members || {});
return apply(type, statics || {}); // return empty object with right [[Prototype]]
} | [
"function",
"define",
"(",
"type",
",",
"baseClass",
",",
"members",
",",
"statics",
")",
"{",
"// empty constructor",
"type",
".",
"prototype",
"=",
"baseClass",
"?",
"typeof",
"baseClass",
"===",
"\"function\"",
"?",
"new",
"baseClass",
"(",
")",
":",
"baseClass",
":",
"new",
"Class",
"(",
")",
";",
"// set base object as prototype",
"type",
".",
"prototype",
".",
"constructor",
"=",
"type",
";",
"type",
".",
"prototype",
"=",
"apply",
"(",
"type",
".",
"prototype",
",",
"members",
"||",
"{",
"}",
")",
";",
"return",
"apply",
"(",
"type",
",",
"statics",
"||",
"{",
"}",
")",
";",
"// return empty object with right [[Prototype]]",
"}"
] | Defines a new member and registers it into the wrapper object.
@param memberName
{String} The name of the member to be defined. It must be a valid
namespace identifier.
@param definition
{Object} Contains the public class members.
@param wrapper
{Object} Defines the wrapper of the new Object, if not provided
window will be taken. | [
"Defines",
"a",
"new",
"member",
"and",
"registers",
"it",
"into",
"the",
"wrapper",
"object",
"."
] | 2cb640e31bedfb554e6766e1e5c61fbb14226b3b | https://github.com/yadirhb/vitruvio/blob/2cb640e31bedfb554e6766e1e5c61fbb14226b3b/source/res/functions.js#L688-L694 |
49,968 | mbullington/goal | lib/helpers.js | inherits | function inherits(constructor, superConstructor) {
constructor.prototype = Object.create(superConstructor.prototype, {
constructor: {
value: constructor
}
});
return constructor;
} | javascript | function inherits(constructor, superConstructor) {
constructor.prototype = Object.create(superConstructor.prototype, {
constructor: {
value: constructor
}
});
return constructor;
} | [
"function",
"inherits",
"(",
"constructor",
",",
"superConstructor",
")",
"{",
"constructor",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"superConstructor",
".",
"prototype",
",",
"{",
"constructor",
":",
"{",
"value",
":",
"constructor",
"}",
"}",
")",
";",
"return",
"constructor",
";",
"}"
] | implementation of node's util.inherits, works in the browser as well | [
"implementation",
"of",
"node",
"s",
"util",
".",
"inherits",
"works",
"in",
"the",
"browser",
"as",
"well"
] | 20cf8db4a2165c04ed88242c9fd411ce016b988f | https://github.com/mbullington/goal/blob/20cf8db4a2165c04ed88242c9fd411ce016b988f/lib/helpers.js#L18-L25 |
49,969 | mbullington/goal | lib/helpers.js | typeOf | function typeOf(value) {
var returned = Object.prototype.toString.call(value);
return returned.substring(1, returned.length - 1).split(' ')[1].toLowerCase();
} | javascript | function typeOf(value) {
var returned = Object.prototype.toString.call(value);
return returned.substring(1, returned.length - 1).split(' ')[1].toLowerCase();
} | [
"function",
"typeOf",
"(",
"value",
")",
"{",
"var",
"returned",
"=",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"value",
")",
";",
"return",
"returned",
".",
"substring",
"(",
"1",
",",
"returned",
".",
"length",
"-",
"1",
")",
".",
"split",
"(",
"' '",
")",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
";",
"}"
] | ES6 iterator ready solution. | [
"ES6",
"iterator",
"ready",
"solution",
"."
] | 20cf8db4a2165c04ed88242c9fd411ce016b988f | https://github.com/mbullington/goal/blob/20cf8db4a2165c04ed88242c9fd411ce016b988f/lib/helpers.js#L46-L49 |
49,970 | redisjs/jsr-server | lib/transaction.js | add | function add(err, req, res) {
if(err) {
// TODO: send args length errors
// transaction errors are not queued
// but the transaction is left open for more
// command to be queued
if(err instanceof TransactionError) {
return res.send(err);
}
// last error
this.error = err;
}
this.queue.push({err: err, req: req, res: res});
res.send(null, QUEUED);
} | javascript | function add(err, req, res) {
if(err) {
// TODO: send args length errors
// transaction errors are not queued
// but the transaction is left open for more
// command to be queued
if(err instanceof TransactionError) {
return res.send(err);
}
// last error
this.error = err;
}
this.queue.push({err: err, req: req, res: res});
res.send(null, QUEUED);
} | [
"function",
"add",
"(",
"err",
",",
"req",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"// TODO: send args length errors",
"// transaction errors are not queued",
"// but the transaction is left open for more",
"// command to be queued",
"if",
"(",
"err",
"instanceof",
"TransactionError",
")",
"{",
"return",
"res",
".",
"send",
"(",
"err",
")",
";",
"}",
"// last error",
"this",
".",
"error",
"=",
"err",
";",
"}",
"this",
".",
"queue",
".",
"push",
"(",
"{",
"err",
":",
"err",
",",
"req",
":",
"req",
",",
"res",
":",
"res",
"}",
")",
";",
"res",
".",
"send",
"(",
"null",
",",
"QUEUED",
")",
";",
"}"
] | Queue a command.
The command and arguments list should already have been
validated to determine if an error would occur (EXECABORT).
@param err A validation error.
@param req The command request.
@param res The command response. | [
"Queue",
"a",
"command",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/transaction.js#L36-L52 |
49,971 | redisjs/jsr-server | lib/transaction.js | exec | function exec(scope, req, res) {
var replies = [], item;
// NOTE: incrby invalid amount will trigger EXECABORT
// NOTE: wrong number of args are returned to the client
// NOTE: but other types of validation errors (argument type coercion)
// NOTE: trigger EXECABORT
if(this.error) return this.destroy(req, res, ExecAbort);
if(this.conflict) return this.destroy(req, res, null, null);
function onReply(err, reply) {
replies.push(err || reply);
}
onReply = onReply.bind(this);
// fifo queue, maintain order
while((item = this.queue.shift()) !== undefined) {
if(item.err) {
replies.push(item.err);
}else{
item.res.cb = onReply;
// execute via the server so that these command
// executions are included in slowlog/monitor
scope.execute(item.req.exec, item.req, item.res);
}
}
// reply and destroy this transaction
this.destroy(req, res, null, replies);
} | javascript | function exec(scope, req, res) {
var replies = [], item;
// NOTE: incrby invalid amount will trigger EXECABORT
// NOTE: wrong number of args are returned to the client
// NOTE: but other types of validation errors (argument type coercion)
// NOTE: trigger EXECABORT
if(this.error) return this.destroy(req, res, ExecAbort);
if(this.conflict) return this.destroy(req, res, null, null);
function onReply(err, reply) {
replies.push(err || reply);
}
onReply = onReply.bind(this);
// fifo queue, maintain order
while((item = this.queue.shift()) !== undefined) {
if(item.err) {
replies.push(item.err);
}else{
item.res.cb = onReply;
// execute via the server so that these command
// executions are included in slowlog/monitor
scope.execute(item.req.exec, item.req, item.res);
}
}
// reply and destroy this transaction
this.destroy(req, res, null, replies);
} | [
"function",
"exec",
"(",
"scope",
",",
"req",
",",
"res",
")",
"{",
"var",
"replies",
"=",
"[",
"]",
",",
"item",
";",
"// NOTE: incrby invalid amount will trigger EXECABORT",
"// NOTE: wrong number of args are returned to the client",
"// NOTE: but other types of validation errors (argument type coercion)",
"// NOTE: trigger EXECABORT",
"if",
"(",
"this",
".",
"error",
")",
"return",
"this",
".",
"destroy",
"(",
"req",
",",
"res",
",",
"ExecAbort",
")",
";",
"if",
"(",
"this",
".",
"conflict",
")",
"return",
"this",
".",
"destroy",
"(",
"req",
",",
"res",
",",
"null",
",",
"null",
")",
";",
"function",
"onReply",
"(",
"err",
",",
"reply",
")",
"{",
"replies",
".",
"push",
"(",
"err",
"||",
"reply",
")",
";",
"}",
"onReply",
"=",
"onReply",
".",
"bind",
"(",
"this",
")",
";",
"// fifo queue, maintain order",
"while",
"(",
"(",
"item",
"=",
"this",
".",
"queue",
".",
"shift",
"(",
")",
")",
"!==",
"undefined",
")",
"{",
"if",
"(",
"item",
".",
"err",
")",
"{",
"replies",
".",
"push",
"(",
"item",
".",
"err",
")",
";",
"}",
"else",
"{",
"item",
".",
"res",
".",
"cb",
"=",
"onReply",
";",
"// execute via the server so that these command",
"// executions are included in slowlog/monitor",
"scope",
".",
"execute",
"(",
"item",
".",
"req",
".",
"exec",
",",
"item",
".",
"req",
",",
"item",
".",
"res",
")",
";",
"}",
"}",
"// reply and destroy this transaction",
"this",
".",
"destroy",
"(",
"req",
",",
"res",
",",
"null",
",",
"replies",
")",
";",
"}"
] | Execute this transaction.
@param scope The server scope.
@param req The request created for the exec command.
@param res The response created for the exec command. | [
"Execute",
"this",
"transaction",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/transaction.js#L61-L93 |
49,972 | redisjs/jsr-server | lib/transaction.js | destroy | function destroy(req, res, err, reply) {
req.conn.transaction = null;
req.conn.unwatch(req.db);
this.queue = null;
this.error = null;
res.send(err, reply);
} | javascript | function destroy(req, res, err, reply) {
req.conn.transaction = null;
req.conn.unwatch(req.db);
this.queue = null;
this.error = null;
res.send(err, reply);
} | [
"function",
"destroy",
"(",
"req",
",",
"res",
",",
"err",
",",
"reply",
")",
"{",
"req",
".",
"conn",
".",
"transaction",
"=",
"null",
";",
"req",
".",
"conn",
".",
"unwatch",
"(",
"req",
".",
"db",
")",
";",
"this",
".",
"queue",
"=",
"null",
";",
"this",
".",
"error",
"=",
"null",
";",
"res",
".",
"send",
"(",
"err",
",",
"reply",
")",
";",
"}"
] | Clear references, unwatch keys and send
a response to the client. | [
"Clear",
"references",
"unwatch",
"keys",
"and",
"send",
"a",
"response",
"to",
"the",
"client",
"."
] | 49413052d3039524fbdd2ade0ef9bae26cb4d647 | https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/transaction.js#L99-L105 |
49,973 | jeremyruppel/hoagie | lib/response.js | format | function format(fn) {
return function(chunk) {
if (arguments.length > 1) {
chunk = util.format.apply(null, arguments);
}
if (chunk === undefined) {
chunk = '';
}
fn.call(this, chunk);
};
} | javascript | function format(fn) {
return function(chunk) {
if (arguments.length > 1) {
chunk = util.format.apply(null, arguments);
}
if (chunk === undefined) {
chunk = '';
}
fn.call(this, chunk);
};
} | [
"function",
"format",
"(",
"fn",
")",
"{",
"return",
"function",
"(",
"chunk",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
">",
"1",
")",
"{",
"chunk",
"=",
"util",
".",
"format",
".",
"apply",
"(",
"null",
",",
"arguments",
")",
";",
"}",
"if",
"(",
"chunk",
"===",
"undefined",
")",
"{",
"chunk",
"=",
"''",
";",
"}",
"fn",
".",
"call",
"(",
"this",
",",
"chunk",
")",
";",
"}",
";",
"}"
] | All hoagie output methods support util.format placeholder
formatting. | [
"All",
"hoagie",
"output",
"methods",
"support",
"util",
".",
"format",
"placeholder",
"formatting",
"."
] | 9e05b4c9f0537d681dcb240eab41822f15bef613 | https://github.com/jeremyruppel/hoagie/blob/9e05b4c9f0537d681dcb240eab41822f15bef613/lib/response.js#L70-L80 |
49,974 | subfuzion/snapfinder-lib | lib/geo.js | getDistanceInKilometers | function getDistanceInKilometers(p1, p2) {
// Credit: adapts code for Haversine formula and degrees-to-radian conversion found at:
// http://www.movable-type.co.uk/scripts/latlong.html
var R = 6371; // earth's radius in kilometers
var dLat = degreesToRadians(p2.lat - p1.lat);
var dLon = degreesToRadians(p2.lng - p1.lng);
var lat1 = degreesToRadians(p1.lat);
var lat2 = degreesToRadians(p2.lat);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2)
+ Math.sin(dLon/2) * Math.sin(dLon/2)
* Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var distance = R * c; // kilomter
return distance;
} | javascript | function getDistanceInKilometers(p1, p2) {
// Credit: adapts code for Haversine formula and degrees-to-radian conversion found at:
// http://www.movable-type.co.uk/scripts/latlong.html
var R = 6371; // earth's radius in kilometers
var dLat = degreesToRadians(p2.lat - p1.lat);
var dLon = degreesToRadians(p2.lng - p1.lng);
var lat1 = degreesToRadians(p1.lat);
var lat2 = degreesToRadians(p2.lat);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2)
+ Math.sin(dLon/2) * Math.sin(dLon/2)
* Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var distance = R * c; // kilomter
return distance;
} | [
"function",
"getDistanceInKilometers",
"(",
"p1",
",",
"p2",
")",
"{",
"// Credit: adapts code for Haversine formula and degrees-to-radian conversion found at:",
"// http://www.movable-type.co.uk/scripts/latlong.html",
"var",
"R",
"=",
"6371",
";",
"// earth's radius in kilometers",
"var",
"dLat",
"=",
"degreesToRadians",
"(",
"p2",
".",
"lat",
"-",
"p1",
".",
"lat",
")",
";",
"var",
"dLon",
"=",
"degreesToRadians",
"(",
"p2",
".",
"lng",
"-",
"p1",
".",
"lng",
")",
";",
"var",
"lat1",
"=",
"degreesToRadians",
"(",
"p1",
".",
"lat",
")",
";",
"var",
"lat2",
"=",
"degreesToRadians",
"(",
"p2",
".",
"lat",
")",
";",
"var",
"a",
"=",
"Math",
".",
"sin",
"(",
"dLat",
"/",
"2",
")",
"*",
"Math",
".",
"sin",
"(",
"dLat",
"/",
"2",
")",
"+",
"Math",
".",
"sin",
"(",
"dLon",
"/",
"2",
")",
"*",
"Math",
".",
"sin",
"(",
"dLon",
"/",
"2",
")",
"*",
"Math",
".",
"cos",
"(",
"lat1",
")",
"*",
"Math",
".",
"cos",
"(",
"lat2",
")",
";",
"var",
"c",
"=",
"2",
"*",
"Math",
".",
"atan2",
"(",
"Math",
".",
"sqrt",
"(",
"a",
")",
",",
"Math",
".",
"sqrt",
"(",
"1",
"-",
"a",
")",
")",
";",
"var",
"distance",
"=",
"R",
"*",
"c",
";",
"// kilomter",
"return",
"distance",
";",
"}"
] | Calculate great circle distance and return result in kilometers
@param p1 the origin with lat (latitude) and lng (longitude) properties
@param p2 the destination with lat (latitude) and lng (longitude) properties | [
"Calculate",
"great",
"circle",
"distance",
"and",
"return",
"result",
"in",
"kilometers"
] | 121172f10a9ec64bc5f3d749fba97662b336caae | https://github.com/subfuzion/snapfinder-lib/blob/121172f10a9ec64bc5f3d749fba97662b336caae/lib/geo.js#L36-L54 |
49,975 | subfuzion/snapfinder-lib | lib/geo.js | parseGoogleGeocodes | function parseGoogleGeocodes(response) {
// the result has a results property that is an array
// there may be more than one result when the address is ambiguous
// for pragmatic reasons, only use the first result
// if the result does not have a zip code, then assume the user
// did not provide a valid address
var result = response.results[0]
, zipComponent = findAddressComponent(result.address_components, 'postal_code')
, simple = {}
;
simple.zip5 = zipComponent ? zipComponent.short_name : null;
simple.address = result.formatted_address.replace(/,\s*USA/, '');
simple.localAddress = getLocalAddress(result) || simple.address;
simple.location = result.geometry.location;
return simple;
} | javascript | function parseGoogleGeocodes(response) {
// the result has a results property that is an array
// there may be more than one result when the address is ambiguous
// for pragmatic reasons, only use the first result
// if the result does not have a zip code, then assume the user
// did not provide a valid address
var result = response.results[0]
, zipComponent = findAddressComponent(result.address_components, 'postal_code')
, simple = {}
;
simple.zip5 = zipComponent ? zipComponent.short_name : null;
simple.address = result.formatted_address.replace(/,\s*USA/, '');
simple.localAddress = getLocalAddress(result) || simple.address;
simple.location = result.geometry.location;
return simple;
} | [
"function",
"parseGoogleGeocodes",
"(",
"response",
")",
"{",
"// the result has a results property that is an array",
"// there may be more than one result when the address is ambiguous",
"// for pragmatic reasons, only use the first result",
"// if the result does not have a zip code, then assume the user",
"// did not provide a valid address",
"var",
"result",
"=",
"response",
".",
"results",
"[",
"0",
"]",
",",
"zipComponent",
"=",
"findAddressComponent",
"(",
"result",
".",
"address_components",
",",
"'postal_code'",
")",
",",
"simple",
"=",
"{",
"}",
";",
"simple",
".",
"zip5",
"=",
"zipComponent",
"?",
"zipComponent",
".",
"short_name",
":",
"null",
";",
"simple",
".",
"address",
"=",
"result",
".",
"formatted_address",
".",
"replace",
"(",
"/",
",\\s*USA",
"/",
",",
"''",
")",
";",
"simple",
".",
"localAddress",
"=",
"getLocalAddress",
"(",
"result",
")",
"||",
"simple",
".",
"address",
";",
"simple",
".",
"location",
"=",
"result",
".",
"geometry",
".",
"location",
";",
"return",
"simple",
";",
"}"
] | Parse the JSON result that Google returned
@param response an object with results parsed from the body of Google's API response
@return an object with zip5, address (formatted address),
and location (lat, lng) properties, or null if not a valid address | [
"Parse",
"the",
"JSON",
"result",
"that",
"Google",
"returned"
] | 121172f10a9ec64bc5f3d749fba97662b336caae | https://github.com/subfuzion/snapfinder-lib/blob/121172f10a9ec64bc5f3d749fba97662b336caae/lib/geo.js#L130-L147 |
49,976 | subfuzion/snapfinder-lib | lib/geo.js | findAddressComponent | function findAddressComponent(components, type) {
for (var i = 0; i < components.length; i++) {
if (components[i].types.indexOf(type) > -1) {
return components[i];
}
}
return null;
} | javascript | function findAddressComponent(components, type) {
for (var i = 0; i < components.length; i++) {
if (components[i].types.indexOf(type) > -1) {
return components[i];
}
}
return null;
} | [
"function",
"findAddressComponent",
"(",
"components",
",",
"type",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"components",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"components",
"[",
"i",
"]",
".",
"types",
".",
"indexOf",
"(",
"type",
")",
">",
"-",
"1",
")",
"{",
"return",
"components",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Return the address component that matches the specified type
@param components an array of address components
@type specifies the component to return
@return the component or null if no components matched | [
"Return",
"the",
"address",
"component",
"that",
"matches",
"the",
"specified",
"type"
] | 121172f10a9ec64bc5f3d749fba97662b336caae | https://github.com/subfuzion/snapfinder-lib/blob/121172f10a9ec64bc5f3d749fba97662b336caae/lib/geo.js#L155-L163 |
49,977 | vesln/to-date | index.js | ToDate | function ToDate(amount, unit, method) {
this.amount = amount;
this.method = method;
this.unit = unit;
} | javascript | function ToDate(amount, unit, method) {
this.amount = amount;
this.method = method;
this.unit = unit;
} | [
"function",
"ToDate",
"(",
"amount",
",",
"unit",
",",
"method",
")",
"{",
"this",
".",
"amount",
"=",
"amount",
";",
"this",
".",
"method",
"=",
"method",
";",
"this",
".",
"unit",
"=",
"unit",
";",
"}"
] | To Date.
@param {Number} amount
@param {String} unit [optional]
@param {String} method [optional]
@constructor | [
"To",
"Date",
"."
] | 16724aaac83bb57b1557ad9b9d2a0496a455b1b6 | https://github.com/vesln/to-date/blob/16724aaac83bb57b1557ad9b9d2a0496a455b1b6/index.js#L37-L41 |
49,978 | vesln/to-date | index.js | function() {
var time = null;
if (this.method === 'from now') {
time = ago.fromNow(this.amount, this.unit);
} else if (this.method === 'ago') {
time = ago(this.amount, this.unit);
} else {
throw new Error('Invalid method: ' + this.method);
}
return new Date(time);
} | javascript | function() {
var time = null;
if (this.method === 'from now') {
time = ago.fromNow(this.amount, this.unit);
} else if (this.method === 'ago') {
time = ago(this.amount, this.unit);
} else {
throw new Error('Invalid method: ' + this.method);
}
return new Date(time);
} | [
"function",
"(",
")",
"{",
"var",
"time",
"=",
"null",
";",
"if",
"(",
"this",
".",
"method",
"===",
"'from now'",
")",
"{",
"time",
"=",
"ago",
".",
"fromNow",
"(",
"this",
".",
"amount",
",",
"this",
".",
"unit",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"method",
"===",
"'ago'",
")",
"{",
"time",
"=",
"ago",
"(",
"this",
".",
"amount",
",",
"this",
".",
"unit",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid method: '",
"+",
"this",
".",
"method",
")",
";",
"}",
"return",
"new",
"Date",
"(",
"time",
")",
";",
"}"
] | Build the desired date and return it.
@returns {Date}
@api public | [
"Build",
"the",
"desired",
"date",
"and",
"return",
"it",
"."
] | 16724aaac83bb57b1557ad9b9d2a0496a455b1b6 | https://github.com/vesln/to-date/blob/16724aaac83bb57b1557ad9b9d2a0496a455b1b6/index.js#L126-L138 |
|
49,979 | gethuman/pancakes-recipe | utils/base64.js | encode | function encode(number) {
if (number === 0) {
return '';
}
var quotient = Math.floor(number / 64);
var remainder = number % 64;
var digit;
if (remainder < 10) {
digit = '' + remainder;
}
else if (remainder < 36) {
digit = String.fromCharCode(remainder + 55);
}
else if (remainder < 62) {
digit = String.fromCharCode(remainder + 61);
}
else if (remainder === 62) {
digit = '-';
}
else if (remainder === 63) {
digit = '_';
}
return encode(quotient) + '' + digit;
} | javascript | function encode(number) {
if (number === 0) {
return '';
}
var quotient = Math.floor(number / 64);
var remainder = number % 64;
var digit;
if (remainder < 10) {
digit = '' + remainder;
}
else if (remainder < 36) {
digit = String.fromCharCode(remainder + 55);
}
else if (remainder < 62) {
digit = String.fromCharCode(remainder + 61);
}
else if (remainder === 62) {
digit = '-';
}
else if (remainder === 63) {
digit = '_';
}
return encode(quotient) + '' + digit;
} | [
"function",
"encode",
"(",
"number",
")",
"{",
"if",
"(",
"number",
"===",
"0",
")",
"{",
"return",
"''",
";",
"}",
"var",
"quotient",
"=",
"Math",
".",
"floor",
"(",
"number",
"/",
"64",
")",
";",
"var",
"remainder",
"=",
"number",
"%",
"64",
";",
"var",
"digit",
";",
"if",
"(",
"remainder",
"<",
"10",
")",
"{",
"digit",
"=",
"''",
"+",
"remainder",
";",
"}",
"else",
"if",
"(",
"remainder",
"<",
"36",
")",
"{",
"digit",
"=",
"String",
".",
"fromCharCode",
"(",
"remainder",
"+",
"55",
")",
";",
"}",
"else",
"if",
"(",
"remainder",
"<",
"62",
")",
"{",
"digit",
"=",
"String",
".",
"fromCharCode",
"(",
"remainder",
"+",
"61",
")",
";",
"}",
"else",
"if",
"(",
"remainder",
"===",
"62",
")",
"{",
"digit",
"=",
"'-'",
";",
"}",
"else",
"if",
"(",
"remainder",
"===",
"63",
")",
"{",
"digit",
"=",
"'_'",
";",
"}",
"return",
"encode",
"(",
"quotient",
")",
"+",
"''",
"+",
"digit",
";",
"}"
] | Take a number and translate it into our custom base64 encoded
string
@param number
@returns {string} | [
"Take",
"a",
"number",
"and",
"translate",
"it",
"into",
"our",
"custom",
"base64",
"encoded",
"string"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/base64.js#L16-L42 |
49,980 | gethuman/pancakes-recipe | utils/base64.js | decode | function decode(base64string) {
var number = 0;
var chars = base64string.split('');
var len = chars.length;
var val10;
var val64;
var asciiVal;
for (var i = 0; i < len; i++) {
val64 = chars[len - 1 - i];
asciiVal = val64.charCodeAt(0);
val10 = 0;
if (val64 === '_') {
val10 = 63;
}
else if (val64 === '-') {
val10 = 62;
}
else if (asciiVal > 96 && asciiVal < 123) {
val10 = asciiVal - 61;
}
else if (asciiVal > 64 && asciiVal < 91) {
val10 = asciiVal - 55;
}
else if (asciiVal > 47 && asciiVal < 58) {
val10 = asciiVal - 48;
}
else {
throw new AppError({ msg: 'Non-base64value in encoded string' });
}
number += (Math.pow(64, i) * val10);
}
return number;
} | javascript | function decode(base64string) {
var number = 0;
var chars = base64string.split('');
var len = chars.length;
var val10;
var val64;
var asciiVal;
for (var i = 0; i < len; i++) {
val64 = chars[len - 1 - i];
asciiVal = val64.charCodeAt(0);
val10 = 0;
if (val64 === '_') {
val10 = 63;
}
else if (val64 === '-') {
val10 = 62;
}
else if (asciiVal > 96 && asciiVal < 123) {
val10 = asciiVal - 61;
}
else if (asciiVal > 64 && asciiVal < 91) {
val10 = asciiVal - 55;
}
else if (asciiVal > 47 && asciiVal < 58) {
val10 = asciiVal - 48;
}
else {
throw new AppError({ msg: 'Non-base64value in encoded string' });
}
number += (Math.pow(64, i) * val10);
}
return number;
} | [
"function",
"decode",
"(",
"base64string",
")",
"{",
"var",
"number",
"=",
"0",
";",
"var",
"chars",
"=",
"base64string",
".",
"split",
"(",
"''",
")",
";",
"var",
"len",
"=",
"chars",
".",
"length",
";",
"var",
"val10",
";",
"var",
"val64",
";",
"var",
"asciiVal",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"val64",
"=",
"chars",
"[",
"len",
"-",
"1",
"-",
"i",
"]",
";",
"asciiVal",
"=",
"val64",
".",
"charCodeAt",
"(",
"0",
")",
";",
"val10",
"=",
"0",
";",
"if",
"(",
"val64",
"===",
"'_'",
")",
"{",
"val10",
"=",
"63",
";",
"}",
"else",
"if",
"(",
"val64",
"===",
"'-'",
")",
"{",
"val10",
"=",
"62",
";",
"}",
"else",
"if",
"(",
"asciiVal",
">",
"96",
"&&",
"asciiVal",
"<",
"123",
")",
"{",
"val10",
"=",
"asciiVal",
"-",
"61",
";",
"}",
"else",
"if",
"(",
"asciiVal",
">",
"64",
"&&",
"asciiVal",
"<",
"91",
")",
"{",
"val10",
"=",
"asciiVal",
"-",
"55",
";",
"}",
"else",
"if",
"(",
"asciiVal",
">",
"47",
"&&",
"asciiVal",
"<",
"58",
")",
"{",
"val10",
"=",
"asciiVal",
"-",
"48",
";",
"}",
"else",
"{",
"throw",
"new",
"AppError",
"(",
"{",
"msg",
":",
"'Non-base64value in encoded string'",
"}",
")",
";",
"}",
"number",
"+=",
"(",
"Math",
".",
"pow",
"(",
"64",
",",
"i",
")",
"*",
"val10",
")",
";",
"}",
"return",
"number",
";",
"}"
] | For a given string that has been encoded already with our custom base64
encoding scheme, translate it into a number
@param base64string
@returns {number} | [
"For",
"a",
"given",
"string",
"that",
"has",
"been",
"encoded",
"already",
"with",
"our",
"custom",
"base64",
"encoding",
"scheme",
"translate",
"it",
"into",
"a",
"number"
] | ea3feb8839e2edaf1b4577c052b8958953db4498 | https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/base64.js#L51-L87 |
49,981 | shuvava/dev-http-server | lib/httphelper.js | httpNotFound | function httpNotFound(req, res) {
console.log(`No request handler found for ${req.url}`);
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.write('404 Not found');
res.end();
} | javascript | function httpNotFound(req, res) {
console.log(`No request handler found for ${req.url}`);
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.write('404 Not found');
res.end();
} | [
"function",
"httpNotFound",
"(",
"req",
",",
"res",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"req",
".",
"url",
"}",
"`",
")",
";",
"res",
".",
"writeHead",
"(",
"404",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"write",
"(",
"'404 Not found'",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}"
] | Default implementation of NotFound HTTP response
@param {Object} req HTTP request
@param {Object} res HTTP response | [
"Default",
"implementation",
"of",
"NotFound",
"HTTP",
"response"
] | db0f3b28f5805125959679828d81c1919cf519b6 | https://github.com/shuvava/dev-http-server/blob/db0f3b28f5805125959679828d81c1919cf519b6/lib/httphelper.js#L16-L21 |
49,982 | shuvava/dev-http-server | lib/httphelper.js | httpInternalError | function httpInternalError(req, res, err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.write(`Error 500 Internal server error: ${err}`);
res.end();
} | javascript | function httpInternalError(req, res, err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.write(`Error 500 Internal server error: ${err}`);
res.end();
} | [
"function",
"httpInternalError",
"(",
"req",
",",
"res",
",",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"res",
".",
"writeHead",
"(",
"500",
",",
"{",
"'Content-Type'",
":",
"'text/plain'",
"}",
")",
";",
"res",
".",
"write",
"(",
"`",
"${",
"err",
"}",
"`",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}"
] | Default implementation of InternalError HTTP response
@param {Object} req HTTP request
@param {Object} res HTTP response
@param {string} err Error message | [
"Default",
"implementation",
"of",
"InternalError",
"HTTP",
"response"
] | db0f3b28f5805125959679828d81c1919cf519b6 | https://github.com/shuvava/dev-http-server/blob/db0f3b28f5805125959679828d81c1919cf519b6/lib/httphelper.js#L29-L34 |
49,983 | shuvava/dev-http-server | lib/httphelper.js | httpOk | function httpOk(req, res, content, fileExt) {
res.writeHead(200, {
'Content-Type': Mine.getType(fileExt),
});
res.write(content, 'binary');
res.end();
} | javascript | function httpOk(req, res, content, fileExt) {
res.writeHead(200, {
'Content-Type': Mine.getType(fileExt),
});
res.write(content, 'binary');
res.end();
} | [
"function",
"httpOk",
"(",
"req",
",",
"res",
",",
"content",
",",
"fileExt",
")",
"{",
"res",
".",
"writeHead",
"(",
"200",
",",
"{",
"'Content-Type'",
":",
"Mine",
".",
"getType",
"(",
"fileExt",
")",
",",
"}",
")",
";",
"res",
".",
"write",
"(",
"content",
",",
"'binary'",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}"
] | Default implementation OK HTTP response on GET file request
@param {Object} req HTTP request
@param {Object} res HTTP response
@param {string} content File content
@param {string} fileExt File extension | [
"Default",
"implementation",
"OK",
"HTTP",
"response",
"on",
"GET",
"file",
"request"
] | db0f3b28f5805125959679828d81c1919cf519b6 | https://github.com/shuvava/dev-http-server/blob/db0f3b28f5805125959679828d81c1919cf519b6/lib/httphelper.js#L43-L49 |
49,984 | scrapjs/promise-routine | index.js | routine | function routine (fn, sets, context) {
const master = []
if (typeof context === 'undefined') {
context = fn
}
for (const args of sets) {
master.push(fn.apply(context, Array.isArray(args) ? args : [args]))
}
return Promise.all(master)
} | javascript | function routine (fn, sets, context) {
const master = []
if (typeof context === 'undefined') {
context = fn
}
for (const args of sets) {
master.push(fn.apply(context, Array.isArray(args) ? args : [args]))
}
return Promise.all(master)
} | [
"function",
"routine",
"(",
"fn",
",",
"sets",
",",
"context",
")",
"{",
"const",
"master",
"=",
"[",
"]",
"if",
"(",
"typeof",
"context",
"===",
"'undefined'",
")",
"{",
"context",
"=",
"fn",
"}",
"for",
"(",
"const",
"args",
"of",
"sets",
")",
"{",
"master",
".",
"push",
"(",
"fn",
".",
"apply",
"(",
"context",
",",
"Array",
".",
"isArray",
"(",
"args",
")",
"?",
"args",
":",
"[",
"args",
"]",
")",
")",
"}",
"return",
"Promise",
".",
"all",
"(",
"master",
")",
"}"
] | Run a promise-returning function multiple times,
in a routine.
```js
routine(promiseFunc, [...args])
```
Optionally supply context:
```js
routine(foo.promiseFunc, [...args], foo)
``` | [
"Run",
"a",
"promise",
"-",
"returning",
"function",
"multiple",
"times",
"in",
"a",
"routine",
"."
] | 9990f5cbf79df7017941c902bcf26b4b9e4893b4 | https://github.com/scrapjs/promise-routine/blob/9990f5cbf79df7017941c902bcf26b4b9e4893b4/index.js#L17-L29 |
49,985 | kirinnee/tslib.elefact | script.js | run | async function run(command) {
if (!Array.isArray(command) && typeof command === "string") command = command.split(' ');
else throw new Error("command is either a string or a string array");
let c = command.shift();
let v = command;
let env = process.env;
env.BROWSERSLIST_CONFIG= "./config/.browserslistrc";
return new Promise((resolve) => spawn(c, v,
{
stdio: "inherit",
shell: true,
env: env
})
.on("exit", (code, signal) => {
if (fs.existsSync("./.nyc_output")) rimraf.sync("./.nyc_output");
if (code === 0) resolve();
else {
console.log("ExternalError:", signal);
process.exit(1);
}
})
);
} | javascript | async function run(command) {
if (!Array.isArray(command) && typeof command === "string") command = command.split(' ');
else throw new Error("command is either a string or a string array");
let c = command.shift();
let v = command;
let env = process.env;
env.BROWSERSLIST_CONFIG= "./config/.browserslistrc";
return new Promise((resolve) => spawn(c, v,
{
stdio: "inherit",
shell: true,
env: env
})
.on("exit", (code, signal) => {
if (fs.existsSync("./.nyc_output")) rimraf.sync("./.nyc_output");
if (code === 0) resolve();
else {
console.log("ExternalError:", signal);
process.exit(1);
}
})
);
} | [
"async",
"function",
"run",
"(",
"command",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"command",
")",
"&&",
"typeof",
"command",
"===",
"\"string\"",
")",
"command",
"=",
"command",
".",
"split",
"(",
"' '",
")",
";",
"else",
"throw",
"new",
"Error",
"(",
"\"command is either a string or a string array\"",
")",
";",
"let",
"c",
"=",
"command",
".",
"shift",
"(",
")",
";",
"let",
"v",
"=",
"command",
";",
"let",
"env",
"=",
"process",
".",
"env",
";",
"env",
".",
"BROWSERSLIST_CONFIG",
"=",
"\"./config/.browserslistrc\"",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
")",
"=>",
"spawn",
"(",
"c",
",",
"v",
",",
"{",
"stdio",
":",
"\"inherit\"",
",",
"shell",
":",
"true",
",",
"env",
":",
"env",
"}",
")",
".",
"on",
"(",
"\"exit\"",
",",
"(",
"code",
",",
"signal",
")",
"=>",
"{",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"\"./.nyc_output\"",
")",
")",
"rimraf",
".",
"sync",
"(",
"\"./.nyc_output\"",
")",
";",
"if",
"(",
"code",
"===",
"0",
")",
"resolve",
"(",
")",
";",
"else",
"{",
"console",
".",
"log",
"(",
"\"ExternalError:\"",
",",
"signal",
")",
";",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}",
")",
")",
";",
"}"
] | Executes the function as if its on the CMD. Exits the script if the external command crashes. | [
"Executes",
"the",
"function",
"as",
"if",
"its",
"on",
"the",
"CMD",
".",
"Exits",
"the",
"script",
"if",
"the",
"external",
"command",
"crashes",
"."
] | b300e668c3aeecb76bbb71fd707ebda49ff7d0d0 | https://github.com/kirinnee/tslib.elefact/blob/b300e668c3aeecb76bbb71fd707ebda49ff7d0d0/script.js#L70-L95 |
49,986 | Psychopoulet/node-promfs | lib/extends/_extractFiles.js | _extractRealFiles | function _extractRealFiles (dir, givenFiles, realFiles, callback) {
if (0 >= givenFiles.length) {
return callback(null, realFiles);
}
else {
const file = join(dir, givenFiles.shift()).trim();
return isFileProm(file).then((exists) => {
if (exists) {
realFiles.push(file);
}
_extractRealFiles(dir, givenFiles, realFiles, callback);
}).catch(callback);
}
} | javascript | function _extractRealFiles (dir, givenFiles, realFiles, callback) {
if (0 >= givenFiles.length) {
return callback(null, realFiles);
}
else {
const file = join(dir, givenFiles.shift()).trim();
return isFileProm(file).then((exists) => {
if (exists) {
realFiles.push(file);
}
_extractRealFiles(dir, givenFiles, realFiles, callback);
}).catch(callback);
}
} | [
"function",
"_extractRealFiles",
"(",
"dir",
",",
"givenFiles",
",",
"realFiles",
",",
"callback",
")",
"{",
"if",
"(",
"0",
">=",
"givenFiles",
".",
"length",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"realFiles",
")",
";",
"}",
"else",
"{",
"const",
"file",
"=",
"join",
"(",
"dir",
",",
"givenFiles",
".",
"shift",
"(",
")",
")",
".",
"trim",
"(",
")",
";",
"return",
"isFileProm",
"(",
"file",
")",
".",
"then",
"(",
"(",
"exists",
")",
"=>",
"{",
"if",
"(",
"exists",
")",
"{",
"realFiles",
".",
"push",
"(",
"file",
")",
";",
"}",
"_extractRealFiles",
"(",
"dir",
",",
"givenFiles",
",",
"realFiles",
",",
"callback",
")",
";",
"}",
")",
".",
"catch",
"(",
"callback",
")",
";",
"}",
"}"
] | methods
Specific to "extractFiles" method, return only the existing files
@param {string} dir : directory to work with
@param {Array} givenFiles : files detected in the directory
@param {Array} realFiles : files detected as real files
@param {function|null} callback : operation's result
@returns {Promise} Operation's result | [
"methods",
"Specific",
"to",
"extractFiles",
"method",
"return",
"only",
"the",
"existing",
"files"
] | 016e272fc58c6ef6eae5ea551a0e8873f0ac20cc | https://github.com/Psychopoulet/node-promfs/blob/016e272fc58c6ef6eae5ea551a0e8873f0ac20cc/lib/extends/_extractFiles.js#L25-L46 |
49,987 | oz/bowerball | index.js | respondText | function respondText(res, code, text) {
res.statusCode = code;
res.setHeader('Content-Type', 'text/plain');
return res.end(text.toString());
} | javascript | function respondText(res, code, text) {
res.statusCode = code;
res.setHeader('Content-Type', 'text/plain');
return res.end(text.toString());
} | [
"function",
"respondText",
"(",
"res",
",",
"code",
",",
"text",
")",
"{",
"res",
".",
"statusCode",
"=",
"code",
";",
"res",
".",
"setHeader",
"(",
"'Content-Type'",
",",
"'text/plain'",
")",
";",
"return",
"res",
".",
"end",
"(",
"text",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Send an error response in plain-text. | [
"Send",
"an",
"error",
"response",
"in",
"plain",
"-",
"text",
"."
] | 6a267e7f530d400790e66617aa8330b21e2aac31 | https://github.com/oz/bowerball/blob/6a267e7f530d400790e66617aa8330b21e2aac31/index.js#L18-L22 |
49,988 | alisonailea/grunt-ractive-parse | tasks/ractiveparse.js | function(){
var string = '\t\t\t',
path = info.path.replace(baseDir, '').split('/');
if(path.length > 1){
for(var i=0;i<path.length;i++){
string = string + '\t';
}
}
return string;
} | javascript | function(){
var string = '\t\t\t',
path = info.path.replace(baseDir, '').split('/');
if(path.length > 1){
for(var i=0;i<path.length;i++){
string = string + '\t';
}
}
return string;
} | [
"function",
"(",
")",
"{",
"var",
"string",
"=",
"'\\t\\t\\t'",
",",
"path",
"=",
"info",
".",
"path",
".",
"replace",
"(",
"baseDir",
",",
"''",
")",
".",
"split",
"(",
"'/'",
")",
";",
"if",
"(",
"path",
".",
"length",
">",
"1",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"path",
".",
"length",
";",
"i",
"++",
")",
"{",
"string",
"=",
"string",
"+",
"'\\t'",
";",
"}",
"}",
"return",
"string",
";",
"}"
] | Assuming it's a file. | [
"Assuming",
"it",
"s",
"a",
"file",
"."
] | 1c2cfa1a1d53d9e367d341de735a46a81647714c | https://github.com/alisonailea/grunt-ractive-parse/blob/1c2cfa1a1d53d9e367d341de735a46a81647714c/tasks/ractiveparse.js#L189-L200 |
|
49,989 | es128/anysort | index.js | splice | function splice(array, criteria, tieBreakers) {
if (!criteria) { criteria = returnFalse; }
var matcher = anymatch(criteria);
var matched = array.filter(matcher);
var unmatched = array.filter(function(s) {
return matched.indexOf(s) === -1;
}).sort();
if (!Array.isArray(criteria)) { criteria = [criteria]; }
// use [].concat.apply because criteria may or may not be an array
matched = matched.sort(anysort([].concat.apply(criteria, tieBreakers)));
return {
matched: matched,
unmatched: unmatched,
sorted: matched.concat(unmatched)
};
} | javascript | function splice(array, criteria, tieBreakers) {
if (!criteria) { criteria = returnFalse; }
var matcher = anymatch(criteria);
var matched = array.filter(matcher);
var unmatched = array.filter(function(s) {
return matched.indexOf(s) === -1;
}).sort();
if (!Array.isArray(criteria)) { criteria = [criteria]; }
// use [].concat.apply because criteria may or may not be an array
matched = matched.sort(anysort([].concat.apply(criteria, tieBreakers)));
return {
matched: matched,
unmatched: unmatched,
sorted: matched.concat(unmatched)
};
} | [
"function",
"splice",
"(",
"array",
",",
"criteria",
",",
"tieBreakers",
")",
"{",
"if",
"(",
"!",
"criteria",
")",
"{",
"criteria",
"=",
"returnFalse",
";",
"}",
"var",
"matcher",
"=",
"anymatch",
"(",
"criteria",
")",
";",
"var",
"matched",
"=",
"array",
".",
"filter",
"(",
"matcher",
")",
";",
"var",
"unmatched",
"=",
"array",
".",
"filter",
"(",
"function",
"(",
"s",
")",
"{",
"return",
"matched",
".",
"indexOf",
"(",
"s",
")",
"===",
"-",
"1",
";",
"}",
")",
".",
"sort",
"(",
")",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"criteria",
")",
")",
"{",
"criteria",
"=",
"[",
"criteria",
"]",
";",
"}",
"// use [].concat.apply because criteria may or may not be an array",
"matched",
"=",
"matched",
".",
"sort",
"(",
"anysort",
"(",
"[",
"]",
".",
"concat",
".",
"apply",
"(",
"criteria",
",",
"tieBreakers",
")",
")",
")",
";",
"return",
"{",
"matched",
":",
"matched",
",",
"unmatched",
":",
"unmatched",
",",
"sorted",
":",
"matched",
".",
"concat",
"(",
"unmatched",
")",
"}",
";",
"}"
] | given the sorting criteria and full array, returns the fully sorted array as well as separate matched and unmatched lists | [
"given",
"the",
"sorting",
"criteria",
"and",
"full",
"array",
"returns",
"the",
"fully",
"sorted",
"array",
"as",
"well",
"as",
"separate",
"matched",
"and",
"unmatched",
"lists"
] | 048a87b0a0f3e6586a1edd09e1060a9863e92ea2 | https://github.com/es128/anysort/blob/048a87b0a0f3e6586a1edd09e1060a9863e92ea2/index.js#L47-L62 |
49,990 | es128/anysort | index.js | grouped | function grouped(array, groups, order) {
if (!groups) { groups = [returnFalse]; }
var sorted = [];
var ordered = [];
var remaining = array.slice();
var unmatchedPosition = groups.indexOf('unmatched');
groups.forEach(function(criteria, index) {
if (index === unmatchedPosition) { return; }
var tieBreakers = [];
if (index !== groups.length - 1) {
tieBreakers = groups.slice(index + 1);
if (index < unmatchedPosition) {
tieBreakers.splice(unmatchedPosition - index - 1, 1);
}
}
var spliced = splice(remaining, criteria, tieBreakers);
var matched = spliced.matched;
var unmatched = spliced.unmatched;
sorted[index] = matched;
remaining = unmatched;
});
if (unmatchedPosition === -1) { unmatchedPosition = sorted.length; }
sorted[unmatchedPosition] = remaining;
if (Array.isArray(order)) {
order.forEach(function(position, index) {
ordered[index] = sorted[position];
});
} else {
ordered = sorted;
}
return ordered.reduce(function(flat, group) {
return flat.concat(group);
}, []);
} | javascript | function grouped(array, groups, order) {
if (!groups) { groups = [returnFalse]; }
var sorted = [];
var ordered = [];
var remaining = array.slice();
var unmatchedPosition = groups.indexOf('unmatched');
groups.forEach(function(criteria, index) {
if (index === unmatchedPosition) { return; }
var tieBreakers = [];
if (index !== groups.length - 1) {
tieBreakers = groups.slice(index + 1);
if (index < unmatchedPosition) {
tieBreakers.splice(unmatchedPosition - index - 1, 1);
}
}
var spliced = splice(remaining, criteria, tieBreakers);
var matched = spliced.matched;
var unmatched = spliced.unmatched;
sorted[index] = matched;
remaining = unmatched;
});
if (unmatchedPosition === -1) { unmatchedPosition = sorted.length; }
sorted[unmatchedPosition] = remaining;
if (Array.isArray(order)) {
order.forEach(function(position, index) {
ordered[index] = sorted[position];
});
} else {
ordered = sorted;
}
return ordered.reduce(function(flat, group) {
return flat.concat(group);
}, []);
} | [
"function",
"grouped",
"(",
"array",
",",
"groups",
",",
"order",
")",
"{",
"if",
"(",
"!",
"groups",
")",
"{",
"groups",
"=",
"[",
"returnFalse",
"]",
";",
"}",
"var",
"sorted",
"=",
"[",
"]",
";",
"var",
"ordered",
"=",
"[",
"]",
";",
"var",
"remaining",
"=",
"array",
".",
"slice",
"(",
")",
";",
"var",
"unmatchedPosition",
"=",
"groups",
".",
"indexOf",
"(",
"'unmatched'",
")",
";",
"groups",
".",
"forEach",
"(",
"function",
"(",
"criteria",
",",
"index",
")",
"{",
"if",
"(",
"index",
"===",
"unmatchedPosition",
")",
"{",
"return",
";",
"}",
"var",
"tieBreakers",
"=",
"[",
"]",
";",
"if",
"(",
"index",
"!==",
"groups",
".",
"length",
"-",
"1",
")",
"{",
"tieBreakers",
"=",
"groups",
".",
"slice",
"(",
"index",
"+",
"1",
")",
";",
"if",
"(",
"index",
"<",
"unmatchedPosition",
")",
"{",
"tieBreakers",
".",
"splice",
"(",
"unmatchedPosition",
"-",
"index",
"-",
"1",
",",
"1",
")",
";",
"}",
"}",
"var",
"spliced",
"=",
"splice",
"(",
"remaining",
",",
"criteria",
",",
"tieBreakers",
")",
";",
"var",
"matched",
"=",
"spliced",
".",
"matched",
";",
"var",
"unmatched",
"=",
"spliced",
".",
"unmatched",
";",
"sorted",
"[",
"index",
"]",
"=",
"matched",
";",
"remaining",
"=",
"unmatched",
";",
"}",
")",
";",
"if",
"(",
"unmatchedPosition",
"===",
"-",
"1",
")",
"{",
"unmatchedPosition",
"=",
"sorted",
".",
"length",
";",
"}",
"sorted",
"[",
"unmatchedPosition",
"]",
"=",
"remaining",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"order",
")",
")",
"{",
"order",
".",
"forEach",
"(",
"function",
"(",
"position",
",",
"index",
")",
"{",
"ordered",
"[",
"index",
"]",
"=",
"sorted",
"[",
"position",
"]",
";",
"}",
")",
";",
"}",
"else",
"{",
"ordered",
"=",
"sorted",
";",
"}",
"return",
"ordered",
".",
"reduce",
"(",
"function",
"(",
"flat",
",",
"group",
")",
"{",
"return",
"flat",
".",
"concat",
"(",
"group",
")",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Does a full sort based on an array of criteria, plus the option to set the position of any unmatched items. Can be used with an anymatch-compatible criteria array, or an array of those arrays. | [
"Does",
"a",
"full",
"sort",
"based",
"on",
"an",
"array",
"of",
"criteria",
"plus",
"the",
"option",
"to",
"set",
"the",
"position",
"of",
"any",
"unmatched",
"items",
".",
"Can",
"be",
"used",
"with",
"an",
"anymatch",
"-",
"compatible",
"criteria",
"array",
"or",
"an",
"array",
"of",
"those",
"arrays",
"."
] | 048a87b0a0f3e6586a1edd09e1060a9863e92ea2 | https://github.com/es128/anysort/blob/048a87b0a0f3e6586a1edd09e1060a9863e92ea2/index.js#L69-L102 |
49,991 | plepe/modulekit-tabs | src/Tab.js | Tab | function Tab (options) {
this.options = options || {}
this.master = null
this.header = document.createElement('li')
this.header.onclick = function () {
this.toggle()
}.bind(this)
this.content = document.createElement('div')
this.content.className = 'tabs-section'
} | javascript | function Tab (options) {
this.options = options || {}
this.master = null
this.header = document.createElement('li')
this.header.onclick = function () {
this.toggle()
}.bind(this)
this.content = document.createElement('div')
this.content.className = 'tabs-section'
} | [
"function",
"Tab",
"(",
"options",
")",
"{",
"this",
".",
"options",
"=",
"options",
"||",
"{",
"}",
"this",
".",
"master",
"=",
"null",
"this",
".",
"header",
"=",
"document",
".",
"createElement",
"(",
"'li'",
")",
"this",
".",
"header",
".",
"onclick",
"=",
"function",
"(",
")",
"{",
"this",
".",
"toggle",
"(",
")",
"}",
".",
"bind",
"(",
"this",
")",
"this",
".",
"content",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
"this",
".",
"content",
".",
"className",
"=",
"'tabs-section'",
"}"
] | add a new tab pane to the tabs
@param {Object} options
@param {String} options.id ID of the tab
@param {Number} [options.weight=0] Order tabs by weight. Tabs with lower weight first.
@property {DOMNode} content
@property {DOMNode} header
@property {Tabs} master | [
"add",
"a",
"new",
"tab",
"pane",
"to",
"the",
"tabs"
] | 6aa10ef20301bc2a4c9f0fcfb7f536b0700ce216 | https://github.com/plepe/modulekit-tabs/blob/6aa10ef20301bc2a4c9f0fcfb7f536b0700ce216/src/Tab.js#L12-L23 |
49,992 | vkiding/jud-vue-render | src/render/browser/extend/components/scrollable/motion.js | quadratic2cubicBezier | function quadratic2cubicBezier (a, b) {
return [
[
(a / 3 + (a + b) / 3 - a) / (b - a),
(a * a / 3 + a * b * 2 / 3 - a * a) / (b * b - a * a)
], [
(b / 3 + (a + b) / 3 - a) / (b - a),
(b * b / 3 + a * b * 2 / 3 - a * a) / (b * b - a * a)
]
]
} | javascript | function quadratic2cubicBezier (a, b) {
return [
[
(a / 3 + (a + b) / 3 - a) / (b - a),
(a * a / 3 + a * b * 2 / 3 - a * a) / (b * b - a * a)
], [
(b / 3 + (a + b) / 3 - a) / (b - a),
(b * b / 3 + a * b * 2 / 3 - a * a) / (b * b - a * a)
]
]
} | [
"function",
"quadratic2cubicBezier",
"(",
"a",
",",
"b",
")",
"{",
"return",
"[",
"[",
"(",
"a",
"/",
"3",
"+",
"(",
"a",
"+",
"b",
")",
"/",
"3",
"-",
"a",
")",
"/",
"(",
"b",
"-",
"a",
")",
",",
"(",
"a",
"*",
"a",
"/",
"3",
"+",
"a",
"*",
"b",
"*",
"2",
"/",
"3",
"-",
"a",
"*",
"a",
")",
"/",
"(",
"b",
"*",
"b",
"-",
"a",
"*",
"a",
")",
"]",
",",
"[",
"(",
"b",
"/",
"3",
"+",
"(",
"a",
"+",
"b",
")",
"/",
"3",
"-",
"a",
")",
"/",
"(",
"b",
"-",
"a",
")",
",",
"(",
"b",
"*",
"b",
"/",
"3",
"+",
"a",
"*",
"b",
"*",
"2",
"/",
"3",
"-",
"a",
"*",
"a",
")",
"/",
"(",
"b",
"*",
"b",
"-",
"a",
"*",
"a",
")",
"]",
"]",
"}"
] | transfer Quadratic Bezier Curve to Cubic Bezier Curve
@param {number} a abscissa of p1
@param {number} b ordinate of p1
@return {Array} parameter matrix for cubic bezier curve
like [[p1x, p1y], [p2x, p2y]] | [
"transfer",
"Quadratic",
"Bezier",
"Curve",
"to",
"Cubic",
"Bezier",
"Curve"
] | 07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47 | https://github.com/vkiding/jud-vue-render/blob/07d8ab08d0ef86cf2819e5f2bf1f4b06381f4d47/src/render/browser/extend/components/scrollable/motion.js#L13-L23 |
49,993 | meandavejustice/deploy-txp | lib/sign.js | distAddon | function distAddon(opts, cb) {
// sign our add-on
const generatedXpi = 'addon.xpi';
signAddon(generatedXpi, opts.apiKey, opts.apiSecret, function(err, signedXpiPath) {
if (err) return cb(err);
// remove our generated xpi since we now have a signed version
removeGeneratedXpi();
// move our signed xpi and rdf into the /dist dir
// directory and exit
checkExistsAndMv(signedXpiPath, 'signed-addon.xpi', function(err) {
if (err) return cb(err);
console.log('addon.xpi written to signed-addon.xpi');
cb();
});
});
} | javascript | function distAddon(opts, cb) {
// sign our add-on
const generatedXpi = 'addon.xpi';
signAddon(generatedXpi, opts.apiKey, opts.apiSecret, function(err, signedXpiPath) {
if (err) return cb(err);
// remove our generated xpi since we now have a signed version
removeGeneratedXpi();
// move our signed xpi and rdf into the /dist dir
// directory and exit
checkExistsAndMv(signedXpiPath, 'signed-addon.xpi', function(err) {
if (err) return cb(err);
console.log('addon.xpi written to signed-addon.xpi');
cb();
});
});
} | [
"function",
"distAddon",
"(",
"opts",
",",
"cb",
")",
"{",
"// sign our add-on",
"const",
"generatedXpi",
"=",
"'addon.xpi'",
";",
"signAddon",
"(",
"generatedXpi",
",",
"opts",
".",
"apiKey",
",",
"opts",
".",
"apiSecret",
",",
"function",
"(",
"err",
",",
"signedXpiPath",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"// remove our generated xpi since we now have a signed version",
"removeGeneratedXpi",
"(",
")",
";",
"// move our signed xpi and rdf into the /dist dir",
"// directory and exit",
"checkExistsAndMv",
"(",
"signedXpiPath",
",",
"'signed-addon.xpi'",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
";",
"console",
".",
"log",
"(",
"'addon.xpi written to signed-addon.xpi'",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | if we need to sign and distribute our add-on, we want to use this method | [
"if",
"we",
"need",
"to",
"sign",
"and",
"distribute",
"our",
"add",
"-",
"on",
"we",
"want",
"to",
"use",
"this",
"method"
] | d9d3024a836c7976c337e934c5065e2d08f4dadb | https://github.com/meandavejustice/deploy-txp/blob/d9d3024a836c7976c337e934c5065e2d08f4dadb/lib/sign.js#L51-L66 |
49,994 | marshallswain/feathers-mongo-collections | lib/feathers-mongo-collections.js | function(coll, callback){
// Switch databases
var collection = self.db.collection(coll.name);
// Get the stats. null if empty.
collection.stats(function(err, stats){
// Add the stats to the corresponding database.
coll.stats = stats;
callback(err, coll);
});
} | javascript | function(coll, callback){
// Switch databases
var collection = self.db.collection(coll.name);
// Get the stats. null if empty.
collection.stats(function(err, stats){
// Add the stats to the corresponding database.
coll.stats = stats;
callback(err, coll);
});
} | [
"function",
"(",
"coll",
",",
"callback",
")",
"{",
"// Switch databases",
"var",
"collection",
"=",
"self",
".",
"db",
".",
"collection",
"(",
"coll",
".",
"name",
")",
";",
"// Get the stats. null if empty.",
"collection",
".",
"stats",
"(",
"function",
"(",
"err",
",",
"stats",
")",
"{",
"// Add the stats to the corresponding database.",
"coll",
".",
"stats",
"=",
"stats",
";",
"callback",
"(",
"err",
",",
"coll",
")",
";",
"}",
")",
";",
"}"
] | Async function to add stats to each collection. | [
"Async",
"function",
"to",
"add",
"stats",
"to",
"each",
"collection",
"."
] | d650b30569984113efda9687f3a45712678bf4e2 | https://github.com/marshallswain/feathers-mongo-collections/blob/d650b30569984113efda9687f3a45712678bf4e2/lib/feathers-mongo-collections.js#L51-L60 |
|
49,995 | marshallswain/feathers-mongo-collections | lib/feathers-mongo-collections.js | function(data, params, callback) {
if (!data.name) {
return callback({error:'name is required'});
}
this.db.createCollection(data.name, {}, function(err, collection){
var response = {
name:collection.collectionName,
_id:collection.collectionName
};
return callback(null, response);
});
} | javascript | function(data, params, callback) {
if (!data.name) {
return callback({error:'name is required'});
}
this.db.createCollection(data.name, {}, function(err, collection){
var response = {
name:collection.collectionName,
_id:collection.collectionName
};
return callback(null, response);
});
} | [
"function",
"(",
"data",
",",
"params",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"data",
".",
"name",
")",
"{",
"return",
"callback",
"(",
"{",
"error",
":",
"'name is required'",
"}",
")",
";",
"}",
"this",
".",
"db",
".",
"createCollection",
"(",
"data",
".",
"name",
",",
"{",
"}",
",",
"function",
"(",
"err",
",",
"collection",
")",
"{",
"var",
"response",
"=",
"{",
"name",
":",
"collection",
".",
"collectionName",
",",
"_id",
":",
"collection",
".",
"collectionName",
"}",
";",
"return",
"callback",
"(",
"null",
",",
"response",
")",
";",
"}",
")",
";",
"}"
] | Create a collection.
@param {String} data.name - The name of the collection to be created.
@return {Object} - name:collectionName | [
"Create",
"a",
"collection",
"."
] | d650b30569984113efda9687f3a45712678bf4e2 | https://github.com/marshallswain/feathers-mongo-collections/blob/d650b30569984113efda9687f3a45712678bf4e2/lib/feathers-mongo-collections.js#L82-L93 |
|
49,996 | wozlla/WOZLLA.js | WOZLLA.js | GameObject | function GameObject(useRectTransform) {
if (useRectTransform === void 0) { useRectTransform = false; }
_super.call(this);
this._UID = WOZLLA.utils.IdentifyUtils.genUID();
this._active = true;
this._visible = true;
this._initialized = false;
this._destroyed = false;
this._touchable = false;
this._loadingAssets = false;
this._name = 'GameObject';
this._children = [];
this._components = [];
this._transform = useRectTransform ? new WOZLLA.RectTransform() : new WOZLLA.Transform();
this._rectTransform = useRectTransform ? this._transform : null;
this._z = 0;
this._behaviours = [];
} | javascript | function GameObject(useRectTransform) {
if (useRectTransform === void 0) { useRectTransform = false; }
_super.call(this);
this._UID = WOZLLA.utils.IdentifyUtils.genUID();
this._active = true;
this._visible = true;
this._initialized = false;
this._destroyed = false;
this._touchable = false;
this._loadingAssets = false;
this._name = 'GameObject';
this._children = [];
this._components = [];
this._transform = useRectTransform ? new WOZLLA.RectTransform() : new WOZLLA.Transform();
this._rectTransform = useRectTransform ? this._transform : null;
this._z = 0;
this._behaviours = [];
} | [
"function",
"GameObject",
"(",
"useRectTransform",
")",
"{",
"if",
"(",
"useRectTransform",
"===",
"void",
"0",
")",
"{",
"useRectTransform",
"=",
"false",
";",
"}",
"_super",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"_UID",
"=",
"WOZLLA",
".",
"utils",
".",
"IdentifyUtils",
".",
"genUID",
"(",
")",
";",
"this",
".",
"_active",
"=",
"true",
";",
"this",
".",
"_visible",
"=",
"true",
";",
"this",
".",
"_initialized",
"=",
"false",
";",
"this",
".",
"_destroyed",
"=",
"false",
";",
"this",
".",
"_touchable",
"=",
"false",
";",
"this",
".",
"_loadingAssets",
"=",
"false",
";",
"this",
".",
"_name",
"=",
"'GameObject'",
";",
"this",
".",
"_children",
"=",
"[",
"]",
";",
"this",
".",
"_components",
"=",
"[",
"]",
";",
"this",
".",
"_transform",
"=",
"useRectTransform",
"?",
"new",
"WOZLLA",
".",
"RectTransform",
"(",
")",
":",
"new",
"WOZLLA",
".",
"Transform",
"(",
")",
";",
"this",
".",
"_rectTransform",
"=",
"useRectTransform",
"?",
"this",
".",
"_transform",
":",
"null",
";",
"this",
".",
"_z",
"=",
"0",
";",
"this",
".",
"_behaviours",
"=",
"[",
"]",
";",
"}"
] | new a GameObject
@method constructor
@member WOZLLA.GameObject
@param {boolean} useRectTransform specify which transform this game object should be used. | [
"new",
"a",
"GameObject"
] | 96273d43cd6cbbfd9f68789f4320ce0f7df9b148 | https://github.com/wozlla/WOZLLA.js/blob/96273d43cd6cbbfd9f68789f4320ce0f7df9b148/WOZLLA.js#L2140-L2157 |
49,997 | wozlla/WOZLLA.js | WOZLLA.js | Sprite | function Sprite(spriteAtlas, frame, name) {
this._spriteAtlas = spriteAtlas;
this._frame = frame;
this._name = name;
} | javascript | function Sprite(spriteAtlas, frame, name) {
this._spriteAtlas = spriteAtlas;
this._frame = frame;
this._name = name;
} | [
"function",
"Sprite",
"(",
"spriteAtlas",
",",
"frame",
",",
"name",
")",
"{",
"this",
".",
"_spriteAtlas",
"=",
"spriteAtlas",
";",
"this",
".",
"_frame",
"=",
"frame",
";",
"this",
".",
"_name",
"=",
"name",
";",
"}"
] | new a sprite
@method constructor
@param spriteAtlas
@param frame
@param name | [
"new",
"a",
"sprite"
] | 96273d43cd6cbbfd9f68789f4320ce0f7df9b148 | https://github.com/wozlla/WOZLLA.js/blob/96273d43cd6cbbfd9f68789f4320ce0f7df9b148/WOZLLA.js#L5031-L5035 |
49,998 | origin1tech/chek | dist/modules/array.js | containsAny | function containsAny(arr, compare, transform) {
if (is_1.isString(arr))
arr = arr.split('');
if (is_1.isString(compare))
compare = compare.split('');
if (!is_1.isArray(arr) || !is_1.isArray(compare))
return false;
return compare.filter(function (c) {
return contains(arr, c, transform);
}).length > 0;
} | javascript | function containsAny(arr, compare, transform) {
if (is_1.isString(arr))
arr = arr.split('');
if (is_1.isString(compare))
compare = compare.split('');
if (!is_1.isArray(arr) || !is_1.isArray(compare))
return false;
return compare.filter(function (c) {
return contains(arr, c, transform);
}).length > 0;
} | [
"function",
"containsAny",
"(",
"arr",
",",
"compare",
",",
"transform",
")",
"{",
"if",
"(",
"is_1",
".",
"isString",
"(",
"arr",
")",
")",
"arr",
"=",
"arr",
".",
"split",
"(",
"''",
")",
";",
"if",
"(",
"is_1",
".",
"isString",
"(",
"compare",
")",
")",
"compare",
"=",
"compare",
".",
"split",
"(",
"''",
")",
";",
"if",
"(",
"!",
"is_1",
".",
"isArray",
"(",
"arr",
")",
"||",
"!",
"is_1",
".",
"isArray",
"(",
"compare",
")",
")",
"return",
"false",
";",
"return",
"compare",
".",
"filter",
"(",
"function",
"(",
"c",
")",
"{",
"return",
"contains",
"(",
"arr",
",",
"c",
",",
"transform",
")",
";",
"}",
")",
".",
"length",
">",
"0",
";",
"}"
] | Contains Any
Tests array check if contains value.
@param arr the array to be inspected.
@param compare - array of values to compare. | [
"Contains",
"Any",
"Tests",
"array",
"check",
"if",
"contains",
"value",
"."
] | 6bc3ab0ac36126cc7918a244a606009749897b2e | https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/array.js#L111-L121 |
49,999 | origin1tech/chek | dist/modules/array.js | duplicates | function duplicates(arr, value, breakable) {
var i = arr.length;
var dupes = 0;
while (i--) {
if (breakable && dupes > 0)
break;
if (is_1.isEqual(arr[i], value))
dupes += 1;
}
return dupes;
} | javascript | function duplicates(arr, value, breakable) {
var i = arr.length;
var dupes = 0;
while (i--) {
if (breakable && dupes > 0)
break;
if (is_1.isEqual(arr[i], value))
dupes += 1;
}
return dupes;
} | [
"function",
"duplicates",
"(",
"arr",
",",
"value",
",",
"breakable",
")",
"{",
"var",
"i",
"=",
"arr",
".",
"length",
";",
"var",
"dupes",
"=",
"0",
";",
"while",
"(",
"i",
"--",
")",
"{",
"if",
"(",
"breakable",
"&&",
"dupes",
">",
"0",
")",
"break",
";",
"if",
"(",
"is_1",
".",
"isEqual",
"(",
"arr",
"[",
"i",
"]",
",",
"value",
")",
")",
"dupes",
"+=",
"1",
";",
"}",
"return",
"dupes",
";",
"}"
] | Duplicates
Counts the number of duplicates in an array.
@param arr the array to check for duplicates.
@param value the value to match.
@param breakable when true allows breaking at first duplicate. | [
"Duplicates",
"Counts",
"the",
"number",
"of",
"duplicates",
"in",
"an",
"array",
"."
] | 6bc3ab0ac36126cc7918a244a606009749897b2e | https://github.com/origin1tech/chek/blob/6bc3ab0ac36126cc7918a244a606009749897b2e/dist/modules/array.js#L131-L141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.