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 |
---|---|---|---|---|---|---|---|---|---|---|---|
creationix/git-pack-codec | decode.js | emitObject | function emitObject() {
var item = {
type: types[type],
size: length,
body: bops.join(parts),
offset: start
};
if (ref) item.ref = ref;
parts.length = 0;
start = 0;
offset = 0;
type = 0;
length = 0;
ref = null;
emit(item);
} | javascript | function emitObject() {
var item = {
type: types[type],
size: length,
body: bops.join(parts),
offset: start
};
if (ref) item.ref = ref;
parts.length = 0;
start = 0;
offset = 0;
type = 0;
length = 0;
ref = null;
emit(item);
} | [
"function",
"emitObject",
"(",
")",
"{",
"var",
"item",
"=",
"{",
"type",
":",
"types",
"[",
"type",
"]",
",",
"size",
":",
"length",
",",
"body",
":",
"bops",
".",
"join",
"(",
"parts",
")",
",",
"offset",
":",
"start",
"}",
";",
"if",
"(",
"ref",
")",
"item",
".",
"ref",
"=",
"ref",
";",
"parts",
".",
"length",
"=",
"0",
";",
"start",
"=",
"0",
";",
"offset",
"=",
"0",
";",
"type",
"=",
"0",
";",
"length",
"=",
"0",
";",
"ref",
"=",
"null",
";",
"emit",
"(",
"item",
")",
";",
"}"
]
| Common helper for emitting all three object shapes | [
"Common",
"helper",
"for",
"emitting",
"all",
"three",
"object",
"shapes"
]
| bf14e63755795dc5d15f7f68b68bbc312a114ef2 | https://github.com/creationix/git-pack-codec/blob/bf14e63755795dc5d15f7f68b68bbc312a114ef2/decode.js#L149-L164 | train |
creationix/git-pack-codec | decode.js | $body | function $body(byte, i, chunk) {
if (inf.write(byte)) return $body;
var buf = inf.flush();
inf.recycle();
if (buf.length) {
parts.push(buf);
}
emitObject();
// If this was all the objects, start calculating the sha1sum
if (--num) return $header;
sha1sum.update(bops.subarray(chunk, 0, i + 1));
return $checksum;
} | javascript | function $body(byte, i, chunk) {
if (inf.write(byte)) return $body;
var buf = inf.flush();
inf.recycle();
if (buf.length) {
parts.push(buf);
}
emitObject();
// If this was all the objects, start calculating the sha1sum
if (--num) return $header;
sha1sum.update(bops.subarray(chunk, 0, i + 1));
return $checksum;
} | [
"function",
"$body",
"(",
"byte",
",",
"i",
",",
"chunk",
")",
"{",
"if",
"(",
"inf",
".",
"write",
"(",
"byte",
")",
")",
"return",
"$body",
";",
"var",
"buf",
"=",
"inf",
".",
"flush",
"(",
")",
";",
"inf",
".",
"recycle",
"(",
")",
";",
"if",
"(",
"buf",
".",
"length",
")",
"{",
"parts",
".",
"push",
"(",
"buf",
")",
";",
"}",
"emitObject",
"(",
")",
";",
"if",
"(",
"--",
"num",
")",
"return",
"$header",
";",
"sha1sum",
".",
"update",
"(",
"bops",
".",
"subarray",
"(",
"chunk",
",",
"0",
",",
"i",
"+",
"1",
")",
")",
";",
"return",
"$checksum",
";",
"}"
]
| Feed the deflated code to the inflate engine | [
"Feed",
"the",
"deflated",
"code",
"to",
"the",
"inflate",
"engine"
]
| bf14e63755795dc5d15f7f68b68bbc312a114ef2 | https://github.com/creationix/git-pack-codec/blob/bf14e63755795dc5d15f7f68b68bbc312a114ef2/decode.js#L167-L179 | train |
pierrec/node-atok | lib/subrule.js | typeOf | function typeOf (rule) {
var ruleType = typeof rule
return ruleType === 'function'
? ruleType
: ruleType !== 'object'
? (rule.length === 0
? 'noop'
: (rule === 0
? 'zero'
: ruleType
)
)
: Buffer.isBuffer(rule)
? 'buffer'
: !isArray(rule)
? ((has(rule, 'start') && has(rule, 'end')
? 'range'
: has(rule, 'start')
? 'rangestart'
: has(rule, 'end')
? 'rangeend'
: has(rule, 'firstOf')
? (( (isArray(rule.firstOf) && sameTypeArray(rule.firstOf) )
|| typeof rule.firstOf === 'string'
)
&& rule.firstOf.length > 1
)
? 'firstof'
: 'invalid firstof'
: 'invalid'
)
+ '_object'
)
: !sameTypeArray(rule)
? 'multi types array'
: ((Buffer.isBuffer( rule[0] )
? 'buffer'
: typeof rule[0]
)
+ '_array'
)
} | javascript | function typeOf (rule) {
var ruleType = typeof rule
return ruleType === 'function'
? ruleType
: ruleType !== 'object'
? (rule.length === 0
? 'noop'
: (rule === 0
? 'zero'
: ruleType
)
)
: Buffer.isBuffer(rule)
? 'buffer'
: !isArray(rule)
? ((has(rule, 'start') && has(rule, 'end')
? 'range'
: has(rule, 'start')
? 'rangestart'
: has(rule, 'end')
? 'rangeend'
: has(rule, 'firstOf')
? (( (isArray(rule.firstOf) && sameTypeArray(rule.firstOf) )
|| typeof rule.firstOf === 'string'
)
&& rule.firstOf.length > 1
)
? 'firstof'
: 'invalid firstof'
: 'invalid'
)
+ '_object'
)
: !sameTypeArray(rule)
? 'multi types array'
: ((Buffer.isBuffer( rule[0] )
? 'buffer'
: typeof rule[0]
)
+ '_array'
)
} | [
"function",
"typeOf",
"(",
"rule",
")",
"{",
"var",
"ruleType",
"=",
"typeof",
"rule",
"return",
"ruleType",
"===",
"'function'",
"?",
"ruleType",
":",
"ruleType",
"!==",
"'object'",
"?",
"(",
"rule",
".",
"length",
"===",
"0",
"?",
"'noop'",
":",
"(",
"rule",
"===",
"0",
"?",
"'zero'",
":",
"ruleType",
")",
")",
":",
"Buffer",
".",
"isBuffer",
"(",
"rule",
")",
"?",
"'buffer'",
":",
"!",
"isArray",
"(",
"rule",
")",
"?",
"(",
"(",
"has",
"(",
"rule",
",",
"'start'",
")",
"&&",
"has",
"(",
"rule",
",",
"'end'",
")",
"?",
"'range'",
":",
"has",
"(",
"rule",
",",
"'start'",
")",
"?",
"'rangestart'",
":",
"has",
"(",
"rule",
",",
"'end'",
")",
"?",
"'rangeend'",
":",
"has",
"(",
"rule",
",",
"'firstOf'",
")",
"?",
"(",
"(",
"(",
"isArray",
"(",
"rule",
".",
"firstOf",
")",
"&&",
"sameTypeArray",
"(",
"rule",
".",
"firstOf",
")",
")",
"||",
"typeof",
"rule",
".",
"firstOf",
"===",
"'string'",
")",
"&&",
"rule",
".",
"firstOf",
".",
"length",
">",
"1",
")",
"?",
"'firstof'",
":",
"'invalid firstof'",
":",
"'invalid'",
")",
"+",
"'_object'",
")",
":",
"!",
"sameTypeArray",
"(",
"rule",
")",
"?",
"'multi types array'",
":",
"(",
"(",
"Buffer",
".",
"isBuffer",
"(",
"rule",
"[",
"0",
"]",
")",
"?",
"'buffer'",
":",
"typeof",
"rule",
"[",
"0",
"]",
")",
"+",
"'_array'",
")",
"}"
]
| Return the type of an item
@param {...} item to check
@return {String} type | [
"Return",
"the",
"type",
"of",
"an",
"item"
]
| abe139e7fa8c092d87e528289b6abd9083df2323 | https://github.com/pierrec/node-atok/blob/abe139e7fa8c092d87e528289b6abd9083df2323/lib/subrule.js#L603-L645 | train |
hillscottc/nostra | src/sentence_mgr.js | encounter | function encounter(mood) {
//Sentence 1: The meeting
const familiar_people = wordLib.getWords("familiar_people");
const strange_people = wordLib.getWords("strange_people");
const locations = wordLib.getWords("locations");
const person = nu.chooseFrom(familiar_people.concat(strange_people));
let location = nu.chooseFrom(wordLib.getWords("locations"));
const preposition = location[0];
location = location[1];
const s1 = `You may meet ${person} ${preposition} ${location}.`;
// Sentence 2: The discussion
let discussions = wordLib.getWords("neutral_discussions");
discussions.concat(wordLib.getWords(mood + "_discussions"));
const feeling_nouns = wordLib.getWords(mood + "_feeling_nouns");
const emotive_nouns = wordLib.getWords(mood + "_emotive_nouns");
const conversation_topics = wordLib.getWords("conversation_topics");
const discussion = nu.chooseFrom(discussions);
const rnum = Math.floor(Math.random() * 10);
let feeling;
if (rnum <- 5) {
feeling = nu.chooseFrom(feeling_nouns);
feeling = "feelings of " + feeling;
} else {
feeling = nu.chooseFrom(emotive_nouns);
}
const topic = nu.chooseFrom(conversation_topics);
let s2 = `${nu.an(discussion)} about ${topic} may lead to ${feeling}.`;
s2 = nu.sentenceCase(s2);
return `${s1} ${s2}`;
} | javascript | function encounter(mood) {
//Sentence 1: The meeting
const familiar_people = wordLib.getWords("familiar_people");
const strange_people = wordLib.getWords("strange_people");
const locations = wordLib.getWords("locations");
const person = nu.chooseFrom(familiar_people.concat(strange_people));
let location = nu.chooseFrom(wordLib.getWords("locations"));
const preposition = location[0];
location = location[1];
const s1 = `You may meet ${person} ${preposition} ${location}.`;
// Sentence 2: The discussion
let discussions = wordLib.getWords("neutral_discussions");
discussions.concat(wordLib.getWords(mood + "_discussions"));
const feeling_nouns = wordLib.getWords(mood + "_feeling_nouns");
const emotive_nouns = wordLib.getWords(mood + "_emotive_nouns");
const conversation_topics = wordLib.getWords("conversation_topics");
const discussion = nu.chooseFrom(discussions);
const rnum = Math.floor(Math.random() * 10);
let feeling;
if (rnum <- 5) {
feeling = nu.chooseFrom(feeling_nouns);
feeling = "feelings of " + feeling;
} else {
feeling = nu.chooseFrom(emotive_nouns);
}
const topic = nu.chooseFrom(conversation_topics);
let s2 = `${nu.an(discussion)} about ${topic} may lead to ${feeling}.`;
s2 = nu.sentenceCase(s2);
return `${s1} ${s2}`;
} | [
"function",
"encounter",
"(",
"mood",
")",
"{",
"const",
"familiar_people",
"=",
"wordLib",
".",
"getWords",
"(",
"\"familiar_people\"",
")",
";",
"const",
"strange_people",
"=",
"wordLib",
".",
"getWords",
"(",
"\"strange_people\"",
")",
";",
"const",
"locations",
"=",
"wordLib",
".",
"getWords",
"(",
"\"locations\"",
")",
";",
"const",
"person",
"=",
"nu",
".",
"chooseFrom",
"(",
"familiar_people",
".",
"concat",
"(",
"strange_people",
")",
")",
";",
"let",
"location",
"=",
"nu",
".",
"chooseFrom",
"(",
"wordLib",
".",
"getWords",
"(",
"\"locations\"",
")",
")",
";",
"const",
"preposition",
"=",
"location",
"[",
"0",
"]",
";",
"location",
"=",
"location",
"[",
"1",
"]",
";",
"const",
"s1",
"=",
"`",
"${",
"person",
"}",
"${",
"preposition",
"}",
"${",
"location",
"}",
"`",
";",
"let",
"discussions",
"=",
"wordLib",
".",
"getWords",
"(",
"\"neutral_discussions\"",
")",
";",
"discussions",
".",
"concat",
"(",
"wordLib",
".",
"getWords",
"(",
"mood",
"+",
"\"_discussions\"",
")",
")",
";",
"const",
"feeling_nouns",
"=",
"wordLib",
".",
"getWords",
"(",
"mood",
"+",
"\"_feeling_nouns\"",
")",
";",
"const",
"emotive_nouns",
"=",
"wordLib",
".",
"getWords",
"(",
"mood",
"+",
"\"_emotive_nouns\"",
")",
";",
"const",
"conversation_topics",
"=",
"wordLib",
".",
"getWords",
"(",
"\"conversation_topics\"",
")",
";",
"const",
"discussion",
"=",
"nu",
".",
"chooseFrom",
"(",
"discussions",
")",
";",
"const",
"rnum",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"10",
")",
";",
"let",
"feeling",
";",
"if",
"(",
"rnum",
"<",
"-",
"5",
")",
"{",
"feeling",
"=",
"nu",
".",
"chooseFrom",
"(",
"feeling_nouns",
")",
";",
"feeling",
"=",
"\"feelings of \"",
"+",
"feeling",
";",
"}",
"else",
"{",
"feeling",
"=",
"nu",
".",
"chooseFrom",
"(",
"emotive_nouns",
")",
";",
"}",
"const",
"topic",
"=",
"nu",
".",
"chooseFrom",
"(",
"conversation_topics",
")",
";",
"let",
"s2",
"=",
"`",
"${",
"nu",
".",
"an",
"(",
"discussion",
")",
"}",
"${",
"topic",
"}",
"${",
"feeling",
"}",
"`",
";",
"s2",
"=",
"nu",
".",
"sentenceCase",
"(",
"s2",
")",
";",
"return",
"`",
"${",
"s1",
"}",
"${",
"s2",
"}",
"`",
";",
"}"
]
| Generate a few sentences about a meeting with another person.
@param mood | [
"Generate",
"a",
"few",
"sentences",
"about",
"a",
"meeting",
"with",
"another",
"person",
"."
]
| 1801c8e19f7fab91dd29fea07195789d41624915 | https://github.com/hillscottc/nostra/blob/1801c8e19f7fab91dd29fea07195789d41624915/src/sentence_mgr.js#L38-L76 | train |
hillscottc/nostra | src/sentence_mgr.js | feeling | function feeling(mood) {
const rnum = Math.floor(Math.random() * 10);
const adjectives = wordLib.getWords(mood + "_feeling_adjs");
//var degrees = getWords("neutral_degrees") + getWords(mood + "_degrees");
const degrees = wordLib.getWords("neutral_degrees").concat(wordLib.getWords(mood + "_degrees"));
const adj = nu.ingToEd(nu.chooseFrom(adjectives));
const degree = nu.chooseFrom(degrees);
let ending;
if (mood === "good") {
ending = wordLib.positiveIntensify();
} else {
ending = wordLib.consolation();
}
const exciting = (mood === "GOOD" && rnum <= 5);
const are = nu.chooseFrom([" are", "'re"]);
const sentence = `You${are} feeling ${degree} ${adj}${ending}`;
return nu.sentenceCase(sentence, exciting);
} | javascript | function feeling(mood) {
const rnum = Math.floor(Math.random() * 10);
const adjectives = wordLib.getWords(mood + "_feeling_adjs");
//var degrees = getWords("neutral_degrees") + getWords(mood + "_degrees");
const degrees = wordLib.getWords("neutral_degrees").concat(wordLib.getWords(mood + "_degrees"));
const adj = nu.ingToEd(nu.chooseFrom(adjectives));
const degree = nu.chooseFrom(degrees);
let ending;
if (mood === "good") {
ending = wordLib.positiveIntensify();
} else {
ending = wordLib.consolation();
}
const exciting = (mood === "GOOD" && rnum <= 5);
const are = nu.chooseFrom([" are", "'re"]);
const sentence = `You${are} feeling ${degree} ${adj}${ending}`;
return nu.sentenceCase(sentence, exciting);
} | [
"function",
"feeling",
"(",
"mood",
")",
"{",
"const",
"rnum",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"random",
"(",
")",
"*",
"10",
")",
";",
"const",
"adjectives",
"=",
"wordLib",
".",
"getWords",
"(",
"mood",
"+",
"\"_feeling_adjs\"",
")",
";",
"const",
"degrees",
"=",
"wordLib",
".",
"getWords",
"(",
"\"neutral_degrees\"",
")",
".",
"concat",
"(",
"wordLib",
".",
"getWords",
"(",
"mood",
"+",
"\"_degrees\"",
")",
")",
";",
"const",
"adj",
"=",
"nu",
".",
"ingToEd",
"(",
"nu",
".",
"chooseFrom",
"(",
"adjectives",
")",
")",
";",
"const",
"degree",
"=",
"nu",
".",
"chooseFrom",
"(",
"degrees",
")",
";",
"let",
"ending",
";",
"if",
"(",
"mood",
"===",
"\"good\"",
")",
"{",
"ending",
"=",
"wordLib",
".",
"positiveIntensify",
"(",
")",
";",
"}",
"else",
"{",
"ending",
"=",
"wordLib",
".",
"consolation",
"(",
")",
";",
"}",
"const",
"exciting",
"=",
"(",
"mood",
"===",
"\"GOOD\"",
"&&",
"rnum",
"<=",
"5",
")",
";",
"const",
"are",
"=",
"nu",
".",
"chooseFrom",
"(",
"[",
"\" are\"",
",",
"\"'re\"",
"]",
")",
";",
"const",
"sentence",
"=",
"`",
"${",
"are",
"}",
"${",
"degree",
"}",
"${",
"adj",
"}",
"${",
"ending",
"}",
"`",
";",
"return",
"nu",
".",
"sentenceCase",
"(",
"sentence",
",",
"exciting",
")",
";",
"}"
]
| A mood-based feeling
@param mood
@returns {*} | [
"A",
"mood",
"-",
"based",
"feeling"
]
| 1801c8e19f7fab91dd29fea07195789d41624915 | https://github.com/hillscottc/nostra/blob/1801c8e19f7fab91dd29fea07195789d41624915/src/sentence_mgr.js#L83-L101 | train |
angeloocana/joj-core | dist-esnext/Move.js | getGameAfterMove | function getGameAfterMove(game, move, backMove = false) {
if (!backMove && canNotMove(game, move))
return game;
const board = getBoardAfterMove(game.board, move);
return {
players: game.players,
board,
score: Score.getScore(game.board),
moves: backMove ? game.moves : game.moves.concat(getMoveXAndY(move))
};
} | javascript | function getGameAfterMove(game, move, backMove = false) {
if (!backMove && canNotMove(game, move))
return game;
const board = getBoardAfterMove(game.board, move);
return {
players: game.players,
board,
score: Score.getScore(game.board),
moves: backMove ? game.moves : game.moves.concat(getMoveXAndY(move))
};
} | [
"function",
"getGameAfterMove",
"(",
"game",
",",
"move",
",",
"backMove",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"backMove",
"&&",
"canNotMove",
"(",
"game",
",",
"move",
")",
")",
"return",
"game",
";",
"const",
"board",
"=",
"getBoardAfterMove",
"(",
"game",
".",
"board",
",",
"move",
")",
";",
"return",
"{",
"players",
":",
"game",
".",
"players",
",",
"board",
",",
"score",
":",
"Score",
".",
"getScore",
"(",
"game",
".",
"board",
")",
",",
"moves",
":",
"backMove",
"?",
"game",
".",
"moves",
":",
"game",
".",
"moves",
".",
"concat",
"(",
"getMoveXAndY",
"(",
"move",
")",
")",
"}",
";",
"}"
]
| Takes game and move then returns new game after move.
Updates:
- .board (It cleans board, set new positions and move breadcrumb)
- .score
- .moves (add new move if valid and it is not backMove) | [
"Takes",
"game",
"and",
"move",
"then",
"returns",
"new",
"game",
"after",
"move",
"."
]
| 14bc7801c004271cefafff6cc0abb0c3173c805a | https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist-esnext/Move.js#L69-L79 | train |
angeloocana/joj-core | dist-esnext/Move.js | getGameBeforeLastMove | function getGameBeforeLastMove(game) {
// $Fix I do NOT know if it is the best way to make game immutable.
game = Object.assign({}, game);
let lastMove = game.moves.pop();
if (lastMove)
game = getGameAfterMove(game, getBackMove(lastMove), true);
if (Game.getPlayerTurn(game).isAi) {
lastMove = game.moves.pop();
if (lastMove) {
game = getGameAfterMove(game, getBackMove(lastMove), true);
}
}
return game;
} | javascript | function getGameBeforeLastMove(game) {
// $Fix I do NOT know if it is the best way to make game immutable.
game = Object.assign({}, game);
let lastMove = game.moves.pop();
if (lastMove)
game = getGameAfterMove(game, getBackMove(lastMove), true);
if (Game.getPlayerTurn(game).isAi) {
lastMove = game.moves.pop();
if (lastMove) {
game = getGameAfterMove(game, getBackMove(lastMove), true);
}
}
return game;
} | [
"function",
"getGameBeforeLastMove",
"(",
"game",
")",
"{",
"game",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"game",
")",
";",
"let",
"lastMove",
"=",
"game",
".",
"moves",
".",
"pop",
"(",
")",
";",
"if",
"(",
"lastMove",
")",
"game",
"=",
"getGameAfterMove",
"(",
"game",
",",
"getBackMove",
"(",
"lastMove",
")",
",",
"true",
")",
";",
"if",
"(",
"Game",
".",
"getPlayerTurn",
"(",
"game",
")",
".",
"isAi",
")",
"{",
"lastMove",
"=",
"game",
".",
"moves",
".",
"pop",
"(",
")",
";",
"if",
"(",
"lastMove",
")",
"{",
"game",
"=",
"getGameAfterMove",
"(",
"game",
",",
"getBackMove",
"(",
"lastMove",
")",
",",
"true",
")",
";",
"}",
"}",
"return",
"game",
";",
"}"
]
| Get game before last move,
if playing vs Ai rollback Ai move too. | [
"Get",
"game",
"before",
"last",
"move",
"if",
"playing",
"vs",
"Ai",
"rollback",
"Ai",
"move",
"too",
"."
]
| 14bc7801c004271cefafff6cc0abb0c3173c805a | https://github.com/angeloocana/joj-core/blob/14bc7801c004271cefafff6cc0abb0c3173c805a/dist-esnext/Move.js#L84-L97 | train |
evaisse/wiresrc | lib/detect.js | function (config) {
/**
* The iterator function, which is called on each component.
*
* @param {string} version the version of the component
* @param {string} component the name of the component
* @return {undefined}
*/
return function (version, component) {
var dep = config.get('global-dependencies').get(component) || {
main: '',
type: '',
name: '',
dependencies: {}
};
console.log(version, component);
var componentConfigFile = findComponentConfigFile(config, component);
var warnings = config.get('warnings');
var overrides = config.get('overrides');
if (overrides && overrides[component]) {
if (overrides[component].dependencies) {
componentConfigFile.dependencies = overrides[component].dependencies;
}
if (overrides[component].main) {
componentConfigFile.main = overrides[component].main;
}
}
var mains = findMainFiles(config, component, componentConfigFile);
var fileTypes = _.chain(mains).map(path.extname).unique().value();
dep.main = mains;
dep.type = fileTypes;
dep.name = componentConfigFile.name;
var depIsExcluded = _.find(config.get('exclude'), function (pattern) {
return path.join(config.get('bower-directory'), component).match(pattern);
});
if (dep.main.length === 0 && !depIsExcluded) {
// can't find the main file. this config file is useless!
warnings.push(component + ' was not injected in your file.');
warnings.push(
'Please go take a look in "' + path.join(config.get('bower-directory'), component) + '" for the file you need, then manually include it in your file.');
config.set('warnings', warnings);
return;
}
if (componentConfigFile.dependencies) {
dep.dependencies = componentConfigFile.dependencies;
_.each(componentConfigFile.dependencies, gatherInfo(config));
}
config.get('global-dependencies').set(component, dep);
};
} | javascript | function (config) {
/**
* The iterator function, which is called on each component.
*
* @param {string} version the version of the component
* @param {string} component the name of the component
* @return {undefined}
*/
return function (version, component) {
var dep = config.get('global-dependencies').get(component) || {
main: '',
type: '',
name: '',
dependencies: {}
};
console.log(version, component);
var componentConfigFile = findComponentConfigFile(config, component);
var warnings = config.get('warnings');
var overrides = config.get('overrides');
if (overrides && overrides[component]) {
if (overrides[component].dependencies) {
componentConfigFile.dependencies = overrides[component].dependencies;
}
if (overrides[component].main) {
componentConfigFile.main = overrides[component].main;
}
}
var mains = findMainFiles(config, component, componentConfigFile);
var fileTypes = _.chain(mains).map(path.extname).unique().value();
dep.main = mains;
dep.type = fileTypes;
dep.name = componentConfigFile.name;
var depIsExcluded = _.find(config.get('exclude'), function (pattern) {
return path.join(config.get('bower-directory'), component).match(pattern);
});
if (dep.main.length === 0 && !depIsExcluded) {
// can't find the main file. this config file is useless!
warnings.push(component + ' was not injected in your file.');
warnings.push(
'Please go take a look in "' + path.join(config.get('bower-directory'), component) + '" for the file you need, then manually include it in your file.');
config.set('warnings', warnings);
return;
}
if (componentConfigFile.dependencies) {
dep.dependencies = componentConfigFile.dependencies;
_.each(componentConfigFile.dependencies, gatherInfo(config));
}
config.get('global-dependencies').set(component, dep);
};
} | [
"function",
"(",
"config",
")",
"{",
"return",
"function",
"(",
"version",
",",
"component",
")",
"{",
"var",
"dep",
"=",
"config",
".",
"get",
"(",
"'global-dependencies'",
")",
".",
"get",
"(",
"component",
")",
"||",
"{",
"main",
":",
"''",
",",
"type",
":",
"''",
",",
"name",
":",
"''",
",",
"dependencies",
":",
"{",
"}",
"}",
";",
"console",
".",
"log",
"(",
"version",
",",
"component",
")",
";",
"var",
"componentConfigFile",
"=",
"findComponentConfigFile",
"(",
"config",
",",
"component",
")",
";",
"var",
"warnings",
"=",
"config",
".",
"get",
"(",
"'warnings'",
")",
";",
"var",
"overrides",
"=",
"config",
".",
"get",
"(",
"'overrides'",
")",
";",
"if",
"(",
"overrides",
"&&",
"overrides",
"[",
"component",
"]",
")",
"{",
"if",
"(",
"overrides",
"[",
"component",
"]",
".",
"dependencies",
")",
"{",
"componentConfigFile",
".",
"dependencies",
"=",
"overrides",
"[",
"component",
"]",
".",
"dependencies",
";",
"}",
"if",
"(",
"overrides",
"[",
"component",
"]",
".",
"main",
")",
"{",
"componentConfigFile",
".",
"main",
"=",
"overrides",
"[",
"component",
"]",
".",
"main",
";",
"}",
"}",
"var",
"mains",
"=",
"findMainFiles",
"(",
"config",
",",
"component",
",",
"componentConfigFile",
")",
";",
"var",
"fileTypes",
"=",
"_",
".",
"chain",
"(",
"mains",
")",
".",
"map",
"(",
"path",
".",
"extname",
")",
".",
"unique",
"(",
")",
".",
"value",
"(",
")",
";",
"dep",
".",
"main",
"=",
"mains",
";",
"dep",
".",
"type",
"=",
"fileTypes",
";",
"dep",
".",
"name",
"=",
"componentConfigFile",
".",
"name",
";",
"var",
"depIsExcluded",
"=",
"_",
".",
"find",
"(",
"config",
".",
"get",
"(",
"'exclude'",
")",
",",
"function",
"(",
"pattern",
")",
"{",
"return",
"path",
".",
"join",
"(",
"config",
".",
"get",
"(",
"'bower-directory'",
")",
",",
"component",
")",
".",
"match",
"(",
"pattern",
")",
";",
"}",
")",
";",
"if",
"(",
"dep",
".",
"main",
".",
"length",
"===",
"0",
"&&",
"!",
"depIsExcluded",
")",
"{",
"warnings",
".",
"push",
"(",
"component",
"+",
"' was not injected in your file.'",
")",
";",
"warnings",
".",
"push",
"(",
"'Please go take a look in \"'",
"+",
"path",
".",
"join",
"(",
"config",
".",
"get",
"(",
"'bower-directory'",
")",
",",
"component",
")",
"+",
"'\" for the file you need, then manually include it in your file.'",
")",
";",
"config",
".",
"set",
"(",
"'warnings'",
",",
"warnings",
")",
";",
"return",
";",
"}",
"if",
"(",
"componentConfigFile",
".",
"dependencies",
")",
"{",
"dep",
".",
"dependencies",
"=",
"componentConfigFile",
".",
"dependencies",
";",
"_",
".",
"each",
"(",
"componentConfigFile",
".",
"dependencies",
",",
"gatherInfo",
"(",
"config",
")",
")",
";",
"}",
"config",
".",
"get",
"(",
"'global-dependencies'",
")",
".",
"set",
"(",
"component",
",",
"dep",
")",
";",
"}",
";",
"}"
]
| Store the information our prioritizer will need to determine rank.
@param {object} config the global configuration object
@return {function} the iterator function, called on every component | [
"Store",
"the",
"information",
"our",
"prioritizer",
"will",
"need",
"to",
"determine",
"rank",
"."
]
| 73b6e8b25bca095d665bf85478429996613f88a3 | https://github.com/evaisse/wiresrc/blob/73b6e8b25bca095d665bf85478429996613f88a3/lib/detect.js#L78-L140 | train |
|
evaisse/wiresrc | lib/detect.js | function (a, b) {
var aNeedsB = false;
var bNeedsA = false;
aNeedsB = Object.
keys(a.dependencies).
some(function (dependency) {
return dependency === b.name;
});
if (aNeedsB) {
return 1;
}
bNeedsA = Object.
keys(b.dependencies).
some(function (dependency) {
return dependency === a.name;
});
if (bNeedsA) {
return -1;
}
return 0;
} | javascript | function (a, b) {
var aNeedsB = false;
var bNeedsA = false;
aNeedsB = Object.
keys(a.dependencies).
some(function (dependency) {
return dependency === b.name;
});
if (aNeedsB) {
return 1;
}
bNeedsA = Object.
keys(b.dependencies).
some(function (dependency) {
return dependency === a.name;
});
if (bNeedsA) {
return -1;
}
return 0;
} | [
"function",
"(",
"a",
",",
"b",
")",
"{",
"var",
"aNeedsB",
"=",
"false",
";",
"var",
"bNeedsA",
"=",
"false",
";",
"aNeedsB",
"=",
"Object",
".",
"keys",
"(",
"a",
".",
"dependencies",
")",
".",
"some",
"(",
"function",
"(",
"dependency",
")",
"{",
"return",
"dependency",
"===",
"b",
".",
"name",
";",
"}",
")",
";",
"if",
"(",
"aNeedsB",
")",
"{",
"return",
"1",
";",
"}",
"bNeedsA",
"=",
"Object",
".",
"keys",
"(",
"b",
".",
"dependencies",
")",
".",
"some",
"(",
"function",
"(",
"dependency",
")",
"{",
"return",
"dependency",
"===",
"a",
".",
"name",
";",
"}",
")",
";",
"if",
"(",
"bNeedsA",
")",
"{",
"return",
"-",
"1",
";",
"}",
"return",
"0",
";",
"}"
]
| Compare two dependencies to determine priority.
@param {object} a dependency a
@param {object} b dependency b
@return {number} the priority of dependency a in comparison to dependency b | [
"Compare",
"two",
"dependencies",
"to",
"determine",
"priority",
"."
]
| 73b6e8b25bca095d665bf85478429996613f88a3 | https://github.com/evaisse/wiresrc/blob/73b6e8b25bca095d665bf85478429996613f88a3/lib/detect.js#L150-L175 | train |
|
evaisse/wiresrc | lib/detect.js | function (left, right) {
var result = [];
var leftIndex = 0;
var rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (dependencyComparator(left[leftIndex], right[rightIndex]) < 1) {
result.push(left[leftIndex++]);
} else {
result.push(right[rightIndex++]);
}
}
return result.
concat(left.slice(leftIndex)).
concat(right.slice(rightIndex));
} | javascript | function (left, right) {
var result = [];
var leftIndex = 0;
var rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (dependencyComparator(left[leftIndex], right[rightIndex]) < 1) {
result.push(left[leftIndex++]);
} else {
result.push(right[rightIndex++]);
}
}
return result.
concat(left.slice(leftIndex)).
concat(right.slice(rightIndex));
} | [
"function",
"(",
"left",
",",
"right",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"leftIndex",
"=",
"0",
";",
"var",
"rightIndex",
"=",
"0",
";",
"while",
"(",
"leftIndex",
"<",
"left",
".",
"length",
"&&",
"rightIndex",
"<",
"right",
".",
"length",
")",
"{",
"if",
"(",
"dependencyComparator",
"(",
"left",
"[",
"leftIndex",
"]",
",",
"right",
"[",
"rightIndex",
"]",
")",
"<",
"1",
")",
"{",
"result",
".",
"push",
"(",
"left",
"[",
"leftIndex",
"++",
"]",
")",
";",
"}",
"else",
"{",
"result",
".",
"push",
"(",
"right",
"[",
"rightIndex",
"++",
"]",
")",
";",
"}",
"}",
"return",
"result",
".",
"concat",
"(",
"left",
".",
"slice",
"(",
"leftIndex",
")",
")",
".",
"concat",
"(",
"right",
".",
"slice",
"(",
"rightIndex",
")",
")",
";",
"}"
]
| Take two arrays, sort based on their dependency relationship, then merge them
together.
@param {array} left
@param {array} right
@return {array} the sorted, merged array | [
"Take",
"two",
"arrays",
"sort",
"based",
"on",
"their",
"dependency",
"relationship",
"then",
"merge",
"them",
"together",
"."
]
| 73b6e8b25bca095d665bf85478429996613f88a3 | https://github.com/evaisse/wiresrc/blob/73b6e8b25bca095d665bf85478429996613f88a3/lib/detect.js#L186-L202 | train |
|
evaisse/wiresrc | lib/detect.js | function (items) {
if (items.length < 2) {
return items;
}
var middle = Math.floor(items.length / 2);
return merge(
mergeSort(items.slice(0, middle)),
mergeSort(items.slice(middle))
);
} | javascript | function (items) {
if (items.length < 2) {
return items;
}
var middle = Math.floor(items.length / 2);
return merge(
mergeSort(items.slice(0, middle)),
mergeSort(items.slice(middle))
);
} | [
"function",
"(",
"items",
")",
"{",
"if",
"(",
"items",
".",
"length",
"<",
"2",
")",
"{",
"return",
"items",
";",
"}",
"var",
"middle",
"=",
"Math",
".",
"floor",
"(",
"items",
".",
"length",
"/",
"2",
")",
";",
"return",
"merge",
"(",
"mergeSort",
"(",
"items",
".",
"slice",
"(",
"0",
",",
"middle",
")",
")",
",",
"mergeSort",
"(",
"items",
".",
"slice",
"(",
"middle",
")",
")",
")",
";",
"}"
]
| Take an array and slice it in halves, sorting each half along the way.
@param {array} items
@return {array} the sorted array | [
"Take",
"an",
"array",
"and",
"slice",
"it",
"in",
"halves",
"sorting",
"each",
"half",
"along",
"the",
"way",
"."
]
| 73b6e8b25bca095d665bf85478429996613f88a3 | https://github.com/evaisse/wiresrc/blob/73b6e8b25bca095d665bf85478429996613f88a3/lib/detect.js#L211-L222 | train |
|
evaisse/wiresrc | lib/detect.js | function (allDependencies, patterns) {
return _.transform(allDependencies, function (result, dependencies, fileType) {
result[fileType] = _.reject(dependencies, function (dependency) {
return _.find(patterns, function (pattern) {
return dependency.match(pattern);
});
});
});
} | javascript | function (allDependencies, patterns) {
return _.transform(allDependencies, function (result, dependencies, fileType) {
result[fileType] = _.reject(dependencies, function (dependency) {
return _.find(patterns, function (pattern) {
return dependency.match(pattern);
});
});
});
} | [
"function",
"(",
"allDependencies",
",",
"patterns",
")",
"{",
"return",
"_",
".",
"transform",
"(",
"allDependencies",
",",
"function",
"(",
"result",
",",
"dependencies",
",",
"fileType",
")",
"{",
"result",
"[",
"fileType",
"]",
"=",
"_",
".",
"reject",
"(",
"dependencies",
",",
"function",
"(",
"dependency",
")",
"{",
"return",
"_",
".",
"find",
"(",
"patterns",
",",
"function",
"(",
"pattern",
")",
"{",
"return",
"dependency",
".",
"match",
"(",
"pattern",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Excludes dependencies that match any of the patterns.
@param {array} allDependencies array of dependencies to filter
@param {array} patterns array of patterns to match against
@return {array} items that don't match any of the patterns | [
"Excludes",
"dependencies",
"that",
"match",
"any",
"of",
"the",
"patterns",
"."
]
| 73b6e8b25bca095d665bf85478429996613f88a3 | https://github.com/evaisse/wiresrc/blob/73b6e8b25bca095d665bf85478429996613f88a3/lib/detect.js#L279-L287 | train |
|
tether/methodd | index.js | proxy | function proxy (original, routes) {
return new Proxy(original, {
get(target, key, receiver) {
const method = target[key]
if (method) return method
else return function (path, ...args) {
const cb = args[0]
if (typeof cb === 'function') {
original.add(key, path, cb)
} else {
const fn = routes[key]
return fn && fn.exec(path, ...args)
}
}
}
})
} | javascript | function proxy (original, routes) {
return new Proxy(original, {
get(target, key, receiver) {
const method = target[key]
if (method) return method
else return function (path, ...args) {
const cb = args[0]
if (typeof cb === 'function') {
original.add(key, path, cb)
} else {
const fn = routes[key]
return fn && fn.exec(path, ...args)
}
}
}
})
} | [
"function",
"proxy",
"(",
"original",
",",
"routes",
")",
"{",
"return",
"new",
"Proxy",
"(",
"original",
",",
"{",
"get",
"(",
"target",
",",
"key",
",",
"receiver",
")",
"{",
"const",
"method",
"=",
"target",
"[",
"key",
"]",
"if",
"(",
"method",
")",
"return",
"method",
"else",
"return",
"function",
"(",
"path",
",",
"...",
"args",
")",
"{",
"const",
"cb",
"=",
"args",
"[",
"0",
"]",
"if",
"(",
"typeof",
"cb",
"===",
"'function'",
")",
"{",
"original",
".",
"add",
"(",
"key",
",",
"path",
",",
"cb",
")",
"}",
"else",
"{",
"const",
"fn",
"=",
"routes",
"[",
"key",
"]",
"return",
"fn",
"&&",
"fn",
".",
"exec",
"(",
"path",
",",
"...",
"args",
")",
"}",
"}",
"}",
"}",
")",
"}"
]
| Proxy function with router.
@param {Function} original
@param {Object} routes
@api private | [
"Proxy",
"function",
"with",
"router",
"."
]
| 1604ffb43e28742003ea74c080d936e5a4f203fd | https://github.com/tether/methodd/blob/1604ffb43e28742003ea74c080d936e5a4f203fd/index.js#L98-L114 | train |
YusukeHirao/sceg | lib/fn/gen.js | gen | function gen(path) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var config = assignConfig_1.default(option, path);
return globElements_1.default(config).then(readElements_1.default(config)).then(optimize_1.default()).then(render_1.default(config));
} | javascript | function gen(path) {
var option = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var config = assignConfig_1.default(option, path);
return globElements_1.default(config).then(readElements_1.default(config)).then(optimize_1.default()).then(render_1.default(config));
} | [
"function",
"gen",
"(",
"path",
")",
"{",
"var",
"option",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"{",
"}",
";",
"var",
"config",
"=",
"assignConfig_1",
".",
"default",
"(",
"option",
",",
"path",
")",
";",
"return",
"globElements_1",
".",
"default",
"(",
"config",
")",
".",
"then",
"(",
"readElements_1",
".",
"default",
"(",
"config",
")",
")",
".",
"then",
"(",
"optimize_1",
".",
"default",
"(",
")",
")",
".",
"then",
"(",
"render_1",
".",
"default",
"(",
"config",
")",
")",
";",
"}"
]
| Generate guide page from elements
@param path Paths of element files that glob pattern
@param option Optional configure
@return rendered HTML string | [
"Generate",
"guide",
"page",
"from",
"elements"
]
| 4cde1e56d48dd3b604cc2ddff36b2e9de3348771 | https://github.com/YusukeHirao/sceg/blob/4cde1e56d48dd3b604cc2ddff36b2e9de3348771/lib/fn/gen.js#L16-L21 | train |
oliversalzburg/strider-modern-extensions | lib/proxy.js | toStriderProxy | function toStriderProxy(instance) {
debug(`Proxying async plugin: ${instance.constructor.name}`);
const functionsInInstance = Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).filter(propertyName => {
return typeof instance[propertyName] === 'function' && propertyName !== 'constructor';
});
functionsInInstance.forEach(functionInInstance => {
instance[`${functionInInstance}Async`] = instance[functionInInstance];
instance[functionInInstance] = function () {
const args = Array.from(arguments);
const done = args.pop();
return instance[`${functionInInstance}Async`].apply(instance, args)
.then(result => done(null, result))
.catch(errors.ExtensionConfigurationError, error => {
debug(`Extension configuration error:${error.message}` || error.info);
return done(error);
})
.catch(error => done(error));
};
Object.defineProperty(instance[functionInInstance], 'length', {
value: instance[`${functionInInstance}Async`].length
});
});
return instance;
} | javascript | function toStriderProxy(instance) {
debug(`Proxying async plugin: ${instance.constructor.name}`);
const functionsInInstance = Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).filter(propertyName => {
return typeof instance[propertyName] === 'function' && propertyName !== 'constructor';
});
functionsInInstance.forEach(functionInInstance => {
instance[`${functionInInstance}Async`] = instance[functionInInstance];
instance[functionInInstance] = function () {
const args = Array.from(arguments);
const done = args.pop();
return instance[`${functionInInstance}Async`].apply(instance, args)
.then(result => done(null, result))
.catch(errors.ExtensionConfigurationError, error => {
debug(`Extension configuration error:${error.message}` || error.info);
return done(error);
})
.catch(error => done(error));
};
Object.defineProperty(instance[functionInInstance], 'length', {
value: instance[`${functionInInstance}Async`].length
});
});
return instance;
} | [
"function",
"toStriderProxy",
"(",
"instance",
")",
"{",
"debug",
"(",
"`",
"${",
"instance",
".",
"constructor",
".",
"name",
"}",
"`",
")",
";",
"const",
"functionsInInstance",
"=",
"Object",
".",
"getOwnPropertyNames",
"(",
"Object",
".",
"getPrototypeOf",
"(",
"instance",
")",
")",
".",
"filter",
"(",
"propertyName",
"=>",
"{",
"return",
"typeof",
"instance",
"[",
"propertyName",
"]",
"===",
"'function'",
"&&",
"propertyName",
"!==",
"'constructor'",
";",
"}",
")",
";",
"functionsInInstance",
".",
"forEach",
"(",
"functionInInstance",
"=>",
"{",
"instance",
"[",
"`",
"${",
"functionInInstance",
"}",
"`",
"]",
"=",
"instance",
"[",
"functionInInstance",
"]",
";",
"instance",
"[",
"functionInInstance",
"]",
"=",
"function",
"(",
")",
"{",
"const",
"args",
"=",
"Array",
".",
"from",
"(",
"arguments",
")",
";",
"const",
"done",
"=",
"args",
".",
"pop",
"(",
")",
";",
"return",
"instance",
"[",
"`",
"${",
"functionInInstance",
"}",
"`",
"]",
".",
"apply",
"(",
"instance",
",",
"args",
")",
".",
"then",
"(",
"result",
"=>",
"done",
"(",
"null",
",",
"result",
")",
")",
".",
"catch",
"(",
"errors",
".",
"ExtensionConfigurationError",
",",
"error",
"=>",
"{",
"debug",
"(",
"`",
"${",
"error",
".",
"message",
"}",
"`",
"||",
"error",
".",
"info",
")",
";",
"return",
"done",
"(",
"error",
")",
";",
"}",
")",
".",
"catch",
"(",
"error",
"=>",
"done",
"(",
"error",
")",
")",
";",
"}",
";",
"Object",
".",
"defineProperty",
"(",
"instance",
"[",
"functionInInstance",
"]",
",",
"'length'",
",",
"{",
"value",
":",
"instance",
"[",
"`",
"${",
"functionInInstance",
"}",
"`",
"]",
".",
"length",
"}",
")",
";",
"}",
")",
";",
"return",
"instance",
";",
"}"
]
| Given an input object, replaces all functions on that object with node-style callback equivalents.
The methods are expected to return promises. It's kind of like a reverse-promisifyAll.
The original methods are available by their old name with "Async" appended.
@param {Object} instance
@returns {Object} | [
"Given",
"an",
"input",
"object",
"replaces",
"all",
"functions",
"on",
"that",
"object",
"with",
"node",
"-",
"style",
"callback",
"equivalents",
".",
"The",
"methods",
"are",
"expected",
"to",
"return",
"promises",
".",
"It",
"s",
"kind",
"of",
"like",
"a",
"reverse",
"-",
"promisifyAll",
".",
"The",
"original",
"methods",
"are",
"available",
"by",
"their",
"old",
"name",
"with",
"Async",
"appended",
"."
]
| f8c37e49af1f05e34c66afff71d977e4b316289b | https://github.com/oliversalzburg/strider-modern-extensions/blob/f8c37e49af1f05e34c66afff71d977e4b316289b/lib/proxy.js#L15-L41 | train |
phated/grunt-enyo | tasks/init/enyo/root/enyo/source/touch/Thumb.js | function(inShowing) {
if (inShowing && inShowing != this.showing) {
if (this.scrollBounds[this.sizeDimension] >= this.scrollBounds[this.dimension]) {
return;
}
}
if (this.hasNode()) {
this.cancelDelayHide();
}
if (inShowing != this.showing) {
var last = this.showing;
this.showing = inShowing;
this.showingChanged(last);
}
} | javascript | function(inShowing) {
if (inShowing && inShowing != this.showing) {
if (this.scrollBounds[this.sizeDimension] >= this.scrollBounds[this.dimension]) {
return;
}
}
if (this.hasNode()) {
this.cancelDelayHide();
}
if (inShowing != this.showing) {
var last = this.showing;
this.showing = inShowing;
this.showingChanged(last);
}
} | [
"function",
"(",
"inShowing",
")",
"{",
"if",
"(",
"inShowing",
"&&",
"inShowing",
"!=",
"this",
".",
"showing",
")",
"{",
"if",
"(",
"this",
".",
"scrollBounds",
"[",
"this",
".",
"sizeDimension",
"]",
">=",
"this",
".",
"scrollBounds",
"[",
"this",
".",
"dimension",
"]",
")",
"{",
"return",
";",
"}",
"}",
"if",
"(",
"this",
".",
"hasNode",
"(",
")",
")",
"{",
"this",
".",
"cancelDelayHide",
"(",
")",
";",
"}",
"if",
"(",
"inShowing",
"!=",
"this",
".",
"showing",
")",
"{",
"var",
"last",
"=",
"this",
".",
"showing",
";",
"this",
".",
"showing",
"=",
"inShowing",
";",
"this",
".",
"showingChanged",
"(",
"last",
")",
";",
"}",
"}"
]
| implement set because showing is not changed while we delayHide but we want to cancel the hide. | [
"implement",
"set",
"because",
"showing",
"is",
"not",
"changed",
"while",
"we",
"delayHide",
"but",
"we",
"want",
"to",
"cancel",
"the",
"hide",
"."
]
| d2990ee4cd85eea8db4108c43086c6d8c3c90c30 | https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/enyo/root/enyo/source/touch/Thumb.js#L88-L102 | train |
|
jharding/yapawapa | lib/utils.js | extend | function extend(obj) {
var slice = Array.prototype.slice;
slice.call(arguments, 1).forEach(function(source) {
var getter
, setter;
for (var key in source) {
getter = source.__lookupGetter__(key);
setter = source.__lookupSetter__(key);
if (getter || setter) {
getter && obj.__defineGetter__(key, getter);
setter && obj.__defineSetter__(key, setter);
}
else {
obj[key] = source[key];
}
}
});
return obj;
} | javascript | function extend(obj) {
var slice = Array.prototype.slice;
slice.call(arguments, 1).forEach(function(source) {
var getter
, setter;
for (var key in source) {
getter = source.__lookupGetter__(key);
setter = source.__lookupSetter__(key);
if (getter || setter) {
getter && obj.__defineGetter__(key, getter);
setter && obj.__defineSetter__(key, setter);
}
else {
obj[key] = source[key];
}
}
});
return obj;
} | [
"function",
"extend",
"(",
"obj",
")",
"{",
"var",
"slice",
"=",
"Array",
".",
"prototype",
".",
"slice",
";",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
".",
"forEach",
"(",
"function",
"(",
"source",
")",
"{",
"var",
"getter",
",",
"setter",
";",
"for",
"(",
"var",
"key",
"in",
"source",
")",
"{",
"getter",
"=",
"source",
".",
"__lookupGetter__",
"(",
"key",
")",
";",
"setter",
"=",
"source",
".",
"__lookupSetter__",
"(",
"key",
")",
";",
"if",
"(",
"getter",
"||",
"setter",
")",
"{",
"getter",
"&&",
"obj",
".",
"__defineGetter__",
"(",
"key",
",",
"getter",
")",
";",
"setter",
"&&",
"obj",
".",
"__defineSetter__",
"(",
"key",
",",
"setter",
")",
";",
"}",
"else",
"{",
"obj",
"[",
"key",
"]",
"=",
"source",
"[",
"key",
"]",
";",
"}",
"}",
"}",
")",
";",
"return",
"obj",
";",
"}"
]
| roll custom extend since underscore's doesn't play nice with getters and setters | [
"roll",
"custom",
"extend",
"since",
"underscore",
"s",
"doesn",
"t",
"play",
"nice",
"with",
"getters",
"and",
"setters"
]
| 18816447a9fcfbe744cadf2d6f0fdceca443c05f | https://github.com/jharding/yapawapa/blob/18816447a9fcfbe744cadf2d6f0fdceca443c05f/lib/utils.js#L12-L35 | train |
Industryswarm/isnode-mod-data | lib/mongodb/mongodb-core/lib/sdam/cursor.js | setCursorDeadAndNotified | function setCursorDeadAndNotified(cursor, callback) {
cursor.s.dead = true;
setCursorNotified(cursor, callback);
} | javascript | function setCursorDeadAndNotified(cursor, callback) {
cursor.s.dead = true;
setCursorNotified(cursor, callback);
} | [
"function",
"setCursorDeadAndNotified",
"(",
"cursor",
",",
"callback",
")",
"{",
"cursor",
".",
"s",
".",
"dead",
"=",
"true",
";",
"setCursorNotified",
"(",
"cursor",
",",
"callback",
")",
";",
"}"
]
| Mark cursor as being dead and notified | [
"Mark",
"cursor",
"as",
"being",
"dead",
"and",
"notified"
]
| 5adc639b88a0d72cbeef23a6b5df7f4540745089 | https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb-core/lib/sdam/cursor.js#L523-L526 | train |
TribeMedia/tribemedia-kurento-client-core | lib/complexTypes/RTCOutboundRTPStreamStats.js | RTCOutboundRTPStreamStats | function RTCOutboundRTPStreamStats(rTCOutboundRTPStreamStatsDict){
if(!(this instanceof RTCOutboundRTPStreamStats))
return new RTCOutboundRTPStreamStats(rTCOutboundRTPStreamStatsDict)
// Check rTCOutboundRTPStreamStatsDict has the required fields
checkType('int', 'rTCOutboundRTPStreamStatsDict.packetsSent', rTCOutboundRTPStreamStatsDict.packetsSent, {required: true});
checkType('int', 'rTCOutboundRTPStreamStatsDict.bytesSent', rTCOutboundRTPStreamStatsDict.bytesSent, {required: true});
checkType('float', 'rTCOutboundRTPStreamStatsDict.targetBitrate', rTCOutboundRTPStreamStatsDict.targetBitrate, {required: true});
checkType('float', 'rTCOutboundRTPStreamStatsDict.roundTripTime', rTCOutboundRTPStreamStatsDict.roundTripTime, {required: true});
// Init parent class
RTCOutboundRTPStreamStats.super_.call(this, rTCOutboundRTPStreamStatsDict)
// Set object properties
Object.defineProperties(this, {
packetsSent: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.packetsSent
},
bytesSent: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.bytesSent
},
targetBitrate: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.targetBitrate
},
roundTripTime: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.roundTripTime
}
})
} | javascript | function RTCOutboundRTPStreamStats(rTCOutboundRTPStreamStatsDict){
if(!(this instanceof RTCOutboundRTPStreamStats))
return new RTCOutboundRTPStreamStats(rTCOutboundRTPStreamStatsDict)
// Check rTCOutboundRTPStreamStatsDict has the required fields
checkType('int', 'rTCOutboundRTPStreamStatsDict.packetsSent', rTCOutboundRTPStreamStatsDict.packetsSent, {required: true});
checkType('int', 'rTCOutboundRTPStreamStatsDict.bytesSent', rTCOutboundRTPStreamStatsDict.bytesSent, {required: true});
checkType('float', 'rTCOutboundRTPStreamStatsDict.targetBitrate', rTCOutboundRTPStreamStatsDict.targetBitrate, {required: true});
checkType('float', 'rTCOutboundRTPStreamStatsDict.roundTripTime', rTCOutboundRTPStreamStatsDict.roundTripTime, {required: true});
// Init parent class
RTCOutboundRTPStreamStats.super_.call(this, rTCOutboundRTPStreamStatsDict)
// Set object properties
Object.defineProperties(this, {
packetsSent: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.packetsSent
},
bytesSent: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.bytesSent
},
targetBitrate: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.targetBitrate
},
roundTripTime: {
writable: true,
enumerable: true,
value: rTCOutboundRTPStreamStatsDict.roundTripTime
}
})
} | [
"function",
"RTCOutboundRTPStreamStats",
"(",
"rTCOutboundRTPStreamStatsDict",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"RTCOutboundRTPStreamStats",
")",
")",
"return",
"new",
"RTCOutboundRTPStreamStats",
"(",
"rTCOutboundRTPStreamStatsDict",
")",
"checkType",
"(",
"'int'",
",",
"'rTCOutboundRTPStreamStatsDict.packetsSent'",
",",
"rTCOutboundRTPStreamStatsDict",
".",
"packetsSent",
",",
"{",
"required",
":",
"true",
"}",
")",
";",
"checkType",
"(",
"'int'",
",",
"'rTCOutboundRTPStreamStatsDict.bytesSent'",
",",
"rTCOutboundRTPStreamStatsDict",
".",
"bytesSent",
",",
"{",
"required",
":",
"true",
"}",
")",
";",
"checkType",
"(",
"'float'",
",",
"'rTCOutboundRTPStreamStatsDict.targetBitrate'",
",",
"rTCOutboundRTPStreamStatsDict",
".",
"targetBitrate",
",",
"{",
"required",
":",
"true",
"}",
")",
";",
"checkType",
"(",
"'float'",
",",
"'rTCOutboundRTPStreamStatsDict.roundTripTime'",
",",
"rTCOutboundRTPStreamStatsDict",
".",
"roundTripTime",
",",
"{",
"required",
":",
"true",
"}",
")",
";",
"RTCOutboundRTPStreamStats",
".",
"super_",
".",
"call",
"(",
"this",
",",
"rTCOutboundRTPStreamStatsDict",
")",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"packetsSent",
":",
"{",
"writable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"rTCOutboundRTPStreamStatsDict",
".",
"packetsSent",
"}",
",",
"bytesSent",
":",
"{",
"writable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"rTCOutboundRTPStreamStatsDict",
".",
"bytesSent",
"}",
",",
"targetBitrate",
":",
"{",
"writable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"rTCOutboundRTPStreamStatsDict",
".",
"targetBitrate",
"}",
",",
"roundTripTime",
":",
"{",
"writable",
":",
"true",
",",
"enumerable",
":",
"true",
",",
"value",
":",
"rTCOutboundRTPStreamStatsDict",
".",
"roundTripTime",
"}",
"}",
")",
"}"
]
| Statistics that represents the measurement metrics for the outgoing media
stream.
@constructor module:core/complexTypes.RTCOutboundRTPStreamStats
@property {external:Integer} packetsSent
Total number of RTP packets sent for this SSRC.
@property {external:Integer} bytesSent
Total number of bytes sent for this SSRC.
@property {external:Number} targetBitrate
Presently configured bitrate target of this SSRC, in bits per second.
@property {external:Number} roundTripTime
Estimated round trip time (seconds) for this SSRC based on the RTCP
timestamp.
@extends module:core.RTCRTPStreamStats | [
"Statistics",
"that",
"represents",
"the",
"measurement",
"metrics",
"for",
"the",
"outgoing",
"media",
"stream",
"."
]
| de4c0094644aae91320e330f9cea418a3ac55468 | https://github.com/TribeMedia/tribemedia-kurento-client-core/blob/de4c0094644aae91320e330f9cea418a3ac55468/lib/complexTypes/RTCOutboundRTPStreamStats.js#L45-L81 | train |
pinyin/outline | vendor/transformation-matrix/inverse.js | inverse | function inverse(matrix) {
//http://www.wolframalpha.com/input/?i=Inverse+%5B%7B%7Ba,c,e%7D,%7Bb,d,f%7D,%7B0,0,1%7D%7D%5D
var a = matrix.a,
b = matrix.b,
c = matrix.c,
d = matrix.d,
e = matrix.e,
f = matrix.f;
var denom = a * d - b * c;
return {
a: d / denom,
b: b / -denom,
c: c / -denom,
d: a / denom,
e: (d * e - c * f) / -denom,
f: (b * e - a * f) / denom
};
} | javascript | function inverse(matrix) {
//http://www.wolframalpha.com/input/?i=Inverse+%5B%7B%7Ba,c,e%7D,%7Bb,d,f%7D,%7B0,0,1%7D%7D%5D
var a = matrix.a,
b = matrix.b,
c = matrix.c,
d = matrix.d,
e = matrix.e,
f = matrix.f;
var denom = a * d - b * c;
return {
a: d / denom,
b: b / -denom,
c: c / -denom,
d: a / denom,
e: (d * e - c * f) / -denom,
f: (b * e - a * f) / denom
};
} | [
"function",
"inverse",
"(",
"matrix",
")",
"{",
"var",
"a",
"=",
"matrix",
".",
"a",
",",
"b",
"=",
"matrix",
".",
"b",
",",
"c",
"=",
"matrix",
".",
"c",
",",
"d",
"=",
"matrix",
".",
"d",
",",
"e",
"=",
"matrix",
".",
"e",
",",
"f",
"=",
"matrix",
".",
"f",
";",
"var",
"denom",
"=",
"a",
"*",
"d",
"-",
"b",
"*",
"c",
";",
"return",
"{",
"a",
":",
"d",
"/",
"denom",
",",
"b",
":",
"b",
"/",
"-",
"denom",
",",
"c",
":",
"c",
"/",
"-",
"denom",
",",
"d",
":",
"a",
"/",
"denom",
",",
"e",
":",
"(",
"d",
"*",
"e",
"-",
"c",
"*",
"f",
")",
"/",
"-",
"denom",
",",
"f",
":",
"(",
"b",
"*",
"e",
"-",
"a",
"*",
"f",
")",
"/",
"denom",
"}",
";",
"}"
]
| Calculate a matrix that is the inverse of the provided matrix
@param matrix Affine matrix
@returns {{a: number, b: number, c: number, e: number, d: number, f: number}} Affine matrix | [
"Calculate",
"a",
"matrix",
"that",
"is",
"the",
"inverse",
"of",
"the",
"provided",
"matrix"
]
| e49f05d2f8ab384f5b1d71b2b10875cd48d41051 | https://github.com/pinyin/outline/blob/e49f05d2f8ab384f5b1d71b2b10875cd48d41051/vendor/transformation-matrix/inverse.js#L13-L34 | train |
brianloveswords/gogo | lib/ext-underscore.js | curry | function curry(fn, obj) {
// create a local copy of the function. don't apply anything yet
// optionally bind an object to the `this` of the function.
var newFunction = _.bind(fn, (obj || null));
// curried functions always take one argument
return function () {
// create another copy of the function with the arguments applied
var me = _.partial(newFunction, arguments);
// take advantage of the fact that bind changes the method signature:
// if we have no arguments left, run the method
if (!me.length) return me();
// otherwise, curry again and return that.
return curry(me);
};
} | javascript | function curry(fn, obj) {
// create a local copy of the function. don't apply anything yet
// optionally bind an object to the `this` of the function.
var newFunction = _.bind(fn, (obj || null));
// curried functions always take one argument
return function () {
// create another copy of the function with the arguments applied
var me = _.partial(newFunction, arguments);
// take advantage of the fact that bind changes the method signature:
// if we have no arguments left, run the method
if (!me.length) return me();
// otherwise, curry again and return that.
return curry(me);
};
} | [
"function",
"curry",
"(",
"fn",
",",
"obj",
")",
"{",
"var",
"newFunction",
"=",
"_",
".",
"bind",
"(",
"fn",
",",
"(",
"obj",
"||",
"null",
")",
")",
";",
"return",
"function",
"(",
")",
"{",
"var",
"me",
"=",
"_",
".",
"partial",
"(",
"newFunction",
",",
"arguments",
")",
";",
"if",
"(",
"!",
"me",
".",
"length",
")",
"return",
"me",
"(",
")",
";",
"return",
"curry",
"(",
"me",
")",
";",
"}",
";",
"}"
]
| this takes advantage of ES5 bind's awesome ability to do partial application | [
"this",
"takes",
"advantage",
"of",
"ES5",
"bind",
"s",
"awesome",
"ability",
"to",
"do",
"partial",
"application"
]
| f17ee794e0439ed961907f52b91bcb74dcca351a | https://github.com/brianloveswords/gogo/blob/f17ee794e0439ed961907f52b91bcb74dcca351a/lib/ext-underscore.js#L21-L38 | train |
brianloveswords/gogo | lib/ext-underscore.js | function (o, path) {
function iterator(m, p) { return _.getv(p)(m); }
return _.reduce(path, iterator, o);
} | javascript | function (o, path) {
function iterator(m, p) { return _.getv(p)(m); }
return _.reduce(path, iterator, o);
} | [
"function",
"(",
"o",
",",
"path",
")",
"{",
"function",
"iterator",
"(",
"m",
",",
"p",
")",
"{",
"return",
"_",
".",
"getv",
"(",
"p",
")",
"(",
"m",
")",
";",
"}",
"return",
"_",
".",
"reduce",
"(",
"path",
",",
"iterator",
",",
"o",
")",
";",
"}"
]
| perform a root canal on an object. depends on getv | [
"perform",
"a",
"root",
"canal",
"on",
"an",
"object",
".",
"depends",
"on",
"getv"
]
| f17ee794e0439ed961907f52b91bcb74dcca351a | https://github.com/brianloveswords/gogo/blob/f17ee794e0439ed961907f52b91bcb74dcca351a/lib/ext-underscore.js#L65-L68 | train |
|
brianloveswords/gogo | lib/ext-underscore.js | function (a) {
var elements = _.reject(_.rest(arguments), _.isMissing);
return a.push.apply(a, elements);
} | javascript | function (a) {
var elements = _.reject(_.rest(arguments), _.isMissing);
return a.push.apply(a, elements);
} | [
"function",
"(",
"a",
")",
"{",
"var",
"elements",
"=",
"_",
".",
"reject",
"(",
"_",
".",
"rest",
"(",
"arguments",
")",
",",
"_",
".",
"isMissing",
")",
";",
"return",
"a",
".",
"push",
".",
"apply",
"(",
"a",
",",
"elements",
")",
";",
"}"
]
| push only defined elements to the array | [
"push",
"only",
"defined",
"elements",
"to",
"the",
"array"
]
| f17ee794e0439ed961907f52b91bcb74dcca351a | https://github.com/brianloveswords/gogo/blob/f17ee794e0439ed961907f52b91bcb74dcca351a/lib/ext-underscore.js#L119-L122 | train |
|
inlight-media/gulp-asset | index.js | function(opts) {
var opts = opts || {};
var shouldHash = typeof opts.hash != 'undefined' ? opts.hash : defaults.hash;
var prefix = _.flatten([defaults.prefix]);
var shouldPrefix = typeof opts.shouldPrefix != 'undefined' ? opts.shouldPrefix : true;
return through.obj(function(file, enc, cb) {
var originalPath = file.path;
// Get hash of contents
var hash = md5(opts, file.contents.toString());
// Construct new filename
var ext = path.extname(file.path);
var basePath = path.basename(file.path, ext);
var filename = typeof hash !== 'undefined' ? basePath + '-' + hash + ext : basePath + ext;
file.path = path.join(path.dirname(file.path), filename);
// Add to manifest
var base = path.join(file.cwd, defaults.src);
var key = originalPath.replace(base, '');
// @TODO: Instead of this it could use "glob" module to regex delete files
// Check for existing value and whether cleanup is set
var existing = manifest[key];
if (existing && existing.src && defaults.cleanup) {
// Delete the file
fs.unlink(path.join(file.cwd, defaults.dest, existing.src));
} else if (defaults.cleanup && shouldHash) {
// Check if cleanup and hash enabled then we can remove any non hashed version from dest directory
var nonHashPath = path.join(path.dirname(originalPath), basePath + ext).replace(base, '');
var absPath = path.join(file.cwd, defaults.dest, nonHashPath);
fs.exists(absPath, function(exists) {
if (!exists) return;
fs.unlink(absPath);
});
}
var filePrefix = shouldPrefix ? prefix[index % prefix.length] : '';
// Finally add new value to manifest
var src = file.path.replace(base, '');
manifest[key] = {
index: index++,
src: src,
dest: filePrefix + src
};
// Write manifest file
writeManifest();
// Return and continue
this.push(file);
cb();
});
} | javascript | function(opts) {
var opts = opts || {};
var shouldHash = typeof opts.hash != 'undefined' ? opts.hash : defaults.hash;
var prefix = _.flatten([defaults.prefix]);
var shouldPrefix = typeof opts.shouldPrefix != 'undefined' ? opts.shouldPrefix : true;
return through.obj(function(file, enc, cb) {
var originalPath = file.path;
// Get hash of contents
var hash = md5(opts, file.contents.toString());
// Construct new filename
var ext = path.extname(file.path);
var basePath = path.basename(file.path, ext);
var filename = typeof hash !== 'undefined' ? basePath + '-' + hash + ext : basePath + ext;
file.path = path.join(path.dirname(file.path), filename);
// Add to manifest
var base = path.join(file.cwd, defaults.src);
var key = originalPath.replace(base, '');
// @TODO: Instead of this it could use "glob" module to regex delete files
// Check for existing value and whether cleanup is set
var existing = manifest[key];
if (existing && existing.src && defaults.cleanup) {
// Delete the file
fs.unlink(path.join(file.cwd, defaults.dest, existing.src));
} else if (defaults.cleanup && shouldHash) {
// Check if cleanup and hash enabled then we can remove any non hashed version from dest directory
var nonHashPath = path.join(path.dirname(originalPath), basePath + ext).replace(base, '');
var absPath = path.join(file.cwd, defaults.dest, nonHashPath);
fs.exists(absPath, function(exists) {
if (!exists) return;
fs.unlink(absPath);
});
}
var filePrefix = shouldPrefix ? prefix[index % prefix.length] : '';
// Finally add new value to manifest
var src = file.path.replace(base, '');
manifest[key] = {
index: index++,
src: src,
dest: filePrefix + src
};
// Write manifest file
writeManifest();
// Return and continue
this.push(file);
cb();
});
} | [
"function",
"(",
"opts",
")",
"{",
"var",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"var",
"shouldHash",
"=",
"typeof",
"opts",
".",
"hash",
"!=",
"'undefined'",
"?",
"opts",
".",
"hash",
":",
"defaults",
".",
"hash",
";",
"var",
"prefix",
"=",
"_",
".",
"flatten",
"(",
"[",
"defaults",
".",
"prefix",
"]",
")",
";",
"var",
"shouldPrefix",
"=",
"typeof",
"opts",
".",
"shouldPrefix",
"!=",
"'undefined'",
"?",
"opts",
".",
"shouldPrefix",
":",
"true",
";",
"return",
"through",
".",
"obj",
"(",
"function",
"(",
"file",
",",
"enc",
",",
"cb",
")",
"{",
"var",
"originalPath",
"=",
"file",
".",
"path",
";",
"var",
"hash",
"=",
"md5",
"(",
"opts",
",",
"file",
".",
"contents",
".",
"toString",
"(",
")",
")",
";",
"var",
"ext",
"=",
"path",
".",
"extname",
"(",
"file",
".",
"path",
")",
";",
"var",
"basePath",
"=",
"path",
".",
"basename",
"(",
"file",
".",
"path",
",",
"ext",
")",
";",
"var",
"filename",
"=",
"typeof",
"hash",
"!==",
"'undefined'",
"?",
"basePath",
"+",
"'-'",
"+",
"hash",
"+",
"ext",
":",
"basePath",
"+",
"ext",
";",
"file",
".",
"path",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"file",
".",
"path",
")",
",",
"filename",
")",
";",
"var",
"base",
"=",
"path",
".",
"join",
"(",
"file",
".",
"cwd",
",",
"defaults",
".",
"src",
")",
";",
"var",
"key",
"=",
"originalPath",
".",
"replace",
"(",
"base",
",",
"''",
")",
";",
"var",
"existing",
"=",
"manifest",
"[",
"key",
"]",
";",
"if",
"(",
"existing",
"&&",
"existing",
".",
"src",
"&&",
"defaults",
".",
"cleanup",
")",
"{",
"fs",
".",
"unlink",
"(",
"path",
".",
"join",
"(",
"file",
".",
"cwd",
",",
"defaults",
".",
"dest",
",",
"existing",
".",
"src",
")",
")",
";",
"}",
"else",
"if",
"(",
"defaults",
".",
"cleanup",
"&&",
"shouldHash",
")",
"{",
"var",
"nonHashPath",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"originalPath",
")",
",",
"basePath",
"+",
"ext",
")",
".",
"replace",
"(",
"base",
",",
"''",
")",
";",
"var",
"absPath",
"=",
"path",
".",
"join",
"(",
"file",
".",
"cwd",
",",
"defaults",
".",
"dest",
",",
"nonHashPath",
")",
";",
"fs",
".",
"exists",
"(",
"absPath",
",",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"!",
"exists",
")",
"return",
";",
"fs",
".",
"unlink",
"(",
"absPath",
")",
";",
"}",
")",
";",
"}",
"var",
"filePrefix",
"=",
"shouldPrefix",
"?",
"prefix",
"[",
"index",
"%",
"prefix",
".",
"length",
"]",
":",
"''",
";",
"var",
"src",
"=",
"file",
".",
"path",
".",
"replace",
"(",
"base",
",",
"''",
")",
";",
"manifest",
"[",
"key",
"]",
"=",
"{",
"index",
":",
"index",
"++",
",",
"src",
":",
"src",
",",
"dest",
":",
"filePrefix",
"+",
"src",
"}",
";",
"writeManifest",
"(",
")",
";",
"this",
".",
"push",
"(",
"file",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Gets md5 from file contents and writes new filename with hash included to destinations | [
"Gets",
"md5",
"from",
"file",
"contents",
"and",
"writes",
"new",
"filename",
"with",
"hash",
"included",
"to",
"destinations"
]
| 13cbd41def828c9af1de50d44b753e1bf05c3916 | https://github.com/inlight-media/gulp-asset/blob/13cbd41def828c9af1de50d44b753e1bf05c3916/index.js#L85-L139 | train |
|
nil/options-config | src/index.js | validateValue | function validateValue(key, valObj, list) {
let type; let valid; let range; let regex;
const object = list[key];
const val = hasKey(valObj, key) ? valObj[key] : 'value_not_defined';
let defaultValue = object;
if (object) {
type = object.type;
valid = object.valid;
range = object.range;
regex = object.regex;
defaultValue = hasKey(object, 'default') ? object.default : object;
}
if (isDeclared(val)) {
return defaultValue;
}
if (isMatch(key, val, regex)) {
return val;
}
if (isValid(key, val, valid, type)) {
return val;
}
isType(key, val, type);
inRange(key, val, range);
return val;
} | javascript | function validateValue(key, valObj, list) {
let type; let valid; let range; let regex;
const object = list[key];
const val = hasKey(valObj, key) ? valObj[key] : 'value_not_defined';
let defaultValue = object;
if (object) {
type = object.type;
valid = object.valid;
range = object.range;
regex = object.regex;
defaultValue = hasKey(object, 'default') ? object.default : object;
}
if (isDeclared(val)) {
return defaultValue;
}
if (isMatch(key, val, regex)) {
return val;
}
if (isValid(key, val, valid, type)) {
return val;
}
isType(key, val, type);
inRange(key, val, range);
return val;
} | [
"function",
"validateValue",
"(",
"key",
",",
"valObj",
",",
"list",
")",
"{",
"let",
"type",
";",
"let",
"valid",
";",
"let",
"range",
";",
"let",
"regex",
";",
"const",
"object",
"=",
"list",
"[",
"key",
"]",
";",
"const",
"val",
"=",
"hasKey",
"(",
"valObj",
",",
"key",
")",
"?",
"valObj",
"[",
"key",
"]",
":",
"'value_not_defined'",
";",
"let",
"defaultValue",
"=",
"object",
";",
"if",
"(",
"object",
")",
"{",
"type",
"=",
"object",
".",
"type",
";",
"valid",
"=",
"object",
".",
"valid",
";",
"range",
"=",
"object",
".",
"range",
";",
"regex",
"=",
"object",
".",
"regex",
";",
"defaultValue",
"=",
"hasKey",
"(",
"object",
",",
"'default'",
")",
"?",
"object",
".",
"default",
":",
"object",
";",
"}",
"if",
"(",
"isDeclared",
"(",
"val",
")",
")",
"{",
"return",
"defaultValue",
";",
"}",
"if",
"(",
"isMatch",
"(",
"key",
",",
"val",
",",
"regex",
")",
")",
"{",
"return",
"val",
";",
"}",
"if",
"(",
"isValid",
"(",
"key",
",",
"val",
",",
"valid",
",",
"type",
")",
")",
"{",
"return",
"val",
";",
"}",
"isType",
"(",
"key",
",",
"val",
",",
"type",
")",
";",
"inRange",
"(",
"key",
",",
"val",
",",
"range",
")",
";",
"return",
"val",
";",
"}"
]
| Checks if a value fits the restrictions.
@param {string} key - The name of the option
@param {object} valObj - The value to check.
@param {object} list - The replacement restrictions.
@returns A value, whether it is the default or the given by the user. | [
"Checks",
"if",
"a",
"value",
"fits",
"the",
"restrictions",
"."
]
| 40fb5011d3d931913318d7e852c029ab816885b8 | https://github.com/nil/options-config/blob/40fb5011d3d931913318d7e852c029ab816885b8/src/index.js#L19-L52 | train |
dekujs/assert-element | index.js | classes | function classes(input) {
if (!input) return [];
assert.strictEqual(typeof input, 'string', 'expected a string for the class name');
if (!input.trim()) return [];
return input.trim().split(/\s+/g);
} | javascript | function classes(input) {
if (!input) return [];
assert.strictEqual(typeof input, 'string', 'expected a string for the class name');
if (!input.trim()) return [];
return input.trim().split(/\s+/g);
} | [
"function",
"classes",
"(",
"input",
")",
"{",
"if",
"(",
"!",
"input",
")",
"return",
"[",
"]",
";",
"assert",
".",
"strictEqual",
"(",
"typeof",
"input",
",",
"'string'",
",",
"'expected a string for the class name'",
")",
";",
"if",
"(",
"!",
"input",
".",
"trim",
"(",
")",
")",
"return",
"[",
"]",
";",
"return",
"input",
".",
"trim",
"(",
")",
".",
"split",
"(",
"/",
"\\s+",
"/",
"g",
")",
";",
"}"
]
| private helpers
Parse the given `input` into an `Array` of class names. Will always return
an `Array`, even if it's empty.
@param {String} [input] The class attribute string.
@return {Array} | [
"private",
"helpers",
"Parse",
"the",
"given",
"input",
"into",
"an",
"Array",
"of",
"class",
"names",
".",
"Will",
"always",
"return",
"an",
"Array",
"even",
"if",
"it",
"s",
"empty",
"."
]
| a275c98825249101f0e790635a1d33b300b16bc1 | https://github.com/dekujs/assert-element/blob/a275c98825249101f0e790635a1d33b300b16bc1/index.js#L162-L167 | train |
dekujs/assert-element | index.js | deepChild | function deepChild(root, path) {
return path.reduce(function (node, index, x) {
assert(index in node.children, 'child does not exist at the given deep index ' + path.join('.'));
return node.children[index];
}, root);
} | javascript | function deepChild(root, path) {
return path.reduce(function (node, index, x) {
assert(index in node.children, 'child does not exist at the given deep index ' + path.join('.'));
return node.children[index];
}, root);
} | [
"function",
"deepChild",
"(",
"root",
",",
"path",
")",
"{",
"return",
"path",
".",
"reduce",
"(",
"function",
"(",
"node",
",",
"index",
",",
"x",
")",
"{",
"assert",
"(",
"index",
"in",
"node",
".",
"children",
",",
"'child does not exist at the given deep index '",
"+",
"path",
".",
"join",
"(",
"'.'",
")",
")",
";",
"return",
"node",
".",
"children",
"[",
"index",
"]",
";",
"}",
",",
"root",
")",
";",
"}"
]
| Retrieve a deep child via an input array `index` of indices to traverse.
@param {Object} node The virtual node to traverse.
@param {Array:Number} path The path to traverse.
@return {Object} | [
"Retrieve",
"a",
"deep",
"child",
"via",
"an",
"input",
"array",
"index",
"of",
"indices",
"to",
"traverse",
"."
]
| a275c98825249101f0e790635a1d33b300b16bc1 | https://github.com/dekujs/assert-element/blob/a275c98825249101f0e790635a1d33b300b16bc1/index.js#L177-L182 | train |
mhelgeson/b9 | src/post/index.js | handler | function handler ( err, data ){
if ( callback != null ){
callback.apply( b9, arguments );
}
// only emit events when there is no error
if ( err == null ){
b9.emit.call( b9, method, data );
}
} | javascript | function handler ( err, data ){
if ( callback != null ){
callback.apply( b9, arguments );
}
// only emit events when there is no error
if ( err == null ){
b9.emit.call( b9, method, data );
}
} | [
"function",
"handler",
"(",
"err",
",",
"data",
")",
"{",
"if",
"(",
"callback",
"!=",
"null",
")",
"{",
"callback",
".",
"apply",
"(",
"b9",
",",
"arguments",
")",
";",
"}",
"if",
"(",
"err",
"==",
"null",
")",
"{",
"b9",
".",
"emit",
".",
"call",
"(",
"b9",
",",
"method",
",",
"data",
")",
";",
"}",
"}"
]
| wrap callback with an event emitter | [
"wrap",
"callback",
"with",
"an",
"event",
"emitter"
]
| 5f7ad9ac7c3fa586b06f6460b70a42c50b34e6f1 | https://github.com/mhelgeson/b9/blob/5f7ad9ac7c3fa586b06f6460b70a42c50b34e6f1/src/post/index.js#L54-L62 | train |
mgesmundo/port-manager | lib/service.js | Service | function Service(manager, name, port, heartbeat) {
var _name = name;
/**
* @property {String} name The name of the service
*/
Object.defineProperty(this, 'name', {
get: function get() {
return _name;
},
enumerable: true
});
var _port = port;
/**
* @property {Number} port The port claimed by the service
*/
Object.defineProperty(this, 'port', {
get: function get() {
return _port;
},
enumerable: true
});
var _heartbeatInterval;
if (heartbeat !== 0) {
debug('set heartbeat %d', heartbeat);
_heartbeatInterval = setInterval(heartbeatTest.call(this, manager), heartbeat);
}
/**
* @property {Number} heartbeat The heartbeat counter for the periodic port checking
*/
Object.defineProperty(this, 'heartbeat', {
get: function get() {
return _heartbeatInterval;
}
});
} | javascript | function Service(manager, name, port, heartbeat) {
var _name = name;
/**
* @property {String} name The name of the service
*/
Object.defineProperty(this, 'name', {
get: function get() {
return _name;
},
enumerable: true
});
var _port = port;
/**
* @property {Number} port The port claimed by the service
*/
Object.defineProperty(this, 'port', {
get: function get() {
return _port;
},
enumerable: true
});
var _heartbeatInterval;
if (heartbeat !== 0) {
debug('set heartbeat %d', heartbeat);
_heartbeatInterval = setInterval(heartbeatTest.call(this, manager), heartbeat);
}
/**
* @property {Number} heartbeat The heartbeat counter for the periodic port checking
*/
Object.defineProperty(this, 'heartbeat', {
get: function get() {
return _heartbeatInterval;
}
});
} | [
"function",
"Service",
"(",
"manager",
",",
"name",
",",
"port",
",",
"heartbeat",
")",
"{",
"var",
"_name",
"=",
"name",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'name'",
",",
"{",
"get",
":",
"function",
"get",
"(",
")",
"{",
"return",
"_name",
";",
"}",
",",
"enumerable",
":",
"true",
"}",
")",
";",
"var",
"_port",
"=",
"port",
";",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'port'",
",",
"{",
"get",
":",
"function",
"get",
"(",
")",
"{",
"return",
"_port",
";",
"}",
",",
"enumerable",
":",
"true",
"}",
")",
";",
"var",
"_heartbeatInterval",
";",
"if",
"(",
"heartbeat",
"!==",
"0",
")",
"{",
"debug",
"(",
"'set heartbeat %d'",
",",
"heartbeat",
")",
";",
"_heartbeatInterval",
"=",
"setInterval",
"(",
"heartbeatTest",
".",
"call",
"(",
"this",
",",
"manager",
")",
",",
"heartbeat",
")",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"'heartbeat'",
",",
"{",
"get",
":",
"function",
"get",
"(",
")",
"{",
"return",
"_heartbeatInterval",
";",
"}",
"}",
")",
";",
"}"
]
| The service to manage
@class node_modules.port_manager.Service
@param {Manager} manager The manager instance that store all services
@param {String} name The name of the service
@param {Number} port The port claimed by the service
@param {Number} [heartbeat] The heartbeat timer
@constructor | [
"The",
"service",
"to",
"manage"
]
| a09356b9063c228616d0ffc56217b93c479f2604 | https://github.com/mgesmundo/port-manager/blob/a09356b9063c228616d0ffc56217b93c479f2604/lib/service.js#L29-L63 | train |
rranauro/boxspringjs | workflows.js | function(docs, callback) {
remaining = docs;
console.log('[ remove ] info: ' + remaining +' to remove.');
async.eachLimit(_.range(0, docs, 10000), 1, handleOneBlock, callback);
} | javascript | function(docs, callback) {
remaining = docs;
console.log('[ remove ] info: ' + remaining +' to remove.');
async.eachLimit(_.range(0, docs, 10000), 1, handleOneBlock, callback);
} | [
"function",
"(",
"docs",
",",
"callback",
")",
"{",
"remaining",
"=",
"docs",
";",
"console",
".",
"log",
"(",
"'[ remove ] info: '",
"+",
"remaining",
"+",
"' to remove.'",
")",
";",
"async",
".",
"eachLimit",
"(",
"_",
".",
"range",
"(",
"0",
",",
"docs",
",",
"10000",
")",
",",
"1",
",",
"handleOneBlock",
",",
"callback",
")",
";",
"}"
]
| fetch the 'removeView' list; returns array of objects marked "_deleted" | [
"fetch",
"the",
"removeView",
"list",
";",
"returns",
"array",
"of",
"objects",
"marked",
"_deleted"
]
| 43fd13ae45ba5b16ba9144084b96748a1cd8c0ea | https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/workflows.js#L83-L87 | train |
|
CCISEL/connect-controller | example/lib/controllers/favorites.js | function(teamId, req) {
const favoritesList = req.app.locals.favoritesList
const index = favoritesList.findIndex(t => t.id == teamId)
if(index < 0) {
const err = new Error('Team is not parte of Favorites!!!')
err.status = 409
throw err
}
favoritesList.splice(index, 1)
} | javascript | function(teamId, req) {
const favoritesList = req.app.locals.favoritesList
const index = favoritesList.findIndex(t => t.id == teamId)
if(index < 0) {
const err = new Error('Team is not parte of Favorites!!!')
err.status = 409
throw err
}
favoritesList.splice(index, 1)
} | [
"function",
"(",
"teamId",
",",
"req",
")",
"{",
"const",
"favoritesList",
"=",
"req",
".",
"app",
".",
"locals",
".",
"favoritesList",
"const",
"index",
"=",
"favoritesList",
".",
"findIndex",
"(",
"t",
"=>",
"t",
".",
"id",
"==",
"teamId",
")",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"const",
"err",
"=",
"new",
"Error",
"(",
"'Team is not parte of Favorites!!!'",
")",
"err",
".",
"status",
"=",
"409",
"throw",
"err",
"}",
"favoritesList",
".",
"splice",
"(",
"index",
",",
"1",
")",
"}"
]
| This is a synchronous action that does not do any IO.
Simply returning with NO exceptions just means success and
connect-controller will send a 200 response status. | [
"This",
"is",
"a",
"synchronous",
"action",
"that",
"does",
"not",
"do",
"any",
"IO",
".",
"Simply",
"returning",
"with",
"NO",
"exceptions",
"just",
"means",
"success",
"and",
"connect",
"-",
"controller",
"will",
"send",
"a",
"200",
"response",
"status",
"."
]
| c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4 | https://github.com/CCISEL/connect-controller/blob/c8e2587c5a31e3cb54e3668c4b98b7b7526d69b4/example/lib/controllers/favorites.js#L34-L43 | train |
|
richRemer/twixt-click | click.js | click | function click(target, handler) {
target.addEventListener("click", function(evt) {
evt.stopPropagation();
evt.preventDefault();
handler.call(this);
});
} | javascript | function click(target, handler) {
target.addEventListener("click", function(evt) {
evt.stopPropagation();
evt.preventDefault();
handler.call(this);
});
} | [
"function",
"click",
"(",
"target",
",",
"handler",
")",
"{",
"target",
".",
"addEventListener",
"(",
"\"click\"",
",",
"function",
"(",
"evt",
")",
"{",
"evt",
".",
"stopPropagation",
"(",
")",
";",
"evt",
".",
"preventDefault",
"(",
")",
";",
"handler",
".",
"call",
"(",
"this",
")",
";",
"}",
")",
";",
"}"
]
| Attach click event handler.
@param {EventTarget} target
@param {function} handler | [
"Attach",
"click",
"event",
"handler",
"."
]
| e3b0574f148c8060b19b1fe4517ede460474e821 | https://github.com/richRemer/twixt-click/blob/e3b0574f148c8060b19b1fe4517ede460474e821/click.js#L6-L12 | train |
fshost/api-chain | api-chain.js | function(name, method) {
API.prototype[name] = function() {
var api = this;
var args = Array.prototype.slice.call(arguments);
this.chain(function(next) {
var cargs = [].slice.call(arguments);
cargs = args.concat(cargs);
// args.push(next);
method.apply(api, cargs);
});
return this;
};
return this;
} | javascript | function(name, method) {
API.prototype[name] = function() {
var api = this;
var args = Array.prototype.slice.call(arguments);
this.chain(function(next) {
var cargs = [].slice.call(arguments);
cargs = args.concat(cargs);
// args.push(next);
method.apply(api, cargs);
});
return this;
};
return this;
} | [
"function",
"(",
"name",
",",
"method",
")",
"{",
"API",
".",
"prototype",
"[",
"name",
"]",
"=",
"function",
"(",
")",
"{",
"var",
"api",
"=",
"this",
";",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"this",
".",
"chain",
"(",
"function",
"(",
"next",
")",
"{",
"var",
"cargs",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"cargs",
"=",
"args",
".",
"concat",
"(",
"cargs",
")",
";",
"method",
".",
"apply",
"(",
"api",
",",
"cargs",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}",
";",
"return",
"this",
";",
"}"
]
| add a method to the prototype | [
"add",
"a",
"method",
"to",
"the",
"prototype"
]
| d98df82575b0a0afd20c10424c0c038389b32f80 | https://github.com/fshost/api-chain/blob/d98df82575b0a0afd20c10424c0c038389b32f80/api-chain.js#L67-L82 | train |
|
fshost/api-chain | api-chain.js | function(err) {
if (err) this._onError(err);
if (this._continueErrors || !err) {
var args = [].slice.call(arguments);
if (this._callbacks.length > 0) {
this._isQueueRunning = true;
var cb = this._callbacks.shift();
cb = cb.bind(this);
args = args.slice(1);
args.push(this.next);
cb.apply(this, args);
} else {
this._isQueueRunning = false;
this.start = (function() {
this.start = null;
this.next.apply(this, args);
}).bind(this);
}
}
return this;
} | javascript | function(err) {
if (err) this._onError(err);
if (this._continueErrors || !err) {
var args = [].slice.call(arguments);
if (this._callbacks.length > 0) {
this._isQueueRunning = true;
var cb = this._callbacks.shift();
cb = cb.bind(this);
args = args.slice(1);
args.push(this.next);
cb.apply(this, args);
} else {
this._isQueueRunning = false;
this.start = (function() {
this.start = null;
this.next.apply(this, args);
}).bind(this);
}
}
return this;
} | [
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"this",
".",
"_onError",
"(",
"err",
")",
";",
"if",
"(",
"this",
".",
"_continueErrors",
"||",
"!",
"err",
")",
"{",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"if",
"(",
"this",
".",
"_callbacks",
".",
"length",
">",
"0",
")",
"{",
"this",
".",
"_isQueueRunning",
"=",
"true",
";",
"var",
"cb",
"=",
"this",
".",
"_callbacks",
".",
"shift",
"(",
")",
";",
"cb",
"=",
"cb",
".",
"bind",
"(",
"this",
")",
";",
"args",
"=",
"args",
".",
"slice",
"(",
"1",
")",
";",
"args",
".",
"push",
"(",
"this",
".",
"next",
")",
";",
"cb",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
"else",
"{",
"this",
".",
"_isQueueRunning",
"=",
"false",
";",
"this",
".",
"start",
"=",
"(",
"function",
"(",
")",
"{",
"this",
".",
"start",
"=",
"null",
";",
"this",
".",
"next",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
")",
".",
"bind",
"(",
"this",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
]
| advance to next cb | [
"advance",
"to",
"next",
"cb"
]
| d98df82575b0a0afd20c10424c0c038389b32f80 | https://github.com/fshost/api-chain/blob/d98df82575b0a0afd20c10424c0c038389b32f80/api-chain.js#L96-L118 | train |
|
fshost/api-chain | api-chain.js | function(name, value, immediate) {
if (immediate) {
this[name] = value;
} else this.chain(function() {
var args = Array.prototype.slice.call(arguments);
var next = args.pop();
this[name] = value;
args.unshift(null);
next.apply(this, args);
});
return this;
} | javascript | function(name, value, immediate) {
if (immediate) {
this[name] = value;
} else this.chain(function() {
var args = Array.prototype.slice.call(arguments);
var next = args.pop();
this[name] = value;
args.unshift(null);
next.apply(this, args);
});
return this;
} | [
"function",
"(",
"name",
",",
"value",
",",
"immediate",
")",
"{",
"if",
"(",
"immediate",
")",
"{",
"this",
"[",
"name",
"]",
"=",
"value",
";",
"}",
"else",
"this",
".",
"chain",
"(",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"var",
"next",
"=",
"args",
".",
"pop",
"(",
")",
";",
"this",
"[",
"name",
"]",
"=",
"value",
";",
"args",
".",
"unshift",
"(",
"null",
")",
";",
"next",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
")",
";",
"return",
"this",
";",
"}"
]
| set instance property | [
"set",
"instance",
"property"
]
| d98df82575b0a0afd20c10424c0c038389b32f80 | https://github.com/fshost/api-chain/blob/d98df82575b0a0afd20c10424c0c038389b32f80/api-chain.js#L121-L132 | train |
|
fshost/api-chain | api-chain.js | function(cb) {
cb = this.wrap(cb);
this._callbacks.push(cb);
if (!this._isQueueRunning) {
if (this.start) {
this.start();
} else this.next();
// this.start();
}
return this;
} | javascript | function(cb) {
cb = this.wrap(cb);
this._callbacks.push(cb);
if (!this._isQueueRunning) {
if (this.start) {
this.start();
} else this.next();
// this.start();
}
return this;
} | [
"function",
"(",
"cb",
")",
"{",
"cb",
"=",
"this",
".",
"wrap",
"(",
"cb",
")",
";",
"this",
".",
"_callbacks",
".",
"push",
"(",
"cb",
")",
";",
"if",
"(",
"!",
"this",
".",
"_isQueueRunning",
")",
"{",
"if",
"(",
"this",
".",
"start",
")",
"{",
"this",
".",
"start",
"(",
")",
";",
"}",
"else",
"this",
".",
"next",
"(",
")",
";",
"}",
"return",
"this",
";",
"}"
]
| add a callback to the execution chain | [
"add",
"a",
"callback",
"to",
"the",
"execution",
"chain"
]
| d98df82575b0a0afd20c10424c0c038389b32f80 | https://github.com/fshost/api-chain/blob/d98df82575b0a0afd20c10424c0c038389b32f80/api-chain.js#L151-L161 | train |
|
iolo/node-toybox | async.js | parallel | function parallel(promises, limit) {
var d = Q.defer();
var total = promises.length;
var results = new Array(total);
var firstErr;
var running = 0;
var finished = 0;
var next = 0;
limit = limit || total;
function sched() {
while (next < total && running < limit) {
DEBUG && debug('*** sched #', next, '***', promises[next].inspect());
exec(next++);
}
}
function exec(id) {
running += 1;
var promise = promises[id];
DEBUG && debug('>>> running', running);
DEBUG && debug('*** run #', id, '***', promise.inspect());
promise.then(function (result) {
DEBUG && debug('#', id, 'then ***', result);
results[id] = result; // collect all result
d.notify(promise.inspect());
}).catch(function (err) {
DEBUG && debug('#', id, 'catch ***', err);
firstErr = firstErr || err; // keep the first error
}).finally(function () {
DEBUG && debug('#', id, 'finally ***', promise.inspect());
if (++finished === total) {
DEBUG && debug('>>> finished all ***', firstErr, results);
return firstErr ? d.reject(firstErr) : d.resolve(results);
}
DEBUG && debug('>>> finished', finished);
running -= 1;
sched();
});
}
sched();
return d.promise;
} | javascript | function parallel(promises, limit) {
var d = Q.defer();
var total = promises.length;
var results = new Array(total);
var firstErr;
var running = 0;
var finished = 0;
var next = 0;
limit = limit || total;
function sched() {
while (next < total && running < limit) {
DEBUG && debug('*** sched #', next, '***', promises[next].inspect());
exec(next++);
}
}
function exec(id) {
running += 1;
var promise = promises[id];
DEBUG && debug('>>> running', running);
DEBUG && debug('*** run #', id, '***', promise.inspect());
promise.then(function (result) {
DEBUG && debug('#', id, 'then ***', result);
results[id] = result; // collect all result
d.notify(promise.inspect());
}).catch(function (err) {
DEBUG && debug('#', id, 'catch ***', err);
firstErr = firstErr || err; // keep the first error
}).finally(function () {
DEBUG && debug('#', id, 'finally ***', promise.inspect());
if (++finished === total) {
DEBUG && debug('>>> finished all ***', firstErr, results);
return firstErr ? d.reject(firstErr) : d.resolve(results);
}
DEBUG && debug('>>> finished', finished);
running -= 1;
sched();
});
}
sched();
return d.promise;
} | [
"function",
"parallel",
"(",
"promises",
",",
"limit",
")",
"{",
"var",
"d",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"var",
"total",
"=",
"promises",
".",
"length",
";",
"var",
"results",
"=",
"new",
"Array",
"(",
"total",
")",
";",
"var",
"firstErr",
";",
"var",
"running",
"=",
"0",
";",
"var",
"finished",
"=",
"0",
";",
"var",
"next",
"=",
"0",
";",
"limit",
"=",
"limit",
"||",
"total",
";",
"function",
"sched",
"(",
")",
"{",
"while",
"(",
"next",
"<",
"total",
"&&",
"running",
"<",
"limit",
")",
"{",
"DEBUG",
"&&",
"debug",
"(",
"'*** sched #'",
",",
"next",
",",
"'***'",
",",
"promises",
"[",
"next",
"]",
".",
"inspect",
"(",
")",
")",
";",
"exec",
"(",
"next",
"++",
")",
";",
"}",
"}",
"function",
"exec",
"(",
"id",
")",
"{",
"running",
"+=",
"1",
";",
"var",
"promise",
"=",
"promises",
"[",
"id",
"]",
";",
"DEBUG",
"&&",
"debug",
"(",
"'>>> running'",
",",
"running",
")",
";",
"DEBUG",
"&&",
"debug",
"(",
"'*** run #'",
",",
"id",
",",
"'***'",
",",
"promise",
".",
"inspect",
"(",
")",
")",
";",
"promise",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"DEBUG",
"&&",
"debug",
"(",
"'#'",
",",
"id",
",",
"'then ***'",
",",
"result",
")",
";",
"results",
"[",
"id",
"]",
"=",
"result",
";",
"d",
".",
"notify",
"(",
"promise",
".",
"inspect",
"(",
")",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"DEBUG",
"&&",
"debug",
"(",
"'#'",
",",
"id",
",",
"'catch ***'",
",",
"err",
")",
";",
"firstErr",
"=",
"firstErr",
"||",
"err",
";",
"}",
")",
".",
"finally",
"(",
"function",
"(",
")",
"{",
"DEBUG",
"&&",
"debug",
"(",
"'#'",
",",
"id",
",",
"'finally ***'",
",",
"promise",
".",
"inspect",
"(",
")",
")",
";",
"if",
"(",
"++",
"finished",
"===",
"total",
")",
"{",
"DEBUG",
"&&",
"debug",
"(",
"'>>> finished all ***'",
",",
"firstErr",
",",
"results",
")",
";",
"return",
"firstErr",
"?",
"d",
".",
"reject",
"(",
"firstErr",
")",
":",
"d",
".",
"resolve",
"(",
"results",
")",
";",
"}",
"DEBUG",
"&&",
"debug",
"(",
"'>>> finished'",
",",
"finished",
")",
";",
"running",
"-=",
"1",
";",
"sched",
"(",
")",
";",
"}",
")",
";",
"}",
"sched",
"(",
")",
";",
"return",
"d",
".",
"promise",
";",
"}"
]
| !!debug.enabled;
@param {Array.<promise>} promises
@param {number} [limit]
@returns {promise} | [
"!!debug",
".",
"enabled",
";"
]
| d03e48b5e4b3deb022688fee59dd33a2b71819d0 | https://github.com/iolo/node-toybox/blob/d03e48b5e4b3deb022688fee59dd33a2b71819d0/async.js#L15-L59 | train |
Techniv/node-command-io | libs/commandio.js | addCommand | function addCommand(descriptor){
// Check descriptor type.
var err = {};
if( !checkDescriptor(descriptor, err) ){
logger.error(
'The command descriptor is invalid.',
new Error('[command.io] Invalid command descriptor ("'+err.key+'": expected "'+err.expect+'", have "'+err.type+'").')
);
logger.error('Please check this doc: https://github.com/Techniv/node-command-io/wiki/Command-descriptor-refactoring');
return module.exports;
}
var name = descriptor.name;
descriptor.controller = new CommandController(descriptor);
// Index the command descriptor
commandDescriptors[name] = descriptor;
// Chain addCommand
return module.exports;
} | javascript | function addCommand(descriptor){
// Check descriptor type.
var err = {};
if( !checkDescriptor(descriptor, err) ){
logger.error(
'The command descriptor is invalid.',
new Error('[command.io] Invalid command descriptor ("'+err.key+'": expected "'+err.expect+'", have "'+err.type+'").')
);
logger.error('Please check this doc: https://github.com/Techniv/node-command-io/wiki/Command-descriptor-refactoring');
return module.exports;
}
var name = descriptor.name;
descriptor.controller = new CommandController(descriptor);
// Index the command descriptor
commandDescriptors[name] = descriptor;
// Chain addCommand
return module.exports;
} | [
"function",
"addCommand",
"(",
"descriptor",
")",
"{",
"var",
"err",
"=",
"{",
"}",
";",
"if",
"(",
"!",
"checkDescriptor",
"(",
"descriptor",
",",
"err",
")",
")",
"{",
"logger",
".",
"error",
"(",
"'The command descriptor is invalid.'",
",",
"new",
"Error",
"(",
"'[command.io] Invalid command descriptor (\"'",
"+",
"err",
".",
"key",
"+",
"'\": expected \"'",
"+",
"err",
".",
"expect",
"+",
"'\", have \"'",
"+",
"err",
".",
"type",
"+",
"'\").'",
")",
")",
";",
"logger",
".",
"error",
"(",
"'Please check this doc: https://github.com/Techniv/node-command-io/wiki/Command-descriptor-refactoring'",
")",
";",
"return",
"module",
".",
"exports",
";",
"}",
"var",
"name",
"=",
"descriptor",
".",
"name",
";",
"descriptor",
".",
"controller",
"=",
"new",
"CommandController",
"(",
"descriptor",
")",
";",
"commandDescriptors",
"[",
"name",
"]",
"=",
"descriptor",
";",
"return",
"module",
".",
"exports",
";",
"}"
]
| Add a command
@param name string
@param description string
@param action Function
@returns Object return Command.IO API. | [
"Add",
"a",
"command"
]
| 3d3cdfac83b2e14e801a9fc94ced9024c757674f | https://github.com/Techniv/node-command-io/blob/3d3cdfac83b2e14e801a9fc94ced9024c757674f/libs/commandio.js#L122-L142 | train |
Techniv/node-command-io | libs/commandio.js | addCommands | function addCommands(commands){
for(var i in commands){
var commandObj = commands[i];
addCommand(commandObj);
}
return module.exports;
} | javascript | function addCommands(commands){
for(var i in commands){
var commandObj = commands[i];
addCommand(commandObj);
}
return module.exports;
} | [
"function",
"addCommands",
"(",
"commands",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"commands",
")",
"{",
"var",
"commandObj",
"=",
"commands",
"[",
"i",
"]",
";",
"addCommand",
"(",
"commandObj",
")",
";",
"}",
"return",
"module",
".",
"exports",
";",
"}"
]
| Add commands recursively.
@param commands Object[] An array of command descriptor {name: string, description: string, :action: function}.
@return Object Return Command.IO API. | [
"Add",
"commands",
"recursively",
"."
]
| 3d3cdfac83b2e14e801a9fc94ced9024c757674f | https://github.com/Techniv/node-command-io/blob/3d3cdfac83b2e14e801a9fc94ced9024c757674f/libs/commandio.js#L149-L156 | train |
Techniv/node-command-io | libs/commandio.js | CommandController | function CommandController(descriptor){
Object.defineProperties(this, {
name: {
get: function(){
return descriptor.name;
}
},
description: {
get: function(){
return descriptor.description;
}
},
CommandError: {
get: function(){
return LocalCommandError;
}
},
RuntimeCommandError: {
get: function (){
return LocalRuntimeCommandError;
}
},
errorLvl: {
get: function(){
return Object.create(CONST.errorLvl);
}
}
});
function LocalCommandError(message, level){
CommandError.call(this, message, descriptor.name, level);
}
LocalCommandError.prototype = Object.create(CommandError.prototype);
function LocalRuntimeCommandError(message){
RuntimeCommandError.call(this, message, descriptor.name);
}
LocalRuntimeCommandError.prototype = Object.create(RuntimeCommandError.prototype);
} | javascript | function CommandController(descriptor){
Object.defineProperties(this, {
name: {
get: function(){
return descriptor.name;
}
},
description: {
get: function(){
return descriptor.description;
}
},
CommandError: {
get: function(){
return LocalCommandError;
}
},
RuntimeCommandError: {
get: function (){
return LocalRuntimeCommandError;
}
},
errorLvl: {
get: function(){
return Object.create(CONST.errorLvl);
}
}
});
function LocalCommandError(message, level){
CommandError.call(this, message, descriptor.name, level);
}
LocalCommandError.prototype = Object.create(CommandError.prototype);
function LocalRuntimeCommandError(message){
RuntimeCommandError.call(this, message, descriptor.name);
}
LocalRuntimeCommandError.prototype = Object.create(RuntimeCommandError.prototype);
} | [
"function",
"CommandController",
"(",
"descriptor",
")",
"{",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"name",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"descriptor",
".",
"name",
";",
"}",
"}",
",",
"description",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"descriptor",
".",
"description",
";",
"}",
"}",
",",
"CommandError",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"LocalCommandError",
";",
"}",
"}",
",",
"RuntimeCommandError",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"LocalRuntimeCommandError",
";",
"}",
"}",
",",
"errorLvl",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"Object",
".",
"create",
"(",
"CONST",
".",
"errorLvl",
")",
";",
"}",
"}",
"}",
")",
";",
"function",
"LocalCommandError",
"(",
"message",
",",
"level",
")",
"{",
"CommandError",
".",
"call",
"(",
"this",
",",
"message",
",",
"descriptor",
".",
"name",
",",
"level",
")",
";",
"}",
"LocalCommandError",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"CommandError",
".",
"prototype",
")",
";",
"function",
"LocalRuntimeCommandError",
"(",
"message",
")",
"{",
"RuntimeCommandError",
".",
"call",
"(",
"this",
",",
"message",
",",
"descriptor",
".",
"name",
")",
";",
"}",
"LocalRuntimeCommandError",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"RuntimeCommandError",
".",
"prototype",
")",
";",
"}"
]
| CommandIO API to command action.
@param descriptor The command descriptor. | [
"CommandIO",
"API",
"to",
"command",
"action",
"."
]
| 3d3cdfac83b2e14e801a9fc94ced9024c757674f | https://github.com/Techniv/node-command-io/blob/3d3cdfac83b2e14e801a9fc94ced9024c757674f/libs/commandio.js#L222-L261 | train |
Techniv/node-command-io | libs/commandio.js | checkDescriptor | function checkDescriptor(descriptor, err){
if(typeof descriptor != 'object') return false;
for(var key in CONST.descriptorType){
if(!checkType(descriptor[key], CONST.descriptorType[key])){
err.key = key;
err.expect = CONST.descriptorType[key];
err.type = typeof descriptor[key];
return false;
}
}
for(var key in CONST.descriptorOptType){
if(typeof descriptor[key] != 'undefined' && checkType(descriptor[key], CONST.descriptorOptType[key].type)) continue;
if(typeof descriptor[key] == 'undefined'){
if(typeof CONST.descriptorOptType[key].value != 'undefined') descriptor[key] = CONST.descriptorOptType[key].value;
continue;
}
err.key = key;
err.expect = CONST.descriptorOptType[key].type;
err.type = typeof descriptor[key];
return false;
}
return true;
} | javascript | function checkDescriptor(descriptor, err){
if(typeof descriptor != 'object') return false;
for(var key in CONST.descriptorType){
if(!checkType(descriptor[key], CONST.descriptorType[key])){
err.key = key;
err.expect = CONST.descriptorType[key];
err.type = typeof descriptor[key];
return false;
}
}
for(var key in CONST.descriptorOptType){
if(typeof descriptor[key] != 'undefined' && checkType(descriptor[key], CONST.descriptorOptType[key].type)) continue;
if(typeof descriptor[key] == 'undefined'){
if(typeof CONST.descriptorOptType[key].value != 'undefined') descriptor[key] = CONST.descriptorOptType[key].value;
continue;
}
err.key = key;
err.expect = CONST.descriptorOptType[key].type;
err.type = typeof descriptor[key];
return false;
}
return true;
} | [
"function",
"checkDescriptor",
"(",
"descriptor",
",",
"err",
")",
"{",
"if",
"(",
"typeof",
"descriptor",
"!=",
"'object'",
")",
"return",
"false",
";",
"for",
"(",
"var",
"key",
"in",
"CONST",
".",
"descriptorType",
")",
"{",
"if",
"(",
"!",
"checkType",
"(",
"descriptor",
"[",
"key",
"]",
",",
"CONST",
".",
"descriptorType",
"[",
"key",
"]",
")",
")",
"{",
"err",
".",
"key",
"=",
"key",
";",
"err",
".",
"expect",
"=",
"CONST",
".",
"descriptorType",
"[",
"key",
"]",
";",
"err",
".",
"type",
"=",
"typeof",
"descriptor",
"[",
"key",
"]",
";",
"return",
"false",
";",
"}",
"}",
"for",
"(",
"var",
"key",
"in",
"CONST",
".",
"descriptorOptType",
")",
"{",
"if",
"(",
"typeof",
"descriptor",
"[",
"key",
"]",
"!=",
"'undefined'",
"&&",
"checkType",
"(",
"descriptor",
"[",
"key",
"]",
",",
"CONST",
".",
"descriptorOptType",
"[",
"key",
"]",
".",
"type",
")",
")",
"continue",
";",
"if",
"(",
"typeof",
"descriptor",
"[",
"key",
"]",
"==",
"'undefined'",
")",
"{",
"if",
"(",
"typeof",
"CONST",
".",
"descriptorOptType",
"[",
"key",
"]",
".",
"value",
"!=",
"'undefined'",
")",
"descriptor",
"[",
"key",
"]",
"=",
"CONST",
".",
"descriptorOptType",
"[",
"key",
"]",
".",
"value",
";",
"continue",
";",
"}",
"err",
".",
"key",
"=",
"key",
";",
"err",
".",
"expect",
"=",
"CONST",
".",
"descriptorOptType",
"[",
"key",
"]",
".",
"type",
";",
"err",
".",
"type",
"=",
"typeof",
"descriptor",
"[",
"key",
"]",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| Check if the command descriptor is valid.
@return boolean | [
"Check",
"if",
"the",
"command",
"descriptor",
"is",
"valid",
"."
]
| 3d3cdfac83b2e14e801a9fc94ced9024c757674f | https://github.com/Techniv/node-command-io/blob/3d3cdfac83b2e14e801a9fc94ced9024c757674f/libs/commandio.js#L306-L332 | train |
Techniv/node-command-io | libs/commandio.js | CommandError | function CommandError(message, command, level){
var that = this, error;
// Set the default level.
if( isNaN(level) || level < 1 || level > 3) level = CONST.errorLvl.error;
// Format the message
if(typeof command == 'string') message = '{'+command+'} '+message;
message = '[command.io] '+message;
// Create the native Error object.
error = new Error(message);
// Create the getter for native error properties and custom properties.
Object.defineProperties(this, {
'stack': {
get: function(){
return error.stack;
}
},
message: {
get: function(){
return error.message;
}
},
command: {
get: function(){
return command;
}
},
level: {
get: function(){
return level;
}
}
});
} | javascript | function CommandError(message, command, level){
var that = this, error;
// Set the default level.
if( isNaN(level) || level < 1 || level > 3) level = CONST.errorLvl.error;
// Format the message
if(typeof command == 'string') message = '{'+command+'} '+message;
message = '[command.io] '+message;
// Create the native Error object.
error = new Error(message);
// Create the getter for native error properties and custom properties.
Object.defineProperties(this, {
'stack': {
get: function(){
return error.stack;
}
},
message: {
get: function(){
return error.message;
}
},
command: {
get: function(){
return command;
}
},
level: {
get: function(){
return level;
}
}
});
} | [
"function",
"CommandError",
"(",
"message",
",",
"command",
",",
"level",
")",
"{",
"var",
"that",
"=",
"this",
",",
"error",
";",
"if",
"(",
"isNaN",
"(",
"level",
")",
"||",
"level",
"<",
"1",
"||",
"level",
">",
"3",
")",
"level",
"=",
"CONST",
".",
"errorLvl",
".",
"error",
";",
"if",
"(",
"typeof",
"command",
"==",
"'string'",
")",
"message",
"=",
"'{'",
"+",
"command",
"+",
"'} '",
"+",
"message",
";",
"message",
"=",
"'[command.io] '",
"+",
"message",
";",
"error",
"=",
"new",
"Error",
"(",
"message",
")",
";",
"Object",
".",
"defineProperties",
"(",
"this",
",",
"{",
"'stack'",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"error",
".",
"stack",
";",
"}",
"}",
",",
"message",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"error",
".",
"message",
";",
"}",
"}",
",",
"command",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"command",
";",
"}",
"}",
",",
"level",
":",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"level",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| ERRORS
Custom error object to manage exceptions on command's action.
@param string message The error message.
@param string command The command name what throw the error.
@param int level The severity level (1,2 or 3 to notice, error, critical).
@constructor | [
"ERRORS",
"Custom",
"error",
"object",
"to",
"manage",
"exceptions",
"on",
"command",
"s",
"action",
"."
]
| 3d3cdfac83b2e14e801a9fc94ced9024c757674f | https://github.com/Techniv/node-command-io/blob/3d3cdfac83b2e14e801a9fc94ced9024c757674f/libs/commandio.js#L354-L390 | train |
wigy/chronicles_of_grunt | lib/templates.js | substitute | function substitute(str, variables) {
// Based on Simple JavaScript Templating by
// John Resig - http://ejohn.org/blog/javascript-micro-templating/ - MIT Licensed
if (!cache[str]) {
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
try {
/*jshint -W054 */
cache[str] = new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'") +
"');}return p.join('');");
/*jshint +W054 */
} catch(e) {
grunt.fail.fatal("Failed to compile template:\n" + str);
}
}
return cache[str](variables || {});
} | javascript | function substitute(str, variables) {
// Based on Simple JavaScript Templating by
// John Resig - http://ejohn.org/blog/javascript-micro-templating/ - MIT Licensed
if (!cache[str]) {
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
try {
/*jshint -W054 */
cache[str] = new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'") +
"');}return p.join('');");
/*jshint +W054 */
} catch(e) {
grunt.fail.fatal("Failed to compile template:\n" + str);
}
}
return cache[str](variables || {});
} | [
"function",
"substitute",
"(",
"str",
",",
"variables",
")",
"{",
"if",
"(",
"!",
"cache",
"[",
"str",
"]",
")",
"{",
"try",
"{",
"cache",
"[",
"str",
"]",
"=",
"new",
"Function",
"(",
"\"obj\"",
",",
"\"var p=[],print=function(){p.push.apply(p,arguments);};\"",
"+",
"\"with(obj){p.push('\"",
"+",
"str",
".",
"replace",
"(",
"/",
"[\\r\\t\\n]",
"/",
"g",
",",
"\" \"",
")",
".",
"split",
"(",
"\"<%\"",
")",
".",
"join",
"(",
"\"\\t\"",
")",
".",
"\\t",
"replace",
".",
"(",
"/",
"((^|%>)[^\\t]*)'",
"/",
"g",
",",
"\"$1\\r\"",
")",
"\\r",
".",
"replace",
"(",
"/",
"\\t=(.*?)%>",
"/",
"g",
",",
"\"',$1,'\"",
")",
".",
"split",
"(",
"\"\\t\"",
")",
".",
"\\t",
"join",
".",
"(",
"\"');\"",
")",
"split",
".",
"(",
"\"%>\"",
")",
"join",
".",
"(",
"\"p.push('\"",
")",
"split",
"+",
"(",
"\"\\r\"",
")",
")",
";",
"}",
"\\r",
"}",
"join",
"}"
]
| Perform variable substitutions in the template.
@param str Content of the template as a string.
@param variables An object containing variable values.
Note that templating does not support single quotes. It also removes line feeds. | [
"Perform",
"variable",
"substitutions",
"in",
"the",
"template",
"."
]
| c5f089a6f391a0ca625fcb81ef51907713471bb3 | https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/templates.js#L39-L70 | train |
wigy/chronicles_of_grunt | lib/templates.js | generate | function generate(tmpl, src, variables) {
variables = variables || {};
variables.FILES = {};
for (var i = 0; i < src.length; i++) {
var content = JSON.stringify(grunt.file.read(src[i]));
variables.FILES[src[i]] = content;
}
var template = grunt.file.read(tmpl);
return substitute(template, variables);
} | javascript | function generate(tmpl, src, variables) {
variables = variables || {};
variables.FILES = {};
for (var i = 0; i < src.length; i++) {
var content = JSON.stringify(grunt.file.read(src[i]));
variables.FILES[src[i]] = content;
}
var template = grunt.file.read(tmpl);
return substitute(template, variables);
} | [
"function",
"generate",
"(",
"tmpl",
",",
"src",
",",
"variables",
")",
"{",
"variables",
"=",
"variables",
"||",
"{",
"}",
";",
"variables",
".",
"FILES",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"src",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"content",
"=",
"JSON",
".",
"stringify",
"(",
"grunt",
".",
"file",
".",
"read",
"(",
"src",
"[",
"i",
"]",
")",
")",
";",
"variables",
".",
"FILES",
"[",
"src",
"[",
"i",
"]",
"]",
"=",
"content",
";",
"}",
"var",
"template",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"tmpl",
")",
";",
"return",
"substitute",
"(",
"template",
",",
"variables",
")",
";",
"}"
]
| Generate a file based on the template and source files.
@param tmpl Path to the template file.
@param src An array of source files.
@param variables Initial variables as an object.
@return A string with template substitutions made. | [
"Generate",
"a",
"file",
"based",
"on",
"the",
"template",
"and",
"source",
"files",
"."
]
| c5f089a6f391a0ca625fcb81ef51907713471bb3 | https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/templates.js#L80-L89 | train |
melvincarvalho/rdf-shell | lib/util.js | putStorage | function putStorage(host, path, data, cert, callback) {
var protocol = 'https://'
var ldp = {
hostname: host,
rejectUnauthorized: false,
port: 443,
method: 'PUT',
headers: {'Content-Type': 'text/turtle'}
}
if (cert) {
ldp.key = fs.readFileSync(cert)
ldp.cert = fs.readFileSync(cert)
}
// put file to ldp
ldp.path = path
debug('sending to : ' + protocol + host + path)
var put = https.request(ldp, function(res) {
chunks = ''
debug('STATUS: ' + res.statusCode)
debug('HEADERS: ' + JSON.stringify(res.headers))
res.on('data', function (chunk) {
chunks += chunk
})
res.on('end', function (chunk) {
callback(null, chunks, ldp)
})
})
put.on('error', function(e) {
callback(e)
})
put.write(data)
put.end()
} | javascript | function putStorage(host, path, data, cert, callback) {
var protocol = 'https://'
var ldp = {
hostname: host,
rejectUnauthorized: false,
port: 443,
method: 'PUT',
headers: {'Content-Type': 'text/turtle'}
}
if (cert) {
ldp.key = fs.readFileSync(cert)
ldp.cert = fs.readFileSync(cert)
}
// put file to ldp
ldp.path = path
debug('sending to : ' + protocol + host + path)
var put = https.request(ldp, function(res) {
chunks = ''
debug('STATUS: ' + res.statusCode)
debug('HEADERS: ' + JSON.stringify(res.headers))
res.on('data', function (chunk) {
chunks += chunk
})
res.on('end', function (chunk) {
callback(null, chunks, ldp)
})
})
put.on('error', function(e) {
callback(e)
})
put.write(data)
put.end()
} | [
"function",
"putStorage",
"(",
"host",
",",
"path",
",",
"data",
",",
"cert",
",",
"callback",
")",
"{",
"var",
"protocol",
"=",
"'https://'",
"var",
"ldp",
"=",
"{",
"hostname",
":",
"host",
",",
"rejectUnauthorized",
":",
"false",
",",
"port",
":",
"443",
",",
"method",
":",
"'PUT'",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'text/turtle'",
"}",
"}",
"if",
"(",
"cert",
")",
"{",
"ldp",
".",
"key",
"=",
"fs",
".",
"readFileSync",
"(",
"cert",
")",
"ldp",
".",
"cert",
"=",
"fs",
".",
"readFileSync",
"(",
"cert",
")",
"}",
"ldp",
".",
"path",
"=",
"path",
"debug",
"(",
"'sending to : '",
"+",
"protocol",
"+",
"host",
"+",
"path",
")",
"var",
"put",
"=",
"https",
".",
"request",
"(",
"ldp",
",",
"function",
"(",
"res",
")",
"{",
"chunks",
"=",
"''",
"debug",
"(",
"'STATUS: '",
"+",
"res",
".",
"statusCode",
")",
"debug",
"(",
"'HEADERS: '",
"+",
"JSON",
".",
"stringify",
"(",
"res",
".",
"headers",
")",
")",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"chunk",
")",
"{",
"chunks",
"+=",
"chunk",
"}",
")",
"res",
".",
"on",
"(",
"'end'",
",",
"function",
"(",
"chunk",
")",
"{",
"callback",
"(",
"null",
",",
"chunks",
",",
"ldp",
")",
"}",
")",
"}",
")",
"put",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"e",
")",
"{",
"callback",
"(",
"e",
")",
"}",
")",
"put",
".",
"write",
"(",
"data",
")",
"put",
".",
"end",
"(",
")",
"}"
]
| putStorage Sends turtle data to remote storage via put request
@param {String} host The host to send to
@param {String} path The path relative to host
@param {String} data The turtle to send
@param {String} cert Certificate path used for auth
@param {Function} callback Callback with error or response | [
"putStorage",
"Sends",
"turtle",
"data",
"to",
"remote",
"storage",
"via",
"put",
"request"
]
| bf2015f6f333855e69a18ce3ec9e917bbddfb425 | https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/util.js#L72-L109 | train |
melvincarvalho/rdf-shell | lib/util.js | is | function is(store, uri, type) {
var ret = false
var types = store.findTypeURIs($rdf.sym(uri))
if (types && types[type]) {
ret = true
}
return ret
} | javascript | function is(store, uri, type) {
var ret = false
var types = store.findTypeURIs($rdf.sym(uri))
if (types && types[type]) {
ret = true
}
return ret
} | [
"function",
"is",
"(",
"store",
",",
"uri",
",",
"type",
")",
"{",
"var",
"ret",
"=",
"false",
"var",
"types",
"=",
"store",
".",
"findTypeURIs",
"(",
"$rdf",
".",
"sym",
"(",
"uri",
")",
")",
"if",
"(",
"types",
"&&",
"types",
"[",
"type",
"]",
")",
"{",
"ret",
"=",
"true",
"}",
"return",
"ret",
"}"
]
| See if a URI is a certain type
@param {object} store the rdflib store
@param {string} uri the uri to check
@param {string} type the type to test
@return {Boolean} true if uri is that type | [
"See",
"if",
"a",
"URI",
"is",
"a",
"certain",
"type"
]
| bf2015f6f333855e69a18ce3ec9e917bbddfb425 | https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/lib/util.js#L362-L372 | train |
kaelzhang/typo-rgb | lib/rgb.js | to_rgb | function to_rgb(obj){
return [obj.R, obj.G, obj.B].map(format_number).join('');
} | javascript | function to_rgb(obj){
return [obj.R, obj.G, obj.B].map(format_number).join('');
} | [
"function",
"to_rgb",
"(",
"obj",
")",
"{",
"return",
"[",
"obj",
".",
"R",
",",
"obj",
".",
"G",
",",
"obj",
".",
"B",
"]",
".",
"map",
"(",
"format_number",
")",
".",
"join",
"(",
"''",
")",
";",
"}"
]
| reversed method of `rgb_2_object` | [
"reversed",
"method",
"of",
"rgb_2_object"
]
| 27a0498bb291fbda8c33e4c9568fc9ae5d539edb | https://github.com/kaelzhang/typo-rgb/blob/27a0498bb291fbda8c33e4c9568fc9ae5d539edb/lib/rgb.js#L313-L315 | train |
benzhou1/iod | lib/iod.js | function(results) {
// Only do so if `callback` is specified
if (IODOpts.callback) {
var options = { url: IODOpts.callback.uri }
var res = JSON.stringify(results)
// Url-encode use `form` property
if (IODOpts.callback.method === 'encoded') {
options.form = { results: res }
}
var r = request.post(options, function(err, res) {
// Emits `CbError` if any error occurs while sending results to callback
if (err) IOD.eventEmitter.emit('CbError', err)
else if (res.statusCode !== 200) {
IOD.eventEmitter.emit('CbError', 'Status Code: ' + res.statusCode)
}
})
// Multipart use form object
if (IODOpts.callback.method === 'multipart') {
var form = r.form()
form.append('results', res)
form.on('error', function(err) {
IOD.evenEmitter.emit('CBError', err)
})
}
}
} | javascript | function(results) {
// Only do so if `callback` is specified
if (IODOpts.callback) {
var options = { url: IODOpts.callback.uri }
var res = JSON.stringify(results)
// Url-encode use `form` property
if (IODOpts.callback.method === 'encoded') {
options.form = { results: res }
}
var r = request.post(options, function(err, res) {
// Emits `CbError` if any error occurs while sending results to callback
if (err) IOD.eventEmitter.emit('CbError', err)
else if (res.statusCode !== 200) {
IOD.eventEmitter.emit('CbError', 'Status Code: ' + res.statusCode)
}
})
// Multipart use form object
if (IODOpts.callback.method === 'multipart') {
var form = r.form()
form.append('results', res)
form.on('error', function(err) {
IOD.evenEmitter.emit('CBError', err)
})
}
}
} | [
"function",
"(",
"results",
")",
"{",
"if",
"(",
"IODOpts",
".",
"callback",
")",
"{",
"var",
"options",
"=",
"{",
"url",
":",
"IODOpts",
".",
"callback",
".",
"uri",
"}",
"var",
"res",
"=",
"JSON",
".",
"stringify",
"(",
"results",
")",
"if",
"(",
"IODOpts",
".",
"callback",
".",
"method",
"===",
"'encoded'",
")",
"{",
"options",
".",
"form",
"=",
"{",
"results",
":",
"res",
"}",
"}",
"var",
"r",
"=",
"request",
".",
"post",
"(",
"options",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"IOD",
".",
"eventEmitter",
".",
"emit",
"(",
"'CbError'",
",",
"err",
")",
"else",
"if",
"(",
"res",
".",
"statusCode",
"!==",
"200",
")",
"{",
"IOD",
".",
"eventEmitter",
".",
"emit",
"(",
"'CbError'",
",",
"'Status Code: '",
"+",
"res",
".",
"statusCode",
")",
"}",
"}",
")",
"if",
"(",
"IODOpts",
".",
"callback",
".",
"method",
"===",
"'multipart'",
")",
"{",
"var",
"form",
"=",
"r",
".",
"form",
"(",
")",
"form",
".",
"append",
"(",
"'results'",
",",
"res",
")",
"form",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"IOD",
".",
"evenEmitter",
".",
"emit",
"(",
"'CBError'",
",",
"err",
")",
"}",
")",
"}",
"}",
"}"
]
| Sends results of request to specified callback.
@param {*} results - Results of request | [
"Sends",
"results",
"of",
"request",
"to",
"specified",
"callback",
"."
]
| a346628f9bc5e4420e4d00e8f21c4cb268b6237c | https://github.com/benzhou1/iod/blob/a346628f9bc5e4420e4d00e8f21c4cb268b6237c/lib/iod.js#L236-L265 | train |
|
benzhou1/iod | lib/iod.js | function(jobId) {
var isFinished = function(res) {
return res && res.status &&
(res.status === 'finished' || res.status === 'failed')
}
var poll = function() {
IOD.status({ jobId: jobId }, function(err, res) {
// Emits err as first argument
if (err) IOD.eventEmitter.emit(jobId, err)
else if (isFinished(res)) {
IOD.eventEmitter.emit(jobId, null, res)
sendCallback(res)
}
else setTimeout(poll, IODOpts.pollInterval)
})
}
setTimeout(poll, IODOpts.pollInterval)
} | javascript | function(jobId) {
var isFinished = function(res) {
return res && res.status &&
(res.status === 'finished' || res.status === 'failed')
}
var poll = function() {
IOD.status({ jobId: jobId }, function(err, res) {
// Emits err as first argument
if (err) IOD.eventEmitter.emit(jobId, err)
else if (isFinished(res)) {
IOD.eventEmitter.emit(jobId, null, res)
sendCallback(res)
}
else setTimeout(poll, IODOpts.pollInterval)
})
}
setTimeout(poll, IODOpts.pollInterval)
} | [
"function",
"(",
"jobId",
")",
"{",
"var",
"isFinished",
"=",
"function",
"(",
"res",
")",
"{",
"return",
"res",
"&&",
"res",
".",
"status",
"&&",
"(",
"res",
".",
"status",
"===",
"'finished'",
"||",
"res",
".",
"status",
"===",
"'failed'",
")",
"}",
"var",
"poll",
"=",
"function",
"(",
")",
"{",
"IOD",
".",
"status",
"(",
"{",
"jobId",
":",
"jobId",
"}",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"IOD",
".",
"eventEmitter",
".",
"emit",
"(",
"jobId",
",",
"err",
")",
"else",
"if",
"(",
"isFinished",
"(",
"res",
")",
")",
"{",
"IOD",
".",
"eventEmitter",
".",
"emit",
"(",
"jobId",
",",
"null",
",",
"res",
")",
"sendCallback",
"(",
"res",
")",
"}",
"else",
"setTimeout",
"(",
"poll",
",",
"IODOpts",
".",
"pollInterval",
")",
"}",
")",
"}",
"setTimeout",
"(",
"poll",
",",
"IODOpts",
".",
"pollInterval",
")",
"}"
]
| Periodically get status of a job with specified job id `jobId`.
Do so until job has finished or failed.
@param {String} jobId - Job id | [
"Periodically",
"get",
"status",
"of",
"a",
"job",
"with",
"specified",
"job",
"id",
"jobId",
".",
"Do",
"so",
"until",
"job",
"has",
"finished",
"or",
"failed",
"."
]
| a346628f9bc5e4420e4d00e8f21c4cb268b6237c | https://github.com/benzhou1/iod/blob/a346628f9bc5e4420e4d00e8f21c4cb268b6237c/lib/iod.js#L273-L292 | train |
|
benzhou1/iod | lib/iod.js | function(asyncRes, callback) {
var jobId = asyncRes.jobID
if (!jobId) return callback(null, asyncRes)
else if (IODOpts.getResults) {
IOD.result({
jobId: jobId,
majorVersion: IODOpts.majorVersion,
retries: 3
}, callback)
}
else {
callback(null, asyncRes)
pollUntilDone(jobId)
}
} | javascript | function(asyncRes, callback) {
var jobId = asyncRes.jobID
if (!jobId) return callback(null, asyncRes)
else if (IODOpts.getResults) {
IOD.result({
jobId: jobId,
majorVersion: IODOpts.majorVersion,
retries: 3
}, callback)
}
else {
callback(null, asyncRes)
pollUntilDone(jobId)
}
} | [
"function",
"(",
"asyncRes",
",",
"callback",
")",
"{",
"var",
"jobId",
"=",
"asyncRes",
".",
"jobID",
"if",
"(",
"!",
"jobId",
")",
"return",
"callback",
"(",
"null",
",",
"asyncRes",
")",
"else",
"if",
"(",
"IODOpts",
".",
"getResults",
")",
"{",
"IOD",
".",
"result",
"(",
"{",
"jobId",
":",
"jobId",
",",
"majorVersion",
":",
"IODOpts",
".",
"majorVersion",
",",
"retries",
":",
"3",
"}",
",",
"callback",
")",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"asyncRes",
")",
"pollUntilDone",
"(",
"jobId",
")",
"}",
"}"
]
| If getResults is true and jobId is found, send IOD result request.
@param {Object} asyncRes - Async request response
@param {Function} callback - Callback(err, IOD response)) | [
"If",
"getResults",
"is",
"true",
"and",
"jobId",
"is",
"found",
"send",
"IOD",
"result",
"request",
"."
]
| a346628f9bc5e4420e4d00e8f21c4cb268b6237c | https://github.com/benzhou1/iod/blob/a346628f9bc5e4420e4d00e8f21c4cb268b6237c/lib/iod.js#L300-L316 | train |
|
JohnnieFucker/dreamix-admin | lib/modules/scripts.js | list | function list(scriptModule, agent, msg, cb) {
const servers = [];
const scripts = [];
const idMap = agent.idMap;
for (const sid in idMap) {
if (idMap.hasOwnProperty(sid)) {
servers.push(sid);
}
}
fs.readdir(scriptModule.root, (err, filenames) => {
if (err) {
filenames = [];
}
for (let i = 0, l = filenames.length; i < l; i++) {
scripts.push(filenames[i]);
}
cb(null, {
servers: servers,
scripts: scripts
});
});
} | javascript | function list(scriptModule, agent, msg, cb) {
const servers = [];
const scripts = [];
const idMap = agent.idMap;
for (const sid in idMap) {
if (idMap.hasOwnProperty(sid)) {
servers.push(sid);
}
}
fs.readdir(scriptModule.root, (err, filenames) => {
if (err) {
filenames = [];
}
for (let i = 0, l = filenames.length; i < l; i++) {
scripts.push(filenames[i]);
}
cb(null, {
servers: servers,
scripts: scripts
});
});
} | [
"function",
"list",
"(",
"scriptModule",
",",
"agent",
",",
"msg",
",",
"cb",
")",
"{",
"const",
"servers",
"=",
"[",
"]",
";",
"const",
"scripts",
"=",
"[",
"]",
";",
"const",
"idMap",
"=",
"agent",
".",
"idMap",
";",
"for",
"(",
"const",
"sid",
"in",
"idMap",
")",
"{",
"if",
"(",
"idMap",
".",
"hasOwnProperty",
"(",
"sid",
")",
")",
"{",
"servers",
".",
"push",
"(",
"sid",
")",
";",
"}",
"}",
"fs",
".",
"readdir",
"(",
"scriptModule",
".",
"root",
",",
"(",
"err",
",",
"filenames",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"filenames",
"=",
"[",
"]",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"filenames",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"scripts",
".",
"push",
"(",
"filenames",
"[",
"i",
"]",
")",
";",
"}",
"cb",
"(",
"null",
",",
"{",
"servers",
":",
"servers",
",",
"scripts",
":",
"scripts",
"}",
")",
";",
"}",
")",
";",
"}"
]
| List server id and scripts file name | [
"List",
"server",
"id",
"and",
"scripts",
"file",
"name"
]
| fc169e2481d5a7456725fb33f7a7907e0776ef79 | https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/modules/scripts.js#L13-L37 | train |
JohnnieFucker/dreamix-admin | lib/modules/scripts.js | get | function get(scriptModule, agent, msg, cb) {
const filename = msg.filename;
if (!filename) {
cb('empty filename');
return;
}
fs.readFile(path.join(scriptModule.root, filename), 'utf-8', (err, data) => {
if (err) {
logger.error(`fail to read script file:${filename}, ${err.stack}`);
cb(`fail to read script with name:${filename}`);
}
cb(null, data);
});
} | javascript | function get(scriptModule, agent, msg, cb) {
const filename = msg.filename;
if (!filename) {
cb('empty filename');
return;
}
fs.readFile(path.join(scriptModule.root, filename), 'utf-8', (err, data) => {
if (err) {
logger.error(`fail to read script file:${filename}, ${err.stack}`);
cb(`fail to read script with name:${filename}`);
}
cb(null, data);
});
} | [
"function",
"get",
"(",
"scriptModule",
",",
"agent",
",",
"msg",
",",
"cb",
")",
"{",
"const",
"filename",
"=",
"msg",
".",
"filename",
";",
"if",
"(",
"!",
"filename",
")",
"{",
"cb",
"(",
"'empty filename'",
")",
";",
"return",
";",
"}",
"fs",
".",
"readFile",
"(",
"path",
".",
"join",
"(",
"scriptModule",
".",
"root",
",",
"filename",
")",
",",
"'utf-8'",
",",
"(",
"err",
",",
"data",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"`",
"${",
"filename",
"}",
"${",
"err",
".",
"stack",
"}",
"`",
")",
";",
"cb",
"(",
"`",
"${",
"filename",
"}",
"`",
")",
";",
"}",
"cb",
"(",
"null",
",",
"data",
")",
";",
"}",
")",
";",
"}"
]
| Get the content of the script file | [
"Get",
"the",
"content",
"of",
"the",
"script",
"file"
]
| fc169e2481d5a7456725fb33f7a7907e0776ef79 | https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/modules/scripts.js#L42-L57 | train |
JohnnieFucker/dreamix-admin | lib/modules/scripts.js | save | function save(scriptModule, agent, msg, cb) {
const filepath = path.join(scriptModule.root, msg.filename);
fs.writeFile(filepath, msg.body, (err) => {
if (err) {
logger.error(`fail to write script file:${msg.filename}, ${err.stack}`);
cb(`fail to write script file:${msg.filename}`);
return;
}
cb();
});
} | javascript | function save(scriptModule, agent, msg, cb) {
const filepath = path.join(scriptModule.root, msg.filename);
fs.writeFile(filepath, msg.body, (err) => {
if (err) {
logger.error(`fail to write script file:${msg.filename}, ${err.stack}`);
cb(`fail to write script file:${msg.filename}`);
return;
}
cb();
});
} | [
"function",
"save",
"(",
"scriptModule",
",",
"agent",
",",
"msg",
",",
"cb",
")",
"{",
"const",
"filepath",
"=",
"path",
".",
"join",
"(",
"scriptModule",
".",
"root",
",",
"msg",
".",
"filename",
")",
";",
"fs",
".",
"writeFile",
"(",
"filepath",
",",
"msg",
".",
"body",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"logger",
".",
"error",
"(",
"`",
"${",
"msg",
".",
"filename",
"}",
"${",
"err",
".",
"stack",
"}",
"`",
")",
";",
"cb",
"(",
"`",
"${",
"msg",
".",
"filename",
"}",
"`",
")",
";",
"return",
";",
"}",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
]
| Save a script file that posted from admin console | [
"Save",
"a",
"script",
"file",
"that",
"posted",
"from",
"admin",
"console"
]
| fc169e2481d5a7456725fb33f7a7907e0776ef79 | https://github.com/JohnnieFucker/dreamix-admin/blob/fc169e2481d5a7456725fb33f7a7907e0776ef79/lib/modules/scripts.js#L62-L74 | train |
melvincarvalho/rdf-shell | bin/cat.js | bin | function bin(argv) {
if (!argv[2]) {
console.error("url is required")
console.error("Usage : cat <url>")
process.exit(-1)
}
shell.cat(argv[2], function(err, res, uri) {
if (err) {
console.error(err)
} else {
console.log(res)
}
})
} | javascript | function bin(argv) {
if (!argv[2]) {
console.error("url is required")
console.error("Usage : cat <url>")
process.exit(-1)
}
shell.cat(argv[2], function(err, res, uri) {
if (err) {
console.error(err)
} else {
console.log(res)
}
})
} | [
"function",
"bin",
"(",
"argv",
")",
"{",
"if",
"(",
"!",
"argv",
"[",
"2",
"]",
")",
"{",
"console",
".",
"error",
"(",
"\"url is required\"",
")",
"console",
".",
"error",
"(",
"\"Usage : cat <url>\"",
")",
"process",
".",
"exit",
"(",
"-",
"1",
")",
"}",
"shell",
".",
"cat",
"(",
"argv",
"[",
"2",
"]",
",",
"function",
"(",
"err",
",",
"res",
",",
"uri",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"res",
")",
"}",
"}",
")",
"}"
]
| cat as a command
@param {Array} argv Args, argv[2] is the uri | [
"cat",
"as",
"a",
"command"
]
| bf2015f6f333855e69a18ce3ec9e917bbddfb425 | https://github.com/melvincarvalho/rdf-shell/blob/bf2015f6f333855e69a18ce3ec9e917bbddfb425/bin/cat.js#L9-L22 | train |
oleics/node-xcouch | registry.js | connectUser | function connectUser(name, pass, cb) {
loginUser(name, pass, function(err, user) {
if(err) return cb(err)
var nano = NANO(_ci.protocol+'//'+encodeURIComponent(name)+':'+encodeURIComponent(pass)+'@'+_ci.host+'/')
, db = nano.use(name)
;
function getObject(type, id, rev) {
var ctor = registry[type]
, obj = new ctor(id, rev)
obj.type(type)
if(ctor.dbname) {
obj.db = nano.use(ctor.dbname)
} else {
obj.db = db
}
obj.getObject = getObject
return obj
}
cb(null, user, getObject, db, nano)
})
} | javascript | function connectUser(name, pass, cb) {
loginUser(name, pass, function(err, user) {
if(err) return cb(err)
var nano = NANO(_ci.protocol+'//'+encodeURIComponent(name)+':'+encodeURIComponent(pass)+'@'+_ci.host+'/')
, db = nano.use(name)
;
function getObject(type, id, rev) {
var ctor = registry[type]
, obj = new ctor(id, rev)
obj.type(type)
if(ctor.dbname) {
obj.db = nano.use(ctor.dbname)
} else {
obj.db = db
}
obj.getObject = getObject
return obj
}
cb(null, user, getObject, db, nano)
})
} | [
"function",
"connectUser",
"(",
"name",
",",
"pass",
",",
"cb",
")",
"{",
"loginUser",
"(",
"name",
",",
"pass",
",",
"function",
"(",
"err",
",",
"user",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"var",
"nano",
"=",
"NANO",
"(",
"_ci",
".",
"protocol",
"+",
"'//'",
"+",
"encodeURIComponent",
"(",
"name",
")",
"+",
"':'",
"+",
"encodeURIComponent",
"(",
"pass",
")",
"+",
"'@'",
"+",
"_ci",
".",
"host",
"+",
"'/'",
")",
",",
"db",
"=",
"nano",
".",
"use",
"(",
"name",
")",
";",
"function",
"getObject",
"(",
"type",
",",
"id",
",",
"rev",
")",
"{",
"var",
"ctor",
"=",
"registry",
"[",
"type",
"]",
",",
"obj",
"=",
"new",
"ctor",
"(",
"id",
",",
"rev",
")",
"obj",
".",
"type",
"(",
"type",
")",
"if",
"(",
"ctor",
".",
"dbname",
")",
"{",
"obj",
".",
"db",
"=",
"nano",
".",
"use",
"(",
"ctor",
".",
"dbname",
")",
"}",
"else",
"{",
"obj",
".",
"db",
"=",
"db",
"}",
"obj",
".",
"getObject",
"=",
"getObject",
"return",
"obj",
"}",
"cb",
"(",
"null",
",",
"user",
",",
"getObject",
",",
"db",
",",
"nano",
")",
"}",
")",
"}"
]
| Connects a user | [
"Connects",
"a",
"user"
]
| 47e492235b8e6c7235c7f8807725a3bb51fb44ba | https://github.com/oleics/node-xcouch/blob/47e492235b8e6c7235c7f8807725a3bb51fb44ba/registry.js#L141-L164 | train |
oleics/node-xcouch | registry.js | createDatabase | function createDatabase(name, cb) {
nano().db.create(name, function(err) {
if(err && err.status_code !== 412) return cb(err)
cb(null, err ? false : true)
})
} | javascript | function createDatabase(name, cb) {
nano().db.create(name, function(err) {
if(err && err.status_code !== 412) return cb(err)
cb(null, err ? false : true)
})
} | [
"function",
"createDatabase",
"(",
"name",
",",
"cb",
")",
"{",
"nano",
"(",
")",
".",
"db",
".",
"create",
"(",
"name",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"status_code",
"!==",
"412",
")",
"return",
"cb",
"(",
"err",
")",
"cb",
"(",
"null",
",",
"err",
"?",
"false",
":",
"true",
")",
"}",
")",
"}"
]
| Creates a database We assume that every database belongs to exactly one user. Both share the same name. | [
"Creates",
"a",
"database",
"We",
"assume",
"that",
"every",
"database",
"belongs",
"to",
"exactly",
"one",
"user",
".",
"Both",
"share",
"the",
"same",
"name",
"."
]
| 47e492235b8e6c7235c7f8807725a3bb51fb44ba | https://github.com/oleics/node-xcouch/blob/47e492235b8e6c7235c7f8807725a3bb51fb44ba/registry.js#L209-L214 | train |
oleics/node-xcouch | registry.js | setDatabaseSecurity | function setDatabaseSecurity(name, cb) {
// Get _security first
getSecurity(name, function(err, d) {
if(err) return cb(err)
// Make name an admin
if(d.admins.names.indexOf(name) === -1) {
d.admins.names.push(name)
}
// Make name a reader
if(d.readers.names.indexOf(name) === -1) {
d.readers.names.push(name)
}
// Merge with _security template
d = mergeSecurity(_security, d)
// Apply changes
setSecurity(name, d, function(err) {
if(err) return cb(err)
cb()
})
})
} | javascript | function setDatabaseSecurity(name, cb) {
// Get _security first
getSecurity(name, function(err, d) {
if(err) return cb(err)
// Make name an admin
if(d.admins.names.indexOf(name) === -1) {
d.admins.names.push(name)
}
// Make name a reader
if(d.readers.names.indexOf(name) === -1) {
d.readers.names.push(name)
}
// Merge with _security template
d = mergeSecurity(_security, d)
// Apply changes
setSecurity(name, d, function(err) {
if(err) return cb(err)
cb()
})
})
} | [
"function",
"setDatabaseSecurity",
"(",
"name",
",",
"cb",
")",
"{",
"getSecurity",
"(",
"name",
",",
"function",
"(",
"err",
",",
"d",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"if",
"(",
"d",
".",
"admins",
".",
"names",
".",
"indexOf",
"(",
"name",
")",
"===",
"-",
"1",
")",
"{",
"d",
".",
"admins",
".",
"names",
".",
"push",
"(",
"name",
")",
"}",
"if",
"(",
"d",
".",
"readers",
".",
"names",
".",
"indexOf",
"(",
"name",
")",
"===",
"-",
"1",
")",
"{",
"d",
".",
"readers",
".",
"names",
".",
"push",
"(",
"name",
")",
"}",
"d",
"=",
"mergeSecurity",
"(",
"_security",
",",
"d",
")",
"setSecurity",
"(",
"name",
",",
"d",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"cb",
"(",
")",
"}",
")",
"}",
")",
"}"
]
| Sets the _security document of a database | [
"Sets",
"the",
"_security",
"document",
"of",
"a",
"database"
]
| 47e492235b8e6c7235c7f8807725a3bb51fb44ba | https://github.com/oleics/node-xcouch/blob/47e492235b8e6c7235c7f8807725a3bb51fb44ba/registry.js#L217-L241 | train |
oleics/node-xcouch | registry.js | loginUser | function loginUser(name, pass, cb) {
// Get the user
var db = nano().use(user_dbname)
db.get(user_namespace+':'+name, function(err, doc) {
if(err) return cb(err)
// Check pass
var hash = crypto.createHash('sha1')
hash.update(pass)
hash.update(doc.salt)
var password_sha = hash.digest('hex')
if(doc.password_sha === password_sha) {
return cb(null, doc)
}
cb(new Error('Access denied.'))
})
} | javascript | function loginUser(name, pass, cb) {
// Get the user
var db = nano().use(user_dbname)
db.get(user_namespace+':'+name, function(err, doc) {
if(err) return cb(err)
// Check pass
var hash = crypto.createHash('sha1')
hash.update(pass)
hash.update(doc.salt)
var password_sha = hash.digest('hex')
if(doc.password_sha === password_sha) {
return cb(null, doc)
}
cb(new Error('Access denied.'))
})
} | [
"function",
"loginUser",
"(",
"name",
",",
"pass",
",",
"cb",
")",
"{",
"var",
"db",
"=",
"nano",
"(",
")",
".",
"use",
"(",
"user_dbname",
")",
"db",
".",
"get",
"(",
"user_namespace",
"+",
"':'",
"+",
"name",
",",
"function",
"(",
"err",
",",
"doc",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"var",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'sha1'",
")",
"hash",
".",
"update",
"(",
"pass",
")",
"hash",
".",
"update",
"(",
"doc",
".",
"salt",
")",
"var",
"password_sha",
"=",
"hash",
".",
"digest",
"(",
"'hex'",
")",
"if",
"(",
"doc",
".",
"password_sha",
"===",
"password_sha",
")",
"{",
"return",
"cb",
"(",
"null",
",",
"doc",
")",
"}",
"cb",
"(",
"new",
"Error",
"(",
"'Access denied.'",
")",
")",
"}",
")",
"}"
]
| Checks loginUser credenciales | [
"Checks",
"loginUser",
"credenciales"
]
| 47e492235b8e6c7235c7f8807725a3bb51fb44ba | https://github.com/oleics/node-xcouch/blob/47e492235b8e6c7235c7f8807725a3bb51fb44ba/registry.js#L244-L261 | train |
oleics/node-xcouch | registry.js | destroyDatabase | function destroyDatabase(name, cb) {
if(name === user_dbname)
throw new Error('We never ever delete that database.')
nano().db.destroy(name, function(err) {
if(err && err.status_code !== 404) return cb(err)
cb(null, err ? false : true)
})
} | javascript | function destroyDatabase(name, cb) {
if(name === user_dbname)
throw new Error('We never ever delete that database.')
nano().db.destroy(name, function(err) {
if(err && err.status_code !== 404) return cb(err)
cb(null, err ? false : true)
})
} | [
"function",
"destroyDatabase",
"(",
"name",
",",
"cb",
")",
"{",
"if",
"(",
"name",
"===",
"user_dbname",
")",
"throw",
"new",
"Error",
"(",
"'We never ever delete that database.'",
")",
"nano",
"(",
")",
".",
"db",
".",
"destroy",
"(",
"name",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
"&&",
"err",
".",
"status_code",
"!==",
"404",
")",
"return",
"cb",
"(",
"err",
")",
"cb",
"(",
"null",
",",
"err",
"?",
"false",
":",
"true",
")",
"}",
")",
"}"
]
| Destroys a database | [
"Destroys",
"a",
"database"
]
| 47e492235b8e6c7235c7f8807725a3bb51fb44ba | https://github.com/oleics/node-xcouch/blob/47e492235b8e6c7235c7f8807725a3bb51fb44ba/registry.js#L264-L271 | train |
oleics/node-xcouch | registry.js | destroyUser | function destroyUser(name, pass, cb) {
loginUser(name, pass, function(err, user) {
if(err) return cb(err)
nano().use(user_dbname).destroy(user._id, user._rev, function(err, doc) {
if(err) return cb(err)
user._id = doc.id
user._rev = doc.rev
destroyDatabase(name, function(err) {
if(err) return cb(err)
cb(null, user)
})
})
})
// var db = nano().use(user_dbname)
// db.head(user_namespace+':'+name, function(err, b, h) {
// if(err) return cb(err)
// db.destroy(user_namespace+':'+name, JSON.parse(h.etag), function(err, doc) {
// if(err) return cb(err)
// destroyDatabase(name, function(err) {
// if(err) return cb(err)
// cb(null, doc)
// })
// })
// })
} | javascript | function destroyUser(name, pass, cb) {
loginUser(name, pass, function(err, user) {
if(err) return cb(err)
nano().use(user_dbname).destroy(user._id, user._rev, function(err, doc) {
if(err) return cb(err)
user._id = doc.id
user._rev = doc.rev
destroyDatabase(name, function(err) {
if(err) return cb(err)
cb(null, user)
})
})
})
// var db = nano().use(user_dbname)
// db.head(user_namespace+':'+name, function(err, b, h) {
// if(err) return cb(err)
// db.destroy(user_namespace+':'+name, JSON.parse(h.etag), function(err, doc) {
// if(err) return cb(err)
// destroyDatabase(name, function(err) {
// if(err) return cb(err)
// cb(null, doc)
// })
// })
// })
} | [
"function",
"destroyUser",
"(",
"name",
",",
"pass",
",",
"cb",
")",
"{",
"loginUser",
"(",
"name",
",",
"pass",
",",
"function",
"(",
"err",
",",
"user",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"nano",
"(",
")",
".",
"use",
"(",
"user_dbname",
")",
".",
"destroy",
"(",
"user",
".",
"_id",
",",
"user",
".",
"_rev",
",",
"function",
"(",
"err",
",",
"doc",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"user",
".",
"_id",
"=",
"doc",
".",
"id",
"user",
".",
"_rev",
"=",
"doc",
".",
"rev",
"destroyDatabase",
"(",
"name",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"cb",
"(",
"err",
")",
"cb",
"(",
"null",
",",
"user",
")",
"}",
")",
"}",
")",
"}",
")",
"}"
]
| Destroys a user AND her database | [
"Destroys",
"a",
"user",
"AND",
"her",
"database"
]
| 47e492235b8e6c7235c7f8807725a3bb51fb44ba | https://github.com/oleics/node-xcouch/blob/47e492235b8e6c7235c7f8807725a3bb51fb44ba/registry.js#L274-L298 | train |
commenthol/streamss | lib/jsonarray.js | JsonArray | function JsonArray (options) {
if (!(this instanceof JsonArray)) {
return new JsonArray(options)
}
this.options = Object.assign({}, options, { objectMode: true })
this.count = 0
this.map = ['[\n', ',\n', '\n]\n']
if (this.options.validJson === false) {
this.map = ['', '\n', '\n']
}
if (this.options.stringify) {
this._transform = this._stringify
this._flush = function (done) {
this.push(this.map[2])
setTimeout(function () {
done()
}, 2)
}
} else {
this._transform = this._parse
}
Transform.call(this, _omit(this.options, ['error', 'validJson', 'stringify']))
return this
} | javascript | function JsonArray (options) {
if (!(this instanceof JsonArray)) {
return new JsonArray(options)
}
this.options = Object.assign({}, options, { objectMode: true })
this.count = 0
this.map = ['[\n', ',\n', '\n]\n']
if (this.options.validJson === false) {
this.map = ['', '\n', '\n']
}
if (this.options.stringify) {
this._transform = this._stringify
this._flush = function (done) {
this.push(this.map[2])
setTimeout(function () {
done()
}, 2)
}
} else {
this._transform = this._parse
}
Transform.call(this, _omit(this.options, ['error', 'validJson', 'stringify']))
return this
} | [
"function",
"JsonArray",
"(",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"JsonArray",
")",
")",
"{",
"return",
"new",
"JsonArray",
"(",
"options",
")",
"}",
"this",
".",
"options",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
",",
"{",
"objectMode",
":",
"true",
"}",
")",
"this",
".",
"count",
"=",
"0",
"this",
".",
"map",
"=",
"[",
"'[\\n'",
",",
"\\n",
",",
"',\\n'",
"]",
"\\n",
"'\\n]\\n'",
"\\n",
"\\n",
"}"
]
| JSON.parse a line and push as object down the pipe.
If `stringify: true` is set, a received object is stringified with JSON.stringify
The output of the stream will be a valid JSON array.
NOTE: Requires that the stream is split beforehand using `Split` or `SplitLine`.
@constructor
@param {Object} [options] - Stream Options `{encoding, highWaterMark, decodeStrings, ...}`
@param {Boolean} options.error - Emit parsing errors as `Error` objects. Default=false.
@param {Boolean} options.validJson - Write out a valid json file, which can be parsed as a whole. Default=true.
@param {Boolean} options.stringify - Transforms an object into a string using JSON.stringify. Default=false.
@return {Transform} A transform stream | [
"JSON",
".",
"parse",
"a",
"line",
"and",
"push",
"as",
"object",
"down",
"the",
"pipe",
"."
]
| cfef5d0ed30c7efe002018886e2e843c91d3558f | https://github.com/commenthol/streamss/blob/cfef5d0ed30c7efe002018886e2e843c91d3558f/lib/jsonarray.js#L29-L57 | train |
seiyugi/debuguy | lib/parser.js | pr_parse | function pr_parse(options) {
this.traverse(options, function (dir, item, out) {
fs.readFile(dir + item, function(err, data) {
console.log('adding log ' + dir + item);
if (err) {
console.log(err);
console.log(data);
return;
}
var source = data.toString();
var output;
// if no match in the file
if (!source.match(regex)) {
return;
}
output = source.replace(regex, replacer);
fs.writeFile(out + item, output, function(err) {
if (err) {
console.log(err);
} else {
console.log(out + item + ' was saved!');
}
});
});
});
} | javascript | function pr_parse(options) {
this.traverse(options, function (dir, item, out) {
fs.readFile(dir + item, function(err, data) {
console.log('adding log ' + dir + item);
if (err) {
console.log(err);
console.log(data);
return;
}
var source = data.toString();
var output;
// if no match in the file
if (!source.match(regex)) {
return;
}
output = source.replace(regex, replacer);
fs.writeFile(out + item, output, function(err) {
if (err) {
console.log(err);
} else {
console.log(out + item + ' was saved!');
}
});
});
});
} | [
"function",
"pr_parse",
"(",
"options",
")",
"{",
"this",
".",
"traverse",
"(",
"options",
",",
"function",
"(",
"dir",
",",
"item",
",",
"out",
")",
"{",
"fs",
".",
"readFile",
"(",
"dir",
"+",
"item",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"console",
".",
"log",
"(",
"'adding log '",
"+",
"dir",
"+",
"item",
")",
";",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"console",
".",
"log",
"(",
"data",
")",
";",
"return",
";",
"}",
"var",
"source",
"=",
"data",
".",
"toString",
"(",
")",
";",
"var",
"output",
";",
"if",
"(",
"!",
"source",
".",
"match",
"(",
"regex",
")",
")",
"{",
"return",
";",
"}",
"output",
"=",
"source",
".",
"replace",
"(",
"regex",
",",
"replacer",
")",
";",
"fs",
".",
"writeFile",
"(",
"out",
"+",
"item",
",",
"output",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"err",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"out",
"+",
"item",
"+",
"' was saved!'",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Replace debuguy comments to predifined condole logs.
@param {[type]} options [description]
@return {[type]} [description] | [
"Replace",
"debuguy",
"comments",
"to",
"predifined",
"condole",
"logs",
"."
]
| 60b18e44b9dd1bcc7a160aac56b570eec6e5e4b4 | https://github.com/seiyugi/debuguy/blob/60b18e44b9dd1bcc7a160aac56b570eec6e5e4b4/lib/parser.js#L169-L199 | train |
seiyugi/debuguy | lib/parser.js | pr_autolog | function pr_autolog(options) {
function espectRewrite(filepath, outpath, template) {
var autologret = require(template);
autologret(filepath, outpath);
}
function insertReturnLog(source, endLine) {
var sourceRet;
// Insert ending log at return statement.
sourceRet = source.replace(/(\s|;)return(\s|;)/g, "$1" + endLine + "return$2");
// Remove any ending log that added twice.
while(sourceRet.indexOf(endLine + endLine) !== -1) {
sourceRet = sourceRet.replace(endLine + endLine, endLine);
}
return sourceRet;
}
function insertEnterAndLeaveLog(item, node, functionName) {
var fnoutLine = 'var DEBOUT="debuguy,"' +
' + (new Date()).getTime() + ",' +
item.substring(0, item.lastIndexOf('.')) + '.' +
functionName + '@' +
node.loc.start.line + '";console.log(DEBOUT + ",ENTER," + Date.now());';
var fnEndLine = 'console.log(DEBOUT + ",LEAVE," + Date.now());';
var startLine = node.getSource().indexOf('{') + 1;
var endLine = node.getSource().lastIndexOf('}');
var source = node.getSource().substr(0, startLine) + fnoutLine +
node.getSource().substr(startLine, endLine - startLine) + fnEndLine +
node.getSource().substr(endLine);
source = insertReturnLog(source, fnEndLine);
return source;
}
function insertEnterLog(item, node, functionName) {
var fnoutLine = '\nconsole.log("debuguy,"' +
' + (new Date()).getTime() + ",' +
item.substring(0, item.lastIndexOf('.')) + '.' +
functionName + '@' +
node.loc.start.line + '");';
var startLine = node.getSource().indexOf('{') + 1;
var source = node.getSource().substr(0, startLine) + fnoutLine +
node.getSource().substr(startLine);
return source;
}
this.traverse(options, function insertLog (dir, item, out) {
if (options.xEspect) {
var templatefile = __dirname + '/autolog.esp.js';
if ('string' === typeof options.xEspect) {
templatefile = options.xEspect;
}
espectRewrite(dir + item, out + item, templatefile);
return;
}
fs.readFile(dir + item, function(err, data) {
console.log('adding log ' + dir + item);
if (err) {
console.log(err);
console.log(data);
return;
}
var text = data.toString();
var output;
try {
output = esprimaTraversal(text, {loc:true})
.traverse(function (node) {
if (node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression') {
// Get the name of the function
var functionName = 'anonymous';
if (node.id) {
functionName = node.id.name;
} else if (node.parent) {
switch (node.parent.type) {
case 'VariableDeclarator':
functionName = node.parent.id.name;
break;
case 'Property':
functionName = node.parent.key.name;
break;
case 'AssignmentExpression':
if (node.parent.left.type === 'MemberExpression') {
functionName = node.parent.left.property.name ||
node.parent.left.property.value;
}
else if (node.parent.left.type === 'Identifier') {
functionName = node.parent.left.name;
}
break;
}
}
// Build the console log output
var source;
if (options.callStackGraph) {
source = insertEnterAndLeaveLog(item, node, functionName);
} else {
source = insertEnterLog(item, node, functionName);
}
node.updateSource(source);
}
});
fs.writeFile(out + item, output, function(err) {
if (err) {
console.log(err);
} else {
console.log(out + item + ' was saved!');
}
});
}
catch (e) {
console.log('parsing failed: ' + dir + item);
console.log(e);
}
});
});
} | javascript | function pr_autolog(options) {
function espectRewrite(filepath, outpath, template) {
var autologret = require(template);
autologret(filepath, outpath);
}
function insertReturnLog(source, endLine) {
var sourceRet;
// Insert ending log at return statement.
sourceRet = source.replace(/(\s|;)return(\s|;)/g, "$1" + endLine + "return$2");
// Remove any ending log that added twice.
while(sourceRet.indexOf(endLine + endLine) !== -1) {
sourceRet = sourceRet.replace(endLine + endLine, endLine);
}
return sourceRet;
}
function insertEnterAndLeaveLog(item, node, functionName) {
var fnoutLine = 'var DEBOUT="debuguy,"' +
' + (new Date()).getTime() + ",' +
item.substring(0, item.lastIndexOf('.')) + '.' +
functionName + '@' +
node.loc.start.line + '";console.log(DEBOUT + ",ENTER," + Date.now());';
var fnEndLine = 'console.log(DEBOUT + ",LEAVE," + Date.now());';
var startLine = node.getSource().indexOf('{') + 1;
var endLine = node.getSource().lastIndexOf('}');
var source = node.getSource().substr(0, startLine) + fnoutLine +
node.getSource().substr(startLine, endLine - startLine) + fnEndLine +
node.getSource().substr(endLine);
source = insertReturnLog(source, fnEndLine);
return source;
}
function insertEnterLog(item, node, functionName) {
var fnoutLine = '\nconsole.log("debuguy,"' +
' + (new Date()).getTime() + ",' +
item.substring(0, item.lastIndexOf('.')) + '.' +
functionName + '@' +
node.loc.start.line + '");';
var startLine = node.getSource().indexOf('{') + 1;
var source = node.getSource().substr(0, startLine) + fnoutLine +
node.getSource().substr(startLine);
return source;
}
this.traverse(options, function insertLog (dir, item, out) {
if (options.xEspect) {
var templatefile = __dirname + '/autolog.esp.js';
if ('string' === typeof options.xEspect) {
templatefile = options.xEspect;
}
espectRewrite(dir + item, out + item, templatefile);
return;
}
fs.readFile(dir + item, function(err, data) {
console.log('adding log ' + dir + item);
if (err) {
console.log(err);
console.log(data);
return;
}
var text = data.toString();
var output;
try {
output = esprimaTraversal(text, {loc:true})
.traverse(function (node) {
if (node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression') {
// Get the name of the function
var functionName = 'anonymous';
if (node.id) {
functionName = node.id.name;
} else if (node.parent) {
switch (node.parent.type) {
case 'VariableDeclarator':
functionName = node.parent.id.name;
break;
case 'Property':
functionName = node.parent.key.name;
break;
case 'AssignmentExpression':
if (node.parent.left.type === 'MemberExpression') {
functionName = node.parent.left.property.name ||
node.parent.left.property.value;
}
else if (node.parent.left.type === 'Identifier') {
functionName = node.parent.left.name;
}
break;
}
}
// Build the console log output
var source;
if (options.callStackGraph) {
source = insertEnterAndLeaveLog(item, node, functionName);
} else {
source = insertEnterLog(item, node, functionName);
}
node.updateSource(source);
}
});
fs.writeFile(out + item, output, function(err) {
if (err) {
console.log(err);
} else {
console.log(out + item + ' was saved!');
}
});
}
catch (e) {
console.log('parsing failed: ' + dir + item);
console.log(e);
}
});
});
} | [
"function",
"pr_autolog",
"(",
"options",
")",
"{",
"function",
"espectRewrite",
"(",
"filepath",
",",
"outpath",
",",
"template",
")",
"{",
"var",
"autologret",
"=",
"require",
"(",
"template",
")",
";",
"autologret",
"(",
"filepath",
",",
"outpath",
")",
";",
"}",
"function",
"insertReturnLog",
"(",
"source",
",",
"endLine",
")",
"{",
"var",
"sourceRet",
";",
"sourceRet",
"=",
"source",
".",
"replace",
"(",
"/",
"(\\s|;)return(\\s|;)",
"/",
"g",
",",
"\"$1\"",
"+",
"endLine",
"+",
"\"return$2\"",
")",
";",
"while",
"(",
"sourceRet",
".",
"indexOf",
"(",
"endLine",
"+",
"endLine",
")",
"!==",
"-",
"1",
")",
"{",
"sourceRet",
"=",
"sourceRet",
".",
"replace",
"(",
"endLine",
"+",
"endLine",
",",
"endLine",
")",
";",
"}",
"return",
"sourceRet",
";",
"}",
"function",
"insertEnterAndLeaveLog",
"(",
"item",
",",
"node",
",",
"functionName",
")",
"{",
"var",
"fnoutLine",
"=",
"'var DEBOUT=\"debuguy,\"'",
"+",
"' + (new Date()).getTime() + \",'",
"+",
"item",
".",
"substring",
"(",
"0",
",",
"item",
".",
"lastIndexOf",
"(",
"'.'",
")",
")",
"+",
"'.'",
"+",
"functionName",
"+",
"'@'",
"+",
"node",
".",
"loc",
".",
"start",
".",
"line",
"+",
"'\";console.log(DEBOUT + \",ENTER,\" + Date.now());'",
";",
"var",
"fnEndLine",
"=",
"'console.log(DEBOUT + \",LEAVE,\" + Date.now());'",
";",
"var",
"startLine",
"=",
"node",
".",
"getSource",
"(",
")",
".",
"indexOf",
"(",
"'{'",
")",
"+",
"1",
";",
"var",
"endLine",
"=",
"node",
".",
"getSource",
"(",
")",
".",
"lastIndexOf",
"(",
"'}'",
")",
";",
"var",
"source",
"=",
"node",
".",
"getSource",
"(",
")",
".",
"substr",
"(",
"0",
",",
"startLine",
")",
"+",
"fnoutLine",
"+",
"node",
".",
"getSource",
"(",
")",
".",
"substr",
"(",
"startLine",
",",
"endLine",
"-",
"startLine",
")",
"+",
"fnEndLine",
"+",
"node",
".",
"getSource",
"(",
")",
".",
"substr",
"(",
"endLine",
")",
";",
"source",
"=",
"insertReturnLog",
"(",
"source",
",",
"fnEndLine",
")",
";",
"return",
"source",
";",
"}",
"function",
"insertEnterLog",
"(",
"item",
",",
"node",
",",
"functionName",
")",
"{",
"var",
"fnoutLine",
"=",
"'\\nconsole.log(\"debuguy,\"'",
"+",
"\\n",
"+",
"' + (new Date()).getTime() + \",'",
"+",
"item",
".",
"substring",
"(",
"0",
",",
"item",
".",
"lastIndexOf",
"(",
"'.'",
")",
")",
"+",
"'.'",
"+",
"functionName",
"+",
"'@'",
"+",
"node",
".",
"loc",
".",
"start",
".",
"line",
";",
"'\");'",
"var",
"startLine",
"=",
"node",
".",
"getSource",
"(",
")",
".",
"indexOf",
"(",
"'{'",
")",
"+",
"1",
";",
"var",
"source",
"=",
"node",
".",
"getSource",
"(",
")",
".",
"substr",
"(",
"0",
",",
"startLine",
")",
"+",
"fnoutLine",
"+",
"node",
".",
"getSource",
"(",
")",
".",
"substr",
"(",
"startLine",
")",
";",
"}",
"return",
"source",
";",
"}"
]
| Automatically insert console logs in javascript functions.
@param {[type]} options [description]
@return {[type]} [description] | [
"Automatically",
"insert",
"console",
"logs",
"in",
"javascript",
"functions",
"."
]
| 60b18e44b9dd1bcc7a160aac56b570eec6e5e4b4 | https://github.com/seiyugi/debuguy/blob/60b18e44b9dd1bcc7a160aac56b570eec6e5e4b4/lib/parser.js#L205-L328 | train |
greggman/hft-game-utils | src/hft/scripts/misc/timeout.js | function(callback, timeInMs) {
var timeout = makeTimeout(callback);
setTriggerTime(timeout, timeInMs);
s_timeoutsToInsert.push(timeout);
return timeout.id;
} | javascript | function(callback, timeInMs) {
var timeout = makeTimeout(callback);
setTriggerTime(timeout, timeInMs);
s_timeoutsToInsert.push(timeout);
return timeout.id;
} | [
"function",
"(",
"callback",
",",
"timeInMs",
")",
"{",
"var",
"timeout",
"=",
"makeTimeout",
"(",
"callback",
")",
";",
"setTriggerTime",
"(",
"timeout",
",",
"timeInMs",
")",
";",
"s_timeoutsToInsert",
".",
"push",
"(",
"timeout",
")",
";",
"return",
"timeout",
".",
"id",
";",
"}"
]
| Same as normal setTimeout
@param {callback} callback function to call when it times out
@param {number} timeInMs duration of timeout
@return {number} id for timeout
@memberOf module:Timeout | [
"Same",
"as",
"normal",
"setTimeout"
]
| 071a0feebeed79d3597efd63e682392179cf0d30 | https://github.com/greggman/hft-game-utils/blob/071a0feebeed79d3597efd63e682392179cf0d30/src/hft/scripts/misc/timeout.js#L106-L111 | train |
|
greggman/hft-game-utils | src/hft/scripts/misc/timeout.js | function(callback, timeInMs) {
var timeout = makeTimeout(function() {
setTriggerTime(timeout, timeout.timeInMs);
s_timeoutsToInsert.push(timeout);
callback();
});
timeout.timeInMs = timeInMs;
s_timeoutsToInsert.push(timeout);
return timeout.id;
} | javascript | function(callback, timeInMs) {
var timeout = makeTimeout(function() {
setTriggerTime(timeout, timeout.timeInMs);
s_timeoutsToInsert.push(timeout);
callback();
});
timeout.timeInMs = timeInMs;
s_timeoutsToInsert.push(timeout);
return timeout.id;
} | [
"function",
"(",
"callback",
",",
"timeInMs",
")",
"{",
"var",
"timeout",
"=",
"makeTimeout",
"(",
"function",
"(",
")",
"{",
"setTriggerTime",
"(",
"timeout",
",",
"timeout",
".",
"timeInMs",
")",
";",
"s_timeoutsToInsert",
".",
"push",
"(",
"timeout",
")",
";",
"callback",
"(",
")",
";",
"}",
")",
";",
"timeout",
".",
"timeInMs",
"=",
"timeInMs",
";",
"s_timeoutsToInsert",
".",
"push",
"(",
"timeout",
")",
";",
"return",
"timeout",
".",
"id",
";",
"}"
]
| Same as normal setInterval
@param {callback} callback function to call at each interval
@param {number} timeInMs duration of internval
@return {number} id for interval
@memberOf module:Timeout | [
"Same",
"as",
"normal",
"setInterval"
]
| 071a0feebeed79d3597efd63e682392179cf0d30 | https://github.com/greggman/hft-game-utils/blob/071a0feebeed79d3597efd63e682392179cf0d30/src/hft/scripts/misc/timeout.js#L120-L129 | train |
|
greggman/hft-game-utils | src/hft/scripts/misc/timeout.js | function(elapsedTimeInSeconds) {
// insert any unscheduled timeouts
if (s_timeoutsToInsert.length) {
s_timeoutsToInsert.forEach(insertTimeout);
s_timeoutsToInsert = [];
}
// Now remove any
if (s_timeoutsToRemoveById.length) {
s_timeoutsToRemoveById.forEach(removeTimeoutById);
s_timeoutsToRemoveById = [];
}
s_clockInMs += elapsedTimeInSeconds * 1000;
// process timeouts
for (var ii = 0; ii < s_timeouts.length; ++ii) {
var timeout = s_timeouts[ii];
if (s_clockInMs < timeout.timeToTrigger) {
break;
}
timeout.callback();
}
// remove expired timeouts
s_timeouts.splice(0, ii);
} | javascript | function(elapsedTimeInSeconds) {
// insert any unscheduled timeouts
if (s_timeoutsToInsert.length) {
s_timeoutsToInsert.forEach(insertTimeout);
s_timeoutsToInsert = [];
}
// Now remove any
if (s_timeoutsToRemoveById.length) {
s_timeoutsToRemoveById.forEach(removeTimeoutById);
s_timeoutsToRemoveById = [];
}
s_clockInMs += elapsedTimeInSeconds * 1000;
// process timeouts
for (var ii = 0; ii < s_timeouts.length; ++ii) {
var timeout = s_timeouts[ii];
if (s_clockInMs < timeout.timeToTrigger) {
break;
}
timeout.callback();
}
// remove expired timeouts
s_timeouts.splice(0, ii);
} | [
"function",
"(",
"elapsedTimeInSeconds",
")",
"{",
"if",
"(",
"s_timeoutsToInsert",
".",
"length",
")",
"{",
"s_timeoutsToInsert",
".",
"forEach",
"(",
"insertTimeout",
")",
";",
"s_timeoutsToInsert",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"s_timeoutsToRemoveById",
".",
"length",
")",
"{",
"s_timeoutsToRemoveById",
".",
"forEach",
"(",
"removeTimeoutById",
")",
";",
"s_timeoutsToRemoveById",
"=",
"[",
"]",
";",
"}",
"s_clockInMs",
"+=",
"elapsedTimeInSeconds",
"*",
"1000",
";",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"s_timeouts",
".",
"length",
";",
"++",
"ii",
")",
"{",
"var",
"timeout",
"=",
"s_timeouts",
"[",
"ii",
"]",
";",
"if",
"(",
"s_clockInMs",
"<",
"timeout",
".",
"timeToTrigger",
")",
"{",
"break",
";",
"}",
"timeout",
".",
"callback",
"(",
")",
";",
"}",
"s_timeouts",
".",
"splice",
"(",
"0",
",",
"ii",
")",
";",
"}"
]
| Processes the intervals and timeouts
This is how you control the clock for the timouts
A typical usage might be
var g = {};
GameSupport.run(g, mainloop);
function mainloop() {
Timeout.process(globals.elapsedTime);
};
@param {number} elapsedTimeInSeconds number of seconds to advance the clock.
@memberOf module:Timeout | [
"Processes",
"the",
"intervals",
"and",
"timeouts"
]
| 071a0feebeed79d3597efd63e682392179cf0d30 | https://github.com/greggman/hft-game-utils/blob/071a0feebeed79d3597efd63e682392179cf0d30/src/hft/scripts/misc/timeout.js#L167-L193 | train |
|
node-jpi/jpi-models | array.js | function () {
const result = Array.prototype.pop.apply(arr)
fn('pop', arr, {
value: result
})
return result
} | javascript | function () {
const result = Array.prototype.pop.apply(arr)
fn('pop', arr, {
value: result
})
return result
} | [
"function",
"(",
")",
"{",
"const",
"result",
"=",
"Array",
".",
"prototype",
".",
"pop",
".",
"apply",
"(",
"arr",
")",
"fn",
"(",
"'pop'",
",",
"arr",
",",
"{",
"value",
":",
"result",
"}",
")",
"return",
"result",
"}"
]
| Proxied array mutators methods
@param {Object} obj
@return {Object}
@api private | [
"Proxied",
"array",
"mutators",
"methods"
]
| f0c34626d004d720cefdbb4ad5d33d84057fd78d | https://github.com/node-jpi/jpi-models/blob/f0c34626d004d720cefdbb4ad5d33d84057fd78d/array.js#L13-L21 | train |
|
nodejitsu/npm-dependencies-pagelet | index.js | process | function process(data) {
//
// Apply previous post processing.
//
data = Pagelet.prototype.postprocess.call(this, data);
data.stats = {
outofdate: 0,
uptodate: 0,
pinned: 0
};
data.shrinkwrap.forEach(function shrinkwrap(module) {
if (module.pinned) data.stats.pinned++;
if (module.uptodate) data.stats.uptodate++;
else data.stats.outofdate++;
});
return data;
} | javascript | function process(data) {
//
// Apply previous post processing.
//
data = Pagelet.prototype.postprocess.call(this, data);
data.stats = {
outofdate: 0,
uptodate: 0,
pinned: 0
};
data.shrinkwrap.forEach(function shrinkwrap(module) {
if (module.pinned) data.stats.pinned++;
if (module.uptodate) data.stats.uptodate++;
else data.stats.outofdate++;
});
return data;
} | [
"function",
"process",
"(",
"data",
")",
"{",
"data",
"=",
"Pagelet",
".",
"prototype",
".",
"postprocess",
".",
"call",
"(",
"this",
",",
"data",
")",
";",
"data",
".",
"stats",
"=",
"{",
"outofdate",
":",
"0",
",",
"uptodate",
":",
"0",
",",
"pinned",
":",
"0",
"}",
";",
"data",
".",
"shrinkwrap",
".",
"forEach",
"(",
"function",
"shrinkwrap",
"(",
"module",
")",
"{",
"if",
"(",
"module",
".",
"pinned",
")",
"data",
".",
"stats",
".",
"pinned",
"++",
";",
"if",
"(",
"module",
".",
"uptodate",
")",
"data",
".",
"stats",
".",
"uptodate",
"++",
";",
"else",
"data",
".",
"stats",
".",
"outofdate",
"++",
";",
"}",
")",
";",
"return",
"data",
";",
"}"
]
| Remove JS dependency.
Final post processing step on the data.
@param {Object} data The resolved data from cache.
@returns {Object} data
@api private | [
"Remove",
"JS",
"dependency",
".",
"Final",
"post",
"processing",
"step",
"on",
"the",
"data",
"."
]
| 5a43cfa31eb0e9ccec609204d0a8dc6a29080e0a | https://github.com/nodejitsu/npm-dependencies-pagelet/blob/5a43cfa31eb0e9ccec609204d0a8dc6a29080e0a/index.js#L22-L41 | train |
muttr/libmuttr | lib/session.js | Session | function Session(identity, connection, options) {
if (!(this instanceof Session)) {
return new Session(identity, connection, options);
}
assert(identity instanceof Identity, 'Invalid identity supplied');
if (!(connection instanceof Connection)) {
options = connection || {};
options.passive = true;
}
this.options = merge(Object.create(Session.DEFAULTS), options);
this.client = new Client(identity);
this._identity = identity;
if (!this.options.passive) {
this._connection = connection;
this._connection.open(this._onConnect.bind(this));
} else {
this._onConnect();
}
if (this.options.subscribe) {
this.client.on('message', this._onMessage.bind(this)).subscribe();
}
} | javascript | function Session(identity, connection, options) {
if (!(this instanceof Session)) {
return new Session(identity, connection, options);
}
assert(identity instanceof Identity, 'Invalid identity supplied');
if (!(connection instanceof Connection)) {
options = connection || {};
options.passive = true;
}
this.options = merge(Object.create(Session.DEFAULTS), options);
this.client = new Client(identity);
this._identity = identity;
if (!this.options.passive) {
this._connection = connection;
this._connection.open(this._onConnect.bind(this));
} else {
this._onConnect();
}
if (this.options.subscribe) {
this.client.on('message', this._onMessage.bind(this)).subscribe();
}
} | [
"function",
"Session",
"(",
"identity",
",",
"connection",
",",
"options",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Session",
")",
")",
"{",
"return",
"new",
"Session",
"(",
"identity",
",",
"connection",
",",
"options",
")",
";",
"}",
"assert",
"(",
"identity",
"instanceof",
"Identity",
",",
"'Invalid identity supplied'",
")",
";",
"if",
"(",
"!",
"(",
"connection",
"instanceof",
"Connection",
")",
")",
"{",
"options",
"=",
"connection",
"||",
"{",
"}",
";",
"options",
".",
"passive",
"=",
"true",
";",
"}",
"this",
".",
"options",
"=",
"merge",
"(",
"Object",
".",
"create",
"(",
"Session",
".",
"DEFAULTS",
")",
",",
"options",
")",
";",
"this",
".",
"client",
"=",
"new",
"Client",
"(",
"identity",
")",
";",
"this",
".",
"_identity",
"=",
"identity",
";",
"if",
"(",
"!",
"this",
".",
"options",
".",
"passive",
")",
"{",
"this",
".",
"_connection",
"=",
"connection",
";",
"this",
".",
"_connection",
".",
"open",
"(",
"this",
".",
"_onConnect",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"else",
"{",
"this",
".",
"_onConnect",
"(",
")",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"subscribe",
")",
"{",
"this",
".",
"client",
".",
"on",
"(",
"'message'",
",",
"this",
".",
"_onMessage",
".",
"bind",
"(",
"this",
")",
")",
".",
"subscribe",
"(",
")",
";",
"}",
"}"
]
| Creates a sandbox for Muttr apps by the given identity
@constructor
@param {Identity} identity
@param {Connection} connection
@param {object} options | [
"Creates",
"a",
"sandbox",
"for",
"Muttr",
"apps",
"by",
"the",
"given",
"identity"
]
| 2e4fda9cb2b47b8febe30585f54196d39d79e2e5 | https://github.com/muttr/libmuttr/blob/2e4fda9cb2b47b8febe30585f54196d39d79e2e5/lib/session.js#L34-L60 | train |
codenothing/munit | lib/assert.js | function(){
var self = this,
logs = self._filterLogs(),
all = logs.all,
keys = logs.keys,
time = munit._relativeTime( self.end - self.start );
// Root module
if ( ! self.callback ) {
munit.color.green( "=== All submodules of " + self.nsPath + " have finished ===" );
return;
}
// Content
munit.color.blue( "\n" + self.nsPath );
munit.each( self.tests, function( test ) {
if ( keys[ test.name ] && keys[ test.name ].length ) {
keys[ test.name ].forEach(function( args ) {
munit.log.apply( munit, args );
});
}
if ( test.error ) {
munit.color.red( test.ns );
munit.log( "\n", test.error.stack );
munit.log( "\n" );
}
else if ( test.skip ) {
munit.color.gray( "[skipped] " + test.ns );
munit.color.gray( "\treason: " + test.skip );
}
else {
munit.color.green( test.ns );
}
});
// Logs made after the final test
if ( all.length ) {
all.forEach(function( args ) {
munit.log.apply( munit, args );
});
}
// Final Output
if ( self.failed ) {
munit.color.red( "\n-- " + self.failed + " tests failed on " + self.nsPath + " (" + time + ") --\n" );
}
else {
munit.color.green( "\n-- All " + self.passed + " tests passed on " + self.nsPath + " (" + time + ") --\n" );
}
} | javascript | function(){
var self = this,
logs = self._filterLogs(),
all = logs.all,
keys = logs.keys,
time = munit._relativeTime( self.end - self.start );
// Root module
if ( ! self.callback ) {
munit.color.green( "=== All submodules of " + self.nsPath + " have finished ===" );
return;
}
// Content
munit.color.blue( "\n" + self.nsPath );
munit.each( self.tests, function( test ) {
if ( keys[ test.name ] && keys[ test.name ].length ) {
keys[ test.name ].forEach(function( args ) {
munit.log.apply( munit, args );
});
}
if ( test.error ) {
munit.color.red( test.ns );
munit.log( "\n", test.error.stack );
munit.log( "\n" );
}
else if ( test.skip ) {
munit.color.gray( "[skipped] " + test.ns );
munit.color.gray( "\treason: " + test.skip );
}
else {
munit.color.green( test.ns );
}
});
// Logs made after the final test
if ( all.length ) {
all.forEach(function( args ) {
munit.log.apply( munit, args );
});
}
// Final Output
if ( self.failed ) {
munit.color.red( "\n-- " + self.failed + " tests failed on " + self.nsPath + " (" + time + ") --\n" );
}
else {
munit.color.green( "\n-- All " + self.passed + " tests passed on " + self.nsPath + " (" + time + ") --\n" );
}
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
",",
"logs",
"=",
"self",
".",
"_filterLogs",
"(",
")",
",",
"all",
"=",
"logs",
".",
"all",
",",
"keys",
"=",
"logs",
".",
"keys",
",",
"time",
"=",
"munit",
".",
"_relativeTime",
"(",
"self",
".",
"end",
"-",
"self",
".",
"start",
")",
";",
"if",
"(",
"!",
"self",
".",
"callback",
")",
"{",
"munit",
".",
"color",
".",
"green",
"(",
"\"=== All submodules of \"",
"+",
"self",
".",
"nsPath",
"+",
"\" have finished ===\"",
")",
";",
"return",
";",
"}",
"munit",
".",
"color",
".",
"blue",
"(",
"\"\\n\"",
"+",
"\\n",
")",
";",
"self",
".",
"nsPath",
"munit",
".",
"each",
"(",
"self",
".",
"tests",
",",
"function",
"(",
"test",
")",
"{",
"if",
"(",
"keys",
"[",
"test",
".",
"name",
"]",
"&&",
"keys",
"[",
"test",
".",
"name",
"]",
".",
"length",
")",
"{",
"keys",
"[",
"test",
".",
"name",
"]",
".",
"forEach",
"(",
"function",
"(",
"args",
")",
"{",
"munit",
".",
"log",
".",
"apply",
"(",
"munit",
",",
"args",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"test",
".",
"error",
")",
"{",
"munit",
".",
"color",
".",
"red",
"(",
"test",
".",
"ns",
")",
";",
"munit",
".",
"log",
"(",
"\"\\n\"",
",",
"\\n",
")",
";",
"test",
".",
"error",
".",
"stack",
"}",
"else",
"munit",
".",
"log",
"(",
"\"\\n\"",
")",
";",
"}",
")",
";",
"\\n",
"}"
]
| Prints module results to cli | [
"Prints",
"module",
"results",
"to",
"cli"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L46-L96 | train |
|
codenothing/munit | lib/assert.js | function(){
var self = this,
all = [],
keys = {},
current = null;
self._logs.reverse().forEach(function( log ) {
if ( log instanceof AssertResult ) {
current = log.name;
return;
}
var name = log[ 0 ];
if ( log.length > 1 && munit.isString( name ) && self.tests[ name ] ) {
if ( ! keys[ name ] ) {
keys[ name ] = [];
}
keys[ name ].unshift( log.slice( 1 ) );
}
else if ( current && self.tests[ current ] ) {
if ( ! keys[ current ] ) {
keys[ current ] = [];
}
keys[ current ].unshift( log );
}
else {
all.unshift( log );
}
});
return { all: all, keys: keys };
} | javascript | function(){
var self = this,
all = [],
keys = {},
current = null;
self._logs.reverse().forEach(function( log ) {
if ( log instanceof AssertResult ) {
current = log.name;
return;
}
var name = log[ 0 ];
if ( log.length > 1 && munit.isString( name ) && self.tests[ name ] ) {
if ( ! keys[ name ] ) {
keys[ name ] = [];
}
keys[ name ].unshift( log.slice( 1 ) );
}
else if ( current && self.tests[ current ] ) {
if ( ! keys[ current ] ) {
keys[ current ] = [];
}
keys[ current ].unshift( log );
}
else {
all.unshift( log );
}
});
return { all: all, keys: keys };
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
",",
"all",
"=",
"[",
"]",
",",
"keys",
"=",
"{",
"}",
",",
"current",
"=",
"null",
";",
"self",
".",
"_logs",
".",
"reverse",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"log",
")",
"{",
"if",
"(",
"log",
"instanceof",
"AssertResult",
")",
"{",
"current",
"=",
"log",
".",
"name",
";",
"return",
";",
"}",
"var",
"name",
"=",
"log",
"[",
"0",
"]",
";",
"if",
"(",
"log",
".",
"length",
">",
"1",
"&&",
"munit",
".",
"isString",
"(",
"name",
")",
"&&",
"self",
".",
"tests",
"[",
"name",
"]",
")",
"{",
"if",
"(",
"!",
"keys",
"[",
"name",
"]",
")",
"{",
"keys",
"[",
"name",
"]",
"=",
"[",
"]",
";",
"}",
"keys",
"[",
"name",
"]",
".",
"unshift",
"(",
"log",
".",
"slice",
"(",
"1",
")",
")",
";",
"}",
"else",
"if",
"(",
"current",
"&&",
"self",
".",
"tests",
"[",
"current",
"]",
")",
"{",
"if",
"(",
"!",
"keys",
"[",
"current",
"]",
")",
"{",
"keys",
"[",
"current",
"]",
"=",
"[",
"]",
";",
"}",
"keys",
"[",
"current",
"]",
".",
"unshift",
"(",
"log",
")",
";",
"}",
"else",
"{",
"all",
".",
"unshift",
"(",
"log",
")",
";",
"}",
"}",
")",
";",
"return",
"{",
"all",
":",
"all",
",",
"keys",
":",
"keys",
"}",
";",
"}"
]
| Generates log arrays based on current test keys | [
"Generates",
"log",
"arrays",
"based",
"on",
"current",
"test",
"keys"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L99-L132 | train |
|
codenothing/munit | lib/assert.js | function( name, error, skip ) {
var self = this,
now = Date.now(),
last = ! self.isAsync && self._lastTest ? self._lastTest : self.start,
result = new AssertResult( name, self.nsPath, now - last, error, skip );
self.tests[ name ] = result;
self.list.push( result );
self._logs.push( result );
self._lastTest = now;
} | javascript | function( name, error, skip ) {
var self = this,
now = Date.now(),
last = ! self.isAsync && self._lastTest ? self._lastTest : self.start,
result = new AssertResult( name, self.nsPath, now - last, error, skip );
self.tests[ name ] = result;
self.list.push( result );
self._logs.push( result );
self._lastTest = now;
} | [
"function",
"(",
"name",
",",
"error",
",",
"skip",
")",
"{",
"var",
"self",
"=",
"this",
",",
"now",
"=",
"Date",
".",
"now",
"(",
")",
",",
"last",
"=",
"!",
"self",
".",
"isAsync",
"&&",
"self",
".",
"_lastTest",
"?",
"self",
".",
"_lastTest",
":",
"self",
".",
"start",
",",
"result",
"=",
"new",
"AssertResult",
"(",
"name",
",",
"self",
".",
"nsPath",
",",
"now",
"-",
"last",
",",
"error",
",",
"skip",
")",
";",
"self",
".",
"tests",
"[",
"name",
"]",
"=",
"result",
";",
"self",
".",
"list",
".",
"push",
"(",
"result",
")",
";",
"self",
".",
"_logs",
".",
"push",
"(",
"result",
")",
";",
"self",
".",
"_lastTest",
"=",
"now",
";",
"}"
]
| Returns a configured result object | [
"Returns",
"a",
"configured",
"result",
"object"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L135-L145 | train |
|
codenothing/munit | lib/assert.js | function( actual, expected, prefix ) {
var self = this, keys, expectedKeys;
prefix = prefix || '';
if ( munit.isArray( actual ) && munit.isArray( expected ) ) {
if ( actual.length !== expected.length ) {
throw "\nActual: actual" + prefix + ".length = " + actual.length +
"\nExpected: expected" + prefix + ".length = " + expected.length;
}
munit.each( actual, function( item, i ) {
if ( munit.isArray( item ) || munit.isObject( item ) ) {
self._objectMatch( item, expected[ i ], prefix + "[" + i + "]" );
}
else if ( item !== expected[ i ] ) {
throw "\nActual: actual" + prefix + "[" + i + "] = " + item +
"\nExpected: expected" + prefix + "[" + i + "] = " + expected[ i ];
}
});
}
else if ( munit.isObject( actual ) && munit.isObject( expected ) ) {
keys = Object.keys( actual );
expectedKeys = Object.keys( expected );
if ( keys.length !== expectedKeys.length ) {
throw "\nActual: actual" + prefix + ".length = " + keys.length +
"\nExpected: expected" + prefix + ".length = " + expectedKeys.length;
}
munit.each( keys, function( key ) {
var item = actual[ key ];
if ( munit.isArray( item ) || munit.isObject( item ) ) {
self._objectMatch( item, expected[ key ], prefix + "[" + key + "]" );
}
else if ( item !== expected[ key ] ) {
throw "\nActual: actual" + prefix + "[" + key + "] = " + item +
"\nExpected: expected" + prefix + "[" + key + "] = " + expected[ key ];
}
});
}
else if ( actual !== expected ) {
throw "\nActual: actual" + prefix + " = " + actual +
"\nExpected: expected" + prefix + " = " + expected;
}
} | javascript | function( actual, expected, prefix ) {
var self = this, keys, expectedKeys;
prefix = prefix || '';
if ( munit.isArray( actual ) && munit.isArray( expected ) ) {
if ( actual.length !== expected.length ) {
throw "\nActual: actual" + prefix + ".length = " + actual.length +
"\nExpected: expected" + prefix + ".length = " + expected.length;
}
munit.each( actual, function( item, i ) {
if ( munit.isArray( item ) || munit.isObject( item ) ) {
self._objectMatch( item, expected[ i ], prefix + "[" + i + "]" );
}
else if ( item !== expected[ i ] ) {
throw "\nActual: actual" + prefix + "[" + i + "] = " + item +
"\nExpected: expected" + prefix + "[" + i + "] = " + expected[ i ];
}
});
}
else if ( munit.isObject( actual ) && munit.isObject( expected ) ) {
keys = Object.keys( actual );
expectedKeys = Object.keys( expected );
if ( keys.length !== expectedKeys.length ) {
throw "\nActual: actual" + prefix + ".length = " + keys.length +
"\nExpected: expected" + prefix + ".length = " + expectedKeys.length;
}
munit.each( keys, function( key ) {
var item = actual[ key ];
if ( munit.isArray( item ) || munit.isObject( item ) ) {
self._objectMatch( item, expected[ key ], prefix + "[" + key + "]" );
}
else if ( item !== expected[ key ] ) {
throw "\nActual: actual" + prefix + "[" + key + "] = " + item +
"\nExpected: expected" + prefix + "[" + key + "] = " + expected[ key ];
}
});
}
else if ( actual !== expected ) {
throw "\nActual: actual" + prefix + " = " + actual +
"\nExpected: expected" + prefix + " = " + expected;
}
} | [
"function",
"(",
"actual",
",",
"expected",
",",
"prefix",
")",
"{",
"var",
"self",
"=",
"this",
",",
"keys",
",",
"expectedKeys",
";",
"prefix",
"=",
"prefix",
"||",
"''",
";",
"if",
"(",
"munit",
".",
"isArray",
"(",
"actual",
")",
"&&",
"munit",
".",
"isArray",
"(",
"expected",
")",
")",
"{",
"if",
"(",
"actual",
".",
"length",
"!==",
"expected",
".",
"length",
")",
"{",
"throw",
"\"\\nActual: actual\"",
"+",
"\\n",
"+",
"prefix",
"+",
"\".length = \"",
"+",
"actual",
".",
"length",
"+",
"\"\\nExpected: expected\"",
"+",
"\\n",
"+",
"prefix",
";",
"}",
"\".length = \"",
"}",
"else",
"expected",
".",
"length",
"}"
]
| Key matching for object match | [
"Key",
"matching",
"for",
"object",
"match"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L148-L193 | train |
|
codenothing/munit | lib/assert.js | function( e, match ) {
var result = { passed: false }, message = '';
// Get a string for matching on the error
if ( munit.isError( e ) ) {
message = e.message;
}
else if ( munit.isString( e ) ) {
message = e;
}
// No match required
if ( match === undefined ) {
result.passed = true;
}
// Non Error/String error object, string matching required
else if ( ! munit.isError( e ) && ! munit.isString( e ) ) {
if ( e === match ) {
result.passed = true;
}
else {
result.extra = "Match object '" + match + "' does not match error '" + e + "'";
}
}
// Function error class matching
else if ( munit.isFunction( match ) ) {
if ( e instanceof match ) {
result.passed = true;
}
else {
result.extra = "Error does not match class '" + match.name + "'";
}
}
// Regex checking on the error message
else if ( munit.isRegExp( match ) ) {
if ( match.exec( message ) ) {
result.passed = true;
}
else {
result.extra = "Regex (" + match + ") could not find match on:\n" + message;
}
}
// String matching on the error message
else if ( munit.isString( match ) ) {
if ( match === message ) {
result.passed = true;
}
else {
result.extra = "Error message doesn't match:\nActual: " + message + "\nExpected: " + match;
}
}
// Unkown error type passed
else {
result.extra = "Unknown error match type '" + match + "'";
}
return result;
} | javascript | function( e, match ) {
var result = { passed: false }, message = '';
// Get a string for matching on the error
if ( munit.isError( e ) ) {
message = e.message;
}
else if ( munit.isString( e ) ) {
message = e;
}
// No match required
if ( match === undefined ) {
result.passed = true;
}
// Non Error/String error object, string matching required
else if ( ! munit.isError( e ) && ! munit.isString( e ) ) {
if ( e === match ) {
result.passed = true;
}
else {
result.extra = "Match object '" + match + "' does not match error '" + e + "'";
}
}
// Function error class matching
else if ( munit.isFunction( match ) ) {
if ( e instanceof match ) {
result.passed = true;
}
else {
result.extra = "Error does not match class '" + match.name + "'";
}
}
// Regex checking on the error message
else if ( munit.isRegExp( match ) ) {
if ( match.exec( message ) ) {
result.passed = true;
}
else {
result.extra = "Regex (" + match + ") could not find match on:\n" + message;
}
}
// String matching on the error message
else if ( munit.isString( match ) ) {
if ( match === message ) {
result.passed = true;
}
else {
result.extra = "Error message doesn't match:\nActual: " + message + "\nExpected: " + match;
}
}
// Unkown error type passed
else {
result.extra = "Unknown error match type '" + match + "'";
}
return result;
} | [
"function",
"(",
"e",
",",
"match",
")",
"{",
"var",
"result",
"=",
"{",
"passed",
":",
"false",
"}",
",",
"message",
"=",
"''",
";",
"if",
"(",
"munit",
".",
"isError",
"(",
"e",
")",
")",
"{",
"message",
"=",
"e",
".",
"message",
";",
"}",
"else",
"if",
"(",
"munit",
".",
"isString",
"(",
"e",
")",
")",
"{",
"message",
"=",
"e",
";",
"}",
"if",
"(",
"match",
"===",
"undefined",
")",
"{",
"result",
".",
"passed",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"!",
"munit",
".",
"isError",
"(",
"e",
")",
"&&",
"!",
"munit",
".",
"isString",
"(",
"e",
")",
")",
"{",
"if",
"(",
"e",
"===",
"match",
")",
"{",
"result",
".",
"passed",
"=",
"true",
";",
"}",
"else",
"{",
"result",
".",
"extra",
"=",
"\"Match object '\"",
"+",
"match",
"+",
"\"' does not match error '\"",
"+",
"e",
"+",
"\"'\"",
";",
"}",
"}",
"else",
"if",
"(",
"munit",
".",
"isFunction",
"(",
"match",
")",
")",
"{",
"if",
"(",
"e",
"instanceof",
"match",
")",
"{",
"result",
".",
"passed",
"=",
"true",
";",
"}",
"else",
"{",
"result",
".",
"extra",
"=",
"\"Error does not match class '\"",
"+",
"match",
".",
"name",
"+",
"\"'\"",
";",
"}",
"}",
"else",
"if",
"(",
"munit",
".",
"isRegExp",
"(",
"match",
")",
")",
"{",
"if",
"(",
"match",
".",
"exec",
"(",
"message",
")",
")",
"{",
"result",
".",
"passed",
"=",
"true",
";",
"}",
"else",
"{",
"result",
".",
"extra",
"=",
"\"Regex (\"",
"+",
"match",
"+",
"\") could not find match on:\\n\"",
"+",
"\\n",
";",
"}",
"}",
"else",
"message",
"if",
"(",
"munit",
".",
"isString",
"(",
"match",
")",
")",
"{",
"if",
"(",
"match",
"===",
"message",
")",
"{",
"result",
".",
"passed",
"=",
"true",
";",
"}",
"else",
"{",
"result",
".",
"extra",
"=",
"\"Error message doesn't match:\\nActual: \"",
"+",
"\\n",
"+",
"message",
"+",
"\"\\nExpected: \"",
";",
"}",
"}",
"else",
"\\n",
"}"
]
| Utility for error object matching | [
"Utility",
"for",
"error",
"object",
"matching"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L196-L253 | train |
|
codenothing/munit | lib/assert.js | function( name, startFunc, error ) {
var self = this, result;
// Assign proper error
if ( ! error ) {
error = new munit.AssertionError( "'" + name + "' test failed", startFunc );
}
else if ( ! ( error instanceof Error ) ) {
error = new munit.AssertionError( error, startFunc );
}
// Increment error count and jump
self._addResult( name, error );
self.failed++;
self.count++;
munit.failed++;
// Kill on test failure
if ( self.options.stopOnFail ) {
self._flush();
munit.exit( 1 );
}
} | javascript | function( name, startFunc, error ) {
var self = this, result;
// Assign proper error
if ( ! error ) {
error = new munit.AssertionError( "'" + name + "' test failed", startFunc );
}
else if ( ! ( error instanceof Error ) ) {
error = new munit.AssertionError( error, startFunc );
}
// Increment error count and jump
self._addResult( name, error );
self.failed++;
self.count++;
munit.failed++;
// Kill on test failure
if ( self.options.stopOnFail ) {
self._flush();
munit.exit( 1 );
}
} | [
"function",
"(",
"name",
",",
"startFunc",
",",
"error",
")",
"{",
"var",
"self",
"=",
"this",
",",
"result",
";",
"if",
"(",
"!",
"error",
")",
"{",
"error",
"=",
"new",
"munit",
".",
"AssertionError",
"(",
"\"'\"",
"+",
"name",
"+",
"\"' test failed\"",
",",
"startFunc",
")",
";",
"}",
"else",
"if",
"(",
"!",
"(",
"error",
"instanceof",
"Error",
")",
")",
"{",
"error",
"=",
"new",
"munit",
".",
"AssertionError",
"(",
"error",
",",
"startFunc",
")",
";",
"}",
"self",
".",
"_addResult",
"(",
"name",
",",
"error",
")",
";",
"self",
".",
"failed",
"++",
";",
"self",
".",
"count",
"++",
";",
"munit",
".",
"failed",
"++",
";",
"if",
"(",
"self",
".",
"options",
".",
"stopOnFail",
")",
"{",
"self",
".",
"_flush",
"(",
")",
";",
"munit",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}"
]
| Failed test storage | [
"Failed",
"test",
"storage"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L256-L278 | train |
|
codenothing/munit | lib/assert.js | function( name ) {
var self = this;
self._addResult( name );
self.passed++;
self.count++;
munit.passed++;
} | javascript | function( name ) {
var self = this;
self._addResult( name );
self.passed++;
self.count++;
munit.passed++;
} | [
"function",
"(",
"name",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"_addResult",
"(",
"name",
")",
";",
"self",
".",
"passed",
"++",
";",
"self",
".",
"count",
"++",
";",
"munit",
".",
"passed",
"++",
";",
"}"
]
| Passed test storage | [
"Passed",
"test",
"storage"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L281-L288 | train |
|
codenothing/munit | lib/assert.js | function( required, startFunc ) {
var self = this;
if ( required !== self.state ) {
self._stateError( startFunc || self.requireState );
}
return self;
} | javascript | function( required, startFunc ) {
var self = this;
if ( required !== self.state ) {
self._stateError( startFunc || self.requireState );
}
return self;
} | [
"function",
"(",
"required",
",",
"startFunc",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"required",
"!==",
"self",
".",
"state",
")",
"{",
"self",
".",
"_stateError",
"(",
"startFunc",
"||",
"self",
".",
"requireState",
")",
";",
"}",
"return",
"self",
";",
"}"
]
| Throws an error if module isn't in the required state | [
"Throws",
"an",
"error",
"if",
"module",
"isn",
"t",
"in",
"the",
"required",
"state"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L305-L313 | train |
|
codenothing/munit | lib/assert.js | function( time, callback ) {
var self = this, timeid;
// Can only delay an active module
self.requireState( munit.ASSERT_STATE_ACTIVE, self.delay );
// Time parameter is required
if ( ! munit.isNumber( time ) ) {
throw new munit.AssertionError( "Time parameter not passed to assert.delay", self.delay );
}
// Module has yet to complete the callback cycle,
// Start async extension now
if ( ! self.isAsync ) {
self.isAsync = true;
self.options.timeout = time;
self._timerStart = Date.now();
self._timeid = timeid = setTimeout(function(){
if ( munit.isFunction( callback ) ) {
callback( self );
}
if ( timeid === self._timeid && self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, time );
}
// Only extend current timeout if it is less then requested delay
else if ( ( self._timerStart + self.options.timeout ) < ( Date.now() + time ) ) {
if ( self._timeid ) {
self._timeid = clearTimeout( self._timeid );
}
self.isAsync = true;
self._timerStart = Date.now();
self._timeid = timeid = setTimeout(function(){
if ( munit.isFunction( callback ) ) {
callback( self );
}
if ( timeid === self._timeid && self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, time );
}
// Force block any delay that does not extend longer than current timeout
else {
throw new munit.AssertionError( "delay time doesn't extend further than the current timeout", self.delay );
}
} | javascript | function( time, callback ) {
var self = this, timeid;
// Can only delay an active module
self.requireState( munit.ASSERT_STATE_ACTIVE, self.delay );
// Time parameter is required
if ( ! munit.isNumber( time ) ) {
throw new munit.AssertionError( "Time parameter not passed to assert.delay", self.delay );
}
// Module has yet to complete the callback cycle,
// Start async extension now
if ( ! self.isAsync ) {
self.isAsync = true;
self.options.timeout = time;
self._timerStart = Date.now();
self._timeid = timeid = setTimeout(function(){
if ( munit.isFunction( callback ) ) {
callback( self );
}
if ( timeid === self._timeid && self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, time );
}
// Only extend current timeout if it is less then requested delay
else if ( ( self._timerStart + self.options.timeout ) < ( Date.now() + time ) ) {
if ( self._timeid ) {
self._timeid = clearTimeout( self._timeid );
}
self.isAsync = true;
self._timerStart = Date.now();
self._timeid = timeid = setTimeout(function(){
if ( munit.isFunction( callback ) ) {
callback( self );
}
if ( timeid === self._timeid && self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, time );
}
// Force block any delay that does not extend longer than current timeout
else {
throw new munit.AssertionError( "delay time doesn't extend further than the current timeout", self.delay );
}
} | [
"function",
"(",
"time",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
",",
"timeid",
";",
"self",
".",
"requireState",
"(",
"munit",
".",
"ASSERT_STATE_ACTIVE",
",",
"self",
".",
"delay",
")",
";",
"if",
"(",
"!",
"munit",
".",
"isNumber",
"(",
"time",
")",
")",
"{",
"throw",
"new",
"munit",
".",
"AssertionError",
"(",
"\"Time parameter not passed to assert.delay\"",
",",
"self",
".",
"delay",
")",
";",
"}",
"if",
"(",
"!",
"self",
".",
"isAsync",
")",
"{",
"self",
".",
"isAsync",
"=",
"true",
";",
"self",
".",
"options",
".",
"timeout",
"=",
"time",
";",
"self",
".",
"_timerStart",
"=",
"Date",
".",
"now",
"(",
")",
";",
"self",
".",
"_timeid",
"=",
"timeid",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"munit",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"callback",
"(",
"self",
")",
";",
"}",
"if",
"(",
"timeid",
"===",
"self",
".",
"_timeid",
"&&",
"self",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_TEARDOWN",
")",
"{",
"self",
".",
"close",
"(",
")",
";",
"}",
"}",
",",
"time",
")",
";",
"}",
"else",
"if",
"(",
"(",
"self",
".",
"_timerStart",
"+",
"self",
".",
"options",
".",
"timeout",
")",
"<",
"(",
"Date",
".",
"now",
"(",
")",
"+",
"time",
")",
")",
"{",
"if",
"(",
"self",
".",
"_timeid",
")",
"{",
"self",
".",
"_timeid",
"=",
"clearTimeout",
"(",
"self",
".",
"_timeid",
")",
";",
"}",
"self",
".",
"isAsync",
"=",
"true",
";",
"self",
".",
"_timerStart",
"=",
"Date",
".",
"now",
"(",
")",
";",
"self",
".",
"_timeid",
"=",
"timeid",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"munit",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"callback",
"(",
"self",
")",
";",
"}",
"if",
"(",
"timeid",
"===",
"self",
".",
"_timeid",
"&&",
"self",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_TEARDOWN",
")",
"{",
"self",
".",
"close",
"(",
")",
";",
"}",
"}",
",",
"time",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"munit",
".",
"AssertionError",
"(",
"\"delay time doesn't extend further than the current timeout\"",
",",
"self",
".",
"delay",
")",
";",
"}",
"}"
]
| Makes module asynchronous | [
"Makes",
"module",
"asynchronous"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L352-L401 | train |
|
codenothing/munit | lib/assert.js | function( name, test, startFunc, extra ) {
var self = this;
// Require an active state for tests
self.requireState( munit.ASSERT_STATE_ACTIVE, startFunc || self.ok );
// Prevent non empty string names
if ( ! munit.isString( name ) || ! name.length ) {
throw new munit.AssertionError(
"Name not found for test on '" + self.nsPath + "'",
startFunc || self.ok
);
}
// Prevent duplicate tests
else if ( self.tests[ name ] ) {
throw new munit.AssertionError(
"Duplicate Test '" + name + "' on '" + self.nsPath + "'",
startFunc || self.ok
);
}
// Increment test count and mark it
self[ !!( test ) ? '_pass' : '_fail' ]( name, startFunc || self.ok, extra );
// Reached expected number of tests, close off
if ( self.options.expect > 0 && self.count >= self.options.expect ) {
self.close();
}
return self;
} | javascript | function( name, test, startFunc, extra ) {
var self = this;
// Require an active state for tests
self.requireState( munit.ASSERT_STATE_ACTIVE, startFunc || self.ok );
// Prevent non empty string names
if ( ! munit.isString( name ) || ! name.length ) {
throw new munit.AssertionError(
"Name not found for test on '" + self.nsPath + "'",
startFunc || self.ok
);
}
// Prevent duplicate tests
else if ( self.tests[ name ] ) {
throw new munit.AssertionError(
"Duplicate Test '" + name + "' on '" + self.nsPath + "'",
startFunc || self.ok
);
}
// Increment test count and mark it
self[ !!( test ) ? '_pass' : '_fail' ]( name, startFunc || self.ok, extra );
// Reached expected number of tests, close off
if ( self.options.expect > 0 && self.count >= self.options.expect ) {
self.close();
}
return self;
} | [
"function",
"(",
"name",
",",
"test",
",",
"startFunc",
",",
"extra",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"requireState",
"(",
"munit",
".",
"ASSERT_STATE_ACTIVE",
",",
"startFunc",
"||",
"self",
".",
"ok",
")",
";",
"if",
"(",
"!",
"munit",
".",
"isString",
"(",
"name",
")",
"||",
"!",
"name",
".",
"length",
")",
"{",
"throw",
"new",
"munit",
".",
"AssertionError",
"(",
"\"Name not found for test on '\"",
"+",
"self",
".",
"nsPath",
"+",
"\"'\"",
",",
"startFunc",
"||",
"self",
".",
"ok",
")",
";",
"}",
"else",
"if",
"(",
"self",
".",
"tests",
"[",
"name",
"]",
")",
"{",
"throw",
"new",
"munit",
".",
"AssertionError",
"(",
"\"Duplicate Test '\"",
"+",
"name",
"+",
"\"' on '\"",
"+",
"self",
".",
"nsPath",
"+",
"\"'\"",
",",
"startFunc",
"||",
"self",
".",
"ok",
")",
";",
"}",
"self",
"[",
"!",
"!",
"(",
"test",
")",
"?",
"'_pass'",
":",
"'_fail'",
"]",
"(",
"name",
",",
"startFunc",
"||",
"self",
".",
"ok",
",",
"extra",
")",
";",
"if",
"(",
"self",
".",
"options",
".",
"expect",
">",
"0",
"&&",
"self",
".",
"count",
">=",
"self",
".",
"options",
".",
"expect",
")",
"{",
"self",
".",
"close",
"(",
")",
";",
"}",
"return",
"self",
";",
"}"
]
| Basic boolean test | [
"Basic",
"boolean",
"test"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L441-L471 | train |
|
codenothing/munit | lib/assert.js | function( name, startFunc, extra ) {
if ( extra === undefined && ! munit.isFunction( startFunc ) ) {
extra = startFunc;
startFunc = undefined;
}
if ( munit.isError( extra ) ) {
extra = extra.message;
}
return this.ok( name, false, startFunc || this.fail, extra );
} | javascript | function( name, startFunc, extra ) {
if ( extra === undefined && ! munit.isFunction( startFunc ) ) {
extra = startFunc;
startFunc = undefined;
}
if ( munit.isError( extra ) ) {
extra = extra.message;
}
return this.ok( name, false, startFunc || this.fail, extra );
} | [
"function",
"(",
"name",
",",
"startFunc",
",",
"extra",
")",
"{",
"if",
"(",
"extra",
"===",
"undefined",
"&&",
"!",
"munit",
".",
"isFunction",
"(",
"startFunc",
")",
")",
"{",
"extra",
"=",
"startFunc",
";",
"startFunc",
"=",
"undefined",
";",
"}",
"if",
"(",
"munit",
".",
"isError",
"(",
"extra",
")",
")",
"{",
"extra",
"=",
"extra",
".",
"message",
";",
"}",
"return",
"this",
".",
"ok",
"(",
"name",
",",
"false",
",",
"startFunc",
"||",
"this",
".",
"fail",
",",
"extra",
")",
";",
"}"
]
| Shortcut for explicit failures | [
"Shortcut",
"for",
"explicit",
"failures"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L479-L490 | train |
|
codenothing/munit | lib/assert.js | function( name, value, match ) {
var self = this,
result = munit.isError( value ) ?
self._errorMatch( value, match ) :
{ passed: false, extra: "Value is not an Error '" + value + "'" };
return self.ok( name, result.passed, self.isError, result.extra );
} | javascript | function( name, value, match ) {
var self = this,
result = munit.isError( value ) ?
self._errorMatch( value, match ) :
{ passed: false, extra: "Value is not an Error '" + value + "'" };
return self.ok( name, result.passed, self.isError, result.extra );
} | [
"function",
"(",
"name",
",",
"value",
",",
"match",
")",
"{",
"var",
"self",
"=",
"this",
",",
"result",
"=",
"munit",
".",
"isError",
"(",
"value",
")",
"?",
"self",
".",
"_errorMatch",
"(",
"value",
",",
"match",
")",
":",
"{",
"passed",
":",
"false",
",",
"extra",
":",
"\"Value is not an Error '\"",
"+",
"value",
"+",
"\"'\"",
"}",
";",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"result",
".",
"passed",
",",
"self",
".",
"isError",
",",
"result",
".",
"extra",
")",
";",
"}"
]
| Testing value for Error object | [
"Testing",
"value",
"for",
"Error",
"object"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L553-L560 | train |
|
codenothing/munit | lib/assert.js | function( name, actual, expected ) {
return this.ok( name, actual !== expected, this.notEqual, "\nValues should not match\nActual:" + actual + "\nExpected:" + expected );
} | javascript | function( name, actual, expected ) {
return this.ok( name, actual !== expected, this.notEqual, "\nValues should not match\nActual:" + actual + "\nExpected:" + expected );
} | [
"function",
"(",
"name",
",",
"actual",
",",
"expected",
")",
"{",
"return",
"this",
".",
"ok",
"(",
"name",
",",
"actual",
"!==",
"expected",
",",
"this",
".",
"notEqual",
",",
"\"\\nValues should not match\\nActual:\"",
"+",
"\\n",
"+",
"\\n",
"+",
"actual",
")",
";",
"}"
]
| Strict un-comparison | [
"Strict",
"un",
"-",
"comparison"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L578-L580 | train |
|
codenothing/munit | lib/assert.js | function( name, upper, lower ) {
return this.ok( name, upper > lower, this.greaterThan, "\nUpper Value '" + upper + "' is not greater than lower value '" + lower + "'" );
} | javascript | function( name, upper, lower ) {
return this.ok( name, upper > lower, this.greaterThan, "\nUpper Value '" + upper + "' is not greater than lower value '" + lower + "'" );
} | [
"function",
"(",
"name",
",",
"upper",
",",
"lower",
")",
"{",
"return",
"this",
".",
"ok",
"(",
"name",
",",
"upper",
">",
"lower",
",",
"this",
".",
"greaterThan",
",",
"\"\\nUpper Value '\"",
"+",
"\\n",
"+",
"upper",
"+",
"\"' is not greater than lower value '\"",
"+",
"lower",
")",
";",
"}"
]
| Greater than comparison | [
"Greater",
"than",
"comparison"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L583-L585 | train |
|
codenothing/munit | lib/assert.js | function( name, lower, upper ) {
return this.ok( name, lower < upper, this.lessThan, "\nLower Value '" + lower + "' is not less than upper value '" + upper + "'" );
} | javascript | function( name, lower, upper ) {
return this.ok( name, lower < upper, this.lessThan, "\nLower Value '" + lower + "' is not less than upper value '" + upper + "'" );
} | [
"function",
"(",
"name",
",",
"lower",
",",
"upper",
")",
"{",
"return",
"this",
".",
"ok",
"(",
"name",
",",
"lower",
"<",
"upper",
",",
"this",
".",
"lessThan",
",",
"\"\\nLower Value '\"",
"+",
"\\n",
"+",
"lower",
"+",
"\"' is not less than upper value '\"",
"+",
"upper",
")",
";",
"}"
]
| Less than comparison | [
"Less",
"than",
"comparison"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L588-L590 | train |
|
codenothing/munit | lib/assert.js | function( name, value, lower, upper ) {
return this.ok(
name,
value > lower && value < upper,
this.between,
"\nValue '" + value + "' is not inbetween '" + lower + "' and '" + upper + "'"
);
} | javascript | function( name, value, lower, upper ) {
return this.ok(
name,
value > lower && value < upper,
this.between,
"\nValue '" + value + "' is not inbetween '" + lower + "' and '" + upper + "'"
);
} | [
"function",
"(",
"name",
",",
"value",
",",
"lower",
",",
"upper",
")",
"{",
"return",
"this",
".",
"ok",
"(",
"name",
",",
"value",
">",
"lower",
"&&",
"value",
"<",
"upper",
",",
"this",
".",
"between",
",",
"\"\\nValue '\"",
"+",
"\\n",
"+",
"value",
"+",
"\"' is not inbetween '\"",
"+",
"lower",
"+",
"\"' and '\"",
"+",
"upper",
")",
";",
"}"
]
| Value between boundary | [
"Value",
"between",
"boundary"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L593-L600 | train |
|
codenothing/munit | lib/assert.js | function( name, actual, expected ) {
var self = this, passed = true, extra = '';
try {
self._objectMatch( actual, expected );
}
catch ( e ) {
passed = false;
extra = e;
if ( ! munit.isString( e ) ) {
throw e;
}
}
return self.ok( name, passed, self.deepEqual, extra );
} | javascript | function( name, actual, expected ) {
var self = this, passed = true, extra = '';
try {
self._objectMatch( actual, expected );
}
catch ( e ) {
passed = false;
extra = e;
if ( ! munit.isString( e ) ) {
throw e;
}
}
return self.ok( name, passed, self.deepEqual, extra );
} | [
"function",
"(",
"name",
",",
"actual",
",",
"expected",
")",
"{",
"var",
"self",
"=",
"this",
",",
"passed",
"=",
"true",
",",
"extra",
"=",
"''",
";",
"try",
"{",
"self",
".",
"_objectMatch",
"(",
"actual",
",",
"expected",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"passed",
"=",
"false",
";",
"extra",
"=",
"e",
";",
"if",
"(",
"!",
"munit",
".",
"isString",
"(",
"e",
")",
")",
"{",
"throw",
"e",
";",
"}",
"}",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"passed",
",",
"self",
".",
"deepEqual",
",",
"extra",
")",
";",
"}"
]
| Deep equal handle | [
"Deep",
"equal",
"handle"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L603-L619 | train |
|
codenothing/munit | lib/assert.js | function( name, actual, expected ) {
var self = this, passed = true;
try {
self._objectMatch( actual, expected );
passed = false;
}
catch ( e ) {
}
return self.ok( name, passed, self.notDeepEqual, 'Objects are not supposed to match' );
} | javascript | function( name, actual, expected ) {
var self = this, passed = true;
try {
self._objectMatch( actual, expected );
passed = false;
}
catch ( e ) {
}
return self.ok( name, passed, self.notDeepEqual, 'Objects are not supposed to match' );
} | [
"function",
"(",
"name",
",",
"actual",
",",
"expected",
")",
"{",
"var",
"self",
"=",
"this",
",",
"passed",
"=",
"true",
";",
"try",
"{",
"self",
".",
"_objectMatch",
"(",
"actual",
",",
"expected",
")",
";",
"passed",
"=",
"false",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"passed",
",",
"self",
".",
"notDeepEqual",
",",
"'Objects are not supposed to match'",
")",
";",
"}"
]
| Not deep equal handle | [
"Not",
"deep",
"equal",
"handle"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L622-L633 | train |
|
codenothing/munit | lib/assert.js | function( name, match, block ) {
var self = this, result = { passed: false, extra: 'Block did not throw error' };
// Variable arguments
if ( block === undefined && munit.isFunction( match ) ) {
block = match;
match = undefined;
}
// Fail quick if block isn't a function
if ( ! munit.isFunction( block ) ) {
throw new Error( "Block passed to assert.throws is not a function: '" + block + "'" );
}
// test for throwing
try {
block();
}
catch ( e ) {
result = self._errorMatch( e, match );
}
return self.ok( name, result.passed, self.throws, result.extra );
} | javascript | function( name, match, block ) {
var self = this, result = { passed: false, extra: 'Block did not throw error' };
// Variable arguments
if ( block === undefined && munit.isFunction( match ) ) {
block = match;
match = undefined;
}
// Fail quick if block isn't a function
if ( ! munit.isFunction( block ) ) {
throw new Error( "Block passed to assert.throws is not a function: '" + block + "'" );
}
// test for throwing
try {
block();
}
catch ( e ) {
result = self._errorMatch( e, match );
}
return self.ok( name, result.passed, self.throws, result.extra );
} | [
"function",
"(",
"name",
",",
"match",
",",
"block",
")",
"{",
"var",
"self",
"=",
"this",
",",
"result",
"=",
"{",
"passed",
":",
"false",
",",
"extra",
":",
"'Block did not throw error'",
"}",
";",
"if",
"(",
"block",
"===",
"undefined",
"&&",
"munit",
".",
"isFunction",
"(",
"match",
")",
")",
"{",
"block",
"=",
"match",
";",
"match",
"=",
"undefined",
";",
"}",
"if",
"(",
"!",
"munit",
".",
"isFunction",
"(",
"block",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Block passed to assert.throws is not a function: '\"",
"+",
"block",
"+",
"\"'\"",
")",
";",
"}",
"try",
"{",
"block",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"result",
"=",
"self",
".",
"_errorMatch",
"(",
"e",
",",
"match",
")",
";",
"}",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"result",
".",
"passed",
",",
"self",
".",
"throws",
",",
"result",
".",
"extra",
")",
";",
"}"
]
| Run internal throw handle | [
"Run",
"internal",
"throw",
"handle"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L636-L659 | train |
|
codenothing/munit | lib/assert.js | function( name, block ) {
var self = this, passed = true;
try {
block();
}
catch ( e ) {
passed = false;
}
return self.ok( name, passed, self.doesNotThrow, 'Block does throw error' );
} | javascript | function( name, block ) {
var self = this, passed = true;
try {
block();
}
catch ( e ) {
passed = false;
}
return self.ok( name, passed, self.doesNotThrow, 'Block does throw error' );
} | [
"function",
"(",
"name",
",",
"block",
")",
"{",
"var",
"self",
"=",
"this",
",",
"passed",
"=",
"true",
";",
"try",
"{",
"block",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"passed",
"=",
"false",
";",
"}",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"passed",
",",
"self",
".",
"doesNotThrow",
",",
"'Block does throw error'",
")",
";",
"}"
]
| Run internal notThrow handle | [
"Run",
"internal",
"notThrow",
"handle"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L662-L673 | train |
|
codenothing/munit | lib/assert.js | function( name, actual, expected ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( expected ) ) {
passed = actual.getTime() === expected.getTime();
message = "Date '" + actual + "' does not match '" + expected + "'";
}
else {
message = munit.isDate( actual ) ?
"Expected value is not a Date object '" + expected + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateEquals, message );
} | javascript | function( name, actual, expected ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( expected ) ) {
passed = actual.getTime() === expected.getTime();
message = "Date '" + actual + "' does not match '" + expected + "'";
}
else {
message = munit.isDate( actual ) ?
"Expected value is not a Date object '" + expected + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateEquals, message );
} | [
"function",
"(",
"name",
",",
"actual",
",",
"expected",
")",
"{",
"var",
"self",
"=",
"this",
",",
"passed",
"=",
"false",
",",
"message",
"=",
"''",
";",
"if",
"(",
"munit",
".",
"isDate",
"(",
"actual",
")",
"&&",
"munit",
".",
"isDate",
"(",
"expected",
")",
")",
"{",
"passed",
"=",
"actual",
".",
"getTime",
"(",
")",
"===",
"expected",
".",
"getTime",
"(",
")",
";",
"message",
"=",
"\"Date '\"",
"+",
"actual",
"+",
"\"' does not match '\"",
"+",
"expected",
"+",
"\"'\"",
";",
"}",
"else",
"{",
"message",
"=",
"munit",
".",
"isDate",
"(",
"actual",
")",
"?",
"\"Expected value is not a Date object '\"",
"+",
"expected",
"+",
"\"'\"",
":",
"\"Actual value is not a Date object '\"",
"+",
"actual",
"+",
"\"'\"",
";",
"}",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"passed",
",",
"self",
".",
"dateEquals",
",",
"message",
")",
";",
"}"
]
| Matching date objects | [
"Matching",
"date",
"objects"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L676-L692 | train |
|
codenothing/munit | lib/assert.js | function( name, actual, lower ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( lower ) ) {
passed = actual.getTime() > lower.getTime();
message = "Date '" + actual + "' is not after '" + lower + "'";
}
else {
message = munit.isDate( actual ) ?
"Lower value is not a Date object '" + lower + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateAfter, message );
} | javascript | function( name, actual, lower ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( lower ) ) {
passed = actual.getTime() > lower.getTime();
message = "Date '" + actual + "' is not after '" + lower + "'";
}
else {
message = munit.isDate( actual ) ?
"Lower value is not a Date object '" + lower + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateAfter, message );
} | [
"function",
"(",
"name",
",",
"actual",
",",
"lower",
")",
"{",
"var",
"self",
"=",
"this",
",",
"passed",
"=",
"false",
",",
"message",
"=",
"''",
";",
"if",
"(",
"munit",
".",
"isDate",
"(",
"actual",
")",
"&&",
"munit",
".",
"isDate",
"(",
"lower",
")",
")",
"{",
"passed",
"=",
"actual",
".",
"getTime",
"(",
")",
">",
"lower",
".",
"getTime",
"(",
")",
";",
"message",
"=",
"\"Date '\"",
"+",
"actual",
"+",
"\"' is not after '\"",
"+",
"lower",
"+",
"\"'\"",
";",
"}",
"else",
"{",
"message",
"=",
"munit",
".",
"isDate",
"(",
"actual",
")",
"?",
"\"Lower value is not a Date object '\"",
"+",
"lower",
"+",
"\"'\"",
":",
"\"Actual value is not a Date object '\"",
"+",
"actual",
"+",
"\"'\"",
";",
"}",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"passed",
",",
"self",
".",
"dateAfter",
",",
"message",
")",
";",
"}"
]
| Tests date is after another date | [
"Tests",
"date",
"is",
"after",
"another",
"date"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L695-L711 | train |
|
codenothing/munit | lib/assert.js | function( name, actual, upper ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( upper ) ) {
passed = actual.getTime() < upper.getTime();
message = "Date '" + actual + "' is not before '" + upper + "'";
}
else {
message = munit.isDate( actual ) ?
"Upper value is not a Date object '" + upper + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateBefore, message );
} | javascript | function( name, actual, upper ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( upper ) ) {
passed = actual.getTime() < upper.getTime();
message = "Date '" + actual + "' is not before '" + upper + "'";
}
else {
message = munit.isDate( actual ) ?
"Upper value is not a Date object '" + upper + "'" :
"Actual value is not a Date object '" + actual + "'";
}
return self.ok( name, passed, self.dateBefore, message );
} | [
"function",
"(",
"name",
",",
"actual",
",",
"upper",
")",
"{",
"var",
"self",
"=",
"this",
",",
"passed",
"=",
"false",
",",
"message",
"=",
"''",
";",
"if",
"(",
"munit",
".",
"isDate",
"(",
"actual",
")",
"&&",
"munit",
".",
"isDate",
"(",
"upper",
")",
")",
"{",
"passed",
"=",
"actual",
".",
"getTime",
"(",
")",
"<",
"upper",
".",
"getTime",
"(",
")",
";",
"message",
"=",
"\"Date '\"",
"+",
"actual",
"+",
"\"' is not before '\"",
"+",
"upper",
"+",
"\"'\"",
";",
"}",
"else",
"{",
"message",
"=",
"munit",
".",
"isDate",
"(",
"actual",
")",
"?",
"\"Upper value is not a Date object '\"",
"+",
"upper",
"+",
"\"'\"",
":",
"\"Actual value is not a Date object '\"",
"+",
"actual",
"+",
"\"'\"",
";",
"}",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"passed",
",",
"self",
".",
"dateBefore",
",",
"message",
")",
";",
"}"
]
| Tests date is before another date | [
"Tests",
"date",
"is",
"before",
"another",
"date"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L714-L730 | train |
|
codenothing/munit | lib/assert.js | function( name, actual, lower, upper ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( lower ) && munit.isDate( upper ) ) {
passed = actual.getTime() > lower.getTime() && actual.getTime() < upper.getTime();
message = "Date '" + actual + "' is not between '" + lower + "' and '" + upper + "'";
}
else {
message = ! munit.isDate( actual ) ? "Actual value is not a Date object '" + actual + "'" :
! munit.isDate( lower ) ? "Lower value is not a Date object '" + lower + "'" :
"Upper value is not a Date object '" + upper + "'";
}
return self.ok( name, passed, self.dateBetween, message );
} | javascript | function( name, actual, lower, upper ) {
var self = this,
passed = false,
message = '';
if ( munit.isDate( actual ) && munit.isDate( lower ) && munit.isDate( upper ) ) {
passed = actual.getTime() > lower.getTime() && actual.getTime() < upper.getTime();
message = "Date '" + actual + "' is not between '" + lower + "' and '" + upper + "'";
}
else {
message = ! munit.isDate( actual ) ? "Actual value is not a Date object '" + actual + "'" :
! munit.isDate( lower ) ? "Lower value is not a Date object '" + lower + "'" :
"Upper value is not a Date object '" + upper + "'";
}
return self.ok( name, passed, self.dateBetween, message );
} | [
"function",
"(",
"name",
",",
"actual",
",",
"lower",
",",
"upper",
")",
"{",
"var",
"self",
"=",
"this",
",",
"passed",
"=",
"false",
",",
"message",
"=",
"''",
";",
"if",
"(",
"munit",
".",
"isDate",
"(",
"actual",
")",
"&&",
"munit",
".",
"isDate",
"(",
"lower",
")",
"&&",
"munit",
".",
"isDate",
"(",
"upper",
")",
")",
"{",
"passed",
"=",
"actual",
".",
"getTime",
"(",
")",
">",
"lower",
".",
"getTime",
"(",
")",
"&&",
"actual",
".",
"getTime",
"(",
")",
"<",
"upper",
".",
"getTime",
"(",
")",
";",
"message",
"=",
"\"Date '\"",
"+",
"actual",
"+",
"\"' is not between '\"",
"+",
"lower",
"+",
"\"' and '\"",
"+",
"upper",
"+",
"\"'\"",
";",
"}",
"else",
"{",
"message",
"=",
"!",
"munit",
".",
"isDate",
"(",
"actual",
")",
"?",
"\"Actual value is not a Date object '\"",
"+",
"actual",
"+",
"\"'\"",
":",
"!",
"munit",
".",
"isDate",
"(",
"lower",
")",
"?",
"\"Lower value is not a Date object '\"",
"+",
"lower",
"+",
"\"'\"",
":",
"\"Upper value is not a Date object '\"",
"+",
"upper",
"+",
"\"'\"",
";",
"}",
"return",
"self",
".",
"ok",
"(",
"name",
",",
"passed",
",",
"self",
".",
"dateBetween",
",",
"message",
")",
";",
"}"
]
| Tests date is between two other dates | [
"Tests",
"date",
"is",
"between",
"two",
"other",
"dates"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L733-L749 | train |
|
codenothing/munit | lib/assert.js | function( name, handle ) {
var self = this;
// Can only add custom assertions when module hasn't been triggered yet
self.requireMaxState( munit.ASSERT_STATE_DEFAULT, self.custom );
// Block on reserved words
if ( munit.customReserved.indexOf( name ) > -1 ) {
throw new Error( "'" + name + "' is a reserved name and cannot be added as a custom assertion test" );
}
// Attach handle to assertion module and all submodules
self[ name ] = handle;
munit.each( self.ns, function( mod ) {
mod.custom( name, handle );
});
return self;
} | javascript | function( name, handle ) {
var self = this;
// Can only add custom assertions when module hasn't been triggered yet
self.requireMaxState( munit.ASSERT_STATE_DEFAULT, self.custom );
// Block on reserved words
if ( munit.customReserved.indexOf( name ) > -1 ) {
throw new Error( "'" + name + "' is a reserved name and cannot be added as a custom assertion test" );
}
// Attach handle to assertion module and all submodules
self[ name ] = handle;
munit.each( self.ns, function( mod ) {
mod.custom( name, handle );
});
return self;
} | [
"function",
"(",
"name",
",",
"handle",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"requireMaxState",
"(",
"munit",
".",
"ASSERT_STATE_DEFAULT",
",",
"self",
".",
"custom",
")",
";",
"if",
"(",
"munit",
".",
"customReserved",
".",
"indexOf",
"(",
"name",
")",
">",
"-",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"'\"",
"+",
"name",
"+",
"\"' is a reserved name and cannot be added as a custom assertion test\"",
")",
";",
"}",
"self",
"[",
"name",
"]",
"=",
"handle",
";",
"munit",
".",
"each",
"(",
"self",
".",
"ns",
",",
"function",
"(",
"mod",
")",
"{",
"mod",
".",
"custom",
"(",
"name",
",",
"handle",
")",
";",
"}",
")",
";",
"return",
"self",
";",
"}"
]
| Custom test additions | [
"Custom",
"test",
"additions"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L787-L805 | train |
|
codenothing/munit | lib/assert.js | function(){
var self = this;
// Can only start a module that hasn't been started yet
self.requireState( munit.ASSERT_STATE_DEFAULT, self.trigger );
// Setup and trigger module
self.start = self.end = Date.now();
// Parent namespaces sometimes don't have tests
// Also close out paths that aren't part of the focus
if ( ! self.callback || ! munit.render.focusPath( self.nsPath ) ) {
self.state = munit.ASSERT_STATE_CLOSED;
return self._close();
}
// Trigger test setup first
self._setup(function( e, setupCallback ) {
if ( e ) {
self.fail( "[munit] Failed to setup '" + self.nsPath + "' module", setupCallback, e );
return self.close();
}
// Run test
self.callback( self, self.queue );
// If module isn't finished, then prove that it's supposed to be asynchronous
if ( self.state < munit.ASSERT_STATE_TEARDOWN ) {
// Only tear it down if no timeout is specified
if ( self.options.timeout < 1 ) {
self.close();
}
// Delayed close
else if ( ! self.isAsync ) {
self.isAsync = true;
self._timerStart = Date.now();
self._timeid = setTimeout(function(){
if ( self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, self.options.timeout );
}
}
});
return self;
} | javascript | function(){
var self = this;
// Can only start a module that hasn't been started yet
self.requireState( munit.ASSERT_STATE_DEFAULT, self.trigger );
// Setup and trigger module
self.start = self.end = Date.now();
// Parent namespaces sometimes don't have tests
// Also close out paths that aren't part of the focus
if ( ! self.callback || ! munit.render.focusPath( self.nsPath ) ) {
self.state = munit.ASSERT_STATE_CLOSED;
return self._close();
}
// Trigger test setup first
self._setup(function( e, setupCallback ) {
if ( e ) {
self.fail( "[munit] Failed to setup '" + self.nsPath + "' module", setupCallback, e );
return self.close();
}
// Run test
self.callback( self, self.queue );
// If module isn't finished, then prove that it's supposed to be asynchronous
if ( self.state < munit.ASSERT_STATE_TEARDOWN ) {
// Only tear it down if no timeout is specified
if ( self.options.timeout < 1 ) {
self.close();
}
// Delayed close
else if ( ! self.isAsync ) {
self.isAsync = true;
self._timerStart = Date.now();
self._timeid = setTimeout(function(){
if ( self.state < munit.ASSERT_STATE_TEARDOWN ) {
self.close();
}
}, self.options.timeout );
}
}
});
return self;
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"self",
".",
"requireState",
"(",
"munit",
".",
"ASSERT_STATE_DEFAULT",
",",
"self",
".",
"trigger",
")",
";",
"self",
".",
"start",
"=",
"self",
".",
"end",
"=",
"Date",
".",
"now",
"(",
")",
";",
"if",
"(",
"!",
"self",
".",
"callback",
"||",
"!",
"munit",
".",
"render",
".",
"focusPath",
"(",
"self",
".",
"nsPath",
")",
")",
"{",
"self",
".",
"state",
"=",
"munit",
".",
"ASSERT_STATE_CLOSED",
";",
"return",
"self",
".",
"_close",
"(",
")",
";",
"}",
"self",
".",
"_setup",
"(",
"function",
"(",
"e",
",",
"setupCallback",
")",
"{",
"if",
"(",
"e",
")",
"{",
"self",
".",
"fail",
"(",
"\"[munit] Failed to setup '\"",
"+",
"self",
".",
"nsPath",
"+",
"\"' module\"",
",",
"setupCallback",
",",
"e",
")",
";",
"return",
"self",
".",
"close",
"(",
")",
";",
"}",
"self",
".",
"callback",
"(",
"self",
",",
"self",
".",
"queue",
")",
";",
"if",
"(",
"self",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_TEARDOWN",
")",
"{",
"if",
"(",
"self",
".",
"options",
".",
"timeout",
"<",
"1",
")",
"{",
"self",
".",
"close",
"(",
")",
";",
"}",
"else",
"if",
"(",
"!",
"self",
".",
"isAsync",
")",
"{",
"self",
".",
"isAsync",
"=",
"true",
";",
"self",
".",
"_timerStart",
"=",
"Date",
".",
"now",
"(",
")",
";",
"self",
".",
"_timeid",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"self",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_TEARDOWN",
")",
"{",
"self",
".",
"close",
"(",
")",
";",
"}",
"}",
",",
"self",
".",
"options",
".",
"timeout",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"self",
";",
"}"
]
| Trigger module's tests | [
"Trigger",
"module",
"s",
"tests"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L900-L946 | train |
|
codenothing/munit | lib/assert.js | function(){
var self = this,
nodeVersion = process.version.replace( /\./g, '_' ),
xml = "<testsuite name='" + munit._xmlEncode( nodeVersion + self.nsPath ) + "' tests='" + self.count + "' failures='" + self.failed + "' skipped='" + self.skipped + "' time='" + ( ( self.end - self.start ) / 1000 ) + "'>";
self.list.forEach(function( result ) {
xml += result.junit();
});
xml += "</testsuite>";
return xml;
} | javascript | function(){
var self = this,
nodeVersion = process.version.replace( /\./g, '_' ),
xml = "<testsuite name='" + munit._xmlEncode( nodeVersion + self.nsPath ) + "' tests='" + self.count + "' failures='" + self.failed + "' skipped='" + self.skipped + "' time='" + ( ( self.end - self.start ) / 1000 ) + "'>";
self.list.forEach(function( result ) {
xml += result.junit();
});
xml += "</testsuite>";
return xml;
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
",",
"nodeVersion",
"=",
"process",
".",
"version",
".",
"replace",
"(",
"/",
"\\.",
"/",
"g",
",",
"'_'",
")",
",",
"xml",
"=",
"\"<testsuite name='\"",
"+",
"munit",
".",
"_xmlEncode",
"(",
"nodeVersion",
"+",
"self",
".",
"nsPath",
")",
"+",
"\"' tests='\"",
"+",
"self",
".",
"count",
"+",
"\"' failures='\"",
"+",
"self",
".",
"failed",
"+",
"\"' skipped='\"",
"+",
"self",
".",
"skipped",
"+",
"\"' time='\"",
"+",
"(",
"(",
"self",
".",
"end",
"-",
"self",
".",
"start",
")",
"/",
"1000",
")",
"+",
"\"'>\"",
";",
"self",
".",
"list",
".",
"forEach",
"(",
"function",
"(",
"result",
")",
"{",
"xml",
"+=",
"result",
".",
"junit",
"(",
")",
";",
"}",
")",
";",
"xml",
"+=",
"\"</testsuite>\"",
";",
"return",
"xml",
";",
"}"
]
| Returns XML result format | [
"Returns",
"XML",
"result",
"format"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L949-L960 | train |
|
codenothing/munit | lib/assert.js | function(){
var self = this;
return {
name: self.nsPath.split( '.' ).pop(),
nsPath: self.nsPath,
count: self.count,
passed: self.passed,
failed: self.failed,
skipped: self.skipped,
start: self.start,
end: self.end,
time: self.end - self.start,
tests: self.list,
ns: self.ns,
};
} | javascript | function(){
var self = this;
return {
name: self.nsPath.split( '.' ).pop(),
nsPath: self.nsPath,
count: self.count,
passed: self.passed,
failed: self.failed,
skipped: self.skipped,
start: self.start,
end: self.end,
time: self.end - self.start,
tests: self.list,
ns: self.ns,
};
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"return",
"{",
"name",
":",
"self",
".",
"nsPath",
".",
"split",
"(",
"'.'",
")",
".",
"pop",
"(",
")",
",",
"nsPath",
":",
"self",
".",
"nsPath",
",",
"count",
":",
"self",
".",
"count",
",",
"passed",
":",
"self",
".",
"passed",
",",
"failed",
":",
"self",
".",
"failed",
",",
"skipped",
":",
"self",
".",
"skipped",
",",
"start",
":",
"self",
".",
"start",
",",
"end",
":",
"self",
".",
"end",
",",
"time",
":",
"self",
".",
"end",
"-",
"self",
".",
"start",
",",
"tests",
":",
"self",
".",
"list",
",",
"ns",
":",
"self",
".",
"ns",
",",
"}",
";",
"}"
]
| JSON result format | [
"JSON",
"result",
"format"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L963-L979 | train |
|
codenothing/munit | lib/assert.js | function( startFunc, forced ) {
var self = this, i, mod;
// Can only close an active module
self.requireState( munit.ASSERT_STATE_ACTIVE, self.close );
// Add fail marker if no tests were ran
if ( self.count < 1 ) {
self.fail( "[munit] No tests ran in this module" );
}
// Auto close out any spies
self._spies.reverse().forEach(function( spy ) {
spy.restore();
});
// Proxy teardown to pass start function and forced state
self._teardown(function( e, teardownCallback ) {
if ( e ) {
self._fail( "[munit] failed to teardown '" + self.nsPath + "' module properly", teardownCallback );
}
self._close( startFunc || self.close, forced );
});
return self;
} | javascript | function( startFunc, forced ) {
var self = this, i, mod;
// Can only close an active module
self.requireState( munit.ASSERT_STATE_ACTIVE, self.close );
// Add fail marker if no tests were ran
if ( self.count < 1 ) {
self.fail( "[munit] No tests ran in this module" );
}
// Auto close out any spies
self._spies.reverse().forEach(function( spy ) {
spy.restore();
});
// Proxy teardown to pass start function and forced state
self._teardown(function( e, teardownCallback ) {
if ( e ) {
self._fail( "[munit] failed to teardown '" + self.nsPath + "' module properly", teardownCallback );
}
self._close( startFunc || self.close, forced );
});
return self;
} | [
"function",
"(",
"startFunc",
",",
"forced",
")",
"{",
"var",
"self",
"=",
"this",
",",
"i",
",",
"mod",
";",
"self",
".",
"requireState",
"(",
"munit",
".",
"ASSERT_STATE_ACTIVE",
",",
"self",
".",
"close",
")",
";",
"if",
"(",
"self",
".",
"count",
"<",
"1",
")",
"{",
"self",
".",
"fail",
"(",
"\"[munit] No tests ran in this module\"",
")",
";",
"}",
"self",
".",
"_spies",
".",
"reverse",
"(",
")",
".",
"forEach",
"(",
"function",
"(",
"spy",
")",
"{",
"spy",
".",
"restore",
"(",
")",
";",
"}",
")",
";",
"self",
".",
"_teardown",
"(",
"function",
"(",
"e",
",",
"teardownCallback",
")",
"{",
"if",
"(",
"e",
")",
"{",
"self",
".",
"_fail",
"(",
"\"[munit] failed to teardown '\"",
"+",
"self",
".",
"nsPath",
"+",
"\"' module properly\"",
",",
"teardownCallback",
")",
";",
"}",
"self",
".",
"_close",
"(",
"startFunc",
"||",
"self",
".",
"close",
",",
"forced",
")",
";",
"}",
")",
";",
"return",
"self",
";",
"}"
]
| Forcing close of module | [
"Forcing",
"close",
"of",
"module"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L982-L1008 | train |
|
codenothing/munit | lib/assert.js | function( startFunc, forced ) {
var self = this, i, mod;
// Handle invalid number of tests ran
if ( self.options.expect > 0 && self.count < self.options.expect && munit.render.focusPath( self.nsPath ) ) {
self._fail(
'[munit] Unexpected End',
startFunc || self._close,
'Expecting ' + self.options.expect + ' tests, only ' + self.count + ' ran.'
);
}
else if ( self.count < 1 && self.callback && munit.render.focusPath( self.nsPath ) ) {
self._fail(
"[munit] No Tests Found",
startFunc || self._close,
"Module closed without any tests being ran."
);
}
// Remove timer
if ( self._timeid ) {
self._timeid = clearTimeout( self._timeid );
}
// Meta
self.end = Date.now();
// Readd the queue back to the stack
if ( self.options.autoQueue && self.queue ) {
munit.queue.add( self.queue );
self.queue = null;
}
// Check to see if submodules have closed off yet
for ( i in self.ns ) {
mod = self.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_CLOSED ) {
// Force close them if needed
if ( forced ) {
mod.close( startFunc || self._close, forced );
}
else {
return self;
}
}
}
// All submodules have closed off, can mark this one as finished
return self.finish( startFunc, forced );
} | javascript | function( startFunc, forced ) {
var self = this, i, mod;
// Handle invalid number of tests ran
if ( self.options.expect > 0 && self.count < self.options.expect && munit.render.focusPath( self.nsPath ) ) {
self._fail(
'[munit] Unexpected End',
startFunc || self._close,
'Expecting ' + self.options.expect + ' tests, only ' + self.count + ' ran.'
);
}
else if ( self.count < 1 && self.callback && munit.render.focusPath( self.nsPath ) ) {
self._fail(
"[munit] No Tests Found",
startFunc || self._close,
"Module closed without any tests being ran."
);
}
// Remove timer
if ( self._timeid ) {
self._timeid = clearTimeout( self._timeid );
}
// Meta
self.end = Date.now();
// Readd the queue back to the stack
if ( self.options.autoQueue && self.queue ) {
munit.queue.add( self.queue );
self.queue = null;
}
// Check to see if submodules have closed off yet
for ( i in self.ns ) {
mod = self.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_CLOSED ) {
// Force close them if needed
if ( forced ) {
mod.close( startFunc || self._close, forced );
}
else {
return self;
}
}
}
// All submodules have closed off, can mark this one as finished
return self.finish( startFunc, forced );
} | [
"function",
"(",
"startFunc",
",",
"forced",
")",
"{",
"var",
"self",
"=",
"this",
",",
"i",
",",
"mod",
";",
"if",
"(",
"self",
".",
"options",
".",
"expect",
">",
"0",
"&&",
"self",
".",
"count",
"<",
"self",
".",
"options",
".",
"expect",
"&&",
"munit",
".",
"render",
".",
"focusPath",
"(",
"self",
".",
"nsPath",
")",
")",
"{",
"self",
".",
"_fail",
"(",
"'[munit] Unexpected End'",
",",
"startFunc",
"||",
"self",
".",
"_close",
",",
"'Expecting '",
"+",
"self",
".",
"options",
".",
"expect",
"+",
"' tests, only '",
"+",
"self",
".",
"count",
"+",
"' ran.'",
")",
";",
"}",
"else",
"if",
"(",
"self",
".",
"count",
"<",
"1",
"&&",
"self",
".",
"callback",
"&&",
"munit",
".",
"render",
".",
"focusPath",
"(",
"self",
".",
"nsPath",
")",
")",
"{",
"self",
".",
"_fail",
"(",
"\"[munit] No Tests Found\"",
",",
"startFunc",
"||",
"self",
".",
"_close",
",",
"\"Module closed without any tests being ran.\"",
")",
";",
"}",
"if",
"(",
"self",
".",
"_timeid",
")",
"{",
"self",
".",
"_timeid",
"=",
"clearTimeout",
"(",
"self",
".",
"_timeid",
")",
";",
"}",
"self",
".",
"end",
"=",
"Date",
".",
"now",
"(",
")",
";",
"if",
"(",
"self",
".",
"options",
".",
"autoQueue",
"&&",
"self",
".",
"queue",
")",
"{",
"munit",
".",
"queue",
".",
"add",
"(",
"self",
".",
"queue",
")",
";",
"self",
".",
"queue",
"=",
"null",
";",
"}",
"for",
"(",
"i",
"in",
"self",
".",
"ns",
")",
"{",
"mod",
"=",
"self",
".",
"ns",
"[",
"i",
"]",
";",
"if",
"(",
"mod",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_CLOSED",
")",
"{",
"if",
"(",
"forced",
")",
"{",
"mod",
".",
"close",
"(",
"startFunc",
"||",
"self",
".",
"_close",
",",
"forced",
")",
";",
"}",
"else",
"{",
"return",
"self",
";",
"}",
"}",
"}",
"return",
"self",
".",
"finish",
"(",
"startFunc",
",",
"forced",
")",
";",
"}"
]
| Closing of module after teardown process | [
"Closing",
"of",
"module",
"after",
"teardown",
"process"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L1011-L1061 | train |
|
codenothing/munit | lib/assert.js | function( startFunc, forced ) {
var self = this, i, mod;
// Can only finish an module that's in a closed state
self.requireState( munit.ASSERT_STATE_CLOSED, startFunc || self.finish );
// Flip state to finished
self.state = munit.ASSERT_STATE_FINISHED;
// Force close each submodule if necessary
for ( i in self.ns ) {
mod = self.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_CLOSED ) {
mod.close( startFunc || self.finish, true );
}
}
// Only print out results if on the focus path
if ( munit.render.focusPath( self.nsPath ) ) {
self._flush();
}
// Finish parent if not forced by it
if ( ! forced ) {
if ( self.parAssert ) {
if ( self.parAssert.state < munit.ASSERT_STATE_CLOSED ) {
munit.render.check();
return self;
}
for ( i in self.parAssert.ns ) {
mod = self.parAssert.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_FINISHED ) {
munit.render.check();
return self;
}
}
self.parAssert.finish();
}
else {
munit.render.check();
}
}
return self;
} | javascript | function( startFunc, forced ) {
var self = this, i, mod;
// Can only finish an module that's in a closed state
self.requireState( munit.ASSERT_STATE_CLOSED, startFunc || self.finish );
// Flip state to finished
self.state = munit.ASSERT_STATE_FINISHED;
// Force close each submodule if necessary
for ( i in self.ns ) {
mod = self.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_CLOSED ) {
mod.close( startFunc || self.finish, true );
}
}
// Only print out results if on the focus path
if ( munit.render.focusPath( self.nsPath ) ) {
self._flush();
}
// Finish parent if not forced by it
if ( ! forced ) {
if ( self.parAssert ) {
if ( self.parAssert.state < munit.ASSERT_STATE_CLOSED ) {
munit.render.check();
return self;
}
for ( i in self.parAssert.ns ) {
mod = self.parAssert.ns[ i ];
if ( mod.state < munit.ASSERT_STATE_FINISHED ) {
munit.render.check();
return self;
}
}
self.parAssert.finish();
}
else {
munit.render.check();
}
}
return self;
} | [
"function",
"(",
"startFunc",
",",
"forced",
")",
"{",
"var",
"self",
"=",
"this",
",",
"i",
",",
"mod",
";",
"self",
".",
"requireState",
"(",
"munit",
".",
"ASSERT_STATE_CLOSED",
",",
"startFunc",
"||",
"self",
".",
"finish",
")",
";",
"self",
".",
"state",
"=",
"munit",
".",
"ASSERT_STATE_FINISHED",
";",
"for",
"(",
"i",
"in",
"self",
".",
"ns",
")",
"{",
"mod",
"=",
"self",
".",
"ns",
"[",
"i",
"]",
";",
"if",
"(",
"mod",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_CLOSED",
")",
"{",
"mod",
".",
"close",
"(",
"startFunc",
"||",
"self",
".",
"finish",
",",
"true",
")",
";",
"}",
"}",
"if",
"(",
"munit",
".",
"render",
".",
"focusPath",
"(",
"self",
".",
"nsPath",
")",
")",
"{",
"self",
".",
"_flush",
"(",
")",
";",
"}",
"if",
"(",
"!",
"forced",
")",
"{",
"if",
"(",
"self",
".",
"parAssert",
")",
"{",
"if",
"(",
"self",
".",
"parAssert",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_CLOSED",
")",
"{",
"munit",
".",
"render",
".",
"check",
"(",
")",
";",
"return",
"self",
";",
"}",
"for",
"(",
"i",
"in",
"self",
".",
"parAssert",
".",
"ns",
")",
"{",
"mod",
"=",
"self",
".",
"parAssert",
".",
"ns",
"[",
"i",
"]",
";",
"if",
"(",
"mod",
".",
"state",
"<",
"munit",
".",
"ASSERT_STATE_FINISHED",
")",
"{",
"munit",
".",
"render",
".",
"check",
"(",
")",
";",
"return",
"self",
";",
"}",
"}",
"self",
".",
"parAssert",
".",
"finish",
"(",
")",
";",
"}",
"else",
"{",
"munit",
".",
"render",
".",
"check",
"(",
")",
";",
"}",
"}",
"return",
"self",
";",
"}"
]
| Finish this module and all sub modules | [
"Finish",
"this",
"module",
"and",
"all",
"sub",
"modules"
]
| aedf3f31aafc05441970eec49eeeb81174c14033 | https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/assert.js#L1064-L1112 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.