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 |
---|---|---|---|---|---|---|---|---|---|---|---|
rei/rei-cedar
|
build/component-docs-build.js
|
slotsAPIObject
|
function slotsAPIObject(vueObj) {
slotsObj = vueObj["slots"] || {}
let slots = []
for (const slot in slotsObj) {
if (slotsObj.hasOwnProperty(slot)) {
const ele = {
"name": `${slot}`,
"description": `${slotsObj[slot]["description"] || 'MISSING DESCRIPTION'}`
}
slots.push(ele)
}
}
return slots.length > 0 ? {slots} : null
}
|
javascript
|
function slotsAPIObject(vueObj) {
slotsObj = vueObj["slots"] || {}
let slots = []
for (const slot in slotsObj) {
if (slotsObj.hasOwnProperty(slot)) {
const ele = {
"name": `${slot}`,
"description": `${slotsObj[slot]["description"] || 'MISSING DESCRIPTION'}`
}
slots.push(ele)
}
}
return slots.length > 0 ? {slots} : null
}
|
[
"function",
"slotsAPIObject",
"(",
"vueObj",
")",
"{",
"slotsObj",
"=",
"vueObj",
"[",
"\"slots\"",
"]",
"||",
"{",
"}",
"let",
"slots",
"=",
"[",
"]",
"for",
"(",
"const",
"slot",
"in",
"slotsObj",
")",
"{",
"if",
"(",
"slotsObj",
".",
"hasOwnProperty",
"(",
"slot",
")",
")",
"{",
"const",
"ele",
"=",
"{",
"\"name\"",
":",
"`",
"${",
"slot",
"}",
"`",
",",
"\"description\"",
":",
"`",
"${",
"slotsObj",
"[",
"slot",
"]",
"[",
"\"description\"",
"]",
"||",
"'MISSING DESCRIPTION'",
"}",
"`",
"}",
"slots",
".",
"push",
"(",
"ele",
")",
"}",
"}",
"return",
"slots",
".",
"length",
">",
"0",
"?",
"{",
"slots",
"}",
":",
"null",
"}"
] |
Create object representing component slots
@param {Object} -- JSON object from vue-docgen-api library
@returns {Object} -- Object for component slots that goes into Cedar Data Object
|
[
"Create",
"object",
"representing",
"component",
"slots"
] |
5ddcce5ccda8fee41235483760332ad5e63c5455
|
https://github.com/rei/rei-cedar/blob/5ddcce5ccda8fee41235483760332ad5e63c5455/build/component-docs-build.js#L184-L198
|
train
|
rei/rei-cedar
|
src/utils/propValidator.js
|
validateProp
|
function validateProp(propValue, validArr, responsive = true) {
const strArr = propValue.split(' ');
return strArr.every((mod) => {
const modValid = validArr.some((validStr) => {
if (responsive) {
return (
mod === validStr
|| mod === `${validStr}@xs`
|| mod === `${validStr}@sm`
|| mod === `${validStr}@md`
|| mod === `${validStr}@lg`
);
}
return (mod === validStr);
});
if (!modValid) {
console.error(`Invalid prop value: ${mod}`); // eslint-disable-line no-console
}
return modValid;
});
}
|
javascript
|
function validateProp(propValue, validArr, responsive = true) {
const strArr = propValue.split(' ');
return strArr.every((mod) => {
const modValid = validArr.some((validStr) => {
if (responsive) {
return (
mod === validStr
|| mod === `${validStr}@xs`
|| mod === `${validStr}@sm`
|| mod === `${validStr}@md`
|| mod === `${validStr}@lg`
);
}
return (mod === validStr);
});
if (!modValid) {
console.error(`Invalid prop value: ${mod}`); // eslint-disable-line no-console
}
return modValid;
});
}
|
[
"function",
"validateProp",
"(",
"propValue",
",",
"validArr",
",",
"responsive",
"=",
"true",
")",
"{",
"const",
"strArr",
"=",
"propValue",
".",
"split",
"(",
"' '",
")",
";",
"return",
"strArr",
".",
"every",
"(",
"(",
"mod",
")",
"=>",
"{",
"const",
"modValid",
"=",
"validArr",
".",
"some",
"(",
"(",
"validStr",
")",
"=>",
"{",
"if",
"(",
"responsive",
")",
"{",
"return",
"(",
"mod",
"===",
"validStr",
"||",
"mod",
"===",
"`",
"${",
"validStr",
"}",
"`",
"||",
"mod",
"===",
"`",
"${",
"validStr",
"}",
"`",
"||",
"mod",
"===",
"`",
"${",
"validStr",
"}",
"`",
"||",
"mod",
"===",
"`",
"${",
"validStr",
"}",
"`",
")",
";",
"}",
"return",
"(",
"mod",
"===",
"validStr",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"modValid",
")",
"{",
"console",
".",
"error",
"(",
"`",
"${",
"mod",
"}",
"`",
")",
";",
"}",
"return",
"modValid",
";",
"}",
")",
";",
"}"
] |
Validates space separated string against an array of accepted values.
@param {String} propValue -- Space separated string (provided by the user)
@param {Array} validArr -- Array of values that are considered "valid"
@param {Boolean} responsive -- Enables validation of validArr values with '@sm', '@md', '@lg' added to them
|
[
"Validates",
"space",
"separated",
"string",
"against",
"an",
"array",
"of",
"accepted",
"values",
"."
] |
5ddcce5ccda8fee41235483760332ad5e63c5455
|
https://github.com/rei/rei-cedar/blob/5ddcce5ccda8fee41235483760332ad5e63c5455/src/utils/propValidator.js#L7-L28
|
train
|
rei/rei-cedar
|
build/component-build.js
|
build
|
function build(info, sharedOpts={}, compOpts={}, pluginOpts={}) {
const dir = process.cwd();
const [org, name] = info.name.split('/');
const outputPath = `${dir}/${config.outDir}`;
console.log(chalk.cyan(`Building ${name}...\n`));
return new Promise((resolve, reject)=>{
rm(
outputPath,
(err) => {
if (err) {
// throw err
reject(err);
}
webpack(createWebpackConfig(dir, name, sharedOpts, compOpts, pluginOpts), (err2, stats) => {
if (err2) {
// throw err2;
reject(err2);
}
stats.stats.forEach(stat => {
process.stdout.write(`${stat.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false,
})}\n\n`);
})
console.log(chalk.cyan(`Build of ${name} complete.\n`));
resolve();
});
}
);
});
}
|
javascript
|
function build(info, sharedOpts={}, compOpts={}, pluginOpts={}) {
const dir = process.cwd();
const [org, name] = info.name.split('/');
const outputPath = `${dir}/${config.outDir}`;
console.log(chalk.cyan(`Building ${name}...\n`));
return new Promise((resolve, reject)=>{
rm(
outputPath,
(err) => {
if (err) {
// throw err
reject(err);
}
webpack(createWebpackConfig(dir, name, sharedOpts, compOpts, pluginOpts), (err2, stats) => {
if (err2) {
// throw err2;
reject(err2);
}
stats.stats.forEach(stat => {
process.stdout.write(`${stat.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false,
})}\n\n`);
})
console.log(chalk.cyan(`Build of ${name} complete.\n`));
resolve();
});
}
);
});
}
|
[
"function",
"build",
"(",
"info",
",",
"sharedOpts",
"=",
"{",
"}",
",",
"compOpts",
"=",
"{",
"}",
",",
"pluginOpts",
"=",
"{",
"}",
")",
"{",
"const",
"dir",
"=",
"process",
".",
"cwd",
"(",
")",
";",
"const",
"[",
"org",
",",
"name",
"]",
"=",
"info",
".",
"name",
".",
"split",
"(",
"'/'",
")",
";",
"const",
"outputPath",
"=",
"`",
"${",
"dir",
"}",
"${",
"config",
".",
"outDir",
"}",
"`",
";",
"console",
".",
"log",
"(",
"chalk",
".",
"cyan",
"(",
"`",
"${",
"name",
"}",
"\\n",
"`",
")",
")",
";",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"rm",
"(",
"outputPath",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
"webpack",
"(",
"createWebpackConfig",
"(",
"dir",
",",
"name",
",",
"sharedOpts",
",",
"compOpts",
",",
"pluginOpts",
")",
",",
"(",
"err2",
",",
"stats",
")",
"=>",
"{",
"if",
"(",
"err2",
")",
"{",
"reject",
"(",
"err2",
")",
";",
"}",
"stats",
".",
"stats",
".",
"forEach",
"(",
"stat",
"=>",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"`",
"${",
"stat",
".",
"toString",
"(",
"{",
"colors",
":",
"true",
",",
"modules",
":",
"false",
",",
"children",
":",
"false",
",",
"chunks",
":",
"false",
",",
"chunkModules",
":",
"false",
",",
"}",
")",
"}",
"\\n",
"\\n",
"`",
")",
";",
"}",
")",
"console",
".",
"log",
"(",
"chalk",
".",
"cyan",
"(",
"`",
"${",
"name",
"}",
"\\n",
"`",
")",
")",
";",
"resolve",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Component build function
@param {Object} info -- package.json
@param {Object} sharedOpts -- webpack config for BOTH plugin/main that will be used in createWebpackConfig()
@param {Object} compOpts -- webpack config for main that will be used in createWebpackConfig()
@param {Object} pluginOpts -- webpack config for plugin that will be used in createWebpackConfig()
|
[
"Component",
"build",
"function"
] |
5ddcce5ccda8fee41235483760332ad5e63c5455
|
https://github.com/rei/rei-cedar/blob/5ddcce5ccda8fee41235483760332ad5e63c5455/build/component-build.js#L93-L129
|
train
|
rei/rei-cedar
|
build/css-loader.conf.js
|
getQueryObj
|
function getQueryObj(query='') {
const qObj = {};
const pairs = (query[0] === '?' ? query.substr(1) : query).split('&');
for (let i = 0, j = pairs.length; i < j; i++) {
let pair = pairs[i].split('=');
qObj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return qObj;
}
|
javascript
|
function getQueryObj(query='') {
const qObj = {};
const pairs = (query[0] === '?' ? query.substr(1) : query).split('&');
for (let i = 0, j = pairs.length; i < j; i++) {
let pair = pairs[i].split('=');
qObj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return qObj;
}
|
[
"function",
"getQueryObj",
"(",
"query",
"=",
"''",
")",
"{",
"const",
"qObj",
"=",
"{",
"}",
";",
"const",
"pairs",
"=",
"(",
"query",
"[",
"0",
"]",
"===",
"'?'",
"?",
"query",
".",
"substr",
"(",
"1",
")",
":",
"query",
")",
".",
"split",
"(",
"'&'",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"j",
"=",
"pairs",
".",
"length",
";",
"i",
"<",
"j",
";",
"i",
"++",
")",
"{",
"let",
"pair",
"=",
"pairs",
"[",
"i",
"]",
".",
"split",
"(",
"'='",
")",
";",
"qObj",
"[",
"decodeURIComponent",
"(",
"pair",
"[",
"0",
"]",
")",
"]",
"=",
"decodeURIComponent",
"(",
"pair",
"[",
"1",
"]",
"||",
"''",
")",
";",
"}",
"return",
"qObj",
";",
"}"
] |
turn resourceQuery into an object
|
[
"turn",
"resourceQuery",
"into",
"an",
"object"
] |
5ddcce5ccda8fee41235483760332ad5e63c5455
|
https://github.com/rei/rei-cedar/blob/5ddcce5ccda8fee41235483760332ad5e63c5455/build/css-loader.conf.js#L5-L13
|
train
|
rei/rei-cedar
|
backstop.js
|
createScenario
|
function createScenario(def) {
const finalScenario = Object.assign({}, scenarioDefaults, def);
scenariosArr.push(finalScenario);
}
|
javascript
|
function createScenario(def) {
const finalScenario = Object.assign({}, scenarioDefaults, def);
scenariosArr.push(finalScenario);
}
|
[
"function",
"createScenario",
"(",
"def",
")",
"{",
"const",
"finalScenario",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"scenarioDefaults",
",",
"def",
")",
";",
"scenariosArr",
".",
"push",
"(",
"finalScenario",
")",
";",
"}"
] |
functions for creating scenarios
|
[
"functions",
"for",
"creating",
"scenarios"
] |
5ddcce5ccda8fee41235483760332ad5e63c5455
|
https://github.com/rei/rei-cedar/blob/5ddcce5ccda8fee41235483760332ad5e63c5455/backstop.js#L16-L19
|
train
|
rei/rei-cedar
|
build/component-docs-archive.js
|
globSearch
|
function globSearch(searchRegex) {
const search = path.join(__dirname, '..', `${searchRegex}`)
return glob(`${search}`, {ignore: ['**/node_modules/**']})
.then(files => {
return new Promise((resolve, reject) => {
resolve(archiveComps(files))
})
})
.catch(globErr)
}
|
javascript
|
function globSearch(searchRegex) {
const search = path.join(__dirname, '..', `${searchRegex}`)
return glob(`${search}`, {ignore: ['**/node_modules/**']})
.then(files => {
return new Promise((resolve, reject) => {
resolve(archiveComps(files))
})
})
.catch(globErr)
}
|
[
"function",
"globSearch",
"(",
"searchRegex",
")",
"{",
"const",
"search",
"=",
"path",
".",
"join",
"(",
"__dirname",
",",
"'..'",
",",
"`",
"${",
"searchRegex",
"}",
"`",
")",
"return",
"glob",
"(",
"`",
"${",
"search",
"}",
"`",
",",
"{",
"ignore",
":",
"[",
"'**/node_modules/**'",
"]",
"}",
")",
".",
"then",
"(",
"files",
"=>",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"resolve",
"(",
"archiveComps",
"(",
"files",
")",
")",
"}",
")",
"}",
")",
".",
"catch",
"(",
"globErr",
")",
"}"
] |
Search for data objects associated with each Cedar component|composition
@param {String} searchRegex -- Regex used to search for component|composition data objects
@returns {Promise} -- Promisified version of glob search
|
[
"Search",
"for",
"data",
"objects",
"associated",
"with",
"each",
"Cedar",
"component|composition"
] |
5ddcce5ccda8fee41235483760332ad5e63c5455
|
https://github.com/rei/rei-cedar/blob/5ddcce5ccda8fee41235483760332ad5e63c5455/build/component-docs-archive.js#L33-L42
|
train
|
rei/rei-cedar
|
build/component-docs-archive.js
|
archiveComps
|
function archiveComps(compFiles) {
return compFiles.reduce((compObjCollection, file) => {
const compObj = require(`${file}`)
if (compObj !== null) {
compObjCollection.push(compObj)
console.log(`Added object for ${compObj.name} to Cedar Data Object`)
}
return compObjCollection
}, [])
}
|
javascript
|
function archiveComps(compFiles) {
return compFiles.reduce((compObjCollection, file) => {
const compObj = require(`${file}`)
if (compObj !== null) {
compObjCollection.push(compObj)
console.log(`Added object for ${compObj.name} to Cedar Data Object`)
}
return compObjCollection
}, [])
}
|
[
"function",
"archiveComps",
"(",
"compFiles",
")",
"{",
"return",
"compFiles",
".",
"reduce",
"(",
"(",
"compObjCollection",
",",
"file",
")",
"=>",
"{",
"const",
"compObj",
"=",
"require",
"(",
"`",
"${",
"file",
"}",
"`",
")",
"if",
"(",
"compObj",
"!==",
"null",
")",
"{",
"compObjCollection",
".",
"push",
"(",
"compObj",
")",
"console",
".",
"log",
"(",
"`",
"${",
"compObj",
".",
"name",
"}",
"`",
")",
"}",
"return",
"compObjCollection",
"}",
",",
"[",
"]",
")",
"}"
] |
Collect the data objects representing each Cedar component|composition
@param {Array} compFiles -- File paths of the JSON data object for each Cedar component
@returns {Array} -- Array of JSON data objects for all Cedar componnents|compositions
|
[
"Collect",
"the",
"data",
"objects",
"representing",
"each",
"Cedar",
"component|composition"
] |
5ddcce5ccda8fee41235483760332ad5e63c5455
|
https://github.com/rei/rei-cedar/blob/5ddcce5ccda8fee41235483760332ad5e63c5455/build/component-docs-archive.js#L49-L58
|
train
|
rei/rei-cedar
|
check-version.js
|
isPre
|
function isPre(p1, p2) {
// remove the ^
const stripped = semver.coerce(p2).raw;
const diff = semver.diff(p1, stripped);
return ['premajor', 'preminor', 'prepatch', 'prerelease'].indexOf(diff) >= 0 ? true : false;
}
|
javascript
|
function isPre(p1, p2) {
// remove the ^
const stripped = semver.coerce(p2).raw;
const diff = semver.diff(p1, stripped);
return ['premajor', 'preminor', 'prepatch', 'prerelease'].indexOf(diff) >= 0 ? true : false;
}
|
[
"function",
"isPre",
"(",
"p1",
",",
"p2",
")",
"{",
"const",
"stripped",
"=",
"semver",
".",
"coerce",
"(",
"p2",
")",
".",
"raw",
";",
"const",
"diff",
"=",
"semver",
".",
"diff",
"(",
"p1",
",",
"stripped",
")",
";",
"return",
"[",
"'premajor'",
",",
"'preminor'",
",",
"'prepatch'",
",",
"'prerelease'",
"]",
".",
"indexOf",
"(",
"diff",
")",
">=",
"0",
"?",
"true",
":",
"false",
";",
"}"
] |
checks if the version is a "pre"
|
[
"checks",
"if",
"the",
"version",
"is",
"a",
"pre"
] |
5ddcce5ccda8fee41235483760332ad5e63c5455
|
https://github.com/rei/rei-cedar/blob/5ddcce5ccda8fee41235483760332ad5e63c5455/check-version.js#L26-L31
|
train
|
begriffs/angular-paginate-anything
|
dist/paginate-anything.js
|
quantizedNumber
|
function quantizedNumber(i) {
var adjust = [1, 2.5, 5];
return Math.floor(Math.pow(10, Math.floor(i/3)) * adjust[i % 3]);
}
|
javascript
|
function quantizedNumber(i) {
var adjust = [1, 2.5, 5];
return Math.floor(Math.pow(10, Math.floor(i/3)) * adjust[i % 3]);
}
|
[
"function",
"quantizedNumber",
"(",
"i",
")",
"{",
"var",
"adjust",
"=",
"[",
"1",
",",
"2.5",
",",
"5",
"]",
";",
"return",
"Math",
".",
"floor",
"(",
"Math",
".",
"pow",
"(",
"10",
",",
"Math",
".",
"floor",
"(",
"i",
"/",
"3",
")",
")",
"*",
"adjust",
"[",
"i",
"%",
"3",
"]",
")",
";",
"}"
] |
1 2 5 10 25 50 100 250 500 etc
|
[
"1",
"2",
"5",
"10",
"25",
"50",
"100",
"250",
"500",
"etc"
] |
b9e3fddace64b53d8301a09a2490f32ff80ae554
|
https://github.com/begriffs/angular-paginate-anything/blob/b9e3fddace64b53d8301a09a2490f32ff80ae554/dist/paginate-anything.js#L5-L8
|
train
|
begriffs/angular-paginate-anything
|
dist/paginate-anything.js
|
appendTransform
|
function appendTransform(defaults, transform) {
defaults = angular.isArray(defaults) ? defaults : [defaults];
return (transform) ? defaults.concat(transform) : defaults;
}
|
javascript
|
function appendTransform(defaults, transform) {
defaults = angular.isArray(defaults) ? defaults : [defaults];
return (transform) ? defaults.concat(transform) : defaults;
}
|
[
"function",
"appendTransform",
"(",
"defaults",
",",
"transform",
")",
"{",
"defaults",
"=",
"angular",
".",
"isArray",
"(",
"defaults",
")",
"?",
"defaults",
":",
"[",
"defaults",
"]",
";",
"return",
"(",
"transform",
")",
"?",
"defaults",
".",
"concat",
"(",
"transform",
")",
":",
"defaults",
";",
"}"
] |
don't overwrite default response transforms
|
[
"don",
"t",
"overwrite",
"default",
"response",
"transforms"
] |
b9e3fddace64b53d8301a09a2490f32ff80ae554
|
https://github.com/begriffs/angular-paginate-anything/blob/b9e3fddace64b53d8301a09a2490f32ff80ae554/dist/paginate-anything.js#L28-L31
|
train
|
ember-data/active-model-adapter
|
addon/active-model-serializer.js
|
function(relationshipModelName, kind) {
var key = decamelize(relationshipModelName);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return singularize(key) + "_ids";
} else {
return key;
}
}
|
javascript
|
function(relationshipModelName, kind) {
var key = decamelize(relationshipModelName);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return singularize(key) + "_ids";
} else {
return key;
}
}
|
[
"function",
"(",
"relationshipModelName",
",",
"kind",
")",
"{",
"var",
"key",
"=",
"decamelize",
"(",
"relationshipModelName",
")",
";",
"if",
"(",
"kind",
"===",
"\"belongsTo\"",
")",
"{",
"return",
"key",
"+",
"\"_id\"",
";",
"}",
"else",
"if",
"(",
"kind",
"===",
"\"hasMany\"",
")",
"{",
"return",
"singularize",
"(",
"key",
")",
"+",
"\"_ids\"",
";",
"}",
"else",
"{",
"return",
"key",
";",
"}",
"}"
] |
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} relationshipModelName
@param {String} kind
@return String
|
[
"Underscores",
"relationship",
"names",
"and",
"appends",
"_id",
"or",
"_ids",
"when",
"serializing",
"relationship",
"keys",
"."
] |
967a47548a923dc3cac816c8dd971ad6f68e05e6
|
https://github.com/ember-data/active-model-adapter/blob/967a47548a923dc3cac816c8dd971ad6f68e05e6/addon/active-model-serializer.js#L131-L140
|
train
|
|
ember-data/active-model-adapter
|
addon/active-model-serializer.js
|
function(snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
var jsonKey = underscore(key + "_type");
if (Ember.isNone(belongsTo)) {
json[jsonKey] = null;
} else {
json[jsonKey] = classify(belongsTo.modelName).replace('/', '::');
}
}
|
javascript
|
function(snapshot, json, relationship) {
var key = relationship.key;
var belongsTo = snapshot.belongsTo(key);
var jsonKey = underscore(key + "_type");
if (Ember.isNone(belongsTo)) {
json[jsonKey] = null;
} else {
json[jsonKey] = classify(belongsTo.modelName).replace('/', '::');
}
}
|
[
"function",
"(",
"snapshot",
",",
"json",
",",
"relationship",
")",
"{",
"var",
"key",
"=",
"relationship",
".",
"key",
";",
"var",
"belongsTo",
"=",
"snapshot",
".",
"belongsTo",
"(",
"key",
")",
";",
"var",
"jsonKey",
"=",
"underscore",
"(",
"key",
"+",
"\"_type\"",
")",
";",
"if",
"(",
"Ember",
".",
"isNone",
"(",
"belongsTo",
")",
")",
"{",
"json",
"[",
"jsonKey",
"]",
"=",
"null",
";",
"}",
"else",
"{",
"json",
"[",
"jsonKey",
"]",
"=",
"classify",
"(",
"belongsTo",
".",
"modelName",
")",
".",
"replace",
"(",
"'/'",
",",
"'::'",
")",
";",
"}",
"}"
] |
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Snapshot} snapshot
@param {Object} json
@param {Object} relationship
|
[
"Serializes",
"a",
"polymorphic",
"type",
"as",
"a",
"fully",
"capitalized",
"model",
"name",
"."
] |
967a47548a923dc3cac816c8dd971ad6f68e05e6
|
https://github.com/ember-data/active-model-adapter/blob/967a47548a923dc3cac816c8dd971ad6f68e05e6/addon/active-model-serializer.js#L179-L189
|
train
|
|
ember-data/active-model-adapter
|
addon/active-model-serializer.js
|
function(data) {
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
}
|
javascript
|
function(data) {
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
}
|
[
"function",
"(",
"data",
")",
"{",
"if",
"(",
"data",
".",
"links",
")",
"{",
"var",
"links",
"=",
"data",
".",
"links",
";",
"for",
"(",
"var",
"link",
"in",
"links",
")",
"{",
"var",
"camelizedLink",
"=",
"camelize",
"(",
"link",
")",
";",
"if",
"(",
"camelizedLink",
"!==",
"link",
")",
"{",
"links",
"[",
"camelizedLink",
"]",
"=",
"links",
"[",
"link",
"]",
";",
"delete",
"links",
"[",
"link",
"]",
";",
"}",
"}",
"}",
"}"
] |
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} data
|
[
"Convert",
"snake_cased",
"links",
"to",
"camelCase"
] |
967a47548a923dc3cac816c8dd971ad6f68e05e6
|
https://github.com/ember-data/active-model-adapter/blob/967a47548a923dc3cac816c8dd971ad6f68e05e6/addon/active-model-serializer.js#L236-L249
|
train
|
|
dcodeIO/ClosureCompiler.js
|
scripts/configure.js
|
platformPostfix
|
function platformPostfix() {
if (/^win/.test(process.platform)) {
return process.arch == 'x64' ? 'win64' : 'win32';
} else if (/^darwin/.test(process.platform)) {
return 'osx64';
}
// This might not be ideal, but we don't have anything else and there is always a chance that it will work
return process.arch == 'x64' ? 'linux64' : 'linux32';
}
|
javascript
|
function platformPostfix() {
if (/^win/.test(process.platform)) {
return process.arch == 'x64' ? 'win64' : 'win32';
} else if (/^darwin/.test(process.platform)) {
return 'osx64';
}
// This might not be ideal, but we don't have anything else and there is always a chance that it will work
return process.arch == 'x64' ? 'linux64' : 'linux32';
}
|
[
"function",
"platformPostfix",
"(",
")",
"{",
"if",
"(",
"/",
"^win",
"/",
".",
"test",
"(",
"process",
".",
"platform",
")",
")",
"{",
"return",
"process",
".",
"arch",
"==",
"'x64'",
"?",
"'win64'",
":",
"'win32'",
";",
"}",
"else",
"if",
"(",
"/",
"^darwin",
"/",
".",
"test",
"(",
"process",
".",
"platform",
")",
")",
"{",
"return",
"'osx64'",
";",
"}",
"return",
"process",
".",
"arch",
"==",
"'x64'",
"?",
"'linux64'",
":",
"'linux32'",
";",
"}"
] |
Gets the platform postfix for downloads
|
[
"Gets",
"the",
"platform",
"postfix",
"for",
"downloads"
] |
96fd199f24eaada9aa67c30164ffc720218f64a4
|
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/scripts/configure.js#L40-L48
|
train
|
dcodeIO/ClosureCompiler.js
|
scripts/configure.js
|
unpack
|
function unpack(filename, callback, entryCallback) {
var input = fs.createReadStream(filename, { flags: 'r', encoding: null }),
files = {},
dir = path.dirname(filename),
returned = false,
to = null;
// Finishs the unpack if all files are done
function maybeFinish() {
if (to !== null) clearTimeout(to);
to = setTimeout(function() {
var alldone = true;
var names = Object.keys(files);
for (var i=0; i<names.length; i++) {
if (!files[names[i]]["done"]) {
alldone = false;
break;
}
}
if (alldone && !returned) {
returned = true;
callback(null);
}
}, 1000);
}
input.pipe(zlib.createGunzip()).pipe(tar.Parse()).on("entry", function(entry) {
if (entryCallback) entryCallback(entry);
if (entry["type"] == 'File') {
files[entry["path"]] = fs.createWriteStream(path.join(dir, entry["path"]), { flags: 'w', encoding: null });
entry.pipe(files[entry["path"]]);
entry.on("end", function() {
files[entry["path"]].end();
files[entry["path"]]["done"] = true;
maybeFinish();
});
} else if (entry["type"] == "Directory") {
try {
fs.mkdirSync(path.join(dir, entry["path"]));
} catch (e) {
if (!fs.existsSync(path.join(dir, entry["path"]))) {
if (!returned) {
returned = true;
callback(e);
}
}
}
}
}).on("error", function(e) {
if (!returned) {
returned = true;
callback(e);
}
});
}
|
javascript
|
function unpack(filename, callback, entryCallback) {
var input = fs.createReadStream(filename, { flags: 'r', encoding: null }),
files = {},
dir = path.dirname(filename),
returned = false,
to = null;
// Finishs the unpack if all files are done
function maybeFinish() {
if (to !== null) clearTimeout(to);
to = setTimeout(function() {
var alldone = true;
var names = Object.keys(files);
for (var i=0; i<names.length; i++) {
if (!files[names[i]]["done"]) {
alldone = false;
break;
}
}
if (alldone && !returned) {
returned = true;
callback(null);
}
}, 1000);
}
input.pipe(zlib.createGunzip()).pipe(tar.Parse()).on("entry", function(entry) {
if (entryCallback) entryCallback(entry);
if (entry["type"] == 'File') {
files[entry["path"]] = fs.createWriteStream(path.join(dir, entry["path"]), { flags: 'w', encoding: null });
entry.pipe(files[entry["path"]]);
entry.on("end", function() {
files[entry["path"]].end();
files[entry["path"]]["done"] = true;
maybeFinish();
});
} else if (entry["type"] == "Directory") {
try {
fs.mkdirSync(path.join(dir, entry["path"]));
} catch (e) {
if (!fs.existsSync(path.join(dir, entry["path"]))) {
if (!returned) {
returned = true;
callback(e);
}
}
}
}
}).on("error", function(e) {
if (!returned) {
returned = true;
callback(e);
}
});
}
|
[
"function",
"unpack",
"(",
"filename",
",",
"callback",
",",
"entryCallback",
")",
"{",
"var",
"input",
"=",
"fs",
".",
"createReadStream",
"(",
"filename",
",",
"{",
"flags",
":",
"'r'",
",",
"encoding",
":",
"null",
"}",
")",
",",
"files",
"=",
"{",
"}",
",",
"dir",
"=",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"returned",
"=",
"false",
",",
"to",
"=",
"null",
";",
"function",
"maybeFinish",
"(",
")",
"{",
"if",
"(",
"to",
"!==",
"null",
")",
"clearTimeout",
"(",
"to",
")",
";",
"to",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"var",
"alldone",
"=",
"true",
";",
"var",
"names",
"=",
"Object",
".",
"keys",
"(",
"files",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"names",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"files",
"[",
"names",
"[",
"i",
"]",
"]",
"[",
"\"done\"",
"]",
")",
"{",
"alldone",
"=",
"false",
";",
"break",
";",
"}",
"}",
"if",
"(",
"alldone",
"&&",
"!",
"returned",
")",
"{",
"returned",
"=",
"true",
";",
"callback",
"(",
"null",
")",
";",
"}",
"}",
",",
"1000",
")",
";",
"}",
"input",
".",
"pipe",
"(",
"zlib",
".",
"createGunzip",
"(",
")",
")",
".",
"pipe",
"(",
"tar",
".",
"Parse",
"(",
")",
")",
".",
"on",
"(",
"\"entry\"",
",",
"function",
"(",
"entry",
")",
"{",
"if",
"(",
"entryCallback",
")",
"entryCallback",
"(",
"entry",
")",
";",
"if",
"(",
"entry",
"[",
"\"type\"",
"]",
"==",
"'File'",
")",
"{",
"files",
"[",
"entry",
"[",
"\"path\"",
"]",
"]",
"=",
"fs",
".",
"createWriteStream",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"entry",
"[",
"\"path\"",
"]",
")",
",",
"{",
"flags",
":",
"'w'",
",",
"encoding",
":",
"null",
"}",
")",
";",
"entry",
".",
"pipe",
"(",
"files",
"[",
"entry",
"[",
"\"path\"",
"]",
"]",
")",
";",
"entry",
".",
"on",
"(",
"\"end\"",
",",
"function",
"(",
")",
"{",
"files",
"[",
"entry",
"[",
"\"path\"",
"]",
"]",
".",
"end",
"(",
")",
";",
"files",
"[",
"entry",
"[",
"\"path\"",
"]",
"]",
"[",
"\"done\"",
"]",
"=",
"true",
";",
"maybeFinish",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"if",
"(",
"entry",
"[",
"\"type\"",
"]",
"==",
"\"Directory\"",
")",
"{",
"try",
"{",
"fs",
".",
"mkdirSync",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"entry",
"[",
"\"path\"",
"]",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"path",
".",
"join",
"(",
"dir",
",",
"entry",
"[",
"\"path\"",
"]",
")",
")",
")",
"{",
"if",
"(",
"!",
"returned",
")",
"{",
"returned",
"=",
"true",
";",
"callback",
"(",
"e",
")",
";",
"}",
"}",
"}",
"}",
"}",
")",
".",
"on",
"(",
"\"error\"",
",",
"function",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"returned",
")",
"{",
"returned",
"=",
"true",
";",
"callback",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Unpacks a file in place.
@param {string} filename File name
@param {function(?Error)} callback
@param {function(Object)=} entryCallback
|
[
"Unpacks",
"a",
"file",
"in",
"place",
"."
] |
96fd199f24eaada9aa67c30164ffc720218f64a4
|
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/scripts/configure.js#L208-L262
|
train
|
dcodeIO/ClosureCompiler.js
|
scripts/configure.js
|
maybeFinish
|
function maybeFinish() {
if (to !== null) clearTimeout(to);
to = setTimeout(function() {
var alldone = true;
var names = Object.keys(files);
for (var i=0; i<names.length; i++) {
if (!files[names[i]]["done"]) {
alldone = false;
break;
}
}
if (alldone && !returned) {
returned = true;
callback(null);
}
}, 1000);
}
|
javascript
|
function maybeFinish() {
if (to !== null) clearTimeout(to);
to = setTimeout(function() {
var alldone = true;
var names = Object.keys(files);
for (var i=0; i<names.length; i++) {
if (!files[names[i]]["done"]) {
alldone = false;
break;
}
}
if (alldone && !returned) {
returned = true;
callback(null);
}
}, 1000);
}
|
[
"function",
"maybeFinish",
"(",
")",
"{",
"if",
"(",
"to",
"!==",
"null",
")",
"clearTimeout",
"(",
"to",
")",
";",
"to",
"=",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"var",
"alldone",
"=",
"true",
";",
"var",
"names",
"=",
"Object",
".",
"keys",
"(",
"files",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"names",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"files",
"[",
"names",
"[",
"i",
"]",
"]",
"[",
"\"done\"",
"]",
")",
"{",
"alldone",
"=",
"false",
";",
"break",
";",
"}",
"}",
"if",
"(",
"alldone",
"&&",
"!",
"returned",
")",
"{",
"returned",
"=",
"true",
";",
"callback",
"(",
"null",
")",
";",
"}",
"}",
",",
"1000",
")",
";",
"}"
] |
Finishs the unpack if all files are done
|
[
"Finishs",
"the",
"unpack",
"if",
"all",
"files",
"are",
"done"
] |
96fd199f24eaada9aa67c30164ffc720218f64a4
|
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/scripts/configure.js#L216-L232
|
train
|
dcodeIO/ClosureCompiler.js
|
scripts/configure.js
|
configure
|
function configure() {
var java = path.normalize(path.join(__dirname, "..", "jre", "bin", "java"+ClosureCompiler.JAVA_EXT));
console.log(" Configuring bundled JRE for platform '"+platformPostfix()+"' ...");
if (!/^win/.test(process.platform)) {
var jre = path.normalize(path.join(__dirname, "..", "jre"));
console.log(" | 0755 "+jre);
fs.chmodSync(jre, 0755);
console.log(" | 0755 "+path.join(jre, "bin"));
fs.chmodSync(path.join(jre, "bin"), 0755);
console.log(" | 0755 "+java);
fs.chmodSync(java, 0755);
console.log(" Complete.\n");
} else {
console.log(" Complete (not necessary).\n");
}
}
|
javascript
|
function configure() {
var java = path.normalize(path.join(__dirname, "..", "jre", "bin", "java"+ClosureCompiler.JAVA_EXT));
console.log(" Configuring bundled JRE for platform '"+platformPostfix()+"' ...");
if (!/^win/.test(process.platform)) {
var jre = path.normalize(path.join(__dirname, "..", "jre"));
console.log(" | 0755 "+jre);
fs.chmodSync(jre, 0755);
console.log(" | 0755 "+path.join(jre, "bin"));
fs.chmodSync(path.join(jre, "bin"), 0755);
console.log(" | 0755 "+java);
fs.chmodSync(java, 0755);
console.log(" Complete.\n");
} else {
console.log(" Complete (not necessary).\n");
}
}
|
[
"function",
"configure",
"(",
")",
"{",
"var",
"java",
"=",
"path",
".",
"normalize",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"\"..\"",
",",
"\"jre\"",
",",
"\"bin\"",
",",
"\"java\"",
"+",
"ClosureCompiler",
".",
"JAVA_EXT",
")",
")",
";",
"console",
".",
"log",
"(",
"\" Configuring bundled JRE for platform '\"",
"+",
"platformPostfix",
"(",
")",
"+",
"\"' ...\"",
")",
";",
"if",
"(",
"!",
"/",
"^win",
"/",
".",
"test",
"(",
"process",
".",
"platform",
")",
")",
"{",
"var",
"jre",
"=",
"path",
".",
"normalize",
"(",
"path",
".",
"join",
"(",
"__dirname",
",",
"\"..\"",
",",
"\"jre\"",
")",
")",
";",
"console",
".",
"log",
"(",
"\" | 0755 \"",
"+",
"jre",
")",
";",
"fs",
".",
"chmodSync",
"(",
"jre",
",",
"0755",
")",
";",
"console",
".",
"log",
"(",
"\" | 0755 \"",
"+",
"path",
".",
"join",
"(",
"jre",
",",
"\"bin\"",
")",
")",
";",
"fs",
".",
"chmodSync",
"(",
"path",
".",
"join",
"(",
"jre",
",",
"\"bin\"",
")",
",",
"0755",
")",
";",
"console",
".",
"log",
"(",
"\" | 0755 \"",
"+",
"java",
")",
";",
"fs",
".",
"chmodSync",
"(",
"java",
",",
"0755",
")",
";",
"console",
".",
"log",
"(",
"\" Complete.\\n\"",
")",
";",
"}",
"else",
"\\n",
"}"
] |
Configures our bundled Java.
|
[
"Configures",
"our",
"bundled",
"Java",
"."
] |
96fd199f24eaada9aa67c30164ffc720218f64a4
|
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/scripts/configure.js#L267-L282
|
train
|
dcodeIO/ClosureCompiler.js
|
ClosureCompiler.js
|
exec
|
function exec(cmd, args, stdin, callback) {
var stdout = concat();
var stderr = concat();
var process = child_process.spawn(cmd, args, {
stdio: [stdin || 'ignore', 'pipe', 'pipe']
});
process.stdout.pipe(stdout);
process.stderr.pipe(stderr);
process.on('exit', function(code, signal) {
var err;
if (code) {
err = new Error(code);
err.code = code;
err.signal = signal;
}
callback(err, stdout, stderr);
});
process.on('error', function (err) {
callback(err, stdout, stderr);
});
}
|
javascript
|
function exec(cmd, args, stdin, callback) {
var stdout = concat();
var stderr = concat();
var process = child_process.spawn(cmd, args, {
stdio: [stdin || 'ignore', 'pipe', 'pipe']
});
process.stdout.pipe(stdout);
process.stderr.pipe(stderr);
process.on('exit', function(code, signal) {
var err;
if (code) {
err = new Error(code);
err.code = code;
err.signal = signal;
}
callback(err, stdout, stderr);
});
process.on('error', function (err) {
callback(err, stdout, stderr);
});
}
|
[
"function",
"exec",
"(",
"cmd",
",",
"args",
",",
"stdin",
",",
"callback",
")",
"{",
"var",
"stdout",
"=",
"concat",
"(",
")",
";",
"var",
"stderr",
"=",
"concat",
"(",
")",
";",
"var",
"process",
"=",
"child_process",
".",
"spawn",
"(",
"cmd",
",",
"args",
",",
"{",
"stdio",
":",
"[",
"stdin",
"||",
"'ignore'",
",",
"'pipe'",
",",
"'pipe'",
"]",
"}",
")",
";",
"process",
".",
"stdout",
".",
"pipe",
"(",
"stdout",
")",
";",
"process",
".",
"stderr",
".",
"pipe",
"(",
"stderr",
")",
";",
"process",
".",
"on",
"(",
"'exit'",
",",
"function",
"(",
"code",
",",
"signal",
")",
"{",
"var",
"err",
";",
"if",
"(",
"code",
")",
"{",
"err",
"=",
"new",
"Error",
"(",
"code",
")",
";",
"err",
".",
"code",
"=",
"code",
";",
"err",
".",
"signal",
"=",
"signal",
";",
"}",
"callback",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
";",
"}",
")",
";",
"process",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
",",
"stdout",
",",
"stderr",
")",
";",
"}",
")",
";",
"}"
] |
Executes a command
|
[
"Executes",
"a",
"command"
] |
96fd199f24eaada9aa67c30164ffc720218f64a4
|
https://github.com/dcodeIO/ClosureCompiler.js/blob/96fd199f24eaada9aa67c30164ffc720218f64a4/ClosureCompiler.js#L267-L288
|
train
|
XervoIO/demeteorizer
|
lib/find-node-version.js
|
fromBoot
|
function fromBoot (options) {
var version
var bootPath = Path.resolve(
options.directory,
'bundle',
'programs',
'server',
'boot.js')
try {
version = Fs.readFileSync(bootPath, 'utf8')
.split('\n')
.find((line) => line.indexOf('MIN_NODE_VERSION') >= 0)
.split(' ')[3] // eslint-disable no-magic-numbers
.replace(/[v;']/g, '')
} catch (err) {
return false
}
return version
}
|
javascript
|
function fromBoot (options) {
var version
var bootPath = Path.resolve(
options.directory,
'bundle',
'programs',
'server',
'boot.js')
try {
version = Fs.readFileSync(bootPath, 'utf8')
.split('\n')
.find((line) => line.indexOf('MIN_NODE_VERSION') >= 0)
.split(' ')[3] // eslint-disable no-magic-numbers
.replace(/[v;']/g, '')
} catch (err) {
return false
}
return version
}
|
[
"function",
"fromBoot",
"(",
"options",
")",
"{",
"var",
"version",
"var",
"bootPath",
"=",
"Path",
".",
"resolve",
"(",
"options",
".",
"directory",
",",
"'bundle'",
",",
"'programs'",
",",
"'server'",
",",
"'boot.js'",
")",
"try",
"{",
"version",
"=",
"Fs",
".",
"readFileSync",
"(",
"bootPath",
",",
"'utf8'",
")",
".",
"split",
"(",
"'\\n'",
")",
".",
"\\n",
"find",
".",
"(",
"(",
"line",
")",
"=>",
"line",
".",
"indexOf",
"(",
"'MIN_NODE_VERSION'",
")",
">=",
"0",
")",
"split",
"[",
"(",
"' '",
")",
"]",
".",
"3",
"replace",
"}",
"(",
"/",
"[v;']",
"/",
"g",
",",
"''",
")",
"catch",
"(",
"err",
")",
"{",
"return",
"false",
"}",
"}"
] |
Read boot.js to find the MIN_NODE_VERSION
|
[
"Read",
"boot",
".",
"js",
"to",
"find",
"the",
"MIN_NODE_VERSION"
] |
2581c3f2064aa4779d44e737ab0793fa7cabbd43
|
https://github.com/XervoIO/demeteorizer/blob/2581c3f2064aa4779d44e737ab0793fa7cabbd43/lib/find-node-version.js#L20-L39
|
train
|
mozilla/dryice
|
lib/dryice/index.js
|
Location
|
function Location(base, somePath) {
if (base == null) {
throw new Error('base == null');
}
this.base = base;
this.path = somePath;
}
|
javascript
|
function Location(base, somePath) {
if (base == null) {
throw new Error('base == null');
}
this.base = base;
this.path = somePath;
}
|
[
"function",
"Location",
"(",
"base",
",",
"somePath",
")",
"{",
"if",
"(",
"base",
"==",
"null",
")",
"{",
"throw",
"new",
"Error",
"(",
"'base == null'",
")",
";",
"}",
"this",
".",
"base",
"=",
"base",
";",
"this",
".",
"path",
"=",
"somePath",
";",
"}"
] |
A Location is a base and a path which together point to a file or directory.
It's useful to be able to know in copy operations relative to some project
root to be able to remember where in a destination the file should go
|
[
"A",
"Location",
"is",
"a",
"base",
"and",
"a",
"path",
"which",
"together",
"point",
"to",
"a",
"file",
"or",
"directory",
".",
"It",
"s",
"useful",
"to",
"be",
"able",
"to",
"know",
"in",
"copy",
"operations",
"relative",
"to",
"some",
"project",
"root",
"to",
"be",
"able",
"to",
"remember",
"where",
"in",
"a",
"destination",
"the",
"file",
"should",
"go"
] |
836fa7533c90abc3a30dd08c721d271d578d7b46
|
https://github.com/mozilla/dryice/blob/836fa7533c90abc3a30dd08c721d271d578d7b46/lib/dryice/index.js#L40-L46
|
train
|
theasta/grunt-assets-versioning
|
tasks/versioners/abstractVersioner.js
|
AbstractVersioner
|
function AbstractVersioner(options, taskData) {
this.options = options;
this.taskData = taskData;
/**
* Map of versioned files
* @type {Array.<{version, originalPath: string, versionedPath: string}>}
*/
this.versionsMap = [];
/**
* Get one of the tagger functions: hash or date
* @type {function}
*/
this.versionTagger = taggers[this.options.tag];
// is task a post versioning task?
this.isPostVersioningTask = grunt.config(this.getAssetsVersioningTaskConfigKey() + '.isPostVersioningTaskFor');
}
|
javascript
|
function AbstractVersioner(options, taskData) {
this.options = options;
this.taskData = taskData;
/**
* Map of versioned files
* @type {Array.<{version, originalPath: string, versionedPath: string}>}
*/
this.versionsMap = [];
/**
* Get one of the tagger functions: hash or date
* @type {function}
*/
this.versionTagger = taggers[this.options.tag];
// is task a post versioning task?
this.isPostVersioningTask = grunt.config(this.getAssetsVersioningTaskConfigKey() + '.isPostVersioningTaskFor');
}
|
[
"function",
"AbstractVersioner",
"(",
"options",
",",
"taskData",
")",
"{",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"taskData",
"=",
"taskData",
";",
"this",
".",
"versionsMap",
"=",
"[",
"]",
";",
"this",
".",
"versionTagger",
"=",
"taggers",
"[",
"this",
".",
"options",
".",
"tag",
"]",
";",
"this",
".",
"isPostVersioningTask",
"=",
"grunt",
".",
"config",
"(",
"this",
".",
"getAssetsVersioningTaskConfigKey",
"(",
")",
"+",
"'.isPostVersioningTaskFor'",
")",
";",
"}"
] |
A surrogate task - task with destination files tagged with a revision marker
@typedef {(string|{files: Array})} surrogateTask
Abstract Versioner
@constructor
@alias module:versioners/AbstractVersioner
@param {object} options - Grunt options
@param {object} taskData - Grunt Assets Versioning Task Object
|
[
"A",
"surrogate",
"task",
"-",
"task",
"with",
"destination",
"files",
"tagged",
"with",
"a",
"revision",
"marker"
] |
5e2e62b90e3cc2b635582cce0e6598ce2bc8acab
|
https://github.com/theasta/grunt-assets-versioning/blob/5e2e62b90e3cc2b635582cce0e6598ce2bc8acab/tasks/versioners/abstractVersioner.js#L28-L46
|
train
|
bem-archive/image-optim
|
lib/modes.js
|
_minFile
|
function _minFile(rawFile, compressedFile) {
if (compressedFile.size < rawFile.size) {
return qfs.move(compressedFile.name, rawFile.name)
.then(function () {
return new File(rawFile.name, compressedFile.size);
});
}
return compressedFile.remove()
.then(function () {
return rawFile;
});
}
|
javascript
|
function _minFile(rawFile, compressedFile) {
if (compressedFile.size < rawFile.size) {
return qfs.move(compressedFile.name, rawFile.name)
.then(function () {
return new File(rawFile.name, compressedFile.size);
});
}
return compressedFile.remove()
.then(function () {
return rawFile;
});
}
|
[
"function",
"_minFile",
"(",
"rawFile",
",",
"compressedFile",
")",
"{",
"if",
"(",
"compressedFile",
".",
"size",
"<",
"rawFile",
".",
"size",
")",
"{",
"return",
"qfs",
".",
"move",
"(",
"compressedFile",
".",
"name",
",",
"rawFile",
".",
"name",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"new",
"File",
"(",
"rawFile",
".",
"name",
",",
"compressedFile",
".",
"size",
")",
";",
"}",
")",
";",
"}",
"return",
"compressedFile",
".",
"remove",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"rawFile",
";",
"}",
")",
";",
"}"
] |
Overwrites the raw file by the compressed one if it is smaller otherwise removes it
@param {File} rawFile
@param {File} compressedFile
@returns {Promise * File}
|
[
"Overwrites",
"the",
"raw",
"file",
"by",
"the",
"compressed",
"one",
"if",
"it",
"is",
"smaller",
"otherwise",
"removes",
"it"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L14-L26
|
train
|
bem-archive/image-optim
|
lib/modes.js
|
_isSmallerAfterCompression
|
function _isSmallerAfterCompression(rawFile, compressedFile, opts) {
return compressedFile.remove()
.then(function () {
var tolerance = opts.tolerance < 1
? opts.tolerance * rawFile.size
: opts.tolerance;
return rawFile.size > compressedFile.size + tolerance;
});
}
|
javascript
|
function _isSmallerAfterCompression(rawFile, compressedFile, opts) {
return compressedFile.remove()
.then(function () {
var tolerance = opts.tolerance < 1
? opts.tolerance * rawFile.size
: opts.tolerance;
return rawFile.size > compressedFile.size + tolerance;
});
}
|
[
"function",
"_isSmallerAfterCompression",
"(",
"rawFile",
",",
"compressedFile",
",",
"opts",
")",
"{",
"return",
"compressedFile",
".",
"remove",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"tolerance",
"=",
"opts",
".",
"tolerance",
"<",
"1",
"?",
"opts",
".",
"tolerance",
"*",
"rawFile",
".",
"size",
":",
"opts",
".",
"tolerance",
";",
"return",
"rawFile",
".",
"size",
">",
"compressedFile",
".",
"size",
"+",
"tolerance",
";",
"}",
")",
";",
"}"
] |
Checks whether the given raw file is smaller than the given compressed file
Removes the compressed file
@param {File} rawFile
@param {File} compressedFile
@param {Object} [opts] -> lib/defaults.js
@param {Number} [opts.tolerance=0]
@param {String[]} [opts.reporters=[]]
@param {String} [opts._tmpDir=md5]
@returns {Promise * Boolean}
|
[
"Checks",
"whether",
"the",
"given",
"raw",
"file",
"is",
"smaller",
"than",
"the",
"given",
"compressed",
"file",
"Removes",
"the",
"compressed",
"file"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L39-L48
|
train
|
bem-archive/image-optim
|
lib/modes.js
|
_getSavedBytes
|
function _getSavedBytes(rawFile, compressedFile) {
var savedBytes = rawFile.size - compressedFile.size;
if (savedBytes > 0) return savedBytes;
return 0;
}
|
javascript
|
function _getSavedBytes(rawFile, compressedFile) {
var savedBytes = rawFile.size - compressedFile.size;
if (savedBytes > 0) return savedBytes;
return 0;
}
|
[
"function",
"_getSavedBytes",
"(",
"rawFile",
",",
"compressedFile",
")",
"{",
"var",
"savedBytes",
"=",
"rawFile",
".",
"size",
"-",
"compressedFile",
".",
"size",
";",
"if",
"(",
"savedBytes",
">",
"0",
")",
"return",
"savedBytes",
";",
"return",
"0",
";",
"}"
] |
Returns saved bytes between the raw and compressed files
@param {File} rawFile
@param {File} compressedFile
@returns {Number}
|
[
"Returns",
"saved",
"bytes",
"between",
"the",
"raw",
"and",
"compressed",
"files"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L56-L62
|
train
|
bem-archive/image-optim
|
lib/modes.js
|
_initCompressedFile
|
function _initCompressedFile(filename, tmpDir) {
return new File(path.join(tmpDir, path.basename(filename) + md5(filename) + path.extname(filename)));
}
|
javascript
|
function _initCompressedFile(filename, tmpDir) {
return new File(path.join(tmpDir, path.basename(filename) + md5(filename) + path.extname(filename)));
}
|
[
"function",
"_initCompressedFile",
"(",
"filename",
",",
"tmpDir",
")",
"{",
"return",
"new",
"File",
"(",
"path",
".",
"join",
"(",
"tmpDir",
",",
"path",
".",
"basename",
"(",
"filename",
")",
"+",
"md5",
"(",
"filename",
")",
"+",
"path",
".",
"extname",
"(",
"filename",
")",
")",
")",
";",
"}"
] |
Initializes a compressed file
@param {String} filename
@param {String} tmpDir
@returns {File}
|
[
"Initializes",
"a",
"compressed",
"file"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L83-L85
|
train
|
bem-archive/image-optim
|
lib/modes.js
|
_imageOptim
|
function _imageOptim(rawFile, algorithms, reduceFunc, initVal) {
return Q.all([rawFile.loadSize(), rawFile.loadType()])
.then(function () {
return algorithms[rawFile.type].reduce(reduceFunc, initVal);
})
.fail(function (err) {
throw err;
});
}
|
javascript
|
function _imageOptim(rawFile, algorithms, reduceFunc, initVal) {
return Q.all([rawFile.loadSize(), rawFile.loadType()])
.then(function () {
return algorithms[rawFile.type].reduce(reduceFunc, initVal);
})
.fail(function (err) {
throw err;
});
}
|
[
"function",
"_imageOptim",
"(",
"rawFile",
",",
"algorithms",
",",
"reduceFunc",
",",
"initVal",
")",
"{",
"return",
"Q",
".",
"all",
"(",
"[",
"rawFile",
".",
"loadSize",
"(",
")",
",",
"rawFile",
".",
"loadType",
"(",
")",
"]",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"algorithms",
"[",
"rawFile",
".",
"type",
"]",
".",
"reduce",
"(",
"reduceFunc",
",",
"initVal",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
")",
";",
"}"
] |
Processes the file in the specifies mode
@param {File} rawFile
@param {Function[]} algorithms
@param {reduceCallback} reduceFunc
@param {Promise * File|Boolean} initVal
@returns {Promise * File|Boolean}
|
[
"Processes",
"the",
"file",
"in",
"the",
"specifies",
"mode"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L95-L103
|
train
|
bem-archive/image-optim
|
lib/modes.js
|
function (rawFile, algorithms, opts) {
return _imageOptim(rawFile, algorithms, function (prev, next) {
return prev.then(function (res) {
return next(rawFile, _initCompressedFile(rawFile.name, opts._tmpDir))
.then(function (compressed) {
return _minFile(res, compressed);
});
});
}, new Q(rawFile))
.then(function (minFile) {
return {
name: rawFile.name,
savedBytes: _getSavedBytes(rawFile, minFile),
exitCode: exit.SUCCESS
};
})
.fail(function (err) {
return _handleError(err, rawFile);
});
}
|
javascript
|
function (rawFile, algorithms, opts) {
return _imageOptim(rawFile, algorithms, function (prev, next) {
return prev.then(function (res) {
return next(rawFile, _initCompressedFile(rawFile.name, opts._tmpDir))
.then(function (compressed) {
return _minFile(res, compressed);
});
});
}, new Q(rawFile))
.then(function (minFile) {
return {
name: rawFile.name,
savedBytes: _getSavedBytes(rawFile, minFile),
exitCode: exit.SUCCESS
};
})
.fail(function (err) {
return _handleError(err, rawFile);
});
}
|
[
"function",
"(",
"rawFile",
",",
"algorithms",
",",
"opts",
")",
"{",
"return",
"_imageOptim",
"(",
"rawFile",
",",
"algorithms",
",",
"function",
"(",
"prev",
",",
"next",
")",
"{",
"return",
"prev",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"next",
"(",
"rawFile",
",",
"_initCompressedFile",
"(",
"rawFile",
".",
"name",
",",
"opts",
".",
"_tmpDir",
")",
")",
".",
"then",
"(",
"function",
"(",
"compressed",
")",
"{",
"return",
"_minFile",
"(",
"res",
",",
"compressed",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
",",
"new",
"Q",
"(",
"rawFile",
")",
")",
".",
"then",
"(",
"function",
"(",
"minFile",
")",
"{",
"return",
"{",
"name",
":",
"rawFile",
".",
"name",
",",
"savedBytes",
":",
"_getSavedBytes",
"(",
"rawFile",
",",
"minFile",
")",
",",
"exitCode",
":",
"exit",
".",
"SUCCESS",
"}",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"return",
"_handleError",
"(",
"err",
",",
"rawFile",
")",
";",
"}",
")",
";",
"}"
] |
This callback is provided as a first argument for reduce function
@callback reduceCallback
@param {Promise * File|Boolean} prev
@param {Promise * File|Boolean} next
Optimizes the given file and returns the information about the compression
@examples
1. { name: 'file.ext', savedBytes: 12345, exitCode: 0 }
2. { name: 'file.ext', exitCode: 1 }
3. { name: 'file.ext', exitCode: 2 }
@param {File} rawFile
@param {Function[]} algorithms
@param {Object} [opts] -> lib/defaults.js
@param {Number} [opts.tolerance=0]
@param {String[]} [opts.reporters=[]]
@param {String} [opts._tmpDir=md5]
@returns {Promise * Object}
|
[
"This",
"callback",
"is",
"provided",
"as",
"a",
"first",
"argument",
"for",
"reduce",
"function"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L131-L150
|
train
|
|
bem-archive/image-optim
|
lib/modes.js
|
function (rawFile, algorithms, opts) {
return _imageOptim(rawFile, algorithms, function (prev, next) {
return prev.then(function (res) {
return res || next(rawFile, _initCompressedFile(rawFile.name, opts._tmpDir))
.then(function (compressed) {
return _isSmallerAfterCompression(rawFile, compressed, opts);
});
});
}, new Q(false))
.then(function (isSmaller) {
return {
name: rawFile.name,
isOptimized: !isSmaller,
exitCode: 0
};
})
.fail(function (err) {
return _handleError(err, rawFile);
});
}
|
javascript
|
function (rawFile, algorithms, opts) {
return _imageOptim(rawFile, algorithms, function (prev, next) {
return prev.then(function (res) {
return res || next(rawFile, _initCompressedFile(rawFile.name, opts._tmpDir))
.then(function (compressed) {
return _isSmallerAfterCompression(rawFile, compressed, opts);
});
});
}, new Q(false))
.then(function (isSmaller) {
return {
name: rawFile.name,
isOptimized: !isSmaller,
exitCode: 0
};
})
.fail(function (err) {
return _handleError(err, rawFile);
});
}
|
[
"function",
"(",
"rawFile",
",",
"algorithms",
",",
"opts",
")",
"{",
"return",
"_imageOptim",
"(",
"rawFile",
",",
"algorithms",
",",
"function",
"(",
"prev",
",",
"next",
")",
"{",
"return",
"prev",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"res",
"||",
"next",
"(",
"rawFile",
",",
"_initCompressedFile",
"(",
"rawFile",
".",
"name",
",",
"opts",
".",
"_tmpDir",
")",
")",
".",
"then",
"(",
"function",
"(",
"compressed",
")",
"{",
"return",
"_isSmallerAfterCompression",
"(",
"rawFile",
",",
"compressed",
",",
"opts",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
",",
"new",
"Q",
"(",
"false",
")",
")",
".",
"then",
"(",
"function",
"(",
"isSmaller",
")",
"{",
"return",
"{",
"name",
":",
"rawFile",
".",
"name",
",",
"isOptimized",
":",
"!",
"isSmaller",
",",
"exitCode",
":",
"0",
"}",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"return",
"_handleError",
"(",
"err",
",",
"rawFile",
")",
";",
"}",
")",
";",
"}"
] |
Checks whether the given file can be optimized further and return the information about the check
@examples
1. { name: 'file.ext', isOptimized: true, exitCode: 0 }
2. { name: 'file.ext', isOptimized: false, exitCode: 0 }
3. { name: 'file.ext', exitCode: 1 }
4. { name: 'file.ext', exitCode: 2 }
@param {File} rawFile
@param {Function[]} algorithms
@param {Object} [opts] -> lib/defaults.js
@param {Number} [opts.tolerance=0]
@param {String[]} [opts.reporters=[]]
@param {String} [opts._tmpDir=md5]
@returns {Promise * Object}
|
[
"Checks",
"whether",
"the",
"given",
"file",
"can",
"be",
"optimized",
"further",
"and",
"return",
"the",
"information",
"about",
"the",
"check"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/modes.js#L167-L186
|
train
|
|
ripple/ripple-hashes
|
src/sha512half.js
|
sha512half
|
function sha512half(buffer) {
var sha512 = createHash('sha512');
return sha512.update(buffer).digest('hex').toUpperCase().slice(0, 64);
}
|
javascript
|
function sha512half(buffer) {
var sha512 = createHash('sha512');
return sha512.update(buffer).digest('hex').toUpperCase().slice(0, 64);
}
|
[
"function",
"sha512half",
"(",
"buffer",
")",
"{",
"var",
"sha512",
"=",
"createHash",
"(",
"'sha512'",
")",
";",
"return",
"sha512",
".",
"update",
"(",
"buffer",
")",
".",
"digest",
"(",
"'hex'",
")",
".",
"toUpperCase",
"(",
")",
".",
"slice",
"(",
"0",
",",
"64",
")",
";",
"}"
] |
For a hash function, rippled uses SHA-512 and then truncates the result to the first 256 bytes. This algorithm, informally called SHA-512Half, provides an output that has comparable security to SHA-256, but runs faster on 64-bit processors.
|
[
"For",
"a",
"hash",
"function",
"rippled",
"uses",
"SHA",
"-",
"512",
"and",
"then",
"truncates",
"the",
"result",
"to",
"the",
"first",
"256",
"bytes",
".",
"This",
"algorithm",
"informally",
"called",
"SHA",
"-",
"512Half",
"provides",
"an",
"output",
"that",
"has",
"comparable",
"security",
"to",
"SHA",
"-",
"256",
"but",
"runs",
"faster",
"on",
"64",
"-",
"bit",
"processors",
"."
] |
7512d0e0e835f3cf132dfb1f69d2f22c0554e409
|
https://github.com/ripple/ripple-hashes/blob/7512d0e0e835f3cf132dfb1f69d2f22c0554e409/src/sha512half.js#L8-L11
|
train
|
bem-archive/image-optim
|
lib/algorithms/png.js
|
_compress
|
function _compress(command, outputFile) {
return qexec(command)
.then(function () {
return outputFile.loadSize();
})
.fail(function (err) {
// Before using of 'advpng' a raw file has to be copied
// This algorithm can not compress a file and write a result to another file
return qfs.exists(outputFile.name)
.then(function (exists) {
if (exists) {
outputFile.remove();
}
throw err;
});
});
}
|
javascript
|
function _compress(command, outputFile) {
return qexec(command)
.then(function () {
return outputFile.loadSize();
})
.fail(function (err) {
// Before using of 'advpng' a raw file has to be copied
// This algorithm can not compress a file and write a result to another file
return qfs.exists(outputFile.name)
.then(function (exists) {
if (exists) {
outputFile.remove();
}
throw err;
});
});
}
|
[
"function",
"_compress",
"(",
"command",
",",
"outputFile",
")",
"{",
"return",
"qexec",
"(",
"command",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"outputFile",
".",
"loadSize",
"(",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
"err",
")",
"{",
"return",
"qfs",
".",
"exists",
"(",
"outputFile",
".",
"name",
")",
".",
"then",
"(",
"function",
"(",
"exists",
")",
"{",
"if",
"(",
"exists",
")",
"{",
"outputFile",
".",
"remove",
"(",
")",
";",
"}",
"throw",
"err",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Executes the given compression command and returns the instace of the compressed file
@param {String} command
@param {File} outputFile
@returns {Promise * File}
|
[
"Executes",
"the",
"given",
"compression",
"command",
"and",
"returns",
"the",
"instace",
"of",
"the",
"compressed",
"file"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/algorithms/png.js#L18-L35
|
train
|
bem-archive/image-optim
|
lib/image-optim.js
|
_splice
|
function _splice(files, length) {
var spliced = [];
while (files.length) {
spliced.push(files.splice(0, length));
}
return spliced;
}
|
javascript
|
function _splice(files, length) {
var spliced = [];
while (files.length) {
spliced.push(files.splice(0, length));
}
return spliced;
}
|
[
"function",
"_splice",
"(",
"files",
",",
"length",
")",
"{",
"var",
"spliced",
"=",
"[",
"]",
";",
"while",
"(",
"files",
".",
"length",
")",
"{",
"spliced",
".",
"push",
"(",
"files",
".",
"splice",
"(",
"0",
",",
"length",
")",
")",
";",
"}",
"return",
"spliced",
";",
"}"
] |
Divides the given array of files into groups of the given length
@param {String[]} files
@param {Number} length
@returns {Object[]}
|
[
"Divides",
"the",
"given",
"array",
"of",
"files",
"into",
"groups",
"of",
"the",
"given",
"length"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/image-optim.js#L15-L23
|
train
|
bem-archive/image-optim
|
lib/image-optim.js
|
_reduceImageOptimFunc
|
function _reduceImageOptimFunc(prev, next) {
return prev.then(function (res) {
return Q.all(next.map(function (filename) {
return modes[mode](new File(filename), algorithms, opts);
}))
.then(function (stepRes) {
return res.concat(stepRes);
});
});
}
|
javascript
|
function _reduceImageOptimFunc(prev, next) {
return prev.then(function (res) {
return Q.all(next.map(function (filename) {
return modes[mode](new File(filename), algorithms, opts);
}))
.then(function (stepRes) {
return res.concat(stepRes);
});
});
}
|
[
"function",
"_reduceImageOptimFunc",
"(",
"prev",
",",
"next",
")",
"{",
"return",
"prev",
".",
"then",
"(",
"function",
"(",
"res",
")",
"{",
"return",
"Q",
".",
"all",
"(",
"next",
".",
"map",
"(",
"function",
"(",
"filename",
")",
"{",
"return",
"modes",
"[",
"mode",
"]",
"(",
"new",
"File",
"(",
"filename",
")",
",",
"algorithms",
",",
"opts",
")",
";",
"}",
")",
")",
".",
"then",
"(",
"function",
"(",
"stepRes",
")",
"{",
"return",
"res",
".",
"concat",
"(",
"stepRes",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Helping reduce function
@param {Promise * OptimResult[]|LintResult[]} prev
@param {Promise * OptimResult[]|LintResult[]} next
@returns {Promise * OptimResult[]|LintResult[]}
|
[
"Helping",
"reduce",
"function"
] |
92dc730bcedf6f20713429c1c0843390377c8a24
|
https://github.com/bem-archive/image-optim/blob/92dc730bcedf6f20713429c1c0843390377c8a24/lib/image-optim.js#L56-L65
|
train
|
ripple/ripple-hashes
|
src/shamap.js
|
SHAMapTreeNodeLeaf
|
function SHAMapTreeNodeLeaf(tag, data, type) {
SHAMapTreeNode.call(this);
if (typeof tag !== 'string') {
throw new Error('Tag is unexpected type.');
}
this.tag = tag;
this.type = type;
this.data = data;
}
|
javascript
|
function SHAMapTreeNodeLeaf(tag, data, type) {
SHAMapTreeNode.call(this);
if (typeof tag !== 'string') {
throw new Error('Tag is unexpected type.');
}
this.tag = tag;
this.type = type;
this.data = data;
}
|
[
"function",
"SHAMapTreeNodeLeaf",
"(",
"tag",
",",
"data",
",",
"type",
")",
"{",
"SHAMapTreeNode",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"typeof",
"tag",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Tag is unexpected type.'",
")",
";",
"}",
"this",
".",
"tag",
"=",
"tag",
";",
"this",
".",
"type",
"=",
"type",
";",
"this",
".",
"data",
"=",
"data",
";",
"}"
] |
Leaf node in a SHAMap tree.
@param {String} tag (equates to a ledger entry `index`)
@param {String} data (hex of account state, transaction etc)
@param {Number} type (one of TYPE_ACCOUNT_STATE, TYPE_TRANSACTION_MD etc)
@class
|
[
"Leaf",
"node",
"in",
"a",
"SHAMap",
"tree",
"."
] |
7512d0e0e835f3cf132dfb1f69d2f22c0554e409
|
https://github.com/ripple/ripple-hashes/blob/7512d0e0e835f3cf132dfb1f69d2f22c0554e409/src/shamap.js#L253-L263
|
train
|
ripple/ripple-hashes
|
src/shamap.js
|
SHAMap
|
function SHAMap(version) {
this.version = version === undefined ? 1 : version;
this.root = this.version === 1 ? new SHAMapTreeNodeInner(0) :
new SHAMapTreeNodeInnerV2(0);
}
|
javascript
|
function SHAMap(version) {
this.version = version === undefined ? 1 : version;
this.root = this.version === 1 ? new SHAMapTreeNodeInner(0) :
new SHAMapTreeNodeInnerV2(0);
}
|
[
"function",
"SHAMap",
"(",
"version",
")",
"{",
"this",
".",
"version",
"=",
"version",
"===",
"undefined",
"?",
"1",
":",
"version",
";",
"this",
".",
"root",
"=",
"this",
".",
"version",
"===",
"1",
"?",
"new",
"SHAMapTreeNodeInner",
"(",
"0",
")",
":",
"new",
"SHAMapTreeNodeInnerV2",
"(",
"0",
")",
";",
"}"
] |
SHAMap tree.
@param {Number} version (inner node version number)
@class
|
[
"SHAMap",
"tree",
"."
] |
7512d0e0e835f3cf132dfb1f69d2f22c0554e409
|
https://github.com/ripple/ripple-hashes/blob/7512d0e0e835f3cf132dfb1f69d2f22c0554e409/src/shamap.js#L288-L292
|
train
|
theasta/grunt-assets-versioning
|
tasks/helpers/task.js
|
function (taskName, taskFiles) {
grunt.log.writeln("Versioning files from " + taskName + " task.");
this.taskName = taskName;
this.taskConfig = this.getTaskConfig();
if (!this.taskConfig) {
grunt.fail.warn("Task '" + this.taskName + "' doesn't exist or doesn't have any configuration.", 1);
}
this.taskFiles = taskFiles || this.getFiles();
if (!this.taskFiles || this.taskFiles.length === 0) {
grunt.fail.warn("Task '" + this.taskName + "' doesn't have any src-dest file mappings.", 1);
}
}
|
javascript
|
function (taskName, taskFiles) {
grunt.log.writeln("Versioning files from " + taskName + " task.");
this.taskName = taskName;
this.taskConfig = this.getTaskConfig();
if (!this.taskConfig) {
grunt.fail.warn("Task '" + this.taskName + "' doesn't exist or doesn't have any configuration.", 1);
}
this.taskFiles = taskFiles || this.getFiles();
if (!this.taskFiles || this.taskFiles.length === 0) {
grunt.fail.warn("Task '" + this.taskName + "' doesn't have any src-dest file mappings.", 1);
}
}
|
[
"function",
"(",
"taskName",
",",
"taskFiles",
")",
"{",
"grunt",
".",
"log",
".",
"writeln",
"(",
"\"Versioning files from \"",
"+",
"taskName",
"+",
"\" task.\"",
")",
";",
"this",
".",
"taskName",
"=",
"taskName",
";",
"this",
".",
"taskConfig",
"=",
"this",
".",
"getTaskConfig",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"taskConfig",
")",
"{",
"grunt",
".",
"fail",
".",
"warn",
"(",
"\"Task '\"",
"+",
"this",
".",
"taskName",
"+",
"\"' doesn't exist or doesn't have any configuration.\"",
",",
"1",
")",
";",
"}",
"this",
".",
"taskFiles",
"=",
"taskFiles",
"||",
"this",
".",
"getFiles",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"taskFiles",
"||",
"this",
".",
"taskFiles",
".",
"length",
"===",
"0",
")",
"{",
"grunt",
".",
"fail",
".",
"warn",
"(",
"\"Task '\"",
"+",
"this",
".",
"taskName",
"+",
"\"' doesn't have any src-dest file mappings.\"",
",",
"1",
")",
";",
"}",
"}"
] |
Create a task instance
@param {string} taskName
@param {Array} [taskFiles]
@constructor
|
[
"Create",
"a",
"task",
"instance"
] |
5e2e62b90e3cc2b635582cce0e6598ce2bc8acab
|
https://github.com/theasta/grunt-assets-versioning/blob/5e2e62b90e3cc2b635582cce0e6598ce2bc8acab/tasks/helpers/task.js#L15-L30
|
train
|
|
bpmn-io/bpmnlint
|
rules/helper.js
|
disallowNodeType
|
function disallowNodeType(type) {
return function() {
function check(node, reporter) {
if (is(node, type)) {
reporter.report(node.id, 'Element has disallowed type <' + type + '>');
}
}
return {
check
};
};
}
|
javascript
|
function disallowNodeType(type) {
return function() {
function check(node, reporter) {
if (is(node, type)) {
reporter.report(node.id, 'Element has disallowed type <' + type + '>');
}
}
return {
check
};
};
}
|
[
"function",
"disallowNodeType",
"(",
"type",
")",
"{",
"return",
"function",
"(",
")",
"{",
"function",
"check",
"(",
"node",
",",
"reporter",
")",
"{",
"if",
"(",
"is",
"(",
"node",
",",
"type",
")",
")",
"{",
"reporter",
".",
"report",
"(",
"node",
".",
"id",
",",
"'Element has disallowed type <'",
"+",
"type",
"+",
"'>'",
")",
";",
"}",
"}",
"return",
"{",
"check",
"}",
";",
"}",
";",
"}"
] |
Create a checker that disallows the given element type.
@param {String} type
@return {Function} ruleImpl
|
[
"Create",
"a",
"checker",
"that",
"disallows",
"the",
"given",
"element",
"type",
"."
] |
fb029d8064506b97a5f500a9760ae35a0d6e4ba9
|
https://github.com/bpmn-io/bpmnlint/blob/fb029d8064506b97a5f500a9760ae35a0d6e4ba9/rules/helper.js#L12-L29
|
train
|
bpmn-io/bpmnlint
|
bin/bpmnlint.js
|
parseDiagram
|
function parseDiagram(diagramXML) {
return new Promise((resolve, reject) => {
moddle.fromXML(diagramXML, (error, moddleElement, context) => {
if (error) {
return resolve({
error
});
}
const warnings = context.warnings || [];
return resolve({
moddleElement,
warnings
});
});
});
}
|
javascript
|
function parseDiagram(diagramXML) {
return new Promise((resolve, reject) => {
moddle.fromXML(diagramXML, (error, moddleElement, context) => {
if (error) {
return resolve({
error
});
}
const warnings = context.warnings || [];
return resolve({
moddleElement,
warnings
});
});
});
}
|
[
"function",
"parseDiagram",
"(",
"diagramXML",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"moddle",
".",
"fromXML",
"(",
"diagramXML",
",",
"(",
"error",
",",
"moddleElement",
",",
"context",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"resolve",
"(",
"{",
"error",
"}",
")",
";",
"}",
"const",
"warnings",
"=",
"context",
".",
"warnings",
"||",
"[",
"]",
";",
"return",
"resolve",
"(",
"{",
"moddleElement",
",",
"warnings",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Reads XML form path and return moddle object
@param {*} sourcePath
|
[
"Reads",
"XML",
"form",
"path",
"and",
"return",
"moddle",
"object"
] |
fb029d8064506b97a5f500a9760ae35a0d6e4ba9
|
https://github.com/bpmn-io/bpmnlint/blob/fb029d8064506b97a5f500a9760ae35a0d6e4ba9/bin/bpmnlint.js#L34-L52
|
train
|
bpmn-io/bpmnlint
|
bin/bpmnlint.js
|
tableEntry
|
function tableEntry(report) {
const category = report.category;
const color = category === 'error' ? red : yellow;
return [ report.id || '', color(categoryMap[category] || category), report.message, report.name || '' ];
}
|
javascript
|
function tableEntry(report) {
const category = report.category;
const color = category === 'error' ? red : yellow;
return [ report.id || '', color(categoryMap[category] || category), report.message, report.name || '' ];
}
|
[
"function",
"tableEntry",
"(",
"report",
")",
"{",
"const",
"category",
"=",
"report",
".",
"category",
";",
"const",
"color",
"=",
"category",
"===",
"'error'",
"?",
"red",
":",
"yellow",
";",
"return",
"[",
"report",
".",
"id",
"||",
"''",
",",
"color",
"(",
"categoryMap",
"[",
"category",
"]",
"||",
"category",
")",
",",
"report",
".",
"message",
",",
"report",
".",
"name",
"||",
"''",
"]",
";",
"}"
] |
Logs a formatted message
|
[
"Logs",
"a",
"formatted",
"message"
] |
fb029d8064506b97a5f500a9760ae35a0d6e4ba9
|
https://github.com/bpmn-io/bpmnlint/blob/fb029d8064506b97a5f500a9760ae35a0d6e4ba9/bin/bpmnlint.js#L61-L67
|
train
|
bpmn-io/bpmnlint
|
bin/bpmnlint.js
|
printReports
|
function printReports(filePath, results) {
let errorCount = 0;
let warningCount = 0;
const table = createTable();
Object.entries(results).forEach(function([ name, reports ]) {
reports.forEach(function(report) {
const {
category,
id,
message,
name: reportName
} = report;
table.push(tableEntry({
category,
id,
message,
name: reportName || name
}));
if (category === 'error') {
errorCount++;
} else {
warningCount++;
}
});
});
const problemCount = warningCount + errorCount;
if (problemCount) {
console.log();
console.log(underline(path.resolve(filePath)));
console.log(table.toString());
}
return {
errorCount,
warningCount
};
}
|
javascript
|
function printReports(filePath, results) {
let errorCount = 0;
let warningCount = 0;
const table = createTable();
Object.entries(results).forEach(function([ name, reports ]) {
reports.forEach(function(report) {
const {
category,
id,
message,
name: reportName
} = report;
table.push(tableEntry({
category,
id,
message,
name: reportName || name
}));
if (category === 'error') {
errorCount++;
} else {
warningCount++;
}
});
});
const problemCount = warningCount + errorCount;
if (problemCount) {
console.log();
console.log(underline(path.resolve(filePath)));
console.log(table.toString());
}
return {
errorCount,
warningCount
};
}
|
[
"function",
"printReports",
"(",
"filePath",
",",
"results",
")",
"{",
"let",
"errorCount",
"=",
"0",
";",
"let",
"warningCount",
"=",
"0",
";",
"const",
"table",
"=",
"createTable",
"(",
")",
";",
"Object",
".",
"entries",
"(",
"results",
")",
".",
"forEach",
"(",
"function",
"(",
"[",
"name",
",",
"reports",
"]",
")",
"{",
"reports",
".",
"forEach",
"(",
"function",
"(",
"report",
")",
"{",
"const",
"{",
"category",
",",
"id",
",",
"message",
",",
"name",
":",
"reportName",
"}",
"=",
"report",
";",
"table",
".",
"push",
"(",
"tableEntry",
"(",
"{",
"category",
",",
"id",
",",
"message",
",",
"name",
":",
"reportName",
"||",
"name",
"}",
")",
")",
";",
"if",
"(",
"category",
"===",
"'error'",
")",
"{",
"errorCount",
"++",
";",
"}",
"else",
"{",
"warningCount",
"++",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"const",
"problemCount",
"=",
"warningCount",
"+",
"errorCount",
";",
"if",
"(",
"problemCount",
")",
"{",
"console",
".",
"log",
"(",
")",
";",
"console",
".",
"log",
"(",
"underline",
"(",
"path",
".",
"resolve",
"(",
"filePath",
")",
")",
")",
";",
"console",
".",
"log",
"(",
"table",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"{",
"errorCount",
",",
"warningCount",
"}",
";",
"}"
] |
Prints lint results to the console
@param {String} filePath
@param {Object} results
|
[
"Prints",
"lint",
"results",
"to",
"the",
"console"
] |
fb029d8064506b97a5f500a9760ae35a0d6e4ba9
|
https://github.com/bpmn-io/bpmnlint/blob/fb029d8064506b97a5f500a9760ae35a0d6e4ba9/bin/bpmnlint.js#L102-L147
|
train
|
meteor/promise
|
promise_server.js
|
awaitPromise
|
function awaitPromise(promise) {
var Promise = promise.constructor;
var Fiber = Promise.Fiber;
assert.strictEqual(
typeof Fiber, "function",
"Cannot await unless Promise.Fiber is defined"
);
var fiber = Fiber.current;
assert.ok(
fiber instanceof Fiber,
"Cannot await without a Fiber"
);
var run = fiber.run;
var throwInto = fiber.throwInto;
if (process.domain) {
run = process.domain.bind(run);
throwInto = process.domain.bind(throwInto);
}
// The overridden es6PromiseThen function is adequate here because these
// two callbacks do not need to run in a Fiber.
es6PromiseThen.call(promise, function (result) {
tryCatchNextTick(fiber, run, [result]);
}, function (error) {
tryCatchNextTick(fiber, throwInto, [error]);
});
return stackSafeYield(Fiber, awaitPromise);
}
|
javascript
|
function awaitPromise(promise) {
var Promise = promise.constructor;
var Fiber = Promise.Fiber;
assert.strictEqual(
typeof Fiber, "function",
"Cannot await unless Promise.Fiber is defined"
);
var fiber = Fiber.current;
assert.ok(
fiber instanceof Fiber,
"Cannot await without a Fiber"
);
var run = fiber.run;
var throwInto = fiber.throwInto;
if (process.domain) {
run = process.domain.bind(run);
throwInto = process.domain.bind(throwInto);
}
// The overridden es6PromiseThen function is adequate here because these
// two callbacks do not need to run in a Fiber.
es6PromiseThen.call(promise, function (result) {
tryCatchNextTick(fiber, run, [result]);
}, function (error) {
tryCatchNextTick(fiber, throwInto, [error]);
});
return stackSafeYield(Fiber, awaitPromise);
}
|
[
"function",
"awaitPromise",
"(",
"promise",
")",
"{",
"var",
"Promise",
"=",
"promise",
".",
"constructor",
";",
"var",
"Fiber",
"=",
"Promise",
".",
"Fiber",
";",
"assert",
".",
"strictEqual",
"(",
"typeof",
"Fiber",
",",
"\"function\"",
",",
"\"Cannot await unless Promise.Fiber is defined\"",
")",
";",
"var",
"fiber",
"=",
"Fiber",
".",
"current",
";",
"assert",
".",
"ok",
"(",
"fiber",
"instanceof",
"Fiber",
",",
"\"Cannot await without a Fiber\"",
")",
";",
"var",
"run",
"=",
"fiber",
".",
"run",
";",
"var",
"throwInto",
"=",
"fiber",
".",
"throwInto",
";",
"if",
"(",
"process",
".",
"domain",
")",
"{",
"run",
"=",
"process",
".",
"domain",
".",
"bind",
"(",
"run",
")",
";",
"throwInto",
"=",
"process",
".",
"domain",
".",
"bind",
"(",
"throwInto",
")",
";",
"}",
"es6PromiseThen",
".",
"call",
"(",
"promise",
",",
"function",
"(",
"result",
")",
"{",
"tryCatchNextTick",
"(",
"fiber",
",",
"run",
",",
"[",
"result",
"]",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"tryCatchNextTick",
"(",
"fiber",
",",
"throwInto",
",",
"[",
"error",
"]",
")",
";",
"}",
")",
";",
"return",
"stackSafeYield",
"(",
"Fiber",
",",
"awaitPromise",
")",
";",
"}"
] |
Yield the current Fiber until the given Promise has been fulfilled.
|
[
"Yield",
"the",
"current",
"Fiber",
"until",
"the",
"given",
"Promise",
"has",
"been",
"fulfilled",
"."
] |
cab087d69b8a7be4ae6b9aa45f0abae47d0778fa
|
https://github.com/meteor/promise/blob/cab087d69b8a7be4ae6b9aa45f0abae47d0778fa/promise_server.js#L64-L97
|
train
|
aurelia/pal-nodejs
|
dist/index.js
|
initialize
|
function initialize() {
if (aurelia_pal_1.isInitialized) {
return;
}
let pal = nodejs_pal_builder_1.buildPal();
aurelia_pal_1.initializePAL((platform, feature, dom) => {
Object.assign(platform, pal.platform);
Object.setPrototypeOf(platform, pal.platform.constructor.prototype);
Object.assign(dom, pal.dom);
Object.setPrototypeOf(dom, pal.dom.constructor.prototype);
Object.assign(feature, pal.feature);
Object.setPrototypeOf(feature, pal.feature.constructor.prototype);
(function (global) {
global.console = global.console || {};
let con = global.console;
let prop;
let method;
let empty = {};
let dummy = function () { };
let properties = 'memory'.split(',');
let methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' +
'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' +
'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',');
while (prop = properties.pop())
if (!con[prop])
con[prop] = empty;
while (method = methods.pop())
if (!con[method])
con[method] = dummy;
})(platform.global);
if (platform.global.console && typeof console.log === 'object') {
if (typeof console['debug'] === 'undefined') {
console['debug'] = this.bind(console['log'], console);
}
['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function (method) {
console[method] = this.bind(console[method], console);
}, Function.prototype.call);
}
Object.defineProperty(dom, 'title', {
get: function () {
return pal.global.document.title;
},
set: function (value) {
pal.global.document.title = value;
}
});
Object.defineProperty(dom, 'activeElement', {
get: function () {
return pal.global.document.activeElement;
}
});
Object.defineProperty(platform, 'XMLHttpRequest', {
get: function () {
return pal.global.XMLHttpRequest;
}
});
});
}
|
javascript
|
function initialize() {
if (aurelia_pal_1.isInitialized) {
return;
}
let pal = nodejs_pal_builder_1.buildPal();
aurelia_pal_1.initializePAL((platform, feature, dom) => {
Object.assign(platform, pal.platform);
Object.setPrototypeOf(platform, pal.platform.constructor.prototype);
Object.assign(dom, pal.dom);
Object.setPrototypeOf(dom, pal.dom.constructor.prototype);
Object.assign(feature, pal.feature);
Object.setPrototypeOf(feature, pal.feature.constructor.prototype);
(function (global) {
global.console = global.console || {};
let con = global.console;
let prop;
let method;
let empty = {};
let dummy = function () { };
let properties = 'memory'.split(',');
let methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' +
'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' +
'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',');
while (prop = properties.pop())
if (!con[prop])
con[prop] = empty;
while (method = methods.pop())
if (!con[method])
con[method] = dummy;
})(platform.global);
if (platform.global.console && typeof console.log === 'object') {
if (typeof console['debug'] === 'undefined') {
console['debug'] = this.bind(console['log'], console);
}
['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'].forEach(function (method) {
console[method] = this.bind(console[method], console);
}, Function.prototype.call);
}
Object.defineProperty(dom, 'title', {
get: function () {
return pal.global.document.title;
},
set: function (value) {
pal.global.document.title = value;
}
});
Object.defineProperty(dom, 'activeElement', {
get: function () {
return pal.global.document.activeElement;
}
});
Object.defineProperty(platform, 'XMLHttpRequest', {
get: function () {
return pal.global.XMLHttpRequest;
}
});
});
}
|
[
"function",
"initialize",
"(",
")",
"{",
"if",
"(",
"aurelia_pal_1",
".",
"isInitialized",
")",
"{",
"return",
";",
"}",
"let",
"pal",
"=",
"nodejs_pal_builder_1",
".",
"buildPal",
"(",
")",
";",
"aurelia_pal_1",
".",
"initializePAL",
"(",
"(",
"platform",
",",
"feature",
",",
"dom",
")",
"=>",
"{",
"Object",
".",
"assign",
"(",
"platform",
",",
"pal",
".",
"platform",
")",
";",
"Object",
".",
"setPrototypeOf",
"(",
"platform",
",",
"pal",
".",
"platform",
".",
"constructor",
".",
"prototype",
")",
";",
"Object",
".",
"assign",
"(",
"dom",
",",
"pal",
".",
"dom",
")",
";",
"Object",
".",
"setPrototypeOf",
"(",
"dom",
",",
"pal",
".",
"dom",
".",
"constructor",
".",
"prototype",
")",
";",
"Object",
".",
"assign",
"(",
"feature",
",",
"pal",
".",
"feature",
")",
";",
"Object",
".",
"setPrototypeOf",
"(",
"feature",
",",
"pal",
".",
"feature",
".",
"constructor",
".",
"prototype",
")",
";",
"(",
"function",
"(",
"global",
")",
"{",
"global",
".",
"console",
"=",
"global",
".",
"console",
"||",
"{",
"}",
";",
"let",
"con",
"=",
"global",
".",
"console",
";",
"let",
"prop",
";",
"let",
"method",
";",
"let",
"empty",
"=",
"{",
"}",
";",
"let",
"dummy",
"=",
"function",
"(",
")",
"{",
"}",
";",
"let",
"properties",
"=",
"'memory'",
".",
"split",
"(",
"','",
")",
";",
"let",
"methods",
"=",
"(",
"'assert,clear,count,debug,dir,dirxml,error,exception,group,'",
"+",
"'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,'",
"+",
"'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn'",
")",
".",
"split",
"(",
"','",
")",
";",
"while",
"(",
"prop",
"=",
"properties",
".",
"pop",
"(",
")",
")",
"if",
"(",
"!",
"con",
"[",
"prop",
"]",
")",
"con",
"[",
"prop",
"]",
"=",
"empty",
";",
"while",
"(",
"method",
"=",
"methods",
".",
"pop",
"(",
")",
")",
"if",
"(",
"!",
"con",
"[",
"method",
"]",
")",
"con",
"[",
"method",
"]",
"=",
"dummy",
";",
"}",
")",
"(",
"platform",
".",
"global",
")",
";",
"if",
"(",
"platform",
".",
"global",
".",
"console",
"&&",
"typeof",
"console",
".",
"log",
"===",
"'object'",
")",
"{",
"if",
"(",
"typeof",
"console",
"[",
"'debug'",
"]",
"===",
"'undefined'",
")",
"{",
"console",
"[",
"'debug'",
"]",
"=",
"this",
".",
"bind",
"(",
"console",
"[",
"'log'",
"]",
",",
"console",
")",
";",
"}",
"[",
"'log'",
",",
"'info'",
",",
"'warn'",
",",
"'error'",
",",
"'assert'",
",",
"'dir'",
",",
"'clear'",
",",
"'profile'",
",",
"'profileEnd'",
"]",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"console",
"[",
"method",
"]",
"=",
"this",
".",
"bind",
"(",
"console",
"[",
"method",
"]",
",",
"console",
")",
";",
"}",
",",
"Function",
".",
"prototype",
".",
"call",
")",
";",
"}",
"Object",
".",
"defineProperty",
"(",
"dom",
",",
"'title'",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"pal",
".",
"global",
".",
"document",
".",
"title",
";",
"}",
",",
"set",
":",
"function",
"(",
"value",
")",
"{",
"pal",
".",
"global",
".",
"document",
".",
"title",
"=",
"value",
";",
"}",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"dom",
",",
"'activeElement'",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"pal",
".",
"global",
".",
"document",
".",
"activeElement",
";",
"}",
"}",
")",
";",
"Object",
".",
"defineProperty",
"(",
"platform",
",",
"'XMLHttpRequest'",
",",
"{",
"get",
":",
"function",
"(",
")",
"{",
"return",
"pal",
".",
"global",
".",
"XMLHttpRequest",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Initializes the PAL with the NodeJS-targeted implementation.
|
[
"Initializes",
"the",
"PAL",
"with",
"the",
"NodeJS",
"-",
"targeted",
"implementation",
"."
] |
711664e16486eac4c33a59cc633813aa316a8ad4
|
https://github.com/aurelia/pal-nodejs/blob/711664e16486eac4c33a59cc633813aa316a8ad4/dist/index.js#L12-L69
|
train
|
angularjs-oauth/oauth-ng
|
dist/oauth-ng.js
|
function (jws, pubKey, alg) {
/*
convert various public key format to RSAKey object
see @KEYUTIL.getKey for a full list of supported input format
*/
var rsaKey = KEYUTIL.getKey(pubKey);
return KJUR.jws.JWS.verify(jws, rsaKey, [alg]);
}
|
javascript
|
function (jws, pubKey, alg) {
/*
convert various public key format to RSAKey object
see @KEYUTIL.getKey for a full list of supported input format
*/
var rsaKey = KEYUTIL.getKey(pubKey);
return KJUR.jws.JWS.verify(jws, rsaKey, [alg]);
}
|
[
"function",
"(",
"jws",
",",
"pubKey",
",",
"alg",
")",
"{",
"var",
"rsaKey",
"=",
"KEYUTIL",
".",
"getKey",
"(",
"pubKey",
")",
";",
"return",
"KJUR",
".",
"jws",
".",
"JWS",
".",
"verify",
"(",
"jws",
",",
"rsaKey",
",",
"[",
"alg",
"]",
")",
";",
"}"
] |
Verifies the JWS string using the JWK
@param {string} jws The JWS string
@param {object} pubKey The public key that will be used to verify the signature
@param {string} alg The algorithm string. Expecting 'RS256', 'RS384', or 'RS512'
@returns {boolean} Validity of the JWS signature
@throws {OidcException}
|
[
"Verifies",
"the",
"JWS",
"string",
"using",
"the",
"JWK"
] |
48aa4fa86fdd8d9c859be4206049ec0d7422c720
|
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L245-L253
|
train
|
|
angularjs-oauth/oauth-ng
|
dist/oauth-ng.js
|
function (id_token) {
var jws = new KJUR.jws.JWS();
jws.parseJWS(id_token);
return [jws.parsedJWS.headS, jws.parsedJWS.payloadS, jws.parsedJWS.si];
}
|
javascript
|
function (id_token) {
var jws = new KJUR.jws.JWS();
jws.parseJWS(id_token);
return [jws.parsedJWS.headS, jws.parsedJWS.payloadS, jws.parsedJWS.si];
}
|
[
"function",
"(",
"id_token",
")",
"{",
"var",
"jws",
"=",
"new",
"KJUR",
".",
"jws",
".",
"JWS",
"(",
")",
";",
"jws",
".",
"parseJWS",
"(",
"id_token",
")",
";",
"return",
"[",
"jws",
".",
"parsedJWS",
".",
"headS",
",",
"jws",
".",
"parsedJWS",
".",
"payloadS",
",",
"jws",
".",
"parsedJWS",
".",
"si",
"]",
";",
"}"
] |
Splits the ID Token string into the individual JWS parts
@param {string} id_token ID Token
@returns {Array} An array of the JWS compact serialization components (header, payload, signature)
|
[
"Splits",
"the",
"ID",
"Token",
"string",
"into",
"the",
"individual",
"JWS",
"parts"
] |
48aa4fa86fdd8d9c859be4206049ec0d7422c720
|
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L260-L264
|
train
|
|
angularjs-oauth/oauth-ng
|
dist/oauth-ng.js
|
function (jsonS) {
var jws = KJUR.jws.JWS;
if(jws.isSafeJSONString(jsonS)) {
return jws.readSafeJSONString(jsonS);
}
return null;
}
|
javascript
|
function (jsonS) {
var jws = KJUR.jws.JWS;
if(jws.isSafeJSONString(jsonS)) {
return jws.readSafeJSONString(jsonS);
}
return null;
}
|
[
"function",
"(",
"jsonS",
")",
"{",
"var",
"jws",
"=",
"KJUR",
".",
"jws",
".",
"JWS",
";",
"if",
"(",
"jws",
".",
"isSafeJSONString",
"(",
"jsonS",
")",
")",
"{",
"return",
"jws",
".",
"readSafeJSONString",
"(",
"jsonS",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Get the JSON object from the JSON string
@param {string} jsonS JSON string
@returns {object|null} JSON object or null
|
[
"Get",
"the",
"JSON",
"object",
"from",
"the",
"JSON",
"string"
] |
48aa4fa86fdd8d9c859be4206049ec0d7422c720
|
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L282-L288
|
train
|
|
angularjs-oauth/oauth-ng
|
dist/oauth-ng.js
|
function(params){
service.token = service.token || {}; // init the token
angular.extend(service.token, params); // set the access token params
setTokenInSession(); // save the token into the session
setExpiresAtEvent(); // event to fire when the token expires
return service.token;
}
|
javascript
|
function(params){
service.token = service.token || {}; // init the token
angular.extend(service.token, params); // set the access token params
setTokenInSession(); // save the token into the session
setExpiresAtEvent(); // event to fire when the token expires
return service.token;
}
|
[
"function",
"(",
"params",
")",
"{",
"service",
".",
"token",
"=",
"service",
".",
"token",
"||",
"{",
"}",
";",
"angular",
".",
"extend",
"(",
"service",
".",
"token",
",",
"params",
")",
";",
"setTokenInSession",
"(",
")",
";",
"setExpiresAtEvent",
"(",
")",
";",
"return",
"service",
".",
"token",
";",
"}"
] |
Set the access token.
@param params
@returns {*|{}}
|
[
"Set",
"the",
"access",
"token",
"."
] |
48aa4fa86fdd8d9c859be4206049ec0d7422c720
|
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L469-L476
|
train
|
|
angularjs-oauth/oauth-ng
|
dist/oauth-ng.js
|
function(hash){
var params = {},
regex = /([^&=]+)=([^&]*)/g,
m;
while ((m = regex.exec(hash)) !== null) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// OpenID Connect
if (params.id_token && !params.error) {
IdToken.validateTokensAndPopulateClaims(params);
return params;
}
// Oauth2
if(params.access_token || params.error){
return params;
}
}
|
javascript
|
function(hash){
var params = {},
regex = /([^&=]+)=([^&]*)/g,
m;
while ((m = regex.exec(hash)) !== null) {
params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
// OpenID Connect
if (params.id_token && !params.error) {
IdToken.validateTokensAndPopulateClaims(params);
return params;
}
// Oauth2
if(params.access_token || params.error){
return params;
}
}
|
[
"function",
"(",
"hash",
")",
"{",
"var",
"params",
"=",
"{",
"}",
",",
"regex",
"=",
"/",
"([^&=]+)=([^&]*)",
"/",
"g",
",",
"m",
";",
"while",
"(",
"(",
"m",
"=",
"regex",
".",
"exec",
"(",
"hash",
")",
")",
"!==",
"null",
")",
"{",
"params",
"[",
"decodeURIComponent",
"(",
"m",
"[",
"1",
"]",
")",
"]",
"=",
"decodeURIComponent",
"(",
"m",
"[",
"2",
"]",
")",
";",
"}",
"if",
"(",
"params",
".",
"id_token",
"&&",
"!",
"params",
".",
"error",
")",
"{",
"IdToken",
".",
"validateTokensAndPopulateClaims",
"(",
"params",
")",
";",
"return",
"params",
";",
"}",
"if",
"(",
"params",
".",
"access_token",
"||",
"params",
".",
"error",
")",
"{",
"return",
"params",
";",
"}",
"}"
] |
Parse the fragment URI and return an object
@param hash
@returns {{}}
|
[
"Parse",
"the",
"fragment",
"URI",
"and",
"return",
"an",
"object"
] |
48aa4fa86fdd8d9c859be4206049ec0d7422c720
|
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L483-L502
|
train
|
|
angularjs-oauth/oauth-ng
|
dist/oauth-ng.js
|
function(){
// Don't bother if there's no expires token
if (typeof(service.token.expires_at) === 'undefined' || service.token.expires_at === null) {
return;
}
cancelExpiresAtEvent();
var time = (new Date(service.token.expires_at))-(new Date());
if(time && time > 0 && time <= 2147483647){
expiresAtEvent = $interval(function(){
$rootScope.$broadcast('oauth:expired', service.token);
}, time, 1);
}
}
|
javascript
|
function(){
// Don't bother if there's no expires token
if (typeof(service.token.expires_at) === 'undefined' || service.token.expires_at === null) {
return;
}
cancelExpiresAtEvent();
var time = (new Date(service.token.expires_at))-(new Date());
if(time && time > 0 && time <= 2147483647){
expiresAtEvent = $interval(function(){
$rootScope.$broadcast('oauth:expired', service.token);
}, time, 1);
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"typeof",
"(",
"service",
".",
"token",
".",
"expires_at",
")",
"===",
"'undefined'",
"||",
"service",
".",
"token",
".",
"expires_at",
"===",
"null",
")",
"{",
"return",
";",
"}",
"cancelExpiresAtEvent",
"(",
")",
";",
"var",
"time",
"=",
"(",
"new",
"Date",
"(",
"service",
".",
"token",
".",
"expires_at",
")",
")",
"-",
"(",
"new",
"Date",
"(",
")",
")",
";",
"if",
"(",
"time",
"&&",
"time",
">",
"0",
"&&",
"time",
"<=",
"2147483647",
")",
"{",
"expiresAtEvent",
"=",
"$interval",
"(",
"function",
"(",
")",
"{",
"$rootScope",
".",
"$broadcast",
"(",
"'oauth:expired'",
",",
"service",
".",
"token",
")",
";",
"}",
",",
"time",
",",
"1",
")",
";",
"}",
"}"
] |
Set the timeout at which the expired event is fired
|
[
"Set",
"the",
"timeout",
"at",
"which",
"the",
"expired",
"event",
"is",
"fired"
] |
48aa4fa86fdd8d9c859be4206049ec0d7422c720
|
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L532-L544
|
train
|
|
angularjs-oauth/oauth-ng
|
dist/oauth-ng.js
|
function(){
var curHash = $location.hash();
angular.forEach(hashFragmentKeys,function(hashKey){
var re = new RegExp('&'+hashKey+'(=[^&]*)?|^'+hashKey+'(=[^&]*)?&?');
curHash = curHash.replace(re,'');
});
$location.hash(curHash);
}
|
javascript
|
function(){
var curHash = $location.hash();
angular.forEach(hashFragmentKeys,function(hashKey){
var re = new RegExp('&'+hashKey+'(=[^&]*)?|^'+hashKey+'(=[^&]*)?&?');
curHash = curHash.replace(re,'');
});
$location.hash(curHash);
}
|
[
"function",
"(",
")",
"{",
"var",
"curHash",
"=",
"$location",
".",
"hash",
"(",
")",
";",
"angular",
".",
"forEach",
"(",
"hashFragmentKeys",
",",
"function",
"(",
"hashKey",
")",
"{",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"'&'",
"+",
"hashKey",
"+",
"'(=[^&]*)?|^'",
"+",
"hashKey",
"+",
"'(=[^&]*)?&?'",
")",
";",
"curHash",
"=",
"curHash",
".",
"replace",
"(",
"re",
",",
"''",
")",
";",
"}",
")",
";",
"$location",
".",
"hash",
"(",
"curHash",
")",
";",
"}"
] |
Remove the oAuth2 pieces from the hash fragment
|
[
"Remove",
"the",
"oAuth2",
"pieces",
"from",
"the",
"hash",
"fragment"
] |
48aa4fa86fdd8d9c859be4206049ec0d7422c720
|
https://github.com/angularjs-oauth/oauth-ng/blob/48aa4fa86fdd8d9c859be4206049ec0d7422c720/dist/oauth-ng.js#L556-L564
|
train
|
|
joaquimserafim/json-web-token
|
index.js
|
JWTError
|
function JWTError (message) {
Error.call(this)
Error.captureStackTrace(this, this.constructor)
this.name = this.constructor.name
this.message = message
}
|
javascript
|
function JWTError (message) {
Error.call(this)
Error.captureStackTrace(this, this.constructor)
this.name = this.constructor.name
this.message = message
}
|
[
"function",
"JWTError",
"(",
"message",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
"this",
".",
"name",
"=",
"this",
".",
"constructor",
".",
"name",
"this",
".",
"message",
"=",
"message",
"}"
] |
JWT token error
|
[
"JWT",
"token",
"error"
] |
b67038f7d9ee11b6c6ddef6e7203008a1e984667
|
https://github.com/joaquimserafim/json-web-token/blob/b67038f7d9ee11b6c6ddef6e7203008a1e984667/index.js#L119-L124
|
train
|
jankolkmeier/xbee-api
|
lib/frame-builder.js
|
appendData
|
function appendData(data, builder) {
if(Array.isArray(data) || Buffer.isBuffer(data)) {
data = Buffer.from(data);
} else {
data = Buffer.from(data, 'ascii');
}
builder.appendBuffer(data);
}
|
javascript
|
function appendData(data, builder) {
if(Array.isArray(data) || Buffer.isBuffer(data)) {
data = Buffer.from(data);
} else {
data = Buffer.from(data, 'ascii');
}
builder.appendBuffer(data);
}
|
[
"function",
"appendData",
"(",
"data",
",",
"builder",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"data",
")",
"||",
"Buffer",
".",
"isBuffer",
"(",
"data",
")",
")",
"{",
"data",
"=",
"Buffer",
".",
"from",
"(",
"data",
")",
";",
"}",
"else",
"{",
"data",
"=",
"Buffer",
".",
"from",
"(",
"data",
",",
"'ascii'",
")",
";",
"}",
"builder",
".",
"appendBuffer",
"(",
"data",
")",
";",
"}"
] |
Appends data provided as Array, String, or Buffer
|
[
"Appends",
"data",
"provided",
"as",
"Array",
"String",
"or",
"Buffer"
] |
c79490b0e624d35137539ceef759a053b80eae0e
|
https://github.com/jankolkmeier/xbee-api/blob/c79490b0e624d35137539ceef759a053b80eae0e/lib/frame-builder.js#L31-L39
|
train
|
tecfu/tty-table
|
adapters/terminal-adapter.js
|
function(header,body){
//footer = [],
let Table = require('../src/factory.js');
options.terminalAdapter = true;
let t1 = Table(header, body,options);
//hide cursor
console.log('\u001b[?25l');
//wipe existing if already rendered
if(alreadyRendered){
//move cursor up number to the top of the previous print
//before deleting
console.log('\u001b['+(previousHeight+3)+'A');
//delete to end of terminal
console.log('\u001b[0J');
}
else{
alreadyRendered = true;
}
console.log(t1.render());
//reset the previous height to the height of this output
//for when we next clear the print
previousHeight = t1.height;
}
|
javascript
|
function(header,body){
//footer = [],
let Table = require('../src/factory.js');
options.terminalAdapter = true;
let t1 = Table(header, body,options);
//hide cursor
console.log('\u001b[?25l');
//wipe existing if already rendered
if(alreadyRendered){
//move cursor up number to the top of the previous print
//before deleting
console.log('\u001b['+(previousHeight+3)+'A');
//delete to end of terminal
console.log('\u001b[0J');
}
else{
alreadyRendered = true;
}
console.log(t1.render());
//reset the previous height to the height of this output
//for when we next clear the print
previousHeight = t1.height;
}
|
[
"function",
"(",
"header",
",",
"body",
")",
"{",
"let",
"Table",
"=",
"require",
"(",
"'../src/factory.js'",
")",
";",
"options",
".",
"terminalAdapter",
"=",
"true",
";",
"let",
"t1",
"=",
"Table",
"(",
"header",
",",
"body",
",",
"options",
")",
";",
"console",
".",
"log",
"(",
"'\\u001b[?25l'",
")",
";",
"\\u001b",
"if",
"(",
"alreadyRendered",
")",
"{",
"console",
".",
"log",
"(",
"'\\u001b['",
"+",
"\\u001b",
"+",
"(",
"previousHeight",
"+",
"3",
")",
")",
";",
"'A'",
"}",
"else",
"console",
".",
"log",
"(",
"'\\u001b[0J'",
")",
";",
"\\u001b",
"}"
] |
because different dataFormats
|
[
"because",
"different",
"dataFormats"
] |
d77380de60e9b7a0023592bfc19c987a4d71cb28
|
https://github.com/tecfu/tty-table/blob/d77380de60e9b7a0023592bfc19c987a4d71cb28/adapters/terminal-adapter.js#L83-L113
|
train
|
|
BrowserSync/browser-sync-client
|
cbfile.js
|
function () {
var chunks = [];
return through2.obj(function (file, enc, cb) {
chunks.push(file);
var string = file._contents.toString();
var regex = /\/\*\*debug:start\*\*\/[\s\S]*\/\*\*debug:end\*\*\//g;
var stripped = string.replace(regex, "");
file.contents = new Buffer(stripped);
this.push(file);
cb();
});
}
|
javascript
|
function () {
var chunks = [];
return through2.obj(function (file, enc, cb) {
chunks.push(file);
var string = file._contents.toString();
var regex = /\/\*\*debug:start\*\*\/[\s\S]*\/\*\*debug:end\*\*\//g;
var stripped = string.replace(regex, "");
file.contents = new Buffer(stripped);
this.push(file);
cb();
});
}
|
[
"function",
"(",
")",
"{",
"var",
"chunks",
"=",
"[",
"]",
";",
"return",
"through2",
".",
"obj",
"(",
"function",
"(",
"file",
",",
"enc",
",",
"cb",
")",
"{",
"chunks",
".",
"push",
"(",
"file",
")",
";",
"var",
"string",
"=",
"file",
".",
"_contents",
".",
"toString",
"(",
")",
";",
"var",
"regex",
"=",
"/",
"\\/\\*\\*debug:start\\*\\*\\/[\\s\\S]*\\/\\*\\*debug:end\\*\\*\\/",
"/",
"g",
";",
"var",
"stripped",
"=",
"string",
".",
"replace",
"(",
"regex",
",",
"\"\"",
")",
";",
"file",
".",
"contents",
"=",
"new",
"Buffer",
"(",
"stripped",
")",
";",
"this",
".",
"push",
"(",
"file",
")",
";",
"cb",
"(",
")",
";",
"}",
")",
";",
"}"
] |
Strip debug statements
@returns {*}
|
[
"Strip",
"debug",
"statements"
] |
8ea3496a7af2f4b4674a5a56b08e206134dd2179
|
https://github.com/BrowserSync/browser-sync-client/blob/8ea3496a7af2f4b4674a5a56b08e206134dd2179/cbfile.js#L35-L46
|
train
|
|
C2FO/comb
|
lib/collections/HashTable.js
|
function (key, value) {
var hash = hashFunction(key);
var bucket = null;
if ((bucket = this.__map[hash]) == null) {
bucket = (this.__map[hash] = new Bucket());
}
bucket.pushValue(key, value);
return value;
}
|
javascript
|
function (key, value) {
var hash = hashFunction(key);
var bucket = null;
if ((bucket = this.__map[hash]) == null) {
bucket = (this.__map[hash] = new Bucket());
}
bucket.pushValue(key, value);
return value;
}
|
[
"function",
"(",
"key",
",",
"value",
")",
"{",
"var",
"hash",
"=",
"hashFunction",
"(",
"key",
")",
";",
"var",
"bucket",
"=",
"null",
";",
"if",
"(",
"(",
"bucket",
"=",
"this",
".",
"__map",
"[",
"hash",
"]",
")",
"==",
"null",
")",
"{",
"bucket",
"=",
"(",
"this",
".",
"__map",
"[",
"hash",
"]",
"=",
"new",
"Bucket",
"(",
")",
")",
";",
"}",
"bucket",
".",
"pushValue",
"(",
"key",
",",
"value",
")",
";",
"return",
"value",
";",
"}"
] |
Put a key, value pair into the table
<b>NOTE :</b> the collection will not check if the key previously existed.
@param {Anything} key the key to look up the object.
@param {Anything} value the value that corresponds to the key.
@returns the value
|
[
"Put",
"a",
"key",
"value",
"pair",
"into",
"the",
"table"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/HashTable.js#L156-L164
|
train
|
|
C2FO/comb
|
lib/collections/HashTable.js
|
function (cb, scope) {
var es = this.__entrySet(), ret = new this._static();
es = es.filter.apply(es, arguments);
for (var i = es.length - 1; i >= 0; i--) {
var e = es[i];
ret.put(e.key, e.value);
}
return ret;
}
|
javascript
|
function (cb, scope) {
var es = this.__entrySet(), ret = new this._static();
es = es.filter.apply(es, arguments);
for (var i = es.length - 1; i >= 0; i--) {
var e = es[i];
ret.put(e.key, e.value);
}
return ret;
}
|
[
"function",
"(",
"cb",
",",
"scope",
")",
"{",
"var",
"es",
"=",
"this",
".",
"__entrySet",
"(",
")",
",",
"ret",
"=",
"new",
"this",
".",
"_static",
"(",
")",
";",
"es",
"=",
"es",
".",
"filter",
".",
"apply",
"(",
"es",
",",
"arguments",
")",
";",
"for",
"(",
"var",
"i",
"=",
"es",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"var",
"e",
"=",
"es",
"[",
"i",
"]",
";",
"ret",
".",
"put",
"(",
"e",
".",
"key",
",",
"e",
".",
"value",
")",
";",
"}",
"return",
"ret",
";",
"}"
] |
Creates a new HashTable containg values that passed the filtering function.
@param {Function} cb Function to callback with each item, the first aruguments is an object containing a key and value field
@param {Object} scope the scope to call the function.
@returns {comb.collections.HashTable} the HashTable containing the values that passed the filter.
|
[
"Creates",
"a",
"new",
"HashTable",
"containg",
"values",
"that",
"passed",
"the",
"filtering",
"function",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/HashTable.js#L261-L269
|
train
|
|
C2FO/comb
|
lib/collections/HashTable.js
|
function (cb, scope) {
var es = this.__entrySet(), l = es.length, f = cb.bind(scope || this);
es.forEach.apply(es, arguments);
}
|
javascript
|
function (cb, scope) {
var es = this.__entrySet(), l = es.length, f = cb.bind(scope || this);
es.forEach.apply(es, arguments);
}
|
[
"function",
"(",
"cb",
",",
"scope",
")",
"{",
"var",
"es",
"=",
"this",
".",
"__entrySet",
"(",
")",
",",
"l",
"=",
"es",
".",
"length",
",",
"f",
"=",
"cb",
".",
"bind",
"(",
"scope",
"||",
"this",
")",
";",
"es",
".",
"forEach",
".",
"apply",
"(",
"es",
",",
"arguments",
")",
";",
"}"
] |
Loop through each value in the hashtable
@param {Function} cb the function to call with an object containing a key and value field
@param {Object} scope the scope to call the funciton in
|
[
"Loop",
"through",
"each",
"value",
"in",
"the",
"hashtable"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/HashTable.js#L277-L280
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function (cb) {
if (cb) {
if (isPromise(cb)) {
cb = cb.callback;
}
if (this.__fired && this.__results) {
this.__callNextTick(cb, this.__results);
} else {
this.__cbs.push(cb);
}
}
return this;
}
|
javascript
|
function (cb) {
if (cb) {
if (isPromise(cb)) {
cb = cb.callback;
}
if (this.__fired && this.__results) {
this.__callNextTick(cb, this.__results);
} else {
this.__cbs.push(cb);
}
}
return this;
}
|
[
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"cb",
")",
"{",
"if",
"(",
"isPromise",
"(",
"cb",
")",
")",
"{",
"cb",
"=",
"cb",
".",
"callback",
";",
"}",
"if",
"(",
"this",
".",
"__fired",
"&&",
"this",
".",
"__results",
")",
"{",
"this",
".",
"__callNextTick",
"(",
"cb",
",",
"this",
".",
"__results",
")",
";",
"}",
"else",
"{",
"this",
".",
"__cbs",
".",
"push",
"(",
"cb",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] |
Add a callback to the callback chain of the promise
@param {Function|comb.Promise} cb the function or promise to callback when the promise is resolved.
@return {comb.Promise} this promise for chaining
|
[
"Add",
"a",
"callback",
"to",
"the",
"callback",
"chain",
"of",
"the",
"promise"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L124-L136
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function (cb) {
if (cb) {
if (isPromise(cb)) {
cb = cb.errback;
}
if (this.__fired && this.__error) {
this.__callNextTick(cb, this.__error);
} else {
this.__errorCbs.push(cb);
}
}
return this;
}
|
javascript
|
function (cb) {
if (cb) {
if (isPromise(cb)) {
cb = cb.errback;
}
if (this.__fired && this.__error) {
this.__callNextTick(cb, this.__error);
} else {
this.__errorCbs.push(cb);
}
}
return this;
}
|
[
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"cb",
")",
"{",
"if",
"(",
"isPromise",
"(",
"cb",
")",
")",
"{",
"cb",
"=",
"cb",
".",
"errback",
";",
"}",
"if",
"(",
"this",
".",
"__fired",
"&&",
"this",
".",
"__error",
")",
"{",
"this",
".",
"__callNextTick",
"(",
"cb",
",",
"this",
".",
"__error",
")",
";",
"}",
"else",
"{",
"this",
".",
"__errorCbs",
".",
"push",
"(",
"cb",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] |
Add a callback to the errback chain of the promise
@param {Function|comb.Promise} cb the function or promise to callback when the promise errors
@return {comb.Promise} this promise for chaining
|
[
"Add",
"a",
"callback",
"to",
"the",
"errback",
"chain",
"of",
"the",
"promise"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L146-L158
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function (args) {
args = argsToArray(arguments);
if (this.__fired) {
throw new Error("Already fired!");
}
this.__results = args;
this.__resolve();
return this.promise();
}
|
javascript
|
function (args) {
args = argsToArray(arguments);
if (this.__fired) {
throw new Error("Already fired!");
}
this.__results = args;
this.__resolve();
return this.promise();
}
|
[
"function",
"(",
"args",
")",
"{",
"args",
"=",
"argsToArray",
"(",
"arguments",
")",
";",
"if",
"(",
"this",
".",
"__fired",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Already fired!\"",
")",
";",
"}",
"this",
".",
"__results",
"=",
"args",
";",
"this",
".",
"__resolve",
"(",
")",
";",
"return",
"this",
".",
"promise",
"(",
")",
";",
"}"
] |
When called all functions registered as callbacks are called with the passed in results.
@param {*} args variable number of results to pass back to listeners of the promise
|
[
"When",
"called",
"all",
"functions",
"registered",
"as",
"callbacks",
"are",
"called",
"with",
"the",
"passed",
"in",
"results",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L185-L193
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function (callback, errback) {
if (isPromise(callback)) {
errback = callback.errback;
callback = callback.callback;
}
this.addCallback(callback);
this.addErrback(errback);
return this;
}
|
javascript
|
function (callback, errback) {
if (isPromise(callback)) {
errback = callback.errback;
callback = callback.callback;
}
this.addCallback(callback);
this.addErrback(errback);
return this;
}
|
[
"function",
"(",
"callback",
",",
"errback",
")",
"{",
"if",
"(",
"isPromise",
"(",
"callback",
")",
")",
"{",
"errback",
"=",
"callback",
".",
"errback",
";",
"callback",
"=",
"callback",
".",
"callback",
";",
"}",
"this",
".",
"addCallback",
"(",
"callback",
")",
";",
"this",
".",
"addErrback",
"(",
"errback",
")",
";",
"return",
"this",
";",
"}"
] |
Call to specify action to take after promise completes or errors
@param {Function} [callback=null] function to call after the promise completes successfully
@param {Function} [errback=null] function to call if the promise errors
@return {comb.Promise} this promise for chaining
|
[
"Call",
"to",
"specify",
"action",
"to",
"take",
"after",
"promise",
"completes",
"or",
"errors"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L243-L252
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function (callback, errback) {
var promise = new Promise(),
self = this;
function _errback(e) {
if (isFunction(errback)) {
try {
var res = spreadArgs(errback, [e]);
isPromiseLike(res) ? res.then(promise.callback, promise.errback) : promise.callback(res);
} catch (e) {
promise.errback(e);
}
} else {
promise.errback(e);
}
}
function _callback() {
try {
var res = isFunction(callback) ? spreadArgs(callback, arguments) : callback;
if (isPromiseLike(res)) {
res.then(promise.callback, _errback);
} else {
promise.callback(res);
promise = null;
}
callback = res = null;
} catch (e) {
_errback(e);
}
}
self.addCallback(_callback);
self.addErrback(_errback);
return promise.promise();
}
|
javascript
|
function (callback, errback) {
var promise = new Promise(),
self = this;
function _errback(e) {
if (isFunction(errback)) {
try {
var res = spreadArgs(errback, [e]);
isPromiseLike(res) ? res.then(promise.callback, promise.errback) : promise.callback(res);
} catch (e) {
promise.errback(e);
}
} else {
promise.errback(e);
}
}
function _callback() {
try {
var res = isFunction(callback) ? spreadArgs(callback, arguments) : callback;
if (isPromiseLike(res)) {
res.then(promise.callback, _errback);
} else {
promise.callback(res);
promise = null;
}
callback = res = null;
} catch (e) {
_errback(e);
}
}
self.addCallback(_callback);
self.addErrback(_errback);
return promise.promise();
}
|
[
"function",
"(",
"callback",
",",
"errback",
")",
"{",
"var",
"promise",
"=",
"new",
"Promise",
"(",
")",
",",
"self",
"=",
"this",
";",
"function",
"_errback",
"(",
"e",
")",
"{",
"if",
"(",
"isFunction",
"(",
"errback",
")",
")",
"{",
"try",
"{",
"var",
"res",
"=",
"spreadArgs",
"(",
"errback",
",",
"[",
"e",
"]",
")",
";",
"isPromiseLike",
"(",
"res",
")",
"?",
"res",
".",
"then",
"(",
"promise",
".",
"callback",
",",
"promise",
".",
"errback",
")",
":",
"promise",
".",
"callback",
"(",
"res",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"promise",
".",
"errback",
"(",
"e",
")",
";",
"}",
"}",
"else",
"{",
"promise",
".",
"errback",
"(",
"e",
")",
";",
"}",
"}",
"function",
"_callback",
"(",
")",
"{",
"try",
"{",
"var",
"res",
"=",
"isFunction",
"(",
"callback",
")",
"?",
"spreadArgs",
"(",
"callback",
",",
"arguments",
")",
":",
"callback",
";",
"if",
"(",
"isPromiseLike",
"(",
"res",
")",
")",
"{",
"res",
".",
"then",
"(",
"promise",
".",
"callback",
",",
"_errback",
")",
";",
"}",
"else",
"{",
"promise",
".",
"callback",
"(",
"res",
")",
";",
"promise",
"=",
"null",
";",
"}",
"callback",
"=",
"res",
"=",
"null",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"_errback",
"(",
"e",
")",
";",
"}",
"}",
"self",
".",
"addCallback",
"(",
"_callback",
")",
";",
"self",
".",
"addErrback",
"(",
"_errback",
")",
";",
"return",
"promise",
".",
"promise",
"(",
")",
";",
"}"
] |
Call to chaining of promises
```
new Promise()
.callback("hello")
.chain(function(previousPromiseResults){
return previousPromiseResults + " world";
}, errorHandler)
.chain(function(previousPromiseResults){
return when(dbCall());
}).classic(function(err, results){
//all promises are done
});
```
You can also use static values
```
new Promise().callback()
.chain("hello")
.chain(function(prev){
return prev + " world!"
}).then(function(str){
console.log(str); //"hello world!"
});
```
If you do not provide an `errback` for each chain then it will be propogated to the final promise
```
new Promise()
.chain(function(){
return new comb.Promise().errback(new Error("error"));
})
.chain(function(){
return prev + " world!"
})
.classic(function(err, str){
console.log(err.message); //"error"
});
```
@param callback method to call this one completes. If you return a promise the execution will delay until the returned promise has resolved.
@param [errback=null] method to call if this promise errors. If errback is not specified then the returned promises
errback method will be used.
@return {comb.Promise} A new that wraps the promise for chaining
|
[
"Call",
"to",
"chaining",
"of",
"promises"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L334-L369
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function (callback) {
var promise = new Promise();
this.addCallback(function () {
try {
when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise);
} catch (e) {
promise.errback(e);
}
});
this.addErrback(function () {
try {
when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise);
} catch (e) {
promise.errback(e);
}
});
return promise.promise();
}
|
javascript
|
function (callback) {
var promise = new Promise();
this.addCallback(function () {
try {
when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise);
} catch (e) {
promise.errback(e);
}
});
this.addErrback(function () {
try {
when(isFunction(callback) ? callback.apply(this, arguments) : callback).then(promise);
} catch (e) {
promise.errback(e);
}
});
return promise.promise();
}
|
[
"function",
"(",
"callback",
")",
"{",
"var",
"promise",
"=",
"new",
"Promise",
"(",
")",
";",
"this",
".",
"addCallback",
"(",
"function",
"(",
")",
"{",
"try",
"{",
"when",
"(",
"isFunction",
"(",
"callback",
")",
"?",
"callback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
":",
"callback",
")",
".",
"then",
"(",
"promise",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"promise",
".",
"errback",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"addErrback",
"(",
"function",
"(",
")",
"{",
"try",
"{",
"when",
"(",
"isFunction",
"(",
"callback",
")",
"?",
"callback",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
":",
"callback",
")",
".",
"then",
"(",
"promise",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"promise",
".",
"errback",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"return",
"promise",
".",
"promise",
"(",
")",
";",
"}"
] |
Applies the same function that returns a promise to both the callback and errback.
@param {Function} callback function to call. This function must return a Promise
@return {comb.Promise} a promise to continue chaining or to resolve with.
|
[
"Applies",
"the",
"same",
"function",
"that",
"returns",
"a",
"promise",
"to",
"both",
"the",
"callback",
"and",
"errback",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L379-L397
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function () {
var ret = {
promise: function () {
return ret;
}
};
var self = this;
ret["chain"] = function () {
return spreadArgs(self["chain"], arguments, self);
};
ret["chainBoth"] = function () {
return spreadArgs(self["chainBoth"], arguments, self);
};
ret["addCallback"] = function () {
spreadArgs(self["addCallback"], arguments, self);
return ret;
};
ret["addErrback"] = function () {
spreadArgs(self["addErrback"], arguments, self);
return ret;
};
ret["then"] = function () {
spreadArgs(self["then"], arguments, self);
return ret;
};
ret["both"] = function () {
spreadArgs(self["both"], arguments, self);
return ret;
};
ret["classic"] = function () {
spreadArgs(self["classic"], arguments, self);
return ret;
};
return ret;
}
|
javascript
|
function () {
var ret = {
promise: function () {
return ret;
}
};
var self = this;
ret["chain"] = function () {
return spreadArgs(self["chain"], arguments, self);
};
ret["chainBoth"] = function () {
return spreadArgs(self["chainBoth"], arguments, self);
};
ret["addCallback"] = function () {
spreadArgs(self["addCallback"], arguments, self);
return ret;
};
ret["addErrback"] = function () {
spreadArgs(self["addErrback"], arguments, self);
return ret;
};
ret["then"] = function () {
spreadArgs(self["then"], arguments, self);
return ret;
};
ret["both"] = function () {
spreadArgs(self["both"], arguments, self);
return ret;
};
ret["classic"] = function () {
spreadArgs(self["classic"], arguments, self);
return ret;
};
return ret;
}
|
[
"function",
"(",
")",
"{",
"var",
"ret",
"=",
"{",
"promise",
":",
"function",
"(",
")",
"{",
"return",
"ret",
";",
"}",
"}",
";",
"var",
"self",
"=",
"this",
";",
"ret",
"[",
"\"chain\"",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"spreadArgs",
"(",
"self",
"[",
"\"chain\"",
"]",
",",
"arguments",
",",
"self",
")",
";",
"}",
";",
"ret",
"[",
"\"chainBoth\"",
"]",
"=",
"function",
"(",
")",
"{",
"return",
"spreadArgs",
"(",
"self",
"[",
"\"chainBoth\"",
"]",
",",
"arguments",
",",
"self",
")",
";",
"}",
";",
"ret",
"[",
"\"addCallback\"",
"]",
"=",
"function",
"(",
")",
"{",
"spreadArgs",
"(",
"self",
"[",
"\"addCallback\"",
"]",
",",
"arguments",
",",
"self",
")",
";",
"return",
"ret",
";",
"}",
";",
"ret",
"[",
"\"addErrback\"",
"]",
"=",
"function",
"(",
")",
"{",
"spreadArgs",
"(",
"self",
"[",
"\"addErrback\"",
"]",
",",
"arguments",
",",
"self",
")",
";",
"return",
"ret",
";",
"}",
";",
"ret",
"[",
"\"then\"",
"]",
"=",
"function",
"(",
")",
"{",
"spreadArgs",
"(",
"self",
"[",
"\"then\"",
"]",
",",
"arguments",
",",
"self",
")",
";",
"return",
"ret",
";",
"}",
";",
"ret",
"[",
"\"both\"",
"]",
"=",
"function",
"(",
")",
"{",
"spreadArgs",
"(",
"self",
"[",
"\"both\"",
"]",
",",
"arguments",
",",
"self",
")",
";",
"return",
"ret",
";",
"}",
";",
"ret",
"[",
"\"classic\"",
"]",
"=",
"function",
"(",
")",
"{",
"spreadArgs",
"(",
"self",
"[",
"\"classic\"",
"]",
",",
"arguments",
",",
"self",
")",
";",
"return",
"ret",
";",
"}",
";",
"return",
"ret",
";",
"}"
] |
Creates an object to that contains methods to listen to resolution but not the "callback" or "errback" methods.
@example
var asyncMethod = function(){
var ret = new comb.Promise();
process.nextTick(ret.callback.bind(ret, "hello"));
return ret.promise();
}
asyncMethod().callback() //throws error
@return {Object} an object containing "chain", "chainBoth", "promise", "addCallback", "addErrback", "then", "both".
|
[
"Creates",
"an",
"object",
"to",
"that",
"contains",
"methods",
"to",
"listen",
"to",
"resolution",
"but",
"not",
"the",
"callback",
"or",
"errback",
"methods",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L414-L448
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function (defs, normalizeResults) {
this.__errors = [];
this.__results = [];
this.normalizeResults = base.isBoolean(normalizeResults) ? normalizeResults : false;
this._super(arguments);
if (defs && defs.length) {
this.__defLength = defs.length;
forEach(defs, this.__addPromise, this);
} else {
this.__resolve();
}
}
|
javascript
|
function (defs, normalizeResults) {
this.__errors = [];
this.__results = [];
this.normalizeResults = base.isBoolean(normalizeResults) ? normalizeResults : false;
this._super(arguments);
if (defs && defs.length) {
this.__defLength = defs.length;
forEach(defs, this.__addPromise, this);
} else {
this.__resolve();
}
}
|
[
"function",
"(",
"defs",
",",
"normalizeResults",
")",
"{",
"this",
".",
"__errors",
"=",
"[",
"]",
";",
"this",
".",
"__results",
"=",
"[",
"]",
";",
"this",
".",
"normalizeResults",
"=",
"base",
".",
"isBoolean",
"(",
"normalizeResults",
")",
"?",
"normalizeResults",
":",
"false",
";",
"this",
".",
"_super",
"(",
"arguments",
")",
";",
"if",
"(",
"defs",
"&&",
"defs",
".",
"length",
")",
"{",
"this",
".",
"__defLength",
"=",
"defs",
".",
"length",
";",
"forEach",
"(",
"defs",
",",
"this",
".",
"__addPromise",
",",
"this",
")",
";",
"}",
"else",
"{",
"this",
".",
"__resolve",
"(",
")",
";",
"}",
"}"
] |
PromiseList object used for handling a list of Promises
@example
var myFunc = function(){
var promise = new Promise();
//callback the promise after 10 Secs
setTimeout(hitch(promise, "callback"), 10000);
return promise.promise();
}
var myFunc2 = function(){
var promises =[];
for(var i = 0; i < 10; i++){
promises.push(myFunc);
}
//create a new promise list with all 10 promises
return new PromiseList(promises).promise();
}
myFunc.then(function(success){}, function(error){})
//chain promise operations
myFunc.chain(myfunc).then(function(success){}, function(error){})
myFunc2.then(function(success){}, function(error){})
//chain promise operations
myFunc2.chain(myfunc).then(function(success){}, function(error){})
@param {comb.Promise[]} [defs=[]] the list of promises
@constructs
@augments comb.Promise
@memberOf comb
|
[
"PromiseList",
"object",
"used",
"for",
"handling",
"a",
"list",
"of",
"Promises"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L508-L519
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function (promise, i) {
var self = this;
promise.then(
function () {
var args = argsToArray(arguments);
args.unshift(i);
spreadArgs(self.callback, args, self);
promise = i = self = null;
},
function () {
var args = argsToArray(arguments);
args.unshift(i);
spreadArgs(self.errback, args, self);
promise = i = self = null;
});
}
|
javascript
|
function (promise, i) {
var self = this;
promise.then(
function () {
var args = argsToArray(arguments);
args.unshift(i);
spreadArgs(self.callback, args, self);
promise = i = self = null;
},
function () {
var args = argsToArray(arguments);
args.unshift(i);
spreadArgs(self.errback, args, self);
promise = i = self = null;
});
}
|
[
"function",
"(",
"promise",
",",
"i",
")",
"{",
"var",
"self",
"=",
"this",
";",
"promise",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"argsToArray",
"(",
"arguments",
")",
";",
"args",
".",
"unshift",
"(",
"i",
")",
";",
"spreadArgs",
"(",
"self",
".",
"callback",
",",
"args",
",",
"self",
")",
";",
"promise",
"=",
"i",
"=",
"self",
"=",
"null",
";",
"}",
",",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"argsToArray",
"(",
"arguments",
")",
";",
"args",
".",
"unshift",
"(",
"i",
")",
";",
"spreadArgs",
"(",
"self",
".",
"errback",
",",
"args",
",",
"self",
")",
";",
"promise",
"=",
"i",
"=",
"self",
"=",
"null",
";",
"}",
")",
";",
"}"
] |
Add a promise to our chain
@private
@param promise the promise to add to our chain
@param i the index of the promise in our chain
|
[
"Add",
"a",
"promise",
"to",
"our",
"chain"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L527-L542
|
train
|
|
C2FO/comb
|
lib/promise.js
|
function () {
if (!this.__fired) {
this.__fired = true;
var self = this;
nextTick(function () {
var cbs = self.__errors.length ? self.__errorCbs : self.__cbs,
len = cbs.length, i,
results = self.__errors.length ? self.__errors : self.__results;
for (i = 0; i < len; i++) {
spreadArgs(cbs[i], [results]);
}
});
}
}
|
javascript
|
function () {
if (!this.__fired) {
this.__fired = true;
var self = this;
nextTick(function () {
var cbs = self.__errors.length ? self.__errorCbs : self.__cbs,
len = cbs.length, i,
results = self.__errors.length ? self.__errors : self.__results;
for (i = 0; i < len; i++) {
spreadArgs(cbs[i], [results]);
}
});
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"__fired",
")",
"{",
"this",
".",
"__fired",
"=",
"true",
";",
"var",
"self",
"=",
"this",
";",
"nextTick",
"(",
"function",
"(",
")",
"{",
"var",
"cbs",
"=",
"self",
".",
"__errors",
".",
"length",
"?",
"self",
".",
"__errorCbs",
":",
"self",
".",
"__cbs",
",",
"len",
"=",
"cbs",
".",
"length",
",",
"i",
",",
"results",
"=",
"self",
".",
"__errors",
".",
"length",
"?",
"self",
".",
"__errors",
":",
"self",
".",
"__results",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"spreadArgs",
"(",
"cbs",
"[",
"i",
"]",
",",
"[",
"results",
"]",
")",
";",
"}",
"}",
")",
";",
"}",
"}"
] |
Resolves the promise
@private
|
[
"Resolves",
"the",
"promise"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L548-L561
|
train
|
|
C2FO/comb
|
lib/promise.js
|
callNext
|
function callNext(list, results, propogate) {
var ret = new Promise().callback();
forEach(list, function (listItem) {
ret = ret.chain(propogate ? listItem : bindIgnore(null, listItem));
if (!propogate) {
ret.addCallback(function (res) {
results.push(res);
res = null;
});
}
});
return propogate ? ret.promise() : ret.chain(results);
}
|
javascript
|
function callNext(list, results, propogate) {
var ret = new Promise().callback();
forEach(list, function (listItem) {
ret = ret.chain(propogate ? listItem : bindIgnore(null, listItem));
if (!propogate) {
ret.addCallback(function (res) {
results.push(res);
res = null;
});
}
});
return propogate ? ret.promise() : ret.chain(results);
}
|
[
"function",
"callNext",
"(",
"list",
",",
"results",
",",
"propogate",
")",
"{",
"var",
"ret",
"=",
"new",
"Promise",
"(",
")",
".",
"callback",
"(",
")",
";",
"forEach",
"(",
"list",
",",
"function",
"(",
"listItem",
")",
"{",
"ret",
"=",
"ret",
".",
"chain",
"(",
"propogate",
"?",
"listItem",
":",
"bindIgnore",
"(",
"null",
",",
"listItem",
")",
")",
";",
"if",
"(",
"!",
"propogate",
")",
"{",
"ret",
".",
"addCallback",
"(",
"function",
"(",
"res",
")",
"{",
"results",
".",
"push",
"(",
"res",
")",
";",
"res",
"=",
"null",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"propogate",
"?",
"ret",
".",
"promise",
"(",
")",
":",
"ret",
".",
"chain",
"(",
"results",
")",
";",
"}"
] |
Creates the promise chain
@ignore
@private
|
[
"Creates",
"the",
"promise",
"chain"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L643-L655
|
train
|
C2FO/comb
|
lib/promise.js
|
when
|
function when(args, cb, eb) {
var p;
args = argsToArray(arguments);
eb = base.isFunction(args[args.length - 1]) ? args.pop() : null;
cb = base.isFunction(args[args.length - 1]) ? args.pop() : null;
if (eb && !cb) {
cb = eb;
eb = null;
}
if (!args.length) {
p = new Promise().callback(args);
} else if (args.length === 1) {
args = args.pop();
if (isPromiseLike(args)) {
p = args;
} else if (isArray(args) && array.every(args, isPromiseLike)) {
p = new PromiseList(args, true);
} else {
p = new Promise().callback(args);
}
} else {
p = new PromiseList(args.map(function (a) {
return isPromiseLike(a) ? a : new Promise().callback(a);
}), true);
}
if (cb) {
p.addCallback(cb);
}
if (eb) {
p.addErrback(eb);
}
return p.promise();
}
|
javascript
|
function when(args, cb, eb) {
var p;
args = argsToArray(arguments);
eb = base.isFunction(args[args.length - 1]) ? args.pop() : null;
cb = base.isFunction(args[args.length - 1]) ? args.pop() : null;
if (eb && !cb) {
cb = eb;
eb = null;
}
if (!args.length) {
p = new Promise().callback(args);
} else if (args.length === 1) {
args = args.pop();
if (isPromiseLike(args)) {
p = args;
} else if (isArray(args) && array.every(args, isPromiseLike)) {
p = new PromiseList(args, true);
} else {
p = new Promise().callback(args);
}
} else {
p = new PromiseList(args.map(function (a) {
return isPromiseLike(a) ? a : new Promise().callback(a);
}), true);
}
if (cb) {
p.addCallback(cb);
}
if (eb) {
p.addErrback(eb);
}
return p.promise();
}
|
[
"function",
"when",
"(",
"args",
",",
"cb",
",",
"eb",
")",
"{",
"var",
"p",
";",
"args",
"=",
"argsToArray",
"(",
"arguments",
")",
";",
"eb",
"=",
"base",
".",
"isFunction",
"(",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
")",
"?",
"args",
".",
"pop",
"(",
")",
":",
"null",
";",
"cb",
"=",
"base",
".",
"isFunction",
"(",
"args",
"[",
"args",
".",
"length",
"-",
"1",
"]",
")",
"?",
"args",
".",
"pop",
"(",
")",
":",
"null",
";",
"if",
"(",
"eb",
"&&",
"!",
"cb",
")",
"{",
"cb",
"=",
"eb",
";",
"eb",
"=",
"null",
";",
"}",
"if",
"(",
"!",
"args",
".",
"length",
")",
"{",
"p",
"=",
"new",
"Promise",
"(",
")",
".",
"callback",
"(",
"args",
")",
";",
"}",
"else",
"if",
"(",
"args",
".",
"length",
"===",
"1",
")",
"{",
"args",
"=",
"args",
".",
"pop",
"(",
")",
";",
"if",
"(",
"isPromiseLike",
"(",
"args",
")",
")",
"{",
"p",
"=",
"args",
";",
"}",
"else",
"if",
"(",
"isArray",
"(",
"args",
")",
"&&",
"array",
".",
"every",
"(",
"args",
",",
"isPromiseLike",
")",
")",
"{",
"p",
"=",
"new",
"PromiseList",
"(",
"args",
",",
"true",
")",
";",
"}",
"else",
"{",
"p",
"=",
"new",
"Promise",
"(",
")",
".",
"callback",
"(",
"args",
")",
";",
"}",
"}",
"else",
"{",
"p",
"=",
"new",
"PromiseList",
"(",
"args",
".",
"map",
"(",
"function",
"(",
"a",
")",
"{",
"return",
"isPromiseLike",
"(",
"a",
")",
"?",
"a",
":",
"new",
"Promise",
"(",
")",
".",
"callback",
"(",
"a",
")",
";",
"}",
")",
",",
"true",
")",
";",
"}",
"if",
"(",
"cb",
")",
"{",
"p",
".",
"addCallback",
"(",
"cb",
")",
";",
"}",
"if",
"(",
"eb",
")",
"{",
"p",
".",
"addErrback",
"(",
"eb",
")",
";",
"}",
"return",
"p",
".",
"promise",
"(",
")",
";",
"}"
] |
Waits for promise and non promise values to resolve and fires callback or errback appropriately. If you pass in an array of promises
then it will wait for all promises in the list to resolve.
@example
var a = "hello";
var b = new comb.Promise().callback(world);
comb.when(a, b) => called back with ["hello", "world"];
@param {Anything...} args variable number of arguments to wait for.
@param {Function} cb the callback function
@param {Function} eb the errback function
@returns {comb.Promise} a promise that is fired when all values have resolved
@static
@memberOf comb
|
[
"Waits",
"for",
"promise",
"and",
"non",
"promise",
"values",
"to",
"resolve",
"and",
"fires",
"callback",
"or",
"errback",
"appropriately",
".",
"If",
"you",
"pass",
"in",
"an",
"array",
"of",
"promises",
"then",
"it",
"will",
"wait",
"for",
"all",
"promises",
"in",
"the",
"list",
"to",
"resolve",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L688-L721
|
train
|
C2FO/comb
|
lib/promise.js
|
serial
|
function serial(list, callback, errback) {
if (base.isArray(list)) {
return callNext(list, [], false);
} else {
throw new Error("When calling comb.serial the first argument must be an array");
}
}
|
javascript
|
function serial(list, callback, errback) {
if (base.isArray(list)) {
return callNext(list, [], false);
} else {
throw new Error("When calling comb.serial the first argument must be an array");
}
}
|
[
"function",
"serial",
"(",
"list",
",",
"callback",
",",
"errback",
")",
"{",
"if",
"(",
"base",
".",
"isArray",
"(",
"list",
")",
")",
"{",
"return",
"callNext",
"(",
"list",
",",
"[",
"]",
",",
"false",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"When calling comb.serial the first argument must be an array\"",
")",
";",
"}",
"}"
] |
Executes a list of items in a serial manner. If the list contains promises then each promise
will be executed in a serial manner, if the list contains non async items then the next item in the list
is called.
@example
var asyncAction = function(item, timeout){
var ret = new comb.Promise();
setTimeout(comb.hitchIgnore(ret, "callback", item), timeout);
return ret.promise();
};
comb.serial([
comb.partial(asyncAction, 1, 1000),
comb.partial(asyncAction, 2, 900),
comb.partial(asyncAction, 3, 800),
comb.partial(asyncAction, 4, 700),
comb.partial(asyncAction, 5, 600),
comb.partial(asyncAction, 6, 500)
]).then(function(results){
console.log(results); // [1,2,3,4,5,6];
});
@param list
@param callback
@param errback
@static
@memberOf comb
|
[
"Executes",
"a",
"list",
"of",
"items",
"in",
"a",
"serial",
"manner",
".",
"If",
"the",
"list",
"contains",
"promises",
"then",
"each",
"promise",
"will",
"be",
"executed",
"in",
"a",
"serial",
"manner",
"if",
"the",
"list",
"contains",
"non",
"async",
"items",
"then",
"the",
"next",
"item",
"in",
"the",
"list",
"is",
"called",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L788-L794
|
train
|
C2FO/comb
|
lib/promise.js
|
wait
|
function wait(args, fn) {
var resolved = false;
args = argsToArray(arguments);
fn = args.pop();
var p = when(args);
return function waiter() {
if (!resolved) {
var args = arguments;
return p.chain(function () {
resolved = true;
p = null;
return fn.apply(this, args);
}.bind(this));
} else {
return when(fn.apply(this, arguments));
}
};
}
|
javascript
|
function wait(args, fn) {
var resolved = false;
args = argsToArray(arguments);
fn = args.pop();
var p = when(args);
return function waiter() {
if (!resolved) {
var args = arguments;
return p.chain(function () {
resolved = true;
p = null;
return fn.apply(this, args);
}.bind(this));
} else {
return when(fn.apply(this, arguments));
}
};
}
|
[
"function",
"wait",
"(",
"args",
",",
"fn",
")",
"{",
"var",
"resolved",
"=",
"false",
";",
"args",
"=",
"argsToArray",
"(",
"arguments",
")",
";",
"fn",
"=",
"args",
".",
"pop",
"(",
")",
";",
"var",
"p",
"=",
"when",
"(",
"args",
")",
";",
"return",
"function",
"waiter",
"(",
")",
"{",
"if",
"(",
"!",
"resolved",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"return",
"p",
".",
"chain",
"(",
"function",
"(",
")",
"{",
"resolved",
"=",
"true",
";",
"p",
"=",
"null",
";",
"return",
"fn",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}",
"else",
"{",
"return",
"when",
"(",
"fn",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
")",
";",
"}",
"}",
";",
"}"
] |
Ensures that a promise is resolved before a the function can be run.
For example suppose you have to ensure that you are connected to a database before you execute a function.
```
var findUser = comb.wait(connect(), function findUser(id){
//this wont execute until we are connected
return User.findById(id);
});
comb.when(findUser(1), findUser(2)).then(function(users){
var user1 = users[0], user2 = users[1];
});
```
@param args variable number of arguments to wait on. See {@link comb.when}.
@param {Function} fn function that will wait.
@return {Function} a function that will wait on the args to resolve.
@memberOf comb
@static
|
[
"Ensures",
"that",
"a",
"promise",
"is",
"resolved",
"before",
"a",
"the",
"function",
"can",
"be",
"run",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L862-L879
|
train
|
C2FO/comb
|
lib/promise.js
|
promisfyStream
|
function promisfyStream(stream) {
var ret = new Promise(), called;
function errorHandler() {
if (!called) {
called = true;
spreadArgs(ret.errback, arguments, ret);
stream.removeListener("error", endHandler);
stream.removeListener("end", endHandler);
stream = ret = null;
}
}
function endHandler() {
if (!called) {
called = true;
spreadArgs(ret.callback, arguments, ret);
stream.removeListener("error", endHandler);
stream.removeListener("end", endHandler);
stream = ret = null;
}
}
stream.on("error", errorHandler).on("end", endHandler);
return ret.promise();
}
|
javascript
|
function promisfyStream(stream) {
var ret = new Promise(), called;
function errorHandler() {
if (!called) {
called = true;
spreadArgs(ret.errback, arguments, ret);
stream.removeListener("error", endHandler);
stream.removeListener("end", endHandler);
stream = ret = null;
}
}
function endHandler() {
if (!called) {
called = true;
spreadArgs(ret.callback, arguments, ret);
stream.removeListener("error", endHandler);
stream.removeListener("end", endHandler);
stream = ret = null;
}
}
stream.on("error", errorHandler).on("end", endHandler);
return ret.promise();
}
|
[
"function",
"promisfyStream",
"(",
"stream",
")",
"{",
"var",
"ret",
"=",
"new",
"Promise",
"(",
")",
",",
"called",
";",
"function",
"errorHandler",
"(",
")",
"{",
"if",
"(",
"!",
"called",
")",
"{",
"called",
"=",
"true",
";",
"spreadArgs",
"(",
"ret",
".",
"errback",
",",
"arguments",
",",
"ret",
")",
";",
"stream",
".",
"removeListener",
"(",
"\"error\"",
",",
"endHandler",
")",
";",
"stream",
".",
"removeListener",
"(",
"\"end\"",
",",
"endHandler",
")",
";",
"stream",
"=",
"ret",
"=",
"null",
";",
"}",
"}",
"function",
"endHandler",
"(",
")",
"{",
"if",
"(",
"!",
"called",
")",
"{",
"called",
"=",
"true",
";",
"spreadArgs",
"(",
"ret",
".",
"callback",
",",
"arguments",
",",
"ret",
")",
";",
"stream",
".",
"removeListener",
"(",
"\"error\"",
",",
"endHandler",
")",
";",
"stream",
".",
"removeListener",
"(",
"\"end\"",
",",
"endHandler",
")",
";",
"stream",
"=",
"ret",
"=",
"null",
";",
"}",
"}",
"stream",
".",
"on",
"(",
"\"error\"",
",",
"errorHandler",
")",
".",
"on",
"(",
"\"end\"",
",",
"endHandler",
")",
";",
"return",
"ret",
".",
"promise",
"(",
")",
";",
"}"
] |
Wraps a stream in a promise waiting for either the `"end"` or `"error"` event to be triggered.
```
comb.promisfyStream(fs.createdReadStream("my.file")).chain(function(){
console.log("done reading!");
});
```
@param stream stream to wrap
@return {comb.Promise} a Promise is resolved if `"end"` is triggered before `"error"` or rejected if `"error"` is triggered.
@memberOf comb
@static
|
[
"Wraps",
"a",
"stream",
"in",
"a",
"promise",
"waiting",
"for",
"either",
"the",
"end",
"or",
"error",
"event",
"to",
"be",
"triggered",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/promise.js#L897-L922
|
train
|
C2FO/comb
|
lib/base/array.js
|
difference
|
function difference(arr1, arr2) {
var ret = arr1, args = flatten(argsToArray(arguments, 1));
if (isArray(arr1)) {
ret = filter(arr1, function (a) {
return indexOf(args, a) === -1;
});
}
return ret;
}
|
javascript
|
function difference(arr1, arr2) {
var ret = arr1, args = flatten(argsToArray(arguments, 1));
if (isArray(arr1)) {
ret = filter(arr1, function (a) {
return indexOf(args, a) === -1;
});
}
return ret;
}
|
[
"function",
"difference",
"(",
"arr1",
",",
"arr2",
")",
"{",
"var",
"ret",
"=",
"arr1",
",",
"args",
"=",
"flatten",
"(",
"argsToArray",
"(",
"arguments",
",",
"1",
")",
")",
";",
"if",
"(",
"isArray",
"(",
"arr1",
")",
")",
"{",
"ret",
"=",
"filter",
"(",
"arr1",
",",
"function",
"(",
"a",
")",
"{",
"return",
"indexOf",
"(",
"args",
",",
"a",
")",
"===",
"-",
"1",
";",
"}",
")",
";",
"}",
"return",
"ret",
";",
"}"
] |
Finds the difference of the two arrays.
@example
comb.array.difference([1,2,3], [2,3]); //[1]
comb.array.difference(["a","b",3], [3]); //["a","b"]
@param {Array} arr1 the array we are subtracting from
@param {Array} arr2 the array we are subtracting from arr1
@return {*} the difference of the arrays.
@static
@memberOf comb.array
|
[
"Finds",
"the",
"difference",
"of",
"the",
"two",
"arrays",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/array.js#L468-L476
|
train
|
C2FO/comb
|
lib/base/array.js
|
removeDuplicates
|
function removeDuplicates(arr) {
if (isArray(arr)) {
return reduce(arr, function (a, b) {
if (indexOf(a, b) === -1) {
return a.concat(b);
} else {
return a;
}
}, []);
}
}
|
javascript
|
function removeDuplicates(arr) {
if (isArray(arr)) {
return reduce(arr, function (a, b) {
if (indexOf(a, b) === -1) {
return a.concat(b);
} else {
return a;
}
}, []);
}
}
|
[
"function",
"removeDuplicates",
"(",
"arr",
")",
"{",
"if",
"(",
"isArray",
"(",
"arr",
")",
")",
"{",
"return",
"reduce",
"(",
"arr",
",",
"function",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"indexOf",
"(",
"a",
",",
"b",
")",
"===",
"-",
"1",
")",
"{",
"return",
"a",
".",
"concat",
"(",
"b",
")",
";",
"}",
"else",
"{",
"return",
"a",
";",
"}",
"}",
",",
"[",
"]",
")",
";",
"}",
"}"
] |
Removes duplicates from an array
@example
comb.array.removeDuplicates([1,1,1]) => [1]
comb.array.removeDuplicates([1,2,3,2]) => [1,2,3]
@param {Aray} array the array of elements to remove duplicates from
@static
@memberOf comb.array
|
[
"Removes",
"duplicates",
"from",
"an",
"array"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/array.js#L492-L502
|
train
|
C2FO/comb
|
lib/base/array.js
|
partition
|
function partition(array, partitionSize) {
partitionSize = partitionSize || array.length;
var ret = [];
for (var i = 0, l = array.length; i < l; i += partitionSize) {
ret.push(array.slice(i, i + partitionSize));
}
return ret;
}
|
javascript
|
function partition(array, partitionSize) {
partitionSize = partitionSize || array.length;
var ret = [];
for (var i = 0, l = array.length; i < l; i += partitionSize) {
ret.push(array.slice(i, i + partitionSize));
}
return ret;
}
|
[
"function",
"partition",
"(",
"array",
",",
"partitionSize",
")",
"{",
"partitionSize",
"=",
"partitionSize",
"||",
"array",
".",
"length",
";",
"var",
"ret",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"array",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"+=",
"partitionSize",
")",
"{",
"ret",
".",
"push",
"(",
"array",
".",
"slice",
"(",
"i",
",",
"i",
"+",
"partitionSize",
")",
")",
";",
"}",
"return",
"ret",
";",
"}"
] |
Paritition an array.
```
var arr = [1,2,3,4,5];
comb.array.partition(arr, 1); //[[1], [2], [3], [4], [5]]
comb.array.partition(arr, 2); //[[1,2], [3,4], [5]]
comb.array.partition(arr, 3); //[[1,2,3], [4,5]]
comb.array.partition(arr); //[[1, 2, 3, 4, 5]]
comb.array.partition(arr, 0); //[[1, 2, 3, 4, 5]]
```
@param array
@param partitionSize
@returns {Array}
@static
@memberOf comb.array
|
[
"Paritition",
"an",
"array",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/array.js#L1051-L1058
|
train
|
C2FO/comb
|
lib/collections/Tree.js
|
function (node, order, callback) {
if (node) {
order = order || Tree.PRE_ORDER;
if (order === Tree.PRE_ORDER) {
callback(node.data);
this.traverse(node.left, order, callback);
this.traverse(node.right, order, callback);
} else if (order === Tree.IN_ORDER) {
this.traverse(node.left, order, callback);
callback(node.data);
this.traverse(node.right, order, callback);
} else if (order === Tree.POST_ORDER) {
this.traverse(node.left, order, callback);
this.traverse(node.right, order, callback);
callback(node.data);
} else if (order === Tree.REVERSE_ORDER) {
this.traverseWithCondition(node.right, order, callback);
callback(node.data);
this.traverseWithCondition(node.left, order, callback);
}
}
}
|
javascript
|
function (node, order, callback) {
if (node) {
order = order || Tree.PRE_ORDER;
if (order === Tree.PRE_ORDER) {
callback(node.data);
this.traverse(node.left, order, callback);
this.traverse(node.right, order, callback);
} else if (order === Tree.IN_ORDER) {
this.traverse(node.left, order, callback);
callback(node.data);
this.traverse(node.right, order, callback);
} else if (order === Tree.POST_ORDER) {
this.traverse(node.left, order, callback);
this.traverse(node.right, order, callback);
callback(node.data);
} else if (order === Tree.REVERSE_ORDER) {
this.traverseWithCondition(node.right, order, callback);
callback(node.data);
this.traverseWithCondition(node.left, order, callback);
}
}
}
|
[
"function",
"(",
"node",
",",
"order",
",",
"callback",
")",
"{",
"if",
"(",
"node",
")",
"{",
"order",
"=",
"order",
"||",
"Tree",
".",
"PRE_ORDER",
";",
"if",
"(",
"order",
"===",
"Tree",
".",
"PRE_ORDER",
")",
"{",
"callback",
"(",
"node",
".",
"data",
")",
";",
"this",
".",
"traverse",
"(",
"node",
".",
"left",
",",
"order",
",",
"callback",
")",
";",
"this",
".",
"traverse",
"(",
"node",
".",
"right",
",",
"order",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"order",
"===",
"Tree",
".",
"IN_ORDER",
")",
"{",
"this",
".",
"traverse",
"(",
"node",
".",
"left",
",",
"order",
",",
"callback",
")",
";",
"callback",
"(",
"node",
".",
"data",
")",
";",
"this",
".",
"traverse",
"(",
"node",
".",
"right",
",",
"order",
",",
"callback",
")",
";",
"}",
"else",
"if",
"(",
"order",
"===",
"Tree",
".",
"POST_ORDER",
")",
"{",
"this",
".",
"traverse",
"(",
"node",
".",
"left",
",",
"order",
",",
"callback",
")",
";",
"this",
".",
"traverse",
"(",
"node",
".",
"right",
",",
"order",
",",
"callback",
")",
";",
"callback",
"(",
"node",
".",
"data",
")",
";",
"}",
"else",
"if",
"(",
"order",
"===",
"Tree",
".",
"REVERSE_ORDER",
")",
"{",
"this",
".",
"traverseWithCondition",
"(",
"node",
".",
"right",
",",
"order",
",",
"callback",
")",
";",
"callback",
"(",
"node",
".",
"data",
")",
";",
"this",
".",
"traverseWithCondition",
"(",
"node",
".",
"left",
",",
"order",
",",
"callback",
")",
";",
"}",
"}",
"}"
] |
Traverse a tree
<p><b>Not typically used directly</b></p>
@param {Object} node the node to start at
@param {Tree.PRE_ORDER|Tree.POST_ORDER|Tree.IN_ORDER|Tree.REVERSE_ORDER} [order=Tree.IN_ORDER] the traversal scheme
@param {Function} callback called for each item
|
[
"Traverse",
"a",
"tree"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Tree.js#L155-L177
|
train
|
|
C2FO/comb
|
lib/logging/index.js
|
function (timerFormat) {
timerFormat = timerFormat || " [Duration: %dms]";
function timerLog(level, start) {
return function (message) {
var args = argsToArray(arguments, 1);
message += timerFormat;
args.push(new Date() - start);
self.log.apply(self, [level, message].concat(args));
return ret;
};
}
var start = new Date(),
self = this,
ret = {
info: timerLog(Level.INFO, start),
debug: timerLog(Level.DEBUG, start),
error: timerLog(Level.ERROR, start),
warn: timerLog(Level.WARN, start),
trace: timerLog(Level.TRACE, start),
fatal: timerLog(Level.FATAL, start),
log: function (level) {
return timerLog(level, start).apply(this, argsToArray(arguments, 1));
},
end: function () {
start = self = null;
}
};
return ret;
}
|
javascript
|
function (timerFormat) {
timerFormat = timerFormat || " [Duration: %dms]";
function timerLog(level, start) {
return function (message) {
var args = argsToArray(arguments, 1);
message += timerFormat;
args.push(new Date() - start);
self.log.apply(self, [level, message].concat(args));
return ret;
};
}
var start = new Date(),
self = this,
ret = {
info: timerLog(Level.INFO, start),
debug: timerLog(Level.DEBUG, start),
error: timerLog(Level.ERROR, start),
warn: timerLog(Level.WARN, start),
trace: timerLog(Level.TRACE, start),
fatal: timerLog(Level.FATAL, start),
log: function (level) {
return timerLog(level, start).apply(this, argsToArray(arguments, 1));
},
end: function () {
start = self = null;
}
};
return ret;
}
|
[
"function",
"(",
"timerFormat",
")",
"{",
"timerFormat",
"=",
"timerFormat",
"||",
"\" [Duration: %dms]\"",
";",
"function",
"timerLog",
"(",
"level",
",",
"start",
")",
"{",
"return",
"function",
"(",
"message",
")",
"{",
"var",
"args",
"=",
"argsToArray",
"(",
"arguments",
",",
"1",
")",
";",
"message",
"+=",
"timerFormat",
";",
"args",
".",
"push",
"(",
"new",
"Date",
"(",
")",
"-",
"start",
")",
";",
"self",
".",
"log",
".",
"apply",
"(",
"self",
",",
"[",
"level",
",",
"message",
"]",
".",
"concat",
"(",
"args",
")",
")",
";",
"return",
"ret",
";",
"}",
";",
"}",
"var",
"start",
"=",
"new",
"Date",
"(",
")",
",",
"self",
"=",
"this",
",",
"ret",
"=",
"{",
"info",
":",
"timerLog",
"(",
"Level",
".",
"INFO",
",",
"start",
")",
",",
"debug",
":",
"timerLog",
"(",
"Level",
".",
"DEBUG",
",",
"start",
")",
",",
"error",
":",
"timerLog",
"(",
"Level",
".",
"ERROR",
",",
"start",
")",
",",
"warn",
":",
"timerLog",
"(",
"Level",
".",
"WARN",
",",
"start",
")",
",",
"trace",
":",
"timerLog",
"(",
"Level",
".",
"TRACE",
",",
"start",
")",
",",
"fatal",
":",
"timerLog",
"(",
"Level",
".",
"FATAL",
",",
"start",
")",
",",
"log",
":",
"function",
"(",
"level",
")",
"{",
"return",
"timerLog",
"(",
"level",
",",
"start",
")",
".",
"apply",
"(",
"this",
",",
"argsToArray",
"(",
"arguments",
",",
"1",
")",
")",
";",
"}",
",",
"end",
":",
"function",
"(",
")",
"{",
"start",
"=",
"self",
"=",
"null",
";",
"}",
"}",
";",
"return",
"ret",
";",
"}"
] |
Create a timer that can be used to log statements with a duration at the send.
```
var timer = LOGGER.timer();
setTimeout(function(){
timer.info("HELLO TIMERS!!!"); //HELLO TIMERS!!! [Duration: 5000ms]
}, 5000);
```
@param timerFormat
@returns {{info: Function, debug: Function, error: Function, warn: Function, trace: Function, fatal: Function, end: Function}}
|
[
"Create",
"a",
"timer",
"that",
"can",
"be",
"used",
"to",
"log",
"statements",
"with",
"a",
"duration",
"at",
"the",
"send",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/index.js#L335-L364
|
train
|
|
C2FO/comb
|
lib/logging/index.js
|
getLogEvent
|
function getLogEvent(level, message, rawMessage) {
return {
hostname: os.hostname(),
pid: process.pid,
gid: hasGetGid ? process.getgid() : null,
processTitle: process.title,
level: level,
levelName: level.name,
message: message,
timeStamp: new Date(),
name: this.fullName,
rawMessage: rawMessage
};
}
|
javascript
|
function getLogEvent(level, message, rawMessage) {
return {
hostname: os.hostname(),
pid: process.pid,
gid: hasGetGid ? process.getgid() : null,
processTitle: process.title,
level: level,
levelName: level.name,
message: message,
timeStamp: new Date(),
name: this.fullName,
rawMessage: rawMessage
};
}
|
[
"function",
"getLogEvent",
"(",
"level",
",",
"message",
",",
"rawMessage",
")",
"{",
"return",
"{",
"hostname",
":",
"os",
".",
"hostname",
"(",
")",
",",
"pid",
":",
"process",
".",
"pid",
",",
"gid",
":",
"hasGetGid",
"?",
"process",
".",
"getgid",
"(",
")",
":",
"null",
",",
"processTitle",
":",
"process",
".",
"title",
",",
"level",
":",
"level",
",",
"levelName",
":",
"level",
".",
"name",
",",
"message",
":",
"message",
",",
"timeStamp",
":",
"new",
"Date",
"(",
")",
",",
"name",
":",
"this",
".",
"fullName",
",",
"rawMessage",
":",
"rawMessage",
"}",
";",
"}"
] |
Creates a log event to be passed to appenders
@param {comb.logging.Level} level the level of the logging event
@param {String} message the message to be logged
@return {Object} the logging event
|
[
"Creates",
"a",
"log",
"event",
"to",
"be",
"passed",
"to",
"appenders"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/index.js#L373-L386
|
train
|
C2FO/comb
|
lib/logging/index.js
|
log
|
function log(level, message) {
var rawMessage = message;
level = Level.toLevel(level);
if (this.hasLevelGt(level)) {
var args = argsToArray(arguments, 1);
if (args.length > 1) {
message = format.apply(null, args);
}
if (Level.TRACE.equals(level)) {
var err = new Error;
err.name = "Trace";
err.message = message || '';
Error.captureStackTrace(err, log);
message = err.stack;
} else if (Level.ERROR.equals(level) && isInstanceOf(message, Error)) {
message = message.stack;
}
var type = level.name.toLowerCase(), appenders = this.__appenders;
var event = this.getLogEvent(level, message, rawMessage);
Object.keys(appenders).forEach(function (i) {
appenders[i].append(event);
});
}
return this;
}
|
javascript
|
function log(level, message) {
var rawMessage = message;
level = Level.toLevel(level);
if (this.hasLevelGt(level)) {
var args = argsToArray(arguments, 1);
if (args.length > 1) {
message = format.apply(null, args);
}
if (Level.TRACE.equals(level)) {
var err = new Error;
err.name = "Trace";
err.message = message || '';
Error.captureStackTrace(err, log);
message = err.stack;
} else if (Level.ERROR.equals(level) && isInstanceOf(message, Error)) {
message = message.stack;
}
var type = level.name.toLowerCase(), appenders = this.__appenders;
var event = this.getLogEvent(level, message, rawMessage);
Object.keys(appenders).forEach(function (i) {
appenders[i].append(event);
});
}
return this;
}
|
[
"function",
"log",
"(",
"level",
",",
"message",
")",
"{",
"var",
"rawMessage",
"=",
"message",
";",
"level",
"=",
"Level",
".",
"toLevel",
"(",
"level",
")",
";",
"if",
"(",
"this",
".",
"hasLevelGt",
"(",
"level",
")",
")",
"{",
"var",
"args",
"=",
"argsToArray",
"(",
"arguments",
",",
"1",
")",
";",
"if",
"(",
"args",
".",
"length",
">",
"1",
")",
"{",
"message",
"=",
"format",
".",
"apply",
"(",
"null",
",",
"args",
")",
";",
"}",
"if",
"(",
"Level",
".",
"TRACE",
".",
"equals",
"(",
"level",
")",
")",
"{",
"var",
"err",
"=",
"new",
"Error",
";",
"err",
".",
"name",
"=",
"\"Trace\"",
";",
"err",
".",
"message",
"=",
"message",
"||",
"''",
";",
"Error",
".",
"captureStackTrace",
"(",
"err",
",",
"log",
")",
";",
"message",
"=",
"err",
".",
"stack",
";",
"}",
"else",
"if",
"(",
"Level",
".",
"ERROR",
".",
"equals",
"(",
"level",
")",
"&&",
"isInstanceOf",
"(",
"message",
",",
"Error",
")",
")",
"{",
"message",
"=",
"message",
".",
"stack",
";",
"}",
"var",
"type",
"=",
"level",
".",
"name",
".",
"toLowerCase",
"(",
")",
",",
"appenders",
"=",
"this",
".",
"__appenders",
";",
"var",
"event",
"=",
"this",
".",
"getLogEvent",
"(",
"level",
",",
"message",
",",
"rawMessage",
")",
";",
"Object",
".",
"keys",
"(",
"appenders",
")",
".",
"forEach",
"(",
"function",
"(",
"i",
")",
"{",
"appenders",
"[",
"i",
"]",
".",
"append",
"(",
"event",
")",
";",
"}",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Log a message
@param {comb.logging.Level} level the level the message is
@param {String} message the message to log.
@return {comb.logging.Logger} for chaining.
|
[
"Log",
"a",
"message"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/index.js#L396-L421
|
train
|
C2FO/comb
|
lib/logging/index.js
|
function (appender, opts) {
var args = argsToArray(arguments);
if (isString(appender)) {
this.addAppender(Appender.createAppender(appender, opts));
} else {
if (!isUndefinedOrNull(appender)) {
var name = appender.name;
if (!(name in this.__appenders)) {
this.__appenders[name] = appender;
if (!appender.level) {
appender.level = this.level;
}
this._tree.addAppender(appender);
}
}
}
return this;
}
|
javascript
|
function (appender, opts) {
var args = argsToArray(arguments);
if (isString(appender)) {
this.addAppender(Appender.createAppender(appender, opts));
} else {
if (!isUndefinedOrNull(appender)) {
var name = appender.name;
if (!(name in this.__appenders)) {
this.__appenders[name] = appender;
if (!appender.level) {
appender.level = this.level;
}
this._tree.addAppender(appender);
}
}
}
return this;
}
|
[
"function",
"(",
"appender",
",",
"opts",
")",
"{",
"var",
"args",
"=",
"argsToArray",
"(",
"arguments",
")",
";",
"if",
"(",
"isString",
"(",
"appender",
")",
")",
"{",
"this",
".",
"addAppender",
"(",
"Appender",
".",
"createAppender",
"(",
"appender",
",",
"opts",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"isUndefinedOrNull",
"(",
"appender",
")",
")",
"{",
"var",
"name",
"=",
"appender",
".",
"name",
";",
"if",
"(",
"!",
"(",
"name",
"in",
"this",
".",
"__appenders",
")",
")",
"{",
"this",
".",
"__appenders",
"[",
"name",
"]",
"=",
"appender",
";",
"if",
"(",
"!",
"appender",
".",
"level",
")",
"{",
"appender",
".",
"level",
"=",
"this",
".",
"level",
";",
"}",
"this",
".",
"_tree",
".",
"addAppender",
"(",
"appender",
")",
";",
"}",
"}",
"}",
"return",
"this",
";",
"}"
] |
Add an appender to this logger. If this is additive then the appender is added to all subloggers.
@example
comb.logger("my.logger")
.addAppender("ConsoleAppender")
.addAppender("FileAppender", {file:'/var/log/my.log'})
.addAppender("RollingFileAppender", {file:'/var/log/myRolling.log'})
.addAppender("JSONAppender", {file:'/var/log/myJson.log'});
@param {comb.logging.Appender|String} If the appender is an {@link comb.logging.appenders.Appender} then it is added.
If the appender is a string then {@link comb.logging.appenders.Appender.createAppender} will be called to create it.
@param {Object} [opts = null] If the first argument is a string then the opts will be used as constructor arguments for
creating the appender.
@return {comb.logging.Logger} for chaining.
|
[
"Add",
"an",
"appender",
"to",
"this",
"logger",
".",
"If",
"this",
"is",
"additive",
"then",
"the",
"appender",
"is",
"added",
"to",
"all",
"subloggers",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/index.js#L441-L459
|
train
|
|
C2FO/comb
|
lib/collections/Heap.js
|
function (key, value) {
if (!base.isString(key)) {
var l = this.__heap.push(this.__makeNode(key, value));
this.__upHeap(l - 1);
} else {
throw new TypeError("Invalid key");
}
}
|
javascript
|
function (key, value) {
if (!base.isString(key)) {
var l = this.__heap.push(this.__makeNode(key, value));
this.__upHeap(l - 1);
} else {
throw new TypeError("Invalid key");
}
}
|
[
"function",
"(",
"key",
",",
"value",
")",
"{",
"if",
"(",
"!",
"base",
".",
"isString",
"(",
"key",
")",
")",
"{",
"var",
"l",
"=",
"this",
".",
"__heap",
".",
"push",
"(",
"this",
".",
"__makeNode",
"(",
"key",
",",
"value",
")",
")",
";",
"this",
".",
"__upHeap",
"(",
"l",
"-",
"1",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Invalid key\"",
")",
";",
"}",
"}"
] |
Insert a key value into the key
@param key
@param value
|
[
"Insert",
"a",
"key",
"value",
"into",
"the",
"key"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Heap.js#L56-L63
|
train
|
|
C2FO/comb
|
lib/collections/Heap.js
|
function () {
var heap = this.__heap,
l = heap.length,
ret;
if (l) {
ret = heap[0];
if (l === 1) {
heap.length = 0;
} else {
heap[0] = heap.pop();
this.__downHeap(0);
}
}
return ret ? ret.value : ret;
}
|
javascript
|
function () {
var heap = this.__heap,
l = heap.length,
ret;
if (l) {
ret = heap[0];
if (l === 1) {
heap.length = 0;
} else {
heap[0] = heap.pop();
this.__downHeap(0);
}
}
return ret ? ret.value : ret;
}
|
[
"function",
"(",
")",
"{",
"var",
"heap",
"=",
"this",
".",
"__heap",
",",
"l",
"=",
"heap",
".",
"length",
",",
"ret",
";",
"if",
"(",
"l",
")",
"{",
"ret",
"=",
"heap",
"[",
"0",
"]",
";",
"if",
"(",
"l",
"===",
"1",
")",
"{",
"heap",
".",
"length",
"=",
"0",
";",
"}",
"else",
"{",
"heap",
"[",
"0",
"]",
"=",
"heap",
".",
"pop",
"(",
")",
";",
"this",
".",
"__downHeap",
"(",
"0",
")",
";",
"}",
"}",
"return",
"ret",
"?",
"ret",
".",
"value",
":",
"ret",
";",
"}"
] |
Removes the root from the heap
@returns the value of the root
|
[
"Removes",
"the",
"root",
"from",
"the",
"heap"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Heap.js#L70-L84
|
train
|
|
C2FO/comb
|
lib/collections/Heap.js
|
function () {
var heap = this.__heap,
l = heap.length,
ret;
if (l) {
ret = heap[0];
}
return ret ? ret.value : ret;
}
|
javascript
|
function () {
var heap = this.__heap,
l = heap.length,
ret;
if (l) {
ret = heap[0];
}
return ret ? ret.value : ret;
}
|
[
"function",
"(",
")",
"{",
"var",
"heap",
"=",
"this",
".",
"__heap",
",",
"l",
"=",
"heap",
".",
"length",
",",
"ret",
";",
"if",
"(",
"l",
")",
"{",
"ret",
"=",
"heap",
"[",
"0",
"]",
";",
"}",
"return",
"ret",
"?",
"ret",
".",
"value",
":",
"ret",
";",
"}"
] |
Gets he value of the root node with out removing it.
@returns the value of the root
|
[
"Gets",
"he",
"value",
"of",
"the",
"root",
"node",
"with",
"out",
"removing",
"it",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Heap.js#L91-L99
|
train
|
|
C2FO/comb
|
lib/collections/Heap.js
|
function () {
var heap = this.__heap,
l = heap.length,
ret;
if (l) {
ret = heap[0];
}
return ret ? ret.key : ret;
}
|
javascript
|
function () {
var heap = this.__heap,
l = heap.length,
ret;
if (l) {
ret = heap[0];
}
return ret ? ret.key : ret;
}
|
[
"function",
"(",
")",
"{",
"var",
"heap",
"=",
"this",
".",
"__heap",
",",
"l",
"=",
"heap",
".",
"length",
",",
"ret",
";",
"if",
"(",
"l",
")",
"{",
"ret",
"=",
"heap",
"[",
"0",
"]",
";",
"}",
"return",
"ret",
"?",
"ret",
".",
"key",
":",
"ret",
";",
"}"
] |
Gets the key of the root node without removing it.
@returns the key of the root
|
[
"Gets",
"the",
"key",
"of",
"the",
"root",
"node",
"without",
"removing",
"it",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Heap.js#L106-L114
|
train
|
|
C2FO/comb
|
lib/base/number.js
|
roundCeil
|
function roundCeil(num, precision){
return Math.ceil(num * Math.pow(10, precision))/Math.pow(10, precision);
}
|
javascript
|
function roundCeil(num, precision){
return Math.ceil(num * Math.pow(10, precision))/Math.pow(10, precision);
}
|
[
"function",
"roundCeil",
"(",
"num",
",",
"precision",
")",
"{",
"return",
"Math",
".",
"ceil",
"(",
"num",
"*",
"Math",
".",
"pow",
"(",
"10",
",",
"precision",
")",
")",
"/",
"Math",
".",
"pow",
"(",
"10",
",",
"precision",
")",
";",
"}"
] |
Rounds a number to the specified places, rounding up.
@example
comb.number.roundCeil(10.000001, 2); //10.01
comb.number.roundCeil(10.000002, 5); //10.00001
comb.number.roundCeil(10.0003, 3); //10.001
comb.number.roundCeil(10.0004, 2); //10.01
comb.number.roundCeil(10.0005, 3); //10.001
comb.number.roundCeil(10.0002, 2); //10.01
@param {Number} num the number to round.
@param {Number} precision the number of places to round to.
@static
@memberOf comb.number
|
[
"Rounds",
"a",
"number",
"to",
"the",
"specified",
"places",
"rounding",
"up",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/number.js#L38-L40
|
train
|
C2FO/comb
|
lib/base/broadcast.js
|
function (obj, method, cb, scope) {
var index,
listeners;
if (typeof method !== "string") {
throw new Error("When calling connect the method must be string");
}
if (!func.isFunction(cb)) {
throw new Error("When calling connect callback must be a string");
}
scope = obj || global;
if (typeof scope[method] === "function") {
listeners = scope[method].__listeners;
if (!listeners) {
var newMethod = wrapper();
newMethod.func = obj[method];
listeners = (newMethod.__listeners = []);
scope[method] = newMethod;
}
index = listeners.push(cb);
} else {
throw new Error("unknow method " + method + " in object " + obj);
}
return [obj, method, index];
}
|
javascript
|
function (obj, method, cb, scope) {
var index,
listeners;
if (typeof method !== "string") {
throw new Error("When calling connect the method must be string");
}
if (!func.isFunction(cb)) {
throw new Error("When calling connect callback must be a string");
}
scope = obj || global;
if (typeof scope[method] === "function") {
listeners = scope[method].__listeners;
if (!listeners) {
var newMethod = wrapper();
newMethod.func = obj[method];
listeners = (newMethod.__listeners = []);
scope[method] = newMethod;
}
index = listeners.push(cb);
} else {
throw new Error("unknow method " + method + " in object " + obj);
}
return [obj, method, index];
}
|
[
"function",
"(",
"obj",
",",
"method",
",",
"cb",
",",
"scope",
")",
"{",
"var",
"index",
",",
"listeners",
";",
"if",
"(",
"typeof",
"method",
"!==",
"\"string\"",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"When calling connect the method must be string\"",
")",
";",
"}",
"if",
"(",
"!",
"func",
".",
"isFunction",
"(",
"cb",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"When calling connect callback must be a string\"",
")",
";",
"}",
"scope",
"=",
"obj",
"||",
"global",
";",
"if",
"(",
"typeof",
"scope",
"[",
"method",
"]",
"===",
"\"function\"",
")",
"{",
"listeners",
"=",
"scope",
"[",
"method",
"]",
".",
"__listeners",
";",
"if",
"(",
"!",
"listeners",
")",
"{",
"var",
"newMethod",
"=",
"wrapper",
"(",
")",
";",
"newMethod",
".",
"func",
"=",
"obj",
"[",
"method",
"]",
";",
"listeners",
"=",
"(",
"newMethod",
".",
"__listeners",
"=",
"[",
"]",
")",
";",
"scope",
"[",
"method",
"]",
"=",
"newMethod",
";",
"}",
"index",
"=",
"listeners",
".",
"push",
"(",
"cb",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"\"unknow method \"",
"+",
"method",
"+",
"\" in object \"",
"+",
"obj",
")",
";",
"}",
"return",
"[",
"obj",
",",
"method",
",",
"index",
"]",
";",
"}"
] |
Function to listen when other functions are called
@example
comb.connect(obj, "event", myfunc);
comb.connect(obj, "event", "log", console);
@param {Object} obj the object in which the method you are connecting to resides
@param {String} method the name of the method to connect to
@param {Function} cb the function to callback
@param {Object} [scope] the scope to call the specified cb in
@returns {Array} handle to pass to {@link comb.disconnect}
|
[
"Function",
"to",
"listen",
"when",
"other",
"functions",
"are",
"called"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/broadcast.js#L68-L91
|
train
|
|
C2FO/comb
|
lib/base/broadcast.js
|
function (topic, callback) {
if (!func.isFunction(callback)) {
throw new Error("callback must be a function");
}
var handle = {
topic: topic,
cb: callback,
pos: null
};
var list = listeners[topic];
if (!list) {
list = (listeners[topic] = []);
}
list.push(handle);
handle.pos = list.length - 1;
return handle;
}
|
javascript
|
function (topic, callback) {
if (!func.isFunction(callback)) {
throw new Error("callback must be a function");
}
var handle = {
topic: topic,
cb: callback,
pos: null
};
var list = listeners[topic];
if (!list) {
list = (listeners[topic] = []);
}
list.push(handle);
handle.pos = list.length - 1;
return handle;
}
|
[
"function",
"(",
"topic",
",",
"callback",
")",
"{",
"if",
"(",
"!",
"func",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"callback must be a function\"",
")",
";",
"}",
"var",
"handle",
"=",
"{",
"topic",
":",
"topic",
",",
"cb",
":",
"callback",
",",
"pos",
":",
"null",
"}",
";",
"var",
"list",
"=",
"listeners",
"[",
"topic",
"]",
";",
"if",
"(",
"!",
"list",
")",
"{",
"list",
"=",
"(",
"listeners",
"[",
"topic",
"]",
"=",
"[",
"]",
")",
";",
"}",
"list",
".",
"push",
"(",
"handle",
")",
";",
"handle",
".",
"pos",
"=",
"list",
".",
"length",
"-",
"1",
";",
"return",
"handle",
";",
"}"
] |
Listen for the broadcast of certain events
@example
comb.listen("hello", function(arg1, arg2){
console.log(arg1);
console.log(arg2);
});
@param {String} topic the topic to listen for
@param {Function} callback the funciton to call when the topic is published
@returns a handle to pass to {@link comb.unListen}
|
[
"Listen",
"for",
"the",
"broadcast",
"of",
"certain",
"events"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/broadcast.js#L140-L156
|
train
|
|
C2FO/comb
|
lib/base/broadcast.js
|
function (handle) {
if (handle) {
var topic = handle.topic, list = listeners[topic];
if (list) {
for (var i = list.length - 1; i >= 0; i--) {
if (list[i] === handle) {
list.splice(i, 1);
}
}
if (!list.length) {
delete listeners[topic];
}
}
}
}
|
javascript
|
function (handle) {
if (handle) {
var topic = handle.topic, list = listeners[topic];
if (list) {
for (var i = list.length - 1; i >= 0; i--) {
if (list[i] === handle) {
list.splice(i, 1);
}
}
if (!list.length) {
delete listeners[topic];
}
}
}
}
|
[
"function",
"(",
"handle",
")",
"{",
"if",
"(",
"handle",
")",
"{",
"var",
"topic",
"=",
"handle",
".",
"topic",
",",
"list",
"=",
"listeners",
"[",
"topic",
"]",
";",
"if",
"(",
"list",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"list",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"list",
"[",
"i",
"]",
"===",
"handle",
")",
"{",
"list",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}",
"}",
"if",
"(",
"!",
"list",
".",
"length",
")",
"{",
"delete",
"listeners",
"[",
"topic",
"]",
";",
"}",
"}",
"}",
"}"
] |
Disconnects a listener
@param handle a handle returned from {@link comb.listen}
|
[
"Disconnects",
"a",
"listener"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/broadcast.js#L163-L177
|
train
|
|
julesfern/spahql
|
doc-html/src/javascripts/pdoc/application.js
|
function() {
var state = $H({
activeTab: PDoc.Sidebar.getActiveTab(),
menuScrollOffset: $('menu_pane').scrollTop,
searchScrollOffset: $('search_results').scrollTop,
searchValue: $('search').getValue()
});
return escape(state.toJSON());
}
|
javascript
|
function() {
var state = $H({
activeTab: PDoc.Sidebar.getActiveTab(),
menuScrollOffset: $('menu_pane').scrollTop,
searchScrollOffset: $('search_results').scrollTop,
searchValue: $('search').getValue()
});
return escape(state.toJSON());
}
|
[
"function",
"(",
")",
"{",
"var",
"state",
"=",
"$H",
"(",
"{",
"activeTab",
":",
"PDoc",
".",
"Sidebar",
".",
"getActiveTab",
"(",
")",
",",
"menuScrollOffset",
":",
"$",
"(",
"'menu_pane'",
")",
".",
"scrollTop",
",",
"searchScrollOffset",
":",
"$",
"(",
"'search_results'",
")",
".",
"scrollTop",
",",
"searchValue",
":",
"$",
"(",
"'search'",
")",
".",
"getValue",
"(",
")",
"}",
")",
";",
"return",
"escape",
"(",
"state",
".",
"toJSON",
"(",
")",
")",
";",
"}"
] |
Remember the state of the sidebar so it can be restored on the next page.
|
[
"Remember",
"the",
"state",
"of",
"the",
"sidebar",
"so",
"it",
"can",
"be",
"restored",
"on",
"the",
"next",
"page",
"."
] |
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
|
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/application.js#L137-L146
|
train
|
|
julesfern/spahql
|
doc-html/src/javascripts/pdoc/application.js
|
function(state) {
try {
state = unescape(state).evalJSON();
var filterer = $('search').retrieve('filterer');
filterer.setSearchValue(state.searchValue);
(function() {
$('menu_pane').scrollTop = state.menuScrollOffset;
$('search_results').scrollTop = state.searchScrollOffset;
}).defer();
} catch(error) {
console.log(error);
if (!(error instanceof SyntaxError)) throw error;
}
}
|
javascript
|
function(state) {
try {
state = unescape(state).evalJSON();
var filterer = $('search').retrieve('filterer');
filterer.setSearchValue(state.searchValue);
(function() {
$('menu_pane').scrollTop = state.menuScrollOffset;
$('search_results').scrollTop = state.searchScrollOffset;
}).defer();
} catch(error) {
console.log(error);
if (!(error instanceof SyntaxError)) throw error;
}
}
|
[
"function",
"(",
"state",
")",
"{",
"try",
"{",
"state",
"=",
"unescape",
"(",
"state",
")",
".",
"evalJSON",
"(",
")",
";",
"var",
"filterer",
"=",
"$",
"(",
"'search'",
")",
".",
"retrieve",
"(",
"'filterer'",
")",
";",
"filterer",
".",
"setSearchValue",
"(",
"state",
".",
"searchValue",
")",
";",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"'menu_pane'",
")",
".",
"scrollTop",
"=",
"state",
".",
"menuScrollOffset",
";",
"$",
"(",
"'search_results'",
")",
".",
"scrollTop",
"=",
"state",
".",
"searchScrollOffset",
";",
"}",
")",
".",
"defer",
"(",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"error",
")",
";",
"if",
"(",
"!",
"(",
"error",
"instanceof",
"SyntaxError",
")",
")",
"throw",
"error",
";",
"}",
"}"
] |
Restore the tree to a certain point based on a cookie.
|
[
"Restore",
"the",
"tree",
"to",
"a",
"certain",
"point",
"based",
"on",
"a",
"cookie",
"."
] |
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
|
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/application.js#L149-L163
|
train
|
|
julesfern/spahql
|
doc-html/src/javascripts/pdoc/application.js
|
function(event) {
// Clear the text box on ESC.
if (event.keyCode && event.keyCode === Event.KEY_ESC) {
this.element.setValue('');
}
if (PDoc.Sidebar.Filterer.INTERCEPT_KEYS.include(event.keyCode))
return;
// If there's nothing in the text box, clear the results list.
var value = $F(this.element).strip().toLowerCase();
if (value === '') {
this.emptyResults();
this.hideResults();
return;
}
var urls = this.findURLs(value);
this.buildResults(urls);
}
|
javascript
|
function(event) {
// Clear the text box on ESC.
if (event.keyCode && event.keyCode === Event.KEY_ESC) {
this.element.setValue('');
}
if (PDoc.Sidebar.Filterer.INTERCEPT_KEYS.include(event.keyCode))
return;
// If there's nothing in the text box, clear the results list.
var value = $F(this.element).strip().toLowerCase();
if (value === '') {
this.emptyResults();
this.hideResults();
return;
}
var urls = this.findURLs(value);
this.buildResults(urls);
}
|
[
"function",
"(",
"event",
")",
"{",
"if",
"(",
"event",
".",
"keyCode",
"&&",
"event",
".",
"keyCode",
"===",
"Event",
".",
"KEY_ESC",
")",
"{",
"this",
".",
"element",
".",
"setValue",
"(",
"''",
")",
";",
"}",
"if",
"(",
"PDoc",
".",
"Sidebar",
".",
"Filterer",
".",
"INTERCEPT_KEYS",
".",
"include",
"(",
"event",
".",
"keyCode",
")",
")",
"return",
";",
"var",
"value",
"=",
"$F",
"(",
"this",
".",
"element",
")",
".",
"strip",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"value",
"===",
"''",
")",
"{",
"this",
".",
"emptyResults",
"(",
")",
";",
"this",
".",
"hideResults",
"(",
")",
";",
"return",
";",
"}",
"var",
"urls",
"=",
"this",
".",
"findURLs",
"(",
"value",
")",
";",
"this",
".",
"buildResults",
"(",
"urls",
")",
";",
"}"
] |
Called whenever the list of results needs to update as a result of a changed search key.
|
[
"Called",
"whenever",
"the",
"list",
"of",
"results",
"needs",
"to",
"update",
"as",
"a",
"result",
"of",
"a",
"changed",
"search",
"key",
"."
] |
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
|
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/application.js#L205-L224
|
train
|
|
julesfern/spahql
|
doc-html/src/javascripts/pdoc/application.js
|
function(str) {
var results = [];
for (var name in PDoc.elements) {
if (name.toLowerCase().include(str.toLowerCase()))
results.push(PDoc.elements[name]);
}
return results;
}
|
javascript
|
function(str) {
var results = [];
for (var name in PDoc.elements) {
if (name.toLowerCase().include(str.toLowerCase()))
results.push(PDoc.elements[name]);
}
return results;
}
|
[
"function",
"(",
"str",
")",
"{",
"var",
"results",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"name",
"in",
"PDoc",
".",
"elements",
")",
"{",
"if",
"(",
"name",
".",
"toLowerCase",
"(",
")",
".",
"include",
"(",
"str",
".",
"toLowerCase",
"(",
")",
")",
")",
"results",
".",
"push",
"(",
"PDoc",
".",
"elements",
"[",
"name",
"]",
")",
";",
"}",
"return",
"results",
";",
"}"
] |
Given a key, finds all the PDoc objects that match.
|
[
"Given",
"a",
"key",
"finds",
"all",
"the",
"PDoc",
"objects",
"that",
"match",
"."
] |
f2eff34e59f5af2e6a48f11f59f99c223b4a2be8
|
https://github.com/julesfern/spahql/blob/f2eff34e59f5af2e6a48f11f59f99c223b4a2be8/doc-html/src/javascripts/pdoc/application.js#L236-L243
|
train
|
|
C2FO/comb
|
lib/base/object.js
|
isHash
|
function isHash(obj) {
var ret = comb.isObject(obj);
return ret && obj.constructor === Object;
}
|
javascript
|
function isHash(obj) {
var ret = comb.isObject(obj);
return ret && obj.constructor === Object;
}
|
[
"function",
"isHash",
"(",
"obj",
")",
"{",
"var",
"ret",
"=",
"comb",
".",
"isObject",
"(",
"obj",
")",
";",
"return",
"ret",
"&&",
"obj",
".",
"constructor",
"===",
"Object",
";",
"}"
] |
Determines if an object is just a hash and not a qualified Object such as Number
@example
comb.isHash({}) => true
comb.isHash({1 : 2, a : "b"}) => true
comb.isHash(new Date()) => false
comb.isHash(new String()) => false
comb.isHash(new Number()) => false
comb.isHash(new Boolean()) => false
comb.isHash() => false
comb.isHash("") => false
comb.isHash(1) => false
comb.isHash(false) => false
comb.isHash(true) => false
@param {Anything} obj the thing to test if it is a hash
@returns {Boolean} true if it is a hash false otherwise
@memberOf comb
@static
|
[
"Determines",
"if",
"an",
"object",
"is",
"just",
"a",
"hash",
"and",
"not",
"a",
"qualified",
"Object",
"such",
"as",
"Number"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/object.js#L161-L164
|
train
|
C2FO/comb
|
lib/base/object.js
|
extend
|
function extend(parent, ext) {
var proto = parent.prototype || parent;
merge(proto, ext);
return parent;
}
|
javascript
|
function extend(parent, ext) {
var proto = parent.prototype || parent;
merge(proto, ext);
return parent;
}
|
[
"function",
"extend",
"(",
"parent",
",",
"ext",
")",
"{",
"var",
"proto",
"=",
"parent",
".",
"prototype",
"||",
"parent",
";",
"merge",
"(",
"proto",
",",
"ext",
")",
";",
"return",
"parent",
";",
"}"
] |
Extends the prototype of an object if it exists otherwise it extends the object.
@example
var MyObj = function(){};
MyObj.prototype.test = true;
comb.extend(MyObj, {test2 : false, test3 : "hello", test4 : "world"});
var myObj = new MyObj();
myObj.test => true
myObj.test2 => false
myObj.test3 => "hello"
myObj.test4 => "world"
var myObj2 = {};
myObj2.test = true;
comb.extend(myObj2, {test2 : false, test3 : "hello", test4 : "world"});
myObj2.test => true
myObj2.test2 => false
myObj2.test3 => "hello"
myObj2.test4 => "world"
@param {Object} parent the parent object to extend
@param {Object} extend the extension object to mixin to the parent
@returns {Object} returns the extended object
@memberOf comb
@static
|
[
"Extends",
"the",
"prototype",
"of",
"an",
"object",
"if",
"it",
"exists",
"otherwise",
"it",
"extends",
"the",
"object",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/object.js#L268-L272
|
train
|
C2FO/comb
|
lib/base/object.js
|
isEmpty
|
function isEmpty(object) {
if (comb.isObject(object)) {
for (var i in object) {
if (object.hasOwnProperty(i)) {
return false;
}
}
}
return true;
}
|
javascript
|
function isEmpty(object) {
if (comb.isObject(object)) {
for (var i in object) {
if (object.hasOwnProperty(i)) {
return false;
}
}
}
return true;
}
|
[
"function",
"isEmpty",
"(",
"object",
")",
"{",
"if",
"(",
"comb",
".",
"isObject",
"(",
"object",
")",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"object",
")",
"{",
"if",
"(",
"object",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"}",
"return",
"true",
";",
"}"
] |
Determines if an object is empty
@example
comb.isEmpty({}) => true
comb.isEmpty({a : 1}) => false
@param object the object to test
@returns {Boolean} true if the object is empty;
@memberOf comb
@static
|
[
"Determines",
"if",
"an",
"object",
"is",
"empty"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/object.js#L302-L311
|
train
|
C2FO/comb
|
lib/base/object.js
|
values
|
function values(hash) {
if (!isHash(hash)) {
throw new TypeError();
}
var keys = Object.keys(hash), ret = [];
for (var i = 0, len = keys.length; i < len; ++i) {
ret.push(hash[keys[i]]);
}
return ret;
}
|
javascript
|
function values(hash) {
if (!isHash(hash)) {
throw new TypeError();
}
var keys = Object.keys(hash), ret = [];
for (var i = 0, len = keys.length; i < len; ++i) {
ret.push(hash[keys[i]]);
}
return ret;
}
|
[
"function",
"values",
"(",
"hash",
")",
"{",
"if",
"(",
"!",
"isHash",
"(",
"hash",
")",
")",
"{",
"throw",
"new",
"TypeError",
"(",
")",
";",
"}",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"hash",
")",
",",
"ret",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"len",
";",
"++",
"i",
")",
"{",
"ret",
".",
"push",
"(",
"hash",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
";",
"}",
"return",
"ret",
";",
"}"
] |
Returns the values of a hash.
```
var obj = {a : "b", c : "d", e : "f"};
comb(obj).values(); //["b", "d", "f"]
comb.hash.values(obj); //["b", "d", "f"]
```
@param {Object} hash the object to retrieve the values of.
@return {Array} array of values.
@memberOf comb.hash
|
[
"Returns",
"the",
"values",
"of",
"a",
"hash",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/object.js#L494-L503
|
train
|
C2FO/comb
|
lib/collections/Pool.js
|
function () {
var ret;
if (this.count <= this.__maxObjects && this.freeCount > 0) {
ret = this.__freeObjects.dequeue();
this.__inUseObjects.push(ret);
} else if (this.count < this.__maxObjects) {
ret = this.createObject();
this.__inUseObjects.push(ret);
}
return ret;
}
|
javascript
|
function () {
var ret;
if (this.count <= this.__maxObjects && this.freeCount > 0) {
ret = this.__freeObjects.dequeue();
this.__inUseObjects.push(ret);
} else if (this.count < this.__maxObjects) {
ret = this.createObject();
this.__inUseObjects.push(ret);
}
return ret;
}
|
[
"function",
"(",
")",
"{",
"var",
"ret",
";",
"if",
"(",
"this",
".",
"count",
"<=",
"this",
".",
"__maxObjects",
"&&",
"this",
".",
"freeCount",
">",
"0",
")",
"{",
"ret",
"=",
"this",
".",
"__freeObjects",
".",
"dequeue",
"(",
")",
";",
"this",
".",
"__inUseObjects",
".",
"push",
"(",
"ret",
")",
";",
"}",
"else",
"if",
"(",
"this",
".",
"count",
"<",
"this",
".",
"__maxObjects",
")",
"{",
"ret",
"=",
"this",
".",
"createObject",
"(",
")",
";",
"this",
".",
"__inUseObjects",
".",
"push",
"(",
"ret",
")",
";",
"}",
"return",
"ret",
";",
"}"
] |
Retrieves an object from this pool.
`
@return {*} an object to contained in this pool
|
[
"Retrieves",
"an",
"object",
"from",
"this",
"pool",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Pool.js#L43-L53
|
train
|
|
C2FO/comb
|
lib/collections/Pool.js
|
function (obj) {
var index;
if (this.validate(obj) && this.count <= this.__maxObjects && (index = this.__inUseObjects.indexOf(obj)) > -1) {
this.__freeObjects.enqueue(obj);
this.__inUseObjects.splice(index, 1);
} else {
this.removeObject(obj);
}
}
|
javascript
|
function (obj) {
var index;
if (this.validate(obj) && this.count <= this.__maxObjects && (index = this.__inUseObjects.indexOf(obj)) > -1) {
this.__freeObjects.enqueue(obj);
this.__inUseObjects.splice(index, 1);
} else {
this.removeObject(obj);
}
}
|
[
"function",
"(",
"obj",
")",
"{",
"var",
"index",
";",
"if",
"(",
"this",
".",
"validate",
"(",
"obj",
")",
"&&",
"this",
".",
"count",
"<=",
"this",
".",
"__maxObjects",
"&&",
"(",
"index",
"=",
"this",
".",
"__inUseObjects",
".",
"indexOf",
"(",
"obj",
")",
")",
">",
"-",
"1",
")",
"{",
"this",
".",
"__freeObjects",
".",
"enqueue",
"(",
"obj",
")",
";",
"this",
".",
"__inUseObjects",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"else",
"{",
"this",
".",
"removeObject",
"(",
"obj",
")",
";",
"}",
"}"
] |
Returns an object to this pool. The object is validated before it is returned to the pool,
if the validation fails then it is removed from the pool;
@param {*} obj the object to return to the pool
|
[
"Returns",
"an",
"object",
"to",
"this",
"pool",
".",
"The",
"object",
"is",
"validated",
"before",
"it",
"is",
"returned",
"to",
"the",
"pool",
"if",
"the",
"validation",
"fails",
"then",
"it",
"is",
"removed",
"from",
"the",
"pool",
";"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Pool.js#L60-L68
|
train
|
|
C2FO/comb
|
lib/collections/Pool.js
|
function (obj) {
var index;
if (this.__freeObjects.contains(obj)) {
this.__freeObjects.remove(obj);
} else if ((index = this.__inUseObjects.indexOf(obj)) > -1) {
this.__inUseObjects.splice(index, 1);
}
//otherwise its not contained in this pool;
return obj;
}
|
javascript
|
function (obj) {
var index;
if (this.__freeObjects.contains(obj)) {
this.__freeObjects.remove(obj);
} else if ((index = this.__inUseObjects.indexOf(obj)) > -1) {
this.__inUseObjects.splice(index, 1);
}
//otherwise its not contained in this pool;
return obj;
}
|
[
"function",
"(",
"obj",
")",
"{",
"var",
"index",
";",
"if",
"(",
"this",
".",
"__freeObjects",
".",
"contains",
"(",
"obj",
")",
")",
"{",
"this",
".",
"__freeObjects",
".",
"remove",
"(",
"obj",
")",
";",
"}",
"else",
"if",
"(",
"(",
"index",
"=",
"this",
".",
"__inUseObjects",
".",
"indexOf",
"(",
"obj",
")",
")",
">",
"-",
"1",
")",
"{",
"this",
".",
"__inUseObjects",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"return",
"obj",
";",
"}"
] |
Removes an object from the pool, this can be overriden to provide any
teardown of objects that needs to take place.
@param {*} obj the object that needs to be removed.
@return {*} the object removed.
|
[
"Removes",
"an",
"object",
"from",
"the",
"pool",
"this",
"can",
"be",
"overriden",
"to",
"provide",
"any",
"teardown",
"of",
"objects",
"that",
"needs",
"to",
"take",
"place",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/collections/Pool.js#L78-L87
|
train
|
|
C2FO/comb
|
lib/base/date/index.js
|
function (/*Date*/date1, /*Date*/date2, /*String*/portion) {
date1 = new Date(date1);
date2 = new Date((date2 || new Date()));
if (portion === "date") {
// Ignore times and compare dates.
date1.setHours(0, 0, 0, 0);
date2.setHours(0, 0, 0, 0);
} else if (portion === "time") {
// Ignore dates and compare times.
date1.setFullYear(0, 0, 0);
date2.setFullYear(0, 0, 0);
}
return date1 > date2 ? 1 : date1 < date2 ? -1 : 0;
}
|
javascript
|
function (/*Date*/date1, /*Date*/date2, /*String*/portion) {
date1 = new Date(date1);
date2 = new Date((date2 || new Date()));
if (portion === "date") {
// Ignore times and compare dates.
date1.setHours(0, 0, 0, 0);
date2.setHours(0, 0, 0, 0);
} else if (portion === "time") {
// Ignore dates and compare times.
date1.setFullYear(0, 0, 0);
date2.setFullYear(0, 0, 0);
}
return date1 > date2 ? 1 : date1 < date2 ? -1 : 0;
}
|
[
"function",
"(",
"date1",
",",
"date2",
",",
"portion",
")",
"{",
"date1",
"=",
"new",
"Date",
"(",
"date1",
")",
";",
"date2",
"=",
"new",
"Date",
"(",
"(",
"date2",
"||",
"new",
"Date",
"(",
")",
")",
")",
";",
"if",
"(",
"portion",
"===",
"\"date\"",
")",
"{",
"date1",
".",
"setHours",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"date2",
".",
"setHours",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
";",
"}",
"else",
"if",
"(",
"portion",
"===",
"\"time\"",
")",
"{",
"date1",
".",
"setFullYear",
"(",
"0",
",",
"0",
",",
"0",
")",
";",
"date2",
".",
"setFullYear",
"(",
"0",
",",
"0",
",",
"0",
")",
";",
"}",
"return",
"date1",
">",
"date2",
"?",
"1",
":",
"date1",
"<",
"date2",
"?",
"-",
"1",
":",
"0",
";",
"}"
] |
Compares two dates
@example
var d1 = new Date();
d1.setHours(0);
comb.date.compare(d1, d1); // 0
var d1 = new Date();
d1.setHours(0);
var d2 = new Date();
d2.setFullYear(2005);
d2.setHours(12);
comb.date.compare(d1, d2, "date"); // 1
comb.date.compare(d1, d2, "datetime"); // 1
var d1 = new Date();
d1.setHours(0);
var d2 = new Date();
d2.setFullYear(2005);
d2.setHours(12);
comb.date.compare(d2, d1, "date"); // -1
comb.date.compare(d1, d2, "time"); //-1
@param {Date|String} date1 the date to comapare
@param {Date|String} [date2=new Date()] the date to compare date1 againse
@param {"date"|"time"|"datetime"} portion compares the portion specified
@returns -1 if date1 is < date2 0 if date1 === date2 1 if date1 > date2
|
[
"Compares",
"two",
"dates"
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/base/date/index.js#L267-L281
|
train
|
|
C2FO/comb
|
lib/logging/appenders/appender.js
|
function (type, options) {
var caseType = type.toLowerCase();
if (caseType in APPENDER_TYPES) {
return new APPENDER_TYPES[caseType](options);
} else {
throw new Error(type + " appender is not registered!");
}
}
|
javascript
|
function (type, options) {
var caseType = type.toLowerCase();
if (caseType in APPENDER_TYPES) {
return new APPENDER_TYPES[caseType](options);
} else {
throw new Error(type + " appender is not registered!");
}
}
|
[
"function",
"(",
"type",
",",
"options",
")",
"{",
"var",
"caseType",
"=",
"type",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"caseType",
"in",
"APPENDER_TYPES",
")",
"{",
"return",
"new",
"APPENDER_TYPES",
"[",
"caseType",
"]",
"(",
"options",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"type",
"+",
"\" appender is not registered!\"",
")",
";",
"}",
"}"
] |
Acts as a factory for appenders.
@example
var logging = comb.logging,
Logger = logging.Logger,
Appender = logging.appenders.Appender;
var logger = comb.logging.Logger.getLogger("my.logger");
logger.addAppender(Appender.createAppender("consoleAppender"));
@param {String} type the type of appender to create.
@param {Object} [options={}] additional options to pass to the appender.
@return {comb.logging.appenders.Appender} an appender to add to a logger.
|
[
"Acts",
"as",
"a",
"factory",
"for",
"appenders",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/appenders/appender.js#L159-L167
|
train
|
|
C2FO/comb
|
lib/logging/config.js
|
function (appender) {
var rootLogger = Logger.getRootLogger();
rootLogger.removeAllAppenders();
if (base.isInstanceOf(appender, appenders.Appender)) {
rootLogger.addAppender(appender);
} else {
rootLogger.addAppender(new appenders.ConsoleAppender());
}
}
|
javascript
|
function (appender) {
var rootLogger = Logger.getRootLogger();
rootLogger.removeAllAppenders();
if (base.isInstanceOf(appender, appenders.Appender)) {
rootLogger.addAppender(appender);
} else {
rootLogger.addAppender(new appenders.ConsoleAppender());
}
}
|
[
"function",
"(",
"appender",
")",
"{",
"var",
"rootLogger",
"=",
"Logger",
".",
"getRootLogger",
"(",
")",
";",
"rootLogger",
".",
"removeAllAppenders",
"(",
")",
";",
"if",
"(",
"base",
".",
"isInstanceOf",
"(",
"appender",
",",
"appenders",
".",
"Appender",
")",
")",
"{",
"rootLogger",
".",
"addAppender",
"(",
"appender",
")",
";",
"}",
"else",
"{",
"rootLogger",
".",
"addAppender",
"(",
"new",
"appenders",
".",
"ConsoleAppender",
"(",
")",
")",
";",
"}",
"}"
] |
Configure logging.
@param {comb.logging.Appender} [appender=null] appender to add to the root logger, by default a console logger is added.
|
[
"Configure",
"logging",
"."
] |
c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9
|
https://github.com/C2FO/comb/blob/c230d025b5af98a0f6ce07e7d0db0a3fa07f1fb9/lib/logging/config.js#L59-L67
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.