repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
egoist/jue | packages/babel-plugin-transform-jue-jsx/src/index.js | buildOpeningElementAttributes | function buildOpeningElementAttributes(attribs, file) {
let _props = []
let objs = []
function pushProps() {
if (_props.length === 0) return
objs.push(t.objectExpression(_props))
_props = []
}
while (attribs.length) {
const prop = attribs.shift()
if (t.isJSXSpreadAttribute(prop)) {
pushProps()
prop.argument._isSpread = true
objs.push(prop.argument)
} else {
_props.push(convertAttribute(prop))
}
}
pushProps()
objs = objs.map(o => {
return o._isSpread ? o : groupProps(o.properties, t)
})
if (objs.length === 1) {
// Only one object
attribs = objs[0]
} else if (objs.length > 0) {
// Add prop merging helper
const helper = file.addImport('babel-helper-vue-jsx-merge-props', 'default', '_mergeJSXProps')
// Spread it
attribs = t.callExpression(
helper,
[t.arrayExpression(objs)]
)
}
return attribs
} | javascript | function buildOpeningElementAttributes(attribs, file) {
let _props = []
let objs = []
function pushProps() {
if (_props.length === 0) return
objs.push(t.objectExpression(_props))
_props = []
}
while (attribs.length) {
const prop = attribs.shift()
if (t.isJSXSpreadAttribute(prop)) {
pushProps()
prop.argument._isSpread = true
objs.push(prop.argument)
} else {
_props.push(convertAttribute(prop))
}
}
pushProps()
objs = objs.map(o => {
return o._isSpread ? o : groupProps(o.properties, t)
})
if (objs.length === 1) {
// Only one object
attribs = objs[0]
} else if (objs.length > 0) {
// Add prop merging helper
const helper = file.addImport('babel-helper-vue-jsx-merge-props', 'default', '_mergeJSXProps')
// Spread it
attribs = t.callExpression(
helper,
[t.arrayExpression(objs)]
)
}
return attribs
} | [
"function",
"buildOpeningElementAttributes",
"(",
"attribs",
",",
"file",
")",
"{",
"let",
"_props",
"=",
"[",
"]",
"let",
"objs",
"=",
"[",
"]",
"function",
"pushProps",
"(",
")",
"{",
"if",
"(",
"_props",
".",
"length",
"===",
"0",
")",
"return",
"objs",
".",
"push",
"(",
"t",
".",
"objectExpression",
"(",
"_props",
")",
")",
"_props",
"=",
"[",
"]",
"}",
"while",
"(",
"attribs",
".",
"length",
")",
"{",
"const",
"prop",
"=",
"attribs",
".",
"shift",
"(",
")",
"if",
"(",
"t",
".",
"isJSXSpreadAttribute",
"(",
"prop",
")",
")",
"{",
"pushProps",
"(",
")",
"prop",
".",
"argument",
".",
"_isSpread",
"=",
"true",
"objs",
".",
"push",
"(",
"prop",
".",
"argument",
")",
"}",
"else",
"{",
"_props",
".",
"push",
"(",
"convertAttribute",
"(",
"prop",
")",
")",
"}",
"}",
"pushProps",
"(",
")",
"objs",
"=",
"objs",
".",
"map",
"(",
"o",
"=>",
"{",
"return",
"o",
".",
"_isSpread",
"?",
"o",
":",
"groupProps",
"(",
"o",
".",
"properties",
",",
"t",
")",
"}",
")",
"if",
"(",
"objs",
".",
"length",
"===",
"1",
")",
"{",
"attribs",
"=",
"objs",
"[",
"0",
"]",
"}",
"else",
"if",
"(",
"objs",
".",
"length",
">",
"0",
")",
"{",
"const",
"helper",
"=",
"file",
".",
"addImport",
"(",
"'babel-helper-vue-jsx-merge-props'",
",",
"'default'",
",",
"'_mergeJSXProps'",
")",
"attribs",
"=",
"t",
".",
"callExpression",
"(",
"helper",
",",
"[",
"t",
".",
"arrayExpression",
"(",
"objs",
")",
"]",
")",
"}",
"return",
"attribs",
"}"
] | The logic for this is quite terse. It's because we need to
support spread elements. We loop over all attributes,
breaking on spreads, we then push a new object containing
all prior attributes to an array for later processing. | [
"The",
"logic",
"for",
"this",
"is",
"quite",
"terse",
".",
"It",
"s",
"because",
"we",
"need",
"to",
"support",
"spread",
"elements",
".",
"We",
"loop",
"over",
"all",
"attributes",
"breaking",
"on",
"spreads",
"we",
"then",
"push",
"a",
"new",
"object",
"containing",
"all",
"prior",
"attributes",
"to",
"an",
"array",
"for",
"later",
"processing",
"."
] | 6ff8ccd3e3d27fcb0dba00411cd03a737be5bf13 | https://github.com/egoist/jue/blob/6ff8ccd3e3d27fcb0dba00411cd03a737be5bf13/packages/babel-plugin-transform-jue-jsx/src/index.js#L145-L185 | train |
node-modules/antpb | lib/decoder.js | decoder | function decoder(mtype) {
const gen = util.codegen([ 'r', 'l' ], mtype.name + '$decode')('if(!(r instanceof Reader))')('r=Reader.create(r)')('var c=l===undefined?r.len:r.pos+l,m=new this.ctor' + (mtype.fieldsArray.filter(field => field.map).length ? ',k' : ''))('while(r.pos<c){')('var t=r.uint32()');
if (mtype.group) {
gen('if((t&7)===4)')('break');
}
gen('switch(t>>>3){');
for (let i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
const field = mtype._fieldsArray[i].resolve();
const type = field.resolvedType instanceof Enum ? 'int32' : field.type;
const ref = 'm' + util.safeProp(field.name);
gen('case %i:', field.id);
// Map fields
if (field.map) {
gen('r.skip().pos++')('if(%s===util.emptyObject)', ref)('%s=new Map()', ref)('k=r.%s()', field.keyType)('r.pos++'); // assumes id 2 + value wireType
// NOTE: 原来这里将 Long 对象转换成 hash 字符串是因为 Object 的 key 只能是字符串,现在用 Map 来实现后就让它原样输出就好了
// if (types.long[field.keyType] !== undefined) {
// if (types.basic[type] === undefined) {
// gen('%s.set(typeof k==="object"?util.longToHash(k):k, types[%i].decode(r,r.uint32()));', ref, i); // can't be groups
// } else {
// gen('%s.set(typeof k==="object"?util.longToHash(k):k, r.%s());', ref, type);
// }
// } else {
if (types.basic[type] === undefined) {
gen('%s.set(k, types[%i].decode(r,r.uint32()));', ref, i); // can't be groups
} else {
gen('%s.set(k, r.%s());', ref, type);
}
// }
// Repeated fields
} else if (field.repeated) {
gen('if(!(%s&&%s.length))', ref, ref)('%s=[]', ref);
// Packable (always check for forward and backward compatiblity)
if (types.packed[type] !== undefined) {
gen('if((t&7)===2){')('var c2=r.uint32()+r.pos')('while(r.pos<c2)')('%s.push(r.%s())', ref, type)('}else');
}
// Non-packed
if (types.basic[type] === undefined) {
gen(field.resolvedType.group ? '%s.push(types[%i].decode(r))' : '%s.push(types[%i].decode(r,r.uint32()))', ref, i);
} else {
gen('%s.push(r.%s())', ref, type);
}
// Non-repeated
} else if (types.basic[type] === undefined) {
gen(field.resolvedType.group ? '%s=types[%i].decode(r)' : '%s=types[%i].decode(r,r.uint32())', ref, i);
} else {
gen('%s=r.%s()', ref, type);
}
gen('break');
// Unknown fields
}
gen('default:')('r.skipType(t&7)')('break')('}')('}');
// Field presence
for (let i = 0; i < mtype._fieldsArray.length; ++i) {
const rfield = mtype._fieldsArray[i];
if (rfield.required) {
gen('if(!m.hasOwnProperty(%j))', rfield.name)('throw util.ProtocolError(%j,{instance:m})', missing(rfield));
}
}
return gen('return m');
} | javascript | function decoder(mtype) {
const gen = util.codegen([ 'r', 'l' ], mtype.name + '$decode')('if(!(r instanceof Reader))')('r=Reader.create(r)')('var c=l===undefined?r.len:r.pos+l,m=new this.ctor' + (mtype.fieldsArray.filter(field => field.map).length ? ',k' : ''))('while(r.pos<c){')('var t=r.uint32()');
if (mtype.group) {
gen('if((t&7)===4)')('break');
}
gen('switch(t>>>3){');
for (let i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
const field = mtype._fieldsArray[i].resolve();
const type = field.resolvedType instanceof Enum ? 'int32' : field.type;
const ref = 'm' + util.safeProp(field.name);
gen('case %i:', field.id);
// Map fields
if (field.map) {
gen('r.skip().pos++')('if(%s===util.emptyObject)', ref)('%s=new Map()', ref)('k=r.%s()', field.keyType)('r.pos++'); // assumes id 2 + value wireType
// NOTE: 原来这里将 Long 对象转换成 hash 字符串是因为 Object 的 key 只能是字符串,现在用 Map 来实现后就让它原样输出就好了
// if (types.long[field.keyType] !== undefined) {
// if (types.basic[type] === undefined) {
// gen('%s.set(typeof k==="object"?util.longToHash(k):k, types[%i].decode(r,r.uint32()));', ref, i); // can't be groups
// } else {
// gen('%s.set(typeof k==="object"?util.longToHash(k):k, r.%s());', ref, type);
// }
// } else {
if (types.basic[type] === undefined) {
gen('%s.set(k, types[%i].decode(r,r.uint32()));', ref, i); // can't be groups
} else {
gen('%s.set(k, r.%s());', ref, type);
}
// }
// Repeated fields
} else if (field.repeated) {
gen('if(!(%s&&%s.length))', ref, ref)('%s=[]', ref);
// Packable (always check for forward and backward compatiblity)
if (types.packed[type] !== undefined) {
gen('if((t&7)===2){')('var c2=r.uint32()+r.pos')('while(r.pos<c2)')('%s.push(r.%s())', ref, type)('}else');
}
// Non-packed
if (types.basic[type] === undefined) {
gen(field.resolvedType.group ? '%s.push(types[%i].decode(r))' : '%s.push(types[%i].decode(r,r.uint32()))', ref, i);
} else {
gen('%s.push(r.%s())', ref, type);
}
// Non-repeated
} else if (types.basic[type] === undefined) {
gen(field.resolvedType.group ? '%s=types[%i].decode(r)' : '%s=types[%i].decode(r,r.uint32())', ref, i);
} else {
gen('%s=r.%s()', ref, type);
}
gen('break');
// Unknown fields
}
gen('default:')('r.skipType(t&7)')('break')('}')('}');
// Field presence
for (let i = 0; i < mtype._fieldsArray.length; ++i) {
const rfield = mtype._fieldsArray[i];
if (rfield.required) {
gen('if(!m.hasOwnProperty(%j))', rfield.name)('throw util.ProtocolError(%j,{instance:m})', missing(rfield));
}
}
return gen('return m');
} | [
"function",
"decoder",
"(",
"mtype",
")",
"{",
"const",
"gen",
"=",
"util",
".",
"codegen",
"(",
"[",
"'r'",
",",
"'l'",
"]",
",",
"mtype",
".",
"name",
"+",
"'$decode'",
")",
"(",
"'if(!(r instanceof Reader))'",
")",
"(",
"'r=Reader.create(r)'",
")",
"(",
"'var c=l===undefined?r.len:r.pos+l,m=new this.ctor'",
"+",
"(",
"mtype",
".",
"fieldsArray",
".",
"filter",
"(",
"field",
"=>",
"field",
".",
"map",
")",
".",
"length",
"?",
"',k'",
":",
"''",
")",
")",
"(",
"'while(r.pos<c){'",
")",
"(",
"'var t=r.uint32()'",
")",
";",
"if",
"(",
"mtype",
".",
"group",
")",
"{",
"gen",
"(",
"'if((t&7)===4)'",
")",
"(",
"'break'",
")",
";",
"}",
"gen",
"(",
"'switch(t>>>3){'",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"mtype",
".",
"fieldsArray",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"field",
"=",
"mtype",
".",
"_fieldsArray",
"[",
"i",
"]",
".",
"resolve",
"(",
")",
";",
"const",
"type",
"=",
"field",
".",
"resolvedType",
"instanceof",
"Enum",
"?",
"'int32'",
":",
"field",
".",
"type",
";",
"const",
"ref",
"=",
"'m'",
"+",
"util",
".",
"safeProp",
"(",
"field",
".",
"name",
")",
";",
"gen",
"(",
"'case %i:'",
",",
"field",
".",
"id",
")",
";",
"if",
"(",
"field",
".",
"map",
")",
"{",
"gen",
"(",
"'r.skip().pos++'",
")",
"(",
"'if(%s===util.emptyObject)'",
",",
"ref",
")",
"(",
"'%s=new Map()'",
",",
"ref",
")",
"(",
"'k=r.%s()'",
",",
"field",
".",
"keyType",
")",
"(",
"'r.pos++'",
")",
";",
"if",
"(",
"types",
".",
"basic",
"[",
"type",
"]",
"===",
"undefined",
")",
"{",
"gen",
"(",
"'%s.set(k, types[%i].decode(r,r.uint32()));'",
",",
"ref",
",",
"i",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'%s.set(k, r.%s());'",
",",
"ref",
",",
"type",
")",
";",
"}",
"}",
"else",
"if",
"(",
"field",
".",
"repeated",
")",
"{",
"gen",
"(",
"'if(!(%s&&%s.length))'",
",",
"ref",
",",
"ref",
")",
"(",
"'%s=[]'",
",",
"ref",
")",
";",
"if",
"(",
"types",
".",
"packed",
"[",
"type",
"]",
"!==",
"undefined",
")",
"{",
"gen",
"(",
"'if((t&7)===2){'",
")",
"(",
"'var c2=r.uint32()+r.pos'",
")",
"(",
"'while(r.pos<c2)'",
")",
"(",
"'%s.push(r.%s())'",
",",
"ref",
",",
"type",
")",
"(",
"'}else'",
")",
";",
"}",
"if",
"(",
"types",
".",
"basic",
"[",
"type",
"]",
"===",
"undefined",
")",
"{",
"gen",
"(",
"field",
".",
"resolvedType",
".",
"group",
"?",
"'%s.push(types[%i].decode(r))'",
":",
"'%s.push(types[%i].decode(r,r.uint32()))'",
",",
"ref",
",",
"i",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'%s.push(r.%s())'",
",",
"ref",
",",
"type",
")",
";",
"}",
"}",
"else",
"if",
"(",
"types",
".",
"basic",
"[",
"type",
"]",
"===",
"undefined",
")",
"{",
"gen",
"(",
"field",
".",
"resolvedType",
".",
"group",
"?",
"'%s=types[%i].decode(r)'",
":",
"'%s=types[%i].decode(r,r.uint32())'",
",",
"ref",
",",
"i",
")",
";",
"}",
"else",
"{",
"gen",
"(",
"'%s=r.%s()'",
",",
"ref",
",",
"type",
")",
";",
"}",
"gen",
"(",
"'break'",
")",
";",
"}",
"gen",
"(",
"'default:'",
")",
"(",
"'r.skipType(t&7)'",
")",
"(",
"'break'",
")",
"(",
"'}'",
")",
"(",
"'}'",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"mtype",
".",
"_fieldsArray",
".",
"length",
";",
"++",
"i",
")",
"{",
"const",
"rfield",
"=",
"mtype",
".",
"_fieldsArray",
"[",
"i",
"]",
";",
"if",
"(",
"rfield",
".",
"required",
")",
"{",
"gen",
"(",
"'if(!m.hasOwnProperty(%j))'",
",",
"rfield",
".",
"name",
")",
"(",
"'throw util.ProtocolError(%j,{instance:m})'",
",",
"missing",
"(",
"rfield",
")",
")",
";",
"}",
"}",
"return",
"gen",
"(",
"'return m'",
")",
";",
"}"
] | Generates a decoder specific to the specified message type.
@param {Type} mtype Message type
@return {Codegen} Codegen instance | [
"Generates",
"a",
"decoder",
"specific",
"to",
"the",
"specified",
"message",
"type",
"."
] | e6d74d4c372151fcb3880eb44a4e85907d99405c | https://github.com/node-modules/antpb/blob/e6d74d4c372151fcb3880eb44a4e85907d99405c/lib/decoder.js#L16-L82 | train |
crysalead-js/dom-layer | src/node/patcher/select-value.js | populateOptions | function populateOptions(node, values) {
if (node.tagName !== 'option') {
for (var i = 0, len = node.children.length; i < len ; i++) {
populateOptions(node.children[i], values);
}
return;
}
var value = node.attrs && node.attrs.value;
value = value || node.props && node.props.value;
if (!values.hasOwnProperty(value)) {
return;
}
node.attrs = node.attrs || {};
node.attrs.selected = 'selected';
node.props = node.props || {};
node.props.selected = true;
} | javascript | function populateOptions(node, values) {
if (node.tagName !== 'option') {
for (var i = 0, len = node.children.length; i < len ; i++) {
populateOptions(node.children[i], values);
}
return;
}
var value = node.attrs && node.attrs.value;
value = value || node.props && node.props.value;
if (!values.hasOwnProperty(value)) {
return;
}
node.attrs = node.attrs || {};
node.attrs.selected = 'selected';
node.props = node.props || {};
node.props.selected = true;
} | [
"function",
"populateOptions",
"(",
"node",
",",
"values",
")",
"{",
"if",
"(",
"node",
".",
"tagName",
"!==",
"'option'",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"node",
".",
"children",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"populateOptions",
"(",
"node",
".",
"children",
"[",
"i",
"]",
",",
"values",
")",
";",
"}",
"return",
";",
"}",
"var",
"value",
"=",
"node",
".",
"attrs",
"&&",
"node",
".",
"attrs",
".",
"value",
";",
"value",
"=",
"value",
"||",
"node",
".",
"props",
"&&",
"node",
".",
"props",
".",
"value",
";",
"if",
"(",
"!",
"values",
".",
"hasOwnProperty",
"(",
"value",
")",
")",
"{",
"return",
";",
"}",
"node",
".",
"attrs",
"=",
"node",
".",
"attrs",
"||",
"{",
"}",
";",
"node",
".",
"attrs",
".",
"selected",
"=",
"'selected'",
";",
"node",
".",
"props",
"=",
"node",
".",
"props",
"||",
"{",
"}",
";",
"node",
".",
"props",
".",
"selected",
"=",
"true",
";",
"}"
] | Populates values to options node.
@param Object node A starting node (generaly a select node).
@param Object values The selected values to populate. | [
"Populates",
"values",
"to",
"options",
"node",
"."
] | 0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2 | https://github.com/crysalead-js/dom-layer/blob/0c3509fe1b6c4cd2ce0c030b73791f951f5f97a2/src/node/patcher/select-value.js#L43-L60 | train |
MarcDiethelm/xtc | lib/utils.js | function(sInput, levels, indentString) {
var indentedLineBreak;
indentString = indentString || '\t';
indentedLineBreak = '\n'+ ( new Array( levels + 1 ).join( indentString ) );
return indentedLineBreak + sInput.split('\n').join(indentedLineBreak);
} | javascript | function(sInput, levels, indentString) {
var indentedLineBreak;
indentString = indentString || '\t';
indentedLineBreak = '\n'+ ( new Array( levels + 1 ).join( indentString ) );
return indentedLineBreak + sInput.split('\n').join(indentedLineBreak);
} | [
"function",
"(",
"sInput",
",",
"levels",
",",
"indentString",
")",
"{",
"var",
"indentedLineBreak",
";",
"indentString",
"=",
"indentString",
"||",
"'\\t'",
";",
"\\t",
"indentedLineBreak",
"=",
"'\\n'",
"+",
"\\n",
";",
"}"
] | Add indentation to a multi-line string
@param {string} sInput
@param {number} levels – How many levels of indentation to apply
@param {string} [indentString] – Character to use for indentation, defaults to tab char.
@returns {string} | [
"Add",
"indentation",
"to",
"a",
"multi",
"-",
"line",
"string"
] | dd422136b27ca52b17255d4e8778ca30a70e987b | https://github.com/MarcDiethelm/xtc/blob/dd422136b27ca52b17255d4e8778ca30a70e987b/lib/utils.js#L41-L48 | train |
|
MarcDiethelm/xtc | lib/utils.js | function(baseUri, branch, filePath, fileName) {
var varPath = fileName ? 'blob/' : 'tree/'
,branch = branch ? branch + '/' : 'develop'
,filePath = path.relative(process.cwd(), filePath) + '/'
;
fileName = fileName || '';
return baseUri ? baseUri + varPath + branch + filePath + fileName : null;
} | javascript | function(baseUri, branch, filePath, fileName) {
var varPath = fileName ? 'blob/' : 'tree/'
,branch = branch ? branch + '/' : 'develop'
,filePath = path.relative(process.cwd(), filePath) + '/'
;
fileName = fileName || '';
return baseUri ? baseUri + varPath + branch + filePath + fileName : null;
} | [
"function",
"(",
"baseUri",
",",
"branch",
",",
"filePath",
",",
"fileName",
")",
"{",
"var",
"varPath",
"=",
"fileName",
"?",
"'blob/'",
":",
"'tree/'",
",",
"branch",
"=",
"branch",
"?",
"branch",
"+",
"'/'",
":",
"'develop'",
",",
"filePath",
"=",
"path",
".",
"relative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"filePath",
")",
"+",
"'/'",
";",
"fileName",
"=",
"fileName",
"||",
"''",
";",
"return",
"baseUri",
"?",
"baseUri",
"+",
"varPath",
"+",
"branch",
"+",
"filePath",
"+",
"fileName",
":",
"null",
";",
"}"
] | Construct an URI to the web view of the file or directory in a repository
@param {string} baseUri – e.g. 'https://github.com/MarcDiethelm/xtc'
@param {string} branch
@param {string} filePath
@param {string} [fileName]
@returns {string} – URI to the web view of the file or directory in the repository | [
"Construct",
"an",
"URI",
"to",
"the",
"web",
"view",
"of",
"the",
"file",
"or",
"directory",
"in",
"a",
"repository"
] | dd422136b27ca52b17255d4e8778ca30a70e987b | https://github.com/MarcDiethelm/xtc/blob/dd422136b27ca52b17255d4e8778ca30a70e987b/lib/utils.js#L58-L67 | train |
|
bryanjhv/express-readme | lib/convert.js | register | function register(types, converter) {
types.split(' ').forEach(function (type) {
converters[type] = converter;
});
} | javascript | function register(types, converter) {
types.split(' ').forEach(function (type) {
converters[type] = converter;
});
} | [
"function",
"register",
"(",
"types",
",",
"converter",
")",
"{",
"types",
".",
"split",
"(",
"' '",
")",
".",
"forEach",
"(",
"function",
"(",
"type",
")",
"{",
"converters",
"[",
"type",
"]",
"=",
"converter",
";",
"}",
")",
";",
"}"
] | Register a converter.
Takes a string, splits by spaces (in case a given markup can
have multiple extensions), and maps the method in the available
converters list.
@param {string} types - The markup types (extensions).
@param {function(string, object)} converter - Markup converter. | [
"Register",
"a",
"converter",
"."
] | 5c3755b8f642a8550ac259e9c74cc2cb89d946c8 | https://github.com/bryanjhv/express-readme/blob/5c3755b8f642a8550ac259e9c74cc2cb89d946c8/lib/convert.js#L45-L49 | train |
sirap-group/connect-sequence | lib/ConnectSequence.js | run | function run () {
var midSequence = this.middlewares.reverse()
var initialNext = this.next.bind()
var req = this.req
var res = this.res
var nestedCallSequence
// create the call sequence
nestedCallSequence = midSequence.reduce(middlewareReducer, initialNext)
// call it
nestedCallSequence.call()
/**
* Reduce the middleware sequence to a nested middleware handler sequence
* @function
* @inner
* @private
* @param {Function} callSequence intermediate resulting call sequence
* @param {Function} middleware the current middleware
* @returns {Function} the new intermediate resulting call sequence
*/
function middlewareReducer (callSequence, middleware) {
return function nextHandler (err) {
// if the previous middleware passed an error argument
if (err !== undefined) {
if (isErrorHandler(middleware)) {
// call the current middleware if it is an error handler middleware
middleware(err, req, res, callSequence)
} else {
// else skip the current middleware and call the intermediate sequence
callSequence(err)
}
} else {
// if no error argument is passed
if (isErrorHandler(middleware)) {
// skip the current middleware if it is an errorHandler
callSequence()
} else {
// else call it
middleware(req, res, callSequence)
}
}
}
}
} | javascript | function run () {
var midSequence = this.middlewares.reverse()
var initialNext = this.next.bind()
var req = this.req
var res = this.res
var nestedCallSequence
// create the call sequence
nestedCallSequence = midSequence.reduce(middlewareReducer, initialNext)
// call it
nestedCallSequence.call()
/**
* Reduce the middleware sequence to a nested middleware handler sequence
* @function
* @inner
* @private
* @param {Function} callSequence intermediate resulting call sequence
* @param {Function} middleware the current middleware
* @returns {Function} the new intermediate resulting call sequence
*/
function middlewareReducer (callSequence, middleware) {
return function nextHandler (err) {
// if the previous middleware passed an error argument
if (err !== undefined) {
if (isErrorHandler(middleware)) {
// call the current middleware if it is an error handler middleware
middleware(err, req, res, callSequence)
} else {
// else skip the current middleware and call the intermediate sequence
callSequence(err)
}
} else {
// if no error argument is passed
if (isErrorHandler(middleware)) {
// skip the current middleware if it is an errorHandler
callSequence()
} else {
// else call it
middleware(req, res, callSequence)
}
}
}
}
} | [
"function",
"run",
"(",
")",
"{",
"var",
"midSequence",
"=",
"this",
".",
"middlewares",
".",
"reverse",
"(",
")",
"var",
"initialNext",
"=",
"this",
".",
"next",
".",
"bind",
"(",
")",
"var",
"req",
"=",
"this",
".",
"req",
"var",
"res",
"=",
"this",
".",
"res",
"var",
"nestedCallSequence",
"nestedCallSequence",
"=",
"midSequence",
".",
"reduce",
"(",
"middlewareReducer",
",",
"initialNext",
")",
"nestedCallSequence",
".",
"call",
"(",
")",
"function",
"middlewareReducer",
"(",
"callSequence",
",",
"middleware",
")",
"{",
"return",
"function",
"nextHandler",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"!==",
"undefined",
")",
"{",
"if",
"(",
"isErrorHandler",
"(",
"middleware",
")",
")",
"{",
"middleware",
"(",
"err",
",",
"req",
",",
"res",
",",
"callSequence",
")",
"}",
"else",
"{",
"callSequence",
"(",
"err",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"isErrorHandler",
"(",
"middleware",
")",
")",
"{",
"callSequence",
"(",
")",
"}",
"else",
"{",
"middleware",
"(",
"req",
",",
"res",
",",
"callSequence",
")",
"}",
"}",
"}",
"}",
"}"
] | Run sequencially each appended middleware, using the next argument as the final callback.
@method
@memberof ConnectSequence.prototype
@returns {undefined} | [
"Run",
"sequencially",
"each",
"appended",
"middleware",
"using",
"the",
"next",
"argument",
"as",
"the",
"final",
"callback",
"."
] | 8b0490d75596107b7c37e2c2cfa4d0486f3eda1a | https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/ConnectSequence.js#L57-L101 | train |
sirap-group/connect-sequence | lib/ConnectSequence.js | middlewareReducer | function middlewareReducer (callSequence, middleware) {
return function nextHandler (err) {
// if the previous middleware passed an error argument
if (err !== undefined) {
if (isErrorHandler(middleware)) {
// call the current middleware if it is an error handler middleware
middleware(err, req, res, callSequence)
} else {
// else skip the current middleware and call the intermediate sequence
callSequence(err)
}
} else {
// if no error argument is passed
if (isErrorHandler(middleware)) {
// skip the current middleware if it is an errorHandler
callSequence()
} else {
// else call it
middleware(req, res, callSequence)
}
}
}
} | javascript | function middlewareReducer (callSequence, middleware) {
return function nextHandler (err) {
// if the previous middleware passed an error argument
if (err !== undefined) {
if (isErrorHandler(middleware)) {
// call the current middleware if it is an error handler middleware
middleware(err, req, res, callSequence)
} else {
// else skip the current middleware and call the intermediate sequence
callSequence(err)
}
} else {
// if no error argument is passed
if (isErrorHandler(middleware)) {
// skip the current middleware if it is an errorHandler
callSequence()
} else {
// else call it
middleware(req, res, callSequence)
}
}
}
} | [
"function",
"middlewareReducer",
"(",
"callSequence",
",",
"middleware",
")",
"{",
"return",
"function",
"nextHandler",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"!==",
"undefined",
")",
"{",
"if",
"(",
"isErrorHandler",
"(",
"middleware",
")",
")",
"{",
"middleware",
"(",
"err",
",",
"req",
",",
"res",
",",
"callSequence",
")",
"}",
"else",
"{",
"callSequence",
"(",
"err",
")",
"}",
"}",
"else",
"{",
"if",
"(",
"isErrorHandler",
"(",
"middleware",
")",
")",
"{",
"callSequence",
"(",
")",
"}",
"else",
"{",
"middleware",
"(",
"req",
",",
"res",
",",
"callSequence",
")",
"}",
"}",
"}",
"}"
] | Reduce the middleware sequence to a nested middleware handler sequence
@function
@inner
@private
@param {Function} callSequence intermediate resulting call sequence
@param {Function} middleware the current middleware
@returns {Function} the new intermediate resulting call sequence | [
"Reduce",
"the",
"middleware",
"sequence",
"to",
"a",
"nested",
"middleware",
"handler",
"sequence"
] | 8b0490d75596107b7c37e2c2cfa4d0486f3eda1a | https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/ConnectSequence.js#L78-L100 | train |
sirap-group/connect-sequence | lib/ConnectSequence.js | append | function append (/* mid_0, ..., mid_n */) {
var i
for (i = 0; i < arguments.length; i++) {
if (typeof arguments[i] !== 'function') {
var type = typeof arguments[i]
var errMsg = 'Given middlewares must be functions. "' + type + '" given.'
throw new TypeError(errMsg)
}
}
for (i = 0; i < arguments.length; i++) {
this.middlewares.push(arguments[i])
}
return this
} | javascript | function append (/* mid_0, ..., mid_n */) {
var i
for (i = 0; i < arguments.length; i++) {
if (typeof arguments[i] !== 'function') {
var type = typeof arguments[i]
var errMsg = 'Given middlewares must be functions. "' + type + '" given.'
throw new TypeError(errMsg)
}
}
for (i = 0; i < arguments.length; i++) {
this.middlewares.push(arguments[i])
}
return this
} | [
"function",
"append",
"(",
")",
"{",
"var",
"i",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"typeof",
"arguments",
"[",
"i",
"]",
"!==",
"'function'",
")",
"{",
"var",
"type",
"=",
"typeof",
"arguments",
"[",
"i",
"]",
"var",
"errMsg",
"=",
"'Given middlewares must be functions. \"'",
"+",
"type",
"+",
"'\" given.'",
"throw",
"new",
"TypeError",
"(",
"errMsg",
")",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"this",
".",
"middlewares",
".",
"push",
"(",
"arguments",
"[",
"i",
"]",
")",
"}",
"return",
"this",
"}"
] | Append an arbitrary number of middlewares as an argument list
@method
@memberof ConnectSequence.prototype
@param {...Function} middlewares A list of middleware functions (or errorHandler middlewares)
@returns {ConnectSequence} a reference to the instance to be chainable
@throws TypeError if one of the given middlewares is not a function. All the given middlewares would be rejected. | [
"Append",
"an",
"arbitrary",
"number",
"of",
"middlewares",
"as",
"an",
"argument",
"list"
] | 8b0490d75596107b7c37e2c2cfa4d0486f3eda1a | https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/ConnectSequence.js#L111-L124 | train |
sirap-group/connect-sequence | lib/ConnectSequence.js | appendList | function appendList (middlewares) {
if (!Array.isArray(middlewares)) {
var errorMsg = 'First argument must be an array of middlewares. '
errorMsg += typeof middlewares + ' given.'
throw new TypeError(errorMsg)
}
return this.append.apply(this, middlewares)
} | javascript | function appendList (middlewares) {
if (!Array.isArray(middlewares)) {
var errorMsg = 'First argument must be an array of middlewares. '
errorMsg += typeof middlewares + ' given.'
throw new TypeError(errorMsg)
}
return this.append.apply(this, middlewares)
} | [
"function",
"appendList",
"(",
"middlewares",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"middlewares",
")",
")",
"{",
"var",
"errorMsg",
"=",
"'First argument must be an array of middlewares. '",
"errorMsg",
"+=",
"typeof",
"middlewares",
"+",
"' given.'",
"throw",
"new",
"TypeError",
"(",
"errorMsg",
")",
"}",
"return",
"this",
".",
"append",
".",
"apply",
"(",
"this",
",",
"middlewares",
")",
"}"
] | Append an arbitrary number of middlewares as an array
@method
@memberof ConnectSequence.prototype
@param {Array<Function>} middlewares An array of middleware functions (or errorHandler middlewares)
@returns {ConnectSequence} a reference to the instance to be chainable | [
"Append",
"an",
"arbitrary",
"number",
"of",
"middlewares",
"as",
"an",
"array"
] | 8b0490d75596107b7c37e2c2cfa4d0486f3eda1a | https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/ConnectSequence.js#L133-L140 | train |
sirap-group/connect-sequence | lib/ConnectSequence.js | appendIf | function appendIf (filter /*, middlewares */) {
var errorMsg
var middlewares = []
if (arguments.length < 2) {
errorMsg = 'ConnectSequence#appendIf() takes 2 arguments. '
errorMsg += arguments.length + ' given.'
throw new MissingArgumentError(errorMsg)
}
if (typeof filter !== 'function') {
errorMsg = 'The first argument must be a filter function. '
errorMsg += typeof filter + ' given.'
throw new TypeError(errorMsg)
}
var middleware, i
for (i = 1; i < arguments.length; i++) {
middleware = arguments[i]
if (typeof middleware !== 'function') {
errorMsg = 'The second argument must be a middleware function. '
errorMsg += typeof middleware + ' given.'
throw new TypeError(errorMsg)
}
middlewares.push(middleware)
}
var firstMiddleware = middlewares[0]
if (isErrorHandler(firstMiddleware)) {
this.append(function (err, req, res, next) {
req.__connectSequenceFilterValue = filter(req)
if (req.__connectSequenceFilterValue) {
firstMiddleware(err, req, res, next)
} else {
next()
}
})
} else {
this.append(function (req, res, next) {
req.__connectSequenceFilterValue = filter(req)
if (req.__connectSequenceFilterValue) {
firstMiddleware(req, res, next)
} else {
next()
}
})
}
for (i = 1; i < middlewares.length; i++) {
middleware = middlewares[i]
appendOnFilterValue.call(this, middleware)
}
return this
} | javascript | function appendIf (filter /*, middlewares */) {
var errorMsg
var middlewares = []
if (arguments.length < 2) {
errorMsg = 'ConnectSequence#appendIf() takes 2 arguments. '
errorMsg += arguments.length + ' given.'
throw new MissingArgumentError(errorMsg)
}
if (typeof filter !== 'function') {
errorMsg = 'The first argument must be a filter function. '
errorMsg += typeof filter + ' given.'
throw new TypeError(errorMsg)
}
var middleware, i
for (i = 1; i < arguments.length; i++) {
middleware = arguments[i]
if (typeof middleware !== 'function') {
errorMsg = 'The second argument must be a middleware function. '
errorMsg += typeof middleware + ' given.'
throw new TypeError(errorMsg)
}
middlewares.push(middleware)
}
var firstMiddleware = middlewares[0]
if (isErrorHandler(firstMiddleware)) {
this.append(function (err, req, res, next) {
req.__connectSequenceFilterValue = filter(req)
if (req.__connectSequenceFilterValue) {
firstMiddleware(err, req, res, next)
} else {
next()
}
})
} else {
this.append(function (req, res, next) {
req.__connectSequenceFilterValue = filter(req)
if (req.__connectSequenceFilterValue) {
firstMiddleware(req, res, next)
} else {
next()
}
})
}
for (i = 1; i < middlewares.length; i++) {
middleware = middlewares[i]
appendOnFilterValue.call(this, middleware)
}
return this
} | [
"function",
"appendIf",
"(",
"filter",
")",
"{",
"var",
"errorMsg",
"var",
"middlewares",
"=",
"[",
"]",
"if",
"(",
"arguments",
".",
"length",
"<",
"2",
")",
"{",
"errorMsg",
"=",
"'ConnectSequence#appendIf() takes 2 arguments. '",
"errorMsg",
"+=",
"arguments",
".",
"length",
"+",
"' given.'",
"throw",
"new",
"MissingArgumentError",
"(",
"errorMsg",
")",
"}",
"if",
"(",
"typeof",
"filter",
"!==",
"'function'",
")",
"{",
"errorMsg",
"=",
"'The first argument must be a filter function. '",
"errorMsg",
"+=",
"typeof",
"filter",
"+",
"' given.'",
"throw",
"new",
"TypeError",
"(",
"errorMsg",
")",
"}",
"var",
"middleware",
",",
"i",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<",
"arguments",
".",
"length",
";",
"i",
"++",
")",
"{",
"middleware",
"=",
"arguments",
"[",
"i",
"]",
"if",
"(",
"typeof",
"middleware",
"!==",
"'function'",
")",
"{",
"errorMsg",
"=",
"'The second argument must be a middleware function. '",
"errorMsg",
"+=",
"typeof",
"middleware",
"+",
"' given.'",
"throw",
"new",
"TypeError",
"(",
"errorMsg",
")",
"}",
"middlewares",
".",
"push",
"(",
"middleware",
")",
"}",
"var",
"firstMiddleware",
"=",
"middlewares",
"[",
"0",
"]",
"if",
"(",
"isErrorHandler",
"(",
"firstMiddleware",
")",
")",
"{",
"this",
".",
"append",
"(",
"function",
"(",
"err",
",",
"req",
",",
"res",
",",
"next",
")",
"{",
"req",
".",
"__connectSequenceFilterValue",
"=",
"filter",
"(",
"req",
")",
"if",
"(",
"req",
".",
"__connectSequenceFilterValue",
")",
"{",
"firstMiddleware",
"(",
"err",
",",
"req",
",",
"res",
",",
"next",
")",
"}",
"else",
"{",
"next",
"(",
")",
"}",
"}",
")",
"}",
"else",
"{",
"this",
".",
"append",
"(",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"req",
".",
"__connectSequenceFilterValue",
"=",
"filter",
"(",
"req",
")",
"if",
"(",
"req",
".",
"__connectSequenceFilterValue",
")",
"{",
"firstMiddleware",
"(",
"req",
",",
"res",
",",
"next",
")",
"}",
"else",
"{",
"next",
"(",
")",
"}",
"}",
")",
"}",
"for",
"(",
"i",
"=",
"1",
";",
"i",
"<",
"middlewares",
".",
"length",
";",
"i",
"++",
")",
"{",
"middleware",
"=",
"middlewares",
"[",
"i",
"]",
"appendOnFilterValue",
".",
"call",
"(",
"this",
",",
"middleware",
")",
"}",
"return",
"this",
"}"
] | Append an arbitrary number of middlewares as an argument list if the filter pass at runtime of the first middleware in the given list
@method
@memberof ConnectSequence.prototype
@param {Function} filter A filter function (returning a Boolean)
@param {...Function} middlewares A list of middleware functions (or errorHandler middlewares)
@returns {ConnectSequence} a reference to the instance to be chainable | [
"Append",
"an",
"arbitrary",
"number",
"of",
"middlewares",
"as",
"an",
"argument",
"list",
"if",
"the",
"filter",
"pass",
"at",
"runtime",
"of",
"the",
"first",
"middleware",
"in",
"the",
"given",
"list"
] | 8b0490d75596107b7c37e2c2cfa4d0486f3eda1a | https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/ConnectSequence.js#L150-L203 | train |
sirap-group/connect-sequence | lib/ConnectSequence.js | appendListIf | function appendListIf (filter, middlewares) {
var args = [filter]
for (var i = 0; i < middlewares.length; i++) {
args.push(middlewares[i])
}
return this.appendIf.apply(this, args)
} | javascript | function appendListIf (filter, middlewares) {
var args = [filter]
for (var i = 0; i < middlewares.length; i++) {
args.push(middlewares[i])
}
return this.appendIf.apply(this, args)
} | [
"function",
"appendListIf",
"(",
"filter",
",",
"middlewares",
")",
"{",
"var",
"args",
"=",
"[",
"filter",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"middlewares",
".",
"length",
";",
"i",
"++",
")",
"{",
"args",
".",
"push",
"(",
"middlewares",
"[",
"i",
"]",
")",
"}",
"return",
"this",
".",
"appendIf",
".",
"apply",
"(",
"this",
",",
"args",
")",
"}"
] | A middleware filter function run at the middleware runtime, causing the middleware or middleware list should be ran or skiped
@callback middlewareFilter
@param {IncomingMessage} req The express request object
@returns {Boolean}
Append an arbitrary number of middlewares as an array if the filter pass at runtime of the first middleware in the given list
@method
@memberof ConnectSequence.prototype
@param {middlewareFilter} filter A filter function on the req object
@param {Array<Function>} middlewares An array of middleware functions (or errorHandler middlewares)
@returns {ConnectSequence} a reference to the instance to be chainable | [
"A",
"middleware",
"filter",
"function",
"run",
"at",
"the",
"middleware",
"runtime",
"causing",
"the",
"middleware",
"or",
"middleware",
"list",
"should",
"be",
"ran",
"or",
"skiped"
] | 8b0490d75596107b7c37e2c2cfa4d0486f3eda1a | https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/ConnectSequence.js#L220-L226 | train |
sirap-group/connect-sequence | lib/ConnectSequence.js | isErrorHandler | function isErrorHandler (cb) {
var str = cb.toString()
var args = str.split('(')[1].split(')')[0].split(',')
return args.length === 4
} | javascript | function isErrorHandler (cb) {
var str = cb.toString()
var args = str.split('(')[1].split(')')[0].split(',')
return args.length === 4
} | [
"function",
"isErrorHandler",
"(",
"cb",
")",
"{",
"var",
"str",
"=",
"cb",
".",
"toString",
"(",
")",
"var",
"args",
"=",
"str",
".",
"split",
"(",
"'('",
")",
"[",
"1",
"]",
".",
"split",
"(",
"')'",
")",
"[",
"0",
"]",
".",
"split",
"(",
"','",
")",
"return",
"args",
".",
"length",
"===",
"4",
"}"
] | Tells if a given middleware is a regular middleware or an error handler
@function
@inner
@private
@param {Function} middleware
@returns {Boolean} | [
"Tells",
"if",
"a",
"given",
"middleware",
"is",
"a",
"regular",
"middleware",
"or",
"an",
"error",
"handler"
] | 8b0490d75596107b7c37e2c2cfa4d0486f3eda1a | https://github.com/sirap-group/connect-sequence/blob/8b0490d75596107b7c37e2c2cfa4d0486f3eda1a/lib/ConnectSequence.js#L236-L240 | train |
nknapp/thought | handlebars/helpers/dirTree.js | condense | function condense (node) {
if (node.nodes.length === 1 && node.nodes[0].nodes.length > 0) {
return condense({
label: (node.label || '') + node.nodes[0].label,
nodes: node.nodes[0].nodes
})
} else {
return {
label: node.label,
nodes: node.nodes.map(condense)
}
}
} | javascript | function condense (node) {
if (node.nodes.length === 1 && node.nodes[0].nodes.length > 0) {
return condense({
label: (node.label || '') + node.nodes[0].label,
nodes: node.nodes[0].nodes
})
} else {
return {
label: node.label,
nodes: node.nodes.map(condense)
}
}
} | [
"function",
"condense",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"nodes",
".",
"length",
"===",
"1",
"&&",
"node",
".",
"nodes",
"[",
"0",
"]",
".",
"nodes",
".",
"length",
">",
"0",
")",
"{",
"return",
"condense",
"(",
"{",
"label",
":",
"(",
"node",
".",
"label",
"||",
"''",
")",
"+",
"node",
".",
"nodes",
"[",
"0",
"]",
".",
"label",
",",
"nodes",
":",
"node",
".",
"nodes",
"[",
"0",
"]",
".",
"nodes",
"}",
")",
"}",
"else",
"{",
"return",
"{",
"label",
":",
"node",
".",
"label",
",",
"nodes",
":",
"node",
".",
"nodes",
".",
"map",
"(",
"condense",
")",
"}",
"}",
"}"
] | Merge an archy-node with its single child, but not with a leaf node.
Keep nodes with zero, two or more childs.
@access private | [
"Merge",
"an",
"archy",
"-",
"node",
"with",
"its",
"single",
"child",
"but",
"not",
"with",
"a",
"leaf",
"node",
".",
"Keep",
"nodes",
"with",
"zero",
"two",
"or",
"more",
"childs",
"."
] | 2ae991f2d3065ff4eae4df544d20787b07be5116 | https://github.com/nknapp/thought/blob/2ae991f2d3065ff4eae4df544d20787b07be5116/handlebars/helpers/dirTree.js#L123-L135 | train |
adrai/devicestack | lib/device.js | Device | function Device(Connection) {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (Device.prototype.log) {
Device.prototype.log = _.wrap(Device.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = Device.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.id = uuid();
this.Connection = Connection;
this.attributes = { id: this.id };
this.on('disconnect', function() {
self.connection = null;
});
} | javascript | function Device(Connection) {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (Device.prototype.log) {
Device.prototype.log = _.wrap(Device.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = Device.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.id = uuid();
this.Connection = Connection;
this.attributes = { id: this.id };
this.on('disconnect', function() {
self.connection = null;
});
} | [
"function",
"Device",
"(",
"Connection",
")",
"{",
"var",
"self",
"=",
"this",
";",
"EventEmitter2",
".",
"call",
"(",
"this",
",",
"{",
"wildcard",
":",
"true",
",",
"delimiter",
":",
"':'",
",",
"maxListeners",
":",
"1000",
"}",
")",
";",
"if",
"(",
"this",
".",
"log",
")",
"{",
"this",
".",
"log",
"=",
"_",
".",
"wrap",
"(",
"this",
".",
"log",
",",
"function",
"(",
"func",
",",
"msg",
")",
"{",
"func",
"(",
"self",
".",
"constructor",
".",
"name",
"+",
"': '",
"+",
"msg",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"Device",
".",
"prototype",
".",
"log",
")",
"{",
"Device",
".",
"prototype",
".",
"log",
"=",
"_",
".",
"wrap",
"(",
"Device",
".",
"prototype",
".",
"log",
",",
"function",
"(",
"func",
",",
"msg",
")",
"{",
"func",
"(",
"self",
".",
"constructor",
".",
"name",
"+",
"': '",
"+",
"msg",
")",
";",
"}",
")",
";",
"this",
".",
"log",
"=",
"Device",
".",
"prototype",
".",
"log",
";",
"}",
"else",
"{",
"var",
"debug",
"=",
"require",
"(",
"'debug'",
")",
"(",
"this",
".",
"constructor",
".",
"name",
")",
";",
"this",
".",
"log",
"=",
"function",
"(",
"msg",
")",
"{",
"debug",
"(",
"msg",
")",
";",
"}",
";",
"}",
"this",
".",
"id",
"=",
"uuid",
"(",
")",
";",
"this",
".",
"Connection",
"=",
"Connection",
";",
"this",
".",
"attributes",
"=",
"{",
"id",
":",
"this",
".",
"id",
"}",
";",
"this",
".",
"on",
"(",
"'disconnect'",
",",
"function",
"(",
")",
"{",
"self",
".",
"connection",
"=",
"null",
";",
"}",
")",
";",
"}"
] | Device represents your physical device.
@param {Object} Connection The constructor function of the connection. | [
"Device",
"represents",
"your",
"physical",
"device",
"."
] | c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76 | https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/device.js#L10-L44 | train |
adrai/devicestack | lib/ftdi/device.js | FtdiDevice | function FtdiDevice(deviceSettings, connectionSettings, Connection) {
// call super class
Device.call(this, Connection);
if (deviceSettings instanceof ftdi.FtdiDevice) {
this.ftdiDevice = deviceSettings;
this.set(this.ftdiDevice.deviceSettings);
} else {
this.set(deviceSettings);
}
this.set('connectionSettings', connectionSettings);
this.set('state', 'close');
} | javascript | function FtdiDevice(deviceSettings, connectionSettings, Connection) {
// call super class
Device.call(this, Connection);
if (deviceSettings instanceof ftdi.FtdiDevice) {
this.ftdiDevice = deviceSettings;
this.set(this.ftdiDevice.deviceSettings);
} else {
this.set(deviceSettings);
}
this.set('connectionSettings', connectionSettings);
this.set('state', 'close');
} | [
"function",
"FtdiDevice",
"(",
"deviceSettings",
",",
"connectionSettings",
",",
"Connection",
")",
"{",
"Device",
".",
"call",
"(",
"this",
",",
"Connection",
")",
";",
"if",
"(",
"deviceSettings",
"instanceof",
"ftdi",
".",
"FtdiDevice",
")",
"{",
"this",
".",
"ftdiDevice",
"=",
"deviceSettings",
";",
"this",
".",
"set",
"(",
"this",
".",
"ftdiDevice",
".",
"deviceSettings",
")",
";",
"}",
"else",
"{",
"this",
".",
"set",
"(",
"deviceSettings",
")",
";",
"}",
"this",
".",
"set",
"(",
"'connectionSettings'",
",",
"connectionSettings",
")",
";",
"this",
".",
"set",
"(",
"'state'",
",",
"'close'",
")",
";",
"}"
] | FtdiDevice represents your physical device.
Extends Device.
@param {Object} deviceSettings The device settings (locationId, serial, index, description).
@param {Object} connectionSettings The connection settings (baudrate, databits, stopbits, parity).
@param {Object} Connection The constructor function of the connection. | [
"FtdiDevice",
"represents",
"your",
"physical",
"device",
".",
"Extends",
"Device",
"."
] | c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76 | https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/ftdi/device.js#L13-L28 | train |
dfilatov/vow-queue | lib/queue.js | function(taskFn, taskParams) {
var task = this._buildTask(taskFn, taskParams);
if(task.params.weight > this._params.weightLimit) {
throw Error('task with weight of ' +
task.params.weight +
' can\'t be performed in queue with limit of ' +
this._params.weightLimit);
}
this._enqueueTask(task);
this._isStopped || this._scheduleRun();
task.defer.promise().always(
function() {
this._stats.processingTasksCount--;
this._stats.processedTasksCount++;
},
this);
return task.defer.promise();
} | javascript | function(taskFn, taskParams) {
var task = this._buildTask(taskFn, taskParams);
if(task.params.weight > this._params.weightLimit) {
throw Error('task with weight of ' +
task.params.weight +
' can\'t be performed in queue with limit of ' +
this._params.weightLimit);
}
this._enqueueTask(task);
this._isStopped || this._scheduleRun();
task.defer.promise().always(
function() {
this._stats.processingTasksCount--;
this._stats.processedTasksCount++;
},
this);
return task.defer.promise();
} | [
"function",
"(",
"taskFn",
",",
"taskParams",
")",
"{",
"var",
"task",
"=",
"this",
".",
"_buildTask",
"(",
"taskFn",
",",
"taskParams",
")",
";",
"if",
"(",
"task",
".",
"params",
".",
"weight",
">",
"this",
".",
"_params",
".",
"weightLimit",
")",
"{",
"throw",
"Error",
"(",
"'task with weight of '",
"+",
"task",
".",
"params",
".",
"weight",
"+",
"' can\\'t be performed in queue with limit of '",
"+",
"\\'",
")",
";",
"}",
"this",
".",
"_params",
".",
"weightLimit",
"this",
".",
"_enqueueTask",
"(",
"task",
")",
";",
"this",
".",
"_isStopped",
"||",
"this",
".",
"_scheduleRun",
"(",
")",
";",
"task",
".",
"defer",
".",
"promise",
"(",
")",
".",
"always",
"(",
"function",
"(",
")",
"{",
"this",
".",
"_stats",
".",
"processingTasksCount",
"--",
";",
"this",
".",
"_stats",
".",
"processedTasksCount",
"++",
";",
"}",
",",
"this",
")",
";",
"}"
] | Adds task to queue
@param {Function} taskFn
@param {Object} [taskParams]
@param {Number} [taskParams.weight=1]
@param {Number} [taskParams.priority=1]
@returns {vow:promise} | [
"Adds",
"task",
"to",
"queue"
] | 32661fa71359a5fbcb2bd75e2e7b6c3cff048b6e | https://github.com/dfilatov/vow-queue/blob/32661fa71359a5fbcb2bd75e2e7b6c3cff048b6e/lib/queue.js#L72-L93 | train |
|
dfilatov/vow-queue | lib/queue.js | function() {
if(!this._isStopped) {
return;
}
this._isStopped = false;
var processedBuffer = this._processedBuffer;
if(processedBuffer.length) {
this._processedBuffer = [];
nextTick(function() {
while(processedBuffer.length) {
processedBuffer.shift()();
}
});
}
this._hasPendingTasks() && this._scheduleRun();
} | javascript | function() {
if(!this._isStopped) {
return;
}
this._isStopped = false;
var processedBuffer = this._processedBuffer;
if(processedBuffer.length) {
this._processedBuffer = [];
nextTick(function() {
while(processedBuffer.length) {
processedBuffer.shift()();
}
});
}
this._hasPendingTasks() && this._scheduleRun();
} | [
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_isStopped",
")",
"{",
"return",
";",
"}",
"this",
".",
"_isStopped",
"=",
"false",
";",
"var",
"processedBuffer",
"=",
"this",
".",
"_processedBuffer",
";",
"if",
"(",
"processedBuffer",
".",
"length",
")",
"{",
"this",
".",
"_processedBuffer",
"=",
"[",
"]",
";",
"nextTick",
"(",
"function",
"(",
")",
"{",
"while",
"(",
"processedBuffer",
".",
"length",
")",
"{",
"processedBuffer",
".",
"shift",
"(",
")",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
"this",
".",
"_hasPendingTasks",
"(",
")",
"&&",
"this",
".",
"_scheduleRun",
"(",
")",
";",
"}"
] | Starts processing of queue | [
"Starts",
"processing",
"of",
"queue"
] | 32661fa71359a5fbcb2bd75e2e7b6c3cff048b6e | https://github.com/dfilatov/vow-queue/blob/32661fa71359a5fbcb2bd75e2e7b6c3cff048b6e/lib/queue.js#L98-L115 | train |
|
scijs/cwise-compiler | lib/compile.js | countMatches | function countMatches(orders) {
var matched = 0, dimension = orders[0].length
while(matched < dimension) {
for(var j=1; j<orders.length; ++j) {
if(orders[j][matched] !== orders[0][matched]) {
return matched
}
}
++matched
}
return matched
} | javascript | function countMatches(orders) {
var matched = 0, dimension = orders[0].length
while(matched < dimension) {
for(var j=1; j<orders.length; ++j) {
if(orders[j][matched] !== orders[0][matched]) {
return matched
}
}
++matched
}
return matched
} | [
"function",
"countMatches",
"(",
"orders",
")",
"{",
"var",
"matched",
"=",
"0",
",",
"dimension",
"=",
"orders",
"[",
"0",
"]",
".",
"length",
"while",
"(",
"matched",
"<",
"dimension",
")",
"{",
"for",
"(",
"var",
"j",
"=",
"1",
";",
"j",
"<",
"orders",
".",
"length",
";",
"++",
"j",
")",
"{",
"if",
"(",
"orders",
"[",
"j",
"]",
"[",
"matched",
"]",
"!==",
"orders",
"[",
"0",
"]",
"[",
"matched",
"]",
")",
"{",
"return",
"matched",
"}",
"}",
"++",
"matched",
"}",
"return",
"matched",
"}"
] | Count the number of compatible inner orders This is the length of the longest common prefix of the arrays in orders. Each array in orders lists the dimensions of the correspond ndarray in order of increasing stride. This is thus the maximum number of dimensions that can be efficiently traversed by simple nested loops for all arrays. | [
"Count",
"the",
"number",
"of",
"compatible",
"inner",
"orders",
"This",
"is",
"the",
"length",
"of",
"the",
"longest",
"common",
"prefix",
"of",
"the",
"arrays",
"in",
"orders",
".",
"Each",
"array",
"in",
"orders",
"lists",
"the",
"dimensions",
"of",
"the",
"correspond",
"ndarray",
"in",
"order",
"of",
"increasing",
"stride",
".",
"This",
"is",
"thus",
"the",
"maximum",
"number",
"of",
"dimensions",
"that",
"can",
"be",
"efficiently",
"traversed",
"by",
"simple",
"nested",
"loops",
"for",
"all",
"arrays",
"."
] | b65933f021302e15c6d4624353bb4b69168cd543 | https://github.com/scijs/cwise-compiler/blob/b65933f021302e15c6d4624353bb4b69168cd543/lib/compile.js#L101-L112 | train |
adrai/devicestack | lib/ftdiserial/device.js | FtdiSerialDevice | function FtdiSerialDevice(deviceSettings, connectionSettings, Connection) {
if (_.isString(deviceSettings) && (deviceSettings.indexOf('COM') === 0 || deviceSettings.indexOf('/') === 0)) {
this.isSerialDevice = true;
// call super class
SerialDevice.call(this,
deviceSettings,
connectionSettings,
Connection
);
} else {
this.isFtdiDevice = true;
// call super class
FtdiDevice.call(this,
deviceSettings,
connectionSettings,
Connection
);
}
} | javascript | function FtdiSerialDevice(deviceSettings, connectionSettings, Connection) {
if (_.isString(deviceSettings) && (deviceSettings.indexOf('COM') === 0 || deviceSettings.indexOf('/') === 0)) {
this.isSerialDevice = true;
// call super class
SerialDevice.call(this,
deviceSettings,
connectionSettings,
Connection
);
} else {
this.isFtdiDevice = true;
// call super class
FtdiDevice.call(this,
deviceSettings,
connectionSettings,
Connection
);
}
} | [
"function",
"FtdiSerialDevice",
"(",
"deviceSettings",
",",
"connectionSettings",
",",
"Connection",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"deviceSettings",
")",
"&&",
"(",
"deviceSettings",
".",
"indexOf",
"(",
"'COM'",
")",
"===",
"0",
"||",
"deviceSettings",
".",
"indexOf",
"(",
"'/'",
")",
"===",
"0",
")",
")",
"{",
"this",
".",
"isSerialDevice",
"=",
"true",
";",
"SerialDevice",
".",
"call",
"(",
"this",
",",
"deviceSettings",
",",
"connectionSettings",
",",
"Connection",
")",
";",
"}",
"else",
"{",
"this",
".",
"isFtdiDevice",
"=",
"true",
";",
"FtdiDevice",
".",
"call",
"(",
"this",
",",
"deviceSettings",
",",
"connectionSettings",
",",
"Connection",
")",
";",
"}",
"}"
] | FtdiSerialDevice represents your physical device.
Extends Device.
@param {Object} deviceSettings The device settings (locationId, serial, index, description) or (portName).
@param {Object} connectionSettings The connection settings (baudrate, databits, stopbits, parity).
@param {Object} Connection The constructor function of the connection. | [
"FtdiSerialDevice",
"represents",
"your",
"physical",
"device",
".",
"Extends",
"Device",
"."
] | c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76 | https://github.com/adrai/devicestack/blob/c0e20b799b5d3d7b5fbd8f0a3b8ab21c13fcad76/lib/ftdiserial/device.js#L14-L33 | train |
wikimedia/banana-i18n | src/emitter.js | strongDirFromContent | function strongDirFromContent (text) {
var m = text.match(strongDirRegExp)
if (!m) {
return null
}
if (m[2] === undefined) {
return 'ltr'
}
return 'rtl'
} | javascript | function strongDirFromContent (text) {
var m = text.match(strongDirRegExp)
if (!m) {
return null
}
if (m[2] === undefined) {
return 'ltr'
}
return 'rtl'
} | [
"function",
"strongDirFromContent",
"(",
"text",
")",
"{",
"var",
"m",
"=",
"text",
".",
"match",
"(",
"strongDirRegExp",
")",
"if",
"(",
"!",
"m",
")",
"{",
"return",
"null",
"}",
"if",
"(",
"m",
"[",
"2",
"]",
"===",
"undefined",
")",
"{",
"return",
"'ltr'",
"}",
"return",
"'rtl'",
"}"
] | Gets directionality of the first strongly directional codepoint
This is the rule the BIDI algorithm uses to determine the directionality of
paragraphs ( http://unicode.org/reports/tr9/#The_Paragraph_Level ) and
FSI isolates ( http://unicode.org/reports/tr9/#Explicit_Directional_Isolates ).
TODO: Does not handle BIDI control characters inside the text.
TODO: Does not handle unallocated characters.
@param {string} text The text from which to extract initial directionality.
@return {string} Directionality (either 'ltr' or 'rtl') | [
"Gets",
"directionality",
"of",
"the",
"first",
"strongly",
"directional",
"codepoint"
] | 17bff23a56d85db02ec0e2a4f908413bb56be03f | https://github.com/wikimedia/banana-i18n/blob/17bff23a56d85db02ec0e2a4f908413bb56be03f/src/emitter.js#L208-L217 | train |
rootsdev/gedcomx-js | src/atom/AtomCategory.js | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomCategory)){
return new AtomCategory(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomCategory.isInstance(json)){
return json;
}
this.init(json);
} | javascript | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomCategory)){
return new AtomCategory(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomCategory.isInstance(json)){
return json;
}
this.init(json);
} | [
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"AtomCategory",
")",
")",
"{",
"return",
"new",
"AtomCategory",
"(",
"json",
")",
";",
"}",
"if",
"(",
"AtomCategory",
".",
"isInstance",
"(",
"json",
")",
")",
"{",
"return",
"json",
";",
"}",
"this",
".",
"init",
"(",
"json",
")",
";",
"}"
] | Information about a category associated with an atom entry or feed.
@see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/atom-model-specification.md#atom-json-media-type|GEDCOM X Atom JSON Spec}
@see {@link https://tools.ietf.org/html/rfc4287#section-4.2.2|RFC 4287}
@class AtomCategory
@extends AtomCommon
@param {Object} [json] | [
"Information",
"about",
"a",
"category",
"associated",
"with",
"an",
"atom",
"entry",
"or",
"feed",
"."
] | 08b2fcde96f1e301c78561bfb7a8b0cac606e26e | https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/atom/AtomCategory.js#L16-L29 | train |
|
rootsdev/gedcomx-js | src/core/Agent.js | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Agent)){
return new Agent(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Agent.isInstance(json)){
return json;
}
this.init(json);
} | javascript | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Agent)){
return new Agent(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Agent.isInstance(json)){
return json;
}
this.init(json);
} | [
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Agent",
")",
")",
"{",
"return",
"new",
"Agent",
"(",
"json",
")",
";",
"}",
"if",
"(",
"Agent",
".",
"isInstance",
"(",
"json",
")",
")",
"{",
"return",
"json",
";",
"}",
"this",
".",
"init",
"(",
"json",
")",
";",
"}"
] | Someone or something that curates genealogical data, such as a genealogical
researcher, user of software, or organization.
@see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#agent|GEDCOM X JSON Spec}
@class
@extends ExtensibleData
@param {Object} [json] | [
"Someone",
"or",
"something",
"that",
"curates",
"genealogical",
"data",
"such",
"as",
"a",
"genealogical",
"researcher",
"user",
"of",
"software",
"or",
"organization",
"."
] | 08b2fcde96f1e301c78561bfb7a8b0cac606e26e | https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Agent.js#L14-L27 | train |
|
AppGeo/cartodb | lib/raw.js | toSQL | function toSQL() {
if (this._cached) {
return this._cached;
}
if (Array.isArray(this.bindings)) {
this._cached = replaceRawArrBindings(this);
} else if (this.bindings && typeof this.bindings === 'object') {
this._cached = replaceKeyBindings(this);
} else {
this._cached = {
method: 'raw',
sql: this.sql,
bindings: this.bindings
};
}
if (this._wrappedBefore) {
this._cached.sql = this._wrappedBefore + this._cached.sql;
}
if (this._wrappedAfter) {
this._cached.sql = this._cached.sql + this._wrappedAfter;
}
this._cached.options = assign({}, this._options);
return this._cached;
} | javascript | function toSQL() {
if (this._cached) {
return this._cached;
}
if (Array.isArray(this.bindings)) {
this._cached = replaceRawArrBindings(this);
} else if (this.bindings && typeof this.bindings === 'object') {
this._cached = replaceKeyBindings(this);
} else {
this._cached = {
method: 'raw',
sql: this.sql,
bindings: this.bindings
};
}
if (this._wrappedBefore) {
this._cached.sql = this._wrappedBefore + this._cached.sql;
}
if (this._wrappedAfter) {
this._cached.sql = this._cached.sql + this._wrappedAfter;
}
this._cached.options = assign({}, this._options);
return this._cached;
} | [
"function",
"toSQL",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_cached",
")",
"{",
"return",
"this",
".",
"_cached",
";",
"}",
"if",
"(",
"Array",
".",
"isArray",
"(",
"this",
".",
"bindings",
")",
")",
"{",
"this",
".",
"_cached",
"=",
"replaceRawArrBindings",
"(",
"this",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"bindings",
"&&",
"typeof",
"this",
".",
"bindings",
"===",
"'object'",
")",
"{",
"this",
".",
"_cached",
"=",
"replaceKeyBindings",
"(",
"this",
")",
";",
"}",
"else",
"{",
"this",
".",
"_cached",
"=",
"{",
"method",
":",
"'raw'",
",",
"sql",
":",
"this",
".",
"sql",
",",
"bindings",
":",
"this",
".",
"bindings",
"}",
";",
"}",
"if",
"(",
"this",
".",
"_wrappedBefore",
")",
"{",
"this",
".",
"_cached",
".",
"sql",
"=",
"this",
".",
"_wrappedBefore",
"+",
"this",
".",
"_cached",
".",
"sql",
";",
"}",
"if",
"(",
"this",
".",
"_wrappedAfter",
")",
"{",
"this",
".",
"_cached",
".",
"sql",
"=",
"this",
".",
"_cached",
".",
"sql",
"+",
"this",
".",
"_wrappedAfter",
";",
"}",
"this",
".",
"_cached",
".",
"options",
"=",
"assign",
"(",
"{",
"}",
",",
"this",
".",
"_options",
")",
";",
"return",
"this",
".",
"_cached",
";",
"}"
] | Returns the raw sql for the query. | [
"Returns",
"the",
"raw",
"sql",
"for",
"the",
"query",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/raw.js#L63-L86 | train |
AckerApple/ack-node | js/modules/reqres/res.js | reqres | function reqres(res, req) {
if (req && req._headers) {
throw new Error('Received response object where request object was expected');
}
this.res = res;
this.req = req;
if (res) {
if (res.$ && res.$.data) {
this.data = res.$.data;
}
else {
this.data = { error: null };
if (!res.$) {
res.$ = this;
}
}
}
} | javascript | function reqres(res, req) {
if (req && req._headers) {
throw new Error('Received response object where request object was expected');
}
this.res = res;
this.req = req;
if (res) {
if (res.$ && res.$.data) {
this.data = res.$.data;
}
else {
this.data = { error: null };
if (!res.$) {
res.$ = this;
}
}
}
} | [
"function",
"reqres",
"(",
"res",
",",
"req",
")",
"{",
"if",
"(",
"req",
"&&",
"req",
".",
"_headers",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Received response object where request object was expected'",
")",
";",
"}",
"this",
".",
"res",
"=",
"res",
";",
"this",
".",
"req",
"=",
"req",
";",
"if",
"(",
"res",
")",
"{",
"if",
"(",
"res",
".",
"$",
"&&",
"res",
".",
"$",
".",
"data",
")",
"{",
"this",
".",
"data",
"=",
"res",
".",
"$",
".",
"data",
";",
"}",
"else",
"{",
"this",
".",
"data",
"=",
"{",
"error",
":",
"null",
"}",
";",
"if",
"(",
"!",
"res",
".",
"$",
")",
"{",
"res",
".",
"$",
"=",
"this",
";",
"}",
"}",
"}",
"}"
] | inbound request response processor returns function that appends output that also has a tun of helper methods | [
"inbound",
"request",
"response",
"processor",
"returns",
"function",
"that",
"appends",
"output",
"that",
"also",
"has",
"a",
"tun",
"of",
"helper",
"methods"
] | c123d3fcbdd0195630fece6dc9ddee8910c9e115 | https://github.com/AckerApple/ack-node/blob/c123d3fcbdd0195630fece6dc9ddee8910c9e115/js/modules/reqres/res.js#L6-L23 | train |
AckerApple/ack-node | js/modules/reqres/res.js | xreqhan | function xreqhan(res, req, output) {
if (isResHeaderSent(res)) {
return console.error('request already closed', new Error().stack);
}
output = output || '';
var isBinary = output && Buffer.isBuffer(output);
if (isBinary) {
res.end(output, 'binary');
}
else if (res.send) { //Express adds send
res.send(output);
}
else if (res.end) { //base way to end request
output = reqResOutputToString(req, res, output);
res.end(output);
}
resMarkClosed(res); //add indicators that show response has been closed
} | javascript | function xreqhan(res, req, output) {
if (isResHeaderSent(res)) {
return console.error('request already closed', new Error().stack);
}
output = output || '';
var isBinary = output && Buffer.isBuffer(output);
if (isBinary) {
res.end(output, 'binary');
}
else if (res.send) { //Express adds send
res.send(output);
}
else if (res.end) { //base way to end request
output = reqResOutputToString(req, res, output);
res.end(output);
}
resMarkClosed(res); //add indicators that show response has been closed
} | [
"function",
"xreqhan",
"(",
"res",
",",
"req",
",",
"output",
")",
"{",
"if",
"(",
"isResHeaderSent",
"(",
"res",
")",
")",
"{",
"return",
"console",
".",
"error",
"(",
"'request already closed'",
",",
"new",
"Error",
"(",
")",
".",
"stack",
")",
";",
"}",
"output",
"=",
"output",
"||",
"''",
";",
"var",
"isBinary",
"=",
"output",
"&&",
"Buffer",
".",
"isBuffer",
"(",
"output",
")",
";",
"if",
"(",
"isBinary",
")",
"{",
"res",
".",
"end",
"(",
"output",
",",
"'binary'",
")",
";",
"}",
"else",
"if",
"(",
"res",
".",
"send",
")",
"{",
"res",
".",
"send",
"(",
"output",
")",
";",
"}",
"else",
"if",
"(",
"res",
".",
"end",
")",
"{",
"output",
"=",
"reqResOutputToString",
"(",
"req",
",",
"res",
",",
"output",
")",
";",
"res",
".",
"end",
"(",
"output",
")",
";",
"}",
"resMarkClosed",
"(",
"res",
")",
";",
"}"
] | close request handler | [
"close",
"request",
"handler"
] | c123d3fcbdd0195630fece6dc9ddee8910c9e115 | https://github.com/AckerApple/ack-node/blob/c123d3fcbdd0195630fece6dc9ddee8910c9e115/js/modules/reqres/res.js#L251-L268 | train |
rootsdev/gedcomx-js | src/records/CollectionContent.js | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof CollectionContent)){
return new CollectionContent(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(CollectionContent.isInstance(json)){
return json;
}
this.init(json);
} | javascript | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof CollectionContent)){
return new CollectionContent(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(CollectionContent.isInstance(json)){
return json;
}
this.init(json);
} | [
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"CollectionContent",
")",
")",
"{",
"return",
"new",
"CollectionContent",
"(",
"json",
")",
";",
"}",
"if",
"(",
"CollectionContent",
".",
"isInstance",
"(",
"json",
")",
")",
"{",
"return",
"json",
";",
"}",
"this",
".",
"init",
"(",
"json",
")",
";",
"}"
] | Information about the contents of a collection.
@see {@link https://github.com/FamilySearch/gedcomx-record/blob/master/specifications/record-specification.md#collection-content|GEDCOM X Records Spec}
@class CollectionContent
@extends ExtensibleData
@param {Object} [json] | [
"Information",
"about",
"the",
"contents",
"of",
"a",
"collection",
"."
] | 08b2fcde96f1e301c78561bfb7a8b0cac606e26e | https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/records/CollectionContent.js#L14-L27 | train |
|
chromaway/blockchainjs | lib/blockchain/verified.js | isGoodHash | function isGoodHash (hash, target) {
hash = new Buffer(hash, 'hex')
target = new Buffer(target, 'hex')
return _.range(32).some(function (index) {
return hash[index] < target[index]
})
} | javascript | function isGoodHash (hash, target) {
hash = new Buffer(hash, 'hex')
target = new Buffer(target, 'hex')
return _.range(32).some(function (index) {
return hash[index] < target[index]
})
} | [
"function",
"isGoodHash",
"(",
"hash",
",",
"target",
")",
"{",
"hash",
"=",
"new",
"Buffer",
"(",
"hash",
",",
"'hex'",
")",
"target",
"=",
"new",
"Buffer",
"(",
"target",
",",
"'hex'",
")",
"return",
"_",
".",
"range",
"(",
"32",
")",
".",
"some",
"(",
"function",
"(",
"index",
")",
"{",
"return",
"hash",
"[",
"index",
"]",
"<",
"target",
"[",
"index",
"]",
"}",
")",
"}"
] | Check that given `hash` lower than `target`
@param {string} hash
@param {string} target
@return {Boolean} | [
"Check",
"that",
"given",
"hash",
"lower",
"than",
"target"
] | 82ae80147cc24cca42f1e1b6113ea41c45e6aae8 | https://github.com/chromaway/blockchainjs/blob/82ae80147cc24cca42f1e1b6113ea41c45e6aae8/lib/blockchain/verified.js#L89-L96 | train |
chromaway/blockchainjs | lib/blockchain/verified.js | verifyHeader | function verifyHeader (currentHash, currentHeader, hashPrevBlock, prevHeader, target, isTestnet) {
try {
// check hashPrevBlock
assert.equal(hashPrevBlock, currentHeader.hashPrevBlock)
try {
// check difficulty
assert.equal(currentHeader.bits, target.bits)
// check hash and target
assert.equal(isGoodHash(currentHash, target.target), true)
} catch (err) {
// special case for testnet:
// If no block has been found in 20 minutes, the difficulty automatically
// resets back to the minimum for a single block, after which it returns
// to its previous value.
if (!(err instanceof assert.AssertionError &&
isTestnet &&
currentHeader.time - prevHeader.time > 1200)) {
throw err
}
assert.equal(currentHeader.bits, MAX_BITS)
assert.equal(isGoodHash(currentHash, MAX_TARGET), true)
}
} catch (err) {
if (err instanceof assert.AssertionError) {
throw new errors.Blockchain.VerifyHeaderError(currentHash, 'verification failed')
}
throw err
}
} | javascript | function verifyHeader (currentHash, currentHeader, hashPrevBlock, prevHeader, target, isTestnet) {
try {
// check hashPrevBlock
assert.equal(hashPrevBlock, currentHeader.hashPrevBlock)
try {
// check difficulty
assert.equal(currentHeader.bits, target.bits)
// check hash and target
assert.equal(isGoodHash(currentHash, target.target), true)
} catch (err) {
// special case for testnet:
// If no block has been found in 20 minutes, the difficulty automatically
// resets back to the minimum for a single block, after which it returns
// to its previous value.
if (!(err instanceof assert.AssertionError &&
isTestnet &&
currentHeader.time - prevHeader.time > 1200)) {
throw err
}
assert.equal(currentHeader.bits, MAX_BITS)
assert.equal(isGoodHash(currentHash, MAX_TARGET), true)
}
} catch (err) {
if (err instanceof assert.AssertionError) {
throw new errors.Blockchain.VerifyHeaderError(currentHash, 'verification failed')
}
throw err
}
} | [
"function",
"verifyHeader",
"(",
"currentHash",
",",
"currentHeader",
",",
"hashPrevBlock",
",",
"prevHeader",
",",
"target",
",",
"isTestnet",
")",
"{",
"try",
"{",
"assert",
".",
"equal",
"(",
"hashPrevBlock",
",",
"currentHeader",
".",
"hashPrevBlock",
")",
"try",
"{",
"assert",
".",
"equal",
"(",
"currentHeader",
".",
"bits",
",",
"target",
".",
"bits",
")",
"assert",
".",
"equal",
"(",
"isGoodHash",
"(",
"currentHash",
",",
"target",
".",
"target",
")",
",",
"true",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"(",
"err",
"instanceof",
"assert",
".",
"AssertionError",
"&&",
"isTestnet",
"&&",
"currentHeader",
".",
"time",
"-",
"prevHeader",
".",
"time",
">",
"1200",
")",
")",
"{",
"throw",
"err",
"}",
"assert",
".",
"equal",
"(",
"currentHeader",
".",
"bits",
",",
"MAX_BITS",
")",
"assert",
".",
"equal",
"(",
"isGoodHash",
"(",
"currentHash",
",",
"MAX_TARGET",
")",
",",
"true",
")",
"}",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"instanceof",
"assert",
".",
"AssertionError",
")",
"{",
"throw",
"new",
"errors",
".",
"Blockchain",
".",
"VerifyHeaderError",
"(",
"currentHash",
",",
"'verification failed'",
")",
"}",
"throw",
"err",
"}",
"}"
] | Verify current header
@param {string} currentHash
@param {BitcoinHeader} currentHeader
@param {string} hashPrevBlock
@param {BitcoinHeader} prevHeader
@param {{bits: number, target: string}} target
@param {Boolean} isTestnet
@throws {VerifyHeaderError} | [
"Verify",
"current",
"header"
] | 82ae80147cc24cca42f1e1b6113ea41c45e6aae8 | https://github.com/chromaway/blockchainjs/blob/82ae80147cc24cca42f1e1b6113ea41c45e6aae8/lib/blockchain/verified.js#L109-L141 | train |
matthewtoast/runiq | parser/lex.js | clean | function clean(source) {
if (!source) return BLANK;
if (source.charCodeAt(0) === BOM_CODE) source = source.slice(1);
source = source.replace(CR_REGEXP, BLANK).replace(TRAILING_WHITESPACE_REGEXP, BLANK);
return source;
} | javascript | function clean(source) {
if (!source) return BLANK;
if (source.charCodeAt(0) === BOM_CODE) source = source.slice(1);
source = source.replace(CR_REGEXP, BLANK).replace(TRAILING_WHITESPACE_REGEXP, BLANK);
return source;
} | [
"function",
"clean",
"(",
"source",
")",
"{",
"if",
"(",
"!",
"source",
")",
"return",
"BLANK",
";",
"if",
"(",
"source",
".",
"charCodeAt",
"(",
"0",
")",
"===",
"BOM_CODE",
")",
"source",
"=",
"source",
".",
"slice",
"(",
"1",
")",
";",
"source",
"=",
"source",
".",
"replace",
"(",
"CR_REGEXP",
",",
"BLANK",
")",
".",
"replace",
"(",
"TRAILING_WHITESPACE_REGEXP",
",",
"BLANK",
")",
";",
"return",
"source",
";",
"}"
] | Remove any unwanted characters from the raw source code string | [
"Remove",
"any",
"unwanted",
"characters",
"from",
"the",
"raw",
"source",
"code",
"string"
] | 897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d | https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/parser/lex.js#L32-L37 | train |
matthewtoast/runiq | parser/lex.js | lex | function lex(source) {
var tokens = [];
var chunk = clean(source);
var total = chunk.length;
var iterations = 0;
while (chunk.length > 0) {
for (var regexpName in REGEXPS) {
var regexp = REGEXPS[regexpName];
var match = regexp.exec(chunk);
if (match) {
var original = match[0];
var str = original;
if (regexpName === 'string') str = str.replace(/\\"/g, '"');
tokens.push({ type: regexpName, string: str, original: original });
// Need to slice the chunk at the original match length
chunk = chunk.slice(match[0].length, chunk.length);
break;
}
}
// We've probably failed to parse correctly if we get here
if (iterations++ > total) {
var parts = [
'Runiq: Lexer ran too many iterations!',
'--- Failed at chunk: `' + chunk + '`'
];
throw new Error(parts.join('\n'));
}
}
return tokens;
} | javascript | function lex(source) {
var tokens = [];
var chunk = clean(source);
var total = chunk.length;
var iterations = 0;
while (chunk.length > 0) {
for (var regexpName in REGEXPS) {
var regexp = REGEXPS[regexpName];
var match = regexp.exec(chunk);
if (match) {
var original = match[0];
var str = original;
if (regexpName === 'string') str = str.replace(/\\"/g, '"');
tokens.push({ type: regexpName, string: str, original: original });
// Need to slice the chunk at the original match length
chunk = chunk.slice(match[0].length, chunk.length);
break;
}
}
// We've probably failed to parse correctly if we get here
if (iterations++ > total) {
var parts = [
'Runiq: Lexer ran too many iterations!',
'--- Failed at chunk: `' + chunk + '`'
];
throw new Error(parts.join('\n'));
}
}
return tokens;
} | [
"function",
"lex",
"(",
"source",
")",
"{",
"var",
"tokens",
"=",
"[",
"]",
";",
"var",
"chunk",
"=",
"clean",
"(",
"source",
")",
";",
"var",
"total",
"=",
"chunk",
".",
"length",
";",
"var",
"iterations",
"=",
"0",
";",
"while",
"(",
"chunk",
".",
"length",
">",
"0",
")",
"{",
"for",
"(",
"var",
"regexpName",
"in",
"REGEXPS",
")",
"{",
"var",
"regexp",
"=",
"REGEXPS",
"[",
"regexpName",
"]",
";",
"var",
"match",
"=",
"regexp",
".",
"exec",
"(",
"chunk",
")",
";",
"if",
"(",
"match",
")",
"{",
"var",
"original",
"=",
"match",
"[",
"0",
"]",
";",
"var",
"str",
"=",
"original",
";",
"if",
"(",
"regexpName",
"===",
"'string'",
")",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"\\\\\"",
"/",
"g",
",",
"'\"'",
")",
";",
"tokens",
".",
"push",
"(",
"{",
"type",
":",
"regexpName",
",",
"string",
":",
"str",
",",
"original",
":",
"original",
"}",
")",
";",
"chunk",
"=",
"chunk",
".",
"slice",
"(",
"match",
"[",
"0",
"]",
".",
"length",
",",
"chunk",
".",
"length",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"iterations",
"++",
">",
"total",
")",
"{",
"var",
"parts",
"=",
"[",
"'Runiq: Lexer ran too many iterations!'",
",",
"'--- Failed at chunk: `'",
"+",
"chunk",
"+",
"'`'",
"]",
";",
"throw",
"new",
"Error",
"(",
"parts",
".",
"join",
"(",
"'\\n'",
")",
")",
";",
"}",
"}",
"\\n",
"}"
] | Return an array of token objects for the clean source code string | [
"Return",
"an",
"array",
"of",
"token",
"objects",
"for",
"the",
"clean",
"source",
"code",
"string"
] | 897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d | https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/parser/lex.js#L40-L73 | train |
grunjol/nobin-debian-installer | index.js | Deb | function Deb () {
this.data = tar.pack()
this.control = tar.pack()
this.pkgSize = 0
this.controlFile = {}
this.filesMd5 = []
this.dirs = {}
} | javascript | function Deb () {
this.data = tar.pack()
this.control = tar.pack()
this.pkgSize = 0
this.controlFile = {}
this.filesMd5 = []
this.dirs = {}
} | [
"function",
"Deb",
"(",
")",
"{",
"this",
".",
"data",
"=",
"tar",
".",
"pack",
"(",
")",
"this",
".",
"control",
"=",
"tar",
".",
"pack",
"(",
")",
"this",
".",
"pkgSize",
"=",
"0",
"this",
".",
"controlFile",
"=",
"{",
"}",
"this",
".",
"filesMd5",
"=",
"[",
"]",
"this",
".",
"dirs",
"=",
"{",
"}",
"}"
] | Class used for creating .deb packages | [
"Class",
"used",
"for",
"creating",
".",
"deb",
"packages"
] | e28e10a4249749301cb0afbb87343157e45691f8 | https://github.com/grunjol/nobin-debian-installer/blob/e28e10a4249749301cb0afbb87343157e45691f8/index.js#L13-L20 | train |
grunjol/nobin-debian-installer | index.js | buildControlFile | function buildControlFile (tempPath, definition, callback) {
var self = this
var author = ''
if (definition.package.author) {
author = typeof definition.package.author === 'string'
? definition.package.author
: definition.package.author.name + ' <' + definition.package.author.email + '>'
}
self.controlFile = {
Package: definition.info.name || definition.package.name,
Version: definition.package.version + '-' + (definition.info.rev || '1'),
'Installed-Size': Math.ceil(self.pkgSize / 1024),
Section: 'misc',
Priority: 'optional',
Architecture: definition.info.arch || 'all',
Depends: definition.info.depends || 'lsb-base (>= 3.2)',
Maintainer: author
}
// optional items
if (definition.package.license) {
self.controlFile.License = definition.package.license
}
// optional items
if (definition.package.homepage) {
self.controlFile.Homepage = definition.package.homepage
}
self.controlFile.Description = definition.package.description + '\n ' +
(definition.info.name || definition.package.name) +
': ' + definition.package.description
// create the control file
async.parallel([
function createControlFile (prlDone) {
var controlHeader = ''
async.forEachOf(self.controlFile, function (value, key, done) {
controlHeader += key + ': ' + value + '\n'
done()
}, function (err) {
if (err) {
debug('could not write control file')
return prlDone(err)
}
self.control.entry({name: './control'}, controlHeader, prlDone)
})
}, function createHashFile (prlDone) {
var fileContent = ''
for (var i = 0; i < self.filesMd5.length; i++) {
fileContent += self.filesMd5[i].md5 + ' ' + self.filesMd5[i].path.replace(/^\W*/, '') + '\n'
}
self.control.entry({name: './md5sums'}, fileContent, prlDone)
}, function addScripts (prlDone) {
async.forEachOf(definition.info.scripts, function (path, scriptName, doneScript) {
debug('processing script ', path)
async.waterfall([
fs.access.bind(fs, path, fs.F_OK),
fs.stat.bind(fs, path),
function readFile (stats, wtfDone) {
fs.readFile(path, function (err, data) {
wtfDone(err, stats, data)
})
},
function addScript (stats, data, wtfDone) {
debug('adding script ', scriptName)
self.control.entry({
name: './' + scriptName,
size: stats.size,
mode: parseInt('755', 8)
}, data, wtfDone)
}
], doneScript)
}, prlDone)
}
], function (err) {
if (err) {
debug('could not write control tarball')
return callback(err)
}
debug('successfully created control file')
self.control.finalize()
var file = fs.createWriteStream(path.join(tempPath, 'control.tar.gz'))
file.on('finish', callback)
var compress = zlib.createGzip()
compress.pipe(file)
self.control.pipe(compress)
})
} | javascript | function buildControlFile (tempPath, definition, callback) {
var self = this
var author = ''
if (definition.package.author) {
author = typeof definition.package.author === 'string'
? definition.package.author
: definition.package.author.name + ' <' + definition.package.author.email + '>'
}
self.controlFile = {
Package: definition.info.name || definition.package.name,
Version: definition.package.version + '-' + (definition.info.rev || '1'),
'Installed-Size': Math.ceil(self.pkgSize / 1024),
Section: 'misc',
Priority: 'optional',
Architecture: definition.info.arch || 'all',
Depends: definition.info.depends || 'lsb-base (>= 3.2)',
Maintainer: author
}
// optional items
if (definition.package.license) {
self.controlFile.License = definition.package.license
}
// optional items
if (definition.package.homepage) {
self.controlFile.Homepage = definition.package.homepage
}
self.controlFile.Description = definition.package.description + '\n ' +
(definition.info.name || definition.package.name) +
': ' + definition.package.description
// create the control file
async.parallel([
function createControlFile (prlDone) {
var controlHeader = ''
async.forEachOf(self.controlFile, function (value, key, done) {
controlHeader += key + ': ' + value + '\n'
done()
}, function (err) {
if (err) {
debug('could not write control file')
return prlDone(err)
}
self.control.entry({name: './control'}, controlHeader, prlDone)
})
}, function createHashFile (prlDone) {
var fileContent = ''
for (var i = 0; i < self.filesMd5.length; i++) {
fileContent += self.filesMd5[i].md5 + ' ' + self.filesMd5[i].path.replace(/^\W*/, '') + '\n'
}
self.control.entry({name: './md5sums'}, fileContent, prlDone)
}, function addScripts (prlDone) {
async.forEachOf(definition.info.scripts, function (path, scriptName, doneScript) {
debug('processing script ', path)
async.waterfall([
fs.access.bind(fs, path, fs.F_OK),
fs.stat.bind(fs, path),
function readFile (stats, wtfDone) {
fs.readFile(path, function (err, data) {
wtfDone(err, stats, data)
})
},
function addScript (stats, data, wtfDone) {
debug('adding script ', scriptName)
self.control.entry({
name: './' + scriptName,
size: stats.size,
mode: parseInt('755', 8)
}, data, wtfDone)
}
], doneScript)
}, prlDone)
}
], function (err) {
if (err) {
debug('could not write control tarball')
return callback(err)
}
debug('successfully created control file')
self.control.finalize()
var file = fs.createWriteStream(path.join(tempPath, 'control.tar.gz'))
file.on('finish', callback)
var compress = zlib.createGzip()
compress.pipe(file)
self.control.pipe(compress)
})
} | [
"function",
"buildControlFile",
"(",
"tempPath",
",",
"definition",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
"var",
"author",
"=",
"''",
"if",
"(",
"definition",
".",
"package",
".",
"author",
")",
"{",
"author",
"=",
"typeof",
"definition",
".",
"package",
".",
"author",
"===",
"'string'",
"?",
"definition",
".",
"package",
".",
"author",
":",
"definition",
".",
"package",
".",
"author",
".",
"name",
"+",
"' <'",
"+",
"definition",
".",
"package",
".",
"author",
".",
"email",
"+",
"'>'",
"}",
"self",
".",
"controlFile",
"=",
"{",
"Package",
":",
"definition",
".",
"info",
".",
"name",
"||",
"definition",
".",
"package",
".",
"name",
",",
"Version",
":",
"definition",
".",
"package",
".",
"version",
"+",
"'-'",
"+",
"(",
"definition",
".",
"info",
".",
"rev",
"||",
"'1'",
")",
",",
"'Installed-Size'",
":",
"Math",
".",
"ceil",
"(",
"self",
".",
"pkgSize",
"/",
"1024",
")",
",",
"Section",
":",
"'misc'",
",",
"Priority",
":",
"'optional'",
",",
"Architecture",
":",
"definition",
".",
"info",
".",
"arch",
"||",
"'all'",
",",
"Depends",
":",
"definition",
".",
"info",
".",
"depends",
"||",
"'lsb-base (>= 3.2)'",
",",
"Maintainer",
":",
"author",
"}",
"if",
"(",
"definition",
".",
"package",
".",
"license",
")",
"{",
"self",
".",
"controlFile",
".",
"License",
"=",
"definition",
".",
"package",
".",
"license",
"}",
"if",
"(",
"definition",
".",
"package",
".",
"homepage",
")",
"{",
"self",
".",
"controlFile",
".",
"Homepage",
"=",
"definition",
".",
"package",
".",
"homepage",
"}",
"self",
".",
"controlFile",
".",
"Description",
"=",
"definition",
".",
"package",
".",
"description",
"+",
"'\\n '",
"+",
"\\n",
"+",
"(",
"definition",
".",
"info",
".",
"name",
"||",
"definition",
".",
"package",
".",
"name",
")",
"+",
"': '",
"definition",
".",
"package",
".",
"description",
"}"
] | Build the control part of the .deb package. | [
"Build",
"the",
"control",
"part",
"of",
"the",
".",
"deb",
"package",
"."
] | e28e10a4249749301cb0afbb87343157e45691f8 | https://github.com/grunjol/nobin-debian-installer/blob/e28e10a4249749301cb0afbb87343157e45691f8/index.js#L66-L161 | train |
grunjol/nobin-debian-installer | index.js | packFiles | function packFiles (tempPath, files, callback) {
var self = this
async.eachSeries(files, function (crtFile, done) {
var filePath = path.resolve(crtFile.src[0])
debug('adding %s', filePath)
async.waterfall([
fs.stat.bind(fs, filePath),
function (stats, wtfDone) {
if (stats.isDirectory()) {
addParentDirs(self.data, crtFile.dest, self.dirs, done)
} else {
async.waterfall([
fs.readFile.bind(fs, filePath),
function writeFileToTarball (data, wtf2Done) {
self.data.entry({
name: '.' + crtFile.dest,
size: stats.size
}, data, function (err) {
wtf2Done(err, data)
})
},
function processFile (fileData, wtf2Done) {
self.pkgSize += stats.size
self.filesMd5.push({
path: crtFile.dest,
md5: crypto.createHash('md5').update(fileData).digest('hex')
})
wtf2Done()
}
], wtfDone)
}
}
], done)
}, function (err) {
if (err) {
debug('there was a problem adding files to the .deb package: ', err)
callback(err)
} else {
debug('successfully added files to .deb package')
var file = fs.createWriteStream(path.join(tempPath, 'data.tar.gz'))
file.on('finish', callback)
var compress = zlib.createGzip()
compress.pipe(file)
self.data.pipe(compress)
self.data.finalize()
}
})
} | javascript | function packFiles (tempPath, files, callback) {
var self = this
async.eachSeries(files, function (crtFile, done) {
var filePath = path.resolve(crtFile.src[0])
debug('adding %s', filePath)
async.waterfall([
fs.stat.bind(fs, filePath),
function (stats, wtfDone) {
if (stats.isDirectory()) {
addParentDirs(self.data, crtFile.dest, self.dirs, done)
} else {
async.waterfall([
fs.readFile.bind(fs, filePath),
function writeFileToTarball (data, wtf2Done) {
self.data.entry({
name: '.' + crtFile.dest,
size: stats.size
}, data, function (err) {
wtf2Done(err, data)
})
},
function processFile (fileData, wtf2Done) {
self.pkgSize += stats.size
self.filesMd5.push({
path: crtFile.dest,
md5: crypto.createHash('md5').update(fileData).digest('hex')
})
wtf2Done()
}
], wtfDone)
}
}
], done)
}, function (err) {
if (err) {
debug('there was a problem adding files to the .deb package: ', err)
callback(err)
} else {
debug('successfully added files to .deb package')
var file = fs.createWriteStream(path.join(tempPath, 'data.tar.gz'))
file.on('finish', callback)
var compress = zlib.createGzip()
compress.pipe(file)
self.data.pipe(compress)
self.data.finalize()
}
})
} | [
"function",
"packFiles",
"(",
"tempPath",
",",
"files",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
"async",
".",
"eachSeries",
"(",
"files",
",",
"function",
"(",
"crtFile",
",",
"done",
")",
"{",
"var",
"filePath",
"=",
"path",
".",
"resolve",
"(",
"crtFile",
".",
"src",
"[",
"0",
"]",
")",
"debug",
"(",
"'adding %s'",
",",
"filePath",
")",
"async",
".",
"waterfall",
"(",
"[",
"fs",
".",
"stat",
".",
"bind",
"(",
"fs",
",",
"filePath",
")",
",",
"function",
"(",
"stats",
",",
"wtfDone",
")",
"{",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"addParentDirs",
"(",
"self",
".",
"data",
",",
"crtFile",
".",
"dest",
",",
"self",
".",
"dirs",
",",
"done",
")",
"}",
"else",
"{",
"async",
".",
"waterfall",
"(",
"[",
"fs",
".",
"readFile",
".",
"bind",
"(",
"fs",
",",
"filePath",
")",
",",
"function",
"writeFileToTarball",
"(",
"data",
",",
"wtf2Done",
")",
"{",
"self",
".",
"data",
".",
"entry",
"(",
"{",
"name",
":",
"'.'",
"+",
"crtFile",
".",
"dest",
",",
"size",
":",
"stats",
".",
"size",
"}",
",",
"data",
",",
"function",
"(",
"err",
")",
"{",
"wtf2Done",
"(",
"err",
",",
"data",
")",
"}",
")",
"}",
",",
"function",
"processFile",
"(",
"fileData",
",",
"wtf2Done",
")",
"{",
"self",
".",
"pkgSize",
"+=",
"stats",
".",
"size",
"self",
".",
"filesMd5",
".",
"push",
"(",
"{",
"path",
":",
"crtFile",
".",
"dest",
",",
"md5",
":",
"crypto",
".",
"createHash",
"(",
"'md5'",
")",
".",
"update",
"(",
"fileData",
")",
".",
"digest",
"(",
"'hex'",
")",
"}",
")",
"wtf2Done",
"(",
")",
"}",
"]",
",",
"wtfDone",
")",
"}",
"}",
"]",
",",
"done",
")",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"debug",
"(",
"'there was a problem adding files to the .deb package: '",
",",
"err",
")",
"callback",
"(",
"err",
")",
"}",
"else",
"{",
"debug",
"(",
"'successfully added files to .deb package'",
")",
"var",
"file",
"=",
"fs",
".",
"createWriteStream",
"(",
"path",
".",
"join",
"(",
"tempPath",
",",
"'data.tar.gz'",
")",
")",
"file",
".",
"on",
"(",
"'finish'",
",",
"callback",
")",
"var",
"compress",
"=",
"zlib",
".",
"createGzip",
"(",
")",
"compress",
".",
"pipe",
"(",
"file",
")",
"self",
".",
"data",
".",
"pipe",
"(",
"compress",
")",
"self",
".",
"data",
".",
"finalize",
"(",
")",
"}",
"}",
")",
"}"
] | Add files to the .deb package.
@param files - an object with the following format {'path/to/source/dir': 'path/to/target/dir'} (e.g. {'../../src/lib': '/srv/productName/lib'}) | [
"Add",
"files",
"to",
"the",
".",
"deb",
"package",
"."
] | e28e10a4249749301cb0afbb87343157e45691f8 | https://github.com/grunjol/nobin-debian-installer/blob/e28e10a4249749301cb0afbb87343157e45691f8/index.js#L168-L222 | train |
pogosandbox/gpsoauth | index.js | generateSignature | function generateSignature(email, password) {
let googleDefaultPublicKey = 'AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ==';
let keyBuffer = Buffer.from(googleDefaultPublicKey, 'base64');
let pem = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKJv9Wv79JW5TtlG67etCdoHLl
0pYxhUF4HMmVr3lixMKOqa8IIt4iSGXaHcoSmUKzVqeZyid7K0V3FFvhdQQ922hF
RnJhIKmi2VDQY5tOe6SkSNepAdGKaXhseaiEOUIys7EfBE0GyizVoEWNEETVc9+J
DCUdz/y4B2sf+q5n+QIDAQAB
-----END PUBLIC KEY-----`;
let sha = crypto.createHash('sha1');
sha.update(keyBuffer);
let hash = sha.digest().slice(0, 4);
let rsa = new nodeRSA(pem);
let encrypted = rsa.encrypt(email + '\x00' + password);
let base64Output = Buffer.concat([
Buffer.from([0]),
hash,
encrypted
]).toString('base64');
base64Output = base64Output.replace(/\+/g, '-');
base64Output = base64Output.replace(/\//g, '_');
return base64Output;
} | javascript | function generateSignature(email, password) {
let googleDefaultPublicKey = 'AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ==';
let keyBuffer = Buffer.from(googleDefaultPublicKey, 'base64');
let pem = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKJv9Wv79JW5TtlG67etCdoHLl
0pYxhUF4HMmVr3lixMKOqa8IIt4iSGXaHcoSmUKzVqeZyid7K0V3FFvhdQQ922hF
RnJhIKmi2VDQY5tOe6SkSNepAdGKaXhseaiEOUIys7EfBE0GyizVoEWNEETVc9+J
DCUdz/y4B2sf+q5n+QIDAQAB
-----END PUBLIC KEY-----`;
let sha = crypto.createHash('sha1');
sha.update(keyBuffer);
let hash = sha.digest().slice(0, 4);
let rsa = new nodeRSA(pem);
let encrypted = rsa.encrypt(email + '\x00' + password);
let base64Output = Buffer.concat([
Buffer.from([0]),
hash,
encrypted
]).toString('base64');
base64Output = base64Output.replace(/\+/g, '-');
base64Output = base64Output.replace(/\//g, '_');
return base64Output;
} | [
"function",
"generateSignature",
"(",
"email",
",",
"password",
")",
"{",
"let",
"googleDefaultPublicKey",
"=",
"'AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ=='",
";",
"let",
"keyBuffer",
"=",
"Buffer",
".",
"from",
"(",
"googleDefaultPublicKey",
",",
"'base64'",
")",
";",
"let",
"pem",
"=",
"`",
"`",
";",
"let",
"sha",
"=",
"crypto",
".",
"createHash",
"(",
"'sha1'",
")",
";",
"sha",
".",
"update",
"(",
"keyBuffer",
")",
";",
"let",
"hash",
"=",
"sha",
".",
"digest",
"(",
")",
".",
"slice",
"(",
"0",
",",
"4",
")",
";",
"let",
"rsa",
"=",
"new",
"nodeRSA",
"(",
"pem",
")",
";",
"let",
"encrypted",
"=",
"rsa",
".",
"encrypt",
"(",
"email",
"+",
"'\\x00'",
"+",
"\\x00",
")",
";",
"password",
"let",
"base64Output",
"=",
"Buffer",
".",
"concat",
"(",
"[",
"Buffer",
".",
"from",
"(",
"[",
"0",
"]",
")",
",",
"hash",
",",
"encrypted",
"]",
")",
".",
"toString",
"(",
"'base64'",
")",
";",
"base64Output",
"=",
"base64Output",
".",
"replace",
"(",
"/",
"\\+",
"/",
"g",
",",
"'-'",
")",
";",
"base64Output",
"=",
"base64Output",
".",
"replace",
"(",
"/",
"\\/",
"/",
"g",
",",
"'_'",
")",
";",
"}"
] | Generates a signature to be passed into GPS | [
"Generates",
"a",
"signature",
"to",
"be",
"passed",
"into",
"GPS"
] | 9d435010622855704c392fd73f6ae12bcb80d56f | https://github.com/pogosandbox/gpsoauth/blob/9d435010622855704c392fd73f6ae12bcb80d56f/index.js#L27-L56 | train |
devaos/grunt-port-pick | tasks/port-pick.js | function(selectedPort, callback) {
if(selectedPort === false)
grunt.fatal('No available port was found')
self.data.targets.forEach(function(prop) {
pp.injectPort(prop, selectedPort)
})
if(pp.options.name) {
pp.injectPort(pp.options.name, selectedPort)
}
callback(null)
return
} | javascript | function(selectedPort, callback) {
if(selectedPort === false)
grunt.fatal('No available port was found')
self.data.targets.forEach(function(prop) {
pp.injectPort(prop, selectedPort)
})
if(pp.options.name) {
pp.injectPort(pp.options.name, selectedPort)
}
callback(null)
return
} | [
"function",
"(",
"selectedPort",
",",
"callback",
")",
"{",
"if",
"(",
"selectedPort",
"===",
"false",
")",
"grunt",
".",
"fatal",
"(",
"'No available port was found'",
")",
"self",
".",
"data",
".",
"targets",
".",
"forEach",
"(",
"function",
"(",
"prop",
")",
"{",
"pp",
".",
"injectPort",
"(",
"prop",
",",
"selectedPort",
")",
"}",
")",
"if",
"(",
"pp",
".",
"options",
".",
"name",
")",
"{",
"pp",
".",
"injectPort",
"(",
"pp",
".",
"options",
".",
"name",
",",
"selectedPort",
")",
"}",
"callback",
"(",
"null",
")",
"return",
"}"
] | Override the configurations we were told to override | [
"Override",
"the",
"configurations",
"we",
"were",
"told",
"to",
"override"
] | f13ed4a8a8e36dfc48e2a10b98847563ca5541b6 | https://github.com/devaos/grunt-port-pick/blob/f13ed4a8a8e36dfc48e2a10b98847563ca5541b6/tasks/port-pick.js#L261-L275 | train |
|
devaos/grunt-port-pick | tasks/port-pick.js | function(callback) {
var step = 0
async.whilst(
function() {
return ++step <= pp.options.extra
},
function(callback) {
pp.tryPorts = []
var c = grunt.config.get('port-pick-' + step)
// With multiple tasks, do not find a port that we've already found
// in a previous task
if(c) {
callback()
return
}
async.waterfall([
pp.findPort,
function(selectedPort, callback) {
if(selectedPort === false)
grunt.fatal('No available port was found')
grunt.config.set('port-pick-' + this.step, selectedPort)
grunt.log.writeln( '>> '.green + 'port-pick-' + this.step + '=' +
selectedPort)
callback()
}.bind({step: step})
],
function(err) {
callback()
})
},
function(err) {
done()
}
)
} | javascript | function(callback) {
var step = 0
async.whilst(
function() {
return ++step <= pp.options.extra
},
function(callback) {
pp.tryPorts = []
var c = grunt.config.get('port-pick-' + step)
// With multiple tasks, do not find a port that we've already found
// in a previous task
if(c) {
callback()
return
}
async.waterfall([
pp.findPort,
function(selectedPort, callback) {
if(selectedPort === false)
grunt.fatal('No available port was found')
grunt.config.set('port-pick-' + this.step, selectedPort)
grunt.log.writeln( '>> '.green + 'port-pick-' + this.step + '=' +
selectedPort)
callback()
}.bind({step: step})
],
function(err) {
callback()
})
},
function(err) {
done()
}
)
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"step",
"=",
"0",
"async",
".",
"whilst",
"(",
"function",
"(",
")",
"{",
"return",
"++",
"step",
"<=",
"pp",
".",
"options",
".",
"extra",
"}",
",",
"function",
"(",
"callback",
")",
"{",
"pp",
".",
"tryPorts",
"=",
"[",
"]",
"var",
"c",
"=",
"grunt",
".",
"config",
".",
"get",
"(",
"'port-pick-'",
"+",
"step",
")",
"if",
"(",
"c",
")",
"{",
"callback",
"(",
")",
"return",
"}",
"async",
".",
"waterfall",
"(",
"[",
"pp",
".",
"findPort",
",",
"function",
"(",
"selectedPort",
",",
"callback",
")",
"{",
"if",
"(",
"selectedPort",
"===",
"false",
")",
"grunt",
".",
"fatal",
"(",
"'No available port was found'",
")",
"grunt",
".",
"config",
".",
"set",
"(",
"'port-pick-'",
"+",
"this",
".",
"step",
",",
"selectedPort",
")",
"grunt",
".",
"log",
".",
"writeln",
"(",
"'>> '",
".",
"green",
"+",
"'port-pick-'",
"+",
"this",
".",
"step",
"+",
"'='",
"+",
"selectedPort",
")",
"callback",
"(",
")",
"}",
".",
"bind",
"(",
"{",
"step",
":",
"step",
"}",
")",
"]",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
")",
"}",
")",
"}",
",",
"function",
"(",
"err",
")",
"{",
"done",
"(",
")",
"}",
")",
"}"
] | Set some configurations for extra ports template interpolation | [
"Set",
"some",
"configurations",
"for",
"extra",
"ports",
"template",
"interpolation"
] | f13ed4a8a8e36dfc48e2a10b98847563ca5541b6 | https://github.com/devaos/grunt-port-pick/blob/f13ed4a8a8e36dfc48e2a10b98847563ca5541b6/tasks/port-pick.js#L278-L318 | train |
|
AppGeo/cartodb | lib/formatter.js | columnize | function columnize(target) {
var columns = typeof target === 'string' ? [target] : target;
var str = '',
i = -1;
while (++i < columns.length) {
if (i > 0) {
str += ', ';
}
str += this.wrap(columns[i]);
}
return str;
} | javascript | function columnize(target) {
var columns = typeof target === 'string' ? [target] : target;
var str = '',
i = -1;
while (++i < columns.length) {
if (i > 0) {
str += ', ';
}
str += this.wrap(columns[i]);
}
return str;
} | [
"function",
"columnize",
"(",
"target",
")",
"{",
"var",
"columns",
"=",
"typeof",
"target",
"===",
"'string'",
"?",
"[",
"target",
"]",
":",
"target",
";",
"var",
"str",
"=",
"''",
",",
"i",
"=",
"-",
"1",
";",
"while",
"(",
"++",
"i",
"<",
"columns",
".",
"length",
")",
"{",
"if",
"(",
"i",
">",
"0",
")",
"{",
"str",
"+=",
"', '",
";",
"}",
"str",
"+=",
"this",
".",
"wrap",
"(",
"columns",
"[",
"i",
"]",
")",
";",
"}",
"return",
"str",
";",
"}"
] | Accepts a string or array of columns to wrap as appropriate. | [
"Accepts",
"a",
"string",
"or",
"array",
"of",
"columns",
"to",
"wrap",
"as",
"appropriate",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/formatter.js#L26-L37 | train |
AppGeo/cartodb | lib/formatter.js | parameter | function parameter(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
return this.unwrapRaw(value, true) || '?';
} | javascript | function parameter(value) {
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
return this.unwrapRaw(value, true) || '?';
} | [
"function",
"parameter",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'function'",
")",
"{",
"return",
"this",
".",
"outputQuery",
"(",
"this",
".",
"compileCallback",
"(",
"value",
")",
",",
"true",
")",
";",
"}",
"return",
"this",
".",
"unwrapRaw",
"(",
"value",
",",
"true",
")",
"||",
"'?'",
";",
"}"
] | Checks whether a value is a function... if it is, we compile it otherwise we check whether it's a raw | [
"Checks",
"whether",
"a",
"value",
"is",
"a",
"function",
"...",
"if",
"it",
"is",
"we",
"compile",
"it",
"otherwise",
"we",
"check",
"whether",
"it",
"s",
"a",
"raw"
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/formatter.js#L59-L64 | train |
AppGeo/cartodb | lib/formatter.js | wrap | function wrap(value) {
var raw;
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
if (typeof value === 'number') {
return value;
}
return this._wrapString(value + '');
} | javascript | function wrap(value) {
var raw;
if (typeof value === 'function') {
return this.outputQuery(this.compileCallback(value), true);
}
raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
if (typeof value === 'number') {
return value;
}
return this._wrapString(value + '');
} | [
"function",
"wrap",
"(",
"value",
")",
"{",
"var",
"raw",
";",
"if",
"(",
"typeof",
"value",
"===",
"'function'",
")",
"{",
"return",
"this",
".",
"outputQuery",
"(",
"this",
".",
"compileCallback",
"(",
"value",
")",
",",
"true",
")",
";",
"}",
"raw",
"=",
"this",
".",
"unwrapRaw",
"(",
"value",
")",
";",
"if",
"(",
"raw",
")",
"{",
"return",
"raw",
";",
"}",
"if",
"(",
"typeof",
"value",
"===",
"'number'",
")",
"{",
"return",
"value",
";",
"}",
"return",
"this",
".",
"_wrapString",
"(",
"value",
"+",
"''",
")",
";",
"}"
] | Puts the appropriate wrapper around a value depending on the database engine, unless it's a knex.raw value, in which case it's left alone. | [
"Puts",
"the",
"appropriate",
"wrapper",
"around",
"a",
"value",
"depending",
"on",
"the",
"database",
"engine",
"unless",
"it",
"s",
"a",
"knex",
".",
"raw",
"value",
"in",
"which",
"case",
"it",
"s",
"left",
"alone",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/formatter.js#L96-L109 | train |
AppGeo/cartodb | lib/formatter.js | operator | function operator(value) {
var raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
if (operators[(value || '').toLowerCase()] !== true) {
throw new TypeError('The operator "' + value + '" is not permitted');
}
return value;
} | javascript | function operator(value) {
var raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
if (operators[(value || '').toLowerCase()] !== true) {
throw new TypeError('The operator "' + value + '" is not permitted');
}
return value;
} | [
"function",
"operator",
"(",
"value",
")",
"{",
"var",
"raw",
"=",
"this",
".",
"unwrapRaw",
"(",
"value",
")",
";",
"if",
"(",
"raw",
")",
"{",
"return",
"raw",
";",
"}",
"if",
"(",
"operators",
"[",
"(",
"value",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
"]",
"!==",
"true",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'The operator \"'",
"+",
"value",
"+",
"'\" is not permitted'",
")",
";",
"}",
"return",
"value",
";",
"}"
] | The operator method takes a value and returns something or other. | [
"The",
"operator",
"method",
"takes",
"a",
"value",
"and",
"returns",
"something",
"or",
"other",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/formatter.js#L116-L125 | train |
AppGeo/cartodb | lib/formatter.js | direction | function direction(value) {
var raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
return orderBys.indexOf((value || '').toLowerCase()) !== -1 ? value : 'asc';
} | javascript | function direction(value) {
var raw = this.unwrapRaw(value);
if (raw) {
return raw;
}
return orderBys.indexOf((value || '').toLowerCase()) !== -1 ? value : 'asc';
} | [
"function",
"direction",
"(",
"value",
")",
"{",
"var",
"raw",
"=",
"this",
".",
"unwrapRaw",
"(",
"value",
")",
";",
"if",
"(",
"raw",
")",
"{",
"return",
"raw",
";",
"}",
"return",
"orderBys",
".",
"indexOf",
"(",
"(",
"value",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
")",
"!==",
"-",
"1",
"?",
"value",
":",
"'asc'",
";",
"}"
] | Specify the direction of the ordering. | [
"Specify",
"the",
"direction",
"of",
"the",
"ordering",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/formatter.js#L128-L134 | train |
AppGeo/cartodb | lib/formatter.js | compileCallback | function compileCallback(callback, method) {
var client = this.client;
// Build the callback
var builder = client.queryBuilder();
callback.call(builder, builder);
// Compile the callback, using the current formatter (to track all bindings).
var compiler = client.queryCompiler(builder);
compiler.formatter = this;
// Return the compiled & parameterized sql.
return compiler.toSQL(method || 'select');
} | javascript | function compileCallback(callback, method) {
var client = this.client;
// Build the callback
var builder = client.queryBuilder();
callback.call(builder, builder);
// Compile the callback, using the current formatter (to track all bindings).
var compiler = client.queryCompiler(builder);
compiler.formatter = this;
// Return the compiled & parameterized sql.
return compiler.toSQL(method || 'select');
} | [
"function",
"compileCallback",
"(",
"callback",
",",
"method",
")",
"{",
"var",
"client",
"=",
"this",
".",
"client",
";",
"var",
"builder",
"=",
"client",
".",
"queryBuilder",
"(",
")",
";",
"callback",
".",
"call",
"(",
"builder",
",",
"builder",
")",
";",
"var",
"compiler",
"=",
"client",
".",
"queryCompiler",
"(",
"builder",
")",
";",
"compiler",
".",
"formatter",
"=",
"this",
";",
"return",
"compiler",
".",
"toSQL",
"(",
"method",
"||",
"'select'",
")",
";",
"}"
] | Compiles a callback using the query builder. | [
"Compiles",
"a",
"callback",
"using",
"the",
"query",
"builder",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/formatter.js#L137-L150 | train |
AppGeo/cartodb | lib/formatter.js | outputQuery | function outputQuery(compiled, isParameter) {
var sql = compiled.sql || '';
if (sql) {
if (compiled.method === 'select' && (isParameter || compiled.as)) {
sql = '(' + sql + ')';
if (compiled.as) {
return this.alias(sql, this.wrap(compiled.as));
}
}
}
return sql;
} | javascript | function outputQuery(compiled, isParameter) {
var sql = compiled.sql || '';
if (sql) {
if (compiled.method === 'select' && (isParameter || compiled.as)) {
sql = '(' + sql + ')';
if (compiled.as) {
return this.alias(sql, this.wrap(compiled.as));
}
}
}
return sql;
} | [
"function",
"outputQuery",
"(",
"compiled",
",",
"isParameter",
")",
"{",
"var",
"sql",
"=",
"compiled",
".",
"sql",
"||",
"''",
";",
"if",
"(",
"sql",
")",
"{",
"if",
"(",
"compiled",
".",
"method",
"===",
"'select'",
"&&",
"(",
"isParameter",
"||",
"compiled",
".",
"as",
")",
")",
"{",
"sql",
"=",
"'('",
"+",
"sql",
"+",
"')'",
";",
"if",
"(",
"compiled",
".",
"as",
")",
"{",
"return",
"this",
".",
"alias",
"(",
"sql",
",",
"this",
".",
"wrap",
"(",
"compiled",
".",
"as",
")",
")",
";",
"}",
"}",
"}",
"return",
"sql",
";",
"}"
] | Ensures the query is aliased if necessary. | [
"Ensures",
"the",
"query",
"is",
"aliased",
"if",
"necessary",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/formatter.js#L153-L164 | train |
AppGeo/cartodb | lib/formatter.js | _wrapString | function _wrapString(value) {
var segments,
asIndex = value.toLowerCase().indexOf(' as ');
if (asIndex !== -1) {
var first = value.slice(0, asIndex);
var second = value.slice(asIndex + 4);
return this.alias(this.wrap(first), this.wrap(second));
}
var i = -1,
wrapped = [];
segments = value.split('.');
while (++i < segments.length) {
value = segments[i];
if (i === 0 && segments.length > 1) {
wrapped.push(this.wrap((value || '').trim()));
} else {
wrapped.push(this.client.wrapIdentifier((value || '').trim()));
}
}
return wrapped.join('.');
} | javascript | function _wrapString(value) {
var segments,
asIndex = value.toLowerCase().indexOf(' as ');
if (asIndex !== -1) {
var first = value.slice(0, asIndex);
var second = value.slice(asIndex + 4);
return this.alias(this.wrap(first), this.wrap(second));
}
var i = -1,
wrapped = [];
segments = value.split('.');
while (++i < segments.length) {
value = segments[i];
if (i === 0 && segments.length > 1) {
wrapped.push(this.wrap((value || '').trim()));
} else {
wrapped.push(this.client.wrapIdentifier((value || '').trim()));
}
}
return wrapped.join('.');
} | [
"function",
"_wrapString",
"(",
"value",
")",
"{",
"var",
"segments",
",",
"asIndex",
"=",
"value",
".",
"toLowerCase",
"(",
")",
".",
"indexOf",
"(",
"' as '",
")",
";",
"if",
"(",
"asIndex",
"!==",
"-",
"1",
")",
"{",
"var",
"first",
"=",
"value",
".",
"slice",
"(",
"0",
",",
"asIndex",
")",
";",
"var",
"second",
"=",
"value",
".",
"slice",
"(",
"asIndex",
"+",
"4",
")",
";",
"return",
"this",
".",
"alias",
"(",
"this",
".",
"wrap",
"(",
"first",
")",
",",
"this",
".",
"wrap",
"(",
"second",
")",
")",
";",
"}",
"var",
"i",
"=",
"-",
"1",
",",
"wrapped",
"=",
"[",
"]",
";",
"segments",
"=",
"value",
".",
"split",
"(",
"'.'",
")",
";",
"while",
"(",
"++",
"i",
"<",
"segments",
".",
"length",
")",
"{",
"value",
"=",
"segments",
"[",
"i",
"]",
";",
"if",
"(",
"i",
"===",
"0",
"&&",
"segments",
".",
"length",
">",
"1",
")",
"{",
"wrapped",
".",
"push",
"(",
"this",
".",
"wrap",
"(",
"(",
"value",
"||",
"''",
")",
".",
"trim",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"wrapped",
".",
"push",
"(",
"this",
".",
"client",
".",
"wrapIdentifier",
"(",
"(",
"value",
"||",
"''",
")",
".",
"trim",
"(",
")",
")",
")",
";",
"}",
"}",
"return",
"wrapped",
".",
"join",
"(",
"'.'",
")",
";",
"}"
] | Coerce to string to prevent strange errors when it's not a string. | [
"Coerce",
"to",
"string",
"to",
"prevent",
"strange",
"errors",
"when",
"it",
"s",
"not",
"a",
"string",
"."
] | 4cc624975d359800961bf34cb74de97488d2efb5 | https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/formatter.js#L167-L187 | train |
rootsdev/gedcomx-js | src/records/Collection.js | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Collection)){
return new Collection(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Collection.isInstance(json)){
return json;
}
this.init(json);
} | javascript | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Collection)){
return new Collection(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Collection.isInstance(json)){
return json;
}
this.init(json);
} | [
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Collection",
")",
")",
"{",
"return",
"new",
"Collection",
"(",
"json",
")",
";",
"}",
"if",
"(",
"Collection",
".",
"isInstance",
"(",
"json",
")",
")",
"{",
"return",
"json",
";",
"}",
"this",
".",
"init",
"(",
"json",
")",
";",
"}"
] | A collection of genealogical data.
@see {@link https://github.com/FamilySearch/gedcomx-record/blob/master/specifications/record-specification.md#collection|GEDCOM X Records Spec}
@class Collection
@extends ExtensibleData
@param {Object} [json] | [
"A",
"collection",
"of",
"genealogical",
"data",
"."
] | 08b2fcde96f1e301c78561bfb7a8b0cac606e26e | https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/records/Collection.js#L14-L27 | train |
|
imbo/imboclient-js | lib/browser/request.js | function(xhr) {
var response = {
headers: {},
statusCode: xhr.status
};
var headerPairs = xhr.getAllResponseHeaders().split('\u000d\u000a');
for (var i = 0; i < headerPairs.length; i++) {
var headerPair = headerPairs[i],
index = headerPair.indexOf('\u003a\u0020');
if (index > 0) {
var key = headerPair.substring(0, index);
var val = headerPair.substring(index + 2);
response.headers[key.toLowerCase()] = val;
}
}
return response;
} | javascript | function(xhr) {
var response = {
headers: {},
statusCode: xhr.status
};
var headerPairs = xhr.getAllResponseHeaders().split('\u000d\u000a');
for (var i = 0; i < headerPairs.length; i++) {
var headerPair = headerPairs[i],
index = headerPair.indexOf('\u003a\u0020');
if (index > 0) {
var key = headerPair.substring(0, index);
var val = headerPair.substring(index + 2);
response.headers[key.toLowerCase()] = val;
}
}
return response;
} | [
"function",
"(",
"xhr",
")",
"{",
"var",
"response",
"=",
"{",
"headers",
":",
"{",
"}",
",",
"statusCode",
":",
"xhr",
".",
"status",
"}",
";",
"var",
"headerPairs",
"=",
"xhr",
".",
"getAllResponseHeaders",
"(",
")",
".",
"split",
"(",
"'\\u000d\\u000a'",
")",
";",
"\\u000d",
"\\u000a",
"}"
] | Normalize a response into a common format for both environments
@param {XMLHttpRequest} xhr
@return {Object} | [
"Normalize",
"a",
"response",
"into",
"a",
"common",
"format",
"for",
"both",
"environments"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/browser/request.js#L25-L44 | train |
|
rootsdev/gedcomx-js | src/core/Fact.js | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Fact)){
return new Fact(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Fact.isInstance(json)){
return json;
}
this.init(json);
} | javascript | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Fact)){
return new Fact(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Fact.isInstance(json)){
return json;
}
this.init(json);
} | [
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Fact",
")",
")",
"{",
"return",
"new",
"Fact",
"(",
"json",
")",
";",
"}",
"if",
"(",
"Fact",
".",
"isInstance",
"(",
"json",
")",
")",
"{",
"return",
"json",
";",
"}",
"this",
".",
"init",
"(",
"json",
")",
";",
"}"
] | A fact for a person or relationship.
@see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#fact-conclusion|GEDCOM X JSON Spec}
@class
@extends Conclusion
@param {Object} [json] | [
"A",
"fact",
"for",
"a",
"person",
"or",
"relationship",
"."
] | 08b2fcde96f1e301c78561bfb7a8b0cac606e26e | https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Fact.js#L13-L26 | train |
|
unshiftio/handshake | index.js | Handshake | function Handshake(context, options) {
if (!this) return new Handshake(context, options);
options = options || {};
this.stringify = options.stringify || qs.stringify;
this.configure = Object.create(null);
this.timers = new Tick(context);
this.id = options.id || v4;
this.context = context;
this.payload = {};
this.timeout = 'handshake timeout' in options
? options['handshake timeout']
: '5 seconds';
this.update();
} | javascript | function Handshake(context, options) {
if (!this) return new Handshake(context, options);
options = options || {};
this.stringify = options.stringify || qs.stringify;
this.configure = Object.create(null);
this.timers = new Tick(context);
this.id = options.id || v4;
this.context = context;
this.payload = {};
this.timeout = 'handshake timeout' in options
? options['handshake timeout']
: '5 seconds';
this.update();
} | [
"function",
"Handshake",
"(",
"context",
",",
"options",
")",
"{",
"if",
"(",
"!",
"this",
")",
"return",
"new",
"Handshake",
"(",
"context",
",",
"options",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"stringify",
"=",
"options",
".",
"stringify",
"||",
"qs",
".",
"stringify",
";",
"this",
".",
"configure",
"=",
"Object",
".",
"create",
"(",
"null",
")",
";",
"this",
".",
"timers",
"=",
"new",
"Tick",
"(",
"context",
")",
";",
"this",
".",
"id",
"=",
"options",
".",
"id",
"||",
"v4",
";",
"this",
".",
"context",
"=",
"context",
";",
"this",
".",
"payload",
"=",
"{",
"}",
";",
"this",
".",
"timeout",
"=",
"'handshake timeout'",
"in",
"options",
"?",
"options",
"[",
"'handshake timeout'",
"]",
":",
"'5 seconds'",
";",
"this",
".",
"update",
"(",
")",
";",
"}"
] | Handle handshakes.
Options:
- `handshake timeout`: Maximum time you're allowed to spend modifying the
handshake.
- `stringify`: Encoder for the complete handshake response.
- `id`: Unique id generator.
@constructor
@param {Mixed} context Context of the callbacks.
@param {Object} options Optional configuration.
@api public | [
"Handle",
"handshakes",
"."
] | 01530f9435ab43b00657934a6a2530caeef712ef | https://github.com/unshiftio/handshake/blob/01530f9435ab43b00657934a6a2530caeef712ef/index.js#L25-L42 | train |
jaredhanson/junction-disco | lib/junction-disco/route.js | Route | function Route(query, node, callbacks, options) {
options = options || {};
this.query = query;
this.node = node;
this.callbacks = callbacks;
this.regexp = normalize(node
, this.keys = []
, options.sensitive
, options.strict);
} | javascript | function Route(query, node, callbacks, options) {
options = options || {};
this.query = query;
this.node = node;
this.callbacks = callbacks;
this.regexp = normalize(node
, this.keys = []
, options.sensitive
, options.strict);
} | [
"function",
"Route",
"(",
"query",
",",
"node",
",",
"callbacks",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"query",
"=",
"query",
";",
"this",
".",
"node",
"=",
"node",
";",
"this",
".",
"callbacks",
"=",
"callbacks",
";",
"this",
".",
"regexp",
"=",
"normalize",
"(",
"node",
",",
"this",
".",
"keys",
"=",
"[",
"]",
",",
"options",
".",
"sensitive",
",",
"options",
".",
"strict",
")",
";",
"}"
] | Initialize a new `Route` with the given `query`, `node`, an array of
`callbacks` and `options`.
Options:
- `sensitive` enable case-sensitive routes
- `strict` enable strict matching for trailing slashes
@param {String} query
@param {String} node
@param {Array} callbacks
@param {Object} options
@api private | [
"Initialize",
"a",
"new",
"Route",
"with",
"the",
"given",
"query",
"node",
"an",
"array",
"of",
"callbacks",
"and",
"options",
"."
] | 89f2d222518b3b0f282d54b25d6405b5e35c1383 | https://github.com/jaredhanson/junction-disco/blob/89f2d222518b3b0f282d54b25d6405b5e35c1383/lib/junction-disco/route.js#L16-L25 | train |
rootsdev/gedcomx-js | src/core/Root.js | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Root)){
return new Root(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Root.isInstance(json)){
return json;
}
this.init(json);
} | javascript | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof Root)){
return new Root(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(Root.isInstance(json)){
return json;
}
this.init(json);
} | [
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Root",
")",
")",
"{",
"return",
"new",
"Root",
"(",
"json",
")",
";",
"}",
"if",
"(",
"Root",
".",
"isInstance",
"(",
"json",
")",
")",
"{",
"return",
"json",
";",
"}",
"this",
".",
"init",
"(",
"json",
")",
";",
"}"
] | A GEDCOM X document.
@see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#gedcomx-type|GEDCOM X JSON Spec}
@class
@extends ExtensibleData
@param {Object} [json] | [
"A",
"GEDCOM",
"X",
"document",
"."
] | 08b2fcde96f1e301c78561bfb7a8b0cac606e26e | https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Root.js#L13-L26 | train |
|
BEMQuery/bemquery-core | src/factory.js | factory | function factory( query, context = document ) {
const converter = bsc();
const selectorEngine = new SelectorEngine();
const bemQuery = new BEMQuery( query, context, converter, selectorEngine );
return bemQuery;
} | javascript | function factory( query, context = document ) {
const converter = bsc();
const selectorEngine = new SelectorEngine();
const bemQuery = new BEMQuery( query, context, converter, selectorEngine );
return bemQuery;
} | [
"function",
"factory",
"(",
"query",
",",
"context",
"=",
"document",
")",
"{",
"const",
"converter",
"=",
"bsc",
"(",
")",
";",
"const",
"selectorEngine",
"=",
"new",
"SelectorEngine",
"(",
")",
";",
"const",
"bemQuery",
"=",
"new",
"BEMQuery",
"(",
"query",
",",
"context",
",",
"converter",
",",
"selectorEngine",
")",
";",
"return",
"bemQuery",
";",
"}"
] | BEMQuery instance factory.
@param {String|Iterable|HTMLElement} query Selector or
existing elements collection upon which the new elements collection
should be created.
@param {Document|HTMLElement|BEMQuery} context Context from which
elements should be fetched.
@return {BEMQuery} New BEMQuery instance. | [
"BEMQuery",
"instance",
"factory",
"."
] | 7c0627d5e038147ee304056bc724490be742f96c | https://github.com/BEMQuery/bemquery-core/blob/7c0627d5e038147ee304056bc724490be742f96c/src/factory.js#L17-L23 | train |
deztopia/treenode | dist/treenode.js | addChild | function addChild(data) {
var child = new TreeNode(data, this);
if (!this.children) {
this.children = [];
}
this.children.push(child);
return child;
} | javascript | function addChild(data) {
var child = new TreeNode(data, this);
if (!this.children) {
this.children = [];
}
this.children.push(child);
return child;
} | [
"function",
"addChild",
"(",
"data",
")",
"{",
"var",
"child",
"=",
"new",
"TreeNode",
"(",
"data",
",",
"this",
")",
";",
"if",
"(",
"!",
"this",
".",
"children",
")",
"{",
"this",
".",
"children",
"=",
"[",
"]",
";",
"}",
"this",
".",
"children",
".",
"push",
"(",
"child",
")",
";",
"return",
"child",
";",
"}"
] | Add child. Returns the newly created child.
@param data
@returns {TreeNode} | [
"Add",
"child",
".",
"Returns",
"the",
"newly",
"created",
"child",
"."
] | 257f05fa97239b283e0ce31fa00cd1f634116ebf | https://github.com/deztopia/treenode/blob/257f05fa97239b283e0ce31fa00cd1f634116ebf/dist/treenode.js#L54-L61 | train |
deztopia/treenode | dist/treenode.js | find | function find(data) {
if (data === this.data) {
return this;
}
if (this.children) {
for (var i = 0, _length = this.children.length, target = null; i < _length; i++) {
target = this.children[i].find(data);
if (target) {
return target;
}
}
}
return null;
} | javascript | function find(data) {
if (data === this.data) {
return this;
}
if (this.children) {
for (var i = 0, _length = this.children.length, target = null; i < _length; i++) {
target = this.children[i].find(data);
if (target) {
return target;
}
}
}
return null;
} | [
"function",
"find",
"(",
"data",
")",
"{",
"if",
"(",
"data",
"===",
"this",
".",
"data",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"this",
".",
"children",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"_length",
"=",
"this",
".",
"children",
".",
"length",
",",
"target",
"=",
"null",
";",
"i",
"<",
"_length",
";",
"i",
"++",
")",
"{",
"target",
"=",
"this",
".",
"children",
"[",
"i",
"]",
".",
"find",
"(",
"data",
")",
";",
"if",
"(",
"target",
")",
"{",
"return",
"target",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] | Given a data object, returns the tree node containing it, if any. If not found, returns null.
@param data
@returns {TreeNode} || null | [
"Given",
"a",
"data",
"object",
"returns",
"the",
"tree",
"node",
"containing",
"it",
"if",
"any",
".",
"If",
"not",
"found",
"returns",
"null",
"."
] | 257f05fa97239b283e0ce31fa00cd1f634116ebf | https://github.com/deztopia/treenode/blob/257f05fa97239b283e0ce31fa00cd1f634116ebf/dist/treenode.js#L70-L85 | train |
deztopia/treenode | dist/treenode.js | leaves | function leaves() {
if (!this.children || this.children.length === 0) {
// this is a leaf
return [this];
}
// if not a leaf, return all children's leaves recursively
var leaves = [];
if (this.children) {
for (var i = 0, _length2 = this.children.length; i < _length2; i++) {
leaves.push.apply(leaves, this.children[i].leaves());
}
}
return leaves;
} | javascript | function leaves() {
if (!this.children || this.children.length === 0) {
// this is a leaf
return [this];
}
// if not a leaf, return all children's leaves recursively
var leaves = [];
if (this.children) {
for (var i = 0, _length2 = this.children.length; i < _length2; i++) {
leaves.push.apply(leaves, this.children[i].leaves());
}
}
return leaves;
} | [
"function",
"leaves",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"children",
"||",
"this",
".",
"children",
".",
"length",
"===",
"0",
")",
"{",
"return",
"[",
"this",
"]",
";",
"}",
"var",
"leaves",
"=",
"[",
"]",
";",
"if",
"(",
"this",
".",
"children",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"_length2",
"=",
"this",
".",
"children",
".",
"length",
";",
"i",
"<",
"_length2",
";",
"i",
"++",
")",
"{",
"leaves",
".",
"push",
".",
"apply",
"(",
"leaves",
",",
"this",
".",
"children",
"[",
"i",
"]",
".",
"leaves",
"(",
")",
")",
";",
"}",
"}",
"return",
"leaves",
";",
"}"
] | Returns an array of all leaf nodes below this one.
@returns {Array} | [
"Returns",
"an",
"array",
"of",
"all",
"leaf",
"nodes",
"below",
"this",
"one",
"."
] | 257f05fa97239b283e0ce31fa00cd1f634116ebf | https://github.com/deztopia/treenode/blob/257f05fa97239b283e0ce31fa00cd1f634116ebf/dist/treenode.js#L93-L107 | train |
deztopia/treenode | dist/treenode.js | forEach | function forEach(callback) {
if (typeof callback !== 'function') {
throw new TypeError('forEach() callback must be a function');
}
// run this node through function
callback(this);
// do the same for all children
if (this.children) {
for (var i = 0, _length3 = this.children.length; i < _length3; i++) {
this.children[i].forEach(callback);
}
}
return this;
} | javascript | function forEach(callback) {
if (typeof callback !== 'function') {
throw new TypeError('forEach() callback must be a function');
}
// run this node through function
callback(this);
// do the same for all children
if (this.children) {
for (var i = 0, _length3 = this.children.length; i < _length3; i++) {
this.children[i].forEach(callback);
}
}
return this;
} | [
"function",
"forEach",
"(",
"callback",
")",
"{",
"if",
"(",
"typeof",
"callback",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'forEach() callback must be a function'",
")",
";",
"}",
"callback",
"(",
"this",
")",
";",
"if",
"(",
"this",
".",
"children",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"_length3",
"=",
"this",
".",
"children",
".",
"length",
";",
"i",
"<",
"_length3",
";",
"i",
"++",
")",
"{",
"this",
".",
"children",
"[",
"i",
"]",
".",
"forEach",
"(",
"callback",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] | Pass this node as a parameter to the given callback function. Iteratively pass each child as well.
Returns the current node afterwards.
@param callback A function which will take each node as a parameter.
@returns {TreeNode} | [
"Pass",
"this",
"node",
"as",
"a",
"parameter",
"to",
"the",
"given",
"callback",
"function",
".",
"Iteratively",
"pass",
"each",
"child",
"as",
"well",
".",
"Returns",
"the",
"current",
"node",
"afterwards",
"."
] | 257f05fa97239b283e0ce31fa00cd1f634116ebf | https://github.com/deztopia/treenode/blob/257f05fa97239b283e0ce31fa00cd1f634116ebf/dist/treenode.js#L131-L147 | train |
WRidder/backgrid-advanced-filter | src/filter-editor.js | function() {
var self = this;
if (self.filter.get("valid")) {
self.$el.removeClass("invalidvalid");
self.$el.addClass("valid");
}
else {
self.$el.removeClass("valid");
self.$el.addClass("invalid");
}
} | javascript | function() {
var self = this;
if (self.filter.get("valid")) {
self.$el.removeClass("invalidvalid");
self.$el.addClass("valid");
}
else {
self.$el.removeClass("valid");
self.$el.addClass("invalid");
}
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"self",
".",
"filter",
".",
"get",
"(",
"\"valid\"",
")",
")",
"{",
"self",
".",
"$el",
".",
"removeClass",
"(",
"\"invalidvalid\"",
")",
";",
"self",
".",
"$el",
".",
"addClass",
"(",
"\"valid\"",
")",
";",
"}",
"else",
"{",
"self",
".",
"$el",
".",
"removeClass",
"(",
"\"valid\"",
")",
";",
"self",
".",
"$el",
".",
"addClass",
"(",
"\"invalid\"",
")",
";",
"}",
"}"
] | Adds an 'active' class to the view element if the attribute filter is valid.
@method setValidClass | [
"Adds",
"an",
"active",
"class",
"to",
"the",
"view",
"element",
"if",
"the",
"attribute",
"filter",
"is",
"valid",
"."
] | 5b10216f091d0e4bad418398fb4ec4c4588f4475 | https://github.com/WRidder/backgrid-advanced-filter/blob/5b10216f091d0e4bad418398fb4ec4c4588f4475/src/filter-editor.js#L805-L816 | train |
|
rootsdev/gedcomx-js | src/atom/AtomFeed.js | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomFeed)){
return new AtomFeed(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomFeed.isInstance(json)){
return json;
}
this.init(json);
} | javascript | function(json){
// Protect against forgetting the new keyword when calling the constructor
if(!(this instanceof AtomFeed)){
return new AtomFeed(json);
}
// If the given object is already an instance then just return it. DON'T copy it.
if(AtomFeed.isInstance(json)){
return json;
}
this.init(json);
} | [
"function",
"(",
"json",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"AtomFeed",
")",
")",
"{",
"return",
"new",
"AtomFeed",
"(",
"json",
")",
";",
"}",
"if",
"(",
"AtomFeed",
".",
"isInstance",
"(",
"json",
")",
")",
"{",
"return",
"json",
";",
"}",
"this",
".",
"init",
"(",
"json",
")",
";",
"}"
] | The Atom data formats provide a format for web content and metadata syndication.
The JSON data format is specific to GEDCOM X and is a translation to JSON from the XML.
@see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/atom-model-specification.md#atom-json-media-type|GEDCOM X Atom JSON Spec}
@see {@link https://tools.ietf.org/html/rfc4287#section-4.1.1|RFC 4287}
@class AtomFeed
@extends AtomCommon
@param {Object} [json] | [
"The",
"Atom",
"data",
"formats",
"provide",
"a",
"format",
"for",
"web",
"content",
"and",
"metadata",
"syndication",
".",
"The",
"JSON",
"data",
"format",
"is",
"specific",
"to",
"GEDCOM",
"X",
"and",
"is",
"a",
"translation",
"to",
"JSON",
"from",
"the",
"XML",
"."
] | 08b2fcde96f1e301c78561bfb7a8b0cac606e26e | https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/atom/AtomFeed.js#L16-L29 | train |
|
szanata/padleft | padleft.js | pad | function pad(side, num, ch) {
var
exp = `${side === 'left' ? '' : '^'}.{${num}}${side === 'right' ? '' : '$'}`,
re = new RegExp(exp), pad = '';
do {
pad += ch;
} while(pad.length < num);
return re.exec( (side === 'left') ? (pad + this) : (this + pad) )[0];
} | javascript | function pad(side, num, ch) {
var
exp = `${side === 'left' ? '' : '^'}.{${num}}${side === 'right' ? '' : '$'}`,
re = new RegExp(exp), pad = '';
do {
pad += ch;
} while(pad.length < num);
return re.exec( (side === 'left') ? (pad + this) : (this + pad) )[0];
} | [
"function",
"pad",
"(",
"side",
",",
"num",
",",
"ch",
")",
"{",
"var",
"exp",
"=",
"`",
"${",
"side",
"===",
"'left'",
"?",
"''",
":",
"'^'",
"}",
"${",
"num",
"}",
"${",
"side",
"===",
"'right'",
"?",
"''",
":",
"'$'",
"}",
"`",
",",
"re",
"=",
"new",
"RegExp",
"(",
"exp",
")",
",",
"pad",
"=",
"''",
";",
"do",
"{",
"pad",
"+=",
"ch",
";",
"}",
"while",
"(",
"pad",
".",
"length",
"<",
"num",
")",
";",
"return",
"re",
".",
"exec",
"(",
"(",
"side",
"===",
"'left'",
")",
"?",
"(",
"pad",
"+",
"this",
")",
":",
"(",
"this",
"+",
"pad",
")",
")",
"[",
"0",
"]",
";",
"}"
] | pads some side | [
"pads",
"some",
"side"
] | 6c5cec4eef0ac203c8143c36e72779e0b05678a2 | https://github.com/szanata/padleft/blob/6c5cec4eef0ac203c8143c36e72779e0b05678a2/padleft.js#L4-L13 | train |
imbo/imboclient-js | lib/client.js | ImboClient | function ImboClient(options, publicKey, privateKey) {
// Run a feature check, ensuring all required features are present
features.checkFeatures();
// Initialize options
var opts = this.options = {
hosts: parseUrls(options.hosts || options),
publicKey: options.publicKey || publicKey,
privateKey: options.privateKey || privateKey,
user: options.user || options.publicKey || publicKey
};
// Validate options
['publicKey', 'privateKey', 'user'].forEach(function validateOption(opt) {
if (!opts[opt] || typeof opts[opt] !== 'string') {
throw new Error('`options.' + opt + '` must be a valid string');
}
});
} | javascript | function ImboClient(options, publicKey, privateKey) {
// Run a feature check, ensuring all required features are present
features.checkFeatures();
// Initialize options
var opts = this.options = {
hosts: parseUrls(options.hosts || options),
publicKey: options.publicKey || publicKey,
privateKey: options.privateKey || privateKey,
user: options.user || options.publicKey || publicKey
};
// Validate options
['publicKey', 'privateKey', 'user'].forEach(function validateOption(opt) {
if (!opts[opt] || typeof opts[opt] !== 'string') {
throw new Error('`options.' + opt + '` must be a valid string');
}
});
} | [
"function",
"ImboClient",
"(",
"options",
",",
"publicKey",
",",
"privateKey",
")",
"{",
"features",
".",
"checkFeatures",
"(",
")",
";",
"var",
"opts",
"=",
"this",
".",
"options",
"=",
"{",
"hosts",
":",
"parseUrls",
"(",
"options",
".",
"hosts",
"||",
"options",
")",
",",
"publicKey",
":",
"options",
".",
"publicKey",
"||",
"publicKey",
",",
"privateKey",
":",
"options",
".",
"privateKey",
"||",
"privateKey",
",",
"user",
":",
"options",
".",
"user",
"||",
"options",
".",
"publicKey",
"||",
"publicKey",
"}",
";",
"[",
"'publicKey'",
",",
"'privateKey'",
",",
"'user'",
"]",
".",
"forEach",
"(",
"function",
"validateOption",
"(",
"opt",
")",
"{",
"if",
"(",
"!",
"opts",
"[",
"opt",
"]",
"||",
"typeof",
"opts",
"[",
"opt",
"]",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'`options.'",
"+",
"opt",
"+",
"'` must be a valid string'",
")",
";",
"}",
"}",
")",
";",
"}"
] | Constructs a new Imbo client
@param {Object} options
@param {String} publicKey
@param {String} privateKey
@throws Will throw an error if there are unsupported features | [
"Constructs",
"a",
"new",
"Imbo",
"client"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L34-L52 | train |
imbo/imboclient-js | lib/client.js | function(file, callback) {
if (isBrowser && file instanceof window.File) {
// Browser File instance
return this.addImageFromBuffer(file, callback);
}
// File on filesystem. Note: the reason why we need the size of the file
// is because of reverse proxies like Varnish which doesn't handle chunked
// Transfer-Encoding properly - instead we need to explicitly pass the
// content length so it knows not to terminate the HTTP connection
readers.getLengthOfFile(file, function(err, fileSize) {
if (err) {
return callback(err);
}
readers.createReadStream(file).pipe(request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
json: true,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js',
'Content-Length': fileSize
},
onComplete: function(addErr, res, body) {
callback(addErr, body ? body.imageIdentifier : null, body, res);
}
}));
}.bind(this));
return this;
} | javascript | function(file, callback) {
if (isBrowser && file instanceof window.File) {
// Browser File instance
return this.addImageFromBuffer(file, callback);
}
// File on filesystem. Note: the reason why we need the size of the file
// is because of reverse proxies like Varnish which doesn't handle chunked
// Transfer-Encoding properly - instead we need to explicitly pass the
// content length so it knows not to terminate the HTTP connection
readers.getLengthOfFile(file, function(err, fileSize) {
if (err) {
return callback(err);
}
readers.createReadStream(file).pipe(request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
json: true,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js',
'Content-Length': fileSize
},
onComplete: function(addErr, res, body) {
callback(addErr, body ? body.imageIdentifier : null, body, res);
}
}));
}.bind(this));
return this;
} | [
"function",
"(",
"file",
",",
"callback",
")",
"{",
"if",
"(",
"isBrowser",
"&&",
"file",
"instanceof",
"window",
".",
"File",
")",
"{",
"return",
"this",
".",
"addImageFromBuffer",
"(",
"file",
",",
"callback",
")",
";",
"}",
"readers",
".",
"getLengthOfFile",
"(",
"file",
",",
"function",
"(",
"err",
",",
"fileSize",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"readers",
".",
"createReadStream",
"(",
"file",
")",
".",
"pipe",
"(",
"request",
"(",
"{",
"method",
":",
"'POST'",
",",
"uri",
":",
"this",
".",
"getSignedResourceUrl",
"(",
"'POST'",
",",
"this",
".",
"getImagesUrl",
"(",
")",
")",
",",
"json",
":",
"true",
",",
"headers",
":",
"{",
"'Accept'",
":",
"'application/json'",
",",
"'User-Agent'",
":",
"'imboclient-js'",
",",
"'Content-Length'",
":",
"fileSize",
"}",
",",
"onComplete",
":",
"function",
"(",
"addErr",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"addErr",
",",
"body",
"?",
"body",
".",
"imageIdentifier",
":",
"null",
",",
"body",
",",
"res",
")",
";",
"}",
"}",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add a new image to the server from a local file
@param {String|File} file - Path to the local image, or an instance of File
@param {Function} callback - Function to call when image has been uploaded
@return {ImboClient} | [
"Add",
"a",
"new",
"image",
"to",
"the",
"server",
"from",
"a",
"local",
"file"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L73-L104 | train |
|
imbo/imboclient-js | lib/client.js | function(source, callback) {
var url = this.getSignedResourceUrl('POST', this.getImagesUrl()),
isFile = isBrowser && source instanceof window.File,
onComplete = callback.onComplete || callback,
onProgress = callback.onProgress || null;
request({
method: 'POST',
uri: url,
body: source,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js',
'Content-Length': isFile ? source.size : source.length
},
onComplete: function(err, res, body) {
body = jsonparse(body);
onComplete(err, body ? body.imageIdentifier : null, body, res);
},
onProgress: onProgress
});
return this;
} | javascript | function(source, callback) {
var url = this.getSignedResourceUrl('POST', this.getImagesUrl()),
isFile = isBrowser && source instanceof window.File,
onComplete = callback.onComplete || callback,
onProgress = callback.onProgress || null;
request({
method: 'POST',
uri: url,
body: source,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js',
'Content-Length': isFile ? source.size : source.length
},
onComplete: function(err, res, body) {
body = jsonparse(body);
onComplete(err, body ? body.imageIdentifier : null, body, res);
},
onProgress: onProgress
});
return this;
} | [
"function",
"(",
"source",
",",
"callback",
")",
"{",
"var",
"url",
"=",
"this",
".",
"getSignedResourceUrl",
"(",
"'POST'",
",",
"this",
".",
"getImagesUrl",
"(",
")",
")",
",",
"isFile",
"=",
"isBrowser",
"&&",
"source",
"instanceof",
"window",
".",
"File",
",",
"onComplete",
"=",
"callback",
".",
"onComplete",
"||",
"callback",
",",
"onProgress",
"=",
"callback",
".",
"onProgress",
"||",
"null",
";",
"request",
"(",
"{",
"method",
":",
"'POST'",
",",
"uri",
":",
"url",
",",
"body",
":",
"source",
",",
"headers",
":",
"{",
"'Accept'",
":",
"'application/json'",
",",
"'User-Agent'",
":",
"'imboclient-js'",
",",
"'Content-Length'",
":",
"isFile",
"?",
"source",
".",
"size",
":",
"source",
".",
"length",
"}",
",",
"onComplete",
":",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"body",
"=",
"jsonparse",
"(",
"body",
")",
";",
"onComplete",
"(",
"err",
",",
"body",
"?",
"body",
".",
"imageIdentifier",
":",
"null",
",",
"body",
",",
"res",
")",
";",
"}",
",",
"onProgress",
":",
"onProgress",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Add an image from a Buffer, String or File instance
@param {Buffer|ArrayBuffer|String|File} source
@param {Function} callback
@return {ImboClient} | [
"Add",
"an",
"image",
"from",
"a",
"Buffer",
"String",
"or",
"File",
"instance"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L113-L136 | train |
|
imbo/imboclient-js | lib/client.js | function(url, callback) {
if (isBrowser) {
// Browser environments can't pipe, so download the file and add it
return this.getImageDataFromUrl(url, function(err, data) {
if (err) {
return callback(err);
}
this.addImageFromBuffer(data, callback);
}.bind(this));
}
// Pipe the source URL into a POST-request
request({ uri: url }).pipe(request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
json: true,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js'
},
onComplete: function(err, res, body) {
callback(err, body ? body.imageIdentifier : null, body, res);
}
}));
return this;
} | javascript | function(url, callback) {
if (isBrowser) {
// Browser environments can't pipe, so download the file and add it
return this.getImageDataFromUrl(url, function(err, data) {
if (err) {
return callback(err);
}
this.addImageFromBuffer(data, callback);
}.bind(this));
}
// Pipe the source URL into a POST-request
request({ uri: url }).pipe(request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', this.getImagesUrl()),
json: true,
headers: {
'Accept': 'application/json',
'User-Agent': 'imboclient-js'
},
onComplete: function(err, res, body) {
callback(err, body ? body.imageIdentifier : null, body, res);
}
}));
return this;
} | [
"function",
"(",
"url",
",",
"callback",
")",
"{",
"if",
"(",
"isBrowser",
")",
"{",
"return",
"this",
".",
"getImageDataFromUrl",
"(",
"url",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"this",
".",
"addImageFromBuffer",
"(",
"data",
",",
"callback",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"request",
"(",
"{",
"uri",
":",
"url",
"}",
")",
".",
"pipe",
"(",
"request",
"(",
"{",
"method",
":",
"'POST'",
",",
"uri",
":",
"this",
".",
"getSignedResourceUrl",
"(",
"'POST'",
",",
"this",
".",
"getImagesUrl",
"(",
")",
")",
",",
"json",
":",
"true",
",",
"headers",
":",
"{",
"'Accept'",
":",
"'application/json'",
",",
"'User-Agent'",
":",
"'imboclient-js'",
"}",
",",
"onComplete",
":",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
"?",
"body",
".",
"imageIdentifier",
":",
"null",
",",
"body",
",",
"res",
")",
";",
"}",
"}",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add an image from a remote URL
@param {String} url
@param {Function} callback
@return {ImboClient} | [
"Add",
"an",
"image",
"from",
"a",
"remote",
"URL"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L145-L172 | train |
|
imbo/imboclient-js | lib/client.js | function(callback) {
request.get(this.getStatsUrl(), function(err, res, body) {
callback(err, body, res);
});
return this;
} | javascript | function(callback) {
request.get(this.getStatsUrl(), function(err, res, body) {
callback(err, body, res);
});
return this;
} | [
"function",
"(",
"callback",
")",
"{",
"request",
".",
"get",
"(",
"this",
".",
"getStatsUrl",
"(",
")",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Get the server statistics
@param {Function} callback
@return {ImboClient} | [
"Get",
"the",
"server",
"statistics"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L180-L186 | train |
|
imbo/imboclient-js | lib/client.js | function(callback) {
request.get(this.getStatusUrl(), function(err, res, body) {
if (err) {
return callback(err);
}
body = body || {};
body.status = res.statusCode;
body.date = new Date(body.date);
callback(err, body, res);
});
return this;
} | javascript | function(callback) {
request.get(this.getStatusUrl(), function(err, res, body) {
if (err) {
return callback(err);
}
body = body || {};
body.status = res.statusCode;
body.date = new Date(body.date);
callback(err, body, res);
});
return this;
} | [
"function",
"(",
"callback",
")",
"{",
"request",
".",
"get",
"(",
"this",
".",
"getStatusUrl",
"(",
")",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"body",
"=",
"body",
"||",
"{",
"}",
";",
"body",
".",
"status",
"=",
"res",
".",
"statusCode",
";",
"body",
".",
"date",
"=",
"new",
"Date",
"(",
"body",
".",
"date",
")",
";",
"callback",
"(",
"err",
",",
"body",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Get the server status
@param {Function} callback
@return {ImboClient} | [
"Get",
"the",
"server",
"status"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L194-L208 | train |
|
imbo/imboclient-js | lib/client.js | function(callback) {
request.get(this.getUserUrl(), function(err, res, body) {
if (body && body.lastModified) {
body.lastModified = new Date(body.lastModified);
}
if (body && !body.user && body.publicKey) {
body.user = body.publicKey;
}
callback(err, body, res);
});
return this;
} | javascript | function(callback) {
request.get(this.getUserUrl(), function(err, res, body) {
if (body && body.lastModified) {
body.lastModified = new Date(body.lastModified);
}
if (body && !body.user && body.publicKey) {
body.user = body.publicKey;
}
callback(err, body, res);
});
return this;
} | [
"function",
"(",
"callback",
")",
"{",
"request",
".",
"get",
"(",
"this",
".",
"getUserUrl",
"(",
")",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"if",
"(",
"body",
"&&",
"body",
".",
"lastModified",
")",
"{",
"body",
".",
"lastModified",
"=",
"new",
"Date",
"(",
"body",
".",
"lastModified",
")",
";",
"}",
"if",
"(",
"body",
"&&",
"!",
"body",
".",
"user",
"&&",
"body",
".",
"publicKey",
")",
"{",
"body",
".",
"user",
"=",
"body",
".",
"publicKey",
";",
"}",
"callback",
"(",
"err",
",",
"body",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Fetch the user info of the current user
@param {Function} callback
@return {ImboClient} | [
"Fetch",
"the",
"user",
"info",
"of",
"the",
"current",
"user"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L216-L230 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, callback) {
var url = this.getImageUrl(imageIdentifier, { usePrimaryHost: true }),
signedUrl = this.getSignedResourceUrl('DELETE', url);
request.del(signedUrl, callback);
return this;
} | javascript | function(imageIdentifier, callback) {
var url = this.getImageUrl(imageIdentifier, { usePrimaryHost: true }),
signedUrl = this.getSignedResourceUrl('DELETE', url);
request.del(signedUrl, callback);
return this;
} | [
"function",
"(",
"imageIdentifier",
",",
"callback",
")",
"{",
"var",
"url",
"=",
"this",
".",
"getImageUrl",
"(",
"imageIdentifier",
",",
"{",
"usePrimaryHost",
":",
"true",
"}",
")",
",",
"signedUrl",
"=",
"this",
".",
"getSignedResourceUrl",
"(",
"'DELETE'",
",",
"url",
")",
";",
"request",
".",
"del",
"(",
"signedUrl",
",",
"callback",
")",
";",
"return",
"this",
";",
"}"
] | Delete an image
@param {String} imageIdentifier
@param {Function} callback
@return {ImboClient} | [
"Delete",
"an",
"image"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L239-L245 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, callback) {
this.headImage(imageIdentifier, function(err, res) {
if (err) {
return callback(err);
}
var headers = res.headers,
prefix = 'x-imbo-original';
callback(err, {
width: parseInt(headers[prefix + 'width'], 10),
height: parseInt(headers[prefix + 'height'], 10),
filesize: parseInt(headers[prefix + 'filesize'], 10),
extension: headers[prefix + 'extension'],
mimetype: headers[prefix + 'mimetype']
});
});
return this;
} | javascript | function(imageIdentifier, callback) {
this.headImage(imageIdentifier, function(err, res) {
if (err) {
return callback(err);
}
var headers = res.headers,
prefix = 'x-imbo-original';
callback(err, {
width: parseInt(headers[prefix + 'width'], 10),
height: parseInt(headers[prefix + 'height'], 10),
filesize: parseInt(headers[prefix + 'filesize'], 10),
extension: headers[prefix + 'extension'],
mimetype: headers[prefix + 'mimetype']
});
});
return this;
} | [
"function",
"(",
"imageIdentifier",
",",
"callback",
")",
"{",
"this",
".",
"headImage",
"(",
"imageIdentifier",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"headers",
"=",
"res",
".",
"headers",
",",
"prefix",
"=",
"'x-imbo-original'",
";",
"callback",
"(",
"err",
",",
"{",
"width",
":",
"parseInt",
"(",
"headers",
"[",
"prefix",
"+",
"'width'",
"]",
",",
"10",
")",
",",
"height",
":",
"parseInt",
"(",
"headers",
"[",
"prefix",
"+",
"'height'",
"]",
",",
"10",
")",
",",
"filesize",
":",
"parseInt",
"(",
"headers",
"[",
"prefix",
"+",
"'filesize'",
"]",
",",
"10",
")",
",",
"extension",
":",
"headers",
"[",
"prefix",
"+",
"'extension'",
"]",
",",
"mimetype",
":",
"headers",
"[",
"prefix",
"+",
"'mimetype'",
"]",
"}",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Get properties about an image stored in Imbo
@param {String} imageIdentifier
@param {Function} callback
@return {ImboClient} | [
"Get",
"properties",
"about",
"an",
"image",
"stored",
"in",
"Imbo"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L254-L273 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, data, callback, method) {
var url = this.getMetadataUrl(imageIdentifier);
request({
method: method || 'POST',
uri: this.getSignedResourceUrl(method || 'POST', url),
json: data,
onComplete: function(err, res, body) {
callback(err, body, res);
}
});
return this;
} | javascript | function(imageIdentifier, data, callback, method) {
var url = this.getMetadataUrl(imageIdentifier);
request({
method: method || 'POST',
uri: this.getSignedResourceUrl(method || 'POST', url),
json: data,
onComplete: function(err, res, body) {
callback(err, body, res);
}
});
return this;
} | [
"function",
"(",
"imageIdentifier",
",",
"data",
",",
"callback",
",",
"method",
")",
"{",
"var",
"url",
"=",
"this",
".",
"getMetadataUrl",
"(",
"imageIdentifier",
")",
";",
"request",
"(",
"{",
"method",
":",
"method",
"||",
"'POST'",
",",
"uri",
":",
"this",
".",
"getSignedResourceUrl",
"(",
"method",
"||",
"'POST'",
",",
"url",
")",
",",
"json",
":",
"data",
",",
"onComplete",
":",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
",",
"res",
")",
";",
"}",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Edit metadata of an image
@param {String} imageIdentifier
@param {Object} data
@param {Function} callback
@param {String} method HTTP method to use (POST/PUT)
@return {ImboClient} | [
"Edit",
"metadata",
"of",
"an",
"image"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L284-L297 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, callback) {
request.get(this.getMetadataUrl(imageIdentifier), function(err, res, body) {
callback(err, body, res);
});
return this;
} | javascript | function(imageIdentifier, callback) {
request.get(this.getMetadataUrl(imageIdentifier), function(err, res, body) {
callback(err, body, res);
});
return this;
} | [
"function",
"(",
"imageIdentifier",
",",
"callback",
")",
"{",
"request",
".",
"get",
"(",
"this",
".",
"getMetadataUrl",
"(",
"imageIdentifier",
")",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Get metadata attached to an image
@param {String} imageIdentifier
@param {Function} callback
@return {ImboClient} | [
"Get",
"metadata",
"attached",
"to",
"an",
"image"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L318-L324 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, callback) {
var url = this.getMetadataUrl(imageIdentifier);
request.del(this.getSignedResourceUrl('DELETE', url), callback);
return this;
} | javascript | function(imageIdentifier, callback) {
var url = this.getMetadataUrl(imageIdentifier);
request.del(this.getSignedResourceUrl('DELETE', url), callback);
return this;
} | [
"function",
"(",
"imageIdentifier",
",",
"callback",
")",
"{",
"var",
"url",
"=",
"this",
".",
"getMetadataUrl",
"(",
"imageIdentifier",
")",
";",
"request",
".",
"del",
"(",
"this",
".",
"getSignedResourceUrl",
"(",
"'DELETE'",
",",
"url",
")",
",",
"callback",
")",
";",
"return",
"this",
";",
"}"
] | Delete all metadata associated with an image
@param {String} imageIdentifier
@param {Function} callback
@return {ImboClient} | [
"Delete",
"all",
"metadata",
"associated",
"with",
"an",
"image"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L333-L338 | train |
|
imbo/imboclient-js | lib/client.js | function(query, callback) {
if (typeof query === 'function' && !callback) {
callback = query;
query = null;
}
// Fetch the response
request.get(this.getImagesUrl(query), function(err, res, body) {
callback(
err,
body && body.images,
body && body.search,
res
);
});
return this;
} | javascript | function(query, callback) {
if (typeof query === 'function' && !callback) {
callback = query;
query = null;
}
// Fetch the response
request.get(this.getImagesUrl(query), function(err, res, body) {
callback(
err,
body && body.images,
body && body.search,
res
);
});
return this;
} | [
"function",
"(",
"query",
",",
"callback",
")",
"{",
"if",
"(",
"typeof",
"query",
"===",
"'function'",
"&&",
"!",
"callback",
")",
"{",
"callback",
"=",
"query",
";",
"query",
"=",
"null",
";",
"}",
"request",
".",
"get",
"(",
"this",
".",
"getImagesUrl",
"(",
"query",
")",
",",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
"&&",
"body",
".",
"images",
",",
"body",
"&&",
"body",
".",
"search",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Get a list of images currently stored on the server,
and optionally provide a query to filter the results
@param {Query|Function} query - A query to use for filtering. If a function
is passed, it will be used as the callback
and the query will use default settings
@param {Function} callback
@return {ImboClient} | [
"Get",
"a",
"list",
"of",
"images",
"currently",
"stored",
"on",
"the",
"server",
"and",
"optionally",
"provide",
"a",
"query",
"to",
"filter",
"the",
"results"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L350-L367 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, options) {
if (typeof imageIdentifier !== 'string' || imageIdentifier.length === 0) {
throw new Error(
'`imageIdentifier` must be a non-empty string, was "' + imageIdentifier + '"' +
' (' + typeof imageIdentifier + ')'
);
}
options = options || {};
return new ImageUrl({
baseUrl: this.getHostForImageIdentifier(
imageIdentifier,
options.usePrimaryHost
),
path: options.path,
user: this.options.user,
publicKey: this.options.publicKey,
privateKey: this.options.privateKey,
imageIdentifier: imageIdentifier
});
} | javascript | function(imageIdentifier, options) {
if (typeof imageIdentifier !== 'string' || imageIdentifier.length === 0) {
throw new Error(
'`imageIdentifier` must be a non-empty string, was "' + imageIdentifier + '"' +
' (' + typeof imageIdentifier + ')'
);
}
options = options || {};
return new ImageUrl({
baseUrl: this.getHostForImageIdentifier(
imageIdentifier,
options.usePrimaryHost
),
path: options.path,
user: this.options.user,
publicKey: this.options.publicKey,
privateKey: this.options.privateKey,
imageIdentifier: imageIdentifier
});
} | [
"function",
"(",
"imageIdentifier",
",",
"options",
")",
"{",
"if",
"(",
"typeof",
"imageIdentifier",
"!==",
"'string'",
"||",
"imageIdentifier",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'`imageIdentifier` must be a non-empty string, was \"'",
"+",
"imageIdentifier",
"+",
"'\"'",
"+",
"' ('",
"+",
"typeof",
"imageIdentifier",
"+",
"')'",
")",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"return",
"new",
"ImageUrl",
"(",
"{",
"baseUrl",
":",
"this",
".",
"getHostForImageIdentifier",
"(",
"imageIdentifier",
",",
"options",
".",
"usePrimaryHost",
")",
",",
"path",
":",
"options",
".",
"path",
",",
"user",
":",
"this",
".",
"options",
".",
"user",
",",
"publicKey",
":",
"this",
".",
"options",
".",
"publicKey",
",",
"privateKey",
":",
"this",
".",
"options",
".",
"privateKey",
",",
"imageIdentifier",
":",
"imageIdentifier",
"}",
")",
";",
"}"
] | Get URL for the image resource
@param {String} imageIdentifier
@param {Object} [options]
@return {Imbo.ImageUrl} | [
"Get",
"URL",
"for",
"the",
"image",
"resource"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L433-L454 | train |
|
imbo/imboclient-js | lib/client.js | function(options) {
return new ImboUrl({
baseUrl: this.options.hosts[0],
user: typeof options.user !== 'undefined' ? options.user : this.options.user,
publicKey: this.options.publicKey,
privateKey: this.options.privateKey,
queryString: options.query,
path: options.path
});
} | javascript | function(options) {
return new ImboUrl({
baseUrl: this.options.hosts[0],
user: typeof options.user !== 'undefined' ? options.user : this.options.user,
publicKey: this.options.publicKey,
privateKey: this.options.privateKey,
queryString: options.query,
path: options.path
});
} | [
"function",
"(",
"options",
")",
"{",
"return",
"new",
"ImboUrl",
"(",
"{",
"baseUrl",
":",
"this",
".",
"options",
".",
"hosts",
"[",
"0",
"]",
",",
"user",
":",
"typeof",
"options",
".",
"user",
"!==",
"'undefined'",
"?",
"options",
".",
"user",
":",
"this",
".",
"options",
".",
"user",
",",
"publicKey",
":",
"this",
".",
"options",
".",
"publicKey",
",",
"privateKey",
":",
"this",
".",
"options",
".",
"privateKey",
",",
"queryString",
":",
"options",
".",
"query",
",",
"path",
":",
"options",
".",
"path",
"}",
")",
";",
"}"
] | Get URL for a resource
@param {Object} options
@return {Imbo.Url} | [
"Get",
"URL",
"for",
"a",
"resource"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L486-L495 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, callback) {
var url = this.getImageUrl(imageIdentifier).setPath('/shorturls'),
signed = this.getSignedResourceUrl('DELETE', url);
request.del(signed, callback);
return this;
} | javascript | function(imageIdentifier, callback) {
var url = this.getImageUrl(imageIdentifier).setPath('/shorturls'),
signed = this.getSignedResourceUrl('DELETE', url);
request.del(signed, callback);
return this;
} | [
"function",
"(",
"imageIdentifier",
",",
"callback",
")",
"{",
"var",
"url",
"=",
"this",
".",
"getImageUrl",
"(",
"imageIdentifier",
")",
".",
"setPath",
"(",
"'/shorturls'",
")",
",",
"signed",
"=",
"this",
".",
"getSignedResourceUrl",
"(",
"'DELETE'",
",",
"url",
")",
";",
"request",
".",
"del",
"(",
"signed",
",",
"callback",
")",
";",
"return",
"this",
";",
"}"
] | Delete all ShortUrls for a given imageIdentifier
@param {String} imageIdentifier
@param {Function} callback
@return {ImboClient} | [
"Delete",
"all",
"ShortUrls",
"for",
"a",
"given",
"imageIdentifier"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L549-L555 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, shortUrl, callback) {
var id = shortUrl instanceof ShortUrl ? shortUrl.getId() : shortUrl,
url = this.getImageUrl(imageIdentifier).setPath('/shorturls/' + id),
signed = this.getSignedResourceUrl('DELETE', url);
request.del(signed, callback);
return this;
} | javascript | function(imageIdentifier, shortUrl, callback) {
var id = shortUrl instanceof ShortUrl ? shortUrl.getId() : shortUrl,
url = this.getImageUrl(imageIdentifier).setPath('/shorturls/' + id),
signed = this.getSignedResourceUrl('DELETE', url);
request.del(signed, callback);
return this;
} | [
"function",
"(",
"imageIdentifier",
",",
"shortUrl",
",",
"callback",
")",
"{",
"var",
"id",
"=",
"shortUrl",
"instanceof",
"ShortUrl",
"?",
"shortUrl",
".",
"getId",
"(",
")",
":",
"shortUrl",
",",
"url",
"=",
"this",
".",
"getImageUrl",
"(",
"imageIdentifier",
")",
".",
"setPath",
"(",
"'/shorturls/'",
"+",
"id",
")",
",",
"signed",
"=",
"this",
".",
"getSignedResourceUrl",
"(",
"'DELETE'",
",",
"url",
")",
";",
"request",
".",
"del",
"(",
"signed",
",",
"callback",
")",
";",
"return",
"this",
";",
"}"
] | Delete a ShortUrl for a given imageIdentifier
@param {String} imageIdentifier
@param {String|Imbo.ShortUrl} shortUrl
@param {Function} callback
@return {ImboClient} | [
"Delete",
"a",
"ShortUrl",
"for",
"a",
"given",
"imageIdentifier"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L565-L572 | train |
|
imbo/imboclient-js | lib/client.js | function(imgPath, callback) {
this.getImageChecksum(imgPath, function(err, checksum) {
if (err) {
return callback(err);
}
this.imageWithChecksumExists(checksum, callback);
}.bind(this));
return this;
} | javascript | function(imgPath, callback) {
this.getImageChecksum(imgPath, function(err, checksum) {
if (err) {
return callback(err);
}
this.imageWithChecksumExists(checksum, callback);
}.bind(this));
return this;
} | [
"function",
"(",
"imgPath",
",",
"callback",
")",
"{",
"this",
".",
"getImageChecksum",
"(",
"imgPath",
",",
"function",
"(",
"err",
",",
"checksum",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"this",
".",
"imageWithChecksumExists",
"(",
"checksum",
",",
"callback",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"return",
"this",
";",
"}"
] | Checks if a given image exists on the server
@param {String} imgPath
@param {Function} callback
@return {ImboClient} | [
"Checks",
"if",
"a",
"given",
"image",
"exists",
"on",
"the",
"server"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L595-L605 | train |
|
imbo/imboclient-js | lib/client.js | function(checksum, callback) {
var query = (new ImboQuery()).originalChecksums([checksum]).limit(1);
this.getImages(query, function(err, images, search) {
if (err) {
return callback(err);
}
var exists = search.hits > 0;
callback(err, exists, exists ? images[0].imageIdentifier : err);
});
return this;
} | javascript | function(checksum, callback) {
var query = (new ImboQuery()).originalChecksums([checksum]).limit(1);
this.getImages(query, function(err, images, search) {
if (err) {
return callback(err);
}
var exists = search.hits > 0;
callback(err, exists, exists ? images[0].imageIdentifier : err);
});
return this;
} | [
"function",
"(",
"checksum",
",",
"callback",
")",
"{",
"var",
"query",
"=",
"(",
"new",
"ImboQuery",
"(",
")",
")",
".",
"originalChecksums",
"(",
"[",
"checksum",
"]",
")",
".",
"limit",
"(",
"1",
")",
";",
"this",
".",
"getImages",
"(",
"query",
",",
"function",
"(",
"err",
",",
"images",
",",
"search",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"var",
"exists",
"=",
"search",
".",
"hits",
">",
"0",
";",
"callback",
"(",
"err",
",",
"exists",
",",
"exists",
"?",
"images",
"[",
"0",
"]",
".",
"imageIdentifier",
":",
"err",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Checks if an image with the given MD5-sum exists on the server
@param {String} checksum
@param {Function} callback
@return {ImboClient} | [
"Checks",
"if",
"an",
"image",
"with",
"the",
"given",
"MD5",
"-",
"sum",
"exists",
"on",
"the",
"server"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L627-L639 | train |
|
imbo/imboclient-js | lib/client.js | function(callback) {
request.get(
this.getResourceUrl({ path: '/groups', user: null }),
function onResourceGroupsResponse(err, res, body) {
callback(
err,
body && body.groups,
body && body.search,
res
);
}
);
return this;
} | javascript | function(callback) {
request.get(
this.getResourceUrl({ path: '/groups', user: null }),
function onResourceGroupsResponse(err, res, body) {
callback(
err,
body && body.groups,
body && body.search,
res
);
}
);
return this;
} | [
"function",
"(",
"callback",
")",
"{",
"request",
".",
"get",
"(",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/groups'",
",",
"user",
":",
"null",
"}",
")",
",",
"function",
"onResourceGroupsResponse",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
"&&",
"body",
".",
"groups",
",",
"body",
"&&",
"body",
".",
"search",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Fetch the resource groups available
@param {Function} callback
@return {ImboClient} | [
"Fetch",
"the",
"resource",
"groups",
"available"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L647-L660 | train |
|
imbo/imboclient-js | lib/client.js | function(groupName, callback) {
request.get(
this.getResourceUrl({ path: '/groups/' + groupName, user: null }),
function onResourceGroupResponse(err, res, body) {
callback(err, body && body.resources, res);
}
);
return this;
} | javascript | function(groupName, callback) {
request.get(
this.getResourceUrl({ path: '/groups/' + groupName, user: null }),
function onResourceGroupResponse(err, res, body) {
callback(err, body && body.resources, res);
}
);
return this;
} | [
"function",
"(",
"groupName",
",",
"callback",
")",
"{",
"request",
".",
"get",
"(",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/groups/'",
"+",
"groupName",
",",
"user",
":",
"null",
"}",
")",
",",
"function",
"onResourceGroupResponse",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
"&&",
"body",
".",
"resources",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Fetch a specific resource group
@param {String} groupName
@param {Function} callback
@return {ImboClient} | [
"Fetch",
"a",
"specific",
"resource",
"group"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L669-L677 | train |
|
imbo/imboclient-js | lib/client.js | function(groupName, resources, callback) {
this.resourceGroupExists(groupName, function onGroupExistsResponse(err, exists) {
if (err) {
return callback(err);
}
if (exists) {
return callback(new Error(
'Resource group `' + groupName + '` already exists'
));
}
this.editResourceGroup(groupName, resources, callback);
}.bind(this));
return this;
} | javascript | function(groupName, resources, callback) {
this.resourceGroupExists(groupName, function onGroupExistsResponse(err, exists) {
if (err) {
return callback(err);
}
if (exists) {
return callback(new Error(
'Resource group `' + groupName + '` already exists'
));
}
this.editResourceGroup(groupName, resources, callback);
}.bind(this));
return this;
} | [
"function",
"(",
"groupName",
",",
"resources",
",",
"callback",
")",
"{",
"this",
".",
"resourceGroupExists",
"(",
"groupName",
",",
"function",
"onGroupExistsResponse",
"(",
"err",
",",
"exists",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"exists",
")",
"{",
"return",
"callback",
"(",
"new",
"Error",
"(",
"'Resource group `'",
"+",
"groupName",
"+",
"'` already exists'",
")",
")",
";",
"}",
"this",
".",
"editResourceGroup",
"(",
"groupName",
",",
"resources",
",",
"callback",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"return",
"this",
";",
"}"
] | Create a resource group, defining the resources that sohuld be available to it
@param {String} groupName
@param {Array} resources
@param {Function} callback
@return {ImboCflient} | [
"Create",
"a",
"resource",
"group",
"defining",
"the",
"resources",
"that",
"sohuld",
"be",
"available",
"to",
"it"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L687-L703 | train |
|
imbo/imboclient-js | lib/client.js | function(groupName, callback) {
var url = this.getResourceUrl({ path: '/groups/' + groupName, user: null });
request.del(this.getSignedResourceUrl('DELETE', url), callback);
return this;
} | javascript | function(groupName, callback) {
var url = this.getResourceUrl({ path: '/groups/' + groupName, user: null });
request.del(this.getSignedResourceUrl('DELETE', url), callback);
return this;
} | [
"function",
"(",
"groupName",
",",
"callback",
")",
"{",
"var",
"url",
"=",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/groups/'",
"+",
"groupName",
",",
"user",
":",
"null",
"}",
")",
";",
"request",
".",
"del",
"(",
"this",
".",
"getSignedResourceUrl",
"(",
"'DELETE'",
",",
"url",
")",
",",
"callback",
")",
";",
"return",
"this",
";",
"}"
] | Delete the resource group with the given name
@param {String} groupName Name of the group you want to delete
@param {Function} callback
@return {ImboClient} | [
"Delete",
"the",
"resource",
"group",
"with",
"the",
"given",
"name"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L734-L739 | train |
|
imbo/imboclient-js | lib/client.js | function(groupName, callback) {
request.head(
this.getResourceUrl({ path: '/groups/' + groupName, user: null }),
get404Handler(callback)
);
return this;
} | javascript | function(groupName, callback) {
request.head(
this.getResourceUrl({ path: '/groups/' + groupName, user: null }),
get404Handler(callback)
);
return this;
} | [
"function",
"(",
"groupName",
",",
"callback",
")",
"{",
"request",
".",
"head",
"(",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/groups/'",
"+",
"groupName",
",",
"user",
":",
"null",
"}",
")",
",",
"get404Handler",
"(",
"callback",
")",
")",
";",
"return",
"this",
";",
"}"
] | Check whether a resource group exists or not
@param {String} groupName Name of the group you want to check for the presence of
@param {Function} callback
@return {ImboClient} | [
"Check",
"whether",
"a",
"resource",
"group",
"exists",
"or",
"not"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L748-L754 | train |
|
imbo/imboclient-js | lib/client.js | function(publicKey, callback) {
request.head(
this.getResourceUrl({ path: '/keys/' + publicKey, user: null }),
get404Handler(callback)
);
return this;
} | javascript | function(publicKey, callback) {
request.head(
this.getResourceUrl({ path: '/keys/' + publicKey, user: null }),
get404Handler(callback)
);
return this;
} | [
"function",
"(",
"publicKey",
",",
"callback",
")",
"{",
"request",
".",
"head",
"(",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/keys/'",
"+",
"publicKey",
",",
"user",
":",
"null",
"}",
")",
",",
"get404Handler",
"(",
"callback",
")",
")",
";",
"return",
"this",
";",
"}"
] | Check whether a public key exists or not
@param {String} publicKey Public key you want to check for the presence of
@param {Function} callback
@return {ImboClient} | [
"Check",
"whether",
"a",
"public",
"key",
"exists",
"or",
"not"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L827-L833 | train |
|
imbo/imboclient-js | lib/client.js | function(publicKey, expandGroups, callback) {
var qs = '';
if (!callback && typeof expandGroups === 'function') {
callback = expandGroups;
} else if (expandGroups) {
qs = '?expandGroups=1';
}
request.get(
this.getResourceUrl({ path: '/keys/' + publicKey + '/access' + qs, user: null }),
function onAccessControlRulesResponse(err, res, body) {
callback(err, body, res);
}
);
return this;
} | javascript | function(publicKey, expandGroups, callback) {
var qs = '';
if (!callback && typeof expandGroups === 'function') {
callback = expandGroups;
} else if (expandGroups) {
qs = '?expandGroups=1';
}
request.get(
this.getResourceUrl({ path: '/keys/' + publicKey + '/access' + qs, user: null }),
function onAccessControlRulesResponse(err, res, body) {
callback(err, body, res);
}
);
return this;
} | [
"function",
"(",
"publicKey",
",",
"expandGroups",
",",
"callback",
")",
"{",
"var",
"qs",
"=",
"''",
";",
"if",
"(",
"!",
"callback",
"&&",
"typeof",
"expandGroups",
"===",
"'function'",
")",
"{",
"callback",
"=",
"expandGroups",
";",
"}",
"else",
"if",
"(",
"expandGroups",
")",
"{",
"qs",
"=",
"'?expandGroups=1'",
";",
"}",
"request",
".",
"get",
"(",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/keys/'",
"+",
"publicKey",
"+",
"'/access'",
"+",
"qs",
",",
"user",
":",
"null",
"}",
")",
",",
"function",
"onAccessControlRulesResponse",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Get a list of access control rules for a given public key
@param {String} publicKey
@param {Boolean} expandGroups
@param {Function} callback
@return {ImboClient} | [
"Get",
"a",
"list",
"of",
"access",
"control",
"rules",
"for",
"a",
"given",
"public",
"key"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L843-L858 | train |
|
imbo/imboclient-js | lib/client.js | function(publicKey, aclRuleId, callback) {
request.get(
this.getResourceUrl({
path: '/keys/' + publicKey + '/access/' + aclRuleId,
user: null
}),
function onAccessControlRulesResponse(err, res, body) {
callback(err, body, res);
}
);
return this;
} | javascript | function(publicKey, aclRuleId, callback) {
request.get(
this.getResourceUrl({
path: '/keys/' + publicKey + '/access/' + aclRuleId,
user: null
}),
function onAccessControlRulesResponse(err, res, body) {
callback(err, body, res);
}
);
return this;
} | [
"function",
"(",
"publicKey",
",",
"aclRuleId",
",",
"callback",
")",
"{",
"request",
".",
"get",
"(",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/keys/'",
"+",
"publicKey",
"+",
"'/access/'",
"+",
"aclRuleId",
",",
"user",
":",
"null",
"}",
")",
",",
"function",
"onAccessControlRulesResponse",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
",",
"res",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Get the details for the access control rule with the given ID
@param {String} publicKey
@param {String} aclRuleId
@param {Function} callback
@return {ImboClient} | [
"Get",
"the",
"details",
"for",
"the",
"access",
"control",
"rule",
"with",
"the",
"given",
"ID"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L868-L879 | train |
|
imbo/imboclient-js | lib/client.js | function(publicKey, rules, callback) {
if (!Array.isArray(rules)) {
rules = [rules];
}
if (!publicKey) {
throw new Error('Public key must be a valid string');
}
var url = this.getResourceUrl({ path: '/keys/' + publicKey + '/access', user: null });
request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', url),
json: rules,
onComplete: function(err, res, body) {
callback(err, body, res);
}
});
return this;
} | javascript | function(publicKey, rules, callback) {
if (!Array.isArray(rules)) {
rules = [rules];
}
if (!publicKey) {
throw new Error('Public key must be a valid string');
}
var url = this.getResourceUrl({ path: '/keys/' + publicKey + '/access', user: null });
request({
method: 'POST',
uri: this.getSignedResourceUrl('POST', url),
json: rules,
onComplete: function(err, res, body) {
callback(err, body, res);
}
});
return this;
} | [
"function",
"(",
"publicKey",
",",
"rules",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"rules",
")",
")",
"{",
"rules",
"=",
"[",
"rules",
"]",
";",
"}",
"if",
"(",
"!",
"publicKey",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Public key must be a valid string'",
")",
";",
"}",
"var",
"url",
"=",
"this",
".",
"getResourceUrl",
"(",
"{",
"path",
":",
"'/keys/'",
"+",
"publicKey",
"+",
"'/access'",
",",
"user",
":",
"null",
"}",
")",
";",
"request",
"(",
"{",
"method",
":",
"'POST'",
",",
"uri",
":",
"this",
".",
"getSignedResourceUrl",
"(",
"'POST'",
",",
"url",
")",
",",
"json",
":",
"rules",
",",
"onComplete",
":",
"function",
"(",
"err",
",",
"res",
",",
"body",
")",
"{",
"callback",
"(",
"err",
",",
"body",
",",
"res",
")",
";",
"}",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Add one or more access control rules to the given public key
@param {String} publicKey The public key to add rules to
@param {Array} rules Array of access control rules to add
@param {Function} callback
@return {ImboClient} | [
"Add",
"one",
"or",
"more",
"access",
"control",
"rules",
"to",
"the",
"given",
"public",
"key"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L889-L910 | train |
|
imbo/imboclient-js | lib/client.js | function(imageUrl, callback) {
readers.getContentsFromUrl(imageUrl.toString(), function(err, data) {
callback(err, err ? null : data);
});
return this;
} | javascript | function(imageUrl, callback) {
readers.getContentsFromUrl(imageUrl.toString(), function(err, data) {
callback(err, err ? null : data);
});
return this;
} | [
"function",
"(",
"imageUrl",
",",
"callback",
")",
"{",
"readers",
".",
"getContentsFromUrl",
"(",
"imageUrl",
".",
"toString",
"(",
")",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"callback",
"(",
"err",
",",
"err",
"?",
"null",
":",
"data",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
] | Get the binary data of an image, specified by URL
@param {String} imageUrl
@param {Function} callback
@return {ImboClient} | [
"Get",
"the",
"binary",
"data",
"of",
"an",
"image",
"specified",
"by",
"URL"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L951-L957 | train |
|
imbo/imboclient-js | lib/client.js | function(imageIdentifier, usePrimary) {
if (usePrimary) {
return this.options.hosts[0];
}
var dec = imageIdentifier.charCodeAt(imageIdentifier.length - 1);
// If this is an old image identifier (32 character hex string),
// maintain backwards compatibility
if (imageIdentifier.match(/^[a-f0-9]{32}$/)) {
dec = parseInt(imageIdentifier.substr(0, 2), 16);
}
return this.options.hosts[dec % this.options.hosts.length];
} | javascript | function(imageIdentifier, usePrimary) {
if (usePrimary) {
return this.options.hosts[0];
}
var dec = imageIdentifier.charCodeAt(imageIdentifier.length - 1);
// If this is an old image identifier (32 character hex string),
// maintain backwards compatibility
if (imageIdentifier.match(/^[a-f0-9]{32}$/)) {
dec = parseInt(imageIdentifier.substr(0, 2), 16);
}
return this.options.hosts[dec % this.options.hosts.length];
} | [
"function",
"(",
"imageIdentifier",
",",
"usePrimary",
")",
"{",
"if",
"(",
"usePrimary",
")",
"{",
"return",
"this",
".",
"options",
".",
"hosts",
"[",
"0",
"]",
";",
"}",
"var",
"dec",
"=",
"imageIdentifier",
".",
"charCodeAt",
"(",
"imageIdentifier",
".",
"length",
"-",
"1",
")",
";",
"if",
"(",
"imageIdentifier",
".",
"match",
"(",
"/",
"^[a-f0-9]{32}$",
"/",
")",
")",
"{",
"dec",
"=",
"parseInt",
"(",
"imageIdentifier",
".",
"substr",
"(",
"0",
",",
"2",
")",
",",
"16",
")",
";",
"}",
"return",
"this",
".",
"options",
".",
"hosts",
"[",
"dec",
"%",
"this",
".",
"options",
".",
"hosts",
".",
"length",
"]",
";",
"}"
] | Get a predictable hostname for the given image identifier
@param {String} imageIdentifier
@param {Boolean} [usePrimary=false] Whether to use the primary host
@return {String} | [
"Get",
"a",
"predictable",
"hostname",
"for",
"the",
"given",
"image",
"identifier"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L966-L980 | train |
|
imbo/imboclient-js | lib/client.js | function(method, url, timestamp) {
var data = [method, url, this.options.publicKey, timestamp].join('|'),
signature = crypto.sha256(this.options.privateKey, data);
return signature;
} | javascript | function(method, url, timestamp) {
var data = [method, url, this.options.publicKey, timestamp].join('|'),
signature = crypto.sha256(this.options.privateKey, data);
return signature;
} | [
"function",
"(",
"method",
",",
"url",
",",
"timestamp",
")",
"{",
"var",
"data",
"=",
"[",
"method",
",",
"url",
",",
"this",
".",
"options",
".",
"publicKey",
",",
"timestamp",
"]",
".",
"join",
"(",
"'|'",
")",
",",
"signature",
"=",
"crypto",
".",
"sha256",
"(",
"this",
".",
"options",
".",
"privateKey",
",",
"data",
")",
";",
"return",
"signature",
";",
"}"
] | Generate a signature for the given parameters
@param {String} method
@param {String} url
@param {String} timestamp
@return {String} | [
"Generate",
"a",
"signature",
"for",
"the",
"given",
"parameters"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L1018-L1023 | train |
|
imbo/imboclient-js | lib/client.js | function(method, url, date) {
var timestamp = (date || new Date()).toISOString().replace(/\.\d+Z$/, 'Z'),
addPubKey = this.options.user !== this.options.publicKey,
qs = url.toString().indexOf('?') > -1 ? '&' : '?',
signUrl = addPubKey ? url + qs + 'publicKey=' + this.options.publicKey : url,
signature = this.generateSignature(method, signUrl.toString(), timestamp);
qs = addPubKey ? '&' : qs;
qs += 'signature=' + encodeURIComponent(signature);
qs += '×tamp=' + encodeURIComponent(timestamp);
return signUrl + qs;
} | javascript | function(method, url, date) {
var timestamp = (date || new Date()).toISOString().replace(/\.\d+Z$/, 'Z'),
addPubKey = this.options.user !== this.options.publicKey,
qs = url.toString().indexOf('?') > -1 ? '&' : '?',
signUrl = addPubKey ? url + qs + 'publicKey=' + this.options.publicKey : url,
signature = this.generateSignature(method, signUrl.toString(), timestamp);
qs = addPubKey ? '&' : qs;
qs += 'signature=' + encodeURIComponent(signature);
qs += '×tamp=' + encodeURIComponent(timestamp);
return signUrl + qs;
} | [
"function",
"(",
"method",
",",
"url",
",",
"date",
")",
"{",
"var",
"timestamp",
"=",
"(",
"date",
"||",
"new",
"Date",
"(",
")",
")",
".",
"toISOString",
"(",
")",
".",
"replace",
"(",
"/",
"\\.\\d+Z$",
"/",
",",
"'Z'",
")",
",",
"addPubKey",
"=",
"this",
".",
"options",
".",
"user",
"!==",
"this",
".",
"options",
".",
"publicKey",
",",
"qs",
"=",
"url",
".",
"toString",
"(",
")",
".",
"indexOf",
"(",
"'?'",
")",
">",
"-",
"1",
"?",
"'&'",
":",
"'?'",
",",
"signUrl",
"=",
"addPubKey",
"?",
"url",
"+",
"qs",
"+",
"'publicKey='",
"+",
"this",
".",
"options",
".",
"publicKey",
":",
"url",
",",
"signature",
"=",
"this",
".",
"generateSignature",
"(",
"method",
",",
"signUrl",
".",
"toString",
"(",
")",
",",
"timestamp",
")",
";",
"qs",
"=",
"addPubKey",
"?",
"'&'",
":",
"qs",
";",
"qs",
"+=",
"'signature='",
"+",
"encodeURIComponent",
"(",
"signature",
")",
";",
"qs",
"+=",
"'×tamp='",
"+",
"encodeURIComponent",
"(",
"timestamp",
")",
";",
"return",
"signUrl",
"+",
"qs",
";",
"}"
] | Get a signed version of a given URL
@param {String} method - HTTP method
@param {String} url - Endpoint URL
@param {Date} [date] - Date to use for signing request
@return {String} | [
"Get",
"a",
"signed",
"version",
"of",
"a",
"given",
"URL"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/client.js#L1033-L1045 | train |
|
DimitarChristoff/primish | options.js | function(options){
var option,
o;
this.options || (this.options = {});
o = this.options = primish.merge(primish.clone(this.options), options);
// add the events as well, if class has events.
if ((this.on && this.off))
for (option in o){
if (o.hasOwnProperty(option)){
if (typeof o[option] !== sFunction || !(/^on[A-Z]/).test(option)) continue;
this.on(removeOn(option), o[option]);
delete o[option];
}
}
return this;
} | javascript | function(options){
var option,
o;
this.options || (this.options = {});
o = this.options = primish.merge(primish.clone(this.options), options);
// add the events as well, if class has events.
if ((this.on && this.off))
for (option in o){
if (o.hasOwnProperty(option)){
if (typeof o[option] !== sFunction || !(/^on[A-Z]/).test(option)) continue;
this.on(removeOn(option), o[option]);
delete o[option];
}
}
return this;
} | [
"function",
"(",
"options",
")",
"{",
"var",
"option",
",",
"o",
";",
"this",
".",
"options",
"||",
"(",
"this",
".",
"options",
"=",
"{",
"}",
")",
";",
"o",
"=",
"this",
".",
"options",
"=",
"primish",
".",
"merge",
"(",
"primish",
".",
"clone",
"(",
"this",
".",
"options",
")",
",",
"options",
")",
";",
"if",
"(",
"(",
"this",
".",
"on",
"&&",
"this",
".",
"off",
")",
")",
"for",
"(",
"option",
"in",
"o",
")",
"{",
"if",
"(",
"o",
".",
"hasOwnProperty",
"(",
"option",
")",
")",
"{",
"if",
"(",
"typeof",
"o",
"[",
"option",
"]",
"!==",
"sFunction",
"||",
"!",
"(",
"/",
"^on[A-Z]",
"/",
")",
".",
"test",
"(",
"option",
")",
")",
"continue",
";",
"this",
".",
"on",
"(",
"removeOn",
"(",
"option",
")",
",",
"o",
"[",
"option",
"]",
")",
";",
"delete",
"o",
"[",
"option",
"]",
";",
"}",
"}",
"return",
"this",
";",
"}"
] | a mixin class that allows for this.setOptions | [
"a",
"mixin",
"class",
"that",
"allows",
"for",
"this",
".",
"setOptions"
] | b80d54e346c8d5594254e95db0936be72264e4b4 | https://github.com/DimitarChristoff/primish/blob/b80d54e346c8d5594254e95db0936be72264e4b4/options.js#L25-L42 | train |
|
Schoonology/discovery | lib/service.js | Service | function Service(options) {
if (!(this instanceof Service)) {
return new Service(options);
}
options = options || {};
debug('New Service: %j', options);
// There's no reasonable way to protect this, so we let it be writable with
// the understanding that .update is called in the future. TL;DR - Write at
// your own risk.
this.data = clone(options.data || {});
this._dataHash = sigmund(this.data);
this._initProperties(options);
assert(this.name, 'Name is required.');
} | javascript | function Service(options) {
if (!(this instanceof Service)) {
return new Service(options);
}
options = options || {};
debug('New Service: %j', options);
// There's no reasonable way to protect this, so we let it be writable with
// the understanding that .update is called in the future. TL;DR - Write at
// your own risk.
this.data = clone(options.data || {});
this._dataHash = sigmund(this.data);
this._initProperties(options);
assert(this.name, 'Name is required.');
} | [
"function",
"Service",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Service",
")",
")",
"{",
"return",
"new",
"Service",
"(",
"options",
")",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"debug",
"(",
"'New Service: %j'",
",",
"options",
")",
";",
"this",
".",
"data",
"=",
"clone",
"(",
"options",
".",
"data",
"||",
"{",
"}",
")",
";",
"this",
".",
"_dataHash",
"=",
"sigmund",
"(",
"this",
".",
"data",
")",
";",
"this",
".",
"_initProperties",
"(",
"options",
")",
";",
"assert",
"(",
"this",
".",
"name",
",",
"'Name is required.'",
")",
";",
"}"
] | Creates a new instance of Service with the provided `options`.
A Service is a simple wrapper around its `data` to ease managing the
Service's representation within its Registry and the announcements thereof.
For more information, see the README.
@param {Object} options | [
"Creates",
"a",
"new",
"instance",
"of",
"Service",
"with",
"the",
"provided",
"options",
"."
] | 9d123d74c13f8c9b6904e409f8933b09ab22e175 | https://github.com/Schoonology/discovery/blob/9d123d74c13f8c9b6904e409f8933b09ab22e175/lib/service.js#L19-L37 | train |
imbo/imboclient-js | lib/url/imageurl.js | function(options) {
options = options || {};
var params = [
'color=' + (options.color || '000000').replace(/^#/, ''),
'width=' + toInt(options.width || 1),
'height=' + toInt(options.height || 1),
'mode=' + (options.mode || 'outbound')
];
return this.append('border:' + params.join(','));
} | javascript | function(options) {
options = options || {};
var params = [
'color=' + (options.color || '000000').replace(/^#/, ''),
'width=' + toInt(options.width || 1),
'height=' + toInt(options.height || 1),
'mode=' + (options.mode || 'outbound')
];
return this.append('border:' + params.join(','));
} | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"params",
"=",
"[",
"'color='",
"+",
"(",
"options",
".",
"color",
"||",
"'000000'",
")",
".",
"replace",
"(",
"/",
"^#",
"/",
",",
"''",
")",
",",
"'width='",
"+",
"toInt",
"(",
"options",
".",
"width",
"||",
"1",
")",
",",
"'height='",
"+",
"toInt",
"(",
"options",
".",
"height",
"||",
"1",
")",
",",
"'mode='",
"+",
"(",
"options",
".",
"mode",
"||",
"'outbound'",
")",
"]",
";",
"return",
"this",
".",
"append",
"(",
"'border:'",
"+",
"params",
".",
"join",
"(",
"','",
")",
")",
";",
"}"
] | Add a border to the image
@param {Object} [options={}]
@param {String} [options.color=000000] Color of the border (in hex-format)
@param {Number} [options.width=1] Width of the left and right borders
@param {Number} [options.height=1] Height of the top and bottom borders
@param {String} [options.mode=outbound] Mode of the border, "inline" or "outbound"
@return {Imbo.ImageUrl} | [
"Add",
"a",
"border",
"to",
"the",
"image"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L72-L83 | train |
|
imbo/imboclient-js | lib/url/imageurl.js | function(options) {
options = options || {};
if (!options.width || !options.height) {
throw new Error('width and height must be specified');
}
var params = [
'width=' + toInt(options.width),
'height=' + toInt(options.height)
];
if (options.mode) {
params.push('mode=' + options.mode);
}
if (options.x) {
params.push('x=' + toInt(options.x));
}
if (options.y) {
params.push('y=' + toInt(options.y));
}
if (options.bg) {
params.push('bg=' + options.bg.replace(/^#/, ''));
}
return this.append('canvas:' + params.join(','));
} | javascript | function(options) {
options = options || {};
if (!options.width || !options.height) {
throw new Error('width and height must be specified');
}
var params = [
'width=' + toInt(options.width),
'height=' + toInt(options.height)
];
if (options.mode) {
params.push('mode=' + options.mode);
}
if (options.x) {
params.push('x=' + toInt(options.x));
}
if (options.y) {
params.push('y=' + toInt(options.y));
}
if (options.bg) {
params.push('bg=' + options.bg.replace(/^#/, ''));
}
return this.append('canvas:' + params.join(','));
} | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"if",
"(",
"!",
"options",
".",
"width",
"||",
"!",
"options",
".",
"height",
")",
"{",
"throw",
"new",
"Error",
"(",
"'width and height must be specified'",
")",
";",
"}",
"var",
"params",
"=",
"[",
"'width='",
"+",
"toInt",
"(",
"options",
".",
"width",
")",
",",
"'height='",
"+",
"toInt",
"(",
"options",
".",
"height",
")",
"]",
";",
"if",
"(",
"options",
".",
"mode",
")",
"{",
"params",
".",
"push",
"(",
"'mode='",
"+",
"options",
".",
"mode",
")",
";",
"}",
"if",
"(",
"options",
".",
"x",
")",
"{",
"params",
".",
"push",
"(",
"'x='",
"+",
"toInt",
"(",
"options",
".",
"x",
")",
")",
";",
"}",
"if",
"(",
"options",
".",
"y",
")",
"{",
"params",
".",
"push",
"(",
"'y='",
"+",
"toInt",
"(",
"options",
".",
"y",
")",
")",
";",
"}",
"if",
"(",
"options",
".",
"bg",
")",
"{",
"params",
".",
"push",
"(",
"'bg='",
"+",
"options",
".",
"bg",
".",
"replace",
"(",
"/",
"^#",
"/",
",",
"''",
")",
")",
";",
"}",
"return",
"this",
".",
"append",
"(",
"'canvas:'",
"+",
"params",
".",
"join",
"(",
"','",
")",
")",
";",
"}"
] | Puts the image inside a canvas
@param {Object} options
@param {Number} options.width Width of the canvas
@param {Number} options.height Height of the canvas
@param {String} [options.mode] Placement mode: "free", "center", "center-x" or "center-y"
@param {Number} [options.x] X coordinate of the placement of the upper left corner of the existing image
@param {Number} [options.y] Y coordinate of the placement of the upper left corner of the existing image
@param {String} [options.bg] Background color of the canvas, in hex-format
@return {Imbo.ImageUrl} | [
"Puts",
"the",
"image",
"inside",
"a",
"canvas"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L97-L126 | train |
|
imbo/imboclient-js | lib/url/imageurl.js | function(options) {
var params = [],
opts = options || {},
transform = 'contrast';
if (opts.sharpen) {
params.push('sharpen=' + opts.sharpen);
}
if (params.length) {
transform += ':' + params.join(',');
}
return this.append(transform);
} | javascript | function(options) {
var params = [],
opts = options || {},
transform = 'contrast';
if (opts.sharpen) {
params.push('sharpen=' + opts.sharpen);
}
if (params.length) {
transform += ':' + params.join(',');
}
return this.append(transform);
} | [
"function",
"(",
"options",
")",
"{",
"var",
"params",
"=",
"[",
"]",
",",
"opts",
"=",
"options",
"||",
"{",
"}",
",",
"transform",
"=",
"'contrast'",
";",
"if",
"(",
"opts",
".",
"sharpen",
")",
"{",
"params",
".",
"push",
"(",
"'sharpen='",
"+",
"opts",
".",
"sharpen",
")",
";",
"}",
"if",
"(",
"params",
".",
"length",
")",
"{",
"transform",
"+=",
"':'",
"+",
"params",
".",
"join",
"(",
"','",
")",
";",
"}",
"return",
"this",
".",
"append",
"(",
"transform",
")",
";",
"}"
] | Adjust contrast in the image
@param {Object} [options={}]
@param {Number} [options.sharpen] Change in contrast given as number of steps up (positive
number) or down (negative number)
@return {Imbo.ImageUrl} | [
"Adjust",
"contrast",
"in",
"the",
"image"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L148-L162 | train |
|
imbo/imboclient-js | lib/url/imageurl.js | function(options) {
var opts = options || {},
mode = opts.mode,
x = opts.x,
y = opts.y,
width = opts.width,
height = opts.height;
if (!mode && (isNaN(x) || isNaN(y))) {
throw new Error('x and y needs to be specified without a crop mode');
}
if (mode === 'center-x' && isNaN(y)) {
throw new Error('y needs to be specified when mode is center-x');
} else if (mode === 'center-y' && isNaN(x)) {
throw new Error('x needs to be specified when mode is center-y');
} else if (isNaN(width) || isNaN(height)) {
throw new Error('width and height needs to be specified');
}
var params = [
'width=' + toInt(width),
'height=' + toInt(height)
];
if (isNumeric(x)) {
params.push('x=' + toInt(x));
}
if (isNumeric(y)) {
params.push('y=' + toInt(y));
}
if (mode) {
params.push('mode=' + mode);
}
return this.append('crop:' + params.join(','));
} | javascript | function(options) {
var opts = options || {},
mode = opts.mode,
x = opts.x,
y = opts.y,
width = opts.width,
height = opts.height;
if (!mode && (isNaN(x) || isNaN(y))) {
throw new Error('x and y needs to be specified without a crop mode');
}
if (mode === 'center-x' && isNaN(y)) {
throw new Error('y needs to be specified when mode is center-x');
} else if (mode === 'center-y' && isNaN(x)) {
throw new Error('x needs to be specified when mode is center-y');
} else if (isNaN(width) || isNaN(height)) {
throw new Error('width and height needs to be specified');
}
var params = [
'width=' + toInt(width),
'height=' + toInt(height)
];
if (isNumeric(x)) {
params.push('x=' + toInt(x));
}
if (isNumeric(y)) {
params.push('y=' + toInt(y));
}
if (mode) {
params.push('mode=' + mode);
}
return this.append('crop:' + params.join(','));
} | [
"function",
"(",
"options",
")",
"{",
"var",
"opts",
"=",
"options",
"||",
"{",
"}",
",",
"mode",
"=",
"opts",
".",
"mode",
",",
"x",
"=",
"opts",
".",
"x",
",",
"y",
"=",
"opts",
".",
"y",
",",
"width",
"=",
"opts",
".",
"width",
",",
"height",
"=",
"opts",
".",
"height",
";",
"if",
"(",
"!",
"mode",
"&&",
"(",
"isNaN",
"(",
"x",
")",
"||",
"isNaN",
"(",
"y",
")",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'x and y needs to be specified without a crop mode'",
")",
";",
"}",
"if",
"(",
"mode",
"===",
"'center-x'",
"&&",
"isNaN",
"(",
"y",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'y needs to be specified when mode is center-x'",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"===",
"'center-y'",
"&&",
"isNaN",
"(",
"x",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'x needs to be specified when mode is center-y'",
")",
";",
"}",
"else",
"if",
"(",
"isNaN",
"(",
"width",
")",
"||",
"isNaN",
"(",
"height",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'width and height needs to be specified'",
")",
";",
"}",
"var",
"params",
"=",
"[",
"'width='",
"+",
"toInt",
"(",
"width",
")",
",",
"'height='",
"+",
"toInt",
"(",
"height",
")",
"]",
";",
"if",
"(",
"isNumeric",
"(",
"x",
")",
")",
"{",
"params",
".",
"push",
"(",
"'x='",
"+",
"toInt",
"(",
"x",
")",
")",
";",
"}",
"if",
"(",
"isNumeric",
"(",
"y",
")",
")",
"{",
"params",
".",
"push",
"(",
"'y='",
"+",
"toInt",
"(",
"y",
")",
")",
";",
"}",
"if",
"(",
"mode",
")",
"{",
"params",
".",
"push",
"(",
"'mode='",
"+",
"mode",
")",
";",
"}",
"return",
"this",
".",
"append",
"(",
"'crop:'",
"+",
"params",
".",
"join",
"(",
"','",
")",
")",
";",
"}"
] | Crops the image using specified parameters
@param {Object} options
@param {String} [options.mode] Crop mode: "center-x" or "center-y" (available in Imbo >= 1.1.0)
@param {Number} [options.x] X coordinate of the top left corner of the crop
@param {Number} [options.y] Y coordinate of the top left corner of the crop
@param {Number} options.width Width of the crop
@param {Number} options.height Height of the crop
@return {Imbo.ImageUrl} | [
"Crops",
"the",
"image",
"using",
"specified",
"parameters"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L186-L224 | train |
|
imbo/imboclient-js | lib/url/imageurl.js | function(options) {
var params = [];
if (options.width) {
params.push('width=' + toInt(options.width));
}
if (options.height) {
params.push('height=' + toInt(options.height));
}
if (!params.length) {
throw new Error('width and/or height needs to be specified');
}
return this.append('maxSize:' + params.join(','));
} | javascript | function(options) {
var params = [];
if (options.width) {
params.push('width=' + toInt(options.width));
}
if (options.height) {
params.push('height=' + toInt(options.height));
}
if (!params.length) {
throw new Error('width and/or height needs to be specified');
}
return this.append('maxSize:' + params.join(','));
} | [
"function",
"(",
"options",
")",
"{",
"var",
"params",
"=",
"[",
"]",
";",
"if",
"(",
"options",
".",
"width",
")",
"{",
"params",
".",
"push",
"(",
"'width='",
"+",
"toInt",
"(",
"options",
".",
"width",
")",
")",
";",
"}",
"if",
"(",
"options",
".",
"height",
")",
"{",
"params",
".",
"push",
"(",
"'height='",
"+",
"toInt",
"(",
"options",
".",
"height",
")",
")",
";",
"}",
"if",
"(",
"!",
"params",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'width and/or height needs to be specified'",
")",
";",
"}",
"return",
"this",
".",
"append",
"(",
"'maxSize:'",
"+",
"params",
".",
"join",
"(",
"','",
")",
")",
";",
"}"
] | Resize the image to be at most the size specified while still preserving
the aspect ratio. If the image is smaller than the given size, the image
remains unchanged
@param {Object} options
@param {Number} [options.width] Max width of the image
@param {Number} [options.height] Max height of the image
@return {Imbo.ImageUrl} | [
"Resize",
"the",
"image",
"to",
"be",
"at",
"most",
"the",
"size",
"specified",
"while",
"still",
"preserving",
"the",
"aspect",
"ratio",
".",
"If",
"the",
"image",
"is",
"smaller",
"than",
"the",
"given",
"size",
"the",
"image",
"remains",
"unchanged"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L263-L279 | train |
|
imbo/imboclient-js | lib/url/imageurl.js | function(options) {
if (!options || isNaN(options.angle)) {
throw new Error('angle needs to be specified');
}
var bg = (options.bg || '000000').replace(/^#/, '');
return this.append('rotate:angle=' + options.angle + ',bg=' + bg);
} | javascript | function(options) {
if (!options || isNaN(options.angle)) {
throw new Error('angle needs to be specified');
}
var bg = (options.bg || '000000').replace(/^#/, '');
return this.append('rotate:angle=' + options.angle + ',bg=' + bg);
} | [
"function",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"options",
"||",
"isNaN",
"(",
"options",
".",
"angle",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'angle needs to be specified'",
")",
";",
"}",
"var",
"bg",
"=",
"(",
"options",
".",
"bg",
"||",
"'000000'",
")",
".",
"replace",
"(",
"/",
"^#",
"/",
",",
"''",
")",
";",
"return",
"this",
".",
"append",
"(",
"'rotate:angle='",
"+",
"options",
".",
"angle",
"+",
"',bg='",
"+",
"bg",
")",
";",
"}"
] | Rotate the image by the specified angle
@param {Object} options
@param {Number} options.angle Angle to rotate by
@param {String} [options.bg] Background color of image, in hex-format
@return {Imbo.ImageUrl} | [
"Rotate",
"the",
"image",
"by",
"the",
"specified",
"angle"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L357-L364 | train |
|
imbo/imboclient-js | lib/url/imageurl.js | function(options) {
var params = [],
opts = options || {},
transform = 'sharpen';
if (opts.preset) {
params.push('preset=' + opts.preset);
}
if (typeof opts.radius !== 'undefined') {
params.push('radius=' + opts.radius);
}
if (typeof opts.sigma !== 'undefined') {
params.push('sigma=' + opts.sigma);
}
if (typeof opts.gain !== 'undefined') {
params.push('gain=' + opts.gain);
}
if (typeof opts.threshold !== 'undefined') {
params.push('threshold=' + opts.threshold);
}
if (params.length) {
transform += ':' + params.join(',');
}
return this.append(transform);
} | javascript | function(options) {
var params = [],
opts = options || {},
transform = 'sharpen';
if (opts.preset) {
params.push('preset=' + opts.preset);
}
if (typeof opts.radius !== 'undefined') {
params.push('radius=' + opts.radius);
}
if (typeof opts.sigma !== 'undefined') {
params.push('sigma=' + opts.sigma);
}
if (typeof opts.gain !== 'undefined') {
params.push('gain=' + opts.gain);
}
if (typeof opts.threshold !== 'undefined') {
params.push('threshold=' + opts.threshold);
}
if (params.length) {
transform += ':' + params.join(',');
}
return this.append(transform);
} | [
"function",
"(",
"options",
")",
"{",
"var",
"params",
"=",
"[",
"]",
",",
"opts",
"=",
"options",
"||",
"{",
"}",
",",
"transform",
"=",
"'sharpen'",
";",
"if",
"(",
"opts",
".",
"preset",
")",
"{",
"params",
".",
"push",
"(",
"'preset='",
"+",
"opts",
".",
"preset",
")",
";",
"}",
"if",
"(",
"typeof",
"opts",
".",
"radius",
"!==",
"'undefined'",
")",
"{",
"params",
".",
"push",
"(",
"'radius='",
"+",
"opts",
".",
"radius",
")",
";",
"}",
"if",
"(",
"typeof",
"opts",
".",
"sigma",
"!==",
"'undefined'",
")",
"{",
"params",
".",
"push",
"(",
"'sigma='",
"+",
"opts",
".",
"sigma",
")",
";",
"}",
"if",
"(",
"typeof",
"opts",
".",
"gain",
"!==",
"'undefined'",
")",
"{",
"params",
".",
"push",
"(",
"'gain='",
"+",
"opts",
".",
"gain",
")",
";",
"}",
"if",
"(",
"typeof",
"opts",
".",
"threshold",
"!==",
"'undefined'",
")",
"{",
"params",
".",
"push",
"(",
"'threshold='",
"+",
"opts",
".",
"threshold",
")",
";",
"}",
"if",
"(",
"params",
".",
"length",
")",
"{",
"transform",
"+=",
"':'",
"+",
"params",
".",
"join",
"(",
"','",
")",
";",
"}",
"return",
"this",
".",
"append",
"(",
"transform",
")",
";",
"}"
] | Sharpen the image
@param {Object} [options]
@param {String} [options.preset] Name of a defined preset to use
@param {Number} [options.radius=2] Radius of the Gaussian operator in pixels
@param {Number} [options.sigma=1] Standard deviation of the Gaussian, in pixels
@param {Number} [options.gain=1] Percentage of difference between original and blurred image
that is added back into the original
@param {Number} [options.threshold=0.05] Threshold in pixels needed to apply the difference gain
@return {Imbo.ImageUrl} | [
"Sharpen",
"the",
"image"
] | 809dcc489528dca9d67f49b03b612a99704339d0 | https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L390-L420 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.