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
|
---|---|---|---|---|---|---|---|---|---|---|---|
44,900 | jrmerz/node-ckan | lib/ckan-importer.js | setVocabIds | function setVocabIds(index, pkg, callback) {
if(!pkg.tags) return callback();
if( index == pkg.tags.length ) {
callback();
} else {
getVocabId(pkg.tags[index].vocabulary_id, function(id) {
pkg.tags[index].vocabulary_id = id;
index++;
setVocabIds(index, pkg, callback);
});
}
} | javascript | function setVocabIds(index, pkg, callback) {
if(!pkg.tags) return callback();
if( index == pkg.tags.length ) {
callback();
} else {
getVocabId(pkg.tags[index].vocabulary_id, function(id) {
pkg.tags[index].vocabulary_id = id;
index++;
setVocabIds(index, pkg, callback);
});
}
} | [
"function",
"setVocabIds",
"(",
"index",
",",
"pkg",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"pkg",
".",
"tags",
")",
"return",
"callback",
"(",
")",
";",
"if",
"(",
"index",
"==",
"pkg",
".",
"tags",
".",
"length",
")",
"{",
"callback",
"(",
")",
";",
"}",
"else",
"{",
"getVocabId",
"(",
"pkg",
".",
"tags",
"[",
"index",
"]",
".",
"vocabulary_id",
",",
"function",
"(",
"id",
")",
"{",
"pkg",
".",
"tags",
"[",
"index",
"]",
".",
"vocabulary_id",
"=",
"id",
";",
"index",
"++",
";",
"setVocabIds",
"(",
"index",
",",
"pkg",
",",
"callback",
")",
";",
"}",
")",
";",
"}",
"}"
]
| we are going to assume people pass names in the vocabulary_id column to which point we need to look up the id from the name so package_create does the correct association | [
"we",
"are",
"going",
"to",
"assume",
"people",
"pass",
"names",
"in",
"the",
"vocabulary_id",
"column",
"to",
"which",
"point",
"we",
"need",
"to",
"look",
"up",
"the",
"id",
"from",
"the",
"name",
"so",
"package_create",
"does",
"the",
"correct",
"association"
]
| 55f6bb1ece7f57ccd5ba57be7888e4d3941bc659 | https://github.com/jrmerz/node-ckan/blob/55f6bb1ece7f57ccd5ba57be7888e4d3941bc659/lib/ckan-importer.js#L158-L170 |
44,901 | jrmerz/node-ckan | lib/ckan-importer.js | getVocabId | function getVocabId(name, callback) {
if( vocabMap[name] ) return callback(vocabMap[name]);
ckan.exec("vocabulary_show", {id: name}, function(err, resp) {
if( err && JSON.parse(err.body).error.__type == 'Not Found Error' ) {
create("vocabulary", {name: name, tags: []}, function(err, resp){
if( err ) error("Unable to create vocabulary: "+name);
vocabMap[name] = resp.result.id;
callback(resp.result.id);
});
return;
} else if( err ) {
error("Unable to access vocabulary 'id:"+name+"'");
}
if( !resp.success ) {
if( name.match(/.*-.*-.*-.*-.*/) ) {
if( err ) error("No vocabulary found for passed id");
create("vocabulary", {name: name, tags: []}, function(err, resp){
if( err ) error("Unable to create vocabulary: "+name);
vocabMap[name] = resp.result.id;
callback(resp.result.id);
});
}
} else {
vocabMap[name] = resp.result.id;
callback(resp.result.id);
}
});
} | javascript | function getVocabId(name, callback) {
if( vocabMap[name] ) return callback(vocabMap[name]);
ckan.exec("vocabulary_show", {id: name}, function(err, resp) {
if( err && JSON.parse(err.body).error.__type == 'Not Found Error' ) {
create("vocabulary", {name: name, tags: []}, function(err, resp){
if( err ) error("Unable to create vocabulary: "+name);
vocabMap[name] = resp.result.id;
callback(resp.result.id);
});
return;
} else if( err ) {
error("Unable to access vocabulary 'id:"+name+"'");
}
if( !resp.success ) {
if( name.match(/.*-.*-.*-.*-.*/) ) {
if( err ) error("No vocabulary found for passed id");
create("vocabulary", {name: name, tags: []}, function(err, resp){
if( err ) error("Unable to create vocabulary: "+name);
vocabMap[name] = resp.result.id;
callback(resp.result.id);
});
}
} else {
vocabMap[name] = resp.result.id;
callback(resp.result.id);
}
});
} | [
"function",
"getVocabId",
"(",
"name",
",",
"callback",
")",
"{",
"if",
"(",
"vocabMap",
"[",
"name",
"]",
")",
"return",
"callback",
"(",
"vocabMap",
"[",
"name",
"]",
")",
";",
"ckan",
".",
"exec",
"(",
"\"vocabulary_show\"",
",",
"{",
"id",
":",
"name",
"}",
",",
"function",
"(",
"err",
",",
"resp",
")",
"{",
"if",
"(",
"err",
"&&",
"JSON",
".",
"parse",
"(",
"err",
".",
"body",
")",
".",
"error",
".",
"__type",
"==",
"'Not Found Error'",
")",
"{",
"create",
"(",
"\"vocabulary\"",
",",
"{",
"name",
":",
"name",
",",
"tags",
":",
"[",
"]",
"}",
",",
"function",
"(",
"err",
",",
"resp",
")",
"{",
"if",
"(",
"err",
")",
"error",
"(",
"\"Unable to create vocabulary: \"",
"+",
"name",
")",
";",
"vocabMap",
"[",
"name",
"]",
"=",
"resp",
".",
"result",
".",
"id",
";",
"callback",
"(",
"resp",
".",
"result",
".",
"id",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"err",
")",
"{",
"error",
"(",
"\"Unable to access vocabulary 'id:\"",
"+",
"name",
"+",
"\"'\"",
")",
";",
"}",
"if",
"(",
"!",
"resp",
".",
"success",
")",
"{",
"if",
"(",
"name",
".",
"match",
"(",
"/",
".*-.*-.*-.*-.*",
"/",
")",
")",
"{",
"if",
"(",
"err",
")",
"error",
"(",
"\"No vocabulary found for passed id\"",
")",
";",
"create",
"(",
"\"vocabulary\"",
",",
"{",
"name",
":",
"name",
",",
"tags",
":",
"[",
"]",
"}",
",",
"function",
"(",
"err",
",",
"resp",
")",
"{",
"if",
"(",
"err",
")",
"error",
"(",
"\"Unable to create vocabulary: \"",
"+",
"name",
")",
";",
"vocabMap",
"[",
"name",
"]",
"=",
"resp",
".",
"result",
".",
"id",
";",
"callback",
"(",
"resp",
".",
"result",
".",
"id",
")",
";",
"}",
")",
";",
"}",
"}",
"else",
"{",
"vocabMap",
"[",
"name",
"]",
"=",
"resp",
".",
"result",
".",
"id",
";",
"callback",
"(",
"resp",
".",
"result",
".",
"id",
")",
";",
"}",
"}",
")",
";",
"}"
]
| if the id doesn't exist, create it | [
"if",
"the",
"id",
"doesn",
"t",
"exist",
"create",
"it"
]
| 55f6bb1ece7f57ccd5ba57be7888e4d3941bc659 | https://github.com/jrmerz/node-ckan/blob/55f6bb1ece7f57ccd5ba57be7888e4d3941bc659/lib/ckan-importer.js#L173-L203 |
44,902 | AsceticBoy/chilli-toolkit | tools/build/bundle.js | format | function format() {
var format = 'es' // default
var args = process.argv.slice(2)
outer:
for (var i = 0; i < formats.length; i++) {
for (var j = 0; j < args.length; j++) {
if (args[j].slice(0, 2) !== '--') { throw new TypeError('process args usage error'); break outer }
if (args[j].toLocaleLowerCase().slice(9) === formats[i]) { format = formats[i]; break outer }
}
}
return format
} | javascript | function format() {
var format = 'es' // default
var args = process.argv.slice(2)
outer:
for (var i = 0; i < formats.length; i++) {
for (var j = 0; j < args.length; j++) {
if (args[j].slice(0, 2) !== '--') { throw new TypeError('process args usage error'); break outer }
if (args[j].toLocaleLowerCase().slice(9) === formats[i]) { format = formats[i]; break outer }
}
}
return format
} | [
"function",
"format",
"(",
")",
"{",
"var",
"format",
"=",
"'es'",
"// default",
"var",
"args",
"=",
"process",
".",
"argv",
".",
"slice",
"(",
"2",
")",
"outer",
":",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"formats",
".",
"length",
";",
"i",
"++",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"args",
".",
"length",
";",
"j",
"++",
")",
"{",
"if",
"(",
"args",
"[",
"j",
"]",
".",
"slice",
"(",
"0",
",",
"2",
")",
"!==",
"'--'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'process args usage error'",
")",
";",
"break",
"outer",
"}",
"if",
"(",
"args",
"[",
"j",
"]",
".",
"toLocaleLowerCase",
"(",
")",
".",
"slice",
"(",
"9",
")",
"===",
"formats",
"[",
"i",
"]",
")",
"{",
"format",
"=",
"formats",
"[",
"i",
"]",
";",
"break",
"outer",
"}",
"}",
"}",
"return",
"format",
"}"
]
| output format type | [
"output",
"format",
"type"
]
| a4f5f03ce55187a8c91b847e84d767357f347839 | https://github.com/AsceticBoy/chilli-toolkit/blob/a4f5f03ce55187a8c91b847e84d767357f347839/tools/build/bundle.js#L95-L107 |
44,903 | AsceticBoy/chilli-toolkit | tools/build/bundle.js | write | function write(dir, code) {
return new Promise(function (resolve, reject) {
fse.ensureFile(dir, (err) => {
if (err) return reject(err)
fs.writeFile(dir, code, 'utf-8', (err) => {
if (err) {
return reject(err)
}
console.info(chalk.red(dir) + ' ' + chalk.green(getSize(code)))
resolve()
})
})
})
} | javascript | function write(dir, code) {
return new Promise(function (resolve, reject) {
fse.ensureFile(dir, (err) => {
if (err) return reject(err)
fs.writeFile(dir, code, 'utf-8', (err) => {
if (err) {
return reject(err)
}
console.info(chalk.red(dir) + ' ' + chalk.green(getSize(code)))
resolve()
})
})
})
} | [
"function",
"write",
"(",
"dir",
",",
"code",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"fse",
".",
"ensureFile",
"(",
"dir",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"return",
"reject",
"(",
"err",
")",
"fs",
".",
"writeFile",
"(",
"dir",
",",
"code",
",",
"'utf-8'",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"err",
")",
"}",
"console",
".",
"info",
"(",
"chalk",
".",
"red",
"(",
"dir",
")",
"+",
"' '",
"+",
"chalk",
".",
"green",
"(",
"getSize",
"(",
"code",
")",
")",
")",
"resolve",
"(",
")",
"}",
")",
"}",
")",
"}",
")",
"}"
]
| Write code in dir path
@param { String } dir file path dir
@param { String | Buffer } code code | [
"Write",
"code",
"in",
"dir",
"path"
]
| a4f5f03ce55187a8c91b847e84d767357f347839 | https://github.com/AsceticBoy/chilli-toolkit/blob/a4f5f03ce55187a8c91b847e84d767357f347839/tools/build/bundle.js#L115-L128 |
44,904 | verekia/remark-lint-no-leading-spaces | index.js | noLeadingSpaces | function noLeadingSpaces(ast, file) {
var lines = file.toString().split('\n');
for (var i = 0; i < lines.length; i++) {
var currentLine = lines[i];
var lineIndex = i + 1;
if (/^\s/.test(currentLine)) {
file.message('Remove leading whitespace', {
position: {
start: { line: lineIndex, column: 1 },
end: { line: lineIndex }
}
});
}
}
} | javascript | function noLeadingSpaces(ast, file) {
var lines = file.toString().split('\n');
for (var i = 0; i < lines.length; i++) {
var currentLine = lines[i];
var lineIndex = i + 1;
if (/^\s/.test(currentLine)) {
file.message('Remove leading whitespace', {
position: {
start: { line: lineIndex, column: 1 },
end: { line: lineIndex }
}
});
}
}
} | [
"function",
"noLeadingSpaces",
"(",
"ast",
",",
"file",
")",
"{",
"var",
"lines",
"=",
"file",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"lines",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"currentLine",
"=",
"lines",
"[",
"i",
"]",
";",
"var",
"lineIndex",
"=",
"i",
"+",
"1",
";",
"if",
"(",
"/",
"^\\s",
"/",
".",
"test",
"(",
"currentLine",
")",
")",
"{",
"file",
".",
"message",
"(",
"'Remove leading whitespace'",
",",
"{",
"position",
":",
"{",
"start",
":",
"{",
"line",
":",
"lineIndex",
",",
"column",
":",
"1",
"}",
",",
"end",
":",
"{",
"line",
":",
"lineIndex",
"}",
"}",
"}",
")",
";",
"}",
"}",
"}"
]
| Lines that are just space characters are not present in
the AST, which is why we loop through lines manually. | [
"Lines",
"that",
"are",
"just",
"space",
"characters",
"are",
"not",
"present",
"in",
"the",
"AST",
"which",
"is",
"why",
"we",
"loop",
"through",
"lines",
"manually",
"."
]
| d6ff6dcb8f1a3c6614deec9d54ed78a224b15e28 | https://github.com/verekia/remark-lint-no-leading-spaces/blob/d6ff6dcb8f1a3c6614deec9d54ed78a224b15e28/index.js#L8-L22 |
44,905 | DScheglov/merest | lib/controllers/static-method.js | callStaticMethod | function callStaticMethod(methodName, req, res, next) {
res.__apiMethod = 'staticMethod';
res.__apiStaticMethod = methodName;
var self = this;
var methodOptions = this.apiOptions.exposeStatic[methodName] || {};
var wrapper = methodOptions.exec;
if (!(wrapper instanceof Function)) wrapper = null;
var httpMethod = methodOptions.method || 'post';
var params = (httpMethod !== 'get') ? req.body : req.query;
var mFunc = wrapper || this.model[methodName];
mFunc.call(this.model, params, function(err, result) {
if (err) return next(err);
res.json(result);
});
} | javascript | function callStaticMethod(methodName, req, res, next) {
res.__apiMethod = 'staticMethod';
res.__apiStaticMethod = methodName;
var self = this;
var methodOptions = this.apiOptions.exposeStatic[methodName] || {};
var wrapper = methodOptions.exec;
if (!(wrapper instanceof Function)) wrapper = null;
var httpMethod = methodOptions.method || 'post';
var params = (httpMethod !== 'get') ? req.body : req.query;
var mFunc = wrapper || this.model[methodName];
mFunc.call(this.model, params, function(err, result) {
if (err) return next(err);
res.json(result);
});
} | [
"function",
"callStaticMethod",
"(",
"methodName",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"__apiMethod",
"=",
"'staticMethod'",
";",
"res",
".",
"__apiStaticMethod",
"=",
"methodName",
";",
"var",
"self",
"=",
"this",
";",
"var",
"methodOptions",
"=",
"this",
".",
"apiOptions",
".",
"exposeStatic",
"[",
"methodName",
"]",
"||",
"{",
"}",
";",
"var",
"wrapper",
"=",
"methodOptions",
".",
"exec",
";",
"if",
"(",
"!",
"(",
"wrapper",
"instanceof",
"Function",
")",
")",
"wrapper",
"=",
"null",
";",
"var",
"httpMethod",
"=",
"methodOptions",
".",
"method",
"||",
"'post'",
";",
"var",
"params",
"=",
"(",
"httpMethod",
"!==",
"'get'",
")",
"?",
"req",
".",
"body",
":",
"req",
".",
"query",
";",
"var",
"mFunc",
"=",
"wrapper",
"||",
"this",
".",
"model",
"[",
"methodName",
"]",
";",
"mFunc",
".",
"call",
"(",
"this",
".",
"model",
",",
"params",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
";",
"res",
".",
"json",
"(",
"result",
")",
";",
"}",
")",
";",
"}"
]
| callStaticMethod - controller that calls a static method of model
@param {String} methodName the name of method that should be called
@param {express.Request} req the http(s) request
@param {express.Response} res the http(s) response
@param {Function} next the callback should be called if controller fails
@memberof ModelAPIRouter | [
"callStaticMethod",
"-",
"controller",
"that",
"calls",
"a",
"static",
"method",
"of",
"model"
]
| d39e7ef0d56236247773467e9bfe83cb128ebc01 | https://github.com/DScheglov/merest/blob/d39e7ef0d56236247773467e9bfe83cb128ebc01/lib/controllers/static-method.js#L12-L30 |
44,906 | cfpb/AtomicComponent | src/utilities/dom-class-list/index.js | addClass | function addClass( element ) {
const addClassNamesArray = _sliceArgs( arguments );
if ( hasClassList ) {
element.classList.add.apply( element.classList, addClassNamesArray );
} else {
var classes = element.className.split( ' ' );
addClassNamesArray.forEach( function( name ) {
if ( classes.indexOf( name ) === -1 ) {
classes.push( name );
}
} );
element.className = classes.join( ' ' );
}
return element;
} | javascript | function addClass( element ) {
const addClassNamesArray = _sliceArgs( arguments );
if ( hasClassList ) {
element.classList.add.apply( element.classList, addClassNamesArray );
} else {
var classes = element.className.split( ' ' );
addClassNamesArray.forEach( function( name ) {
if ( classes.indexOf( name ) === -1 ) {
classes.push( name );
}
} );
element.className = classes.join( ' ' );
}
return element;
} | [
"function",
"addClass",
"(",
"element",
")",
"{",
"const",
"addClassNamesArray",
"=",
"_sliceArgs",
"(",
"arguments",
")",
";",
"if",
"(",
"hasClassList",
")",
"{",
"element",
".",
"classList",
".",
"add",
".",
"apply",
"(",
"element",
".",
"classList",
",",
"addClassNamesArray",
")",
";",
"}",
"else",
"{",
"var",
"classes",
"=",
"element",
".",
"className",
".",
"split",
"(",
"' '",
")",
";",
"addClassNamesArray",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"if",
"(",
"classes",
".",
"indexOf",
"(",
"name",
")",
"===",
"-",
"1",
")",
"{",
"classes",
".",
"push",
"(",
"name",
")",
";",
"}",
"}",
")",
";",
"element",
".",
"className",
"=",
"classes",
".",
"join",
"(",
"' '",
")",
";",
"}",
"return",
"element",
";",
"}"
]
| Add CSS class from an element.
@param {HTMLNode} element - A DOM element.
@param {string} className - CSS selector.
@returns {HTMLNode} element - A DOM element. | [
"Add",
"CSS",
"class",
"from",
"an",
"element",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/dom-class-list/index.js#L34-L49 |
44,907 | cfpb/AtomicComponent | src/utilities/dom-class-list/index.js | contains | function contains( element, className ) {
className = className.replace( '.', '' );
if ( hasClassList ) {
return element.classList.contains( className );
}
return element.className.indexOf( className ) > -1;
} | javascript | function contains( element, className ) {
className = className.replace( '.', '' );
if ( hasClassList ) {
return element.classList.contains( className );
}
return element.className.indexOf( className ) > -1;
} | [
"function",
"contains",
"(",
"element",
",",
"className",
")",
"{",
"className",
"=",
"className",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
";",
"if",
"(",
"hasClassList",
")",
"{",
"return",
"element",
".",
"classList",
".",
"contains",
"(",
"className",
")",
";",
"}",
"return",
"element",
".",
"className",
".",
"indexOf",
"(",
"className",
")",
">",
"-",
"1",
";",
"}"
]
| Determine if element has particular CSS class.
@param {HTMLNode} element - A DOM element.
@param {string} className - CSS selector.
@returns {boolean} True if `element` contains class `className`. | [
"Determine",
"if",
"element",
"has",
"particular",
"CSS",
"class",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/dom-class-list/index.js#L58-L65 |
44,908 | cfpb/AtomicComponent | src/utilities/dom-class-list/index.js | removeClass | function removeClass( element ) {
const removeClassNamesArray = _sliceArgs( arguments );
if ( hasClassList ) {
element.classList.remove
.apply( element.classList, removeClassNamesArray );
} else {
var classes = element.className.split( ' ' );
removeClassNamesArray.forEach( function( className ) {
if ( className ) {
classes.splice( classes.indexOf( className ), 1 );
}
} );
element.className = classes.join( ' ' );
}
} | javascript | function removeClass( element ) {
const removeClassNamesArray = _sliceArgs( arguments );
if ( hasClassList ) {
element.classList.remove
.apply( element.classList, removeClassNamesArray );
} else {
var classes = element.className.split( ' ' );
removeClassNamesArray.forEach( function( className ) {
if ( className ) {
classes.splice( classes.indexOf( className ), 1 );
}
} );
element.className = classes.join( ' ' );
}
} | [
"function",
"removeClass",
"(",
"element",
")",
"{",
"const",
"removeClassNamesArray",
"=",
"_sliceArgs",
"(",
"arguments",
")",
";",
"if",
"(",
"hasClassList",
")",
"{",
"element",
".",
"classList",
".",
"remove",
".",
"apply",
"(",
"element",
".",
"classList",
",",
"removeClassNamesArray",
")",
";",
"}",
"else",
"{",
"var",
"classes",
"=",
"element",
".",
"className",
".",
"split",
"(",
"' '",
")",
";",
"removeClassNamesArray",
".",
"forEach",
"(",
"function",
"(",
"className",
")",
"{",
"if",
"(",
"className",
")",
"{",
"classes",
".",
"splice",
"(",
"classes",
".",
"indexOf",
"(",
"className",
")",
",",
"1",
")",
";",
"}",
"}",
")",
";",
"element",
".",
"className",
"=",
"classes",
".",
"join",
"(",
"' '",
")",
";",
"}",
"}"
]
| Remove CSS class from an element.
@param {HTMLNode} element - A DOM element.
@param {string} className - CSS selector. | [
"Remove",
"CSS",
"class",
"from",
"an",
"element",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/dom-class-list/index.js#L73-L87 |
44,909 | cfpb/AtomicComponent | src/utilities/dom-class-list/index.js | toggleClass | function toggleClass( element, className, forceFlag ) {
let hasClass = false;
if ( hasClassList ) {
hasClass = element.classList.toggle( className );
} else if ( forceFlag === false || contains( element, className ) ) {
removeClass( element, forceFlag );
} else {
addClass( element, className );
hasClass = true;
}
return hasClass;
} | javascript | function toggleClass( element, className, forceFlag ) {
let hasClass = false;
if ( hasClassList ) {
hasClass = element.classList.toggle( className );
} else if ( forceFlag === false || contains( element, className ) ) {
removeClass( element, forceFlag );
} else {
addClass( element, className );
hasClass = true;
}
return hasClass;
} | [
"function",
"toggleClass",
"(",
"element",
",",
"className",
",",
"forceFlag",
")",
"{",
"let",
"hasClass",
"=",
"false",
";",
"if",
"(",
"hasClassList",
")",
"{",
"hasClass",
"=",
"element",
".",
"classList",
".",
"toggle",
"(",
"className",
")",
";",
"}",
"else",
"if",
"(",
"forceFlag",
"===",
"false",
"||",
"contains",
"(",
"element",
",",
"className",
")",
")",
"{",
"removeClass",
"(",
"element",
",",
"forceFlag",
")",
";",
"}",
"else",
"{",
"addClass",
"(",
"element",
",",
"className",
")",
";",
"hasClass",
"=",
"true",
";",
"}",
"return",
"hasClass",
";",
"}"
]
| Toggle CSS class on an element.
@param {HTMLNode} element - A DOM element.
@param {string} className - CSS selector.
@param {boolean} forceFlag - True if `className` class
should be forcibly removed.
@returns {boolean} True if the flag existed, false otherwise. | [
"Toggle",
"CSS",
"class",
"on",
"an",
"element",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/dom-class-list/index.js#L98-L110 |
44,910 | WISEPLAT/solc-js | wrapper.js | function (versionString, cb) {
var mem = new MemoryStream(null, {readable: false});
var url = 'https://wiseplat.github.io/solc-bin/bin/soljson-' + versionString + '.js';
https.get(url, function (response) {
if (response.statusCode !== 200) {
cb(new Error('Error retrieving binary: ' + response.statusMessage));
} else {
response.pipe(mem);
response.on('end', function () {
cb(null, setupMethods(requireFromString(mem.toString(), 'soljson-' + versionString + '.js')));
});
}
}).on('error', function (error) {
cb(error);
});
} | javascript | function (versionString, cb) {
var mem = new MemoryStream(null, {readable: false});
var url = 'https://wiseplat.github.io/solc-bin/bin/soljson-' + versionString + '.js';
https.get(url, function (response) {
if (response.statusCode !== 200) {
cb(new Error('Error retrieving binary: ' + response.statusMessage));
} else {
response.pipe(mem);
response.on('end', function () {
cb(null, setupMethods(requireFromString(mem.toString(), 'soljson-' + versionString + '.js')));
});
}
}).on('error', function (error) {
cb(error);
});
} | [
"function",
"(",
"versionString",
",",
"cb",
")",
"{",
"var",
"mem",
"=",
"new",
"MemoryStream",
"(",
"null",
",",
"{",
"readable",
":",
"false",
"}",
")",
";",
"var",
"url",
"=",
"'https://wiseplat.github.io/solc-bin/bin/soljson-'",
"+",
"versionString",
"+",
"'.js'",
";",
"https",
".",
"get",
"(",
"url",
",",
"function",
"(",
"response",
")",
"{",
"if",
"(",
"response",
".",
"statusCode",
"!==",
"200",
")",
"{",
"cb",
"(",
"new",
"Error",
"(",
"'Error retrieving binary: '",
"+",
"response",
".",
"statusMessage",
")",
")",
";",
"}",
"else",
"{",
"response",
".",
"pipe",
"(",
"mem",
")",
";",
"response",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"cb",
"(",
"null",
",",
"setupMethods",
"(",
"requireFromString",
"(",
"mem",
".",
"toString",
"(",
")",
",",
"'soljson-'",
"+",
"versionString",
"+",
"'.js'",
")",
")",
")",
";",
"}",
")",
";",
"}",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"error",
")",
"{",
"cb",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
]
| Loads the compiler of the given version from the github repository instead of from the local filesystem. | [
"Loads",
"the",
"compiler",
"of",
"the",
"given",
"version",
"from",
"the",
"github",
"repository",
"instead",
"of",
"from",
"the",
"local",
"filesystem",
"."
]
| edabdd02fb0a9385851b92fcf10dee0b8af8e766 | https://github.com/WISEPLAT/solc-js/blob/edabdd02fb0a9385851b92fcf10dee0b8af8e766/wrapper.js#L179-L194 |
|
44,911 | Rafflecopter/deetoo | index.js | function($done) {
function procType(kv, $_done) {
var jobType=kv[0], func=kv[1]
JOBS.process(jobType, func._concurrent, func)
$_done()
}
// TODO: wouldn't need to do this if async.forEach() took an object
var _procs = _.zip(_.keys(__processors), _.values(__processors))
async.forEach(_procs, procType, function(err) {
if (err) return $done(err);
__running.process = true
$done()
})
} | javascript | function($done) {
function procType(kv, $_done) {
var jobType=kv[0], func=kv[1]
JOBS.process(jobType, func._concurrent, func)
$_done()
}
// TODO: wouldn't need to do this if async.forEach() took an object
var _procs = _.zip(_.keys(__processors), _.values(__processors))
async.forEach(_procs, procType, function(err) {
if (err) return $done(err);
__running.process = true
$done()
})
} | [
"function",
"(",
"$done",
")",
"{",
"function",
"procType",
"(",
"kv",
",",
"$_done",
")",
"{",
"var",
"jobType",
"=",
"kv",
"[",
"0",
"]",
",",
"func",
"=",
"kv",
"[",
"1",
"]",
"JOBS",
".",
"process",
"(",
"jobType",
",",
"func",
".",
"_concurrent",
",",
"func",
")",
"$_done",
"(",
")",
"}",
"// TODO: wouldn't need to do this if async.forEach() took an object",
"var",
"_procs",
"=",
"_",
".",
"zip",
"(",
"_",
".",
"keys",
"(",
"__processors",
")",
",",
"_",
".",
"values",
"(",
"__processors",
")",
")",
"async",
".",
"forEach",
"(",
"_procs",
",",
"procType",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"$done",
"(",
"err",
")",
";",
"__running",
".",
"process",
"=",
"true",
"$done",
"(",
")",
"}",
")",
"}"
]
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~ Util Functions | [
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",
"~~",
"Util",
"Functions"
]
| 4d7932efeab35e01fa3a584b6c1253b21f0c4515 | https://github.com/Rafflecopter/deetoo/blob/4d7932efeab35e01fa3a584b6c1253b21f0c4515/index.js#L55-L70 |
|
44,912 | Rafflecopter/deetoo | index.js | function(config) {
INIT(config)
this.__init__()
this.log = LOG
this.jobs = JOBS
MEM = new MemChecker(this, CONF.memChecker)
this._ = {
www: WWW
,redis: JOBS._rawQueue.client
}
} | javascript | function(config) {
INIT(config)
this.__init__()
this.log = LOG
this.jobs = JOBS
MEM = new MemChecker(this, CONF.memChecker)
this._ = {
www: WWW
,redis: JOBS._rawQueue.client
}
} | [
"function",
"(",
"config",
")",
"{",
"INIT",
"(",
"config",
")",
"this",
".",
"__init__",
"(",
")",
"this",
".",
"log",
"=",
"LOG",
"this",
".",
"jobs",
"=",
"JOBS",
"MEM",
"=",
"new",
"MemChecker",
"(",
"this",
",",
"CONF",
".",
"memChecker",
")",
"this",
".",
"_",
"=",
"{",
"www",
":",
"WWW",
",",
"redis",
":",
"JOBS",
".",
"_rawQueue",
".",
"client",
"}",
"}"
]
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~ Worker | [
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",
"~~",
"Worker"
]
| 4d7932efeab35e01fa3a584b6c1253b21f0c4515 | https://github.com/Rafflecopter/deetoo/blob/4d7932efeab35e01fa3a584b6c1253b21f0c4515/index.js#L123-L136 |
|
44,913 | berkeleybop/class-expression | lib/class_expression.js | function(in_type){
this._is_a = 'class_expression';
var anchor = this;
///
/// Initialize.
///
// in_type is always a JSON object, trivial catch of attempt to
// use just a string as a class identifier.
if( in_type ){
if( what_is(in_type) === 'class_expression' ){
// Unfold and re-parse (takes some properties of new
// host).
in_type = in_type.structure();
}else if( what_is(in_type) === 'object' ){
// Fine as it is.
}else if( what_is(in_type) === 'string' ){
// Convert to a safe representation.
in_type = {
'type': 'class',
'id': in_type,
'label': in_type
};
}
}
// Every single one is a precious snowflake (which is necessary
// for managing some of the aspects of the UI for some use cases).
this._id = bbop.uuid();
// Derived property defaults.
this._type = null;
this._category = 'unknown';
this._class_id = null;
this._class_label = null;
this._property_id = null;
this._property_label = null;
// Recursive elements.
this._frame = [];
//
this._raw_type = in_type;
if( in_type ){
anchor.parse(in_type);
}
} | javascript | function(in_type){
this._is_a = 'class_expression';
var anchor = this;
///
/// Initialize.
///
// in_type is always a JSON object, trivial catch of attempt to
// use just a string as a class identifier.
if( in_type ){
if( what_is(in_type) === 'class_expression' ){
// Unfold and re-parse (takes some properties of new
// host).
in_type = in_type.structure();
}else if( what_is(in_type) === 'object' ){
// Fine as it is.
}else if( what_is(in_type) === 'string' ){
// Convert to a safe representation.
in_type = {
'type': 'class',
'id': in_type,
'label': in_type
};
}
}
// Every single one is a precious snowflake (which is necessary
// for managing some of the aspects of the UI for some use cases).
this._id = bbop.uuid();
// Derived property defaults.
this._type = null;
this._category = 'unknown';
this._class_id = null;
this._class_label = null;
this._property_id = null;
this._property_label = null;
// Recursive elements.
this._frame = [];
//
this._raw_type = in_type;
if( in_type ){
anchor.parse(in_type);
}
} | [
"function",
"(",
"in_type",
")",
"{",
"this",
".",
"_is_a",
"=",
"'class_expression'",
";",
"var",
"anchor",
"=",
"this",
";",
"///",
"/// Initialize.",
"///",
"// in_type is always a JSON object, trivial catch of attempt to",
"// use just a string as a class identifier.",
"if",
"(",
"in_type",
")",
"{",
"if",
"(",
"what_is",
"(",
"in_type",
")",
"===",
"'class_expression'",
")",
"{",
"// Unfold and re-parse (takes some properties of new",
"// host).",
"in_type",
"=",
"in_type",
".",
"structure",
"(",
")",
";",
"}",
"else",
"if",
"(",
"what_is",
"(",
"in_type",
")",
"===",
"'object'",
")",
"{",
"// Fine as it is.",
"}",
"else",
"if",
"(",
"what_is",
"(",
"in_type",
")",
"===",
"'string'",
")",
"{",
"// Convert to a safe representation.",
"in_type",
"=",
"{",
"'type'",
":",
"'class'",
",",
"'id'",
":",
"in_type",
",",
"'label'",
":",
"in_type",
"}",
";",
"}",
"}",
"// Every single one is a precious snowflake (which is necessary",
"// for managing some of the aspects of the UI for some use cases).",
"this",
".",
"_id",
"=",
"bbop",
".",
"uuid",
"(",
")",
";",
"// Derived property defaults.",
"this",
".",
"_type",
"=",
"null",
";",
"this",
".",
"_category",
"=",
"'unknown'",
";",
"this",
".",
"_class_id",
"=",
"null",
";",
"this",
".",
"_class_label",
"=",
"null",
";",
"this",
".",
"_property_id",
"=",
"null",
";",
"this",
".",
"_property_label",
"=",
"null",
";",
"// Recursive elements.",
"this",
".",
"_frame",
"=",
"[",
"]",
";",
"// ",
"this",
".",
"_raw_type",
"=",
"in_type",
";",
"if",
"(",
"in_type",
")",
"{",
"anchor",
".",
"parse",
"(",
"in_type",
")",
";",
"}",
"}"
]
| Core constructor.
The argument "in_type" may be:
- a class id (string)
- a JSON blob as described from Minerva
- another <class_expression>
- null (user will load or interactively create one)
@constructor
@param {String|Object|class_expression|null} - the raw type description (see above) | [
"Core",
"constructor",
"."
]
| 47dc5dffe8aedd1c1be92f223715c27c7d67fa76 | https://github.com/berkeleybop/class-expression/blob/47dc5dffe8aedd1c1be92f223715c27c7d67fa76/lib/class_expression.js#L44-L91 |
|
44,914 | berkeleybop/class-expression | lib/class_expression.js | _class_labeler | function _class_labeler(ce){
var ret = ce.class_label();
// Optional ID.
var cid = ce.class_id();
if( cid && cid !== ret ){
ret = '[' + cid + '] ' + ret;
}
return ret;
} | javascript | function _class_labeler(ce){
var ret = ce.class_label();
// Optional ID.
var cid = ce.class_id();
if( cid && cid !== ret ){
ret = '[' + cid + '] ' + ret;
}
return ret;
} | [
"function",
"_class_labeler",
"(",
"ce",
")",
"{",
"var",
"ret",
"=",
"ce",
".",
"class_label",
"(",
")",
";",
"// Optional ID.",
"var",
"cid",
"=",
"ce",
".",
"class_id",
"(",
")",
";",
"if",
"(",
"cid",
"&&",
"cid",
"!==",
"ret",
")",
"{",
"ret",
"=",
"'['",
"+",
"cid",
"+",
"'] '",
"+",
"ret",
";",
"}",
"return",
"ret",
";",
"}"
]
| Class label is main, but prepend class ID if available and different. | [
"Class",
"label",
"is",
"main",
"but",
"prepend",
"class",
"ID",
"if",
"available",
"and",
"different",
"."
]
| 47dc5dffe8aedd1c1be92f223715c27c7d67fa76 | https://github.com/berkeleybop/class-expression/blob/47dc5dffe8aedd1c1be92f223715c27c7d67fa76/lib/class_expression.js#L584-L592 |
44,915 | chapmanu/hb | lib/adapter.js | function(config) {
this._config = this._defaultConfig();
if (!config) return true;
var datastore;
switch(config.adapter) {
case 'disk':
datastore = this._adapters.disk.connection();
break;
case 'redis':
datastore = this._adapters.redis.connection(config.redis);
break;
case 'memory':
default:
return true; // Memory adapter by default
}
// Set connection
this._config.connections.datastore = datastore;
return true;
} | javascript | function(config) {
this._config = this._defaultConfig();
if (!config) return true;
var datastore;
switch(config.adapter) {
case 'disk':
datastore = this._adapters.disk.connection();
break;
case 'redis':
datastore = this._adapters.redis.connection(config.redis);
break;
case 'memory':
default:
return true; // Memory adapter by default
}
// Set connection
this._config.connections.datastore = datastore;
return true;
} | [
"function",
"(",
"config",
")",
"{",
"this",
".",
"_config",
"=",
"this",
".",
"_defaultConfig",
"(",
")",
";",
"if",
"(",
"!",
"config",
")",
"return",
"true",
";",
"var",
"datastore",
";",
"switch",
"(",
"config",
".",
"adapter",
")",
"{",
"case",
"'disk'",
":",
"datastore",
"=",
"this",
".",
"_adapters",
".",
"disk",
".",
"connection",
"(",
")",
";",
"break",
";",
"case",
"'redis'",
":",
"datastore",
"=",
"this",
".",
"_adapters",
".",
"redis",
".",
"connection",
"(",
"config",
".",
"redis",
")",
";",
"break",
";",
"case",
"'memory'",
":",
"default",
":",
"return",
"true",
";",
"// Memory adapter by default",
"}",
"// Set connection",
"this",
".",
"_config",
".",
"connections",
".",
"datastore",
"=",
"datastore",
";",
"return",
"true",
";",
"}"
]
| Configure adapter connection
@param {object} config - Adapter configuration | [
"Configure",
"adapter",
"connection"
]
| 5edd8de89c7c5fdffc3df0c627513889220f7d51 | https://github.com/chapmanu/hb/blob/5edd8de89c7c5fdffc3df0c627513889220f7d51/lib/adapter.js#L39-L62 |
|
44,916 | chapmanu/hb | lib/adapter.js | function(cb) {
this._loadCollections();
// Start Waterline
var self = this;
this._waterline.initialize(self.config, function(err, waterline) {
if(err) throw err;
hb.addModel('Account', waterline.collections['accounts-'+hb.env]);
hb.addModel('Keyword', waterline.collections['keywords-'+hb.env]);
cb();
});
} | javascript | function(cb) {
this._loadCollections();
// Start Waterline
var self = this;
this._waterline.initialize(self.config, function(err, waterline) {
if(err) throw err;
hb.addModel('Account', waterline.collections['accounts-'+hb.env]);
hb.addModel('Keyword', waterline.collections['keywords-'+hb.env]);
cb();
});
} | [
"function",
"(",
"cb",
")",
"{",
"this",
".",
"_loadCollections",
"(",
")",
";",
"// Start Waterline",
"var",
"self",
"=",
"this",
";",
"this",
".",
"_waterline",
".",
"initialize",
"(",
"self",
".",
"config",
",",
"function",
"(",
"err",
",",
"waterline",
")",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
";",
"hb",
".",
"addModel",
"(",
"'Account'",
",",
"waterline",
".",
"collections",
"[",
"'accounts-'",
"+",
"hb",
".",
"env",
"]",
")",
";",
"hb",
".",
"addModel",
"(",
"'Keyword'",
",",
"waterline",
".",
"collections",
"[",
"'keywords-'",
"+",
"hb",
".",
"env",
"]",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Initialize the connection | [
"Initialize",
"the",
"connection"
]
| 5edd8de89c7c5fdffc3df0c627513889220f7d51 | https://github.com/chapmanu/hb/blob/5edd8de89c7c5fdffc3df0c627513889220f7d51/lib/adapter.js#L68-L81 |
|
44,917 | bjarneo/mini-template-engine | src/mini-template-engine.js | miniTemplateEngine | function miniTemplateEngine(str, props, callback) {
var isCallback = false,
errorString = 'The first parameter must be a string';
if (callback && isFunction(callback)) {
isCallback = true;
}
if (!str || !isString(str)) {
if (isCallback) {
callback(null, errorString);
} else {
throw new Error(errorString);
}
}
if (!props || !isObject(props)) {
props = {};
}
if (isCallback) {
setTimeout(function() {
return callback(
new TemplateBuilder(str, props)
.getRenderedTemplate()
);
}, 1);
} else {
return new TemplateBuilder(str, props)
.getRenderedTemplate();
}
} | javascript | function miniTemplateEngine(str, props, callback) {
var isCallback = false,
errorString = 'The first parameter must be a string';
if (callback && isFunction(callback)) {
isCallback = true;
}
if (!str || !isString(str)) {
if (isCallback) {
callback(null, errorString);
} else {
throw new Error(errorString);
}
}
if (!props || !isObject(props)) {
props = {};
}
if (isCallback) {
setTimeout(function() {
return callback(
new TemplateBuilder(str, props)
.getRenderedTemplate()
);
}, 1);
} else {
return new TemplateBuilder(str, props)
.getRenderedTemplate();
}
} | [
"function",
"miniTemplateEngine",
"(",
"str",
",",
"props",
",",
"callback",
")",
"{",
"var",
"isCallback",
"=",
"false",
",",
"errorString",
"=",
"'The first parameter must be a string'",
";",
"if",
"(",
"callback",
"&&",
"isFunction",
"(",
"callback",
")",
")",
"{",
"isCallback",
"=",
"true",
";",
"}",
"if",
"(",
"!",
"str",
"||",
"!",
"isString",
"(",
"str",
")",
")",
"{",
"if",
"(",
"isCallback",
")",
"{",
"callback",
"(",
"null",
",",
"errorString",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"errorString",
")",
";",
"}",
"}",
"if",
"(",
"!",
"props",
"||",
"!",
"isObject",
"(",
"props",
")",
")",
"{",
"props",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"isCallback",
")",
"{",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"return",
"callback",
"(",
"new",
"TemplateBuilder",
"(",
"str",
",",
"props",
")",
".",
"getRenderedTemplate",
"(",
")",
")",
";",
"}",
",",
"1",
")",
";",
"}",
"else",
"{",
"return",
"new",
"TemplateBuilder",
"(",
"str",
",",
"props",
")",
".",
"getRenderedTemplate",
"(",
")",
";",
"}",
"}"
]
| This is a small easy template engine.
It just replaces variable placeholders with objects passed to the function.
@param {string} the string with placeholders
@param {object} the properties to replace the placeholders
@throws {Error} Throws an error if the first parameter is not a string
@returns {string} | [
"This",
"is",
"a",
"small",
"easy",
"template",
"engine",
".",
"It",
"just",
"replaces",
"variable",
"placeholders",
"with",
"objects",
"passed",
"to",
"the",
"function",
"."
]
| 22a0d71205cf04d5edb9d96cb5d4725530ef0c63 | https://github.com/bjarneo/mini-template-engine/blob/22a0d71205cf04d5edb9d96cb5d4725530ef0c63/src/mini-template-engine.js#L17-L48 |
44,918 | odogono/elsinore-js | src/query/dsl.js | rpnToTree | function rpnToTree(values) {
let ii, len, op, stack, slice, count;
stack = [];
// result = [];
for (ii = 0, len = values.length; ii < len; ii++) {
op = values[ii];
if (op === LEFT_PAREN) {
// cut out this sub and convert it to a tree
slice = findMatchingRightParam(values, ii);
if (!slice || slice.length === 0) {
throw new Error('mismatch parentheses');
}
ii += slice.length + 1;
// evaluate this sub command before pushing it to the stack
slice = rpnToTree(slice);
stack.push(slice);
} else {
if (Array.isArray(op)) {
stack.push(op);
} else {
// figure out how many arguments to take from the stack
count = argCount(op);
slice = stack.splice(stack.length - count, count);
if (Array.isArray(slice) && slice.length === 1) {
slice = arrayFlatten(slice, true);
}
// TODO: ugh, occasionally args will get flattened too much
if (slice[0] === VALUE) {
// note only happens with ALIAS_GET
// log.debug('overly flat ' + JSON.stringify([op].concat(slice)));
slice = [slice];
}
stack.push([op].concat(slice));
}
}
}
return stack;
} | javascript | function rpnToTree(values) {
let ii, len, op, stack, slice, count;
stack = [];
// result = [];
for (ii = 0, len = values.length; ii < len; ii++) {
op = values[ii];
if (op === LEFT_PAREN) {
// cut out this sub and convert it to a tree
slice = findMatchingRightParam(values, ii);
if (!slice || slice.length === 0) {
throw new Error('mismatch parentheses');
}
ii += slice.length + 1;
// evaluate this sub command before pushing it to the stack
slice = rpnToTree(slice);
stack.push(slice);
} else {
if (Array.isArray(op)) {
stack.push(op);
} else {
// figure out how many arguments to take from the stack
count = argCount(op);
slice = stack.splice(stack.length - count, count);
if (Array.isArray(slice) && slice.length === 1) {
slice = arrayFlatten(slice, true);
}
// TODO: ugh, occasionally args will get flattened too much
if (slice[0] === VALUE) {
// note only happens with ALIAS_GET
// log.debug('overly flat ' + JSON.stringify([op].concat(slice)));
slice = [slice];
}
stack.push([op].concat(slice));
}
}
}
return stack;
} | [
"function",
"rpnToTree",
"(",
"values",
")",
"{",
"let",
"ii",
",",
"len",
",",
"op",
",",
"stack",
",",
"slice",
",",
"count",
";",
"stack",
"=",
"[",
"]",
";",
"// result = [];",
"for",
"(",
"ii",
"=",
"0",
",",
"len",
"=",
"values",
".",
"length",
";",
"ii",
"<",
"len",
";",
"ii",
"++",
")",
"{",
"op",
"=",
"values",
"[",
"ii",
"]",
";",
"if",
"(",
"op",
"===",
"LEFT_PAREN",
")",
"{",
"// cut out this sub and convert it to a tree",
"slice",
"=",
"findMatchingRightParam",
"(",
"values",
",",
"ii",
")",
";",
"if",
"(",
"!",
"slice",
"||",
"slice",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'mismatch parentheses'",
")",
";",
"}",
"ii",
"+=",
"slice",
".",
"length",
"+",
"1",
";",
"// evaluate this sub command before pushing it to the stack",
"slice",
"=",
"rpnToTree",
"(",
"slice",
")",
";",
"stack",
".",
"push",
"(",
"slice",
")",
";",
"}",
"else",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"op",
")",
")",
"{",
"stack",
".",
"push",
"(",
"op",
")",
";",
"}",
"else",
"{",
"// figure out how many arguments to take from the stack",
"count",
"=",
"argCount",
"(",
"op",
")",
";",
"slice",
"=",
"stack",
".",
"splice",
"(",
"stack",
".",
"length",
"-",
"count",
",",
"count",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"slice",
")",
"&&",
"slice",
".",
"length",
"===",
"1",
")",
"{",
"slice",
"=",
"arrayFlatten",
"(",
"slice",
",",
"true",
")",
";",
"}",
"// TODO: ugh, occasionally args will get flattened too much",
"if",
"(",
"slice",
"[",
"0",
"]",
"===",
"VALUE",
")",
"{",
"// note only happens with ALIAS_GET",
"// log.debug('overly flat ' + JSON.stringify([op].concat(slice)));",
"slice",
"=",
"[",
"slice",
"]",
";",
"}",
"stack",
".",
"push",
"(",
"[",
"op",
"]",
".",
"concat",
"(",
"slice",
")",
")",
";",
"}",
"}",
"}",
"return",
"stack",
";",
"}"
]
| Converts an RPN expression into an AST | [
"Converts",
"an",
"RPN",
"expression",
"into",
"an",
"AST"
]
| 1ecce67ad0022646419a740def029b1ba92dd558 | https://github.com/odogono/elsinore-js/blob/1ecce67ad0022646419a740def029b1ba92dd558/src/query/dsl.js#L81-L128 |
44,919 | warehouseai/warehouse-models | lib/common.js | strip | function strip(file) {
file.fingerprint = file.fingerprint.slice(0, -3);
delete file.source;
delete file.sourcemap;
delete file.shrinkwrap;
return file;
} | javascript | function strip(file) {
file.fingerprint = file.fingerprint.slice(0, -3);
delete file.source;
delete file.sourcemap;
delete file.shrinkwrap;
return file;
} | [
"function",
"strip",
"(",
"file",
")",
"{",
"file",
".",
"fingerprint",
"=",
"file",
".",
"fingerprint",
".",
"slice",
"(",
"0",
",",
"-",
"3",
")",
";",
"delete",
"file",
".",
"source",
";",
"delete",
"file",
".",
"sourcemap",
";",
"delete",
"file",
".",
"shrinkwrap",
";",
"return",
"file",
";",
"}"
]
| Cleanup the heavyweight stuff and meta data | [
"Cleanup",
"the",
"heavyweight",
"stuff",
"and",
"meta",
"data"
]
| ee65aa759adc6a7f83f4b02608a4e74fe562aa89 | https://github.com/warehouseai/warehouse-models/blob/ee65aa759adc6a7f83f4b02608a4e74fe562aa89/lib/common.js#L24-L30 |
44,920 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | validateParamsPresent | function validateParamsPresent(expectedKeys, params) {
params = params || {};
var paramKeys = _.keys(params);
return _.first(_.difference(expectedKeys, _.intersection(paramKeys, expectedKeys)));
} | javascript | function validateParamsPresent(expectedKeys, params) {
params = params || {};
var paramKeys = _.keys(params);
return _.first(_.difference(expectedKeys, _.intersection(paramKeys, expectedKeys)));
} | [
"function",
"validateParamsPresent",
"(",
"expectedKeys",
",",
"params",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"var",
"paramKeys",
"=",
"_",
".",
"keys",
"(",
"params",
")",
";",
"return",
"_",
".",
"first",
"(",
"_",
".",
"difference",
"(",
"expectedKeys",
",",
"_",
".",
"intersection",
"(",
"paramKeys",
",",
"expectedKeys",
")",
")",
")",
";",
"}"
]
| Validating Params Have Expected Key Values
@param expectedKeys
@param params
@private | [
"Validating",
"Params",
"Have",
"Expected",
"Key",
"Values"
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L16-L20 |
44,921 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | validateCommonParams | function validateCommonParams(params) {
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: validateCommonParams");
var expectedParams = ["method", "data", "resourcePath", "environment", "domain"];
var missingParam = validateParamsPresent(expectedParams, params);
if (missingParam) {
return missingParam;
}
//The resource Path Is Invalid If It Is An Object
log.logger.debug('ResourcePath :: ', params.resourcePath);
if (_.isObject(params.resourcePath)) {
log.logger.debug('Resource Path Is Object, returning path key !!! ', params.resourcePath);
return params.resourcePath.key;
}
//If it is a file request, the data entry must contain file params.
if (params.fileRequest && params.fileUploadRequest) {
missingParam = validateParamsPresent(["name", "type", "size", "stream"], params.data);
}
return missingParam;
} | javascript | function validateCommonParams(params) {
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: validateCommonParams");
var expectedParams = ["method", "data", "resourcePath", "environment", "domain"];
var missingParam = validateParamsPresent(expectedParams, params);
if (missingParam) {
return missingParam;
}
//The resource Path Is Invalid If It Is An Object
log.logger.debug('ResourcePath :: ', params.resourcePath);
if (_.isObject(params.resourcePath)) {
log.logger.debug('Resource Path Is Object, returning path key !!! ', params.resourcePath);
return params.resourcePath.key;
}
//If it is a file request, the data entry must contain file params.
if (params.fileRequest && params.fileUploadRequest) {
missingParam = validateParamsPresent(["name", "type", "size", "stream"], params.data);
}
return missingParam;
} | [
"function",
"validateCommonParams",
"(",
"params",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"{",
"params",
":",
"params",
"}",
",",
"\"FH-MBAAS-CLIENT: validateCommonParams\"",
")",
";",
"var",
"expectedParams",
"=",
"[",
"\"method\"",
",",
"\"data\"",
",",
"\"resourcePath\"",
",",
"\"environment\"",
",",
"\"domain\"",
"]",
";",
"var",
"missingParam",
"=",
"validateParamsPresent",
"(",
"expectedParams",
",",
"params",
")",
";",
"if",
"(",
"missingParam",
")",
"{",
"return",
"missingParam",
";",
"}",
"//The resource Path Is Invalid If It Is An Object",
"log",
".",
"logger",
".",
"debug",
"(",
"'ResourcePath :: '",
",",
"params",
".",
"resourcePath",
")",
";",
"if",
"(",
"_",
".",
"isObject",
"(",
"params",
".",
"resourcePath",
")",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"'Resource Path Is Object, returning path key !!! '",
",",
"params",
".",
"resourcePath",
")",
";",
"return",
"params",
".",
"resourcePath",
".",
"key",
";",
"}",
"//If it is a file request, the data entry must contain file params.",
"if",
"(",
"params",
".",
"fileRequest",
"&&",
"params",
".",
"fileUploadRequest",
")",
"{",
"missingParam",
"=",
"validateParamsPresent",
"(",
"[",
"\"name\"",
",",
"\"type\"",
",",
"\"size\"",
",",
"\"stream\"",
"]",
",",
"params",
".",
"data",
")",
";",
"}",
"return",
"missingParam",
";",
"}"
]
| Validating Common Params Between Admin and App MbaaS Requests
@param params
@private | [
"Validating",
"Common",
"Params",
"Between",
"Admin",
"and",
"App",
"MbaaS",
"Requests"
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L28-L52 |
44,922 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | validateAppParams | function validateAppParams(params) {
params = params || {};
var expectedAppParams = ["project", "app", "accessKey", "appApiKey", "url"];
var missingParam = validateCommonParams(params);
if (missingParam) {
return new Error("Missing Param " + missingParam);
}
missingParam = validateParamsPresent(expectedAppParams, params);
if (missingParam) {
return new Error("Missing MbaaS Config Param " + missingParam);
}
return undefined;
} | javascript | function validateAppParams(params) {
params = params || {};
var expectedAppParams = ["project", "app", "accessKey", "appApiKey", "url"];
var missingParam = validateCommonParams(params);
if (missingParam) {
return new Error("Missing Param " + missingParam);
}
missingParam = validateParamsPresent(expectedAppParams, params);
if (missingParam) {
return new Error("Missing MbaaS Config Param " + missingParam);
}
return undefined;
} | [
"function",
"validateAppParams",
"(",
"params",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"var",
"expectedAppParams",
"=",
"[",
"\"project\"",
",",
"\"app\"",
",",
"\"accessKey\"",
",",
"\"appApiKey\"",
",",
"\"url\"",
"]",
";",
"var",
"missingParam",
"=",
"validateCommonParams",
"(",
"params",
")",
";",
"if",
"(",
"missingParam",
")",
"{",
"return",
"new",
"Error",
"(",
"\"Missing Param \"",
"+",
"missingParam",
")",
";",
"}",
"missingParam",
"=",
"validateParamsPresent",
"(",
"expectedAppParams",
",",
"params",
")",
";",
"if",
"(",
"missingParam",
")",
"{",
"return",
"new",
"Error",
"(",
"\"Missing MbaaS Config Param \"",
"+",
"missingParam",
")",
";",
"}",
"return",
"undefined",
";",
"}"
]
| App API Requests To An MbaaS Require
@param params
@returns {*}
@private | [
"App",
"API",
"Requests",
"To",
"An",
"MbaaS",
"Require"
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L60-L78 |
44,923 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | validateAdminParams | function validateAdminParams(params) {
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: validateAdminParams");
var missingParam = validateCommonParams(params);
var expectedAdminMbaasConfig = ["url", "username", "password"];
if (missingParam) {
return new Error("Missing Param " + missingParam);
}
missingParam = validateParamsPresent(expectedAdminMbaasConfig, params);
if (missingParam) {
return new Error("Missing MbaaS Config Param " + missingParam);
}
return undefined;
} | javascript | function validateAdminParams(params) {
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: validateAdminParams");
var missingParam = validateCommonParams(params);
var expectedAdminMbaasConfig = ["url", "username", "password"];
if (missingParam) {
return new Error("Missing Param " + missingParam);
}
missingParam = validateParamsPresent(expectedAdminMbaasConfig, params);
if (missingParam) {
return new Error("Missing MbaaS Config Param " + missingParam);
}
return undefined;
} | [
"function",
"validateAdminParams",
"(",
"params",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"{",
"params",
":",
"params",
"}",
",",
"\"FH-MBAAS-CLIENT: validateAdminParams\"",
")",
";",
"var",
"missingParam",
"=",
"validateCommonParams",
"(",
"params",
")",
";",
"var",
"expectedAdminMbaasConfig",
"=",
"[",
"\"url\"",
",",
"\"username\"",
",",
"\"password\"",
"]",
";",
"if",
"(",
"missingParam",
")",
"{",
"return",
"new",
"Error",
"(",
"\"Missing Param \"",
"+",
"missingParam",
")",
";",
"}",
"missingParam",
"=",
"validateParamsPresent",
"(",
"expectedAdminMbaasConfig",
",",
"params",
")",
";",
"if",
"(",
"missingParam",
")",
"{",
"return",
"new",
"Error",
"(",
"\"Missing MbaaS Config Param \"",
"+",
"missingParam",
")",
";",
"}",
"return",
"undefined",
";",
"}"
]
| Administration API Requests To An MbaaS Require The Username And Password Of The MbaaS.
@param params
@returns {*}
@private | [
"Administration",
"API",
"Requests",
"To",
"An",
"MbaaS",
"Require",
"The",
"Username",
"And",
"Password",
"Of",
"The",
"MbaaS",
"."
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L86-L102 |
44,924 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | _buildAdminMbaasParams | function _buildAdminMbaasParams(params) {
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: _buildAdminMbaasParams");
var basePath;
basePath = config.addURIParams(constants.ADMIN_API_PATH, params);
params = params || {};
var method, resourcePath;
method = params.method;
resourcePath = params.resourcePath;
var mbaasUrl = params.__mbaasUrl;
var parsedMbaasUrl = url.parse(mbaasUrl);
parsedMbaasUrl.pathname = basePath + resourcePath;
var adminRequestParams = {
url: parsedMbaasUrl.format(),
method: method,
headers: {
host: parsedMbaasUrl.host,
'x-fh-service-key': params.servicekey
},
fileRequest: params.fileRequest,
fileUploadRequest: params.fileUploadRequest,
data: params.data,
paginate: params.paginate,
envLabel: params._label
};
if (params.username && params.password) {
adminRequestParams.auth = {
user: params.username,
pass: params.password
};
}
log.logger.debug({adminRequestParams: adminRequestParams}, "FH-MBAAS-CLIENT: _buildAdminMbaasParams");
return adminRequestParams;
} | javascript | function _buildAdminMbaasParams(params) {
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: _buildAdminMbaasParams");
var basePath;
basePath = config.addURIParams(constants.ADMIN_API_PATH, params);
params = params || {};
var method, resourcePath;
method = params.method;
resourcePath = params.resourcePath;
var mbaasUrl = params.__mbaasUrl;
var parsedMbaasUrl = url.parse(mbaasUrl);
parsedMbaasUrl.pathname = basePath + resourcePath;
var adminRequestParams = {
url: parsedMbaasUrl.format(),
method: method,
headers: {
host: parsedMbaasUrl.host,
'x-fh-service-key': params.servicekey
},
fileRequest: params.fileRequest,
fileUploadRequest: params.fileUploadRequest,
data: params.data,
paginate: params.paginate,
envLabel: params._label
};
if (params.username && params.password) {
adminRequestParams.auth = {
user: params.username,
pass: params.password
};
}
log.logger.debug({adminRequestParams: adminRequestParams}, "FH-MBAAS-CLIENT: _buildAdminMbaasParams");
return adminRequestParams;
} | [
"function",
"_buildAdminMbaasParams",
"(",
"params",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"{",
"params",
":",
"params",
"}",
",",
"\"FH-MBAAS-CLIENT: _buildAdminMbaasParams\"",
")",
";",
"var",
"basePath",
";",
"basePath",
"=",
"config",
".",
"addURIParams",
"(",
"constants",
".",
"ADMIN_API_PATH",
",",
"params",
")",
";",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"var",
"method",
",",
"resourcePath",
";",
"method",
"=",
"params",
".",
"method",
";",
"resourcePath",
"=",
"params",
".",
"resourcePath",
";",
"var",
"mbaasUrl",
"=",
"params",
".",
"__mbaasUrl",
";",
"var",
"parsedMbaasUrl",
"=",
"url",
".",
"parse",
"(",
"mbaasUrl",
")",
";",
"parsedMbaasUrl",
".",
"pathname",
"=",
"basePath",
"+",
"resourcePath",
";",
"var",
"adminRequestParams",
"=",
"{",
"url",
":",
"parsedMbaasUrl",
".",
"format",
"(",
")",
",",
"method",
":",
"method",
",",
"headers",
":",
"{",
"host",
":",
"parsedMbaasUrl",
".",
"host",
",",
"'x-fh-service-key'",
":",
"params",
".",
"servicekey",
"}",
",",
"fileRequest",
":",
"params",
".",
"fileRequest",
",",
"fileUploadRequest",
":",
"params",
".",
"fileUploadRequest",
",",
"data",
":",
"params",
".",
"data",
",",
"paginate",
":",
"params",
".",
"paginate",
",",
"envLabel",
":",
"params",
".",
"_label",
"}",
";",
"if",
"(",
"params",
".",
"username",
"&&",
"params",
".",
"password",
")",
"{",
"adminRequestParams",
".",
"auth",
"=",
"{",
"user",
":",
"params",
".",
"username",
",",
"pass",
":",
"params",
".",
"password",
"}",
";",
"}",
"log",
".",
"logger",
".",
"debug",
"(",
"{",
"adminRequestParams",
":",
"adminRequestParams",
"}",
",",
"\"FH-MBAAS-CLIENT: _buildAdminMbaasParams\"",
")",
";",
"return",
"adminRequestParams",
";",
"}"
]
| Building Request Params For A Call To Administration APIs In An MbaaS
@param params
@returns {{url: *, json: boolean, method: (method|*|string), auth: {user: *, pass: *}, headers: {host: string}, body: *}}
@private | [
"Building",
"Request",
"Params",
"For",
"A",
"Call",
"To",
"Administration",
"APIs",
"In",
"An",
"MbaaS"
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L110-L149 |
44,925 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | responseHandler | function responseHandler(params, cb) {
return function handleResponse(err, httpResponse, body) {
body = body || "{}";
httpResponse = httpResponse || {};
//The response should be JSON. If it is a string, then the response should be parsed.
if (_.isString(body)) {
try {
body = JSON.parse(body);
} catch (e) {
log.logger.error("FH-MBAAS-CLIENT: Invalid Response Body ", {body: body});
}
}
log.logger.debug("FH-MBAAS-CLIENT: Request Finish ", {
err: err,
httpResponse: httpResponse.statusCode,
body: body
});
// provide defaults
if (httpResponse && httpResponse.statusCode >= 400) {
err = err || {};
err.httpCode = httpResponse.statusCode;
err.message = "Unexpected Status Code " + httpResponse.statusCode;
}
//There is a specific error message if an environment is unreachable
if (httpResponse && httpResponse.statusCode === 503) {
err = {
httpCode: 503,
message: CONSTANTS.ERROR_MESSAGES.ENVIRONMENT_UNREACHABLE.replace('{{ENVLABEL}}', params.envLabel || "")
};
}
// MbaaS unavailable
if (err && err.code !== undefined && (err.code === "ENOTFOUND" || err.code === "ETIMEDOUT")) {
err = {
httpCode: httpResponse.statusCode || 500,
message: "MBaaS environment is not reachable. Please make the environment available or delete it. Environment Label - " + params.envLabel || ""
};
}
if (err) {
cb(err || body || "Unexpected Status Code " + httpResponse.statusCode);
} else {
cb(undefined, body);
}
};
} | javascript | function responseHandler(params, cb) {
return function handleResponse(err, httpResponse, body) {
body = body || "{}";
httpResponse = httpResponse || {};
//The response should be JSON. If it is a string, then the response should be parsed.
if (_.isString(body)) {
try {
body = JSON.parse(body);
} catch (e) {
log.logger.error("FH-MBAAS-CLIENT: Invalid Response Body ", {body: body});
}
}
log.logger.debug("FH-MBAAS-CLIENT: Request Finish ", {
err: err,
httpResponse: httpResponse.statusCode,
body: body
});
// provide defaults
if (httpResponse && httpResponse.statusCode >= 400) {
err = err || {};
err.httpCode = httpResponse.statusCode;
err.message = "Unexpected Status Code " + httpResponse.statusCode;
}
//There is a specific error message if an environment is unreachable
if (httpResponse && httpResponse.statusCode === 503) {
err = {
httpCode: 503,
message: CONSTANTS.ERROR_MESSAGES.ENVIRONMENT_UNREACHABLE.replace('{{ENVLABEL}}', params.envLabel || "")
};
}
// MbaaS unavailable
if (err && err.code !== undefined && (err.code === "ENOTFOUND" || err.code === "ETIMEDOUT")) {
err = {
httpCode: httpResponse.statusCode || 500,
message: "MBaaS environment is not reachable. Please make the environment available or delete it. Environment Label - " + params.envLabel || ""
};
}
if (err) {
cb(err || body || "Unexpected Status Code " + httpResponse.statusCode);
} else {
cb(undefined, body);
}
};
} | [
"function",
"responseHandler",
"(",
"params",
",",
"cb",
")",
"{",
"return",
"function",
"handleResponse",
"(",
"err",
",",
"httpResponse",
",",
"body",
")",
"{",
"body",
"=",
"body",
"||",
"\"{}\"",
";",
"httpResponse",
"=",
"httpResponse",
"||",
"{",
"}",
";",
"//The response should be JSON. If it is a string, then the response should be parsed.",
"if",
"(",
"_",
".",
"isString",
"(",
"body",
")",
")",
"{",
"try",
"{",
"body",
"=",
"JSON",
".",
"parse",
"(",
"body",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"log",
".",
"logger",
".",
"error",
"(",
"\"FH-MBAAS-CLIENT: Invalid Response Body \"",
",",
"{",
"body",
":",
"body",
"}",
")",
";",
"}",
"}",
"log",
".",
"logger",
".",
"debug",
"(",
"\"FH-MBAAS-CLIENT: Request Finish \"",
",",
"{",
"err",
":",
"err",
",",
"httpResponse",
":",
"httpResponse",
".",
"statusCode",
",",
"body",
":",
"body",
"}",
")",
";",
"// provide defaults",
"if",
"(",
"httpResponse",
"&&",
"httpResponse",
".",
"statusCode",
">=",
"400",
")",
"{",
"err",
"=",
"err",
"||",
"{",
"}",
";",
"err",
".",
"httpCode",
"=",
"httpResponse",
".",
"statusCode",
";",
"err",
".",
"message",
"=",
"\"Unexpected Status Code \"",
"+",
"httpResponse",
".",
"statusCode",
";",
"}",
"//There is a specific error message if an environment is unreachable",
"if",
"(",
"httpResponse",
"&&",
"httpResponse",
".",
"statusCode",
"===",
"503",
")",
"{",
"err",
"=",
"{",
"httpCode",
":",
"503",
",",
"message",
":",
"CONSTANTS",
".",
"ERROR_MESSAGES",
".",
"ENVIRONMENT_UNREACHABLE",
".",
"replace",
"(",
"'{{ENVLABEL}}'",
",",
"params",
".",
"envLabel",
"||",
"\"\"",
")",
"}",
";",
"}",
"// MbaaS unavailable",
"if",
"(",
"err",
"&&",
"err",
".",
"code",
"!==",
"undefined",
"&&",
"(",
"err",
".",
"code",
"===",
"\"ENOTFOUND\"",
"||",
"err",
".",
"code",
"===",
"\"ETIMEDOUT\"",
")",
")",
"{",
"err",
"=",
"{",
"httpCode",
":",
"httpResponse",
".",
"statusCode",
"||",
"500",
",",
"message",
":",
"\"MBaaS environment is not reachable. Please make the environment available or delete it. Environment Label - \"",
"+",
"params",
".",
"envLabel",
"||",
"\"\"",
"}",
";",
"}",
"if",
"(",
"err",
")",
"{",
"cb",
"(",
"err",
"||",
"body",
"||",
"\"Unexpected Status Code \"",
"+",
"httpResponse",
".",
"statusCode",
")",
";",
"}",
"else",
"{",
"cb",
"(",
"undefined",
",",
"body",
")",
";",
"}",
"}",
";",
"}"
]
| Create a response handler from a request to the MBaaS.
@param params
@param cb
@returns {handleResponse} | [
"Create",
"a",
"response",
"handler",
"from",
"a",
"request",
"to",
"the",
"MBaaS",
"."
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L158-L208 |
44,926 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | doFHMbaaSRequest | function doFHMbaaSRequest(params, cb) {
//Preventing multiple callbacks.
// _.defaults(undefined, ...) === undefined, so we still need to OR with an empty object
params = _.defaults(params || {}, {
headers: {}
});
//Adding pagination parameters if required
params.url = addPaginationUrlParams(params.url, params);
// add request id header to request if present
if (_.isFunction(log.logger.getRequestId)) {
var reqId = log.logger.getRequestId();
if (reqId) {
params.headers[log.logger.requestIdHeader] = reqId;
}
}
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: doFHMbaaSRequest");
var fileData = params.data;
//If it is a file upload request, the file data is assigned differently
if (params.fileRequest && params.fileUploadRequest) {
params.json = false;
} else {
//Normal JSON Request
params.json = true;
//Dont set a body if it is a get request
if (params.method === "GET") {
params.qs = params.data;
} else {
params.body = params.data;
}
}
//The data field is no longer needed
params = _.omit(params, 'data');
//If Mbaas Request Expects To Send/Recieve Files, then return the request value
if (params.fileRequest && params.fileUploadRequest) {
log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest File Upload Request");
var formData = {};
formData[fileData.name] = {
value: fileData.stream,
options: {
filename: fileData.name,
contentType: fileData.type
}
};
return request({
method: params.method,
url: params.url,
auth: params.auth,
headers: params.headers,
formData: formData
}, responseHandler(params, cb));
} else if (params.fileRequest) {
log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest File Download Request");
//File Download Request. Return the readable request stream.
return cb(undefined, request(params));
} else {
//Normal call.
log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest Normal Request");
request(params, responseHandler(params, cb));
}
} | javascript | function doFHMbaaSRequest(params, cb) {
//Preventing multiple callbacks.
// _.defaults(undefined, ...) === undefined, so we still need to OR with an empty object
params = _.defaults(params || {}, {
headers: {}
});
//Adding pagination parameters if required
params.url = addPaginationUrlParams(params.url, params);
// add request id header to request if present
if (_.isFunction(log.logger.getRequestId)) {
var reqId = log.logger.getRequestId();
if (reqId) {
params.headers[log.logger.requestIdHeader] = reqId;
}
}
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: doFHMbaaSRequest");
var fileData = params.data;
//If it is a file upload request, the file data is assigned differently
if (params.fileRequest && params.fileUploadRequest) {
params.json = false;
} else {
//Normal JSON Request
params.json = true;
//Dont set a body if it is a get request
if (params.method === "GET") {
params.qs = params.data;
} else {
params.body = params.data;
}
}
//The data field is no longer needed
params = _.omit(params, 'data');
//If Mbaas Request Expects To Send/Recieve Files, then return the request value
if (params.fileRequest && params.fileUploadRequest) {
log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest File Upload Request");
var formData = {};
formData[fileData.name] = {
value: fileData.stream,
options: {
filename: fileData.name,
contentType: fileData.type
}
};
return request({
method: params.method,
url: params.url,
auth: params.auth,
headers: params.headers,
formData: formData
}, responseHandler(params, cb));
} else if (params.fileRequest) {
log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest File Download Request");
//File Download Request. Return the readable request stream.
return cb(undefined, request(params));
} else {
//Normal call.
log.logger.debug("FH-MBAAS-CLIENT: doFHMbaaSRequest Normal Request");
request(params, responseHandler(params, cb));
}
} | [
"function",
"doFHMbaaSRequest",
"(",
"params",
",",
"cb",
")",
"{",
"//Preventing multiple callbacks.",
"// _.defaults(undefined, ...) === undefined, so we still need to OR with an empty object",
"params",
"=",
"_",
".",
"defaults",
"(",
"params",
"||",
"{",
"}",
",",
"{",
"headers",
":",
"{",
"}",
"}",
")",
";",
"//Adding pagination parameters if required",
"params",
".",
"url",
"=",
"addPaginationUrlParams",
"(",
"params",
".",
"url",
",",
"params",
")",
";",
"// add request id header to request if present",
"if",
"(",
"_",
".",
"isFunction",
"(",
"log",
".",
"logger",
".",
"getRequestId",
")",
")",
"{",
"var",
"reqId",
"=",
"log",
".",
"logger",
".",
"getRequestId",
"(",
")",
";",
"if",
"(",
"reqId",
")",
"{",
"params",
".",
"headers",
"[",
"log",
".",
"logger",
".",
"requestIdHeader",
"]",
"=",
"reqId",
";",
"}",
"}",
"log",
".",
"logger",
".",
"debug",
"(",
"{",
"params",
":",
"params",
"}",
",",
"\"FH-MBAAS-CLIENT: doFHMbaaSRequest\"",
")",
";",
"var",
"fileData",
"=",
"params",
".",
"data",
";",
"//If it is a file upload request, the file data is assigned differently",
"if",
"(",
"params",
".",
"fileRequest",
"&&",
"params",
".",
"fileUploadRequest",
")",
"{",
"params",
".",
"json",
"=",
"false",
";",
"}",
"else",
"{",
"//Normal JSON Request",
"params",
".",
"json",
"=",
"true",
";",
"//Dont set a body if it is a get request",
"if",
"(",
"params",
".",
"method",
"===",
"\"GET\"",
")",
"{",
"params",
".",
"qs",
"=",
"params",
".",
"data",
";",
"}",
"else",
"{",
"params",
".",
"body",
"=",
"params",
".",
"data",
";",
"}",
"}",
"//The data field is no longer needed",
"params",
"=",
"_",
".",
"omit",
"(",
"params",
",",
"'data'",
")",
";",
"//If Mbaas Request Expects To Send/Recieve Files, then return the request value",
"if",
"(",
"params",
".",
"fileRequest",
"&&",
"params",
".",
"fileUploadRequest",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"\"FH-MBAAS-CLIENT: doFHMbaaSRequest File Upload Request\"",
")",
";",
"var",
"formData",
"=",
"{",
"}",
";",
"formData",
"[",
"fileData",
".",
"name",
"]",
"=",
"{",
"value",
":",
"fileData",
".",
"stream",
",",
"options",
":",
"{",
"filename",
":",
"fileData",
".",
"name",
",",
"contentType",
":",
"fileData",
".",
"type",
"}",
"}",
";",
"return",
"request",
"(",
"{",
"method",
":",
"params",
".",
"method",
",",
"url",
":",
"params",
".",
"url",
",",
"auth",
":",
"params",
".",
"auth",
",",
"headers",
":",
"params",
".",
"headers",
",",
"formData",
":",
"formData",
"}",
",",
"responseHandler",
"(",
"params",
",",
"cb",
")",
")",
";",
"}",
"else",
"if",
"(",
"params",
".",
"fileRequest",
")",
"{",
"log",
".",
"logger",
".",
"debug",
"(",
"\"FH-MBAAS-CLIENT: doFHMbaaSRequest File Download Request\"",
")",
";",
"//File Download Request. Return the readable request stream.",
"return",
"cb",
"(",
"undefined",
",",
"request",
"(",
"params",
")",
")",
";",
"}",
"else",
"{",
"//Normal call.",
"log",
".",
"logger",
".",
"debug",
"(",
"\"FH-MBAAS-CLIENT: doFHMbaaSRequest Normal Request\"",
")",
";",
"request",
"(",
"params",
",",
"responseHandler",
"(",
"params",
",",
"cb",
")",
")",
";",
"}",
"}"
]
| Perform A Request To An MbaaS
@private | [
"Perform",
"A",
"Request",
"To",
"An",
"MbaaS"
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L217-L284 |
44,927 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | _buildAppRequestParams | function _buildAppRequestParams(params) {
params = params || {};
var basePath = config.addURIParams(constants.APP_API_PATH, params);
var fullPath = basePath + params.resourcePath;
var mbaasUrl = url.parse(params.url);
mbaasUrl.pathname = fullPath;
var headers = {
'x-fh-env-access-key': params.accessKey,
'x-fh-auth-app': params.appApiKey
};
return {
url: mbaasUrl.format(mbaasUrl),
method: params.method,
headers: headers,
fileRequest: params.fileRequest,
fileUploadRequest: params.fileUploadRequest,
data: params.data,
paginate: params.paginate
};
} | javascript | function _buildAppRequestParams(params) {
params = params || {};
var basePath = config.addURIParams(constants.APP_API_PATH, params);
var fullPath = basePath + params.resourcePath;
var mbaasUrl = url.parse(params.url);
mbaasUrl.pathname = fullPath;
var headers = {
'x-fh-env-access-key': params.accessKey,
'x-fh-auth-app': params.appApiKey
};
return {
url: mbaasUrl.format(mbaasUrl),
method: params.method,
headers: headers,
fileRequest: params.fileRequest,
fileUploadRequest: params.fileUploadRequest,
data: params.data,
paginate: params.paginate
};
} | [
"function",
"_buildAppRequestParams",
"(",
"params",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"var",
"basePath",
"=",
"config",
".",
"addURIParams",
"(",
"constants",
".",
"APP_API_PATH",
",",
"params",
")",
";",
"var",
"fullPath",
"=",
"basePath",
"+",
"params",
".",
"resourcePath",
";",
"var",
"mbaasUrl",
"=",
"url",
".",
"parse",
"(",
"params",
".",
"url",
")",
";",
"mbaasUrl",
".",
"pathname",
"=",
"fullPath",
";",
"var",
"headers",
"=",
"{",
"'x-fh-env-access-key'",
":",
"params",
".",
"accessKey",
",",
"'x-fh-auth-app'",
":",
"params",
".",
"appApiKey",
"}",
";",
"return",
"{",
"url",
":",
"mbaasUrl",
".",
"format",
"(",
"mbaasUrl",
")",
",",
"method",
":",
"params",
".",
"method",
",",
"headers",
":",
"headers",
",",
"fileRequest",
":",
"params",
".",
"fileRequest",
",",
"fileUploadRequest",
":",
"params",
".",
"fileUploadRequest",
",",
"data",
":",
"params",
".",
"data",
",",
"paginate",
":",
"params",
".",
"paginate",
"}",
";",
"}"
]
| Building Request Params For An App Request To An Mbaas
@param params
@returns {{url: string, body: *, method: (method|*|string), json: boolean, headers: {fh-app-env-access-key: *}}}
@private | [
"Building",
"Request",
"Params",
"For",
"An",
"App",
"Request",
"To",
"An",
"Mbaas"
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L293-L318 |
44,928 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | adminRequest | function adminRequest(params, cb) {
params = params || {};
var mbaasConf = params[constants.MBAAS_CONF_KEY];
params[constants.MBAAS_CONF_KEY] = undefined;
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: adminRequest ");
var fullParams = _.extend(_.clone(params), mbaasConf);
log.logger.info({
env: params.environment,
domain: fullParams.domain,
mbaasUrl: fullParams.__mbaasUrl
}, "FH-MBAAS-CLIENT.adminRequest - calling mbaas:");
var invalidParamError = validateAdminParams(fullParams);
if (invalidParamError) {
return cb(invalidParamError);
}
fullParams.data = fullParams.data || {};
fullParams.data.notStats = params.notStats;
fullParams = _buildAdminMbaasParams(fullParams);
log.logger.debug({fullParams: fullParams}, "FH-MBAAS-CLIENT: adminRequest ");
return doFHMbaaSRequest(fullParams, cb);
} | javascript | function adminRequest(params, cb) {
params = params || {};
var mbaasConf = params[constants.MBAAS_CONF_KEY];
params[constants.MBAAS_CONF_KEY] = undefined;
log.logger.debug({params: params}, "FH-MBAAS-CLIENT: adminRequest ");
var fullParams = _.extend(_.clone(params), mbaasConf);
log.logger.info({
env: params.environment,
domain: fullParams.domain,
mbaasUrl: fullParams.__mbaasUrl
}, "FH-MBAAS-CLIENT.adminRequest - calling mbaas:");
var invalidParamError = validateAdminParams(fullParams);
if (invalidParamError) {
return cb(invalidParamError);
}
fullParams.data = fullParams.data || {};
fullParams.data.notStats = params.notStats;
fullParams = _buildAdminMbaasParams(fullParams);
log.logger.debug({fullParams: fullParams}, "FH-MBAAS-CLIENT: adminRequest ");
return doFHMbaaSRequest(fullParams, cb);
} | [
"function",
"adminRequest",
"(",
"params",
",",
"cb",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"var",
"mbaasConf",
"=",
"params",
"[",
"constants",
".",
"MBAAS_CONF_KEY",
"]",
";",
"params",
"[",
"constants",
".",
"MBAAS_CONF_KEY",
"]",
"=",
"undefined",
";",
"log",
".",
"logger",
".",
"debug",
"(",
"{",
"params",
":",
"params",
"}",
",",
"\"FH-MBAAS-CLIENT: adminRequest \"",
")",
";",
"var",
"fullParams",
"=",
"_",
".",
"extend",
"(",
"_",
".",
"clone",
"(",
"params",
")",
",",
"mbaasConf",
")",
";",
"log",
".",
"logger",
".",
"info",
"(",
"{",
"env",
":",
"params",
".",
"environment",
",",
"domain",
":",
"fullParams",
".",
"domain",
",",
"mbaasUrl",
":",
"fullParams",
".",
"__mbaasUrl",
"}",
",",
"\"FH-MBAAS-CLIENT.adminRequest - calling mbaas:\"",
")",
";",
"var",
"invalidParamError",
"=",
"validateAdminParams",
"(",
"fullParams",
")",
";",
"if",
"(",
"invalidParamError",
")",
"{",
"return",
"cb",
"(",
"invalidParamError",
")",
";",
"}",
"fullParams",
".",
"data",
"=",
"fullParams",
".",
"data",
"||",
"{",
"}",
";",
"fullParams",
".",
"data",
".",
"notStats",
"=",
"params",
".",
"notStats",
";",
"fullParams",
"=",
"_buildAdminMbaasParams",
"(",
"fullParams",
")",
";",
"log",
".",
"logger",
".",
"debug",
"(",
"{",
"fullParams",
":",
"fullParams",
"}",
",",
"\"FH-MBAAS-CLIENT: adminRequest \"",
")",
";",
"return",
"doFHMbaaSRequest",
"(",
"fullParams",
",",
"cb",
")",
";",
"}"
]
| Performing A Request Against The Admin MBaaS API
@param params
@param cb | [
"Performing",
"A",
"Request",
"Against",
"The",
"Admin",
"MBaaS",
"API"
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L326-L350 |
44,929 | feedhenry/fh-mbaas-client | lib/mbaasRequest/mbaasRequest.js | appRequest | function appRequest(params, cb) {
params = params || {};
var mbaasConf = params[constants.MBAAS_CONF_KEY];
params[constants.MBAAS_CONF_KEY] = undefined;
//Adding Mbaas Config Params
var fullParams = _.extend(_.clone(params), mbaasConf);
var invalidParamError = validateAppParams(fullParams);
if (invalidParamError) {
return cb(invalidParamError);
}
fullParams = _buildAppRequestParams(fullParams);
return doFHMbaaSRequest(fullParams, cb);
} | javascript | function appRequest(params, cb) {
params = params || {};
var mbaasConf = params[constants.MBAAS_CONF_KEY];
params[constants.MBAAS_CONF_KEY] = undefined;
//Adding Mbaas Config Params
var fullParams = _.extend(_.clone(params), mbaasConf);
var invalidParamError = validateAppParams(fullParams);
if (invalidParamError) {
return cb(invalidParamError);
}
fullParams = _buildAppRequestParams(fullParams);
return doFHMbaaSRequest(fullParams, cb);
} | [
"function",
"appRequest",
"(",
"params",
",",
"cb",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"}",
";",
"var",
"mbaasConf",
"=",
"params",
"[",
"constants",
".",
"MBAAS_CONF_KEY",
"]",
";",
"params",
"[",
"constants",
".",
"MBAAS_CONF_KEY",
"]",
"=",
"undefined",
";",
"//Adding Mbaas Config Params",
"var",
"fullParams",
"=",
"_",
".",
"extend",
"(",
"_",
".",
"clone",
"(",
"params",
")",
",",
"mbaasConf",
")",
";",
"var",
"invalidParamError",
"=",
"validateAppParams",
"(",
"fullParams",
")",
";",
"if",
"(",
"invalidParamError",
")",
"{",
"return",
"cb",
"(",
"invalidParamError",
")",
";",
"}",
"fullParams",
"=",
"_buildAppRequestParams",
"(",
"fullParams",
")",
";",
"return",
"doFHMbaaSRequest",
"(",
"fullParams",
",",
"cb",
")",
";",
"}"
]
| Performing A Request Against The App MBaaS API
@param params
@param cb | [
"Performing",
"A",
"Request",
"Against",
"The",
"App",
"MBaaS",
"API"
]
| 2d5a9cbb32e1b2464d71ffa18513358fea388859 | https://github.com/feedhenry/fh-mbaas-client/blob/2d5a9cbb32e1b2464d71ffa18513358fea388859/lib/mbaasRequest/mbaasRequest.js#L359-L375 |
44,930 | node-ffi-napi/ref-union-di | lib/union.js | Union | function Union () {
debug('defining new union "type"')
function UnionType (arg, data) {
if (!(this instanceof UnionType)) {
return new UnionType(arg, data)
}
debug('creating new union instance')
var store
if (Buffer.isBuffer(arg)) {
debug('using passed-in Buffer instance to back the union', arg)
assert(arg.length >= UnionType.size, 'Buffer instance must be at least '
+ UnionType.size + ' bytes to back this untion type')
store = arg
arg = data
} else {
debug('creating new Buffer instance to back the union (size: %d)', UnionType.size)
store = new Buffer(UnionType.size)
}
// set the backing Buffer store
store.type = UnionType
this['ref.buffer'] = store
// initialise the union with values supplied
if (arg) {
//TODO: Sanity check - e.g. (Object.keys(arg).length == 1)
for (var key in arg) {
// hopefully hit the union setters
this[key] = arg[key]
}
}
UnionType._instanceCreated = true
}
// make instances inherit from `proto`
UnionType.prototype = Object.create(proto, {
constructor: {
value: UnionType
, enumerable: false
, writable: true
, configurable: true
}
})
UnionType.defineProperty = defineProperty
UnionType.toString = toString
UnionType.fields = {}
// comply with ref's "type" interface
UnionType.size = 0
UnionType.alignment = 0
UnionType.indirection = 1
UnionType.get = get
UnionType.set = set
// Read the fields list
var arg = arguments[0]
if (typeof arg === 'object') {
Object.keys(arg).forEach(function (name) {
var type = arg[name];
UnionType.defineProperty(name, type);
})
}
return UnionType
} | javascript | function Union () {
debug('defining new union "type"')
function UnionType (arg, data) {
if (!(this instanceof UnionType)) {
return new UnionType(arg, data)
}
debug('creating new union instance')
var store
if (Buffer.isBuffer(arg)) {
debug('using passed-in Buffer instance to back the union', arg)
assert(arg.length >= UnionType.size, 'Buffer instance must be at least '
+ UnionType.size + ' bytes to back this untion type')
store = arg
arg = data
} else {
debug('creating new Buffer instance to back the union (size: %d)', UnionType.size)
store = new Buffer(UnionType.size)
}
// set the backing Buffer store
store.type = UnionType
this['ref.buffer'] = store
// initialise the union with values supplied
if (arg) {
//TODO: Sanity check - e.g. (Object.keys(arg).length == 1)
for (var key in arg) {
// hopefully hit the union setters
this[key] = arg[key]
}
}
UnionType._instanceCreated = true
}
// make instances inherit from `proto`
UnionType.prototype = Object.create(proto, {
constructor: {
value: UnionType
, enumerable: false
, writable: true
, configurable: true
}
})
UnionType.defineProperty = defineProperty
UnionType.toString = toString
UnionType.fields = {}
// comply with ref's "type" interface
UnionType.size = 0
UnionType.alignment = 0
UnionType.indirection = 1
UnionType.get = get
UnionType.set = set
// Read the fields list
var arg = arguments[0]
if (typeof arg === 'object') {
Object.keys(arg).forEach(function (name) {
var type = arg[name];
UnionType.defineProperty(name, type);
})
}
return UnionType
} | [
"function",
"Union",
"(",
")",
"{",
"debug",
"(",
"'defining new union \"type\"'",
")",
"function",
"UnionType",
"(",
"arg",
",",
"data",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"UnionType",
")",
")",
"{",
"return",
"new",
"UnionType",
"(",
"arg",
",",
"data",
")",
"}",
"debug",
"(",
"'creating new union instance'",
")",
"var",
"store",
"if",
"(",
"Buffer",
".",
"isBuffer",
"(",
"arg",
")",
")",
"{",
"debug",
"(",
"'using passed-in Buffer instance to back the union'",
",",
"arg",
")",
"assert",
"(",
"arg",
".",
"length",
">=",
"UnionType",
".",
"size",
",",
"'Buffer instance must be at least '",
"+",
"UnionType",
".",
"size",
"+",
"' bytes to back this untion type'",
")",
"store",
"=",
"arg",
"arg",
"=",
"data",
"}",
"else",
"{",
"debug",
"(",
"'creating new Buffer instance to back the union (size: %d)'",
",",
"UnionType",
".",
"size",
")",
"store",
"=",
"new",
"Buffer",
"(",
"UnionType",
".",
"size",
")",
"}",
"// set the backing Buffer store",
"store",
".",
"type",
"=",
"UnionType",
"this",
"[",
"'ref.buffer'",
"]",
"=",
"store",
"// initialise the union with values supplied",
"if",
"(",
"arg",
")",
"{",
"//TODO: Sanity check - e.g. (Object.keys(arg).length == 1)",
"for",
"(",
"var",
"key",
"in",
"arg",
")",
"{",
"// hopefully hit the union setters",
"this",
"[",
"key",
"]",
"=",
"arg",
"[",
"key",
"]",
"}",
"}",
"UnionType",
".",
"_instanceCreated",
"=",
"true",
"}",
"// make instances inherit from `proto`",
"UnionType",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"proto",
",",
"{",
"constructor",
":",
"{",
"value",
":",
"UnionType",
",",
"enumerable",
":",
"false",
",",
"writable",
":",
"true",
",",
"configurable",
":",
"true",
"}",
"}",
")",
"UnionType",
".",
"defineProperty",
"=",
"defineProperty",
"UnionType",
".",
"toString",
"=",
"toString",
"UnionType",
".",
"fields",
"=",
"{",
"}",
"// comply with ref's \"type\" interface",
"UnionType",
".",
"size",
"=",
"0",
"UnionType",
".",
"alignment",
"=",
"0",
"UnionType",
".",
"indirection",
"=",
"1",
"UnionType",
".",
"get",
"=",
"get",
"UnionType",
".",
"set",
"=",
"set",
"// Read the fields list",
"var",
"arg",
"=",
"arguments",
"[",
"0",
"]",
"if",
"(",
"typeof",
"arg",
"===",
"'object'",
")",
"{",
"Object",
".",
"keys",
"(",
"arg",
")",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"var",
"type",
"=",
"arg",
"[",
"name",
"]",
";",
"UnionType",
".",
"defineProperty",
"(",
"name",
",",
"type",
")",
";",
"}",
")",
"}",
"return",
"UnionType",
"}"
]
| The "Union" type constructor. | [
"The",
"Union",
"type",
"constructor",
"."
]
| 858792be59a2c75f4a8d8958b1c59c3bb7483671 | https://github.com/node-ffi-napi/ref-union-di/blob/858792be59a2c75f4a8d8958b1c59c3bb7483671/lib/union.js#L20-L86 |
44,931 | node-ffi-napi/ref-union-di | lib/union.js | defineProperty | function defineProperty (name, type) {
debug('defining new union type field', name)
// allow string types for convenience
type = ref.coerceType(type)
assert(!this._instanceCreated, 'an instance of this Union type has already '
+ 'been created, cannot add new data members anymore')
assert.equal('string', typeof name, 'expected a "string" field name')
assert(type && /object|function/i.test(typeof type) && 'size' in type &&
'indirection' in type
, 'expected a "type" object describing the field type: "' + type + '"')
assert(!(name in this.prototype), 'the field "' + name
+ '" already exists in this Union type')
// define the getter/setter property
Object.defineProperty(this.prototype, name, {
enumerable: true
, configurable: true
, get: get
, set: set
});
var field = {
type: type
}
this.fields[name] = field
// calculate the new size and alignment
recalc(this);
function get () {
debug('getting "%s" union field (length: %d)', name, type.size)
return ref.get(this['ref.buffer'], 0, type)
}
function set (value) {
debug('setting "%s" union field (length: %d)', name, type.size, value)
return ref.set(this['ref.buffer'], 0, value, type)
}
} | javascript | function defineProperty (name, type) {
debug('defining new union type field', name)
// allow string types for convenience
type = ref.coerceType(type)
assert(!this._instanceCreated, 'an instance of this Union type has already '
+ 'been created, cannot add new data members anymore')
assert.equal('string', typeof name, 'expected a "string" field name')
assert(type && /object|function/i.test(typeof type) && 'size' in type &&
'indirection' in type
, 'expected a "type" object describing the field type: "' + type + '"')
assert(!(name in this.prototype), 'the field "' + name
+ '" already exists in this Union type')
// define the getter/setter property
Object.defineProperty(this.prototype, name, {
enumerable: true
, configurable: true
, get: get
, set: set
});
var field = {
type: type
}
this.fields[name] = field
// calculate the new size and alignment
recalc(this);
function get () {
debug('getting "%s" union field (length: %d)', name, type.size)
return ref.get(this['ref.buffer'], 0, type)
}
function set (value) {
debug('setting "%s" union field (length: %d)', name, type.size, value)
return ref.set(this['ref.buffer'], 0, value, type)
}
} | [
"function",
"defineProperty",
"(",
"name",
",",
"type",
")",
"{",
"debug",
"(",
"'defining new union type field'",
",",
"name",
")",
"// allow string types for convenience",
"type",
"=",
"ref",
".",
"coerceType",
"(",
"type",
")",
"assert",
"(",
"!",
"this",
".",
"_instanceCreated",
",",
"'an instance of this Union type has already '",
"+",
"'been created, cannot add new data members anymore'",
")",
"assert",
".",
"equal",
"(",
"'string'",
",",
"typeof",
"name",
",",
"'expected a \"string\" field name'",
")",
"assert",
"(",
"type",
"&&",
"/",
"object|function",
"/",
"i",
".",
"test",
"(",
"typeof",
"type",
")",
"&&",
"'size'",
"in",
"type",
"&&",
"'indirection'",
"in",
"type",
",",
"'expected a \"type\" object describing the field type: \"'",
"+",
"type",
"+",
"'\"'",
")",
"assert",
"(",
"!",
"(",
"name",
"in",
"this",
".",
"prototype",
")",
",",
"'the field \"'",
"+",
"name",
"+",
"'\" already exists in this Union type'",
")",
"// define the getter/setter property",
"Object",
".",
"defineProperty",
"(",
"this",
".",
"prototype",
",",
"name",
",",
"{",
"enumerable",
":",
"true",
",",
"configurable",
":",
"true",
",",
"get",
":",
"get",
",",
"set",
":",
"set",
"}",
")",
";",
"var",
"field",
"=",
"{",
"type",
":",
"type",
"}",
"this",
".",
"fields",
"[",
"name",
"]",
"=",
"field",
"// calculate the new size and alignment",
"recalc",
"(",
"this",
")",
";",
"function",
"get",
"(",
")",
"{",
"debug",
"(",
"'getting \"%s\" union field (length: %d)'",
",",
"name",
",",
"type",
".",
"size",
")",
"return",
"ref",
".",
"get",
"(",
"this",
"[",
"'ref.buffer'",
"]",
",",
"0",
",",
"type",
")",
"}",
"function",
"set",
"(",
"value",
")",
"{",
"debug",
"(",
"'setting \"%s\" union field (length: %d)'",
",",
"name",
",",
"type",
".",
"size",
",",
"value",
")",
"return",
"ref",
".",
"set",
"(",
"this",
"[",
"'ref.buffer'",
"]",
",",
"0",
",",
"value",
",",
"type",
")",
"}",
"}"
]
| Adds a new field to the union instance with the given name and type.
Note that this function will throw an Error if any instances of the union
type have already been created, therefore this function must be called at the
beginning, before any instances are created. | [
"Adds",
"a",
"new",
"field",
"to",
"the",
"union",
"instance",
"with",
"the",
"given",
"name",
"and",
"type",
".",
"Note",
"that",
"this",
"function",
"will",
"throw",
"an",
"Error",
"if",
"any",
"instances",
"of",
"the",
"union",
"type",
"have",
"already",
"been",
"created",
"therefore",
"this",
"function",
"must",
"be",
"called",
"at",
"the",
"beginning",
"before",
"any",
"instances",
"are",
"created",
"."
]
| 858792be59a2c75f4a8d8958b1c59c3bb7483671 | https://github.com/node-ffi-napi/ref-union-di/blob/858792be59a2c75f4a8d8958b1c59c3bb7483671/lib/union.js#L128-L168 |
44,932 | brianbrunner/yowl | lib/yowl.js | createBot | function createBot() {
var bot = function(platform, context, event, next) {
context.platform = platform;
bot.handle(context, event, next);
};
mixin(bot, EventEmitter.prototype, false);
mixin(bot, proto, false);
bot.context = { __proto__: context, bot: bot };
bot.event = { __proto__: event, bot: bot };
bot.display_name = "bot"; // default, should be overwritten
bot.init();
return bot;
} | javascript | function createBot() {
var bot = function(platform, context, event, next) {
context.platform = platform;
bot.handle(context, event, next);
};
mixin(bot, EventEmitter.prototype, false);
mixin(bot, proto, false);
bot.context = { __proto__: context, bot: bot };
bot.event = { __proto__: event, bot: bot };
bot.display_name = "bot"; // default, should be overwritten
bot.init();
return bot;
} | [
"function",
"createBot",
"(",
")",
"{",
"var",
"bot",
"=",
"function",
"(",
"platform",
",",
"context",
",",
"event",
",",
"next",
")",
"{",
"context",
".",
"platform",
"=",
"platform",
";",
"bot",
".",
"handle",
"(",
"context",
",",
"event",
",",
"next",
")",
";",
"}",
";",
"mixin",
"(",
"bot",
",",
"EventEmitter",
".",
"prototype",
",",
"false",
")",
";",
"mixin",
"(",
"bot",
",",
"proto",
",",
"false",
")",
";",
"bot",
".",
"context",
"=",
"{",
"__proto__",
":",
"context",
",",
"bot",
":",
"bot",
"}",
";",
"bot",
".",
"event",
"=",
"{",
"__proto__",
":",
"event",
",",
"bot",
":",
"bot",
"}",
";",
"bot",
".",
"display_name",
"=",
"\"bot\"",
";",
"// default, should be overwritten",
"bot",
".",
"init",
"(",
")",
";",
"return",
"bot",
";",
"}"
]
| Creates a bot.
@return {Function}
@api public | [
"Creates",
"a",
"bot",
"."
]
| 35d6764f4cc6c4a3487eca18a12fd8ca567d4293 | https://github.com/brianbrunner/yowl/blob/35d6764f4cc6c4a3487eca18a12fd8ca567d4293/lib/yowl.js#L34-L48 |
44,933 | vid/SenseBase | lib/indexer.js | resultToContentItem | function resultToContentItem(esDoc) {
var annoDoc = {_source : {}};
publishFields.forEach(function(f) {
annoDoc._source[f] = esDoc[f];
});
return annoDoc;
} | javascript | function resultToContentItem(esDoc) {
var annoDoc = {_source : {}};
publishFields.forEach(function(f) {
annoDoc._source[f] = esDoc[f];
});
return annoDoc;
} | [
"function",
"resultToContentItem",
"(",
"esDoc",
")",
"{",
"var",
"annoDoc",
"=",
"{",
"_source",
":",
"{",
"}",
"}",
";",
"publishFields",
".",
"forEach",
"(",
"function",
"(",
"f",
")",
"{",
"annoDoc",
".",
"_source",
"[",
"f",
"]",
"=",
"esDoc",
"[",
"f",
"]",
";",
"}",
")",
";",
"return",
"annoDoc",
";",
"}"
]
| copy a cItem to elasticsearch field result format | [
"copy",
"a",
"cItem",
"to",
"elasticsearch",
"field",
"result",
"format"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/indexer.js#L50-L56 |
44,934 | vid/SenseBase | lib/indexer.js | retrieveByURI | function retrieveByURI(uri, callback) {
var query = {
query: {
term: {
uri : uri
}
}
};
getEs().search({ _index : GLOBAL.config.ESEARCH._index, _type : 'contentItem'}, query, function(err, res) {
if (!err && res && res.hits.total) {
if (res.hits.total > 1) {
// That would be weird.
throw new Error('more than one result for', uri);
}
res = res.hits.hits[0];
}
callback(err, res);
});
} | javascript | function retrieveByURI(uri, callback) {
var query = {
query: {
term: {
uri : uri
}
}
};
getEs().search({ _index : GLOBAL.config.ESEARCH._index, _type : 'contentItem'}, query, function(err, res) {
if (!err && res && res.hits.total) {
if (res.hits.total > 1) {
// That would be weird.
throw new Error('more than one result for', uri);
}
res = res.hits.hits[0];
}
callback(err, res);
});
} | [
"function",
"retrieveByURI",
"(",
"uri",
",",
"callback",
")",
"{",
"var",
"query",
"=",
"{",
"query",
":",
"{",
"term",
":",
"{",
"uri",
":",
"uri",
"}",
"}",
"}",
";",
"getEs",
"(",
")",
".",
"search",
"(",
"{",
"_index",
":",
"GLOBAL",
".",
"config",
".",
"ESEARCH",
".",
"_index",
",",
"_type",
":",
"'contentItem'",
"}",
",",
"query",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"!",
"err",
"&&",
"res",
"&&",
"res",
".",
"hits",
".",
"total",
")",
"{",
"if",
"(",
"res",
".",
"hits",
".",
"total",
">",
"1",
")",
"{",
"// That would be weird.",
"throw",
"new",
"Error",
"(",
"'more than one result for'",
",",
"uri",
")",
";",
"}",
"res",
"=",
"res",
".",
"hits",
".",
"hits",
"[",
"0",
"]",
";",
"}",
"callback",
"(",
"err",
",",
"res",
")",
";",
"}",
")",
";",
"}"
]
| Retrieves a complete contentItem by URI. | [
"Retrieves",
"a",
"complete",
"contentItem",
"by",
"URI",
"."
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/indexer.js#L85-L103 |
44,935 | vid/SenseBase | lib/indexer.js | deleteRecord | function deleteRecord(rType, idFun) {
return function(item, callback) {
GLOBAL.debug('deleting', item, rType);
var tc = [];
getEs().delete({ _type: rType, _id : encodeURIComponent(idFun(item))}, function(err, deleteRes) {
callback(err, deleteRes);
});
};
} | javascript | function deleteRecord(rType, idFun) {
return function(item, callback) {
GLOBAL.debug('deleting', item, rType);
var tc = [];
getEs().delete({ _type: rType, _id : encodeURIComponent(idFun(item))}, function(err, deleteRes) {
callback(err, deleteRes);
});
};
} | [
"function",
"deleteRecord",
"(",
"rType",
",",
"idFun",
")",
"{",
"return",
"function",
"(",
"item",
",",
"callback",
")",
"{",
"GLOBAL",
".",
"debug",
"(",
"'deleting'",
",",
"item",
",",
"rType",
")",
";",
"var",
"tc",
"=",
"[",
"]",
";",
"getEs",
"(",
")",
".",
"delete",
"(",
"{",
"_type",
":",
"rType",
",",
"_id",
":",
"encodeURIComponent",
"(",
"idFun",
"(",
"item",
")",
")",
"}",
",",
"function",
"(",
"err",
",",
"deleteRes",
")",
"{",
"callback",
"(",
"err",
",",
"deleteRes",
")",
";",
"}",
")",
";",
"}",
";",
"}"
]
| delete member record partial | [
"delete",
"member",
"record",
"partial"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/indexer.js#L106-L114 |
44,936 | vid/SenseBase | lib/indexer.js | saveRecord | function saveRecord(rType, idFun) {
return function(records, callback) {
GLOBAL.debug('inserting', records.length, rType);
if (!_.isArray(records)) {
records = [records];
}
var tc = [];
records.forEach(function(d) {
var meta = {_index : GLOBAL.config.ESEARCH._index, _type : rType};
if (idFun) {
meta._id = idFun(d);
}
tc.push({ index : meta});
tc.push(d);
});
getEs().bulk(tc, function (err, data) {
callback(err, data, records);
});
};
} | javascript | function saveRecord(rType, idFun) {
return function(records, callback) {
GLOBAL.debug('inserting', records.length, rType);
if (!_.isArray(records)) {
records = [records];
}
var tc = [];
records.forEach(function(d) {
var meta = {_index : GLOBAL.config.ESEARCH._index, _type : rType};
if (idFun) {
meta._id = idFun(d);
}
tc.push({ index : meta});
tc.push(d);
});
getEs().bulk(tc, function (err, data) {
callback(err, data, records);
});
};
} | [
"function",
"saveRecord",
"(",
"rType",
",",
"idFun",
")",
"{",
"return",
"function",
"(",
"records",
",",
"callback",
")",
"{",
"GLOBAL",
".",
"debug",
"(",
"'inserting'",
",",
"records",
".",
"length",
",",
"rType",
")",
";",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"records",
")",
")",
"{",
"records",
"=",
"[",
"records",
"]",
";",
"}",
"var",
"tc",
"=",
"[",
"]",
";",
"records",
".",
"forEach",
"(",
"function",
"(",
"d",
")",
"{",
"var",
"meta",
"=",
"{",
"_index",
":",
"GLOBAL",
".",
"config",
".",
"ESEARCH",
".",
"_index",
",",
"_type",
":",
"rType",
"}",
";",
"if",
"(",
"idFun",
")",
"{",
"meta",
".",
"_id",
"=",
"idFun",
"(",
"d",
")",
";",
"}",
"tc",
".",
"push",
"(",
"{",
"index",
":",
"meta",
"}",
")",
";",
"tc",
".",
"push",
"(",
"d",
")",
";",
"}",
")",
";",
"getEs",
"(",
")",
".",
"bulk",
"(",
"tc",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"callback",
"(",
"err",
",",
"data",
",",
"records",
")",
";",
"}",
")",
";",
"}",
";",
"}"
]
| save member record partial | [
"save",
"member",
"record",
"partial"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/indexer.js#L117-L136 |
44,937 | vid/SenseBase | lib/indexer.js | formQuery | function formQuery(params, callback) {
params = params || { query: {}};
var query = formQueryLib.createFormQuery(params);
var q = {
_source : params.sourceFields || sourceFields,
sort : params.sort || [
{ "timestamp" : {"order" : "desc"}},
],
from: params.from || 0,
size : querySize(params),
query: query
};
if (params.query && params.query.terms) {
q.highlight = { fields: {"title" : {}, "text" : {}}};
}
getEs().search({ _index : GLOBAL.config.ESEARCH._index, _type : 'contentItem'}, q, function(err, res) {
if (err) {
utils.passingError(err, params);
} else {
res.from = params.from || 0;
res.query = q;
if (!res || res.hits.hits.length < 1) {
GLOBAL.debug('NO HITS FOR', JSON.stringify(q, null, 2));
}
}
formQueryLib.filter(params.filters, res);
callback(err, res);
});
} | javascript | function formQuery(params, callback) {
params = params || { query: {}};
var query = formQueryLib.createFormQuery(params);
var q = {
_source : params.sourceFields || sourceFields,
sort : params.sort || [
{ "timestamp" : {"order" : "desc"}},
],
from: params.from || 0,
size : querySize(params),
query: query
};
if (params.query && params.query.terms) {
q.highlight = { fields: {"title" : {}, "text" : {}}};
}
getEs().search({ _index : GLOBAL.config.ESEARCH._index, _type : 'contentItem'}, q, function(err, res) {
if (err) {
utils.passingError(err, params);
} else {
res.from = params.from || 0;
res.query = q;
if (!res || res.hits.hits.length < 1) {
GLOBAL.debug('NO HITS FOR', JSON.stringify(q, null, 2));
}
}
formQueryLib.filter(params.filters, res);
callback(err, res);
});
} | [
"function",
"formQuery",
"(",
"params",
",",
"callback",
")",
"{",
"params",
"=",
"params",
"||",
"{",
"query",
":",
"{",
"}",
"}",
";",
"var",
"query",
"=",
"formQueryLib",
".",
"createFormQuery",
"(",
"params",
")",
";",
"var",
"q",
"=",
"{",
"_source",
":",
"params",
".",
"sourceFields",
"||",
"sourceFields",
",",
"sort",
":",
"params",
".",
"sort",
"||",
"[",
"{",
"\"timestamp\"",
":",
"{",
"\"order\"",
":",
"\"desc\"",
"}",
"}",
",",
"]",
",",
"from",
":",
"params",
".",
"from",
"||",
"0",
",",
"size",
":",
"querySize",
"(",
"params",
")",
",",
"query",
":",
"query",
"}",
";",
"if",
"(",
"params",
".",
"query",
"&&",
"params",
".",
"query",
".",
"terms",
")",
"{",
"q",
".",
"highlight",
"=",
"{",
"fields",
":",
"{",
"\"title\"",
":",
"{",
"}",
",",
"\"text\"",
":",
"{",
"}",
"}",
"}",
";",
"}",
"getEs",
"(",
")",
".",
"search",
"(",
"{",
"_index",
":",
"GLOBAL",
".",
"config",
".",
"ESEARCH",
".",
"_index",
",",
"_type",
":",
"'contentItem'",
"}",
",",
"q",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"utils",
".",
"passingError",
"(",
"err",
",",
"params",
")",
";",
"}",
"else",
"{",
"res",
".",
"from",
"=",
"params",
".",
"from",
"||",
"0",
";",
"res",
".",
"query",
"=",
"q",
";",
"if",
"(",
"!",
"res",
"||",
"res",
".",
"hits",
".",
"hits",
".",
"length",
"<",
"1",
")",
"{",
"GLOBAL",
".",
"debug",
"(",
"'NO HITS FOR'",
",",
"JSON",
".",
"stringify",
"(",
"q",
",",
"null",
",",
"2",
")",
")",
";",
"}",
"}",
"formQueryLib",
".",
"filter",
"(",
"params",
".",
"filters",
",",
"res",
")",
";",
"callback",
"(",
"err",
",",
"res",
")",
";",
"}",
")",
";",
"}"
]
| Executes form params, returning results | [
"Executes",
"form",
"params",
"returning",
"results"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/indexer.js#L182-L213 |
44,938 | vid/SenseBase | lib/indexer.js | formCluster | function formCluster(params, callback) {
var query = formQueryLib.createFormQuery(params);
var q = {
"search_request" : {
_source : sourceFields.concat(['text']),
sort : [
{ "visitors.@timestamp" : {"order" : "desc"}},
],
size : querySize(params),
query: query
},
"query_hint": "*",
"algorithm": "lingo",
"field_mapping": {
"title": ["_source.title"],
"content": ["_source.text"],
"url": ["_source.uri"]
}
};
doPost('/contentItem/_search_with_clusters', JSON.stringify(q), function(err, res) {
if (err) {
GLOBAL.error('formCluster, carrot2 extension not installed?', err, q);
callback(err);
return;
}
res.query = q;
if (!res || res.hits.hits.length < 1) {
GLOBAL.info('NO HITS FOR', JSON.stringify(q, null, 2));
}
// FIXME don't send text
callback(err, res);
});
} | javascript | function formCluster(params, callback) {
var query = formQueryLib.createFormQuery(params);
var q = {
"search_request" : {
_source : sourceFields.concat(['text']),
sort : [
{ "visitors.@timestamp" : {"order" : "desc"}},
],
size : querySize(params),
query: query
},
"query_hint": "*",
"algorithm": "lingo",
"field_mapping": {
"title": ["_source.title"],
"content": ["_source.text"],
"url": ["_source.uri"]
}
};
doPost('/contentItem/_search_with_clusters', JSON.stringify(q), function(err, res) {
if (err) {
GLOBAL.error('formCluster, carrot2 extension not installed?', err, q);
callback(err);
return;
}
res.query = q;
if (!res || res.hits.hits.length < 1) {
GLOBAL.info('NO HITS FOR', JSON.stringify(q, null, 2));
}
// FIXME don't send text
callback(err, res);
});
} | [
"function",
"formCluster",
"(",
"params",
",",
"callback",
")",
"{",
"var",
"query",
"=",
"formQueryLib",
".",
"createFormQuery",
"(",
"params",
")",
";",
"var",
"q",
"=",
"{",
"\"search_request\"",
":",
"{",
"_source",
":",
"sourceFields",
".",
"concat",
"(",
"[",
"'text'",
"]",
")",
",",
"sort",
":",
"[",
"{",
"\"visitors.@timestamp\"",
":",
"{",
"\"order\"",
":",
"\"desc\"",
"}",
"}",
",",
"]",
",",
"size",
":",
"querySize",
"(",
"params",
")",
",",
"query",
":",
"query",
"}",
",",
"\"query_hint\"",
":",
"\"*\"",
",",
"\"algorithm\"",
":",
"\"lingo\"",
",",
"\"field_mapping\"",
":",
"{",
"\"title\"",
":",
"[",
"\"_source.title\"",
"]",
",",
"\"content\"",
":",
"[",
"\"_source.text\"",
"]",
",",
"\"url\"",
":",
"[",
"\"_source.uri\"",
"]",
"}",
"}",
";",
"doPost",
"(",
"'/contentItem/_search_with_clusters'",
",",
"JSON",
".",
"stringify",
"(",
"q",
")",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"GLOBAL",
".",
"error",
"(",
"'formCluster, carrot2 extension not installed?'",
",",
"err",
",",
"q",
")",
";",
"callback",
"(",
"err",
")",
";",
"return",
";",
"}",
"res",
".",
"query",
"=",
"q",
";",
"if",
"(",
"!",
"res",
"||",
"res",
".",
"hits",
".",
"hits",
".",
"length",
"<",
"1",
")",
"{",
"GLOBAL",
".",
"info",
"(",
"'NO HITS FOR'",
",",
"JSON",
".",
"stringify",
"(",
"q",
",",
"null",
",",
"2",
")",
")",
";",
"}",
"// FIXME don't send text",
"callback",
"(",
"err",
",",
"res",
")",
";",
"}",
")",
";",
"}"
]
| Executes carrot2 cluster query | [
"Executes",
"carrot2",
"cluster",
"query"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/indexer.js#L216-L249 |
44,939 | vid/SenseBase | lib/indexer.js | doPost | function doPost(path, data, callback) {
var options = {
host: GLOBAL.config.ESEARCH.server.host,
port: GLOBAL.config.ESEARCH.server.port,
path: GLOBAL.config.ESEARCH._index + path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
utils.doPostJson(options, data, callback);
} | javascript | function doPost(path, data, callback) {
var options = {
host: GLOBAL.config.ESEARCH.server.host,
port: GLOBAL.config.ESEARCH.server.port,
path: GLOBAL.config.ESEARCH._index + path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
utils.doPostJson(options, data, callback);
} | [
"function",
"doPost",
"(",
"path",
",",
"data",
",",
"callback",
")",
"{",
"var",
"options",
"=",
"{",
"host",
":",
"GLOBAL",
".",
"config",
".",
"ESEARCH",
".",
"server",
".",
"host",
",",
"port",
":",
"GLOBAL",
".",
"config",
".",
"ESEARCH",
".",
"server",
".",
"port",
",",
"path",
":",
"GLOBAL",
".",
"config",
".",
"ESEARCH",
".",
"_index",
"+",
"path",
",",
"method",
":",
"'POST'",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
",",
"'Content-Length'",
":",
"Buffer",
".",
"byteLength",
"(",
"data",
")",
"}",
"}",
";",
"utils",
".",
"doPostJson",
"(",
"options",
",",
"data",
",",
"callback",
")",
";",
"}"
]
| POST for es functions that aren't locally supported | [
"POST",
"for",
"es",
"functions",
"that",
"aren",
"t",
"locally",
"supported"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/indexer.js#L297-L309 |
44,940 | Whitebolt/require-extra | src/require.js | _getResolve | function _getResolve(obj) {
if (!obj) return settings.get('resolver');
if (obj instanceof Resolver) return obj;
if (obj.resolver) return obj.resolver;
let pass = true;
Resolver.resolveLike.forEach(property=>{pass &= (property in obj);});
if (pass) return obj;
return new Resolver(obj);
} | javascript | function _getResolve(obj) {
if (!obj) return settings.get('resolver');
if (obj instanceof Resolver) return obj;
if (obj.resolver) return obj.resolver;
let pass = true;
Resolver.resolveLike.forEach(property=>{pass &= (property in obj);});
if (pass) return obj;
return new Resolver(obj);
} | [
"function",
"_getResolve",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"return",
"settings",
".",
"get",
"(",
"'resolver'",
")",
";",
"if",
"(",
"obj",
"instanceof",
"Resolver",
")",
"return",
"obj",
";",
"if",
"(",
"obj",
".",
"resolver",
")",
"return",
"obj",
".",
"resolver",
";",
"let",
"pass",
"=",
"true",
";",
"Resolver",
".",
"resolveLike",
".",
"forEach",
"(",
"property",
"=>",
"{",
"pass",
"&=",
"(",
"property",
"in",
"obj",
")",
";",
"}",
")",
";",
"if",
"(",
"pass",
")",
"return",
"obj",
";",
"return",
"new",
"Resolver",
"(",
"obj",
")",
";",
"}"
]
| Get the resolver object from a given object. Assumes it has received
either an actual resolver or an options object with resolver in it. If this
is not true then return the default resolver.
@private
@param {Object} obj Object to get resolver from.
@returns {Object} The resolver object. | [
"Get",
"the",
"resolver",
"object",
"from",
"a",
"given",
"object",
".",
"Assumes",
"it",
"has",
"received",
"either",
"an",
"actual",
"resolver",
"or",
"an",
"options",
"object",
"with",
"resolver",
"in",
"it",
".",
"If",
"this",
"is",
"not",
"true",
"then",
"return",
"the",
"default",
"resolver",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L52-L60 |
44,941 | Whitebolt/require-extra | src/require.js | _getRoot | function _getRoot(obj) {
return (getCallingDir(((obj && obj.basedir) ? obj.basedir : undefined)) || (obj?obj.basedir:undefined));
} | javascript | function _getRoot(obj) {
return (getCallingDir(((obj && obj.basedir) ? obj.basedir : undefined)) || (obj?obj.basedir:undefined));
} | [
"function",
"_getRoot",
"(",
"obj",
")",
"{",
"return",
"(",
"getCallingDir",
"(",
"(",
"(",
"obj",
"&&",
"obj",
".",
"basedir",
")",
"?",
"obj",
".",
"basedir",
":",
"undefined",
")",
")",
"||",
"(",
"obj",
"?",
"obj",
".",
"basedir",
":",
"undefined",
")",
")",
";",
"}"
]
| Get the root directory to use from the supplied object or calculate it.
@private
@param {Object} obj The options object containing a 'dir' property.
@returns {string} The directory path. | [
"Get",
"the",
"root",
"directory",
"to",
"use",
"from",
"the",
"supplied",
"object",
"or",
"calculate",
"it",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L69-L71 |
44,942 | Whitebolt/require-extra | src/require.js | _loadModuleText | function _loadModuleText(target, source, sync=false) {
const time = process.hrtime();
const loadEventEvent = new emitter.Load({target, source, sync});
const loadEvent = emitter.emit('load', loadEventEvent);
const loaded = txtBuffer=>{
try {
const loadedEvent = emitter.emit('loaded', new emitter.Loaded({
target,
otherTarget: loadEventEvent.data.target,
duration: process.hrtime(time),
size: txtBuffer.byteLength,
source,
sync,
data: txtBuffer
}));
return sync?txtBuffer:loadedEvent.then(()=>txtBuffer,loadError);
} catch (error) {
return loadError(error);
}
};
const loadError = error=>{
const _error = new emitter.Error({target, source, error});
emitter.emit('error', _error);
if (!_error.ignore || (_error.ignore && isFunction(_error.ignore) && !_error.ignore())) throw error;
};
if (!sync) return loadEvent.then(()=>readFile(loadEventEvent.data.target || target, fileCache).then(loaded, loadError), loadError);
try {
return loaded(readFileSync(loadEventEvent.data.target || target, fileCache));
} catch(error) {
loadError(error);
}
} | javascript | function _loadModuleText(target, source, sync=false) {
const time = process.hrtime();
const loadEventEvent = new emitter.Load({target, source, sync});
const loadEvent = emitter.emit('load', loadEventEvent);
const loaded = txtBuffer=>{
try {
const loadedEvent = emitter.emit('loaded', new emitter.Loaded({
target,
otherTarget: loadEventEvent.data.target,
duration: process.hrtime(time),
size: txtBuffer.byteLength,
source,
sync,
data: txtBuffer
}));
return sync?txtBuffer:loadedEvent.then(()=>txtBuffer,loadError);
} catch (error) {
return loadError(error);
}
};
const loadError = error=>{
const _error = new emitter.Error({target, source, error});
emitter.emit('error', _error);
if (!_error.ignore || (_error.ignore && isFunction(_error.ignore) && !_error.ignore())) throw error;
};
if (!sync) return loadEvent.then(()=>readFile(loadEventEvent.data.target || target, fileCache).then(loaded, loadError), loadError);
try {
return loaded(readFileSync(loadEventEvent.data.target || target, fileCache));
} catch(error) {
loadError(error);
}
} | [
"function",
"_loadModuleText",
"(",
"target",
",",
"source",
",",
"sync",
"=",
"false",
")",
"{",
"const",
"time",
"=",
"process",
".",
"hrtime",
"(",
")",
";",
"const",
"loadEventEvent",
"=",
"new",
"emitter",
".",
"Load",
"(",
"{",
"target",
",",
"source",
",",
"sync",
"}",
")",
";",
"const",
"loadEvent",
"=",
"emitter",
".",
"emit",
"(",
"'load'",
",",
"loadEventEvent",
")",
";",
"const",
"loaded",
"=",
"txtBuffer",
"=>",
"{",
"try",
"{",
"const",
"loadedEvent",
"=",
"emitter",
".",
"emit",
"(",
"'loaded'",
",",
"new",
"emitter",
".",
"Loaded",
"(",
"{",
"target",
",",
"otherTarget",
":",
"loadEventEvent",
".",
"data",
".",
"target",
",",
"duration",
":",
"process",
".",
"hrtime",
"(",
"time",
")",
",",
"size",
":",
"txtBuffer",
".",
"byteLength",
",",
"source",
",",
"sync",
",",
"data",
":",
"txtBuffer",
"}",
")",
")",
";",
"return",
"sync",
"?",
"txtBuffer",
":",
"loadedEvent",
".",
"then",
"(",
"(",
")",
"=>",
"txtBuffer",
",",
"loadError",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"loadError",
"(",
"error",
")",
";",
"}",
"}",
";",
"const",
"loadError",
"=",
"error",
"=>",
"{",
"const",
"_error",
"=",
"new",
"emitter",
".",
"Error",
"(",
"{",
"target",
",",
"source",
",",
"error",
"}",
")",
";",
"emitter",
".",
"emit",
"(",
"'error'",
",",
"_error",
")",
";",
"if",
"(",
"!",
"_error",
".",
"ignore",
"||",
"(",
"_error",
".",
"ignore",
"&&",
"isFunction",
"(",
"_error",
".",
"ignore",
")",
"&&",
"!",
"_error",
".",
"ignore",
"(",
")",
")",
")",
"throw",
"error",
";",
"}",
";",
"if",
"(",
"!",
"sync",
")",
"return",
"loadEvent",
".",
"then",
"(",
"(",
")",
"=>",
"readFile",
"(",
"loadEventEvent",
".",
"data",
".",
"target",
"||",
"target",
",",
"fileCache",
")",
".",
"then",
"(",
"loaded",
",",
"loadError",
")",
",",
"loadError",
")",
";",
"try",
"{",
"return",
"loaded",
"(",
"readFileSync",
"(",
"loadEventEvent",
".",
"data",
".",
"target",
"||",
"target",
",",
"fileCache",
")",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"loadError",
"(",
"error",
")",
";",
"}",
"}"
]
| Read text from a file and handle any errors.
@private
@param {string} target The target to load.
@param {string} source The loading source path.
@param {boolean} [sync=false] Use sync method?
@returns {Promise.<string>|string} The results. | [
"Read",
"text",
"from",
"a",
"file",
"and",
"handle",
"any",
"errors",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L110-L144 |
44,943 | Whitebolt/require-extra | src/require.js | _evalModuleText | function _evalModuleText(filename, content, userResolver, sync=true) {
if (content === undefined) return;
const ext = path.extname(filename);
const config = _createModuleConfig(filename, content, _getResolve(userResolver));
let module = _runEval(config, settings.get(ext) || function(){}, userResolver.options || {}, sync);
if ((!(config.resolver || {}).squashErrors) && fileCache.has(filename)) fileCache.delete(filename);
return module;
} | javascript | function _evalModuleText(filename, content, userResolver, sync=true) {
if (content === undefined) return;
const ext = path.extname(filename);
const config = _createModuleConfig(filename, content, _getResolve(userResolver));
let module = _runEval(config, settings.get(ext) || function(){}, userResolver.options || {}, sync);
if ((!(config.resolver || {}).squashErrors) && fileCache.has(filename)) fileCache.delete(filename);
return module;
} | [
"function",
"_evalModuleText",
"(",
"filename",
",",
"content",
",",
"userResolver",
",",
"sync",
"=",
"true",
")",
"{",
"if",
"(",
"content",
"===",
"undefined",
")",
"return",
";",
"const",
"ext",
"=",
"path",
".",
"extname",
"(",
"filename",
")",
";",
"const",
"config",
"=",
"_createModuleConfig",
"(",
"filename",
",",
"content",
",",
"_getResolve",
"(",
"userResolver",
")",
")",
";",
"let",
"module",
"=",
"_runEval",
"(",
"config",
",",
"settings",
".",
"get",
"(",
"ext",
")",
"||",
"function",
"(",
")",
"{",
"}",
",",
"userResolver",
".",
"options",
"||",
"{",
"}",
",",
"sync",
")",
";",
"if",
"(",
"(",
"!",
"(",
"config",
".",
"resolver",
"||",
"{",
"}",
")",
".",
"squashErrors",
")",
"&&",
"fileCache",
".",
"has",
"(",
"filename",
")",
")",
"fileCache",
".",
"delete",
"(",
"filename",
")",
";",
"return",
"module",
";",
"}"
]
| Evaluate module text in similar fashion to require evaluations, returning the module.
@private
@param {string} filename The path of the evaluated module.
@param {string} content The text content of the module.
@param {Resolver|Object} [userResolver] Resolver to use, if not a resolver assume it is config for a new resolver.
@returns {Module} The new module. | [
"Evaluate",
"module",
"text",
"in",
"similar",
"fashion",
"to",
"require",
"evaluations",
"returning",
"the",
"module",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L155-L164 |
44,944 | Whitebolt/require-extra | src/require.js | _runEval | function _runEval(config, parser, options, sync=true) {
const time = process.hrtime();
const evalEvent = new emitter.Evaluate({
target:config.filename,
source:(config.parent || {}).filename,
moduleConfig: config,
parserOptions: options,
sync
});
const evaluateEvent = emitter.emit('evaluate', evalEvent);
function evaluated() {
let module = ((evalEvent.data.module) ? evalEvent.data.module : parser.bind(settings)(config, options));
if (!module || !module.loaded) return module;
const evaluatedEvent = emitter.emit('evaluated', new emitter.Evaluated({
target:module.filename,
source:(module.parent || {}).filename,
duration:process.hrtime(time),
cacheSize: cache.size,
exports: module.exports,
sync
}));
try {filePaths.set(module.exports, module.filename);} catch(err) {}
return sync?module:evaluatedEvent.then(()=>module);
}
return sync?evaluated():evaluateEvent.then(evaluated);
} | javascript | function _runEval(config, parser, options, sync=true) {
const time = process.hrtime();
const evalEvent = new emitter.Evaluate({
target:config.filename,
source:(config.parent || {}).filename,
moduleConfig: config,
parserOptions: options,
sync
});
const evaluateEvent = emitter.emit('evaluate', evalEvent);
function evaluated() {
let module = ((evalEvent.data.module) ? evalEvent.data.module : parser.bind(settings)(config, options));
if (!module || !module.loaded) return module;
const evaluatedEvent = emitter.emit('evaluated', new emitter.Evaluated({
target:module.filename,
source:(module.parent || {}).filename,
duration:process.hrtime(time),
cacheSize: cache.size,
exports: module.exports,
sync
}));
try {filePaths.set(module.exports, module.filename);} catch(err) {}
return sync?module:evaluatedEvent.then(()=>module);
}
return sync?evaluated():evaluateEvent.then(evaluated);
} | [
"function",
"_runEval",
"(",
"config",
",",
"parser",
",",
"options",
",",
"sync",
"=",
"true",
")",
"{",
"const",
"time",
"=",
"process",
".",
"hrtime",
"(",
")",
";",
"const",
"evalEvent",
"=",
"new",
"emitter",
".",
"Evaluate",
"(",
"{",
"target",
":",
"config",
".",
"filename",
",",
"source",
":",
"(",
"config",
".",
"parent",
"||",
"{",
"}",
")",
".",
"filename",
",",
"moduleConfig",
":",
"config",
",",
"parserOptions",
":",
"options",
",",
"sync",
"}",
")",
";",
"const",
"evaluateEvent",
"=",
"emitter",
".",
"emit",
"(",
"'evaluate'",
",",
"evalEvent",
")",
";",
"function",
"evaluated",
"(",
")",
"{",
"let",
"module",
"=",
"(",
"(",
"evalEvent",
".",
"data",
".",
"module",
")",
"?",
"evalEvent",
".",
"data",
".",
"module",
":",
"parser",
".",
"bind",
"(",
"settings",
")",
"(",
"config",
",",
"options",
")",
")",
";",
"if",
"(",
"!",
"module",
"||",
"!",
"module",
".",
"loaded",
")",
"return",
"module",
";",
"const",
"evaluatedEvent",
"=",
"emitter",
".",
"emit",
"(",
"'evaluated'",
",",
"new",
"emitter",
".",
"Evaluated",
"(",
"{",
"target",
":",
"module",
".",
"filename",
",",
"source",
":",
"(",
"module",
".",
"parent",
"||",
"{",
"}",
")",
".",
"filename",
",",
"duration",
":",
"process",
".",
"hrtime",
"(",
"time",
")",
",",
"cacheSize",
":",
"cache",
".",
"size",
",",
"exports",
":",
"module",
".",
"exports",
",",
"sync",
"}",
")",
")",
";",
"try",
"{",
"filePaths",
".",
"set",
"(",
"module",
".",
"exports",
",",
"module",
".",
"filename",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"return",
"sync",
"?",
"module",
":",
"evaluatedEvent",
".",
"then",
"(",
"(",
")",
"=>",
"module",
")",
";",
"}",
"return",
"sync",
"?",
"evaluated",
"(",
")",
":",
"evaluateEvent",
".",
"then",
"(",
"evaluated",
")",
";",
"}"
]
| Run the parser with the given configuration and deal with events, returning the module.
@private
@param {Object} config
@param {Function} parser
@returns {Module} | [
"Run",
"the",
"parser",
"with",
"the",
"given",
"configuration",
"and",
"deal",
"with",
"events",
"returning",
"the",
"module",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L174-L203 |
44,945 | Whitebolt/require-extra | src/require.js | _createModuleConfig | function _createModuleConfig(filename, content, userResolver) {
return Object.assign({
content,
filename,
includeGlobals:true,
syncRequire:_syncRequire(_syncRequire),
resolveModulePath,
resolveModulePathSync,
basedir: path.dirname(filename),
resolver: userResolver
}, userResolver.export);
} | javascript | function _createModuleConfig(filename, content, userResolver) {
return Object.assign({
content,
filename,
includeGlobals:true,
syncRequire:_syncRequire(_syncRequire),
resolveModulePath,
resolveModulePathSync,
basedir: path.dirname(filename),
resolver: userResolver
}, userResolver.export);
} | [
"function",
"_createModuleConfig",
"(",
"filename",
",",
"content",
",",
"userResolver",
")",
"{",
"return",
"Object",
".",
"assign",
"(",
"{",
"content",
",",
"filename",
",",
"includeGlobals",
":",
"true",
",",
"syncRequire",
":",
"_syncRequire",
"(",
"_syncRequire",
")",
",",
"resolveModulePath",
",",
"resolveModulePathSync",
",",
"basedir",
":",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"resolver",
":",
"userResolver",
"}",
",",
"userResolver",
".",
"export",
")",
";",
"}"
]
| Create a config object to pass to _eval or Module constructor using supplied filename, content and Resolver.
@private
@param {string} filename The filename to create for.
@param {string|Buffer} content The content of the file.
@param {Resolver} userResolver The Resolver being used.
@returns {Object} The new config object. | [
"Create",
"a",
"config",
"object",
"to",
"pass",
"to",
"_eval",
"or",
"Module",
"constructor",
"using",
"supplied",
"filename",
"content",
"and",
"Resolver",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L249-L260 |
44,946 | Whitebolt/require-extra | src/require.js | _loadModuleSyncAsync | async function _loadModuleSyncAsync(filename, userResolver) {
const localRequire = requireLike(_getResolve(userResolver).parent || settings.get('parent').filename);
await promisify(setImmediate)();
return localRequire(filename);
} | javascript | async function _loadModuleSyncAsync(filename, userResolver) {
const localRequire = requireLike(_getResolve(userResolver).parent || settings.get('parent').filename);
await promisify(setImmediate)();
return localRequire(filename);
} | [
"async",
"function",
"_loadModuleSyncAsync",
"(",
"filename",
",",
"userResolver",
")",
"{",
"const",
"localRequire",
"=",
"requireLike",
"(",
"_getResolve",
"(",
"userResolver",
")",
".",
"parent",
"||",
"settings",
".",
"get",
"(",
"'parent'",
")",
".",
"filename",
")",
";",
"await",
"promisify",
"(",
"setImmediate",
")",
"(",
")",
";",
"return",
"localRequire",
"(",
"filename",
")",
";",
"}"
]
| This is a sychronous version of loadModule. The module is still resolved
using async methods but the actual loading is done using the native require
from node.
Load and evaluate a module returning undefined to promise resolve
on failure.
@private
@param {string} filename The path of the evaluated module.
@param {Resolver|Object} [userResolver] Resolver to use, if not a resolver assume it is config for a new resolver.
@returns {*} | [
"This",
"is",
"a",
"sychronous",
"version",
"of",
"loadModule",
".",
"The",
"module",
"is",
"still",
"resolved",
"using",
"async",
"methods",
"but",
"the",
"actual",
"loading",
"is",
"done",
"using",
"the",
"native",
"require",
"from",
"node",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L314-L318 |
44,947 | Whitebolt/require-extra | src/require.js | _parseRequireParams | function _parseRequireParams([userResolver, moduleId, callback], useSyncResolve=false) {
if(isString(userResolver) || Array.isArray(userResolver)) {
return [settings.get('resolver'), userResolver, moduleId, useSyncResolve];
}else {
return [_getResolve(userResolver), moduleId, callback, useSyncResolve];
}
} | javascript | function _parseRequireParams([userResolver, moduleId, callback], useSyncResolve=false) {
if(isString(userResolver) || Array.isArray(userResolver)) {
return [settings.get('resolver'), userResolver, moduleId, useSyncResolve];
}else {
return [_getResolve(userResolver), moduleId, callback, useSyncResolve];
}
} | [
"function",
"_parseRequireParams",
"(",
"[",
"userResolver",
",",
"moduleId",
",",
"callback",
"]",
",",
"useSyncResolve",
"=",
"false",
")",
"{",
"if",
"(",
"isString",
"(",
"userResolver",
")",
"||",
"Array",
".",
"isArray",
"(",
"userResolver",
")",
")",
"{",
"return",
"[",
"settings",
".",
"get",
"(",
"'resolver'",
")",
",",
"userResolver",
",",
"moduleId",
",",
"useSyncResolve",
"]",
";",
"}",
"else",
"{",
"return",
"[",
"_getResolve",
"(",
"userResolver",
")",
",",
"moduleId",
",",
"callback",
",",
"useSyncResolve",
"]",
";",
"}",
"}"
]
| Take arguments supplied to the different require function and parse ready for internal use.
@private
@param {Resolver} [userResolver] Resolver to use.
@param {string} moduleId The module to load.
@param {Function} [callback] Node-style callback to fire if promise not wanted.
@param {boolean} [useSyncResolve=false] Use the native require to child requires?
@returns {[{Resolver}, {string}, {Function}, {boolean}]} Parsed parameters, ready for use. | [
"Take",
"arguments",
"supplied",
"to",
"the",
"different",
"require",
"function",
"and",
"parse",
"ready",
"for",
"internal",
"use",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L379-L385 |
44,948 | Whitebolt/require-extra | src/require.js | syncRequire | function syncRequire(...params) {
const [userResolver, moduleId] = _parseRequireParams(params);
if (userResolver.isCoreModule(moduleId)) return getRequire()(moduleId);
userResolver.basedir = userResolver.basedir || userResolver.dir;
const filename = resolveModulePathSync(userResolver, moduleId, true);
return _loadModuleSync(filename, userResolver);
} | javascript | function syncRequire(...params) {
const [userResolver, moduleId] = _parseRequireParams(params);
if (userResolver.isCoreModule(moduleId)) return getRequire()(moduleId);
userResolver.basedir = userResolver.basedir || userResolver.dir;
const filename = resolveModulePathSync(userResolver, moduleId, true);
return _loadModuleSync(filename, userResolver);
} | [
"function",
"syncRequire",
"(",
"...",
"params",
")",
"{",
"const",
"[",
"userResolver",
",",
"moduleId",
"]",
"=",
"_parseRequireParams",
"(",
"params",
")",
";",
"if",
"(",
"userResolver",
".",
"isCoreModule",
"(",
"moduleId",
")",
")",
"return",
"getRequire",
"(",
")",
"(",
"moduleId",
")",
";",
"userResolver",
".",
"basedir",
"=",
"userResolver",
".",
"basedir",
"||",
"userResolver",
".",
"dir",
";",
"const",
"filename",
"=",
"resolveModulePathSync",
"(",
"userResolver",
",",
"moduleId",
",",
"true",
")",
";",
"return",
"_loadModuleSync",
"(",
"filename",
",",
"userResolver",
")",
";",
"}"
]
| CommonJs require function, similar to node.js native version but with extra features of this module.
@param {Resolver} [userResolver] Resolver to use in requiring.
@param {string} moduleId Module to load.
@returns {*} Module exports | [
"CommonJs",
"require",
"function",
"similar",
"to",
"node",
".",
"js",
"native",
"version",
"but",
"with",
"extra",
"features",
"of",
"this",
"module",
"."
]
| 2a8f737aab67305c9fda3ee56aa7953e97cee859 | https://github.com/Whitebolt/require-extra/blob/2a8f737aab67305c9fda3ee56aa7953e97cee859/src/require.js#L428-L434 |
44,949 | ciena-frost/ember-frost-page-title | index.js | function (type, config) {
// fail if we don't have a default for frost-page-title in the config
if (!config.APP || !config.APP['frost-page-title'].defaultTitle) {
return
}
// insert default page title
if (type === 'page-title') {
return config.APP['frost-page-title'].defaultTitle
}
} | javascript | function (type, config) {
// fail if we don't have a default for frost-page-title in the config
if (!config.APP || !config.APP['frost-page-title'].defaultTitle) {
return
}
// insert default page title
if (type === 'page-title') {
return config.APP['frost-page-title'].defaultTitle
}
} | [
"function",
"(",
"type",
",",
"config",
")",
"{",
"// fail if we don't have a default for frost-page-title in the config",
"if",
"(",
"!",
"config",
".",
"APP",
"||",
"!",
"config",
".",
"APP",
"[",
"'frost-page-title'",
"]",
".",
"defaultTitle",
")",
"{",
"return",
"}",
"// insert default page title",
"if",
"(",
"type",
"===",
"'page-title'",
")",
"{",
"return",
"config",
".",
"APP",
"[",
"'frost-page-title'",
"]",
".",
"defaultTitle",
"}",
"}"
]
| sets the default page title on build
@param {string} type - type of content in which to be included
@param {object} config - the app config object
@returns {string|undefined} - string for content | [
"sets",
"the",
"default",
"page",
"title",
"on",
"build"
]
| a8c85180f522ad7fb6a2836122867bc8178d69c8 | https://github.com/ciena-frost/ember-frost-page-title/blob/a8c85180f522ad7fb6a2836122867bc8178d69c8/index.js#L13-L23 |
|
44,950 | jonschlinkert/file-contents | index.js | contentsAsync | function contentsAsync(file, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof cb !== 'function') {
throw new TypeError('expected a callback function');
}
if (!utils.isObject(file)) {
cb(new TypeError('expected file to be an object'));
return;
}
contentsSync(file, options);
cb(null, file);
} | javascript | function contentsAsync(file, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof cb !== 'function') {
throw new TypeError('expected a callback function');
}
if (!utils.isObject(file)) {
cb(new TypeError('expected file to be an object'));
return;
}
contentsSync(file, options);
cb(null, file);
} | [
"function",
"contentsAsync",
"(",
"file",
",",
"options",
",",
"cb",
")",
"{",
"if",
"(",
"typeof",
"options",
"===",
"'function'",
")",
"{",
"cb",
"=",
"options",
";",
"options",
"=",
"{",
"}",
";",
"}",
"if",
"(",
"typeof",
"cb",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected a callback function'",
")",
";",
"}",
"if",
"(",
"!",
"utils",
".",
"isObject",
"(",
"file",
")",
")",
"{",
"cb",
"(",
"new",
"TypeError",
"(",
"'expected file to be an object'",
")",
")",
";",
"return",
";",
"}",
"contentsSync",
"(",
"file",
",",
"options",
")",
";",
"cb",
"(",
"null",
",",
"file",
")",
";",
"}"
]
| Async method for getting `file.contents`.
@param {Object} `file`
@param {Object} `options`
@param {Function} `cb`
@return {Object} | [
"Async",
"method",
"for",
"getting",
"file",
".",
"contents",
"."
]
| a53dcc62a1a529fc5f8b1dc0fa2a76a3196236fa | https://github.com/jonschlinkert/file-contents/blob/a53dcc62a1a529fc5f8b1dc0fa2a76a3196236fa/index.js#L29-L46 |
44,951 | jonschlinkert/file-contents | index.js | contentsSync | function contentsSync(file, options) {
if (!utils.isObject(file)) {
throw new TypeError('expected file to be an object');
}
try {
// ideally we want to stat the real, initial filepath
file.stat = fs.lstatSync(file.history[0]);
} catch (err) {
try {
// if that doesn't work, try again
file.stat = fs.lstatSync(file.path);
} catch (err) {
file.stat = new fs.Stats();
}
}
utils.syncContents(file, options);
return file;
} | javascript | function contentsSync(file, options) {
if (!utils.isObject(file)) {
throw new TypeError('expected file to be an object');
}
try {
// ideally we want to stat the real, initial filepath
file.stat = fs.lstatSync(file.history[0]);
} catch (err) {
try {
// if that doesn't work, try again
file.stat = fs.lstatSync(file.path);
} catch (err) {
file.stat = new fs.Stats();
}
}
utils.syncContents(file, options);
return file;
} | [
"function",
"contentsSync",
"(",
"file",
",",
"options",
")",
"{",
"if",
"(",
"!",
"utils",
".",
"isObject",
"(",
"file",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'expected file to be an object'",
")",
";",
"}",
"try",
"{",
"// ideally we want to stat the real, initial filepath",
"file",
".",
"stat",
"=",
"fs",
".",
"lstatSync",
"(",
"file",
".",
"history",
"[",
"0",
"]",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"try",
"{",
"// if that doesn't work, try again",
"file",
".",
"stat",
"=",
"fs",
".",
"lstatSync",
"(",
"file",
".",
"path",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"file",
".",
"stat",
"=",
"new",
"fs",
".",
"Stats",
"(",
")",
";",
"}",
"}",
"utils",
".",
"syncContents",
"(",
"file",
",",
"options",
")",
";",
"return",
"file",
";",
"}"
]
| Sync method for getting `file.contents`.
@param {Object} `file`
@param {Object} `options`
@return {Object} | [
"Sync",
"method",
"for",
"getting",
"file",
".",
"contents",
"."
]
| a53dcc62a1a529fc5f8b1dc0fa2a76a3196236fa | https://github.com/jonschlinkert/file-contents/blob/a53dcc62a1a529fc5f8b1dc0fa2a76a3196236fa/index.js#L56-L75 |
44,952 | vid/SenseBase | lib/utils.js | retrieve | function retrieve(uri, callback) {
var buffer = '';
http.get(uri, function(res) {
res.on('data', function (chunk) {
buffer += chunk;
});
res.on('end', function() {
callback(null, buffer);
});
}).on('error', function(e) {
callback(e);
});
} | javascript | function retrieve(uri, callback) {
var buffer = '';
http.get(uri, function(res) {
res.on('data', function (chunk) {
buffer += chunk;
});
res.on('end', function() {
callback(null, buffer);
});
}).on('error', function(e) {
callback(e);
});
} | [
"function",
"retrieve",
"(",
"uri",
",",
"callback",
")",
"{",
"var",
"buffer",
"=",
"''",
";",
"http",
".",
"get",
"(",
"uri",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"buffer",
"+=",
"chunk",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
")",
"{",
"callback",
"(",
"null",
",",
"buffer",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"e",
")",
"{",
"callback",
"(",
"e",
")",
";",
"}",
")",
";",
"}"
]
| perform a GET then callback content | [
"perform",
"a",
"GET",
"then",
"callback",
"content"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/utils.js#L82-L94 |
44,953 | vid/SenseBase | lib/utils.js | doPost | function doPost(options, data, callback) {
var buffer = '';
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
buffer += chunk;
});
res.on('end', function(err) {
callback(err, buffer);
});
}).on('error', function(e) {
callback(e);
});
if (data && data.length) {
req.write(data);
}
req.end();
} | javascript | function doPost(options, data, callback) {
var buffer = '';
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
buffer += chunk;
});
res.on('end', function(err) {
callback(err, buffer);
});
}).on('error', function(e) {
callback(e);
});
if (data && data.length) {
req.write(data);
}
req.end();
} | [
"function",
"doPost",
"(",
"options",
",",
"data",
",",
"callback",
")",
"{",
"var",
"buffer",
"=",
"''",
";",
"var",
"req",
"=",
"http",
".",
"request",
"(",
"options",
",",
"function",
"(",
"res",
")",
"{",
"res",
".",
"setEncoding",
"(",
"'utf8'",
")",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"buffer",
"+=",
"chunk",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"buffer",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"e",
")",
"{",
"callback",
"(",
"e",
")",
";",
"}",
")",
";",
"if",
"(",
"data",
"&&",
"data",
".",
"length",
")",
"{",
"req",
".",
"write",
"(",
"data",
")",
";",
"}",
"req",
".",
"end",
"(",
")",
";",
"}"
]
| perform a POST then callback contents | [
"perform",
"a",
"POST",
"then",
"callback",
"contents"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/lib/utils.js#L97-L115 |
44,954 | wunderbyte/grunt-spiritual-build | trash/super.NOTUSED.js | checkextension | function checkextension(subword) {
var checknext = true;
if(findbehind(subword) && endshere(subword)) {
wordindex = startindex(subword);
prototype = getprototypeat(wordindex);
curlcount = 0;
prencount = 0;
checknext = false;
}
return checknext;
} | javascript | function checkextension(subword) {
var checknext = true;
if(findbehind(subword) && endshere(subword)) {
wordindex = startindex(subword);
prototype = getprototypeat(wordindex);
curlcount = 0;
prencount = 0;
checknext = false;
}
return checknext;
} | [
"function",
"checkextension",
"(",
"subword",
")",
"{",
"var",
"checknext",
"=",
"true",
";",
"if",
"(",
"findbehind",
"(",
"subword",
")",
"&&",
"endshere",
"(",
"subword",
")",
")",
"{",
"wordindex",
"=",
"startindex",
"(",
"subword",
")",
";",
"prototype",
"=",
"getprototypeat",
"(",
"wordindex",
")",
";",
"curlcount",
"=",
"0",
";",
"prencount",
"=",
"0",
";",
"checknext",
"=",
"false",
";",
"}",
"return",
"checknext",
";",
"}"
]
| Did the code just itend to extend or mixin something?
If so, we switch to super keyword replacement modus.
@param {string} subword
@returns {boolean} True if no match (so check another match) | [
"Did",
"the",
"code",
"just",
"itend",
"to",
"extend",
"or",
"mixin",
"something?",
"If",
"so",
"we",
"switch",
"to",
"super",
"keyword",
"replacement",
"modus",
"."
]
| 6676b699904fe72f899fe7b88871de5ef23a23c3 | https://github.com/wunderbyte/grunt-spiritual-build/blob/6676b699904fe72f899fe7b88871de5ef23a23c3/trash/super.NOTUSED.js#L61-L71 |
44,955 | wunderbyte/grunt-spiritual-build | trash/super.NOTUSED.js | checksupercall | function checksupercall() {
keywords.every(function(keyword) {
if (findbehind(keyword)) {
supercall = true;
methodname = true;
buffer = buffer.substr(0, startindex(keyword));
buffer += prototype;
return false;
}
return true;
});
} | javascript | function checksupercall() {
keywords.every(function(keyword) {
if (findbehind(keyword)) {
supercall = true;
methodname = true;
buffer = buffer.substr(0, startindex(keyword));
buffer += prototype;
return false;
}
return true;
});
} | [
"function",
"checksupercall",
"(",
")",
"{",
"keywords",
".",
"every",
"(",
"function",
"(",
"keyword",
")",
"{",
"if",
"(",
"findbehind",
"(",
"keyword",
")",
")",
"{",
"supercall",
"=",
"true",
";",
"methodname",
"=",
"true",
";",
"buffer",
"=",
"buffer",
".",
"substr",
"(",
"0",
",",
"startindex",
"(",
"keyword",
")",
")",
";",
"buffer",
"+=",
"prototype",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
")",
";",
"}"
]
| Did the code just intend a supercall? | [
"Did",
"the",
"code",
"just",
"intend",
"a",
"supercall?"
]
| 6676b699904fe72f899fe7b88871de5ef23a23c3 | https://github.com/wunderbyte/grunt-spiritual-build/blob/6676b699904fe72f899fe7b88871de5ef23a23c3/trash/super.NOTUSED.js#L76-L87 |
44,956 | wunderbyte/grunt-spiritual-build | trash/super.NOTUSED.js | endshere | function endshere(subword) {
var nextindex = charindex + 1;
return input.length === nextindex ||
!input[nextindex].match(METHODNAME);
} | javascript | function endshere(subword) {
var nextindex = charindex + 1;
return input.length === nextindex ||
!input[nextindex].match(METHODNAME);
} | [
"function",
"endshere",
"(",
"subword",
")",
"{",
"var",
"nextindex",
"=",
"charindex",
"+",
"1",
";",
"return",
"input",
".",
"length",
"===",
"nextindex",
"||",
"!",
"input",
"[",
"nextindex",
"]",
".",
"match",
"(",
"METHODNAME",
")",
";",
"}"
]
| Magic word is not a substring of a longer word?
@param {string} subword
@returns {booleans} | [
"Magic",
"word",
"is",
"not",
"a",
"substring",
"of",
"a",
"longer",
"word?"
]
| 6676b699904fe72f899fe7b88871de5ef23a23c3 | https://github.com/wunderbyte/grunt-spiritual-build/blob/6676b699904fe72f899fe7b88871de5ef23a23c3/trash/super.NOTUSED.js#L122-L126 |
44,957 | wunderbyte/grunt-spiritual-build | trash/super.NOTUSED.js | flush | function flush() {
output += buffer;
output += character;
buffer = '';
supercall = false;
methodname = false;
superargs = false;
} | javascript | function flush() {
output += buffer;
output += character;
buffer = '';
supercall = false;
methodname = false;
superargs = false;
} | [
"function",
"flush",
"(",
")",
"{",
"output",
"+=",
"buffer",
";",
"output",
"+=",
"character",
";",
"buffer",
"=",
"''",
";",
"supercall",
"=",
"false",
";",
"methodname",
"=",
"false",
";",
"superargs",
"=",
"false",
";",
"}"
]
| Flush buffer to output. | [
"Flush",
"buffer",
"to",
"output",
"."
]
| 6676b699904fe72f899fe7b88871de5ef23a23c3 | https://github.com/wunderbyte/grunt-spiritual-build/blob/6676b699904fe72f899fe7b88871de5ef23a23c3/trash/super.NOTUSED.js#L175-L182 |
44,958 | wunderbyte/grunt-spiritual-build | trash/super.NOTUSED.js | morechars | function morechars() {
switch (character) {
case ';':
flush();
break;
case '=':
case '\'':
case '"':
if(!supercall) {
flush();
}
break;
default:
if (supercall) {
processsupercall();
}
buffer += character;
if (prototype && !supercall) {
checksupercall();
}
if(!prototype) {
checkextensions();
}
break;
}
} | javascript | function morechars() {
switch (character) {
case ';':
flush();
break;
case '=':
case '\'':
case '"':
if(!supercall) {
flush();
}
break;
default:
if (supercall) {
processsupercall();
}
buffer += character;
if (prototype && !supercall) {
checksupercall();
}
if(!prototype) {
checkextensions();
}
break;
}
} | [
"function",
"morechars",
"(",
")",
"{",
"switch",
"(",
"character",
")",
"{",
"case",
"';'",
":",
"flush",
"(",
")",
";",
"break",
";",
"case",
"'='",
":",
"case",
"'\\''",
":",
"case",
"'\"'",
":",
"if",
"(",
"!",
"supercall",
")",
"{",
"flush",
"(",
")",
";",
"}",
"break",
";",
"default",
":",
"if",
"(",
"supercall",
")",
"{",
"processsupercall",
"(",
")",
";",
"}",
"buffer",
"+=",
"character",
";",
"if",
"(",
"prototype",
"&&",
"!",
"supercall",
")",
"{",
"checksupercall",
"(",
")",
";",
"}",
"if",
"(",
"!",
"prototype",
")",
"{",
"checkextensions",
"(",
")",
";",
"}",
"break",
";",
"}",
"}"
]
| Process chars in another way. | [
"Process",
"chars",
"in",
"another",
"way",
"."
]
| 6676b699904fe72f899fe7b88871de5ef23a23c3 | https://github.com/wunderbyte/grunt-spiritual-build/blob/6676b699904fe72f899fe7b88871de5ef23a23c3/trash/super.NOTUSED.js#L221-L246 |
44,959 | feedhenry/fh-reportingclient | lib/sync.js | reqeueBatch | function reqeueBatch(times,interval,batch) {
async.retry({times: times, interval: interval}, function(cb) {
syncBatch(batch,cb);
}, function done(err) {
if (err) {
log.error("failed to sync message batch", {err: err, data: batch});
}
});
} | javascript | function reqeueBatch(times,interval,batch) {
async.retry({times: times, interval: interval}, function(cb) {
syncBatch(batch,cb);
}, function done(err) {
if (err) {
log.error("failed to sync message batch", {err: err, data: batch});
}
});
} | [
"function",
"reqeueBatch",
"(",
"times",
",",
"interval",
",",
"batch",
")",
"{",
"async",
".",
"retry",
"(",
"{",
"times",
":",
"times",
",",
"interval",
":",
"interval",
"}",
",",
"function",
"(",
"cb",
")",
"{",
"syncBatch",
"(",
"batch",
",",
"cb",
")",
";",
"}",
",",
"function",
"done",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"log",
".",
"error",
"(",
"\"failed to sync message batch\"",
",",
"{",
"err",
":",
"err",
",",
"data",
":",
"batch",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| requeue the send of messages on failure. stopping after times or first success | [
"requeue",
"the",
"send",
"of",
"messages",
"on",
"failure",
".",
"stopping",
"after",
"times",
"or",
"first",
"success"
]
| a0e2c959ce73addbf138d48f3ed46ef87229ae1a | https://github.com/feedhenry/fh-reportingclient/blob/a0e2c959ce73addbf138d48f3ed46ef87229ae1a/lib/sync.js#L18-L26 |
44,960 | feedhenry/fh-reportingclient | lib/sync.js | syncBatch | function syncBatch(batch, cb) {
if (batch && batch.length > 0) {
var mbaasClient = new MBaaSClient(ENVIRONMENT, {
url: URL.format(PROTOCOL + '://' + HOST),
accessKey: ACCESS_KEY,
project: PROJECT,
app: GUID,
appApiKey: API_KEY
});
// /api/app/:domain/:environment/:projectid/:appid/message/:topic with [] or messages for data (a batch)
mbaasClient.app.message.sendbatch({
'host': HOST,
'environment': ENVIRONMENT,
'domain': DOMAIN,
'data': batch,
'topic': 'fhact' //the only other topic is fhweb which is not longer used
}, function(err) {
if (err) {
return cb(err, {message: 'Error sending message batch to MBaaS', host: HOST, environment: ENVIRONMENT, domain: DOMAIN, topic:'fhact', batch: batch});
} else {
return cb(undefined, {message: 'Batch sent to MBaaS'});
}
});
} else {
return cb(undefined, {message: 'Batch empty...nothing to sync at this time'});
}
} | javascript | function syncBatch(batch, cb) {
if (batch && batch.length > 0) {
var mbaasClient = new MBaaSClient(ENVIRONMENT, {
url: URL.format(PROTOCOL + '://' + HOST),
accessKey: ACCESS_KEY,
project: PROJECT,
app: GUID,
appApiKey: API_KEY
});
// /api/app/:domain/:environment/:projectid/:appid/message/:topic with [] or messages for data (a batch)
mbaasClient.app.message.sendbatch({
'host': HOST,
'environment': ENVIRONMENT,
'domain': DOMAIN,
'data': batch,
'topic': 'fhact' //the only other topic is fhweb which is not longer used
}, function(err) {
if (err) {
return cb(err, {message: 'Error sending message batch to MBaaS', host: HOST, environment: ENVIRONMENT, domain: DOMAIN, topic:'fhact', batch: batch});
} else {
return cb(undefined, {message: 'Batch sent to MBaaS'});
}
});
} else {
return cb(undefined, {message: 'Batch empty...nothing to sync at this time'});
}
} | [
"function",
"syncBatch",
"(",
"batch",
",",
"cb",
")",
"{",
"if",
"(",
"batch",
"&&",
"batch",
".",
"length",
">",
"0",
")",
"{",
"var",
"mbaasClient",
"=",
"new",
"MBaaSClient",
"(",
"ENVIRONMENT",
",",
"{",
"url",
":",
"URL",
".",
"format",
"(",
"PROTOCOL",
"+",
"'://'",
"+",
"HOST",
")",
",",
"accessKey",
":",
"ACCESS_KEY",
",",
"project",
":",
"PROJECT",
",",
"app",
":",
"GUID",
",",
"appApiKey",
":",
"API_KEY",
"}",
")",
";",
"// /api/app/:domain/:environment/:projectid/:appid/message/:topic with [] or messages for data (a batch)",
"mbaasClient",
".",
"app",
".",
"message",
".",
"sendbatch",
"(",
"{",
"'host'",
":",
"HOST",
",",
"'environment'",
":",
"ENVIRONMENT",
",",
"'domain'",
":",
"DOMAIN",
",",
"'data'",
":",
"batch",
",",
"'topic'",
":",
"'fhact'",
"//the only other topic is fhweb which is not longer used",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"{",
"message",
":",
"'Error sending message batch to MBaaS'",
",",
"host",
":",
"HOST",
",",
"environment",
":",
"ENVIRONMENT",
",",
"domain",
":",
"DOMAIN",
",",
"topic",
":",
"'fhact'",
",",
"batch",
":",
"batch",
"}",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"undefined",
",",
"{",
"message",
":",
"'Batch sent to MBaaS'",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"return",
"cb",
"(",
"undefined",
",",
"{",
"message",
":",
"'Batch empty...nothing to sync at this time'",
"}",
")",
";",
"}",
"}"
]
| send data to fhmbaas | [
"send",
"data",
"to",
"fhmbaas"
]
| a0e2c959ce73addbf138d48f3ed46ef87229ae1a | https://github.com/feedhenry/fh-reportingclient/blob/a0e2c959ce73addbf138d48f3ed46ef87229ae1a/lib/sync.js#L29-L55 |
44,961 | haeric/bailey.js | src/compiler.js | normalizeBlocks | function normalizeBlocks(input) {
var numberOfLinesToIndent = 0;
var thisLineContainsStuff = false;
var thisLinesIndentation = '';
var out = '';
for (var i = 0; i < input.length; i++) {
var chr = input[i];
if (chr == '\r') {
continue;
}
if (chr === '\n') {
if (!thisLineContainsStuff) {
numberOfLinesToIndent++;
} else {
out += '\n';
}
thisLineContainsStuff = false;
thisLinesIndentation = '';
continue;
}
if (!thisLineContainsStuff && (chr === ' ' || chr === '\t')) {
thisLinesIndentation += chr;
continue;
}
if (chr !== ' ' || chr !== '\t') {
if (!thisLineContainsStuff) {
for (var j = 0; j < numberOfLinesToIndent; j++) {
out += thisLinesIndentation + '\n';
}
out += thisLinesIndentation + chr;
} else {
out += chr;
}
numberOfLinesToIndent = 0;
thisLineContainsStuff = true;
}
}
return out;
} | javascript | function normalizeBlocks(input) {
var numberOfLinesToIndent = 0;
var thisLineContainsStuff = false;
var thisLinesIndentation = '';
var out = '';
for (var i = 0; i < input.length; i++) {
var chr = input[i];
if (chr == '\r') {
continue;
}
if (chr === '\n') {
if (!thisLineContainsStuff) {
numberOfLinesToIndent++;
} else {
out += '\n';
}
thisLineContainsStuff = false;
thisLinesIndentation = '';
continue;
}
if (!thisLineContainsStuff && (chr === ' ' || chr === '\t')) {
thisLinesIndentation += chr;
continue;
}
if (chr !== ' ' || chr !== '\t') {
if (!thisLineContainsStuff) {
for (var j = 0; j < numberOfLinesToIndent; j++) {
out += thisLinesIndentation + '\n';
}
out += thisLinesIndentation + chr;
} else {
out += chr;
}
numberOfLinesToIndent = 0;
thisLineContainsStuff = true;
}
}
return out;
} | [
"function",
"normalizeBlocks",
"(",
"input",
")",
"{",
"var",
"numberOfLinesToIndent",
"=",
"0",
";",
"var",
"thisLineContainsStuff",
"=",
"false",
";",
"var",
"thisLinesIndentation",
"=",
"''",
";",
"var",
"out",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"input",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"chr",
"=",
"input",
"[",
"i",
"]",
";",
"if",
"(",
"chr",
"==",
"'\\r'",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"chr",
"===",
"'\\n'",
")",
"{",
"if",
"(",
"!",
"thisLineContainsStuff",
")",
"{",
"numberOfLinesToIndent",
"++",
";",
"}",
"else",
"{",
"out",
"+=",
"'\\n'",
";",
"}",
"thisLineContainsStuff",
"=",
"false",
";",
"thisLinesIndentation",
"=",
"''",
";",
"continue",
";",
"}",
"if",
"(",
"!",
"thisLineContainsStuff",
"&&",
"(",
"chr",
"===",
"' '",
"||",
"chr",
"===",
"'\\t'",
")",
")",
"{",
"thisLinesIndentation",
"+=",
"chr",
";",
"continue",
";",
"}",
"if",
"(",
"chr",
"!==",
"' '",
"||",
"chr",
"!==",
"'\\t'",
")",
"{",
"if",
"(",
"!",
"thisLineContainsStuff",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"numberOfLinesToIndent",
";",
"j",
"++",
")",
"{",
"out",
"+=",
"thisLinesIndentation",
"+",
"'\\n'",
";",
"}",
"out",
"+=",
"thisLinesIndentation",
"+",
"chr",
";",
"}",
"else",
"{",
"out",
"+=",
"chr",
";",
"}",
"numberOfLinesToIndent",
"=",
"0",
";",
"thisLineContainsStuff",
"=",
"true",
";",
"}",
"}",
"return",
"out",
";",
"}"
]
| Whenever we hit an indented block, make sure all preceding empty lines are made to have this indentation level | [
"Whenever",
"we",
"hit",
"an",
"indented",
"block",
"make",
"sure",
"all",
"preceding",
"empty",
"lines",
"are",
"made",
"to",
"have",
"this",
"indentation",
"level"
]
| c8152d809d5be4ca48d059b907a8ba896bf1245b | https://github.com/haeric/bailey.js/blob/c8152d809d5be4ca48d059b907a8ba896bf1245b/src/compiler.js#L9-L62 |
44,962 | commonform/cftemplate | index.js | addPosition | function addPosition (error, message) {
error.message = (
message + ' at ' +
'line ' + token.position.line + ', ' +
'column ' + token.position.column
)
error.position = token.position
return error
} | javascript | function addPosition (error, message) {
error.message = (
message + ' at ' +
'line ' + token.position.line + ', ' +
'column ' + token.position.column
)
error.position = token.position
return error
} | [
"function",
"addPosition",
"(",
"error",
",",
"message",
")",
"{",
"error",
".",
"message",
"=",
"(",
"message",
"+",
"' at '",
"+",
"'line '",
"+",
"token",
".",
"position",
".",
"line",
"+",
"', '",
"+",
"'column '",
"+",
"token",
".",
"position",
".",
"column",
")",
"error",
".",
"position",
"=",
"token",
".",
"position",
"return",
"error",
"}"
]
| Add position information to errors. | [
"Add",
"position",
"information",
"to",
"errors",
"."
]
| 259b9d59e8a39c4505e185249a2f9055e91dddf9 | https://github.com/commonform/cftemplate/blob/259b9d59e8a39c4505e185249a2f9055e91dddf9/index.js#L52-L60 |
44,963 | commonform/cftemplate | index.js | format | function format (form) {
return formToMarkup(form)
// Split lines.
.split('\n')
.map(function (line, index) {
return EMPTY_LINE.test(line)
// If the line is empty, leave it empty.
? line
: index === 0
? line
// On subsequent lines with indentation, add spaces
// to existing indentation.
: ' '.repeat(token.position.column - 1) + line
})
.join('\n')
} | javascript | function format (form) {
return formToMarkup(form)
// Split lines.
.split('\n')
.map(function (line, index) {
return EMPTY_LINE.test(line)
// If the line is empty, leave it empty.
? line
: index === 0
? line
// On subsequent lines with indentation, add spaces
// to existing indentation.
: ' '.repeat(token.position.column - 1) + line
})
.join('\n')
} | [
"function",
"format",
"(",
"form",
")",
"{",
"return",
"formToMarkup",
"(",
"form",
")",
"// Split lines.",
".",
"split",
"(",
"'\\n'",
")",
".",
"map",
"(",
"function",
"(",
"line",
",",
"index",
")",
"{",
"return",
"EMPTY_LINE",
".",
"test",
"(",
"line",
")",
"// If the line is empty, leave it empty.",
"?",
"line",
":",
"index",
"===",
"0",
"?",
"line",
"// On subsequent lines with indentation, add spaces",
"// to existing indentation.",
":",
"' '",
".",
"repeat",
"(",
"token",
".",
"position",
".",
"column",
"-",
"1",
")",
"+",
"line",
"}",
")",
".",
"join",
"(",
"'\\n'",
")",
"}"
]
| Format markup for insertion at the current position. | [
"Format",
"markup",
"for",
"insertion",
"at",
"the",
"current",
"position",
"."
]
| 259b9d59e8a39c4505e185249a2f9055e91dddf9 | https://github.com/commonform/cftemplate/blob/259b9d59e8a39c4505e185249a2f9055e91dddf9/index.js#L63-L78 |
44,964 | commonform/cftemplate | index.js | function (path, done) {
fs.access(path, fs.R_OK, function (error) {
done(!error)
})
} | javascript | function (path, done) {
fs.access(path, fs.R_OK, function (error) {
done(!error)
})
} | [
"function",
"(",
"path",
",",
"done",
")",
"{",
"fs",
".",
"access",
"(",
"path",
",",
"fs",
".",
"R_OK",
",",
"function",
"(",
"error",
")",
"{",
"done",
"(",
"!",
"error",
")",
"}",
")",
"}"
]
| Can we read the file? | [
"Can",
"we",
"read",
"the",
"file?"
]
| 259b9d59e8a39c4505e185249a2f9055e91dddf9 | https://github.com/commonform/cftemplate/blob/259b9d59e8a39c4505e185249a2f9055e91dddf9/index.js#L127-L131 |
|
44,965 | liziqiang/simple-webpack-progress-plugin | index.js | logStage | function logStage(stage) {
if (!spinner) {
spinner = ora({
color: 'green',
text: chalk.green(defaults.text)
}).info();
}
if (!stage || (lastStage && lastStage !== stage)) {
spinner.succeed(chalk.grey(lastStage));
}
if (stage) {
spinner.start(stage);
}
} | javascript | function logStage(stage) {
if (!spinner) {
spinner = ora({
color: 'green',
text: chalk.green(defaults.text)
}).info();
}
if (!stage || (lastStage && lastStage !== stage)) {
spinner.succeed(chalk.grey(lastStage));
}
if (stage) {
spinner.start(stage);
}
} | [
"function",
"logStage",
"(",
"stage",
")",
"{",
"if",
"(",
"!",
"spinner",
")",
"{",
"spinner",
"=",
"ora",
"(",
"{",
"color",
":",
"'green'",
",",
"text",
":",
"chalk",
".",
"green",
"(",
"defaults",
".",
"text",
")",
"}",
")",
".",
"info",
"(",
")",
";",
"}",
"if",
"(",
"!",
"stage",
"||",
"(",
"lastStage",
"&&",
"lastStage",
"!==",
"stage",
")",
")",
"{",
"spinner",
".",
"succeed",
"(",
"chalk",
".",
"grey",
"(",
"lastStage",
")",
")",
";",
"}",
"if",
"(",
"stage",
")",
"{",
"spinner",
".",
"start",
"(",
"stage",
")",
";",
"}",
"}"
]
| output stage message | [
"output",
"stage",
"message"
]
| 6dba2a1aa81de5d515afc72bae05237834ca73ce | https://github.com/liziqiang/simple-webpack-progress-plugin/blob/6dba2a1aa81de5d515afc72bae05237834ca73ce/index.js#L25-L38 |
44,966 | vid/SenseBase | web/lib/results.js | addUpdated | function addUpdated(results) {
results.forEach(function(result) {
result = normalizeResult(result);
if (!lastQuery.results.hits) {
lastQuery = { results: { hits: { total : 0, hits: [] } } };
} else {
var i = 0, l = lastQuery.results.hits.hits.length;
for (i; i < l; i++) {
if (lastQuery.results.hits.hits[i]._source.uri === result._source.uri) {
lastQuery.results.hits.hits.splice(i, 1);
break;
}
}
}
lastQuery.results.hits.hits.unshift(result);
});
updateResults(lastQuery);
} | javascript | function addUpdated(results) {
results.forEach(function(result) {
result = normalizeResult(result);
if (!lastQuery.results.hits) {
lastQuery = { results: { hits: { total : 0, hits: [] } } };
} else {
var i = 0, l = lastQuery.results.hits.hits.length;
for (i; i < l; i++) {
if (lastQuery.results.hits.hits[i]._source.uri === result._source.uri) {
lastQuery.results.hits.hits.splice(i, 1);
break;
}
}
}
lastQuery.results.hits.hits.unshift(result);
});
updateResults(lastQuery);
} | [
"function",
"addUpdated",
"(",
"results",
")",
"{",
"results",
".",
"forEach",
"(",
"function",
"(",
"result",
")",
"{",
"result",
"=",
"normalizeResult",
"(",
"result",
")",
";",
"if",
"(",
"!",
"lastQuery",
".",
"results",
".",
"hits",
")",
"{",
"lastQuery",
"=",
"{",
"results",
":",
"{",
"hits",
":",
"{",
"total",
":",
"0",
",",
"hits",
":",
"[",
"]",
"}",
"}",
"}",
";",
"}",
"else",
"{",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"lastQuery",
".",
"results",
".",
"hits",
".",
"hits",
".",
"length",
";",
"for",
"(",
"i",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"lastQuery",
".",
"results",
".",
"hits",
".",
"hits",
"[",
"i",
"]",
".",
"_source",
".",
"uri",
"===",
"result",
".",
"_source",
".",
"uri",
")",
"{",
"lastQuery",
".",
"results",
".",
"hits",
".",
"hits",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"break",
";",
"}",
"}",
"}",
"lastQuery",
".",
"results",
".",
"hits",
".",
"hits",
".",
"unshift",
"(",
"result",
")",
";",
"}",
")",
";",
"updateResults",
"(",
"lastQuery",
")",
";",
"}"
]
| add updated items | [
"add",
"updated",
"items"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/lib/results.js#L90-L107 |
44,967 | vid/SenseBase | web/lib/results.js | normalizeResult | function normalizeResult(result) {
if (result.uri) {
console.log('normalizing', result);
if (!result._source) {
result._source = {};
}
['title', 'timestamp', 'uri', 'annotationSummary', 'annotations', 'visitors'].forEach(function(f) {
result._source[f] = result[f];
});
}
return result;
} | javascript | function normalizeResult(result) {
if (result.uri) {
console.log('normalizing', result);
if (!result._source) {
result._source = {};
}
['title', 'timestamp', 'uri', 'annotationSummary', 'annotations', 'visitors'].forEach(function(f) {
result._source[f] = result[f];
});
}
return result;
} | [
"function",
"normalizeResult",
"(",
"result",
")",
"{",
"if",
"(",
"result",
".",
"uri",
")",
"{",
"console",
".",
"log",
"(",
"'normalizing'",
",",
"result",
")",
";",
"if",
"(",
"!",
"result",
".",
"_source",
")",
"{",
"result",
".",
"_source",
"=",
"{",
"}",
";",
"}",
"[",
"'title'",
",",
"'timestamp'",
",",
"'uri'",
",",
"'annotationSummary'",
",",
"'annotations'",
",",
"'visitors'",
"]",
".",
"forEach",
"(",
"function",
"(",
"f",
")",
"{",
"result",
".",
"_source",
"[",
"f",
"]",
"=",
"result",
"[",
"f",
"]",
";",
"}",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| FIXME normalize fields between base and _source | [
"FIXME",
"normalize",
"fields",
"between",
"base",
"and",
"_source"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/lib/results.js#L116-L127 |
44,968 | vid/SenseBase | web/lib/results.js | gotResults | function gotResults(results) {
results.JSONquery = JSON.stringify(results.query, null, 2);
console.log('gotResults', results);
updateResults(results);
} | javascript | function gotResults(results) {
results.JSONquery = JSON.stringify(results.query, null, 2);
console.log('gotResults', results);
updateResults(results);
} | [
"function",
"gotResults",
"(",
"results",
")",
"{",
"results",
".",
"JSONquery",
"=",
"JSON",
".",
"stringify",
"(",
"results",
".",
"query",
",",
"null",
",",
"2",
")",
";",
"console",
".",
"log",
"(",
"'gotResults'",
",",
"results",
")",
";",
"updateResults",
"(",
"results",
")",
";",
"}"
]
| Query results were received | [
"Query",
"results",
"were",
"received"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/lib/results.js#L134-L138 |
44,969 | vid/SenseBase | web/lib/results.js | gotNavigation | function gotNavigation(results) {
console.log('gotNavigation', results, browser);
var browser;
if (results.navigator === 'treemap') {
browser = browseTreemap;
} else if (results.navigator === 'facet') {
browser = browseFacet;
} else if (results.navigator === 'cluster') {
browser = browseCluster;
} else if (results.navigator === 'debug') {
browser = browseDebug;
}
if (browser) {
$('.browse.sidebar').sidebar('show');
$('#browse').html();
browser.render('#browse', results, resultView, context);
} else {
$('.browse.sidebar').sidebar('hide');
}
} | javascript | function gotNavigation(results) {
console.log('gotNavigation', results, browser);
var browser;
if (results.navigator === 'treemap') {
browser = browseTreemap;
} else if (results.navigator === 'facet') {
browser = browseFacet;
} else if (results.navigator === 'cluster') {
browser = browseCluster;
} else if (results.navigator === 'debug') {
browser = browseDebug;
}
if (browser) {
$('.browse.sidebar').sidebar('show');
$('#browse').html();
browser.render('#browse', results, resultView, context);
} else {
$('.browse.sidebar').sidebar('hide');
}
} | [
"function",
"gotNavigation",
"(",
"results",
")",
"{",
"console",
".",
"log",
"(",
"'gotNavigation'",
",",
"results",
",",
"browser",
")",
";",
"var",
"browser",
";",
"if",
"(",
"results",
".",
"navigator",
"===",
"'treemap'",
")",
"{",
"browser",
"=",
"browseTreemap",
";",
"}",
"else",
"if",
"(",
"results",
".",
"navigator",
"===",
"'facet'",
")",
"{",
"browser",
"=",
"browseFacet",
";",
"}",
"else",
"if",
"(",
"results",
".",
"navigator",
"===",
"'cluster'",
")",
"{",
"browser",
"=",
"browseCluster",
";",
"}",
"else",
"if",
"(",
"results",
".",
"navigator",
"===",
"'debug'",
")",
"{",
"browser",
"=",
"browseDebug",
";",
"}",
"if",
"(",
"browser",
")",
"{",
"$",
"(",
"'.browse.sidebar'",
")",
".",
"sidebar",
"(",
"'show'",
")",
";",
"$",
"(",
"'#browse'",
")",
".",
"html",
"(",
")",
";",
"browser",
".",
"render",
"(",
"'#browse'",
",",
"results",
",",
"resultView",
",",
"context",
")",
";",
"}",
"else",
"{",
"$",
"(",
"'.browse.sidebar'",
")",
".",
"sidebar",
"(",
"'hide'",
")",
";",
"}",
"}"
]
| Navigation results to accompany results | [
"Navigation",
"results",
"to",
"accompany",
"results"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/lib/results.js#L141-L160 |
44,970 | vid/SenseBase | web/lib/results.js | updateResults | function updateResults(res) {
if (res === undefined) {
res = lastQuery;
}
var results = res.results;
lastQuery = res;
// content is being viewed or edited, delay updates
if (noUpdates) {
console.log('in noUpdates');
hasQueuedUpdates = true;
clearTimeout(queuedNotifier);
queuedNotifier = setInterval(function() { $('.toggle.item').toggleClass('red'); }, 2000);
return;
}
// clear queued notifier
$('.toggle.item').removeClass('red');
clearInterval(queuedNotifier);
$('.query.button').animate({opacity: 1}, 500, 'linear');
// use arbitrary rendering to fill results
var container = '#results';
$('.selected.fields').html('<option value="">Select a field</option>');
var baseFields = ['title'];
if (res.options.query.selectFields) {
res.options.query.selectFields.forEach(function(f) {
$('.selected.fields').append('<option>' + f + '</option>');
});
}
$('.all.fields').html('<option value="">Select a field</option>');
baseFields.forEach(function(f) {
$('.all.fields').append('<option>' + f + '</option>');
});
if (results.hits) {
$(container).html('');
$('#queryCount').html(results.hits.hits.length === results.hits.total ? results.hits.total : (results.hits.hits.length + '/' + results.hits.total));
resultView.render(container, res, context);
} else {
$(container).html('<i>No items.</i>');
$('#queryCount').html('0');
resultView.render(container, res, context);
}
} | javascript | function updateResults(res) {
if (res === undefined) {
res = lastQuery;
}
var results = res.results;
lastQuery = res;
// content is being viewed or edited, delay updates
if (noUpdates) {
console.log('in noUpdates');
hasQueuedUpdates = true;
clearTimeout(queuedNotifier);
queuedNotifier = setInterval(function() { $('.toggle.item').toggleClass('red'); }, 2000);
return;
}
// clear queued notifier
$('.toggle.item').removeClass('red');
clearInterval(queuedNotifier);
$('.query.button').animate({opacity: 1}, 500, 'linear');
// use arbitrary rendering to fill results
var container = '#results';
$('.selected.fields').html('<option value="">Select a field</option>');
var baseFields = ['title'];
if (res.options.query.selectFields) {
res.options.query.selectFields.forEach(function(f) {
$('.selected.fields').append('<option>' + f + '</option>');
});
}
$('.all.fields').html('<option value="">Select a field</option>');
baseFields.forEach(function(f) {
$('.all.fields').append('<option>' + f + '</option>');
});
if (results.hits) {
$(container).html('');
$('#queryCount').html(results.hits.hits.length === results.hits.total ? results.hits.total : (results.hits.hits.length + '/' + results.hits.total));
resultView.render(container, res, context);
} else {
$(container).html('<i>No items.</i>');
$('#queryCount').html('0');
resultView.render(container, res, context);
}
} | [
"function",
"updateResults",
"(",
"res",
")",
"{",
"if",
"(",
"res",
"===",
"undefined",
")",
"{",
"res",
"=",
"lastQuery",
";",
"}",
"var",
"results",
"=",
"res",
".",
"results",
";",
"lastQuery",
"=",
"res",
";",
"// content is being viewed or edited, delay updates",
"if",
"(",
"noUpdates",
")",
"{",
"console",
".",
"log",
"(",
"'in noUpdates'",
")",
";",
"hasQueuedUpdates",
"=",
"true",
";",
"clearTimeout",
"(",
"queuedNotifier",
")",
";",
"queuedNotifier",
"=",
"setInterval",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"'.toggle.item'",
")",
".",
"toggleClass",
"(",
"'red'",
")",
";",
"}",
",",
"2000",
")",
";",
"return",
";",
"}",
"// clear queued notifier",
"$",
"(",
"'.toggle.item'",
")",
".",
"removeClass",
"(",
"'red'",
")",
";",
"clearInterval",
"(",
"queuedNotifier",
")",
";",
"$",
"(",
"'.query.button'",
")",
".",
"animate",
"(",
"{",
"opacity",
":",
"1",
"}",
",",
"500",
",",
"'linear'",
")",
";",
"// use arbitrary rendering to fill results",
"var",
"container",
"=",
"'#results'",
";",
"$",
"(",
"'.selected.fields'",
")",
".",
"html",
"(",
"'<option value=\"\">Select a field</option>'",
")",
";",
"var",
"baseFields",
"=",
"[",
"'title'",
"]",
";",
"if",
"(",
"res",
".",
"options",
".",
"query",
".",
"selectFields",
")",
"{",
"res",
".",
"options",
".",
"query",
".",
"selectFields",
".",
"forEach",
"(",
"function",
"(",
"f",
")",
"{",
"$",
"(",
"'.selected.fields'",
")",
".",
"append",
"(",
"'<option>'",
"+",
"f",
"+",
"'</option>'",
")",
";",
"}",
")",
";",
"}",
"$",
"(",
"'.all.fields'",
")",
".",
"html",
"(",
"'<option value=\"\">Select a field</option>'",
")",
";",
"baseFields",
".",
"forEach",
"(",
"function",
"(",
"f",
")",
"{",
"$",
"(",
"'.all.fields'",
")",
".",
"append",
"(",
"'<option>'",
"+",
"f",
"+",
"'</option>'",
")",
";",
"}",
")",
";",
"if",
"(",
"results",
".",
"hits",
")",
"{",
"$",
"(",
"container",
")",
".",
"html",
"(",
"''",
")",
";",
"$",
"(",
"'#queryCount'",
")",
".",
"html",
"(",
"results",
".",
"hits",
".",
"hits",
".",
"length",
"===",
"results",
".",
"hits",
".",
"total",
"?",
"results",
".",
"hits",
".",
"total",
":",
"(",
"results",
".",
"hits",
".",
"hits",
".",
"length",
"+",
"'/'",
"+",
"results",
".",
"hits",
".",
"total",
")",
")",
";",
"resultView",
".",
"render",
"(",
"container",
",",
"res",
",",
"context",
")",
";",
"}",
"else",
"{",
"$",
"(",
"container",
")",
".",
"html",
"(",
"'<i>No items.</i>'",
")",
";",
"$",
"(",
"'#queryCount'",
")",
".",
"html",
"(",
"'0'",
")",
";",
"resultView",
".",
"render",
"(",
"container",
",",
"res",
",",
"context",
")",
";",
"}",
"}"
]
| Update displayed results using results view. If passed results are null, use lastQuery. | [
"Update",
"displayed",
"results",
"using",
"results",
"view",
".",
"If",
"passed",
"results",
"are",
"null",
"use",
"lastQuery",
"."
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/lib/results.js#L203-L246 |
44,971 | vid/SenseBase | web/lib/results.js | getSelected | function getSelected() {
var selected = [];
$('.selectItem').each(function() {
if ($(this).is(':checked')) {
selected.push(utils.deEncID($(this).attr('name').replace('cb_', '')));
}
});
return selected;
} | javascript | function getSelected() {
var selected = [];
$('.selectItem').each(function() {
if ($(this).is(':checked')) {
selected.push(utils.deEncID($(this).attr('name').replace('cb_', '')));
}
});
return selected;
} | [
"function",
"getSelected",
"(",
")",
"{",
"var",
"selected",
"=",
"[",
"]",
";",
"$",
"(",
"'.selectItem'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"$",
"(",
"this",
")",
".",
"is",
"(",
"':checked'",
")",
")",
"{",
"selected",
".",
"push",
"(",
"utils",
".",
"deEncID",
"(",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'name'",
")",
".",
"replace",
"(",
"'cb_'",
",",
"''",
")",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"selected",
";",
"}"
]
| return all items selected | [
"return",
"all",
"items",
"selected"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/web/lib/results.js#L265-L273 |
44,972 | vladaspasic/ember-cli-data-validation | addon/error.js | ValidationError | function ValidationError(message, errors) {
Error.call(this, message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ValidationError);
}
this.message = message;
this.errors = errors;
} | javascript | function ValidationError(message, errors) {
Error.call(this, message);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ValidationError);
}
this.message = message;
this.errors = errors;
} | [
"function",
"ValidationError",
"(",
"message",
",",
"errors",
")",
"{",
"Error",
".",
"call",
"(",
"this",
",",
"message",
")",
";",
"if",
"(",
"Error",
".",
"captureStackTrace",
")",
"{",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"ValidationError",
")",
";",
"}",
"this",
".",
"message",
"=",
"message",
";",
"this",
".",
"errors",
"=",
"errors",
";",
"}"
]
| Error thrown when a Model validation fails.
This error contains the `DS.Errors` object from the Model.
@class ValidationError
@extends {Error}
@param {Srting} message
@param {DS.Errors} errors | [
"Error",
"thrown",
"when",
"a",
"Model",
"validation",
"fails",
"."
]
| 08ee8694b9276bf7cbb40e8bc69c52592bb512d3 | https://github.com/vladaspasic/ember-cli-data-validation/blob/08ee8694b9276bf7cbb40e8bc69c52592bb512d3/addon/error.js#L11-L20 |
44,973 | socialally/air | lib/air.js | Air | function Air(el, context) {
if(!(this instanceof Air)) {
return new Air(el, context);
}
if(typeof context === 'string') {
context = document.querySelector(context);
}else if(context instanceof Air) {
context = context.get(0);
}
context = context || document;
// NOTE: do not pass empty string to querySelectorAll
if(!arguments.length || el === '') {
this.dom = [];
}else{
this.dom = typeof el === 'string' ? context.querySelectorAll(el) : el;
}
if(el instanceof Air) {
this.dom = el.dom.slice(0);
}else if(!Array.isArray(el)) {
if(this.dom instanceof NodeList) {
this.dom = Array.prototype.slice.call(this.dom);
}else if(el) {
this.dom = ((el instanceof Node) || el === window) ? [el] : [];
}
}
// shortcut to Array.prototype.slice
this.slice = Array.prototype.slice;
} | javascript | function Air(el, context) {
if(!(this instanceof Air)) {
return new Air(el, context);
}
if(typeof context === 'string') {
context = document.querySelector(context);
}else if(context instanceof Air) {
context = context.get(0);
}
context = context || document;
// NOTE: do not pass empty string to querySelectorAll
if(!arguments.length || el === '') {
this.dom = [];
}else{
this.dom = typeof el === 'string' ? context.querySelectorAll(el) : el;
}
if(el instanceof Air) {
this.dom = el.dom.slice(0);
}else if(!Array.isArray(el)) {
if(this.dom instanceof NodeList) {
this.dom = Array.prototype.slice.call(this.dom);
}else if(el) {
this.dom = ((el instanceof Node) || el === window) ? [el] : [];
}
}
// shortcut to Array.prototype.slice
this.slice = Array.prototype.slice;
} | [
"function",
"Air",
"(",
"el",
",",
"context",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Air",
")",
")",
"{",
"return",
"new",
"Air",
"(",
"el",
",",
"context",
")",
";",
"}",
"if",
"(",
"typeof",
"context",
"===",
"'string'",
")",
"{",
"context",
"=",
"document",
".",
"querySelector",
"(",
"context",
")",
";",
"}",
"else",
"if",
"(",
"context",
"instanceof",
"Air",
")",
"{",
"context",
"=",
"context",
".",
"get",
"(",
"0",
")",
";",
"}",
"context",
"=",
"context",
"||",
"document",
";",
"// NOTE: do not pass empty string to querySelectorAll",
"if",
"(",
"!",
"arguments",
".",
"length",
"||",
"el",
"===",
"''",
")",
"{",
"this",
".",
"dom",
"=",
"[",
"]",
";",
"}",
"else",
"{",
"this",
".",
"dom",
"=",
"typeof",
"el",
"===",
"'string'",
"?",
"context",
".",
"querySelectorAll",
"(",
"el",
")",
":",
"el",
";",
"}",
"if",
"(",
"el",
"instanceof",
"Air",
")",
"{",
"this",
".",
"dom",
"=",
"el",
".",
"dom",
".",
"slice",
"(",
"0",
")",
";",
"}",
"else",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"el",
")",
")",
"{",
"if",
"(",
"this",
".",
"dom",
"instanceof",
"NodeList",
")",
"{",
"this",
".",
"dom",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"this",
".",
"dom",
")",
";",
"}",
"else",
"if",
"(",
"el",
")",
"{",
"this",
".",
"dom",
"=",
"(",
"(",
"el",
"instanceof",
"Node",
")",
"||",
"el",
"===",
"window",
")",
"?",
"[",
"el",
"]",
":",
"[",
"]",
";",
"}",
"}",
"// shortcut to Array.prototype.slice",
"this",
".",
"slice",
"=",
"Array",
".",
"prototype",
".",
"slice",
";",
"}"
]
| Chainable wrapper class.
This is the core of the entire plugin system and typically you extend
functionality by adding methods to the prototype of this function.
However a plugin may also add static methods to the main function,
see the `create` plugin for an example of adding static methods.
This implementation targets modern browsers (IE9+) and requires that
the array methods `isArray`, `forEach` and `filter` are available,
for older browsers you will need to include polyfills.
@param el A selector, DOM element, array of elements or Air instance.
@param context The context element for a selector. | [
"Chainable",
"wrapper",
"class",
"."
]
| a3d94de58aaa4930a425fbcc7266764bf6ca8ca6 | https://github.com/socialally/air/blob/a3d94de58aaa4930a425fbcc7266764bf6ca8ca6/lib/air.js#L22-L50 |
44,974 | DScheglov/merest | lib/controllers/find-by-id.js | findById | function findById(method, req, res, next) {
res.__apiMethod = method;
var self = this;
var id = req.params.id;
var fields = this.option(method, 'fields');
var populate = this.option(method, 'populate');
var filter = this.option(method, 'filter');
if (filter instanceof Function) filter = filter.call(this, req);
var query = extend({_id: id}, filter);
var dbQuery = this.model.findOne(query, fields);
if (populate) {
dbQuery = dbQuery.populate(populate);
}
dbQuery.exec(function (err, obj) {
if (err) return next(err);
if (!obj) {
return next(new ModelAPIError(
404, `The ${self.nameSingle} was not found by ${id}`
));
}
if (method === 'details') res.status(200);
res.json(obj);
});
} | javascript | function findById(method, req, res, next) {
res.__apiMethod = method;
var self = this;
var id = req.params.id;
var fields = this.option(method, 'fields');
var populate = this.option(method, 'populate');
var filter = this.option(method, 'filter');
if (filter instanceof Function) filter = filter.call(this, req);
var query = extend({_id: id}, filter);
var dbQuery = this.model.findOne(query, fields);
if (populate) {
dbQuery = dbQuery.populate(populate);
}
dbQuery.exec(function (err, obj) {
if (err) return next(err);
if (!obj) {
return next(new ModelAPIError(
404, `The ${self.nameSingle} was not found by ${id}`
));
}
if (method === 'details') res.status(200);
res.json(obj);
});
} | [
"function",
"findById",
"(",
"method",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"__apiMethod",
"=",
"method",
";",
"var",
"self",
"=",
"this",
";",
"var",
"id",
"=",
"req",
".",
"params",
".",
"id",
";",
"var",
"fields",
"=",
"this",
".",
"option",
"(",
"method",
",",
"'fields'",
")",
";",
"var",
"populate",
"=",
"this",
".",
"option",
"(",
"method",
",",
"'populate'",
")",
";",
"var",
"filter",
"=",
"this",
".",
"option",
"(",
"method",
",",
"'filter'",
")",
";",
"if",
"(",
"filter",
"instanceof",
"Function",
")",
"filter",
"=",
"filter",
".",
"call",
"(",
"this",
",",
"req",
")",
";",
"var",
"query",
"=",
"extend",
"(",
"{",
"_id",
":",
"id",
"}",
",",
"filter",
")",
";",
"var",
"dbQuery",
"=",
"this",
".",
"model",
".",
"findOne",
"(",
"query",
",",
"fields",
")",
";",
"if",
"(",
"populate",
")",
"{",
"dbQuery",
"=",
"dbQuery",
".",
"populate",
"(",
"populate",
")",
";",
"}",
"dbQuery",
".",
"exec",
"(",
"function",
"(",
"err",
",",
"obj",
")",
"{",
"if",
"(",
"err",
")",
"return",
"next",
"(",
"err",
")",
";",
"if",
"(",
"!",
"obj",
")",
"{",
"return",
"next",
"(",
"new",
"ModelAPIError",
"(",
"404",
",",
"`",
"${",
"self",
".",
"nameSingle",
"}",
"${",
"id",
"}",
"`",
")",
")",
";",
"}",
"if",
"(",
"method",
"===",
"'details'",
")",
"res",
".",
"status",
"(",
"200",
")",
";",
"res",
".",
"json",
"(",
"obj",
")",
";",
"}",
")",
";",
"}"
]
| findById - sub-controller that is used to response
with one model instance
@param {String} method the name of main controller
@param {express.Request} req the http(s) request
@param {express.Response} res the http(s) response
@param {Function} next the callback should be called if controller fails
@throws ModelAPIError(404, '...')
@memberof ModelAPIRouter | [
"findById",
"-",
"sub",
"-",
"controller",
"that",
"is",
"used",
"to",
"response",
"with",
"one",
"model",
"instance"
]
| d39e7ef0d56236247773467e9bfe83cb128ebc01 | https://github.com/DScheglov/merest/blob/d39e7ef0d56236247773467e9bfe83cb128ebc01/lib/controllers/find-by-id.js#L19-L44 |
44,975 | odogono/elsinore-js | src/query/attr.js | commandAttr | function commandAttr(context, attributes) {
let ii, jj, len, jlen, result;
let entity = context.entity;
// let debug = context.debug;
const componentIDs = context.componentIDs;
// printIns( context,1 );
// if( debug ){ console.log('ATTR> ' + stringify(componentIDs) + ' ' + stringify( _.rest(arguments)) ); }
// if( !componentIDs ){
// throw new Error('no componentIDs in context');
// }
if (!entity) {
// console.log('ATTR> no entity');
return (context.last = [VALUE, null]);
}
attributes = Array.isArray(attributes) ? attributes : [attributes];
// components = entity.components;
result = [];
const components = entity.getComponents(componentIDs);
// console.log('commandComponentAttribute', attributes);
for (ii = 0, len = components.length; ii < len; ii++) {
const component = components[ii];
for (jj = 0, jlen = attributes.length; jj < jlen; jj++) {
const attr = attributes[jj];
const val = component.get(attr);
if (val !== undefined) {
result.push(val);
}
}
}
if (result.length === 0) {
result = null;
} else if (result.length === 1) {
result = result[0];
}
return (context.last = [VALUE, result]);
} | javascript | function commandAttr(context, attributes) {
let ii, jj, len, jlen, result;
let entity = context.entity;
// let debug = context.debug;
const componentIDs = context.componentIDs;
// printIns( context,1 );
// if( debug ){ console.log('ATTR> ' + stringify(componentIDs) + ' ' + stringify( _.rest(arguments)) ); }
// if( !componentIDs ){
// throw new Error('no componentIDs in context');
// }
if (!entity) {
// console.log('ATTR> no entity');
return (context.last = [VALUE, null]);
}
attributes = Array.isArray(attributes) ? attributes : [attributes];
// components = entity.components;
result = [];
const components = entity.getComponents(componentIDs);
// console.log('commandComponentAttribute', attributes);
for (ii = 0, len = components.length; ii < len; ii++) {
const component = components[ii];
for (jj = 0, jlen = attributes.length; jj < jlen; jj++) {
const attr = attributes[jj];
const val = component.get(attr);
if (val !== undefined) {
result.push(val);
}
}
}
if (result.length === 0) {
result = null;
} else if (result.length === 1) {
result = result[0];
}
return (context.last = [VALUE, result]);
} | [
"function",
"commandAttr",
"(",
"context",
",",
"attributes",
")",
"{",
"let",
"ii",
",",
"jj",
",",
"len",
",",
"jlen",
",",
"result",
";",
"let",
"entity",
"=",
"context",
".",
"entity",
";",
"// let debug = context.debug;",
"const",
"componentIDs",
"=",
"context",
".",
"componentIDs",
";",
"// printIns( context,1 );",
"// if( debug ){ console.log('ATTR> ' + stringify(componentIDs) + ' ' + stringify( _.rest(arguments)) ); }",
"// if( !componentIDs ){",
"// throw new Error('no componentIDs in context');",
"// }",
"if",
"(",
"!",
"entity",
")",
"{",
"// console.log('ATTR> no entity');",
"return",
"(",
"context",
".",
"last",
"=",
"[",
"VALUE",
",",
"null",
"]",
")",
";",
"}",
"attributes",
"=",
"Array",
".",
"isArray",
"(",
"attributes",
")",
"?",
"attributes",
":",
"[",
"attributes",
"]",
";",
"// components = entity.components;",
"result",
"=",
"[",
"]",
";",
"const",
"components",
"=",
"entity",
".",
"getComponents",
"(",
"componentIDs",
")",
";",
"// console.log('commandComponentAttribute', attributes);",
"for",
"(",
"ii",
"=",
"0",
",",
"len",
"=",
"components",
".",
"length",
";",
"ii",
"<",
"len",
";",
"ii",
"++",
")",
"{",
"const",
"component",
"=",
"components",
"[",
"ii",
"]",
";",
"for",
"(",
"jj",
"=",
"0",
",",
"jlen",
"=",
"attributes",
".",
"length",
";",
"jj",
"<",
"jlen",
";",
"jj",
"++",
")",
"{",
"const",
"attr",
"=",
"attributes",
"[",
"jj",
"]",
";",
"const",
"val",
"=",
"component",
".",
"get",
"(",
"attr",
")",
";",
"if",
"(",
"val",
"!==",
"undefined",
")",
"{",
"result",
".",
"push",
"(",
"val",
")",
";",
"}",
"}",
"}",
"if",
"(",
"result",
".",
"length",
"===",
"0",
")",
"{",
"result",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"result",
".",
"length",
"===",
"1",
")",
"{",
"result",
"=",
"result",
"[",
"0",
"]",
";",
"}",
"return",
"(",
"context",
".",
"last",
"=",
"[",
"VALUE",
",",
"result",
"]",
")",
";",
"}"
]
| Takes the attribute value of the given component and returns it
This command operates on the single entity within context. | [
"Takes",
"the",
"attribute",
"value",
"of",
"the",
"given",
"component",
"and",
"returns",
"it"
]
| 1ecce67ad0022646419a740def029b1ba92dd558 | https://github.com/odogono/elsinore-js/blob/1ecce67ad0022646419a740def029b1ba92dd558/src/query/attr.js#L20-L63 |
44,976 | Rafflecopter/deetoo | lib/util.js | partial | function partial(fn) {
var preset=_slice.call(arguments, 1), self=this
return function(){ return fn.apply(self, arrfill(preset, arguments)) }
} | javascript | function partial(fn) {
var preset=_slice.call(arguments, 1), self=this
return function(){ return fn.apply(self, arrfill(preset, arguments)) }
} | [
"function",
"partial",
"(",
"fn",
")",
"{",
"var",
"preset",
"=",
"_slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
",",
"self",
"=",
"this",
"return",
"function",
"(",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"self",
",",
"arrfill",
"(",
"preset",
",",
"arguments",
")",
")",
"}",
"}"
]
| allows out-of-order arguments by using `undefined` | [
"allows",
"out",
"-",
"of",
"-",
"order",
"arguments",
"by",
"using",
"undefined"
]
| 4d7932efeab35e01fa3a584b6c1253b21f0c4515 | https://github.com/Rafflecopter/deetoo/blob/4d7932efeab35e01fa3a584b6c1253b21f0c4515/lib/util.js#L11-L14 |
44,977 | ryanflorence/detect-globals | lib/detect-globals.js | setupContext | function setupContext(node) {
if (node.type === 'Program') {
node.context = GLOBAL_CONTEXT;
return;
}
// default context is the parent context
node.context = node.parent.context;
// IIFE (function(win){ win.x = 'x' }(window))
if ( isIIFE(node) ) {
var args = node.arguments;
var params = node.callee.params;
if (args.length && params.length) {
params.forEach(function(param, i){
var arg = args[i] || {};
var init = arg.type === 'ThisExpression'? node.context : arg.name;
addVarToScope(node, {
name: param.name,
init: init
});
});
}
node.context = node.parent.context;
return;
}
// function.call and function.apply change the context
if (node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
(node.callee.property.name === 'call' || node.callee.property.name === 'apply')) {
var arg = node.arguments[0];
var ctx = (!arg || arg.type === 'ThisExpression' ||
(arg.type === 'Literal' && arg.value == null))? GLOBAL_CONTEXT : CUSTOM_CONTEXT;
addVarToScope(node, {
name: 'this',
init: ctx,
pointer: ctx
});
node.context = ctx;
return;
}
if ((node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration') && !isIIFE(node.parent)) {
// params are "free variables"
node.params.forEach(function(param){
addVarToScope(node, {
name: param.name,
init: undefined
});
});
// by default we assume that all properties of object use "this" to referece
// itself even tho this might not be true depending on how the method is
// called
if (node.parent.type === 'Property' ||
(node.parent.type === 'AssignmentExpression' &&
node.parent.left.type === 'MemberExpression')) {
node.context = CUSTOM_CONTEXT;
return;
}
}
} | javascript | function setupContext(node) {
if (node.type === 'Program') {
node.context = GLOBAL_CONTEXT;
return;
}
// default context is the parent context
node.context = node.parent.context;
// IIFE (function(win){ win.x = 'x' }(window))
if ( isIIFE(node) ) {
var args = node.arguments;
var params = node.callee.params;
if (args.length && params.length) {
params.forEach(function(param, i){
var arg = args[i] || {};
var init = arg.type === 'ThisExpression'? node.context : arg.name;
addVarToScope(node, {
name: param.name,
init: init
});
});
}
node.context = node.parent.context;
return;
}
// function.call and function.apply change the context
if (node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
(node.callee.property.name === 'call' || node.callee.property.name === 'apply')) {
var arg = node.arguments[0];
var ctx = (!arg || arg.type === 'ThisExpression' ||
(arg.type === 'Literal' && arg.value == null))? GLOBAL_CONTEXT : CUSTOM_CONTEXT;
addVarToScope(node, {
name: 'this',
init: ctx,
pointer: ctx
});
node.context = ctx;
return;
}
if ((node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration') && !isIIFE(node.parent)) {
// params are "free variables"
node.params.forEach(function(param){
addVarToScope(node, {
name: param.name,
init: undefined
});
});
// by default we assume that all properties of object use "this" to referece
// itself even tho this might not be true depending on how the method is
// called
if (node.parent.type === 'Property' ||
(node.parent.type === 'AssignmentExpression' &&
node.parent.left.type === 'MemberExpression')) {
node.context = CUSTOM_CONTEXT;
return;
}
}
} | [
"function",
"setupContext",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"type",
"===",
"'Program'",
")",
"{",
"node",
".",
"context",
"=",
"GLOBAL_CONTEXT",
";",
"return",
";",
"}",
"// default context is the parent context",
"node",
".",
"context",
"=",
"node",
".",
"parent",
".",
"context",
";",
"// IIFE (function(win){ win.x = 'x' }(window))",
"if",
"(",
"isIIFE",
"(",
"node",
")",
")",
"{",
"var",
"args",
"=",
"node",
".",
"arguments",
";",
"var",
"params",
"=",
"node",
".",
"callee",
".",
"params",
";",
"if",
"(",
"args",
".",
"length",
"&&",
"params",
".",
"length",
")",
"{",
"params",
".",
"forEach",
"(",
"function",
"(",
"param",
",",
"i",
")",
"{",
"var",
"arg",
"=",
"args",
"[",
"i",
"]",
"||",
"{",
"}",
";",
"var",
"init",
"=",
"arg",
".",
"type",
"===",
"'ThisExpression'",
"?",
"node",
".",
"context",
":",
"arg",
".",
"name",
";",
"addVarToScope",
"(",
"node",
",",
"{",
"name",
":",
"param",
".",
"name",
",",
"init",
":",
"init",
"}",
")",
";",
"}",
")",
";",
"}",
"node",
".",
"context",
"=",
"node",
".",
"parent",
".",
"context",
";",
"return",
";",
"}",
"// function.call and function.apply change the context",
"if",
"(",
"node",
".",
"type",
"===",
"'CallExpression'",
"&&",
"node",
".",
"callee",
".",
"type",
"===",
"'MemberExpression'",
"&&",
"(",
"node",
".",
"callee",
".",
"property",
".",
"name",
"===",
"'call'",
"||",
"node",
".",
"callee",
".",
"property",
".",
"name",
"===",
"'apply'",
")",
")",
"{",
"var",
"arg",
"=",
"node",
".",
"arguments",
"[",
"0",
"]",
";",
"var",
"ctx",
"=",
"(",
"!",
"arg",
"||",
"arg",
".",
"type",
"===",
"'ThisExpression'",
"||",
"(",
"arg",
".",
"type",
"===",
"'Literal'",
"&&",
"arg",
".",
"value",
"==",
"null",
")",
")",
"?",
"GLOBAL_CONTEXT",
":",
"CUSTOM_CONTEXT",
";",
"addVarToScope",
"(",
"node",
",",
"{",
"name",
":",
"'this'",
",",
"init",
":",
"ctx",
",",
"pointer",
":",
"ctx",
"}",
")",
";",
"node",
".",
"context",
"=",
"ctx",
";",
"return",
";",
"}",
"if",
"(",
"(",
"node",
".",
"type",
"===",
"'FunctionExpression'",
"||",
"node",
".",
"type",
"===",
"'FunctionDeclaration'",
")",
"&&",
"!",
"isIIFE",
"(",
"node",
".",
"parent",
")",
")",
"{",
"// params are \"free variables\"",
"node",
".",
"params",
".",
"forEach",
"(",
"function",
"(",
"param",
")",
"{",
"addVarToScope",
"(",
"node",
",",
"{",
"name",
":",
"param",
".",
"name",
",",
"init",
":",
"undefined",
"}",
")",
";",
"}",
")",
";",
"// by default we assume that all properties of object use \"this\" to referece",
"// itself even tho this might not be true depending on how the method is",
"// called",
"if",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"'Property'",
"||",
"(",
"node",
".",
"parent",
".",
"type",
"===",
"'AssignmentExpression'",
"&&",
"node",
".",
"parent",
".",
"left",
".",
"type",
"===",
"'MemberExpression'",
")",
")",
"{",
"node",
".",
"context",
"=",
"CUSTOM_CONTEXT",
";",
"return",
";",
"}",
"}",
"}"
]
| gets reference to the "this" value | [
"gets",
"reference",
"to",
"the",
"this",
"value"
]
| da2242ee01c3617d54fd79e8373dd44a7c876181 | https://github.com/ryanflorence/detect-globals/blob/da2242ee01c3617d54fd79e8373dd44a7c876181/lib/detect-globals.js#L64-L130 |
44,978 | HelpfulHuman/Router-Kit | src/connectHistory.js | assertHistoryType | function assertHistoryType (history) {
assertType("history", "object", history);
assertType("history.listen", "function", history.listen);
assertType("history.push", "function", history.push);
assertType("history.replace", "function", history.replace);
assertType("history.goBack", "function", history.goBack);
} | javascript | function assertHistoryType (history) {
assertType("history", "object", history);
assertType("history.listen", "function", history.listen);
assertType("history.push", "function", history.push);
assertType("history.replace", "function", history.replace);
assertType("history.goBack", "function", history.goBack);
} | [
"function",
"assertHistoryType",
"(",
"history",
")",
"{",
"assertType",
"(",
"\"history\"",
",",
"\"object\"",
",",
"history",
")",
";",
"assertType",
"(",
"\"history.listen\"",
",",
"\"function\"",
",",
"history",
".",
"listen",
")",
";",
"assertType",
"(",
"\"history.push\"",
",",
"\"function\"",
",",
"history",
".",
"push",
")",
";",
"assertType",
"(",
"\"history.replace\"",
",",
"\"function\"",
",",
"history",
".",
"replace",
")",
";",
"assertType",
"(",
"\"history.goBack\"",
",",
"\"function\"",
",",
"history",
".",
"goBack",
")",
";",
"}"
]
| Throws an error if object shape is not that of a history object.
@param {History} history | [
"Throws",
"an",
"error",
"if",
"object",
"shape",
"is",
"not",
"that",
"of",
"a",
"history",
"object",
"."
]
| 2864833465348d0b38ee6652ea5d872f0a793ded | https://github.com/HelpfulHuman/Router-Kit/blob/2864833465348d0b38ee6652ea5d872f0a793ded/src/connectHistory.js#L9-L15 |
44,979 | HelpfulHuman/Router-Kit | src/connectHistory.js | createDefaultHandler | function createDefaultHandler (history) {
return function (context, runMiddleware) {
runMiddleware(context, function (err, redirect) {
if (err) {
console.error(`${context.uri} -> ${err.message}`, err);
} else if (redirect) {
history.replace(redirect);
}
});
}
} | javascript | function createDefaultHandler (history) {
return function (context, runMiddleware) {
runMiddleware(context, function (err, redirect) {
if (err) {
console.error(`${context.uri} -> ${err.message}`, err);
} else if (redirect) {
history.replace(redirect);
}
});
}
} | [
"function",
"createDefaultHandler",
"(",
"history",
")",
"{",
"return",
"function",
"(",
"context",
",",
"runMiddleware",
")",
"{",
"runMiddleware",
"(",
"context",
",",
"function",
"(",
"err",
",",
"redirect",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"context",
".",
"uri",
"}",
"${",
"err",
".",
"message",
"}",
"`",
",",
"err",
")",
";",
"}",
"else",
"if",
"(",
"redirect",
")",
"{",
"history",
".",
"replace",
"(",
"redirect",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
]
| Create a default handler for connecting a router to a history object.
@param {History} history
@return {Function} | [
"Create",
"a",
"default",
"handler",
"for",
"connecting",
"a",
"router",
"to",
"a",
"history",
"object",
"."
]
| 2864833465348d0b38ee6652ea5d872f0a793ded | https://github.com/HelpfulHuman/Router-Kit/blob/2864833465348d0b38ee6652ea5d872f0a793ded/src/connectHistory.js#L23-L33 |
44,980 | vid/SenseBase | util/mapJsonToItemAnnotation.js | flatten | function flatten(level, map) {
for (var key in map) {
var kmap = map[key];
// we found a definition
if (kmap._VAL_ || kmap._TAG_) {
if (kmap._VAL_) {
flatFields[key] = { level: level, _VAL_ : kmap._VAL_};
} else {
flatFields[key] = { level: level, _TAG_ : kmap._TAG_};
}
// presumed a level def
} else {
var here = level.slice(0);
here.push(key);
flatten(here, kmap);
}
}
} | javascript | function flatten(level, map) {
for (var key in map) {
var kmap = map[key];
// we found a definition
if (kmap._VAL_ || kmap._TAG_) {
if (kmap._VAL_) {
flatFields[key] = { level: level, _VAL_ : kmap._VAL_};
} else {
flatFields[key] = { level: level, _TAG_ : kmap._TAG_};
}
// presumed a level def
} else {
var here = level.slice(0);
here.push(key);
flatten(here, kmap);
}
}
} | [
"function",
"flatten",
"(",
"level",
",",
"map",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"map",
")",
"{",
"var",
"kmap",
"=",
"map",
"[",
"key",
"]",
";",
"// we found a definition",
"if",
"(",
"kmap",
".",
"_VAL_",
"||",
"kmap",
".",
"_TAG_",
")",
"{",
"if",
"(",
"kmap",
".",
"_VAL_",
")",
"{",
"flatFields",
"[",
"key",
"]",
"=",
"{",
"level",
":",
"level",
",",
"_VAL_",
":",
"kmap",
".",
"_VAL_",
"}",
";",
"}",
"else",
"{",
"flatFields",
"[",
"key",
"]",
"=",
"{",
"level",
":",
"level",
",",
"_TAG_",
":",
"kmap",
".",
"_TAG_",
"}",
";",
"}",
"// presumed a level def",
"}",
"else",
"{",
"var",
"here",
"=",
"level",
".",
"slice",
"(",
"0",
")",
";",
"here",
".",
"push",
"(",
"key",
")",
";",
"flatten",
"(",
"here",
",",
"kmap",
")",
";",
"}",
"}",
"}"
]
| recursively flatten fields to flatFields for fast lookups | [
"recursively",
"flatten",
"fields",
"to",
"flatFields",
"for",
"fast",
"lookups"
]
| d60bcf28239e7dde437d8a6bdae41a6921dcd05b | https://github.com/vid/SenseBase/blob/d60bcf28239e7dde437d8a6bdae41a6921dcd05b/util/mapJsonToItemAnnotation.js#L136-L153 |
44,981 | cfpb/AtomicComponent | src/utilities/function-bind/index.js | bind | function bind( fn, context ) {
if ( Function.prototype.bind ) {
return fn.bind.apply( fn, Array.prototype.slice.call( arguments, 1 ) );
}
return function() {
return fn.apply( context, arguments );
};
} | javascript | function bind( fn, context ) {
if ( Function.prototype.bind ) {
return fn.bind.apply( fn, Array.prototype.slice.call( arguments, 1 ) );
}
return function() {
return fn.apply( context, arguments );
};
} | [
"function",
"bind",
"(",
"fn",
",",
"context",
")",
"{",
"if",
"(",
"Function",
".",
"prototype",
".",
"bind",
")",
"{",
"return",
"fn",
".",
"bind",
".",
"apply",
"(",
"fn",
",",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
")",
";",
"}",
"return",
"function",
"(",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"context",
",",
"arguments",
")",
";",
"}",
";",
"}"
]
| Function.prototype.bind polyfill.
@access private
@function bind
@param {Function} fn - A function you want to change `this` reference to.
@param {Object} context - The `this` you want to call the function with.
@returns {Function} The wrapped version of the supplied function. | [
"Function",
".",
"prototype",
".",
"bind",
"polyfill",
"."
]
| f45d7ded6687672c8b701c9910ddfe90c7ede742 | https://github.com/cfpb/AtomicComponent/blob/f45d7ded6687672c8b701c9910ddfe90c7ede742/src/utilities/function-bind/index.js#L22-L30 |
44,982 | bminer/trivial-port | serialport.js | openSerialPortDevice | function openSerialPortDevice(readFd) {
//Save TTY streams
self._readStream = new tty.ReadStream(readFd);
self._readStream.setRawMode(true);
self._writeStream = self._readStream;
//Setup error handlers
self._readStream.on("error", function(err) {
self.emit("error", err);
});
//Setup read event handlers
self._readStream.on("data", function(chunk) {
self.push(chunk);
});
self._readStream.on("end", function() {
self.push(null);
});
self._readStream.on("close", function() {
self.emit("close");
});
//Emit open event
self.emit("open",self._readStream);
} | javascript | function openSerialPortDevice(readFd) {
//Save TTY streams
self._readStream = new tty.ReadStream(readFd);
self._readStream.setRawMode(true);
self._writeStream = self._readStream;
//Setup error handlers
self._readStream.on("error", function(err) {
self.emit("error", err);
});
//Setup read event handlers
self._readStream.on("data", function(chunk) {
self.push(chunk);
});
self._readStream.on("end", function() {
self.push(null);
});
self._readStream.on("close", function() {
self.emit("close");
});
//Emit open event
self.emit("open",self._readStream);
} | [
"function",
"openSerialPortDevice",
"(",
"readFd",
")",
"{",
"//Save TTY streams",
"self",
".",
"_readStream",
"=",
"new",
"tty",
".",
"ReadStream",
"(",
"readFd",
")",
";",
"self",
".",
"_readStream",
".",
"setRawMode",
"(",
"true",
")",
";",
"self",
".",
"_writeStream",
"=",
"self",
".",
"_readStream",
";",
"//Setup error handlers",
"self",
".",
"_readStream",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
"err",
")",
"{",
"self",
".",
"emit",
"(",
"\"error\"",
",",
"err",
")",
";",
"}",
")",
";",
"//Setup read event handlers",
"self",
".",
"_readStream",
".",
"on",
"(",
"\"data\"",
",",
"function",
"(",
"chunk",
")",
"{",
"self",
".",
"push",
"(",
"chunk",
")",
";",
"}",
")",
";",
"self",
".",
"_readStream",
".",
"on",
"(",
"\"end\"",
",",
"function",
"(",
")",
"{",
"self",
".",
"push",
"(",
"null",
")",
";",
"}",
")",
";",
"self",
".",
"_readStream",
".",
"on",
"(",
"\"close\"",
",",
"function",
"(",
")",
"{",
"self",
".",
"emit",
"(",
"\"close\"",
")",
";",
"}",
")",
";",
"//Emit open event",
"self",
".",
"emit",
"(",
"\"open\"",
",",
"self",
".",
"_readStream",
")",
";",
"}"
]
| Once the process exits successfully, we call this function | [
"Once",
"the",
"process",
"exits",
"successfully",
"we",
"call",
"this",
"function"
]
| f0db774ae14b2af3a75789060c9c2999c24d27a6 | https://github.com/bminer/trivial-port/blob/f0db774ae14b2af3a75789060c9c2999c24d27a6/serialport.js#L152-L173 |
44,983 | donothingloop/netinterfaces | lib/index.js | findIntf | function findIntf(intf, osIntfs) {
var keys = Object.keys(osIntfs);
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
if (intf === key) {
return osIntfs[key];
}
}
return null;
} | javascript | function findIntf(intf, osIntfs) {
var keys = Object.keys(osIntfs);
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
if (intf === key) {
return osIntfs[key];
}
}
return null;
} | [
"function",
"findIntf",
"(",
"intf",
",",
"osIntfs",
")",
"{",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"osIntfs",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"intf",
"===",
"key",
")",
"{",
"return",
"osIntfs",
"[",
"key",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Find the interface by interface name in the data returned by os.networkInterfaces.
@param intf
@param osIntfs | [
"Find",
"the",
"interface",
"by",
"interface",
"name",
"in",
"the",
"data",
"returned",
"by",
"os",
".",
"networkInterfaces",
"."
]
| 83327e9c930693db0ec2e443343ef29ed318246c | https://github.com/donothingloop/netinterfaces/blob/83327e9c930693db0ec2e443343ef29ed318246c/lib/index.js#L24-L35 |
44,984 | mesmotronic/conbo | src/conbo/net/Router.js | function(route, name, callback)
{
var regExp = conbo.isRegExp(route) ? route : this.__routeToRegExp(route);
if (!callback)
{
callback = this[name];
}
if (conbo.isFunction(name))
{
callback = name;
name = '';
}
if (!callback)
{
callback = this[name];
}
this.__history.addRoute(regExp, (function(path)
{
var args = this.__extractParameters(regExp, path);
var params = conbo.isString(route)
? conbo.object((route.match(/:\w+/g) || []).map(function(r) { return r.substr(1); }), args)
: {}
;
callback && callback.apply(this, args);
var options =
{
router: this,
route: regExp,
name: name,
parameters: args,
params: params,
path: path
};
this.dispatchEvent(new conbo.ConboEvent('route:'+name, options));
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.ROUTE, options));
}).bind(this));
return this;
} | javascript | function(route, name, callback)
{
var regExp = conbo.isRegExp(route) ? route : this.__routeToRegExp(route);
if (!callback)
{
callback = this[name];
}
if (conbo.isFunction(name))
{
callback = name;
name = '';
}
if (!callback)
{
callback = this[name];
}
this.__history.addRoute(regExp, (function(path)
{
var args = this.__extractParameters(regExp, path);
var params = conbo.isString(route)
? conbo.object((route.match(/:\w+/g) || []).map(function(r) { return r.substr(1); }), args)
: {}
;
callback && callback.apply(this, args);
var options =
{
router: this,
route: regExp,
name: name,
parameters: args,
params: params,
path: path
};
this.dispatchEvent(new conbo.ConboEvent('route:'+name, options));
this.dispatchEvent(new conbo.ConboEvent(conbo.ConboEvent.ROUTE, options));
}).bind(this));
return this;
} | [
"function",
"(",
"route",
",",
"name",
",",
"callback",
")",
"{",
"var",
"regExp",
"=",
"conbo",
".",
"isRegExp",
"(",
"route",
")",
"?",
"route",
":",
"this",
".",
"__routeToRegExp",
"(",
"route",
")",
";",
"if",
"(",
"!",
"callback",
")",
"{",
"callback",
"=",
"this",
"[",
"name",
"]",
";",
"}",
"if",
"(",
"conbo",
".",
"isFunction",
"(",
"name",
")",
")",
"{",
"callback",
"=",
"name",
";",
"name",
"=",
"''",
";",
"}",
"if",
"(",
"!",
"callback",
")",
"{",
"callback",
"=",
"this",
"[",
"name",
"]",
";",
"}",
"this",
".",
"__history",
".",
"addRoute",
"(",
"regExp",
",",
"(",
"function",
"(",
"path",
")",
"{",
"var",
"args",
"=",
"this",
".",
"__extractParameters",
"(",
"regExp",
",",
"path",
")",
";",
"var",
"params",
"=",
"conbo",
".",
"isString",
"(",
"route",
")",
"?",
"conbo",
".",
"object",
"(",
"(",
"route",
".",
"match",
"(",
"/",
":\\w+",
"/",
"g",
")",
"||",
"[",
"]",
")",
".",
"map",
"(",
"function",
"(",
"r",
")",
"{",
"return",
"r",
".",
"substr",
"(",
"1",
")",
";",
"}",
")",
",",
"args",
")",
":",
"{",
"}",
";",
"callback",
"&&",
"callback",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"var",
"options",
"=",
"{",
"router",
":",
"this",
",",
"route",
":",
"regExp",
",",
"name",
":",
"name",
",",
"parameters",
":",
"args",
",",
"params",
":",
"params",
",",
"path",
":",
"path",
"}",
";",
"this",
".",
"dispatchEvent",
"(",
"new",
"conbo",
".",
"ConboEvent",
"(",
"'route:'",
"+",
"name",
",",
"options",
")",
")",
";",
"this",
".",
"dispatchEvent",
"(",
"new",
"conbo",
".",
"ConboEvent",
"(",
"conbo",
".",
"ConboEvent",
".",
"ROUTE",
",",
"options",
")",
")",
";",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"return",
"this",
";",
"}"
]
| Adds a named route
@example
this.addRoute('search/:query/p:num', 'search', function(query, num) {
...
}); | [
"Adds",
"a",
"named",
"route"
]
| 339df613eefc48e054e115337079573ad842f717 | https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/net/Router.js#L87-L134 |
|
44,985 | mesmotronic/conbo | src/conbo/net/Router.js | function(path, options)
{
options = conbo.setDefaults({}, options, {trigger:true});
this.__history.setPath(path, options);
return this;
} | javascript | function(path, options)
{
options = conbo.setDefaults({}, options, {trigger:true});
this.__history.setPath(path, options);
return this;
} | [
"function",
"(",
"path",
",",
"options",
")",
"{",
"options",
"=",
"conbo",
".",
"setDefaults",
"(",
"{",
"}",
",",
"options",
",",
"{",
"trigger",
":",
"true",
"}",
")",
";",
"this",
".",
"__history",
".",
"setPath",
"(",
"path",
",",
"options",
")",
";",
"return",
"this",
";",
"}"
]
| Sets the current path, optionally replacing the current path or silently
without triggering a route event
@param {string} path - The path to navigate to
@param {Object} [options] - Object containing options: trigger (default: true) and replace (default: false) | [
"Sets",
"the",
"current",
"path",
"optionally",
"replacing",
"the",
"current",
"path",
"or",
"silently",
"without",
"triggering",
"a",
"route",
"event"
]
| 339df613eefc48e054e115337079573ad842f717 | https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/net/Router.js#L143-L149 |
|
44,986 | mesmotronic/conbo | src/conbo/net/Router.js | function()
{
if (!this.routes) return;
var route;
var routes = conbo.keys(this.routes);
while ((route = routes.pop()) != null)
{
this.addRoute(route, this.routes[route]);
}
} | javascript | function()
{
if (!this.routes) return;
var route;
var routes = conbo.keys(this.routes);
while ((route = routes.pop()) != null)
{
this.addRoute(route, this.routes[route]);
}
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"routes",
")",
"return",
";",
"var",
"route",
";",
"var",
"routes",
"=",
"conbo",
".",
"keys",
"(",
"this",
".",
"routes",
")",
";",
"while",
"(",
"(",
"route",
"=",
"routes",
".",
"pop",
"(",
")",
")",
"!=",
"null",
")",
"{",
"this",
".",
"addRoute",
"(",
"route",
",",
"this",
".",
"routes",
"[",
"route",
"]",
")",
";",
"}",
"}"
]
| Bind all defined routes. We have to reverse the
order of the routes here to support behavior where the most general
routes can be defined at the bottom of the route map.
@private | [
"Bind",
"all",
"defined",
"routes",
".",
"We",
"have",
"to",
"reverse",
"the",
"order",
"of",
"the",
"routes",
"here",
"to",
"support",
"behavior",
"where",
"the",
"most",
"general",
"routes",
"can",
"be",
"defined",
"at",
"the",
"bottom",
"of",
"the",
"route",
"map",
"."
]
| 339df613eefc48e054e115337079573ad842f717 | https://github.com/mesmotronic/conbo/blob/339df613eefc48e054e115337079573ad842f717/src/conbo/net/Router.js#L177-L188 |
|
44,987 | edappy/bunyan-config | index.js | convertConfig | function convertConfig(jsonConfig) {
var bunyanConfig = extend({}, jsonConfig);
if (Array.isArray(bunyanConfig.streams)) {
bunyanConfig.streams = bunyanConfig.streams.map(convertStream);
}
if (bunyanConfig.serializers) {
bunyanConfig.serializers = convertSerializers(bunyanConfig.serializers);
}
return bunyanConfig;
} | javascript | function convertConfig(jsonConfig) {
var bunyanConfig = extend({}, jsonConfig);
if (Array.isArray(bunyanConfig.streams)) {
bunyanConfig.streams = bunyanConfig.streams.map(convertStream);
}
if (bunyanConfig.serializers) {
bunyanConfig.serializers = convertSerializers(bunyanConfig.serializers);
}
return bunyanConfig;
} | [
"function",
"convertConfig",
"(",
"jsonConfig",
")",
"{",
"var",
"bunyanConfig",
"=",
"extend",
"(",
"{",
"}",
",",
"jsonConfig",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"bunyanConfig",
".",
"streams",
")",
")",
"{",
"bunyanConfig",
".",
"streams",
"=",
"bunyanConfig",
".",
"streams",
".",
"map",
"(",
"convertStream",
")",
";",
"}",
"if",
"(",
"bunyanConfig",
".",
"serializers",
")",
"{",
"bunyanConfig",
".",
"serializers",
"=",
"convertSerializers",
"(",
"bunyanConfig",
".",
"serializers",
")",
";",
"}",
"return",
"bunyanConfig",
";",
"}"
]
| Converts jsonConfig into proper bunyan config. The original object is not modified.
@param {Object} jsonConfig
@returns {Object} bunyanConfig | [
"Converts",
"jsonConfig",
"into",
"proper",
"bunyan",
"config",
".",
"The",
"original",
"object",
"is",
"not",
"modified",
"."
]
| de3213cb3cad1c41855987d85c0eac37fc04bade | https://github.com/edappy/bunyan-config/blob/de3213cb3cad1c41855987d85c0eac37fc04bade/index.js#L37-L49 |
44,988 | bahrus/templ-mount | first-templ.js | def | function def(p) {
if (p && p.tagName && p.cls) {
if (customElements.get(p.tagName)) {
console.warn(p.tagName + '!!');
}
else {
customElements.define(p.tagName, p.cls);
}
}
} | javascript | function def(p) {
if (p && p.tagName && p.cls) {
if (customElements.get(p.tagName)) {
console.warn(p.tagName + '!!');
}
else {
customElements.define(p.tagName, p.cls);
}
}
} | [
"function",
"def",
"(",
"p",
")",
"{",
"if",
"(",
"p",
"&&",
"p",
".",
"tagName",
"&&",
"p",
".",
"cls",
")",
"{",
"if",
"(",
"customElements",
".",
"get",
"(",
"p",
".",
"tagName",
")",
")",
"{",
"console",
".",
"warn",
"(",
"p",
".",
"tagName",
"+",
"'!!'",
")",
";",
"}",
"else",
"{",
"customElements",
".",
"define",
"(",
"p",
".",
"tagName",
",",
"p",
".",
"cls",
")",
";",
"}",
"}",
"}"
]
| fetch in progress | [
"fetch",
"in",
"progress"
]
| e5d4719547632df9c6a21713bbe2c807943d4ef3 | https://github.com/bahrus/templ-mount/blob/e5d4719547632df9c6a21713bbe2c807943d4ef3/first-templ.js#L3-L12 |
44,989 | fullcube/loopback-component-meta | models/meta.js | formatProperties | function formatProperties (properties) {
const result = {}
Object.keys(properties).forEach(key => {
debug('formatProperties: key: ' + key)
if (properties.hasOwnProperty(key)) {
result[ key ] = _.clone(properties[ key ])
result[ key ].type = properties[ key ].type.name
}
})
return result
} | javascript | function formatProperties (properties) {
const result = {}
Object.keys(properties).forEach(key => {
debug('formatProperties: key: ' + key)
if (properties.hasOwnProperty(key)) {
result[ key ] = _.clone(properties[ key ])
result[ key ].type = properties[ key ].type.name
}
})
return result
} | [
"function",
"formatProperties",
"(",
"properties",
")",
"{",
"const",
"result",
"=",
"{",
"}",
"Object",
".",
"keys",
"(",
"properties",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"debug",
"(",
"'formatProperties: key: '",
"+",
"key",
")",
"if",
"(",
"properties",
".",
"hasOwnProperty",
"(",
"key",
")",
")",
"{",
"result",
"[",
"key",
"]",
"=",
"_",
".",
"clone",
"(",
"properties",
"[",
"key",
"]",
")",
"result",
"[",
"key",
"]",
".",
"type",
"=",
"properties",
"[",
"key",
"]",
".",
"type",
".",
"name",
"}",
"}",
")",
"return",
"result",
"}"
]
| Helper method for format the type of the properties | [
"Helper",
"method",
"for",
"format",
"the",
"type",
"of",
"the",
"properties"
]
| b91bc0e93881f8e47ac88a77d4a91231053b219a | https://github.com/fullcube/loopback-component-meta/blob/b91bc0e93881f8e47ac88a77d4a91231053b219a/models/meta.js#L30-L40 |
44,990 | fullcube/loopback-component-meta | models/meta.js | getModelInfo | function getModelInfo (modelName) {
debug('getModelInfo: ' + modelName)
// Get the model
const model = Meta.app.models[ modelName ]
// Create the base return object
const result = {
id: model.definition.name,
name: model.definition.name,
properties: formatProperties(model.definition.properties)
}
// Get the following keys from the settings object, if they are set
const keys = {
'acls': [],
'base': '',
'description': '',
'hidden': [],
'idInjection': true,
'methods': {},
'mixins': {},
'persistUndefinedAsNull': false,
'plural': '',
'relations': {},
'strict': false,
'validations': [],
}
// Loop through the keys and add them to the result with their value
Object.keys(keys).forEach(key => {
result[ key ] = _.get(model.definition.settings, key, keys[ key ])
})
return result
} | javascript | function getModelInfo (modelName) {
debug('getModelInfo: ' + modelName)
// Get the model
const model = Meta.app.models[ modelName ]
// Create the base return object
const result = {
id: model.definition.name,
name: model.definition.name,
properties: formatProperties(model.definition.properties)
}
// Get the following keys from the settings object, if they are set
const keys = {
'acls': [],
'base': '',
'description': '',
'hidden': [],
'idInjection': true,
'methods': {},
'mixins': {},
'persistUndefinedAsNull': false,
'plural': '',
'relations': {},
'strict': false,
'validations': [],
}
// Loop through the keys and add them to the result with their value
Object.keys(keys).forEach(key => {
result[ key ] = _.get(model.definition.settings, key, keys[ key ])
})
return result
} | [
"function",
"getModelInfo",
"(",
"modelName",
")",
"{",
"debug",
"(",
"'getModelInfo: '",
"+",
"modelName",
")",
"// Get the model",
"const",
"model",
"=",
"Meta",
".",
"app",
".",
"models",
"[",
"modelName",
"]",
"// Create the base return object",
"const",
"result",
"=",
"{",
"id",
":",
"model",
".",
"definition",
".",
"name",
",",
"name",
":",
"model",
".",
"definition",
".",
"name",
",",
"properties",
":",
"formatProperties",
"(",
"model",
".",
"definition",
".",
"properties",
")",
"}",
"// Get the following keys from the settings object, if they are set",
"const",
"keys",
"=",
"{",
"'acls'",
":",
"[",
"]",
",",
"'base'",
":",
"''",
",",
"'description'",
":",
"''",
",",
"'hidden'",
":",
"[",
"]",
",",
"'idInjection'",
":",
"true",
",",
"'methods'",
":",
"{",
"}",
",",
"'mixins'",
":",
"{",
"}",
",",
"'persistUndefinedAsNull'",
":",
"false",
",",
"'plural'",
":",
"''",
",",
"'relations'",
":",
"{",
"}",
",",
"'strict'",
":",
"false",
",",
"'validations'",
":",
"[",
"]",
",",
"}",
"// Loop through the keys and add them to the result with their value",
"Object",
".",
"keys",
"(",
"keys",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"result",
"[",
"key",
"]",
"=",
"_",
".",
"get",
"(",
"model",
".",
"definition",
".",
"settings",
",",
"key",
",",
"keys",
"[",
"key",
"]",
")",
"}",
")",
"return",
"result",
"}"
]
| Get the definition of a model and format the result in a way that's similar to a LoopBack model definition file | [
"Get",
"the",
"definition",
"of",
"a",
"model",
"and",
"format",
"the",
"result",
"in",
"a",
"way",
"that",
"s",
"similar",
"to",
"a",
"LoopBack",
"model",
"definition",
"file"
]
| b91bc0e93881f8e47ac88a77d4a91231053b219a | https://github.com/fullcube/loopback-component-meta/blob/b91bc0e93881f8e47ac88a77d4a91231053b219a/models/meta.js#L45-L79 |
44,991 | theworkers/W.js | redis/redis-set-storage.js | function (req, res) {
self.getItems(function (err, result) {
if (!err) {
res.json( result );
} else {
res.json(500, { error: err });
}
});
} | javascript | function (req, res) {
self.getItems(function (err, result) {
if (!err) {
res.json( result );
} else {
res.json(500, { error: err });
}
});
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"self",
".",
"getItems",
"(",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"res",
".",
"json",
"(",
"result",
")",
";",
"}",
"else",
"{",
"res",
".",
"json",
"(",
"500",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Returns a JSON list of all the items | [
"Returns",
"a",
"JSON",
"list",
"of",
"all",
"the",
"items"
]
| 25a11baf8edb27c306f2baf6438bed2faf935bc6 | https://github.com/theworkers/W.js/blob/25a11baf8edb27c306f2baf6438bed2faf935bc6/redis/redis-set-storage.js#L11-L19 |
|
44,992 | theworkers/W.js | redis/redis-set-storage.js | function (req, res) {
// Add items
if (req.body.items instanceof Array) {
self.removeItems(req.body.items, function (err, result) {
if (!err) {
res.json( result );
} else {
res.json(500, { error: err });
}
});
} else {
res.json(500, { error: "No `items` array in request body" });
}
} | javascript | function (req, res) {
// Add items
if (req.body.items instanceof Array) {
self.removeItems(req.body.items, function (err, result) {
if (!err) {
res.json( result );
} else {
res.json(500, { error: err });
}
});
} else {
res.json(500, { error: "No `items` array in request body" });
}
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"// Add items",
"if",
"(",
"req",
".",
"body",
".",
"items",
"instanceof",
"Array",
")",
"{",
"self",
".",
"removeItems",
"(",
"req",
".",
"body",
".",
"items",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"!",
"err",
")",
"{",
"res",
".",
"json",
"(",
"result",
")",
";",
"}",
"else",
"{",
"res",
".",
"json",
"(",
"500",
",",
"{",
"error",
":",
"err",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"res",
".",
"json",
"(",
"500",
",",
"{",
"error",
":",
"\"No `items` array in request body\"",
"}",
")",
";",
"}",
"}"
]
| Expects an JSON object in the request with an array of items called `items`. | [
"Expects",
"an",
"JSON",
"object",
"in",
"the",
"request",
"with",
"an",
"array",
"of",
"items",
"called",
"items",
"."
]
| 25a11baf8edb27c306f2baf6438bed2faf935bc6 | https://github.com/theworkers/W.js/blob/25a11baf8edb27c306f2baf6438bed2faf935bc6/redis/redis-set-storage.js#L21-L34 |
|
44,993 | cheminfo-js/mzData | src/index.js | mzData | function mzData(xml) {
xml = ensureText(xml);
if (typeof xml !== 'string') throw new TypeError('xml must be a string');
let parsed = FastXmlParser.parse(xml, {
textNodeName: '_data',
attributeNamePrefix: '',
parseAttributeValue: true,
attrNodeName: '_attr',
ignoreAttributes: false
});
if (!parsed.mzData) throw new Error('The parent node is not mzData');
let result = {
metadata: {},
times: [],
series: {
ms: {
data: []
}
}
};
processMetadata(parsed.mzData, result.metadata);
processSpectrumList(parsed.mzData, result.times, result.series.ms.data);
return result;
} | javascript | function mzData(xml) {
xml = ensureText(xml);
if (typeof xml !== 'string') throw new TypeError('xml must be a string');
let parsed = FastXmlParser.parse(xml, {
textNodeName: '_data',
attributeNamePrefix: '',
parseAttributeValue: true,
attrNodeName: '_attr',
ignoreAttributes: false
});
if (!parsed.mzData) throw new Error('The parent node is not mzData');
let result = {
metadata: {},
times: [],
series: {
ms: {
data: []
}
}
};
processMetadata(parsed.mzData, result.metadata);
processSpectrumList(parsed.mzData, result.times, result.series.ms.data);
return result;
} | [
"function",
"mzData",
"(",
"xml",
")",
"{",
"xml",
"=",
"ensureText",
"(",
"xml",
")",
";",
"if",
"(",
"typeof",
"xml",
"!==",
"'string'",
")",
"throw",
"new",
"TypeError",
"(",
"'xml must be a string'",
")",
";",
"let",
"parsed",
"=",
"FastXmlParser",
".",
"parse",
"(",
"xml",
",",
"{",
"textNodeName",
":",
"'_data'",
",",
"attributeNamePrefix",
":",
"''",
",",
"parseAttributeValue",
":",
"true",
",",
"attrNodeName",
":",
"'_attr'",
",",
"ignoreAttributes",
":",
"false",
"}",
")",
";",
"if",
"(",
"!",
"parsed",
".",
"mzData",
")",
"throw",
"new",
"Error",
"(",
"'The parent node is not mzData'",
")",
";",
"let",
"result",
"=",
"{",
"metadata",
":",
"{",
"}",
",",
"times",
":",
"[",
"]",
",",
"series",
":",
"{",
"ms",
":",
"{",
"data",
":",
"[",
"]",
"}",
"}",
"}",
";",
"processMetadata",
"(",
"parsed",
".",
"mzData",
",",
"result",
".",
"metadata",
")",
";",
"processSpectrumList",
"(",
"parsed",
".",
"mzData",
",",
"result",
".",
"times",
",",
"result",
".",
"series",
".",
"ms",
".",
"data",
")",
";",
"return",
"result",
";",
"}"
]
| Reads a mzData v1.05 file
@param {ArrayBuffer|string} xml - ArrayBuffer or String or any Typed Array (including Node.js' Buffer from v4) with the data
@return {{times: Array<number>, series: { ms: { data:Array<Array<number>>}}}} | [
"Reads",
"a",
"mzData",
"v1",
".",
"05",
"file"
]
| 85b2d8d5ca3a72bd2c93f6c3f823d24471b1879a | https://github.com/cheminfo-js/mzData/blob/85b2d8d5ca3a72bd2c93f6c3f823d24471b1879a/src/index.js#L14-L44 |
44,994 | Tixit/EmitterB | src/EmitterB.js | triggerIfHandlers | function triggerIfHandlers(that, handlerListName, event) {
triggerIfHandlerList(that[handlerListName][event], event)
triggerIfHandlerList(that[normalHandlerToAllHandlerProperty(handlerListName)], event)
} | javascript | function triggerIfHandlers(that, handlerListName, event) {
triggerIfHandlerList(that[handlerListName][event], event)
triggerIfHandlerList(that[normalHandlerToAllHandlerProperty(handlerListName)], event)
} | [
"function",
"triggerIfHandlers",
"(",
"that",
",",
"handlerListName",
",",
"event",
")",
"{",
"triggerIfHandlerList",
"(",
"that",
"[",
"handlerListName",
"]",
"[",
"event",
"]",
",",
"event",
")",
"triggerIfHandlerList",
"(",
"that",
"[",
"normalHandlerToAllHandlerProperty",
"(",
"handlerListName",
")",
"]",
",",
"event",
")",
"}"
]
| triggers the if handlers from the normal list and the "all" list | [
"triggers",
"the",
"if",
"handlers",
"from",
"the",
"normal",
"list",
"and",
"the",
"all",
"list"
]
| b94a9ad7a1fb26bb1918a30e2c3dff3e93a2e378 | https://github.com/Tixit/EmitterB/blob/b94a9ad7a1fb26bb1918a30e2c3dff3e93a2e378/src/EmitterB.js#L129-L132 |
44,995 | synder/xpress | demo/body-parser/lib/types/raw.js | raw | function raw (options) {
var opts = options || {}
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'application/octet-stream'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (buf) {
return buf
}
return function rawParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// read
read(req, res, next, parse, debug, {
encoding: null,
inflate: inflate,
limit: limit,
verify: verify
})
}
} | javascript | function raw (options) {
var opts = options || {}
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'application/octet-stream'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (buf) {
return buf
}
return function rawParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// read
read(req, res, next, parse, debug, {
encoding: null,
inflate: inflate,
limit: limit,
verify: verify
})
}
} | [
"function",
"raw",
"(",
"options",
")",
"{",
"var",
"opts",
"=",
"options",
"||",
"{",
"}",
"var",
"inflate",
"=",
"opts",
".",
"inflate",
"!==",
"false",
"var",
"limit",
"=",
"typeof",
"opts",
".",
"limit",
"!==",
"'number'",
"?",
"bytes",
".",
"parse",
"(",
"opts",
".",
"limit",
"||",
"'100kb'",
")",
":",
"opts",
".",
"limit",
"var",
"type",
"=",
"opts",
".",
"type",
"||",
"'application/octet-stream'",
"var",
"verify",
"=",
"opts",
".",
"verify",
"||",
"false",
"if",
"(",
"verify",
"!==",
"false",
"&&",
"typeof",
"verify",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'option verify must be function'",
")",
"}",
"// create the appropriate type checking function",
"var",
"shouldParse",
"=",
"typeof",
"type",
"!==",
"'function'",
"?",
"typeChecker",
"(",
"type",
")",
":",
"type",
"function",
"parse",
"(",
"buf",
")",
"{",
"return",
"buf",
"}",
"return",
"function",
"rawParser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"if",
"(",
"req",
".",
"_body",
")",
"{",
"debug",
"(",
"'body already parsed'",
")",
"next",
"(",
")",
"return",
"}",
"req",
".",
"body",
"=",
"req",
".",
"body",
"||",
"{",
"}",
"// skip requests without bodies",
"if",
"(",
"!",
"typeis",
".",
"hasBody",
"(",
"req",
")",
")",
"{",
"debug",
"(",
"'skip empty body'",
")",
"next",
"(",
")",
"return",
"}",
"debug",
"(",
"'content-type %j'",
",",
"req",
".",
"headers",
"[",
"'content-type'",
"]",
")",
"// determine if request should be parsed",
"if",
"(",
"!",
"shouldParse",
"(",
"req",
")",
")",
"{",
"debug",
"(",
"'skip parsing'",
")",
"next",
"(",
")",
"return",
"}",
"// read",
"read",
"(",
"req",
",",
"res",
",",
"next",
",",
"parse",
",",
"debug",
",",
"{",
"encoding",
":",
"null",
",",
"inflate",
":",
"inflate",
",",
"limit",
":",
"limit",
",",
"verify",
":",
"verify",
"}",
")",
"}",
"}"
]
| Create a middleware to parse raw bodies.
@param {object} [options]
@return {function}
@api public | [
"Create",
"a",
"middleware",
"to",
"parse",
"raw",
"bodies",
"."
]
| 4b1e89208b6f34cd78ce90b8a858592115b6ccb5 | https://github.com/synder/xpress/blob/4b1e89208b6f34cd78ce90b8a858592115b6ccb5/demo/body-parser/lib/types/raw.js#L32-L88 |
44,996 | feilaoda/power | public/javascripts/vendor/javascripts/validator.js | filter_attributes | function filter_attributes(str) {
var comments = /\/\*.*?\*\//g;
return str.replace(/\s*[a-z-]+\s*=\s*'[^']*'/gi, function (m) {
return m.replace(comments, '');
}).replace(/\s*[a-z-]+\s*=\s*"[^"]*"/gi, function (m) {
return m.replace(comments, '');
}).replace(/\s*[a-z-]+\s*=\s*[^\s]+/gi, function (m) {
return m.replace(comments, '');
});
} | javascript | function filter_attributes(str) {
var comments = /\/\*.*?\*\//g;
return str.replace(/\s*[a-z-]+\s*=\s*'[^']*'/gi, function (m) {
return m.replace(comments, '');
}).replace(/\s*[a-z-]+\s*=\s*"[^"]*"/gi, function (m) {
return m.replace(comments, '');
}).replace(/\s*[a-z-]+\s*=\s*[^\s]+/gi, function (m) {
return m.replace(comments, '');
});
} | [
"function",
"filter_attributes",
"(",
"str",
")",
"{",
"var",
"comments",
"=",
"/",
"\\/\\*.*?\\*\\/",
"/",
"g",
";",
"return",
"str",
".",
"replace",
"(",
"/",
"\\s*[a-z-]+\\s*=\\s*'[^']*'",
"/",
"gi",
",",
"function",
"(",
"m",
")",
"{",
"return",
"m",
".",
"replace",
"(",
"comments",
",",
"''",
")",
";",
"}",
")",
".",
"replace",
"(",
"/",
"\\s*[a-z-]+\\s*=\\s*\"[^\"]*\"",
"/",
"gi",
",",
"function",
"(",
"m",
")",
"{",
"return",
"m",
".",
"replace",
"(",
"comments",
",",
"''",
")",
";",
"}",
")",
".",
"replace",
"(",
"/",
"\\s*[a-z-]+\\s*=\\s*[^\\s]+",
"/",
"gi",
",",
"function",
"(",
"m",
")",
"{",
"return",
"m",
".",
"replace",
"(",
"comments",
",",
"''",
")",
";",
"}",
")",
";",
"}"
]
| Filter Attributes - filters tag attributes for consistency and safety | [
"Filter",
"Attributes",
"-",
"filters",
"tag",
"attributes",
"for",
"consistency",
"and",
"safety"
]
| 89432e5b8e455eceef5f5098d479ad94c88acc59 | https://github.com/feilaoda/power/blob/89432e5b8e455eceef5f5098d479ad94c88acc59/public/javascripts/vendor/javascripts/validator.js#L514-L523 |
44,997 | bonesoul/node-hpool-web | public/js/plugins/input-mask/jquery.inputmask.js | getMaskTemplate | function getMaskTemplate(mask) {
if (opts.numericInput) {
mask = mask.split('').reverse().join('');
}
var escaped = false, outCount = 0, greedy = opts.greedy, repeat = opts.repeat;
if (repeat == "*") greedy = false;
//if (greedy == true && opts.placeholder == "") opts.placeholder = " ";
if (mask.length == 1 && greedy == false && repeat != 0) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask
var singleMask = $.map(mask.split(""), function (element, index) {
var outElem = [];
if (element == opts.escapeChar) {
escaped = true;
}
else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) {
var maskdef = opts.definitions[element];
if (maskdef && !escaped) {
for (var i = 0; i < maskdef.cardinality; i++) {
outElem.push(opts.placeholder.charAt((outCount + i) % opts.placeholder.length));
}
} else {
outElem.push(element);
escaped = false;
}
outCount += outElem.length;
return outElem;
}
});
//allocate repetitions
var repeatedMask = singleMask.slice();
for (var i = 1; i < repeat && greedy; i++) {
repeatedMask = repeatedMask.concat(singleMask.slice());
}
return { "mask": repeatedMask, "repeat": repeat, "greedy": greedy };
} | javascript | function getMaskTemplate(mask) {
if (opts.numericInput) {
mask = mask.split('').reverse().join('');
}
var escaped = false, outCount = 0, greedy = opts.greedy, repeat = opts.repeat;
if (repeat == "*") greedy = false;
//if (greedy == true && opts.placeholder == "") opts.placeholder = " ";
if (mask.length == 1 && greedy == false && repeat != 0) { opts.placeholder = ""; } //hide placeholder with single non-greedy mask
var singleMask = $.map(mask.split(""), function (element, index) {
var outElem = [];
if (element == opts.escapeChar) {
escaped = true;
}
else if ((element != opts.optionalmarker.start && element != opts.optionalmarker.end) || escaped) {
var maskdef = opts.definitions[element];
if (maskdef && !escaped) {
for (var i = 0; i < maskdef.cardinality; i++) {
outElem.push(opts.placeholder.charAt((outCount + i) % opts.placeholder.length));
}
} else {
outElem.push(element);
escaped = false;
}
outCount += outElem.length;
return outElem;
}
});
//allocate repetitions
var repeatedMask = singleMask.slice();
for (var i = 1; i < repeat && greedy; i++) {
repeatedMask = repeatedMask.concat(singleMask.slice());
}
return { "mask": repeatedMask, "repeat": repeat, "greedy": greedy };
} | [
"function",
"getMaskTemplate",
"(",
"mask",
")",
"{",
"if",
"(",
"opts",
".",
"numericInput",
")",
"{",
"mask",
"=",
"mask",
".",
"split",
"(",
"''",
")",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"''",
")",
";",
"}",
"var",
"escaped",
"=",
"false",
",",
"outCount",
"=",
"0",
",",
"greedy",
"=",
"opts",
".",
"greedy",
",",
"repeat",
"=",
"opts",
".",
"repeat",
";",
"if",
"(",
"repeat",
"==",
"\"*\"",
")",
"greedy",
"=",
"false",
";",
"//if (greedy == true && opts.placeholder == \"\") opts.placeholder = \" \";",
"if",
"(",
"mask",
".",
"length",
"==",
"1",
"&&",
"greedy",
"==",
"false",
"&&",
"repeat",
"!=",
"0",
")",
"{",
"opts",
".",
"placeholder",
"=",
"\"\"",
";",
"}",
"//hide placeholder with single non-greedy mask",
"var",
"singleMask",
"=",
"$",
".",
"map",
"(",
"mask",
".",
"split",
"(",
"\"\"",
")",
",",
"function",
"(",
"element",
",",
"index",
")",
"{",
"var",
"outElem",
"=",
"[",
"]",
";",
"if",
"(",
"element",
"==",
"opts",
".",
"escapeChar",
")",
"{",
"escaped",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"(",
"element",
"!=",
"opts",
".",
"optionalmarker",
".",
"start",
"&&",
"element",
"!=",
"opts",
".",
"optionalmarker",
".",
"end",
")",
"||",
"escaped",
")",
"{",
"var",
"maskdef",
"=",
"opts",
".",
"definitions",
"[",
"element",
"]",
";",
"if",
"(",
"maskdef",
"&&",
"!",
"escaped",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"maskdef",
".",
"cardinality",
";",
"i",
"++",
")",
"{",
"outElem",
".",
"push",
"(",
"opts",
".",
"placeholder",
".",
"charAt",
"(",
"(",
"outCount",
"+",
"i",
")",
"%",
"opts",
".",
"placeholder",
".",
"length",
")",
")",
";",
"}",
"}",
"else",
"{",
"outElem",
".",
"push",
"(",
"element",
")",
";",
"escaped",
"=",
"false",
";",
"}",
"outCount",
"+=",
"outElem",
".",
"length",
";",
"return",
"outElem",
";",
"}",
"}",
")",
";",
"//allocate repetitions",
"var",
"repeatedMask",
"=",
"singleMask",
".",
"slice",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"repeat",
"&&",
"greedy",
";",
"i",
"++",
")",
"{",
"repeatedMask",
"=",
"repeatedMask",
".",
"concat",
"(",
"singleMask",
".",
"slice",
"(",
")",
")",
";",
"}",
"return",
"{",
"\"mask\"",
":",
"repeatedMask",
",",
"\"repeat\"",
":",
"repeat",
",",
"\"greedy\"",
":",
"greedy",
"}",
";",
"}"
]
| used to keep track of the masks that where processed, to avoid duplicates | [
"used",
"to",
"keep",
"track",
"of",
"the",
"masks",
"that",
"where",
"processed",
"to",
"avoid",
"duplicates"
]
| 3d7749b2bcff8b59243939b5b3da19396c4878ff | https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/input-mask/jquery.inputmask.js#L36-L71 |
44,998 | bonesoul/node-hpool-web | public/js/plugins/input-mask/jquery.inputmask.js | _isValid | function _isValid(position, activeMaskset, c, strict) {
var testPos = determineTestPosition(position), loopend = c ? 1 : 0, chrs = '', buffer = activeMaskset["buffer"];
for (var i = activeMaskset['tests'][testPos].cardinality; i > loopend; i--) {
chrs += getBufferElement(buffer, testPos - (i - 1));
}
if (c) {
chrs += c;
}
//return is false or a json object => { pos: ??, c: ??} or true
return activeMaskset['tests'][testPos].fn != null ?
activeMaskset['tests'][testPos].fn.test(chrs, buffer, position, strict, opts)
: (c == getBufferElement(activeMaskset['_buffer'], position, true) || c == opts.skipOptionalPartCharacter) ?
{ "refresh": true, c: getBufferElement(activeMaskset['_buffer'], position, true), pos: position }
: false;
} | javascript | function _isValid(position, activeMaskset, c, strict) {
var testPos = determineTestPosition(position), loopend = c ? 1 : 0, chrs = '', buffer = activeMaskset["buffer"];
for (var i = activeMaskset['tests'][testPos].cardinality; i > loopend; i--) {
chrs += getBufferElement(buffer, testPos - (i - 1));
}
if (c) {
chrs += c;
}
//return is false or a json object => { pos: ??, c: ??} or true
return activeMaskset['tests'][testPos].fn != null ?
activeMaskset['tests'][testPos].fn.test(chrs, buffer, position, strict, opts)
: (c == getBufferElement(activeMaskset['_buffer'], position, true) || c == opts.skipOptionalPartCharacter) ?
{ "refresh": true, c: getBufferElement(activeMaskset['_buffer'], position, true), pos: position }
: false;
} | [
"function",
"_isValid",
"(",
"position",
",",
"activeMaskset",
",",
"c",
",",
"strict",
")",
"{",
"var",
"testPos",
"=",
"determineTestPosition",
"(",
"position",
")",
",",
"loopend",
"=",
"c",
"?",
"1",
":",
"0",
",",
"chrs",
"=",
"''",
",",
"buffer",
"=",
"activeMaskset",
"[",
"\"buffer\"",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"activeMaskset",
"[",
"'tests'",
"]",
"[",
"testPos",
"]",
".",
"cardinality",
";",
"i",
">",
"loopend",
";",
"i",
"--",
")",
"{",
"chrs",
"+=",
"getBufferElement",
"(",
"buffer",
",",
"testPos",
"-",
"(",
"i",
"-",
"1",
")",
")",
";",
"}",
"if",
"(",
"c",
")",
"{",
"chrs",
"+=",
"c",
";",
"}",
"//return is false or a json object => { pos: ??, c: ??} or true",
"return",
"activeMaskset",
"[",
"'tests'",
"]",
"[",
"testPos",
"]",
".",
"fn",
"!=",
"null",
"?",
"activeMaskset",
"[",
"'tests'",
"]",
"[",
"testPos",
"]",
".",
"fn",
".",
"test",
"(",
"chrs",
",",
"buffer",
",",
"position",
",",
"strict",
",",
"opts",
")",
":",
"(",
"c",
"==",
"getBufferElement",
"(",
"activeMaskset",
"[",
"'_buffer'",
"]",
",",
"position",
",",
"true",
")",
"||",
"c",
"==",
"opts",
".",
"skipOptionalPartCharacter",
")",
"?",
"{",
"\"refresh\"",
":",
"true",
",",
"c",
":",
"getBufferElement",
"(",
"activeMaskset",
"[",
"'_buffer'",
"]",
",",
"position",
",",
"true",
")",
",",
"pos",
":",
"position",
"}",
":",
"false",
";",
"}"
]
| always set a value to strict to prevent possible strange behavior in the extensions | [
"always",
"set",
"a",
"value",
"to",
"strict",
"to",
"prevent",
"possible",
"strange",
"behavior",
"in",
"the",
"extensions"
]
| 3d7749b2bcff8b59243939b5b3da19396c4878ff | https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/input-mask/jquery.inputmask.js#L266-L282 |
44,999 | bonesoul/node-hpool-web | public/js/plugins/input-mask/jquery.inputmask.js | prepareBuffer | function prepareBuffer(buffer, position) {
var j;
while (buffer[position] == undefined && buffer.length < getMaskLength()) {
j = 0;
while (getActiveBufferTemplate()[j] !== undefined) { //add a new buffer
buffer.push(getActiveBufferTemplate()[j++]);
}
}
return position;
} | javascript | function prepareBuffer(buffer, position) {
var j;
while (buffer[position] == undefined && buffer.length < getMaskLength()) {
j = 0;
while (getActiveBufferTemplate()[j] !== undefined) { //add a new buffer
buffer.push(getActiveBufferTemplate()[j++]);
}
}
return position;
} | [
"function",
"prepareBuffer",
"(",
"buffer",
",",
"position",
")",
"{",
"var",
"j",
";",
"while",
"(",
"buffer",
"[",
"position",
"]",
"==",
"undefined",
"&&",
"buffer",
".",
"length",
"<",
"getMaskLength",
"(",
")",
")",
"{",
"j",
"=",
"0",
";",
"while",
"(",
"getActiveBufferTemplate",
"(",
")",
"[",
"j",
"]",
"!==",
"undefined",
")",
"{",
"//add a new buffer",
"buffer",
".",
"push",
"(",
"getActiveBufferTemplate",
"(",
")",
"[",
"j",
"++",
"]",
")",
";",
"}",
"}",
"return",
"position",
";",
"}"
]
| needed to handle the non-greedy mask repetitions | [
"needed",
"to",
"handle",
"the",
"non",
"-",
"greedy",
"mask",
"repetitions"
]
| 3d7749b2bcff8b59243939b5b3da19396c4878ff | https://github.com/bonesoul/node-hpool-web/blob/3d7749b2bcff8b59243939b5b3da19396c4878ff/public/js/plugins/input-mask/jquery.inputmask.js#L497-L507 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.