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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
clay/amphora | lib/services/metadata.js | unpublishPage | function unpublishPage(uri, user) {
const update = {
published: false,
publishTime: null,
url: '',
history: [{ action: 'unpublish', timestamp: new Date().toISOString(), users: [userOrRobot(user)] }]
};
return changeMetaState(uri, update);
} | javascript | function unpublishPage(uri, user) {
const update = {
published: false,
publishTime: null,
url: '',
history: [{ action: 'unpublish', timestamp: new Date().toISOString(), users: [userOrRobot(user)] }]
};
return changeMetaState(uri, update);
} | [
"function",
"unpublishPage",
"(",
"uri",
",",
"user",
")",
"{",
"const",
"update",
"=",
"{",
"published",
":",
"false",
",",
"publishTime",
":",
"null",
",",
"url",
":",
"''",
",",
"history",
":",
"[",
"{",
"action",
":",
"'unpublish'",
",",
"timestamp... | Update the page meta on unpublish
@param {String} uri
@param {Object} user
@returns {Promise} | [
"Update",
"the",
"page",
"meta",
"on",
"unpublish"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L125-L134 | train |
clay/amphora | lib/services/metadata.js | changeMetaState | function changeMetaState(uri, update) {
return getMeta(uri)
.then(old => mergeNewAndOldMeta(old, update))
.then(updatedMeta => putMeta(uri, updatedMeta));
} | javascript | function changeMetaState(uri, update) {
return getMeta(uri)
.then(old => mergeNewAndOldMeta(old, update))
.then(updatedMeta => putMeta(uri, updatedMeta));
} | [
"function",
"changeMetaState",
"(",
"uri",
",",
"update",
")",
"{",
"return",
"getMeta",
"(",
"uri",
")",
".",
"then",
"(",
"old",
"=>",
"mergeNewAndOldMeta",
"(",
"old",
",",
"update",
")",
")",
".",
"then",
"(",
"updatedMeta",
"=>",
"putMeta",
"(",
"... | Given a uri and an object that is an
update, retreive the old meta, merge
the new and old and then put the merge
to the db.
@param {String} uri
@param {Object} update
@returns {Promise} | [
"Given",
"a",
"uri",
"and",
"an",
"object",
"that",
"is",
"an",
"update",
"retreive",
"the",
"old",
"meta",
"merge",
"the",
"new",
"and",
"old",
"and",
"then",
"put",
"the",
"merge",
"to",
"the",
"db",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L160-L164 | train |
clay/amphora | lib/services/metadata.js | putMeta | function putMeta(uri, data) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.putMeta(id, data)
.then(pubToBus(id));
} | javascript | function putMeta(uri, data) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.putMeta(id, data)
.then(pubToBus(id));
} | [
"function",
"putMeta",
"(",
"uri",
",",
"data",
")",
"{",
"const",
"id",
"=",
"replaceVersion",
"(",
"uri",
".",
"replace",
"(",
"'/meta'",
",",
"''",
")",
")",
";",
"return",
"db",
".",
"putMeta",
"(",
"id",
",",
"data",
")",
".",
"then",
"(",
"... | Write the page's meta object to the DB
@param {String} uri
@param {Object} data
@returns {Promise} | [
"Write",
"the",
"page",
"s",
"meta",
"object",
"to",
"the",
"DB"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L214-L219 | train |
clay/amphora | lib/services/metadata.js | patchMeta | function patchMeta(uri, data) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.patchMeta(id, data)
.then(() => getMeta(uri))
.then(pubToBus(id));
} | javascript | function patchMeta(uri, data) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.patchMeta(id, data)
.then(() => getMeta(uri))
.then(pubToBus(id));
} | [
"function",
"patchMeta",
"(",
"uri",
",",
"data",
")",
"{",
"const",
"id",
"=",
"replaceVersion",
"(",
"uri",
".",
"replace",
"(",
"'/meta'",
",",
"''",
")",
")",
";",
"return",
"db",
".",
"patchMeta",
"(",
"id",
",",
"data",
")",
".",
"then",
"(",... | Update a subset of properties on
a metadata object
@param {String} uri
@param {Object} data
@returns {Promise} | [
"Update",
"a",
"subset",
"of",
"properties",
"on",
"a",
"metadata",
"object"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L229-L235 | train |
clay/amphora | lib/services/metadata.js | checkProps | function checkProps(uri, props) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.getMeta(id)
.then(meta => {
return Array.isArray(props)
? props.every(prop => meta[prop])
: meta[props] && true;
})
.catch(err => {
throw new Error(err);
});
} | javascript | function checkProps(uri, props) {
const id = replaceVersion(uri.replace('/meta', ''));
return db.getMeta(id)
.then(meta => {
return Array.isArray(props)
? props.every(prop => meta[prop])
: meta[props] && true;
})
.catch(err => {
throw new Error(err);
});
} | [
"function",
"checkProps",
"(",
"uri",
",",
"props",
")",
"{",
"const",
"id",
"=",
"replaceVersion",
"(",
"uri",
".",
"replace",
"(",
"'/meta'",
",",
"''",
")",
")",
";",
"return",
"db",
".",
"getMeta",
"(",
"id",
")",
".",
"then",
"(",
"meta",
"=>"... | Check metadata property or properties for truthy values.
Returns true if all properties have truthy values.
@param {String} uri
@param {String | Array} props
@returns {Boolean | Object} | [
"Check",
"metadata",
"property",
"or",
"properties",
"for",
"truthy",
"values",
".",
"Returns",
"true",
"if",
"all",
"properties",
"have",
"truthy",
"values",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/metadata.js#L244-L256 | train |
clay/amphora | lib/services/models.js | put | function put(model, uri, data, locals) {
const startTime = process.hrtime(),
timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_PUT_COEFFICIENT;
return bluebird.try(() => {
return bluebird.resolve(model.save(uri, data, locals))
.then(resolvedData => {
if (!_.isObject(resolvedData)) {
throw n... | javascript | function put(model, uri, data, locals) {
const startTime = process.hrtime(),
timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_PUT_COEFFICIENT;
return bluebird.try(() => {
return bluebird.resolve(model.save(uri, data, locals))
.then(resolvedData => {
if (!_.isObject(resolvedData)) {
throw n... | [
"function",
"put",
"(",
"model",
",",
"uri",
",",
"data",
",",
"locals",
")",
"{",
"const",
"startTime",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"timeoutLimit",
"=",
"TIMEOUT_CONSTANT",
"*",
"TIMEOUT_PUT_COEFFICIENT",
";",
"return",
"bluebird",
".",
... | Execute the save function of a model.js file
for either a component or a layout
@param {Object} model
@param {String} uri
@param {Object} data
@param {Object} locals
@returns {Object} | [
"Execute",
"the",
"save",
"function",
"of",
"a",
"model",
".",
"js",
"file",
"for",
"either",
"a",
"component",
"or",
"a",
"layout"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/models.js#L23-L47 | train |
clay/amphora | lib/services/models.js | get | function get(model, renderModel, executeRender, uri, locals) { /* eslint max-params: ["error", 5] */
var promise;
if (executeRender) {
const startTime = process.hrtime(),
timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_GET_COEFFICIENT;
promise = bluebird.try(() => {
return db.get(uri)
.then(... | javascript | function get(model, renderModel, executeRender, uri, locals) { /* eslint max-params: ["error", 5] */
var promise;
if (executeRender) {
const startTime = process.hrtime(),
timeoutLimit = TIMEOUT_CONSTANT * TIMEOUT_GET_COEFFICIENT;
promise = bluebird.try(() => {
return db.get(uri)
.then(... | [
"function",
"get",
"(",
"model",
",",
"renderModel",
",",
"executeRender",
",",
"uri",
",",
"locals",
")",
"{",
"/* eslint max-params: [\"error\", 5] */",
"var",
"promise",
";",
"if",
"(",
"executeRender",
")",
"{",
"const",
"startTime",
"=",
"process",
".",
"... | Execute the get function of a model.js file
for either a component or a layout
@param {Object} model
@param {Object} renderModel
@param {Boolean} executeRender
@param {String} uri
@param {Object} locals
@returns {Promise} | [
"Execute",
"the",
"get",
"function",
"of",
"a",
"model",
".",
"js",
"file",
"for",
"either",
"a",
"component",
"or",
"a",
"layout"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/models.js#L60-L98 | train |
clay/amphora | lib/services/pages.js | renameReferenceUniquely | function renameReferenceUniquely(uri) {
const prefix = uri.substr(0, uri.indexOf('/_components/'));
return `${prefix}/_components/${getComponentName(uri)}/instances/${uid.get()}`;
} | javascript | function renameReferenceUniquely(uri) {
const prefix = uri.substr(0, uri.indexOf('/_components/'));
return `${prefix}/_components/${getComponentName(uri)}/instances/${uid.get()}`;
} | [
"function",
"renameReferenceUniquely",
"(",
"uri",
")",
"{",
"const",
"prefix",
"=",
"uri",
".",
"substr",
"(",
"0",
",",
"uri",
".",
"indexOf",
"(",
"'/_components/'",
")",
")",
";",
"return",
"`",
"${",
"prefix",
"}",
"${",
"getComponentName",
"(",
"ur... | Get a reference that is unique, but of the same component type as original.
@param {string} uri
@returns {string} | [
"Get",
"a",
"reference",
"that",
"is",
"unique",
"but",
"of",
"the",
"same",
"component",
"type",
"as",
"original",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L56-L60 | train |
clay/amphora | lib/services/pages.js | getPageClonePutOperations | function getPageClonePutOperations(pageData, locals) {
return bluebird.all(_.reduce(pageData, (promises, pageValue, pageKey) => {
if (typeof pageValue === 'string' && getComponentName(pageValue)) {
// for all strings that are component references
promises.push(components.get(pageValue, locals)
... | javascript | function getPageClonePutOperations(pageData, locals) {
return bluebird.all(_.reduce(pageData, (promises, pageValue, pageKey) => {
if (typeof pageValue === 'string' && getComponentName(pageValue)) {
// for all strings that are component references
promises.push(components.get(pageValue, locals)
... | [
"function",
"getPageClonePutOperations",
"(",
"pageData",
",",
"locals",
")",
"{",
"return",
"bluebird",
".",
"all",
"(",
"_",
".",
"reduce",
"(",
"pageData",
",",
"(",
"promises",
",",
"pageValue",
",",
"pageKey",
")",
"=>",
"{",
"if",
"(",
"typeof",
"p... | Clone all instance components that are referenced by this page data, and maintain the data's object structure.
@param {object} pageData
@param {object} locals
@returns {Promise} | [
"Clone",
"all",
"instance",
"components",
"that",
"are",
"referenced",
"by",
"this",
"page",
"data",
"and",
"maintain",
"the",
"data",
"s",
"object",
"structure",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L69-L96 | train |
clay/amphora | lib/services/pages.js | replacePageReferenceVersions | function replacePageReferenceVersions(data, version) {
const replace = _.partial(replaceVersion, _, version);
return _.mapValues(data, function (value, key) {
let result;
if (references.isUri(value)) {
result = replace(value);
} else if (_.isArray(value) && key !== 'urlHistory') {
// urlHi... | javascript | function replacePageReferenceVersions(data, version) {
const replace = _.partial(replaceVersion, _, version);
return _.mapValues(data, function (value, key) {
let result;
if (references.isUri(value)) {
result = replace(value);
} else if (_.isArray(value) && key !== 'urlHistory') {
// urlHi... | [
"function",
"replacePageReferenceVersions",
"(",
"data",
",",
"version",
")",
"{",
"const",
"replace",
"=",
"_",
".",
"partial",
"(",
"replaceVersion",
",",
"_",
",",
"version",
")",
";",
"return",
"_",
".",
"mapValues",
"(",
"data",
",",
"function",
"(",
... | Replace the referenced things in the page data with a different version
@param {object} data
@param {string} version
@returns {object} | [
"Replace",
"the",
"referenced",
"things",
"in",
"the",
"page",
"data",
"with",
"a",
"different",
"version"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L120-L136 | train |
clay/amphora | lib/services/pages.js | getRecursivePublishedPutOperations | function getRecursivePublishedPutOperations(locals) {
return rootComponentRef => {
/**
* 1) Get reference (could be latest, could be other)
* 2) Get all references within reference
* 3) Replace all references with @published (including root reference)
* 4) Get list of put operations needed
... | javascript | function getRecursivePublishedPutOperations(locals) {
return rootComponentRef => {
/**
* 1) Get reference (could be latest, could be other)
* 2) Get all references within reference
* 3) Replace all references with @published (including root reference)
* 4) Get list of put operations needed
... | [
"function",
"getRecursivePublishedPutOperations",
"(",
"locals",
")",
"{",
"return",
"rootComponentRef",
"=>",
"{",
"/**\n * 1) Get reference (could be latest, could be other)\n * 2) Get all references within reference\n * 3) Replace all references with @published (including root ref... | Get a list of all operations with all references converted to @published
@param {object} locals
@returns {function} | [
"Get",
"a",
"list",
"of",
"all",
"operations",
"with",
"all",
"references",
"converted",
"to"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L143-L155 | train |
clay/amphora | lib/services/pages.js | getSite | function getSite(prefix, locals) {
const site = locals && locals.site;
return site || siteService.getSiteFromPrefix(prefix);
} | javascript | function getSite(prefix, locals) {
const site = locals && locals.site;
return site || siteService.getSiteFromPrefix(prefix);
} | [
"function",
"getSite",
"(",
"prefix",
",",
"locals",
")",
"{",
"const",
"site",
"=",
"locals",
"&&",
"locals",
".",
"site",
";",
"return",
"site",
"||",
"siteService",
".",
"getSiteFromPrefix",
"(",
"prefix",
")",
";",
"}"
] | Given either locals or a string,
return the site we're working with
@param {String} prefix
@param {Object} locals
@returns {Object} | [
"Given",
"either",
"locals",
"or",
"a",
"string",
"return",
"the",
"site",
"we",
"re",
"working",
"with"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L165-L169 | train |
clay/amphora | lib/services/pages.js | publish | function publish(uri, data, locals) {
const startTime = process.hrtime(),
prefix = getPrefix(uri),
site = getSite(prefix, locals),
timeoutLimit = timeoutConstant * timeoutPublishCoefficient,
user = locals && locals.user;
var publishedMeta; // We need to store some meta a little later
return getPu... | javascript | function publish(uri, data, locals) {
const startTime = process.hrtime(),
prefix = getPrefix(uri),
site = getSite(prefix, locals),
timeoutLimit = timeoutConstant * timeoutPublishCoefficient,
user = locals && locals.user;
var publishedMeta; // We need to store some meta a little later
return getPu... | [
"function",
"publish",
"(",
"uri",
",",
"data",
",",
"locals",
")",
"{",
"const",
"startTime",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"prefix",
"=",
"getPrefix",
"(",
"uri",
")",
",",
"site",
"=",
"getSite",
"(",
"prefix",
",",
"locals",
")",
... | Publish a uri
@param {string} uri
@param {object} [data]
@param {object} [locals]
@returns {Promise} | [
"Publish",
"a",
"uri"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/pages.js#L226-L284 | train |
clay/amphora | lib/services/plugins.js | initPlugins | function initPlugins(router, site) {
return bluebird.all(module.exports.plugins.map(plugin => {
return bluebird.try(() => {
if (typeof plugin === 'function') {
return plugin(router, pluginDBAdapter, publish, sites, site);
} else {
log('warn', 'Plugin is not a function');
return... | javascript | function initPlugins(router, site) {
return bluebird.all(module.exports.plugins.map(plugin => {
return bluebird.try(() => {
if (typeof plugin === 'function') {
return plugin(router, pluginDBAdapter, publish, sites, site);
} else {
log('warn', 'Plugin is not a function');
return... | [
"function",
"initPlugins",
"(",
"router",
",",
"site",
")",
"{",
"return",
"bluebird",
".",
"all",
"(",
"module",
".",
"exports",
".",
"plugins",
".",
"map",
"(",
"plugin",
"=>",
"{",
"return",
"bluebird",
".",
"try",
"(",
"(",
")",
"=>",
"{",
"if",
... | Call each plugin and pass along the router,
a subset of the db service the publish method
of the bus service.
@param {Object} router
@param {Object} site
@returns {Promise} | [
"Call",
"each",
"plugin",
"and",
"pass",
"along",
"the",
"router",
"a",
"subset",
"of",
"the",
"db",
"service",
"the",
"publish",
"method",
"of",
"the",
"bus",
"service",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/plugins.js#L23-L34 | train |
clay/amphora | lib/services/plugins.js | createDBAdapter | function createDBAdapter() {
var returnObj = {
getMeta,
patchMeta
};
for (const key in db) {
/* istanbul ignore else */
if (db.hasOwnProperty(key) && key.indexOf('Meta') === -1) {
returnObj[key] = db[key];
}
}
return returnObj;
} | javascript | function createDBAdapter() {
var returnObj = {
getMeta,
patchMeta
};
for (const key in db) {
/* istanbul ignore else */
if (db.hasOwnProperty(key) && key.indexOf('Meta') === -1) {
returnObj[key] = db[key];
}
}
return returnObj;
} | [
"function",
"createDBAdapter",
"(",
")",
"{",
"var",
"returnObj",
"=",
"{",
"getMeta",
",",
"patchMeta",
"}",
";",
"for",
"(",
"const",
"key",
"in",
"db",
")",
"{",
"/* istanbul ignore else */",
"if",
"(",
"db",
".",
"hasOwnProperty",
"(",
"key",
")",
"&... | Builds the db object to pass to
the plugin. Needs to use the metadata
functions and not pass along `putMeta`
@returns {Object} | [
"Builds",
"the",
"db",
"object",
"to",
"pass",
"to",
"the",
"plugin",
".",
"Needs",
"to",
"use",
"the",
"metadata",
"functions",
"and",
"not",
"pass",
"along",
"putMeta"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/plugins.js#L43-L57 | train |
clay/amphora | lib/services/bus.js | connect | function connect(busModule) {
if (busModule) {
module.exports.client = busModule.connect();
BUS_MODULE = true;
} else {
log('info', `Connecting to default Redis event bus at ${process.env.CLAY_BUS_HOST}`);
module.exports.client = new Redis(process.env.CLAY_BUS_HOST);
}
} | javascript | function connect(busModule) {
if (busModule) {
module.exports.client = busModule.connect();
BUS_MODULE = true;
} else {
log('info', `Connecting to default Redis event bus at ${process.env.CLAY_BUS_HOST}`);
module.exports.client = new Redis(process.env.CLAY_BUS_HOST);
}
} | [
"function",
"connect",
"(",
"busModule",
")",
"{",
"if",
"(",
"busModule",
")",
"{",
"module",
".",
"exports",
".",
"client",
"=",
"busModule",
".",
"connect",
"(",
")",
";",
"BUS_MODULE",
"=",
"true",
";",
"}",
"else",
"{",
"log",
"(",
"'info'",
","... | Connect to the bus Redis instance
@param {Object} busModule | [
"Connect",
"to",
"the",
"bus",
"Redis",
"instance"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/bus.js#L13-L21 | train |
clay/amphora | lib/services/bus.js | publish | function publish(topic, msg) {
if (!topic || !msg || typeof topic !== 'string' || typeof msg !== 'object') {
throw new Error('A `topic` (string) and `msg` (object) property must be defined');
}
if (module.exports.client && BUS_MODULE) {
module.exports.client.publish(`${NAMESPACE}:${topic}`, msg);
} els... | javascript | function publish(topic, msg) {
if (!topic || !msg || typeof topic !== 'string' || typeof msg !== 'object') {
throw new Error('A `topic` (string) and `msg` (object) property must be defined');
}
if (module.exports.client && BUS_MODULE) {
module.exports.client.publish(`${NAMESPACE}:${topic}`, msg);
} els... | [
"function",
"publish",
"(",
"topic",
",",
"msg",
")",
"{",
"if",
"(",
"!",
"topic",
"||",
"!",
"msg",
"||",
"typeof",
"topic",
"!==",
"'string'",
"||",
"typeof",
"msg",
"!==",
"'object'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'A `topic` (string) and `... | Publish a message to the bus.
@param {String} topic
@param {String} msg | [
"Publish",
"a",
"message",
"to",
"the",
"bus",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/bus.js#L29-L39 | train |
clay/amphora | lib/locals.js | addSiteData | function addSiteData(site) {
return (req, res, next) => {
res.locals.url = uriToUrl(req.hostname + req.originalUrl, site.protocol, site.port);
res.locals.site = site;
next();
};
} | javascript | function addSiteData(site) {
return (req, res, next) => {
res.locals.url = uriToUrl(req.hostname + req.originalUrl, site.protocol, site.port);
res.locals.site = site;
next();
};
} | [
"function",
"addSiteData",
"(",
"site",
")",
"{",
"return",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"res",
".",
"locals",
".",
"url",
"=",
"uriToUrl",
"(",
"req",
".",
"hostname",
"+",
"req",
".",
"originalUrl",
",",
"site",
".",
"prot... | Add site data to locals for each site
@param {Object} site
@returns {Function} | [
"Add",
"site",
"data",
"to",
"locals",
"for",
"each",
"site"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L12-L19 | train |
clay/amphora | lib/locals.js | addQueryParams | function addQueryParams(req, res, next) {
_assign(res.locals, req.params, req.query);
next();
} | javascript | function addQueryParams(req, res, next) {
_assign(res.locals, req.params, req.query);
next();
} | [
"function",
"addQueryParams",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"_assign",
"(",
"res",
".",
"locals",
",",
"req",
".",
"params",
",",
"req",
".",
"query",
")",
";",
"next",
"(",
")",
";",
"}"
] | Adds query params to locals
@param {Object} req
@param {Object} res
@param {Function} next | [
"Adds",
"query",
"params",
"to",
"locals"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L27-L30 | train |
clay/amphora | lib/locals.js | addAvailableRoutes | function addAvailableRoutes(router) {
return (req, res, next) => {
const routes = router.stack
.filter((r) => r.route && r.route.path) // grab only the defined routes (not api stuff)
.map((r) => r.route.path); // pull out their paths
res.locals.routes = routes; // and add them to the locals
n... | javascript | function addAvailableRoutes(router) {
return (req, res, next) => {
const routes = router.stack
.filter((r) => r.route && r.route.path) // grab only the defined routes (not api stuff)
.map((r) => r.route.path); // pull out their paths
res.locals.routes = routes; // and add them to the locals
n... | [
"function",
"addAvailableRoutes",
"(",
"router",
")",
"{",
"return",
"(",
"req",
",",
"res",
",",
"next",
")",
"=>",
"{",
"const",
"routes",
"=",
"router",
".",
"stack",
".",
"filter",
"(",
"(",
"r",
")",
"=>",
"r",
".",
"route",
"&&",
"r",
".",
... | Adds available site routes to locals
@param {express.Router} router
@returns {Function} | [
"Adds",
"available",
"site",
"routes",
"to",
"locals"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L37-L46 | train |
clay/amphora | lib/locals.js | addAvailableComponents | function addAvailableComponents(req, res, next) {
res.locals.components = files.getComponents();
next();
} | javascript | function addAvailableComponents(req, res, next) {
res.locals.components = files.getComponents();
next();
} | [
"function",
"addAvailableComponents",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"locals",
".",
"components",
"=",
"files",
".",
"getComponents",
"(",
")",
";",
"next",
"(",
")",
";",
"}"
] | Adds available components to locals
@param {Object} req
@param {Object} res
@param {Function} next | [
"Adds",
"available",
"components",
"to",
"locals"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L54-L57 | train |
clay/amphora | lib/locals.js | addUser | function addUser(req, res, next) {
res.locals.user = req.user;
next();
} | javascript | function addUser(req, res, next) {
res.locals.user = req.user;
next();
} | [
"function",
"addUser",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"locals",
".",
"user",
"=",
"req",
".",
"user",
";",
"next",
"(",
")",
";",
"}"
] | Adds current user to locals
@param {Object} req
@param {Object} res
@param {Function} next | [
"Adds",
"current",
"user",
"to",
"locals"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/locals.js#L65-L68 | train |
clay/amphora | lib/services/references.js | isPropagatingVersion | function isPropagatingVersion(uri) {
const version = uri.split('@')[1];
return !!version && _.includes(propagatingVersions, version);
} | javascript | function isPropagatingVersion(uri) {
const version = uri.split('@')[1];
return !!version && _.includes(propagatingVersions, version);
} | [
"function",
"isPropagatingVersion",
"(",
"uri",
")",
"{",
"const",
"version",
"=",
"uri",
".",
"split",
"(",
"'@'",
")",
"[",
"1",
"]",
";",
"return",
"!",
"!",
"version",
"&&",
"_",
".",
"includes",
"(",
"propagatingVersions",
",",
"version",
")",
";"... | Some versions should propagate throughout the rest of the data.
@param {string} uri
@returns {boolean} | [
"Some",
"versions",
"should",
"propagate",
"throughout",
"the",
"rest",
"of",
"the",
"data",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/references.js#L60-L64 | train |
clay/amphora | lib/services/references.js | uriToUrl | function uriToUrl(uri, protocol, port) {
// just pretend to start with http; it's overwritten two lines down
const parts = urlParse.parse('http://' + uri);
parts.protocol = protocol || 'http';
parts.port = port || process.env.PORT;
delete parts.host;
if (parts.port &&
(parts.protocol === 'http' && par... | javascript | function uriToUrl(uri, protocol, port) {
// just pretend to start with http; it's overwritten two lines down
const parts = urlParse.parse('http://' + uri);
parts.protocol = protocol || 'http';
parts.port = port || process.env.PORT;
delete parts.host;
if (parts.port &&
(parts.protocol === 'http' && par... | [
"function",
"uriToUrl",
"(",
"uri",
",",
"protocol",
",",
"port",
")",
"{",
"// just pretend to start with http; it's overwritten two lines down",
"const",
"parts",
"=",
"urlParse",
".",
"parse",
"(",
"'http://'",
"+",
"uri",
")",
";",
"parts",
".",
"protocol",
"=... | Take the protocol and port from a sourceUrl and apply them to some uri
@param {string} uri
@param {string} [protocol]
@param {string} [port]
@returns {string} | [
"Take",
"the",
"protocol",
"and",
"port",
"from",
"a",
"sourceUrl",
"and",
"apply",
"them",
"to",
"some",
"uri"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/references.js#L92-L108 | train |
clay/amphora | lib/services/references.js | urlToUri | function urlToUri(url) {
let parts;
if (!isUrl(url)) {
throw new Error('Invalid url ' + url);
}
parts = urlParse.parse(url);
return `${parts.hostname}${decodeURIComponent(parts.path)}`;
} | javascript | function urlToUri(url) {
let parts;
if (!isUrl(url)) {
throw new Error('Invalid url ' + url);
}
parts = urlParse.parse(url);
return `${parts.hostname}${decodeURIComponent(parts.path)}`;
} | [
"function",
"urlToUri",
"(",
"url",
")",
"{",
"let",
"parts",
";",
"if",
"(",
"!",
"isUrl",
"(",
"url",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid url '",
"+",
"url",
")",
";",
"}",
"parts",
"=",
"urlParse",
".",
"parse",
"(",
"url",
... | Remove protocol and port
@param {string} url
@returns {string} | [
"Remove",
"protocol",
"and",
"port"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/references.js#L115-L124 | train |
clay/amphora | lib/services/components.js | put | function put(uri, data, locals) {
let model = files.getComponentModule(getComponentName(uri)),
callHooks = _.get(locals, 'hooks') !== 'false',
result;
if (model && _.isFunction(model.save) && callHooks) {
result = models.put(model, uri, data, locals);
} else {
result = dbOps.putDefaultBehavior(ur... | javascript | function put(uri, data, locals) {
let model = files.getComponentModule(getComponentName(uri)),
callHooks = _.get(locals, 'hooks') !== 'false',
result;
if (model && _.isFunction(model.save) && callHooks) {
result = models.put(model, uri, data, locals);
} else {
result = dbOps.putDefaultBehavior(ur... | [
"function",
"put",
"(",
"uri",
",",
"data",
",",
"locals",
")",
"{",
"let",
"model",
"=",
"files",
".",
"getComponentModule",
"(",
"getComponentName",
"(",
"uri",
")",
")",
",",
"callHooks",
"=",
"_",
".",
"get",
"(",
"locals",
",",
"'hooks'",
")",
"... | Given a component uri, its data and the locals
check if there exists a model.js file for the
component.
If yes, run the model.js. If not, turn the component
data into ops.
@param {String} uri
@param {String} data
@param {Object} [locals]
@returns {Promise} | [
"Given",
"a",
"component",
"uri",
"its",
"data",
"and",
"the",
"locals",
"check",
"if",
"there",
"exists",
"a",
"model",
".",
"js",
"file",
"for",
"the",
"component",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/components.js#L40-L52 | train |
clay/amphora | lib/render.js | getExtension | function getExtension(req) {
return _.get(req, 'params.ext', '') ? req.params.ext.toLowerCase() : renderers.default;
} | javascript | function getExtension(req) {
return _.get(req, 'params.ext', '') ? req.params.ext.toLowerCase() : renderers.default;
} | [
"function",
"getExtension",
"(",
"req",
")",
"{",
"return",
"_",
".",
"get",
"(",
"req",
",",
"'params.ext'",
",",
"''",
")",
"?",
"req",
".",
"params",
".",
"ext",
".",
"toLowerCase",
"(",
")",
":",
"renderers",
".",
"default",
";",
"}"
] | Check the renderers for the request extension. If the
request does not have an extension, grab the default.
@param {Object} req
@return {String} | [
"Check",
"the",
"renderers",
"for",
"the",
"request",
"extension",
".",
"If",
"the",
"request",
"does",
"not",
"have",
"an",
"extension",
"grab",
"the",
"default",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L26-L28 | train |
clay/amphora | lib/render.js | findRenderer | function findRenderer(extension) {
var renderer;
// Default to HTML if you don't have an extension
extension = extension || renderers.default;
// Get the renderer
renderer = _.get(renderers, `${extension}`, null);
if (renderer) {
return renderer;
} else {
return new Error(`Renderer not found for... | javascript | function findRenderer(extension) {
var renderer;
// Default to HTML if you don't have an extension
extension = extension || renderers.default;
// Get the renderer
renderer = _.get(renderers, `${extension}`, null);
if (renderer) {
return renderer;
} else {
return new Error(`Renderer not found for... | [
"function",
"findRenderer",
"(",
"extension",
")",
"{",
"var",
"renderer",
";",
"// Default to HTML if you don't have an extension",
"extension",
"=",
"extension",
"||",
"renderers",
".",
"default",
";",
"// Get the renderer",
"renderer",
"=",
"_",
".",
"get",
"(",
... | Find the renderer so to use for the request.
@param {String|Undefined} extension
@return {Object} | [
"Find",
"the",
"renderer",
"so",
"to",
"use",
"for",
"the",
"request",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L47-L60 | train |
clay/amphora | lib/render.js | renderComponent | function renderComponent(req, res, hrStart) {
var extension = getExtension(req), // Get the extension for the request
renderer = findRenderer(extension), // Determine which renderer we are using
_ref = req.uri,
locals = res.locals,
options = options || {};
if (renderer instanceof Error) {
log('... | javascript | function renderComponent(req, res, hrStart) {
var extension = getExtension(req), // Get the extension for the request
renderer = findRenderer(extension), // Determine which renderer we are using
_ref = req.uri,
locals = res.locals,
options = options || {};
if (renderer instanceof Error) {
log('... | [
"function",
"renderComponent",
"(",
"req",
",",
"res",
",",
"hrStart",
")",
"{",
"var",
"extension",
"=",
"getExtension",
"(",
"req",
")",
",",
"// Get the extension for the request",
"renderer",
"=",
"findRenderer",
"(",
"extension",
")",
",",
"// Determine which... | Render a component via whatever renderer should be used
@param {Object} req
@param {Object} res
@param {Object} hrStart
@return {Promise} | [
"Render",
"a",
"component",
"via",
"whatever",
"renderer",
"should",
"be",
"used"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L70-L92 | train |
clay/amphora | lib/render.js | renderPage | function renderPage(uri, req, res, hrStart) {
const locals = res.locals,
extension = getExtension(req),
renderer = findRenderer(extension);
// Add request route params, request query params
// and the request extension to the locals object
locals.params = req.params;
locals.query = req.query;
local... | javascript | function renderPage(uri, req, res, hrStart) {
const locals = res.locals,
extension = getExtension(req),
renderer = findRenderer(extension);
// Add request route params, request query params
// and the request extension to the locals object
locals.params = req.params;
locals.query = req.query;
local... | [
"function",
"renderPage",
"(",
"uri",
",",
"req",
",",
"res",
",",
"hrStart",
")",
"{",
"const",
"locals",
"=",
"res",
".",
"locals",
",",
"extension",
"=",
"getExtension",
"(",
"req",
")",
",",
"renderer",
"=",
"findRenderer",
"(",
"extension",
")",
"... | Render a page with the appropriate renderer
@param {String} uri
@param {Object} req
@param {Object} res
@param {Object} hrStart
@return {Promise} | [
"Render",
"a",
"page",
"with",
"the",
"appropriate",
"renderer"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L111-L131 | train |
clay/amphora | lib/render.js | renderDynamicRoute | function renderDynamicRoute(pageId) {
return (req, res) => {
const hrStart = process.hrtime(),
site = res.locals.site,
pageUri = `${getExpressRoutePrefix(site)}/_pages/${pageId}@published`;
return module.exports.renderPage(pageUri, req, res, hrStart);
};
} | javascript | function renderDynamicRoute(pageId) {
return (req, res) => {
const hrStart = process.hrtime(),
site = res.locals.site,
pageUri = `${getExpressRoutePrefix(site)}/_pages/${pageId}@published`;
return module.exports.renderPage(pageUri, req, res, hrStart);
};
} | [
"function",
"renderDynamicRoute",
"(",
"pageId",
")",
"{",
"return",
"(",
"req",
",",
"res",
")",
"=>",
"{",
"const",
"hrStart",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"site",
"=",
"res",
".",
"locals",
".",
"site",
",",
"pageUri",
"=",
"`",
... | Given a pageId, render the page directly from a call
to an Express route without trying to match to a uri
directly
@param {String} pageId
@return {Function} | [
"Given",
"a",
"pageId",
"render",
"the",
"page",
"directly",
"from",
"a",
"call",
"to",
"an",
"Express",
"route",
"without",
"trying",
"to",
"match",
"to",
"a",
"uri",
"directly"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L141-L149 | train |
clay/amphora | lib/render.js | formDataFromLayout | function formDataFromLayout(locals, uri) {
return function (result) {
const _layoutRef = result.layout,
pageData = references.omitPageConfiguration(result);
return components.get(_layoutRef, locals)
.then(layout => mapLayoutToPageData(pageData, layout))
.then(mappedData => module.exports.fo... | javascript | function formDataFromLayout(locals, uri) {
return function (result) {
const _layoutRef = result.layout,
pageData = references.omitPageConfiguration(result);
return components.get(_layoutRef, locals)
.then(layout => mapLayoutToPageData(pageData, layout))
.then(mappedData => module.exports.fo... | [
"function",
"formDataFromLayout",
"(",
"locals",
",",
"uri",
")",
"{",
"return",
"function",
"(",
"result",
")",
"{",
"const",
"_layoutRef",
"=",
"result",
".",
"layout",
",",
"pageData",
"=",
"references",
".",
"omitPageConfiguration",
"(",
"result",
")",
"... | Given a page uri, get it from the db, resolve the layout,
map page data to the page ares and then format all the
data for the renderer
@param {Object} locals
@param {String} uri
@return {Function<Promise>} | [
"Given",
"a",
"page",
"uri",
"get",
"it",
"from",
"the",
"db",
"resolve",
"the",
"layout",
"map",
"page",
"data",
"to",
"the",
"page",
"ares",
"and",
"then",
"format",
"all",
"the",
"data",
"for",
"the",
"renderer"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L160-L169 | train |
clay/amphora | lib/render.js | formDataForRenderer | function formDataForRenderer(unresolvedData, { _layoutRef, _ref }, locals) {
return composer.resolveComponentReferences(unresolvedData, locals)
.then((data) => ({
data,
options: { locals, _ref, _layoutRef }
}));
} | javascript | function formDataForRenderer(unresolvedData, { _layoutRef, _ref }, locals) {
return composer.resolveComponentReferences(unresolvedData, locals)
.then((data) => ({
data,
options: { locals, _ref, _layoutRef }
}));
} | [
"function",
"formDataForRenderer",
"(",
"unresolvedData",
",",
"{",
"_layoutRef",
",",
"_ref",
"}",
",",
"locals",
")",
"{",
"return",
"composer",
".",
"resolveComponentReferences",
"(",
"unresolvedData",
",",
"locals",
")",
".",
"then",
"(",
"(",
"data",
")",... | Resolve all references for nested objects and form the
data up in the expected object to send to a renderer
@param {Object} unresolvedData
@param {Object} options
@param {Object} locals
@return {Promise} | [
"Resolve",
"all",
"references",
"for",
"nested",
"objects",
"and",
"form",
"the",
"data",
"up",
"in",
"the",
"expected",
"object",
"to",
"send",
"to",
"a",
"renderer"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L179-L185 | train |
clay/amphora | lib/render.js | getExpressRoutePrefix | function getExpressRoutePrefix(site) {
let prefix = site.host;
if (site.path.length > 1) {
prefix += site.path;
}
return prefix;
} | javascript | function getExpressRoutePrefix(site) {
let prefix = site.host;
if (site.path.length > 1) {
prefix += site.path;
}
return prefix;
} | [
"function",
"getExpressRoutePrefix",
"(",
"site",
")",
"{",
"let",
"prefix",
"=",
"site",
".",
"host",
";",
"if",
"(",
"site",
".",
"path",
".",
"length",
">",
"1",
")",
"{",
"prefix",
"+=",
"site",
".",
"path",
";",
"}",
"return",
"prefix",
";",
"... | Get the prefix that normalizes the slash on the path with the expectation that references to routes using the prefix
will start with a slash as well.
@param {object} site
@returns {string} | [
"Get",
"the",
"prefix",
"that",
"normalizes",
"the",
"slash",
"on",
"the",
"path",
"with",
"the",
"expectation",
"that",
"references",
"to",
"routes",
"using",
"the",
"prefix",
"will",
"start",
"with",
"a",
"slash",
"as",
"well",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L194-L202 | train |
clay/amphora | lib/render.js | renderUri | function renderUri(uri, req, res, hrStart) {
hrStart = hrStart || process.hrtime(); // Check if we actually have a start time
return db.get(uri).then(function (result) {
const route = _.find(uriRoutes, function (item) {
return result.match(item.when);
});
if (!route) {
throw new Error('Inv... | javascript | function renderUri(uri, req, res, hrStart) {
hrStart = hrStart || process.hrtime(); // Check if we actually have a start time
return db.get(uri).then(function (result) {
const route = _.find(uriRoutes, function (item) {
return result.match(item.when);
});
if (!route) {
throw new Error('Inv... | [
"function",
"renderUri",
"(",
"uri",
",",
"req",
",",
"res",
",",
"hrStart",
")",
"{",
"hrStart",
"=",
"hrStart",
"||",
"process",
".",
"hrtime",
"(",
")",
";",
"// Check if we actually have a start time",
"return",
"db",
".",
"get",
"(",
"uri",
")",
".",
... | Redirect to referenced type.
Depending on what the uri references, load something different.
@param {string} uri
@param {object} req
@param {object} res
@param {object} hrStart
@returns {Promise} | [
"Redirect",
"to",
"referenced",
"type",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L215-L242 | train |
clay/amphora | lib/render.js | logTime | function logTime(hrStart, uri) {
return () => {
const diff = process.hrtime(hrStart),
ms = Math.floor((diff[0] * 1e9 + diff[1]) / 1000000);
log('info', `composed data for: ${uri} (${ms}ms)`, {
composeTime: ms,
uri
});
};
} | javascript | function logTime(hrStart, uri) {
return () => {
const diff = process.hrtime(hrStart),
ms = Math.floor((diff[0] * 1e9 + diff[1]) / 1000000);
log('info', `composed data for: ${uri} (${ms}ms)`, {
composeTime: ms,
uri
});
};
} | [
"function",
"logTime",
"(",
"hrStart",
",",
"uri",
")",
"{",
"return",
"(",
")",
"=>",
"{",
"const",
"diff",
"=",
"process",
".",
"hrtime",
"(",
"hrStart",
")",
",",
"ms",
"=",
"Math",
".",
"floor",
"(",
"(",
"diff",
"[",
"0",
"]",
"*",
"1e9",
... | Log the timing for data composition
@param {Object} hrStart
@param {String} uri
@return {Function} | [
"Log",
"the",
"timing",
"for",
"data",
"composition"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L251-L261 | train |
clay/amphora | lib/render.js | renderExpressRoute | function renderExpressRoute(req, res, next) {
var hrStart = process.hrtime(),
site = res.locals.site,
prefix = `${getExpressRoutePrefix(site)}/_uris/`,
pageReference = `${prefix}${buf.encode(req.hostname + req.baseUrl + req.path)}`;
return module.exports.renderUri(pageReference, req, res, hrStart)
... | javascript | function renderExpressRoute(req, res, next) {
var hrStart = process.hrtime(),
site = res.locals.site,
prefix = `${getExpressRoutePrefix(site)}/_uris/`,
pageReference = `${prefix}${buf.encode(req.hostname + req.baseUrl + req.path)}`;
return module.exports.renderUri(pageReference, req, res, hrStart)
... | [
"function",
"renderExpressRoute",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"hrStart",
"=",
"process",
".",
"hrtime",
"(",
")",
",",
"site",
"=",
"res",
".",
"locals",
".",
"site",
",",
"prefix",
"=",
"`",
"${",
"getExpressRoutePrefix",
"("... | Run composer by translating url to a "page" by base64ing it. Errors are handled by Express.
@param {Object} req
@param {Object} res
@param {Function} next
@return {Promise} | [
"Run",
"composer",
"by",
"translating",
"url",
"to",
"a",
"page",
"by",
"base64ing",
"it",
".",
"Errors",
"are",
"handled",
"by",
"Express",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L271-L288 | train |
clay/amphora | lib/render.js | assumePublishedUnlessEditing | function assumePublishedUnlessEditing(fn) {
return function (uri, req, res, hrStart) {
// ignore version if they are editing; default to 'published'
if (!_.get(res, 'req.query.edit')) {
uri = clayUtils.replaceVersion(uri, uri.split('@')[1] || 'published');
}
return fn(uri, req, res, hrStart);
... | javascript | function assumePublishedUnlessEditing(fn) {
return function (uri, req, res, hrStart) {
// ignore version if they are editing; default to 'published'
if (!_.get(res, 'req.query.edit')) {
uri = clayUtils.replaceVersion(uri, uri.split('@')[1] || 'published');
}
return fn(uri, req, res, hrStart);
... | [
"function",
"assumePublishedUnlessEditing",
"(",
"fn",
")",
"{",
"return",
"function",
"(",
"uri",
",",
"req",
",",
"res",
",",
"hrStart",
")",
"{",
"// ignore version if they are editing; default to 'published'",
"if",
"(",
"!",
"_",
".",
"get",
"(",
"res",
","... | Assume they're talking about published content unless ?edit
@param {function} fn
@returns {function} | [
"Assume",
"they",
"re",
"talking",
"about",
"published",
"content",
"unless",
"?edit"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L296-L305 | train |
clay/amphora | lib/render.js | resetUriRouteHandlers | function resetUriRouteHandlers() {
/**
* URIs can point to many different things, and this list will probably grow.
* @type {[{when: RegExp, html: function, json: function}]}
*/
uriRoutes = [
// assume published
{
when: /\/_pages\//,
default: assumePublishedUnlessEditing(renderPage),
... | javascript | function resetUriRouteHandlers() {
/**
* URIs can point to many different things, and this list will probably grow.
* @type {[{when: RegExp, html: function, json: function}]}
*/
uriRoutes = [
// assume published
{
when: /\/_pages\//,
default: assumePublishedUnlessEditing(renderPage),
... | [
"function",
"resetUriRouteHandlers",
"(",
")",
"{",
"/**\n * URIs can point to many different things, and this list will probably grow.\n * @type {[{when: RegExp, html: function, json: function}]}\n */",
"uriRoutes",
"=",
"[",
"// assume published",
"{",
"when",
":",
"/",
"\\/_page... | Uris route as following | [
"Uris",
"route",
"as",
"following"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/render.js#L327-L352 | train |
clay/amphora | lib/routes.js | addAuthenticationRoutes | function addAuthenticationRoutes(router) {
const authRouter = express.Router();
authRouter.use(require('body-parser').json({ strict: true, type: 'application/json', limit: '50mb' }));
authRouter.use(require('body-parser').text({ type: 'text/*' }));
amphoraAuth.addRoutes(authRouter);
router.use('/_users', aut... | javascript | function addAuthenticationRoutes(router) {
const authRouter = express.Router();
authRouter.use(require('body-parser').json({ strict: true, type: 'application/json', limit: '50mb' }));
authRouter.use(require('body-parser').text({ type: 'text/*' }));
amphoraAuth.addRoutes(authRouter);
router.use('/_users', aut... | [
"function",
"addAuthenticationRoutes",
"(",
"router",
")",
"{",
"const",
"authRouter",
"=",
"express",
".",
"Router",
"(",
")",
";",
"authRouter",
".",
"use",
"(",
"require",
"(",
"'body-parser'",
")",
".",
"json",
"(",
"{",
"strict",
":",
"true",
",",
"... | Add routes from the authentication module that
can be passed in. If no module is passed in at
instantiation time then use the default auth module.
@param {express.Router} router | [
"Add",
"routes",
"from",
"the",
"authentication",
"module",
"that",
"can",
"be",
"passed",
"in",
".",
"If",
"no",
"module",
"is",
"passed",
"in",
"at",
"instantiation",
"time",
"then",
"use",
"the",
"default",
"auth",
"module",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/routes.js#L90-L97 | train |
clay/amphora | lib/routes.js | addSiteController | function addSiteController(router, site, providers) {
if (site.dir) {
const controller = files.tryRequire(site.dir);
if (controller) {
if (Array.isArray(controller.middleware)) {
router.use(controller.middleware);
}
if (Array.isArray(controller.routes)) {
attachRoutes(route... | javascript | function addSiteController(router, site, providers) {
if (site.dir) {
const controller = files.tryRequire(site.dir);
if (controller) {
if (Array.isArray(controller.middleware)) {
router.use(controller.middleware);
}
if (Array.isArray(controller.routes)) {
attachRoutes(route... | [
"function",
"addSiteController",
"(",
"router",
",",
"site",
",",
"providers",
")",
"{",
"if",
"(",
"site",
".",
"dir",
")",
"{",
"const",
"controller",
"=",
"files",
".",
"tryRequire",
"(",
"site",
".",
"dir",
")",
";",
"if",
"(",
"controller",
")",
... | Default way to load site controllers.
@param {express.Router} router
@param {Object} site
@param {Array} providers
@returns {express.Router} | [
"Default",
"way",
"to",
"load",
"site",
"controllers",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/routes.js#L131-L157 | train |
clay/amphora | lib/routes.js | loadFromConfig | function loadFromConfig(router, providers, sessionStore) {
const sitesMap = siteService.sites(),
siteHosts = _.uniq(_.map(sitesMap, 'host'));
// iterate through the hosts
_.each(siteHosts, hostname => {
const sites = _.filter(sitesMap, {host: hostname}).sort(sortByDepthOfPath);
addHost({
route... | javascript | function loadFromConfig(router, providers, sessionStore) {
const sitesMap = siteService.sites(),
siteHosts = _.uniq(_.map(sitesMap, 'host'));
// iterate through the hosts
_.each(siteHosts, hostname => {
const sites = _.filter(sitesMap, {host: hostname}).sort(sortByDepthOfPath);
addHost({
route... | [
"function",
"loadFromConfig",
"(",
"router",
",",
"providers",
",",
"sessionStore",
")",
"{",
"const",
"sitesMap",
"=",
"siteService",
".",
"sites",
"(",
")",
",",
"siteHosts",
"=",
"_",
".",
"uniq",
"(",
"_",
".",
"map",
"(",
"sitesMap",
",",
"'host'",
... | Loads sites config and attach the basic routes for each one.
@param {express.Router} router - Often an express app.
@param {Array} [providers]
@param {Object} [sessionStore]
@returns {*}
@example
var app = express();
require('./routes)(app); | [
"Loads",
"sites",
"config",
"and",
"attach",
"the",
"basic",
"routes",
"for",
"each",
"one",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/routes.js#L307-L325 | train |
clay/amphora | lib/bootstrap.js | getConfig | function getConfig(dir) {
dir = path.resolve(dir);
if (dir.indexOf('.', 2) > 0) {
// remove extension
dir = dir.substring(0, dir.indexOf('.', 2));
}
if (files.isDirectory(dir)) {
// default to bootstrap.yaml or bootstrap.yml
dir = path.join(dir, 'bootstrap');
}
return files.getYaml(dir);
... | javascript | function getConfig(dir) {
dir = path.resolve(dir);
if (dir.indexOf('.', 2) > 0) {
// remove extension
dir = dir.substring(0, dir.indexOf('.', 2));
}
if (files.isDirectory(dir)) {
// default to bootstrap.yaml or bootstrap.yml
dir = path.join(dir, 'bootstrap');
}
return files.getYaml(dir);
... | [
"function",
"getConfig",
"(",
"dir",
")",
"{",
"dir",
"=",
"path",
".",
"resolve",
"(",
"dir",
")",
";",
"if",
"(",
"dir",
".",
"indexOf",
"(",
"'.'",
",",
"2",
")",
">",
"0",
")",
"{",
"// remove extension",
"dir",
"=",
"dir",
".",
"substring",
... | Get yaml file as object
@param {string} dir
@returns {object} | [
"Get",
"yaml",
"file",
"as",
"object"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L30-L44 | train |
clay/amphora | lib/bootstrap.js | saveWithInstances | function saveWithInstances(dbPath, list, save) {
const promises = [];
// load item defaults
_.each(list, function (item, itemName) {
let obj = _.omit(item, 'instances');
if (_.isObject(item)) {
obj = _.omit(item, 'instances');
if (_.size(obj) > 0) {
promises.push(save(dbPath + itemN... | javascript | function saveWithInstances(dbPath, list, save) {
const promises = [];
// load item defaults
_.each(list, function (item, itemName) {
let obj = _.omit(item, 'instances');
if (_.isObject(item)) {
obj = _.omit(item, 'instances');
if (_.size(obj) > 0) {
promises.push(save(dbPath + itemN... | [
"function",
"saveWithInstances",
"(",
"dbPath",
",",
"list",
",",
"save",
")",
"{",
"const",
"promises",
"=",
"[",
"]",
";",
"// load item defaults",
"_",
".",
"each",
"(",
"list",
",",
"function",
"(",
"item",
",",
"itemName",
")",
"{",
"let",
"obj",
... | Component specific loading.
@param {string} dbPath
@param {object} list
@param {function} save
@returns {Promise} | [
"Component",
"specific",
"loading",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L68-L94 | train |
clay/amphora | lib/bootstrap.js | saveBase64Strings | function saveBase64Strings(dbPath, list, save) {
return bluebird.all(_.map(list, function (item, itemName) {
return save(dbPath + buf.encode(itemName), item);
}));
} | javascript | function saveBase64Strings(dbPath, list, save) {
return bluebird.all(_.map(list, function (item, itemName) {
return save(dbPath + buf.encode(itemName), item);
}));
} | [
"function",
"saveBase64Strings",
"(",
"dbPath",
",",
"list",
",",
"save",
")",
"{",
"return",
"bluebird",
".",
"all",
"(",
"_",
".",
"map",
"(",
"list",
",",
"function",
"(",
"item",
",",
"itemName",
")",
"{",
"return",
"save",
"(",
"dbPath",
"+",
"b... | Page specific loading. This will probably grow differently than component loading, so different function to
contain it.
@param {string} dbPath
@param {object} list
@param {function} save
@returns {Promise} | [
"Page",
"specific",
"loading",
".",
"This",
"will",
"probably",
"grow",
"differently",
"than",
"component",
"loading",
"so",
"different",
"function",
"to",
"contain",
"it",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L104-L108 | train |
clay/amphora | lib/bootstrap.js | load | function load(data, site) {
let promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps,
prefix = site.prefix,
compData = applyPrefix(data, site);
promiseListsOps = saveObjects(`${prefix}/_lists/`, compData._lists, getPutOperation);
promiseUrisOps = saveBase64Strings(`${pr... | javascript | function load(data, site) {
let promiseComponentsOps, promisePagesOps, promiseUrisOps, promiseListsOps, promiseUsersOps,
prefix = site.prefix,
compData = applyPrefix(data, site);
promiseListsOps = saveObjects(`${prefix}/_lists/`, compData._lists, getPutOperation);
promiseUrisOps = saveBase64Strings(`${pr... | [
"function",
"load",
"(",
"data",
",",
"site",
")",
"{",
"let",
"promiseComponentsOps",
",",
"promisePagesOps",
",",
"promiseUrisOps",
",",
"promiseListsOps",
",",
"promiseUsersOps",
",",
"prefix",
"=",
"site",
".",
"prefix",
",",
"compData",
"=",
"applyPrefix",
... | Load items into db from config object
@param {object} data
@param {object} site
@returns {Promise} | [
"Load",
"items",
"into",
"db",
"from",
"config",
"object"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L208-L233 | train |
clay/amphora | lib/bootstrap.js | bootstrapPath | function bootstrapPath(dir, site) {
let promise,
data = getConfig(dir);
if (data) {
promise = load(data, site);
} else {
promise = Promise.reject(new Error(`No bootstrap found at ${dir}`));
}
return promise;
} | javascript | function bootstrapPath(dir, site) {
let promise,
data = getConfig(dir);
if (data) {
promise = load(data, site);
} else {
promise = Promise.reject(new Error(`No bootstrap found at ${dir}`));
}
return promise;
} | [
"function",
"bootstrapPath",
"(",
"dir",
",",
"site",
")",
"{",
"let",
"promise",
",",
"data",
"=",
"getConfig",
"(",
"dir",
")",
";",
"if",
"(",
"data",
")",
"{",
"promise",
"=",
"load",
"(",
"data",
",",
"site",
")",
";",
"}",
"else",
"{",
"pro... | Load items into db from yaml file
@param {string} dir
@param {object} site
@returns {Promise} | [
"Load",
"items",
"into",
"db",
"from",
"yaml",
"file"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L241-L252 | train |
clay/amphora | lib/bootstrap.js | bootstrapError | function bootstrapError(component, e) {
if (ERRORING_COMPONENTS.indexOf(component) === -1) {
ERRORING_COMPONENTS.push(component);
log('error', `Error bootstrapping component ${component}: ${e.message}`);
}
return bluebird.reject();
} | javascript | function bootstrapError(component, e) {
if (ERRORING_COMPONENTS.indexOf(component) === -1) {
ERRORING_COMPONENTS.push(component);
log('error', `Error bootstrapping component ${component}: ${e.message}`);
}
return bluebird.reject();
} | [
"function",
"bootstrapError",
"(",
"component",
",",
"e",
")",
"{",
"if",
"(",
"ERRORING_COMPONENTS",
".",
"indexOf",
"(",
"component",
")",
"===",
"-",
"1",
")",
"{",
"ERRORING_COMPONENTS",
".",
"push",
"(",
"component",
")",
";",
"log",
"(",
"'error'",
... | Log a bootstrapping error for if one exists
for a component.
@param {String} component
@param {Error} e
@return {Promise} | [
"Log",
"a",
"bootstrapping",
"error",
"for",
"if",
"one",
"exists",
"for",
"a",
"component",
"."
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L274-L281 | train |
clay/amphora | lib/bootstrap.js | bootrapSitesAndComponents | function bootrapSitesAndComponents() {
const sites = siteService.sites(),
sitesArray = _.map(Object.keys(sites), site => sites[site]);
return highland(sitesArray)
.flatMap(site => {
return highland(
bootstrapComponents(site)
.then(function () {
return site;
})
... | javascript | function bootrapSitesAndComponents() {
const sites = siteService.sites(),
sitesArray = _.map(Object.keys(sites), site => sites[site]);
return highland(sitesArray)
.flatMap(site => {
return highland(
bootstrapComponents(site)
.then(function () {
return site;
})
... | [
"function",
"bootrapSitesAndComponents",
"(",
")",
"{",
"const",
"sites",
"=",
"siteService",
".",
"sites",
"(",
")",
",",
"sitesArray",
"=",
"_",
".",
"map",
"(",
"Object",
".",
"keys",
"(",
"sites",
")",
",",
"site",
"=>",
"sites",
"[",
"site",
"]",
... | Bootstrap all sites and the individual
bootstrap files in each component's directory
@return {Promise} | [
"Bootstrap",
"all",
"sites",
"and",
"the",
"individual",
"bootstrap",
"files",
"in",
"each",
"component",
"s",
"directory"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/bootstrap.js#L289-L317 | train |
clay/amphora | lib/services/db-operations.js | replacePropagatingVersions | function replacePropagatingVersions(uri, data) {
if (references.isPropagatingVersion(uri)) {
references.replaceAllVersions(uri.split('@')[1])(data);
}
return data;
} | javascript | function replacePropagatingVersions(uri, data) {
if (references.isPropagatingVersion(uri)) {
references.replaceAllVersions(uri.split('@')[1])(data);
}
return data;
} | [
"function",
"replacePropagatingVersions",
"(",
"uri",
",",
"data",
")",
"{",
"if",
"(",
"references",
".",
"isPropagatingVersion",
"(",
"uri",
")",
")",
"{",
"references",
".",
"replaceAllVersions",
"(",
"uri",
".",
"split",
"(",
"'@'",
")",
"[",
"1",
"]",... | If the ref has a version that is "propagating" like @published or @latest, replace all versions in the data
with the new version (in-place).
@param {string} uri
@param {object} data
@returns {object} | [
"If",
"the",
"ref",
"has",
"a",
"version",
"that",
"is",
"propagating",
"like"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/db-operations.js#L45-L51 | train |
clay/amphora | lib/services/db-operations.js | splitCascadingData | function splitCascadingData(uri, data) {
let ops, list;
// search for _ref with _size greater than 1
list = references.listDeepObjects(data, isReferencedAndReal);
ops = _.map(list.reverse(), function (obj) {
const ref = obj[referenceProperty],
// since children are before parents, no one will see dat... | javascript | function splitCascadingData(uri, data) {
let ops, list;
// search for _ref with _size greater than 1
list = references.listDeepObjects(data, isReferencedAndReal);
ops = _.map(list.reverse(), function (obj) {
const ref = obj[referenceProperty],
// since children are before parents, no one will see dat... | [
"function",
"splitCascadingData",
"(",
"uri",
",",
"data",
")",
"{",
"let",
"ops",
",",
"list",
";",
"// search for _ref with _size greater than 1",
"list",
"=",
"references",
".",
"listDeepObjects",
"(",
"data",
",",
"isReferencedAndReal",
")",
";",
"ops",
"=",
... | Split cascading component data into individual components
@param {string} uri Root reference in uri form
@param {object} data Cascading component data
@returns {[{key: string, value: object}]} | [
"Split",
"cascading",
"component",
"data",
"into",
"individual",
"components"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/db-operations.js#L59-L81 | train |
clay/amphora | lib/services/db-operations.js | getPutOperations | function getPutOperations(putFn, uri, data, locals) {
// potentially propagate version throughout object
const cmptOrLayout = splitCascadingData(uri, replacePropagatingVersions(uri, data));
// if locals exist and there are more than one component being put,
// then we should pass a read-only version to each co... | javascript | function getPutOperations(putFn, uri, data, locals) {
// potentially propagate version throughout object
const cmptOrLayout = splitCascadingData(uri, replacePropagatingVersions(uri, data));
// if locals exist and there are more than one component being put,
// then we should pass a read-only version to each co... | [
"function",
"getPutOperations",
"(",
"putFn",
",",
"uri",
",",
"data",
",",
"locals",
")",
"{",
"// potentially propagate version throughout object",
"const",
"cmptOrLayout",
"=",
"splitCascadingData",
"(",
"uri",
",",
"replacePropagatingVersions",
"(",
"uri",
",",
"d... | Get a list of all the put operations needed to complete a cascading PUT
NOTE: this function changes the data object _in-place_ for speed and memory reasons. We are not okay with doing
a deep clone here, because that will significantly slow down this operation. If someone wants to deep clone the data
before this opera... | [
"Get",
"a",
"list",
"of",
"all",
"the",
"put",
"operations",
"needed",
"to",
"complete",
"a",
"cascading",
"PUT"
] | b883a94cbc38c1891ce568addb6cb280aa1d5353 | https://github.com/clay/amphora/blob/b883a94cbc38c1891ce568addb6cb280aa1d5353/lib/services/db-operations.js#L96-L110 | train |
gregtillbrook/parcel-plugin-bundle-visualiser | src/buildReportAssets/init.js | function(e) {
e.preventDefault();
var group = e.group;
var toZoom;
if (group) {
toZoom = e.secondary ? group.parent : group;
} else {
toZoom = this.get('dataObject');
}
this.zoom(toZoom);
} | javascript | function(e) {
e.preventDefault();
var group = e.group;
var toZoom;
if (group) {
toZoom = e.secondary ? group.parent : group;
} else {
toZoom = this.get('dataObject');
}
this.zoom(toZoom);
} | [
"function",
"(",
"e",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"var",
"group",
"=",
"e",
".",
"group",
";",
"var",
"toZoom",
";",
"if",
"(",
"group",
")",
"{",
"toZoom",
"=",
"e",
".",
"secondary",
"?",
"group",
".",
"parent",
":",
... | zoom to group rather than that weird pop out thing | [
"zoom",
"to",
"group",
"rather",
"than",
"that",
"weird",
"pop",
"out",
"thing"
] | ca5440fc61c85e40e7abc220ad99e274c7c104c6 | https://github.com/gregtillbrook/parcel-plugin-bundle-visualiser/blob/ca5440fc61c85e40e7abc220ad99e274c7c104c6/src/buildReportAssets/init.js#L34-L44 | train | |
gregtillbrook/parcel-plugin-bundle-visualiser | src/buildTreeData.js | formatProjectPath | function formatProjectPath(filePath = '') {
let dir = path.relative(process.cwd(), path.dirname(filePath));
return dir + (dir ? path.sep : '') + path.basename(filePath);
} | javascript | function formatProjectPath(filePath = '') {
let dir = path.relative(process.cwd(), path.dirname(filePath));
return dir + (dir ? path.sep : '') + path.basename(filePath);
} | [
"function",
"formatProjectPath",
"(",
"filePath",
"=",
"''",
")",
"{",
"let",
"dir",
"=",
"path",
".",
"relative",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"path",
".",
"dirname",
"(",
"filePath",
")",
")",
";",
"return",
"dir",
"+",
"(",
"dir",
... | path relative to project root | [
"path",
"relative",
"to",
"project",
"root"
] | ca5440fc61c85e40e7abc220ad99e274c7c104c6 | https://github.com/gregtillbrook/parcel-plugin-bundle-visualiser/blob/ca5440fc61c85e40e7abc220ad99e274c7c104c6/src/buildTreeData.js#L132-L135 | train |
jdalton/docdown | lib/util.js | format | function format(string) {
string = _.toString(string);
// Replace all code snippets with a token.
var snippets = [];
string = string.replace(reCode, function(match) {
snippets.push(match);
return token;
});
return string
// Add line breaks.
.replace(/:\n(?=[\t ]*\S)/g, ':<br>\n')
.repl... | javascript | function format(string) {
string = _.toString(string);
// Replace all code snippets with a token.
var snippets = [];
string = string.replace(reCode, function(match) {
snippets.push(match);
return token;
});
return string
// Add line breaks.
.replace(/:\n(?=[\t ]*\S)/g, ':<br>\n')
.repl... | [
"function",
"format",
"(",
"string",
")",
"{",
"string",
"=",
"_",
".",
"toString",
"(",
"string",
")",
";",
"// Replace all code snippets with a token.",
"var",
"snippets",
"=",
"[",
"]",
";",
"string",
"=",
"string",
".",
"replace",
"(",
"reCode",
",",
"... | Performs common string formatting operations.
@memberOf util
@param {string} string The string to format.
@returns {string} Returns the formatted string. | [
"Performs",
"common",
"string",
"formatting",
"operations",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/util.js#L50-L76 | train |
jdalton/docdown | index.js | docdown | function docdown(options) {
options = _.defaults(options, {
'lang': 'js',
'sort': true,
'style': 'default',
'title': path.basename(options.path) + ' API documentation',
'toc': 'properties'
});
if (!options.path || !options.url) {
throw new Error('Path and URL must be specified');
}
re... | javascript | function docdown(options) {
options = _.defaults(options, {
'lang': 'js',
'sort': true,
'style': 'default',
'title': path.basename(options.path) + ' API documentation',
'toc': 'properties'
});
if (!options.path || !options.url) {
throw new Error('Path and URL must be specified');
}
re... | [
"function",
"docdown",
"(",
"options",
")",
"{",
"options",
"=",
"_",
".",
"defaults",
"(",
"options",
",",
"{",
"'lang'",
":",
"'js'",
",",
"'sort'",
":",
"true",
",",
"'style'",
":",
"'default'",
",",
"'title'",
":",
"path",
".",
"basename",
"(",
"... | Generates Markdown documentation based on JSDoc comments.
@param {Object} options The options object.
@param {string} options.path The input file path.
@param {string} options.url The source URL.
@param {string} [options.lang='js'] The language indicator for code blocks.
@param {boolean} [options.sort=true] Specify wh... | [
"Generates",
"Markdown",
"documentation",
"based",
"on",
"JSDoc",
"comments",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/index.js#L26-L39 | train |
jdalton/docdown | lib/entry.js | getTag | function getTag(entry, tagName) {
var parsed = entry.parsed;
return _.find(parsed.tags, ['title', tagName]) || null;
} | javascript | function getTag(entry, tagName) {
var parsed = entry.parsed;
return _.find(parsed.tags, ['title', tagName]) || null;
} | [
"function",
"getTag",
"(",
"entry",
",",
"tagName",
")",
"{",
"var",
"parsed",
"=",
"entry",
".",
"parsed",
";",
"return",
"_",
".",
"find",
"(",
"parsed",
".",
"tags",
",",
"[",
"'title'",
",",
"tagName",
"]",
")",
"||",
"null",
";",
"}"
] | Gets an `entry` tag by `tagName`.
@private
@param {Object} entry The entry to inspect.
@param {string} tagName The name of the tag.
@returns {null|Object} Returns the tag. | [
"Gets",
"an",
"entry",
"tag",
"by",
"tagName",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L72-L75 | train |
jdalton/docdown | lib/entry.js | getValue | function getValue(entry, tagName) {
var parsed = entry.parsed,
result = parsed.description,
tag = getTag(entry, tagName);
if (tagName == 'alias') {
result = _.get(tag, 'name') ;
// Doctrine can't parse alias tags containing multiple values so extract
// them from the error message.
var... | javascript | function getValue(entry, tagName) {
var parsed = entry.parsed,
result = parsed.description,
tag = getTag(entry, tagName);
if (tagName == 'alias') {
result = _.get(tag, 'name') ;
// Doctrine can't parse alias tags containing multiple values so extract
// them from the error message.
var... | [
"function",
"getValue",
"(",
"entry",
",",
"tagName",
")",
"{",
"var",
"parsed",
"=",
"entry",
".",
"parsed",
",",
"result",
"=",
"parsed",
".",
"description",
",",
"tag",
"=",
"getTag",
"(",
"entry",
",",
"tagName",
")",
";",
"if",
"(",
"tagName",
"... | Gets an `entry` tag value by `tagName`.
@private
@param {Object} entry The entry to inspect.
@param {string} tagName The name of the tag.
@returns {string} Returns the tag value. | [
"Gets",
"an",
"entry",
"tag",
"value",
"by",
"tagName",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L85-L109 | train |
jdalton/docdown | lib/entry.js | getAliases | function getAliases(index) {
if (this._aliases === undefined) {
var owner = this;
this._aliases = _(getValue(this, 'alias'))
.split(/,\s*/)
.compact()
.sort(util.compareNatural)
.map(function(value) { return new Alias(value, owner); })
.value();
}
var result = this._aliases;
... | javascript | function getAliases(index) {
if (this._aliases === undefined) {
var owner = this;
this._aliases = _(getValue(this, 'alias'))
.split(/,\s*/)
.compact()
.sort(util.compareNatural)
.map(function(value) { return new Alias(value, owner); })
.value();
}
var result = this._aliases;
... | [
"function",
"getAliases",
"(",
"index",
")",
"{",
"if",
"(",
"this",
".",
"_aliases",
"===",
"undefined",
")",
"{",
"var",
"owner",
"=",
"this",
";",
"this",
".",
"_aliases",
"=",
"_",
"(",
"getValue",
"(",
"this",
",",
"'alias'",
")",
")",
".",
"s... | Extracts the entry's `alias` objects.
@memberOf Entry
@param {number} index The index of the array value to return.
@returns {Array|string} Returns the entry's `alias` objects. | [
"Extracts",
"the",
"entry",
"s",
"alias",
"objects",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L191-L203 | train |
jdalton/docdown | lib/entry.js | getCall | function getCall() {
var result = _.trim(_.get(/\*\/\s*(?:function\s+)?([^\s(]+)\s*\(/.exec(this.entry), 1));
if (!result) {
result = _.trim(_.get(/\*\/\s*(.*?)[:=,]/.exec(this.entry), 1));
result = /['"]$/.test(result)
? _.trim(result, '"\'')
: result.split('.').pop().split(/^(?:const|let|var) ... | javascript | function getCall() {
var result = _.trim(_.get(/\*\/\s*(?:function\s+)?([^\s(]+)\s*\(/.exec(this.entry), 1));
if (!result) {
result = _.trim(_.get(/\*\/\s*(.*?)[:=,]/.exec(this.entry), 1));
result = /['"]$/.test(result)
? _.trim(result, '"\'')
: result.split('.').pop().split(/^(?:const|let|var) ... | [
"function",
"getCall",
"(",
")",
"{",
"var",
"result",
"=",
"_",
".",
"trim",
"(",
"_",
".",
"get",
"(",
"/",
"\\*\\/\\s*(?:function\\s+)?([^\\s(]+)\\s*\\(",
"/",
".",
"exec",
"(",
"this",
".",
"entry",
")",
",",
"1",
")",
")",
";",
"if",
"(",
"!",
... | Extracts the function call from the entry.
@memberOf Entry
@returns {string} Returns the function call. | [
"Extracts",
"the",
"function",
"call",
"from",
"the",
"entry",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L211-L243 | train |
jdalton/docdown | lib/entry.js | getDesc | function getDesc() {
var type = this.getType(),
result = getValue(this, 'description');
return (!result || type == 'Function' || type == 'unknown')
? result
: ('(' + _.trim(type.replace(/\|/g, ', '), '()') + '): ' + result);
} | javascript | function getDesc() {
var type = this.getType(),
result = getValue(this, 'description');
return (!result || type == 'Function' || type == 'unknown')
? result
: ('(' + _.trim(type.replace(/\|/g, ', '), '()') + '): ' + result);
} | [
"function",
"getDesc",
"(",
")",
"{",
"var",
"type",
"=",
"this",
".",
"getType",
"(",
")",
",",
"result",
"=",
"getValue",
"(",
"this",
",",
"'description'",
")",
";",
"return",
"(",
"!",
"result",
"||",
"type",
"==",
"'Function'",
"||",
"type",
"==... | Extracts the entry's description.
@memberOf Entry
@returns {string} Returns the entry's description. | [
"Extracts",
"the",
"entry",
"s",
"description",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L262-L269 | train |
jdalton/docdown | lib/entry.js | getHash | function getHash(style) {
var result = _.toString(this.getMembers(0));
if (style == 'github') {
if (result) {
result += this.isPlugin() ? 'prototype' : '';
}
result += this.getCall();
return result
.replace(/[\\.=|'"(){}\[\]\t ]/g, '')
.replace(/[#,]+/g, '-')
.toLowerCase();
... | javascript | function getHash(style) {
var result = _.toString(this.getMembers(0));
if (style == 'github') {
if (result) {
result += this.isPlugin() ? 'prototype' : '';
}
result += this.getCall();
return result
.replace(/[\\.=|'"(){}\[\]\t ]/g, '')
.replace(/[#,]+/g, '-')
.toLowerCase();
... | [
"function",
"getHash",
"(",
"style",
")",
"{",
"var",
"result",
"=",
"_",
".",
"toString",
"(",
"this",
".",
"getMembers",
"(",
"0",
")",
")",
";",
"if",
"(",
"style",
"==",
"'github'",
")",
"{",
"if",
"(",
"result",
")",
"{",
"result",
"+=",
"th... | Extracts the entry's hash value for permalinking.
@memberOf Entry
@param {string} [style] The hash style.
@returns {string} Returns the entry's hash value (without a hash itself). | [
"Extracts",
"the",
"entry",
"s",
"hash",
"value",
"for",
"permalinking",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L289-L308 | train |
jdalton/docdown | lib/entry.js | getLineNumber | function getLineNumber() {
var lines = this.source
.slice(0, this.source.indexOf(this.entry) + this.entry.length)
.match(/\n/g)
.slice(1);
// Offset by 2 because the first line number is before a line break and the
// last line doesn't include a line break.
return lines.length + 2;
} | javascript | function getLineNumber() {
var lines = this.source
.slice(0, this.source.indexOf(this.entry) + this.entry.length)
.match(/\n/g)
.slice(1);
// Offset by 2 because the first line number is before a line break and the
// last line doesn't include a line break.
return lines.length + 2;
} | [
"function",
"getLineNumber",
"(",
")",
"{",
"var",
"lines",
"=",
"this",
".",
"source",
".",
"slice",
"(",
"0",
",",
"this",
".",
"source",
".",
"indexOf",
"(",
"this",
".",
"entry",
")",
"+",
"this",
".",
"entry",
".",
"length",
")",
".",
"match",... | Resolves the entry's line number.
@memberOf Entry
@returns {number} Returns the entry's line number. | [
"Resolves",
"the",
"entry",
"s",
"line",
"number",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L316-L325 | train |
jdalton/docdown | lib/entry.js | getMembers | function getMembers(index) {
if (this._members === undefined) {
this._members = _(getValue(this, 'member') || getValue(this, 'memberOf'))
.split(/,\s*/)
.compact()
.sort(util.compareNatural)
.value();
}
var result = this._members;
return index === undefined ? result : result[index];
... | javascript | function getMembers(index) {
if (this._members === undefined) {
this._members = _(getValue(this, 'member') || getValue(this, 'memberOf'))
.split(/,\s*/)
.compact()
.sort(util.compareNatural)
.value();
}
var result = this._members;
return index === undefined ? result : result[index];
... | [
"function",
"getMembers",
"(",
"index",
")",
"{",
"if",
"(",
"this",
".",
"_members",
"===",
"undefined",
")",
"{",
"this",
".",
"_members",
"=",
"_",
"(",
"getValue",
"(",
"this",
",",
"'member'",
")",
"||",
"getValue",
"(",
"this",
",",
"'memberOf'",... | Extracts the entry's `member` data.
@memberOf Entry
@param {number} [index] The index of the array value to return.
@returns {Array|string} Returns the entry's `member` data. | [
"Extracts",
"the",
"entry",
"s",
"member",
"data",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L334-L344 | train |
jdalton/docdown | lib/entry.js | getParams | function getParams(index) {
if (this._params === undefined) {
this._params = _(this.parsed.tags)
.filter(['title', 'param'])
.filter('name')
.map(function(tag) {
var defaultValue = tag['default'],
desc = util.format(tag.description),
name = _.toString(tag.name),
... | javascript | function getParams(index) {
if (this._params === undefined) {
this._params = _(this.parsed.tags)
.filter(['title', 'param'])
.filter('name')
.map(function(tag) {
var defaultValue = tag['default'],
desc = util.format(tag.description),
name = _.toString(tag.name),
... | [
"function",
"getParams",
"(",
"index",
")",
"{",
"if",
"(",
"this",
".",
"_params",
"===",
"undefined",
")",
"{",
"this",
".",
"_params",
"=",
"_",
"(",
"this",
".",
"parsed",
".",
"tags",
")",
".",
"filter",
"(",
"[",
"'title'",
",",
"'param'",
"]... | Extracts the entry's `param` data.
@memberOf Entry
@param {number} [index] The index of the array value to return.
@returns {Array} Returns the entry's `param` data. | [
"Extracts",
"the",
"entry",
"s",
"param",
"data",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L365-L388 | train |
jdalton/docdown | lib/entry.js | getRelated | function getRelated() {
var relatedValues = getValue(this, 'see');
if (relatedValues && relatedValues.trim().length > 0) {
var relatedItems = relatedValues.split(',').map((relatedItem) => relatedItem.trim());
return relatedItems.map((relatedItem) => '[' + relatedItem + '](#' + relatedItem + ')');
} else {... | javascript | function getRelated() {
var relatedValues = getValue(this, 'see');
if (relatedValues && relatedValues.trim().length > 0) {
var relatedItems = relatedValues.split(',').map((relatedItem) => relatedItem.trim());
return relatedItems.map((relatedItem) => '[' + relatedItem + '](#' + relatedItem + ')');
} else {... | [
"function",
"getRelated",
"(",
")",
"{",
"var",
"relatedValues",
"=",
"getValue",
"(",
"this",
",",
"'see'",
")",
";",
"if",
"(",
"relatedValues",
"&&",
"relatedValues",
".",
"trim",
"(",
")",
".",
"length",
">",
"0",
")",
"{",
"var",
"relatedItems",
"... | Extracts the entry's `see` data.
@memberOf Entry
@returns {array} Returns the entry's `see` data as links. | [
"Extracts",
"the",
"entry",
"s",
"see",
"data",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L396-L404 | train |
jdalton/docdown | lib/entry.js | getReturns | function getReturns() {
var tag = getTag(this, 'returns'),
desc = _.toString(_.get(tag, 'description')),
type = _.toString(_.get(tag, 'type.name')) || '*';
return tag ? [type, desc] : [];
} | javascript | function getReturns() {
var tag = getTag(this, 'returns'),
desc = _.toString(_.get(tag, 'description')),
type = _.toString(_.get(tag, 'type.name')) || '*';
return tag ? [type, desc] : [];
} | [
"function",
"getReturns",
"(",
")",
"{",
"var",
"tag",
"=",
"getTag",
"(",
"this",
",",
"'returns'",
")",
",",
"desc",
"=",
"_",
".",
"toString",
"(",
"_",
".",
"get",
"(",
"tag",
",",
"'description'",
")",
")",
",",
"type",
"=",
"_",
".",
"toStr... | Extracts the entry's `returns` data.
@memberOf Entry
@returns {array} Returns the entry's `returns` data. | [
"Extracts",
"the",
"entry",
"s",
"returns",
"data",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L412-L418 | train |
jdalton/docdown | lib/entry.js | getType | function getType() {
var result = getValue(this, 'type');
if (!result) {
return this.isFunction() ? 'Function' : 'unknown';
}
return /^(?:array|function|object|regexp)$/.test(result)
? _.capitalize(result)
: result;
} | javascript | function getType() {
var result = getValue(this, 'type');
if (!result) {
return this.isFunction() ? 'Function' : 'unknown';
}
return /^(?:array|function|object|regexp)$/.test(result)
? _.capitalize(result)
: result;
} | [
"function",
"getType",
"(",
")",
"{",
"var",
"result",
"=",
"getValue",
"(",
"this",
",",
"'type'",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"return",
"this",
".",
"isFunction",
"(",
")",
"?",
"'Function'",
":",
"'unknown'",
";",
"}",
"return",
... | Extracts the entry's `type` data.
@memberOf Entry
@returns {string} Returns the entry's `type` data. | [
"Extracts",
"the",
"entry",
"s",
"type",
"data",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L436-L444 | train |
jdalton/docdown | lib/entry.js | isFunction | function isFunction() {
return !!(
this.isCtor() ||
_.size(this.getParams()) ||
_.size(this.getReturns()) ||
hasTag(this, 'function') ||
/\*\/\s*(?:function\s+)?[^\s(]+\s*\(/.test(this.entry)
);
} | javascript | function isFunction() {
return !!(
this.isCtor() ||
_.size(this.getParams()) ||
_.size(this.getReturns()) ||
hasTag(this, 'function') ||
/\*\/\s*(?:function\s+)?[^\s(]+\s*\(/.test(this.entry)
);
} | [
"function",
"isFunction",
"(",
")",
"{",
"return",
"!",
"!",
"(",
"this",
".",
"isCtor",
"(",
")",
"||",
"_",
".",
"size",
"(",
"this",
".",
"getParams",
"(",
")",
")",
"||",
"_",
".",
"size",
"(",
"this",
".",
"getReturns",
"(",
")",
")",
"||"... | Checks if the entry is a function reference.
@memberOf Entry
@returns {boolean} Returns `true` if the entry is a function reference, else `false`. | [
"Checks",
"if",
"the",
"entry",
"is",
"a",
"function",
"reference",
"."
] | 297e61f2ef179b4cebca9656cb4eac2dbdd18669 | https://github.com/jdalton/docdown/blob/297e61f2ef179b4cebca9656cb4eac2dbdd18669/lib/entry.js#L471-L479 | train |
emberjs/list-view | addon/list-view-mixin.js | function (buffer) {
var element = buffer.element();
var dom = buffer.dom;
var container = dom.createElement('div');
container.className = 'ember-list-container';
element.appendChild(container);
this._childViewsMorph = dom.appendMorph(container, container, null);
... | javascript | function (buffer) {
var element = buffer.element();
var dom = buffer.dom;
var container = dom.createElement('div');
container.className = 'ember-list-container';
element.appendChild(container);
this._childViewsMorph = dom.appendMorph(container, container, null);
... | [
"function",
"(",
"buffer",
")",
"{",
"var",
"element",
"=",
"buffer",
".",
"element",
"(",
")",
";",
"var",
"dom",
"=",
"buffer",
".",
"dom",
";",
"var",
"container",
"=",
"dom",
".",
"createElement",
"(",
"'div'",
")",
";",
"container",
".",
"classN... | Called on your view when it should push strings of HTML into a
`Ember.RenderBuffer`.
Adds a [div](https://developer.mozilla.org/en-US/docs/HTML/Element/div)
with a required `ember-list-container` class.
@method render
@param {Ember.RenderBuffer} buffer The render buffer | [
"Called",
"on",
"your",
"view",
"when",
"it",
"should",
"push",
"strings",
"of",
"HTML",
"into",
"a",
"Ember",
".",
"RenderBuffer",
"."
] | d463fa6f874c143fe4766379594b6c11cdf7a5d0 | https://github.com/emberjs/list-view/blob/d463fa6f874c143fe4766379594b6c11cdf7a5d0/addon/list-view-mixin.js#L142-L152 | train | |
joyent/node-docker-registry-client | lib/registry-client-v2.js | _getRegistryErrorMessage | function _getRegistryErrorMessage(err) {
if (err.body && Array.isArray(err.body.errors) && err.body.errors[0]) {
return err.body.errors[0].message;
} else if (err.body && err.body.details) {
return err.body.details;
} else if (Array.isArray(err.errors) && err.errors[0].message) {
ret... | javascript | function _getRegistryErrorMessage(err) {
if (err.body && Array.isArray(err.body.errors) && err.body.errors[0]) {
return err.body.errors[0].message;
} else if (err.body && err.body.details) {
return err.body.details;
} else if (Array.isArray(err.errors) && err.errors[0].message) {
ret... | [
"function",
"_getRegistryErrorMessage",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"body",
"&&",
"Array",
".",
"isArray",
"(",
"err",
".",
"body",
".",
"errors",
")",
"&&",
"err",
".",
"body",
".",
"errors",
"[",
"0",
"]",
")",
"{",
"return",
"er... | Special handling of errors from the registry server.
Some registry errors will use a custom error format, so detect those
and convert these as necessary.
Example JSON response for a missing repo:
{
"jse_shortmsg": "",
"jse_info": {},
"message": "{\"errors\":[{\"code\":\"UNAUTHORIZED\",\"message\":\"...}\n",
"body": {... | [
"Special",
"handling",
"of",
"errors",
"from",
"the",
"registry",
"server",
"."
] | 389a27229744094bb4784087723ce8be50c703dc | https://github.com/joyent/node-docker-registry-client/blob/389a27229744094bb4784087723ce8be50c703dc/lib/registry-client-v2.js#L140-L151 | train |
joyent/node-docker-registry-client | lib/registry-client-v2.js | _getRegistryErrMessage | function _getRegistryErrMessage(body) {
if (!body) {
return null;
}
var obj = body;
if (typeof (obj) === 'string' && obj.length <= MAX_REGISTRY_ERROR_LENGTH) {
try {
obj = JSON.parse(obj);
} catch (ex) {
// Just return the error as a string.
re... | javascript | function _getRegistryErrMessage(body) {
if (!body) {
return null;
}
var obj = body;
if (typeof (obj) === 'string' && obj.length <= MAX_REGISTRY_ERROR_LENGTH) {
try {
obj = JSON.parse(obj);
} catch (ex) {
// Just return the error as a string.
re... | [
"function",
"_getRegistryErrMessage",
"(",
"body",
")",
"{",
"if",
"(",
"!",
"body",
")",
"{",
"return",
"null",
";",
"}",
"var",
"obj",
"=",
"body",
";",
"if",
"(",
"typeof",
"(",
"obj",
")",
"===",
"'string'",
"&&",
"obj",
".",
"length",
"<=",
"M... | Special handling of JSON body errors from the registry server.
POST/PUT endpoints can return an error in the body of the response.
We want to check for that and get the error body message and return it.
Usage:
var regErr = _getRegistryErrMessage(body)); | [
"Special",
"handling",
"of",
"JSON",
"body",
"errors",
"from",
"the",
"registry",
"server",
"."
] | 389a27229744094bb4784087723ce8be50c703dc | https://github.com/joyent/node-docker-registry-client/blob/389a27229744094bb4784087723ce8be50c703dc/lib/registry-client-v2.js#L170-L206 | train |
joyent/node-docker-registry-client | lib/registry-client-v2.js | registryError | function registryError(err, res, callback) {
var body = '';
res.on('data', function onResChunk(chunk) {
body += chunk;
});
res.on('end', function onResEnd() {
// Parse errors in the response body.
var message = _getRegistryErrMessage(body);
if (message) {
err.... | javascript | function registryError(err, res, callback) {
var body = '';
res.on('data', function onResChunk(chunk) {
body += chunk;
});
res.on('end', function onResEnd() {
// Parse errors in the response body.
var message = _getRegistryErrMessage(body);
if (message) {
err.... | [
"function",
"registryError",
"(",
"err",
",",
"res",
",",
"callback",
")",
"{",
"var",
"body",
"=",
"''",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"function",
"onResChunk",
"(",
"chunk",
")",
"{",
"body",
"+=",
"chunk",
";",
"}",
")",
";",
"res",... | The Docker Registry will usually provide a more detailed JSON error message in the response body, so try to read that data in order to get a more detailed error msg. | [
"The",
"Docker",
"Registry",
"will",
"usually",
"provide",
"a",
"more",
"detailed",
"JSON",
"error",
"message",
"in",
"the",
"response",
"body",
"so",
"try",
"to",
"read",
"that",
"data",
"in",
"order",
"to",
"get",
"a",
"more",
"detailed",
"error",
"msg",... | 389a27229744094bb4784087723ce8be50c703dc | https://github.com/joyent/node-docker-registry-client/blob/389a27229744094bb4784087723ce8be50c703dc/lib/registry-client-v2.js#L212-L225 | train |
joyent/node-docker-registry-client | lib/registry-client-v2.js | digestFromManifestStr | function digestFromManifestStr(manifestStr) {
assert.string(manifestStr, 'manifestStr');
var hash = crypto.createHash('sha256');
var digestPrefix = 'sha256:';
var manifest;
try {
manifest = JSON.parse(manifestStr);
} catch (err) {
throw new restifyErrors.InvalidContentError(err... | javascript | function digestFromManifestStr(manifestStr) {
assert.string(manifestStr, 'manifestStr');
var hash = crypto.createHash('sha256');
var digestPrefix = 'sha256:';
var manifest;
try {
manifest = JSON.parse(manifestStr);
} catch (err) {
throw new restifyErrors.InvalidContentError(err... | [
"function",
"digestFromManifestStr",
"(",
"manifestStr",
")",
"{",
"assert",
".",
"string",
"(",
"manifestStr",
",",
"'manifestStr'",
")",
";",
"var",
"hash",
"=",
"crypto",
".",
"createHash",
"(",
"'sha256'",
")",
";",
"var",
"digestPrefix",
"=",
"'sha256:'",... | Calculate the 'Docker-Content-Digest' header for the given manifest.
@returns {String} The docker digest string.
@throws {InvalidContentError} if there is a problem parsing the manifest. | [
"Calculate",
"the",
"Docker",
"-",
"Content",
"-",
"Digest",
"header",
"for",
"the",
"given",
"manifest",
"."
] | 389a27229744094bb4784087723ce8be50c703dc | https://github.com/joyent/node-docker-registry-client/blob/389a27229744094bb4784087723ce8be50c703dc/lib/registry-client-v2.js#L1010-L1039 | train |
dominictarr/map-stream | index.js | wrappedMapper | function wrappedMapper (input, number, callback) {
return mapper.call(null, input, function(err, data){
callback(err, data, number)
})
} | javascript | function wrappedMapper (input, number, callback) {
return mapper.call(null, input, function(err, data){
callback(err, data, number)
})
} | [
"function",
"wrappedMapper",
"(",
"input",
",",
"number",
",",
"callback",
")",
"{",
"return",
"mapper",
".",
"call",
"(",
"null",
",",
"input",
",",
"function",
"(",
"err",
",",
"data",
")",
"{",
"callback",
"(",
"err",
",",
"data",
",",
"number",
"... | Wrap the mapper function by calling its callback with the order number of the item in the stream. | [
"Wrap",
"the",
"mapper",
"function",
"by",
"calling",
"its",
"callback",
"with",
"the",
"order",
"number",
"of",
"the",
"item",
"in",
"the",
"stream",
"."
] | 70794870aab81a7081be50eab59f6789253368da | https://github.com/dominictarr/map-stream/blob/70794870aab81a7081be50eab59f6789253368da/index.js#L82-L86 | train |
fdecampredon/rx-react | lib/funcSubject.js | factory | function factory(BaseClass, mapFunction) {
function subject(value) {
if (typeof mapFunction === 'function') {
value = mapFunction.apply(undefined, arguments);
} else if (typeof mapFunction !== 'undefined') {
value = mapFunction;
}
subject.onNext(value);
return value;
}
for (var ... | javascript | function factory(BaseClass, mapFunction) {
function subject(value) {
if (typeof mapFunction === 'function') {
value = mapFunction.apply(undefined, arguments);
} else if (typeof mapFunction !== 'undefined') {
value = mapFunction;
}
subject.onNext(value);
return value;
}
for (var ... | [
"function",
"factory",
"(",
"BaseClass",
",",
"mapFunction",
")",
"{",
"function",
"subject",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"mapFunction",
"===",
"'function'",
")",
"{",
"value",
"=",
"mapFunction",
".",
"apply",
"(",
"undefined",
",",
"argu... | Factory that allows you to create your custom `FuncSuject`
example:
var myFuncSubject = FuncSubject.factory(MyCustomSubject, (val1, val2) => val1 + val2, ...arguments); | [
"Factory",
"that",
"allows",
"you",
"to",
"create",
"your",
"custom",
"FuncSuject"
] | c86411a5dbeee4a8fb08ea8655a3bf2cc32a6d9c | https://github.com/fdecampredon/rx-react/blob/c86411a5dbeee4a8fb08ea8655a3bf2cc32a6d9c/lib/funcSubject.js#L27-L45 | train |
pubkey/async-test-util | dist/lib/wait-until.js | waitUntil | function waitUntil(fun) {
var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
var timedOut = false;
var ok = false;
if (timeout !== 0) (0, _wait2['default'])(timeout).then(functi... | javascript | function waitUntil(fun) {
var timeout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var interval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 20;
var timedOut = false;
var ok = false;
if (timeout !== 0) (0, _wait2['default'])(timeout).then(functi... | [
"function",
"waitUntil",
"(",
"fun",
")",
"{",
"var",
"timeout",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"0",
";",
"var",
"interval",
"=",
"arguments",
"."... | waits until the given function returns true
@param {function} fun
@return {Promise} | [
"waits",
"until",
"the",
"given",
"function",
"returns",
"true"
] | 5f8bf587cd9d16217f4a19755303a88c30b1f2db | https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/wait-until.js#L23-L54 | train |
pubkey/async-test-util | dist/lib/resolve-values.js | resolveValues | function resolveValues(obj) {
var ret = {};
return Promise.all(Object.keys(obj).map(function (k) {
var val = (0, _promisify2['default'])(obj[k]);
return val.then(function (v) {
return ret[k] = v;
});
})).then(function () {
return ret;
});
} | javascript | function resolveValues(obj) {
var ret = {};
return Promise.all(Object.keys(obj).map(function (k) {
var val = (0, _promisify2['default'])(obj[k]);
return val.then(function (v) {
return ret[k] = v;
});
})).then(function () {
return ret;
});
} | [
"function",
"resolveValues",
"(",
"obj",
")",
"{",
"var",
"ret",
"=",
"{",
"}",
";",
"return",
"Promise",
".",
"all",
"(",
"Object",
".",
"keys",
"(",
"obj",
")",
".",
"map",
"(",
"function",
"(",
"k",
")",
"{",
"var",
"val",
"=",
"(",
"0",
","... | resolves all values if they are promises
returns equal object with resolved | [
"resolves",
"all",
"values",
"if",
"they",
"are",
"promises",
"returns",
"equal",
"object",
"with",
"resolved"
] | 5f8bf587cd9d16217f4a19755303a88c30b1f2db | https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/resolve-values.js#L18-L28 | train |
pubkey/async-test-util | dist/lib/assert-throws.js | assertThrows | function assertThrows(test) {
var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error;
var contains = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (!Array.isArray(contains)) contains = [contains];
var shouldErrorName = typeof error === 'stri... | javascript | function assertThrows(test) {
var error = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Error;
var contains = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (!Array.isArray(contains)) contains = [contains];
var shouldErrorName = typeof error === 'stri... | [
"function",
"assertThrows",
"(",
"test",
")",
"{",
"var",
"error",
"=",
"arguments",
".",
"length",
">",
"1",
"&&",
"arguments",
"[",
"1",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"1",
"]",
":",
"Error",
";",
"var",
"contains",
"=",
"arguments",... | async version of assert.throws
@param {function} test
@param {Error|TypeError|string} [error=Error] error
@param {?string} [contains=''] contains
@return {Promise} [description] | [
"async",
"version",
"of",
"assert",
".",
"throws"
] | 5f8bf587cd9d16217f4a19755303a88c30b1f2db | https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/assert-throws.js#L23-L65 | train |
pubkey/async-test-util | dist/lib/wait-resolveable.js | waitResolveable | function waitResolveable() {
var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var ret = {};
ret.promise = new Promise(function (res) {
ret.resolve = function (x) {
return res(x);
};
setTimeout(res, ms);
});
return ret;
} | javascript | function waitResolveable() {
var ms = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var ret = {};
ret.promise = new Promise(function (res) {
ret.resolve = function (x) {
return res(x);
};
setTimeout(res, ms);
});
return ret;
} | [
"function",
"waitResolveable",
"(",
")",
"{",
"var",
"ms",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"0",
";",
"var",
"ret",
"=",
"{",
"}",
";",
"ret",
"... | this returns a promise and the resolve-function
which can be called to resolve before the timeout has passed
@param {Number} [ms=0] [description] | [
"this",
"returns",
"a",
"promise",
"and",
"the",
"resolve",
"-",
"function",
"which",
"can",
"be",
"called",
"to",
"resolve",
"before",
"the",
"timeout",
"has",
"passed"
] | 5f8bf587cd9d16217f4a19755303a88c30b1f2db | https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/wait-resolveable.js#L12-L23 | train |
pubkey/async-test-util | dist/lib/random-number.js | randomNumber | function randomNumber() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
return Math.floor(Math.random() * (max - min + 1)) + min;
} | javascript | function randomNumber() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
return Math.floor(Math.random() * (max - min + 1)) + min;
} | [
"function",
"randomNumber",
"(",
")",
"{",
"var",
"min",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"0",
";",
"var",
"max",
"=",
"arguments",
".",
"length",
... | returns a random number
@param {number} [min=0] inclusive
@param {number} [max=1000] inclusive
@return {number} | [
"returns",
"a",
"random",
"number"
] | 5f8bf587cd9d16217f4a19755303a88c30b1f2db | https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/random-number.js#L13-L18 | train |
lucalanca/grunt-a11y | tasks/a11y.js | a11yPromise | function a11yPromise (url, viewportSize, verbose) {
var deferred = Q.defer();
a11y(url, {viewportSize: viewportSize}, function (err, reports) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve({url: url, reports: reports, verbose: verbose});
}
});
r... | javascript | function a11yPromise (url, viewportSize, verbose) {
var deferred = Q.defer();
a11y(url, {viewportSize: viewportSize}, function (err, reports) {
if (err) {
deferred.reject(new Error(err));
} else {
deferred.resolve({url: url, reports: reports, verbose: verbose});
}
});
r... | [
"function",
"a11yPromise",
"(",
"url",
",",
"viewportSize",
",",
"verbose",
")",
"{",
"var",
"deferred",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"a11y",
"(",
"url",
",",
"{",
"viewportSize",
":",
"viewportSize",
"}",
",",
"function",
"(",
"err",
",",
... | A promise-based wrapper on a11y.
@param {String} url
@param {String} viewportSize
@param {Boolean} verbose
@return {Promise} | [
"A",
"promise",
"-",
"based",
"wrapper",
"on",
"a11y",
"."
] | b11f0175d69cc0dbd6dd2b452616cb40fad545d8 | https://github.com/lucalanca/grunt-a11y/blob/b11f0175d69cc0dbd6dd2b452616cb40fad545d8/tasks/a11y.js#L32-L42 | train |
lucalanca/grunt-a11y | tasks/a11y.js | logReports | function logReports (url, reports, verbose) {
var passes = '';
var failures = '';
grunt.log.writeln(chalk.underline(chalk.cyan('\nReport for ' + url + '\n')));
reports.audit.forEach(function (el) {
if (el.result === 'PASS') {
passes += logSymbols.success + ' ' + el.heading + '\n';
... | javascript | function logReports (url, reports, verbose) {
var passes = '';
var failures = '';
grunt.log.writeln(chalk.underline(chalk.cyan('\nReport for ' + url + '\n')));
reports.audit.forEach(function (el) {
if (el.result === 'PASS') {
passes += logSymbols.success + ' ' + el.heading + '\n';
... | [
"function",
"logReports",
"(",
"url",
",",
"reports",
",",
"verbose",
")",
"{",
"var",
"passes",
"=",
"''",
";",
"var",
"failures",
"=",
"''",
";",
"grunt",
".",
"log",
".",
"writeln",
"(",
"chalk",
".",
"underline",
"(",
"chalk",
".",
"cyan",
"(",
... | Utility function that logs an audit in the console and
returns a boolean with the validity of the audit.
@param {String} url
@param {a11y reports} reports
@return {Boolean} if the audit is valid | [
"Utility",
"function",
"that",
"logs",
"an",
"audit",
"in",
"the",
"console",
"and",
"returns",
"a",
"boolean",
"with",
"the",
"validity",
"of",
"the",
"audit",
"."
] | b11f0175d69cc0dbd6dd2b452616cb40fad545d8 | https://github.com/lucalanca/grunt-a11y/blob/b11f0175d69cc0dbd6dd2b452616cb40fad545d8/tasks/a11y.js#L52-L76 | train |
pubkey/async-test-util | dist/lib/random-string.js | randomString | function randomString() {
var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8;
var charset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'abcdefghijklmnopqrstuvwxyz';
var text = '';
for (var i = 0; i < length; i++) {
text += charset.charAt(... | javascript | function randomString() {
var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 8;
var charset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'abcdefghijklmnopqrstuvwxyz';
var text = '';
for (var i = 0; i < length; i++) {
text += charset.charAt(... | [
"function",
"randomString",
"(",
")",
"{",
"var",
"length",
"=",
"arguments",
".",
"length",
">",
"0",
"&&",
"arguments",
"[",
"0",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"0",
"]",
":",
"8",
";",
"var",
"charset",
"=",
"arguments",
".",
"len... | create a random string
@return {string} | [
"create",
"a",
"random",
"string"
] | 5f8bf587cd9d16217f4a19755303a88c30b1f2db | https://github.com/pubkey/async-test-util/blob/5f8bf587cd9d16217f4a19755303a88c30b1f2db/dist/lib/random-string.js#L11-L19 | train |
FineLinePrototyping/angularjs-rails-resource | dist/extensions/snapshots.js | _prepSnapshot | function _prepSnapshot() {
var config = this.constructor.config,
copy = (config.snapshotSerializer || config.serializer).serialize(this);
// we don't want to store our snapshots in the snapshots because that would make the rollback kind of funny
// not to mention usi... | javascript | function _prepSnapshot() {
var config = this.constructor.config,
copy = (config.snapshotSerializer || config.serializer).serialize(this);
// we don't want to store our snapshots in the snapshots because that would make the rollback kind of funny
// not to mention usi... | [
"function",
"_prepSnapshot",
"(",
")",
"{",
"var",
"config",
"=",
"this",
".",
"constructor",
".",
"config",
",",
"copy",
"=",
"(",
"config",
".",
"snapshotSerializer",
"||",
"config",
".",
"serializer",
")",
".",
"serialize",
"(",
"this",
")",
";",
"// ... | Prepares a copy of the resource to be stored as a snapshot
@returns {Resource} the copied resource, sans $$snapshots | [
"Prepares",
"a",
"copy",
"of",
"the",
"resource",
"to",
"be",
"stored",
"as",
"a",
"snapshot"
] | 1edf9a4d924b060e62ed7a44041dea00898b0a3b | https://github.com/FineLinePrototyping/angularjs-rails-resource/blob/1edf9a4d924b060e62ed7a44041dea00898b0a3b/dist/extensions/snapshots.js#L32-L41 | train |
FineLinePrototyping/angularjs-rails-resource | dist/extensions/snapshots.js | rollback | function rollback(numVersions) {
var snapshotsLength = this.$$snapshots ? this.$$snapshots.length : 0;
numVersions = Math.min(numVersions || 1, snapshotsLength);
if (numVersions < 0) {
numVersions = snapshotsLength;
}
if (snapshotsLength) {
... | javascript | function rollback(numVersions) {
var snapshotsLength = this.$$snapshots ? this.$$snapshots.length : 0;
numVersions = Math.min(numVersions || 1, snapshotsLength);
if (numVersions < 0) {
numVersions = snapshotsLength;
}
if (snapshotsLength) {
... | [
"function",
"rollback",
"(",
"numVersions",
")",
"{",
"var",
"snapshotsLength",
"=",
"this",
".",
"$$snapshots",
"?",
"this",
".",
"$$snapshots",
".",
"length",
":",
"0",
";",
"numVersions",
"=",
"Math",
".",
"min",
"(",
"numVersions",
"||",
"1",
",",
"s... | Rolls back the resource to a previous snapshot.
When numVersions is undefined or 0 then a single version is rolled back.
When numVersions exceeds the stored number of snapshots then the resource is rolled back to the first snapshot version.
When numVersions is less than 0 then the resource is rolled back to the first ... | [
"Rolls",
"back",
"the",
"resource",
"to",
"a",
"previous",
"snapshot",
"."
] | 1edf9a4d924b060e62ed7a44041dea00898b0a3b | https://github.com/FineLinePrototyping/angularjs-rails-resource/blob/1edf9a4d924b060e62ed7a44041dea00898b0a3b/dist/extensions/snapshots.js#L117-L130 | train |
FineLinePrototyping/angularjs-rails-resource | dist/extensions/snapshots.js | unsnappedChanges | function unsnappedChanges() {
if (!this.$$snapshots) {
return true
}
var copy = this._prepSnapshot(),
latestSnap = this.$$snapshots[this.$$snapshots.length - 1]
return !angular.equals(copy, latestSnap)
} | javascript | function unsnappedChanges() {
if (!this.$$snapshots) {
return true
}
var copy = this._prepSnapshot(),
latestSnap = this.$$snapshots[this.$$snapshots.length - 1]
return !angular.equals(copy, latestSnap)
} | [
"function",
"unsnappedChanges",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"$$snapshots",
")",
"{",
"return",
"true",
"}",
"var",
"copy",
"=",
"this",
".",
"_prepSnapshot",
"(",
")",
",",
"latestSnap",
"=",
"this",
".",
"$$snapshots",
"[",
"this",
"."... | Checks if resource is changed from the most recent snapshot.
@returns {Boolean} true if the latest snapshot differs from resource as-is | [
"Checks",
"if",
"resource",
"is",
"changed",
"from",
"the",
"most",
"recent",
"snapshot",
"."
] | 1edf9a4d924b060e62ed7a44041dea00898b0a3b | https://github.com/FineLinePrototyping/angularjs-rails-resource/blob/1edf9a4d924b060e62ed7a44041dea00898b0a3b/dist/extensions/snapshots.js#L136-L145 | train |
FineLinePrototyping/angularjs-rails-resource | dist/angularjs-rails-resource.js | getService | function getService(service) {
// strings and functions are not considered objects by angular.isObject()
if (angular.isObject(service)) {
return service;
} else if (service) {
return createService(service);
}
return undefined;
... | javascript | function getService(service) {
// strings and functions are not considered objects by angular.isObject()
if (angular.isObject(service)) {
return service;
} else if (service) {
return createService(service);
}
return undefined;
... | [
"function",
"getService",
"(",
"service",
")",
"{",
"// strings and functions are not considered objects by angular.isObject()",
"if",
"(",
"angular",
".",
"isObject",
"(",
"service",
")",
")",
"{",
"return",
"service",
";",
"}",
"else",
"if",
"(",
"service",
")",
... | Looks up and instantiates an instance of the requested service if .
@param {String|function|Object} service The service to instantiate
@returns {*} | [
"Looks",
"up",
"and",
"instantiates",
"an",
"instance",
"of",
"the",
"requested",
"service",
"if",
"."
] | 1edf9a4d924b060e62ed7a44041dea00898b0a3b | https://github.com/FineLinePrototyping/angularjs-rails-resource/blob/1edf9a4d924b060e62ed7a44041dea00898b0a3b/dist/angularjs-rails-resource.js#L87-L96 | train |
marcello3d/node-mongolian | lib/gridfile.js | MongolianGridFileWriteStream | function MongolianGridFileWriteStream(file) {
if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)
stream.Stream.call(this)
this.file = file
this.writable = true
this.enco... | javascript | function MongolianGridFileWriteStream(file) {
if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)
stream.Stream.call(this)
this.file = file
this.writable = true
this.enco... | [
"function",
"MongolianGridFileWriteStream",
"(",
"file",
")",
"{",
"if",
"(",
"file",
".",
"chunkSize",
"instanceof",
"Long",
")",
"throw",
"new",
"Error",
"(",
"\"Long (64bit) chunkSize unsupported\"",
")",
"if",
"(",
"file",
".",
"chunkSize",
"<=",
"0",
")",
... | Treats a MongolianGridFile as a node.js Writeable Stream | [
"Treats",
"a",
"MongolianGridFile",
"as",
"a",
"node",
".",
"js",
"Writeable",
"Stream"
] | 4a337462c712a400cd4644d2cdf5177ed964163e | https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/lib/gridfile.js#L115-L126 | train |
marcello3d/node-mongolian | lib/gridfile.js | MongolianGridFileReadStream | function MongolianGridFileReadStream(file) {
if (!file._id) throw new Error("Can only read files retrieved from the database")
if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)
... | javascript | function MongolianGridFileReadStream(file) {
if (!file._id) throw new Error("Can only read files retrieved from the database")
if (file.chunkSize instanceof Long) throw new Error("Long (64bit) chunkSize unsupported")
if (file.chunkSize <= 0) throw new Error("File has invalid chunkSize: "+file.chunkSize)
... | [
"function",
"MongolianGridFileReadStream",
"(",
"file",
")",
"{",
"if",
"(",
"!",
"file",
".",
"_id",
")",
"throw",
"new",
"Error",
"(",
"\"Can only read files retrieved from the database\"",
")",
"if",
"(",
"file",
".",
"chunkSize",
"instanceof",
"Long",
")",
"... | Treats a MongolianGridFile as a node.js Readable Stream | [
"Treats",
"a",
"MongolianGridFile",
"as",
"a",
"node",
".",
"js",
"Readable",
"Stream"
] | 4a337462c712a400cd4644d2cdf5177ed964163e | https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/lib/gridfile.js#L211-L224 | train |
marcello3d/node-mongolian | lib/server.js | MongolianServer | function MongolianServer(mongolian, url) {
var self = this
this.mongolian = mongolian
this.url = url
this._callbacks = []
this._callbackCount = 0
this._connection = taxman(function(callback) {
var connection = new Connection
var connected = false
connection.requestId = 0
... | javascript | function MongolianServer(mongolian, url) {
var self = this
this.mongolian = mongolian
this.url = url
this._callbacks = []
this._callbackCount = 0
this._connection = taxman(function(callback) {
var connection = new Connection
var connected = false
connection.requestId = 0
... | [
"function",
"MongolianServer",
"(",
"mongolian",
",",
"url",
")",
"{",
"var",
"self",
"=",
"this",
"this",
".",
"mongolian",
"=",
"mongolian",
"this",
".",
"url",
"=",
"url",
"this",
".",
"_callbacks",
"=",
"[",
"]",
"this",
".",
"_callbackCount",
"=",
... | Constructs a new MongolianServer object | [
"Constructs",
"a",
"new",
"MongolianServer",
"object"
] | 4a337462c712a400cd4644d2cdf5177ed964163e | https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/lib/server.js#L202-L239 | train |
marcello3d/node-mongolian | examples/mongolian_trainer.js | fillCollection | function fillCollection(collection, max, callback) {
collection.count(function(err,count) {
console.log(collection+" count = "+count)
while (count < max) {
var toInsert = []
while (count < max) {
toInsert.push({ foo: Math.random(), index: count++ })
... | javascript | function fillCollection(collection, max, callback) {
collection.count(function(err,count) {
console.log(collection+" count = "+count)
while (count < max) {
var toInsert = []
while (count < max) {
toInsert.push({ foo: Math.random(), index: count++ })
... | [
"function",
"fillCollection",
"(",
"collection",
",",
"max",
",",
"callback",
")",
"{",
"collection",
".",
"count",
"(",
"function",
"(",
"err",
",",
"count",
")",
"{",
"console",
".",
"log",
"(",
"collection",
"+",
"\" count = \"",
"+",
"count",
")",
"w... | Adds some junk to the database | [
"Adds",
"some",
"junk",
"to",
"the",
"database"
] | 4a337462c712a400cd4644d2cdf5177ed964163e | https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/examples/mongolian_trainer.js#L21-L37 | train |
marcello3d/node-mongolian | examples/mongolian_trainer.js | funBuffer | function funBuffer(size) {
var buffer = new Buffer(size)
for (var i=0; i<size; i++) {
if (i%1000 == 0) buffer[i++] = 13
buffer[i] = 97 + (i%26)
}
return buffer
} | javascript | function funBuffer(size) {
var buffer = new Buffer(size)
for (var i=0; i<size; i++) {
if (i%1000 == 0) buffer[i++] = 13
buffer[i] = 97 + (i%26)
}
return buffer
} | [
"function",
"funBuffer",
"(",
"size",
")",
"{",
"var",
"buffer",
"=",
"new",
"Buffer",
"(",
"size",
")",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
"%",
"1000",
"==",
"0",
")",
"buffer",... | Generates alphabet buffers | [
"Generates",
"alphabet",
"buffers"
] | 4a337462c712a400cd4644d2cdf5177ed964163e | https://github.com/marcello3d/node-mongolian/blob/4a337462c712a400cd4644d2cdf5177ed964163e/examples/mongolian_trainer.js#L152-L159 | train |
jsreport/jsreport-xlsx | static/helpers.js | safeGet | function safeGet (obj, path) {
// split ['c:chart'].row[0] into ['c:chart', 'row', 0]
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').replace(/'/g, '').split('.')
for (var i = 0; i < paths.length; i++) {
if (paths[i] === '') {
// the first can be empty string if the path starts with [... | javascript | function safeGet (obj, path) {
// split ['c:chart'].row[0] into ['c:chart', 'row', 0]
var paths = path.replace(/\[/g, '.').replace(/\]/g, '').replace(/'/g, '').split('.')
for (var i = 0; i < paths.length; i++) {
if (paths[i] === '') {
// the first can be empty string if the path starts with [... | [
"function",
"safeGet",
"(",
"obj",
",",
"path",
")",
"{",
"// split ['c:chart'].row[0] into ['c:chart', 'row', 0]",
"var",
"paths",
"=",
"path",
".",
"replace",
"(",
"/",
"\\[",
"/",
"g",
",",
"'.'",
")",
".",
"replace",
"(",
"/",
"\\]",
"/",
"g",
",",
"... | Safely go through object path and create the missing object parts with
empty array or object to be compatible with xml -> json represantation | [
"Safely",
"go",
"through",
"object",
"path",
"and",
"create",
"the",
"missing",
"object",
"parts",
"with",
"empty",
"array",
"or",
"object",
"to",
"be",
"compatible",
"with",
"xml",
"-",
">",
"json",
"represantation"
] | 8dbadd5af87dd9eb4386919e306aa5458f273b54 | https://github.com/jsreport/jsreport-xlsx/blob/8dbadd5af87dd9eb4386919e306aa5458f273b54/static/helpers.js#L196-L215 | train |
massgov/mayflower | patternlab/styleguide/public/styleguide/js/patternlab-viewer.js | function (name,val) {
var cookieVal = $.cookie(this.cookieName);
cookieVal = ((cookieVal === null) || (cookieVal === "")) ? name+"~"+val : cookieVal+"|"+name+"~"+val;
$.cookie(this.cookieName,cookieVal);
} | javascript | function (name,val) {
var cookieVal = $.cookie(this.cookieName);
cookieVal = ((cookieVal === null) || (cookieVal === "")) ? name+"~"+val : cookieVal+"|"+name+"~"+val;
$.cookie(this.cookieName,cookieVal);
} | [
"function",
"(",
"name",
",",
"val",
")",
"{",
"var",
"cookieVal",
"=",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
")",
";",
"cookieVal",
"=",
"(",
"(",
"cookieVal",
"===",
"null",
")",
"||",
"(",
"cookieVal",
"===",
"\"\"",
")",
")",
"?",... | Add a given value to the cookie
@param {String} the name of the key
@param {String} the value | [
"Add",
"a",
"given",
"value",
"to",
"the",
"cookie"
] | 6ae90009c5d611f9fdbcc208f9bd5f1e22926094 | https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L91-L95 | train | |
massgov/mayflower | patternlab/styleguide/public/styleguide/js/patternlab-viewer.js | function (name,val) {
if (this.findValue(name)) {
var updateCookieVals = "";
var cookieVals = $.cookie(this.cookieName).split("|");
for (var i = 0; i < cookieVals.length; i++) {
var fieldVals = cookieVals[i].split("~");
if (fieldVals[0] == name) {
fieldVals[1] = val;
... | javascript | function (name,val) {
if (this.findValue(name)) {
var updateCookieVals = "";
var cookieVals = $.cookie(this.cookieName).split("|");
for (var i = 0; i < cookieVals.length; i++) {
var fieldVals = cookieVals[i].split("~");
if (fieldVals[0] == name) {
fieldVals[1] = val;
... | [
"function",
"(",
"name",
",",
"val",
")",
"{",
"if",
"(",
"this",
".",
"findValue",
"(",
"name",
")",
")",
"{",
"var",
"updateCookieVals",
"=",
"\"\"",
";",
"var",
"cookieVals",
"=",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
")",
".",
"sp... | Update a value found in the cookie. If the key doesn't exist add the value
@param {String} the name of the key
@param {String} the value | [
"Update",
"a",
"value",
"found",
"in",
"the",
"cookie",
".",
"If",
"the",
"key",
"doesn",
"t",
"exist",
"add",
"the",
"value"
] | 6ae90009c5d611f9fdbcc208f9bd5f1e22926094 | https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L102-L117 | train | |
massgov/mayflower | patternlab/styleguide/public/styleguide/js/patternlab-viewer.js | function (name) {
var updateCookieVals = "";
var cookieVals = $.cookie(this.cookieName).split("|");
var k = 0;
for (var i = 0; i < cookieVals.length; i++) {
var fieldVals = cookieVals[i].split("~");
if (fieldVals[0] != name) {
updateCookieVals += (k === 0) ? fieldVals[0]+"~"+fieldVal... | javascript | function (name) {
var updateCookieVals = "";
var cookieVals = $.cookie(this.cookieName).split("|");
var k = 0;
for (var i = 0; i < cookieVals.length; i++) {
var fieldVals = cookieVals[i].split("~");
if (fieldVals[0] != name) {
updateCookieVals += (k === 0) ? fieldVals[0]+"~"+fieldVal... | [
"function",
"(",
"name",
")",
"{",
"var",
"updateCookieVals",
"=",
"\"\"",
";",
"var",
"cookieVals",
"=",
"$",
".",
"cookie",
"(",
"this",
".",
"cookieName",
")",
".",
"split",
"(",
"\"|\"",
")",
";",
"var",
"k",
"=",
"0",
";",
"for",
"(",
"var",
... | Remove the given key
@param {String} the name of the key | [
"Remove",
"the",
"given",
"key"
] | 6ae90009c5d611f9fdbcc208f9bd5f1e22926094 | https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L123-L135 | train | |
massgov/mayflower | patternlab/styleguide/public/styleguide/js/patternlab-viewer.js | function() {
// the following is taken from https://developer.mozilla.org/en-US/docs/Web/API/window.location
var oGetVars = new (function (sSearch) {
if (sSearch.length > 1) {
for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
... | javascript | function() {
// the following is taken from https://developer.mozilla.org/en-US/docs/Web/API/window.location
var oGetVars = new (function (sSearch) {
if (sSearch.length > 1) {
for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
... | [
"function",
"(",
")",
"{",
"// the following is taken from https://developer.mozilla.org/en-US/docs/Web/API/window.location",
"var",
"oGetVars",
"=",
"new",
"(",
"function",
"(",
"sSearch",
")",
"{",
"if",
"(",
"sSearch",
".",
"length",
">",
"1",
")",
"{",
"for",
"(... | search the request vars for a particular item
@return {Object} a search of the window.location.search vars | [
"search",
"the",
"request",
"vars",
"for",
"a",
"particular",
"item"
] | 6ae90009c5d611f9fdbcc208f9bd5f1e22926094 | https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L303-L317 | train | |
massgov/mayflower | patternlab/styleguide/public/styleguide/js/patternlab-viewer.js | function (pattern, givenPath) {
var data = { "pattern": pattern };
var fileName = urlHandler.getFileName(pattern);
var path = window.location.pathname;
path = (window.location.protocol === "file") ? path.replace("/public/index.html","public/") : path.replace(/\/index\.htm... | javascript | function (pattern, givenPath) {
var data = { "pattern": pattern };
var fileName = urlHandler.getFileName(pattern);
var path = window.location.pathname;
path = (window.location.protocol === "file") ? path.replace("/public/index.html","public/") : path.replace(/\/index\.htm... | [
"function",
"(",
"pattern",
",",
"givenPath",
")",
"{",
"var",
"data",
"=",
"{",
"\"pattern\"",
":",
"pattern",
"}",
";",
"var",
"fileName",
"=",
"urlHandler",
".",
"getFileName",
"(",
"pattern",
")",
";",
"var",
"path",
"=",
"window",
".",
"location",
... | push a pattern onto the current history based on a click
@param {String} the shorthand partials syntax for a given pattern
@param {String} the path given by the loaded iframe | [
"push",
"a",
"pattern",
"onto",
"the",
"current",
"history",
"based",
"on",
"a",
"click"
] | 6ae90009c5d611f9fdbcc208f9bd5f1e22926094 | https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L324-L345 | train | |
massgov/mayflower | patternlab/styleguide/public/styleguide/js/patternlab-viewer.js | function() {
// make sure the modal viewer and other options are off just in case
modalViewer.close();
// note it's turned on in the viewer
DataSaver.updateValue('modalActive', 'true');
modalViewer.active = true;
// add an active class to the button that matches this template
$('#sg-t... | javascript | function() {
// make sure the modal viewer and other options are off just in case
modalViewer.close();
// note it's turned on in the viewer
DataSaver.updateValue('modalActive', 'true');
modalViewer.active = true;
// add an active class to the button that matches this template
$('#sg-t... | [
"function",
"(",
")",
"{",
"// make sure the modal viewer and other options are off just in case",
"modalViewer",
".",
"close",
"(",
")",
";",
"// note it's turned on in the viewer",
"DataSaver",
".",
"updateValue",
"(",
"'modalActive'",
",",
"'true'",
")",
";",
"modalViewe... | open the modal window | [
"open",
"the",
"modal",
"window"
] | 6ae90009c5d611f9fdbcc208f9bd5f1e22926094 | https://github.com/massgov/mayflower/blob/6ae90009c5d611f9fdbcc208f9bd5f1e22926094/patternlab/styleguide/public/styleguide/js/patternlab-viewer.js#L492-L510 | train |
Subsets and Splits
SQL Console for semeru/code-text-javascript
Retrieves 20,000 non-null code samples labeled as JavaScript, providing a basic overview of the dataset.