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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
RackHD/on-tasks
spec/lib/task-data/schemas/schema-ut-helper.js
loadSchemas
function loadSchemas(ajv) { var metaSchema = helper.require('/lib/task-data/schemas/rackhd-task-schema.json'); ajv.addMetaSchema(metaSchema, 'rackhd-task-schema.json'); var fileNames = glob.sync(helper.relativeToRoot('/lib/task-data/schemas/*.json')); _(fileNames).filter(function (filename) { return path.basename(filename) !== 'rackhd-task-schema.json'; }) .forEach(function (filename) { try { var data = fs.readFileSync(filename).toString(); jsonlint.parse(data); ajv.addSchema(JSON.parse(data), path.basename(filename)); } catch(err) { console.error('fail to add schema: ' + filename); throw err; } }) .value(); return ajv; }
javascript
function loadSchemas(ajv) { var metaSchema = helper.require('/lib/task-data/schemas/rackhd-task-schema.json'); ajv.addMetaSchema(metaSchema, 'rackhd-task-schema.json'); var fileNames = glob.sync(helper.relativeToRoot('/lib/task-data/schemas/*.json')); _(fileNames).filter(function (filename) { return path.basename(filename) !== 'rackhd-task-schema.json'; }) .forEach(function (filename) { try { var data = fs.readFileSync(filename).toString(); jsonlint.parse(data); ajv.addSchema(JSON.parse(data), path.basename(filename)); } catch(err) { console.error('fail to add schema: ' + filename); throw err; } }) .value(); return ajv; }
[ "function", "loadSchemas", "(", "ajv", ")", "{", "var", "metaSchema", "=", "helper", ".", "require", "(", "'/lib/task-data/schemas/rackhd-task-schema.json'", ")", ";", "ajv", ".", "addMetaSchema", "(", "metaSchema", ",", "'rackhd-task-schema.json'", ")", ";", "var", "fileNames", "=", "glob", ".", "sync", "(", "helper", ".", "relativeToRoot", "(", "'/lib/task-data/schemas/*.json'", ")", ")", ";", "_", "(", "fileNames", ")", ".", "filter", "(", "function", "(", "filename", ")", "{", "return", "path", ".", "basename", "(", "filename", ")", "!==", "'rackhd-task-schema.json'", ";", "}", ")", ".", "forEach", "(", "function", "(", "filename", ")", "{", "try", "{", "var", "data", "=", "fs", ".", "readFileSync", "(", "filename", ")", ".", "toString", "(", ")", ";", "jsonlint", ".", "parse", "(", "data", ")", ";", "ajv", ".", "addSchema", "(", "JSON", ".", "parse", "(", "data", ")", ",", "path", ".", "basename", "(", "filename", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "'fail to add schema: '", "+", "filename", ")", ";", "throw", "err", ";", "}", "}", ")", ".", "value", "(", ")", ";", "return", "ajv", ";", "}" ]
load all schemas into the validator to resolve all schema references @param {Object} ajv - The Ajv instance @return {Object} the input Ajv instance
[ "load", "all", "schemas", "into", "the", "validator", "to", "resolve", "all", "schema", "references" ]
18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea
https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/spec/lib/task-data/schemas/schema-ut-helper.js#L18-L38
train
RackHD/on-tasks
spec/lib/task-data/schemas/schema-ut-helper.js
getSchema
function getSchema(ajv, name) { var result = ajv.getSchema(name); if (!result || !result.schema) { throw new Error('cannot find the schema with name "' + name + '".'); } return result.schema; }
javascript
function getSchema(ajv, name) { var result = ajv.getSchema(name); if (!result || !result.schema) { throw new Error('cannot find the schema with name "' + name + '".'); } return result.schema; }
[ "function", "getSchema", "(", "ajv", ",", "name", ")", "{", "var", "result", "=", "ajv", ".", "getSchema", "(", "name", ")", ";", "if", "(", "!", "result", "||", "!", "result", ".", "schema", ")", "{", "throw", "new", "Error", "(", "'cannot find the schema with name \"'", "+", "name", "+", "'\".'", ")", ";", "}", "return", "result", ".", "schema", ";", "}" ]
Get the schema definition via name @param {Object} ajv - The Ajv instance @param {String} name - The schema name or id @return {Object} The schema definition.
[ "Get", "the", "schema", "definition", "via", "name" ]
18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea
https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/spec/lib/task-data/schemas/schema-ut-helper.js#L46-L52
train
RackHD/on-tasks
spec/lib/task-data/schemas/schema-ut-helper.js
validateData
function validateData(validator, schemaId, data, expected) { var result = validator.validate(schemaId, data); if (!result && expected || result && !expected) { if (!result) { return new Error(validator.errorsText()); } else { return new Error('expected schema violation, but get conformity.'); } } }
javascript
function validateData(validator, schemaId, data, expected) { var result = validator.validate(schemaId, data); if (!result && expected || result && !expected) { if (!result) { return new Error(validator.errorsText()); } else { return new Error('expected schema violation, but get conformity.'); } } }
[ "function", "validateData", "(", "validator", ",", "schemaId", ",", "data", ",", "expected", ")", "{", "var", "result", "=", "validator", ".", "validate", "(", "schemaId", ",", "data", ")", ";", "if", "(", "!", "result", "&&", "expected", "||", "result", "&&", "!", "expected", ")", "{", "if", "(", "!", "result", ")", "{", "return", "new", "Error", "(", "validator", ".", "errorsText", "(", ")", ")", ";", "}", "else", "{", "return", "new", "Error", "(", "'expected schema violation, but get conformity.'", ")", ";", "}", "}", "}" ]
validate the data against a schema @param {Object} validator - The JSON-Schema validator instance @param {String} schemaId - The schema id @param {Object} data - The data that to be validated @param {Boolean} expected - true if expect data conforms to schema, otherwise expect violation. @return {undefined | Error} - return undefined if the validation gets expected result; Otherwise throw error.
[ "validate", "the", "data", "against", "a", "schema" ]
18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea
https://github.com/RackHD/on-tasks/blob/18ca8021a18e51cb8fc01ef3c08c9e48d34f73ea/spec/lib/task-data/schemas/schema-ut-helper.js#L74-L84
train
stadt-bielefeld/wms-downloader
src/helper/getNumberOfTiles.js
getNumberOfTiles
function getNumberOfTiles(options) { // Determine ground resolution if scale is only set determineGroundResolution(options.tiles.resolutions); // Counter of all tiles let countOfAllTiles = 0; // Calculate parameters of bbox let widthM = options.task.area.bbox.xmax - options.task.area.bbox.xmin; let heightM = options.task.area.bbox.ymax - options.task.area.bbox.ymin; // Iterate over all resolutions for (let int = 0; int < options.tiles.resolutions.length; int++) { // Current resolution let res = options.tiles.resolutions[int]; // Size of all tiles in sum let widthPx = widthM / res.groundResolution; let heightPx = heightM / res.groundResolution; // Calculate tiles count of the current resolution let tiles = {}; tiles.sizePx = options.tiles.maxSizePx - 2 * options.tiles.gutterPx; tiles.xCount = Math.ceil(widthPx / tiles.sizePx); tiles.yCount = Math.ceil(heightPx / tiles.sizePx); // Note tiles count of current resolution countOfAllTiles += tiles.xCount * tiles.yCount * options.wms.length; } return countOfAllTiles; }
javascript
function getNumberOfTiles(options) { // Determine ground resolution if scale is only set determineGroundResolution(options.tiles.resolutions); // Counter of all tiles let countOfAllTiles = 0; // Calculate parameters of bbox let widthM = options.task.area.bbox.xmax - options.task.area.bbox.xmin; let heightM = options.task.area.bbox.ymax - options.task.area.bbox.ymin; // Iterate over all resolutions for (let int = 0; int < options.tiles.resolutions.length; int++) { // Current resolution let res = options.tiles.resolutions[int]; // Size of all tiles in sum let widthPx = widthM / res.groundResolution; let heightPx = heightM / res.groundResolution; // Calculate tiles count of the current resolution let tiles = {}; tiles.sizePx = options.tiles.maxSizePx - 2 * options.tiles.gutterPx; tiles.xCount = Math.ceil(widthPx / tiles.sizePx); tiles.yCount = Math.ceil(heightPx / tiles.sizePx); // Note tiles count of current resolution countOfAllTiles += tiles.xCount * tiles.yCount * options.wms.length; } return countOfAllTiles; }
[ "function", "getNumberOfTiles", "(", "options", ")", "{", "determineGroundResolution", "(", "options", ".", "tiles", ".", "resolutions", ")", ";", "let", "countOfAllTiles", "=", "0", ";", "let", "widthM", "=", "options", ".", "task", ".", "area", ".", "bbox", ".", "xmax", "-", "options", ".", "task", ".", "area", ".", "bbox", ".", "xmin", ";", "let", "heightM", "=", "options", ".", "task", ".", "area", ".", "bbox", ".", "ymax", "-", "options", ".", "task", ".", "area", ".", "bbox", ".", "ymin", ";", "for", "(", "let", "int", "=", "0", ";", "int", "<", "options", ".", "tiles", ".", "resolutions", ".", "length", ";", "int", "++", ")", "{", "let", "res", "=", "options", ".", "tiles", ".", "resolutions", "[", "int", "]", ";", "let", "widthPx", "=", "widthM", "/", "res", ".", "groundResolution", ";", "let", "heightPx", "=", "heightM", "/", "res", ".", "groundResolution", ";", "let", "tiles", "=", "{", "}", ";", "tiles", ".", "sizePx", "=", "options", ".", "tiles", ".", "maxSizePx", "-", "2", "*", "options", ".", "tiles", ".", "gutterPx", ";", "tiles", ".", "xCount", "=", "Math", ".", "ceil", "(", "widthPx", "/", "tiles", ".", "sizePx", ")", ";", "tiles", ".", "yCount", "=", "Math", ".", "ceil", "(", "heightPx", "/", "tiles", ".", "sizePx", ")", ";", "countOfAllTiles", "+=", "tiles", ".", "xCount", "*", "tiles", ".", "yCount", "*", "options", ".", "wms", ".", "length", ";", "}", "return", "countOfAllTiles", ";", "}" ]
Calculates the number of tiles of a task. @param {Object} options Task options (see example) @returns {Number} Number of all tiles of this task @example // task options const task = { 'task': { 'area': { 'bbox': { 'xmin': 455000, 'ymin': 5750000, 'xmax': 479000, 'ymax': 5774000 } } }, 'tiles': { 'maxSizePx': 2500, 'gutterPx': 250, 'resolutions': [ { 'id': 'id_of_groundResolution_10', 'groundResolution': 10 }, { 'id': 'id_of_resolution_25000', 'scale': 25000, 'dpi': 72 } ] }, 'wms': [ { 'id': 'id_of_wms_stadtbezirke' } ] }; // all tiles of this task const count = getNumberOfTiles(task); console.log(count); // 8
[ "Calculates", "the", "number", "of", "tiles", "of", "a", "task", "." ]
8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d
https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/getNumberOfTiles.js#L49-L82
train
stadt-bielefeld/wms-downloader
src/helper/handleTask.js
handleTask
function handleTask(options, config, progress, callback) { fs.ensureDir(options.task.workspace, (err) => { if (err) { // Call callback function with error. callback(err); } else { // Workspace of this task let ws = options.task.workspace + '/' + options.task.id; // Create directory of task workspace fs.ensureDir(ws, (err) => { // Error if (err) { // Directory could not be created. // Call callback function with error. callback(err); } else { // No errors // Handle all resolutions handleResolution(options, ws, 0, config, progress, (err) => { // Error if (err) { // It could not be handled all resolutions. // Call callback function with error. callback(err); } else { // No errors // Call callback function without errors. Task was // handled. callback(null); } }); } }); } }); }
javascript
function handleTask(options, config, progress, callback) { fs.ensureDir(options.task.workspace, (err) => { if (err) { // Call callback function with error. callback(err); } else { // Workspace of this task let ws = options.task.workspace + '/' + options.task.id; // Create directory of task workspace fs.ensureDir(ws, (err) => { // Error if (err) { // Directory could not be created. // Call callback function with error. callback(err); } else { // No errors // Handle all resolutions handleResolution(options, ws, 0, config, progress, (err) => { // Error if (err) { // It could not be handled all resolutions. // Call callback function with error. callback(err); } else { // No errors // Call callback function without errors. Task was // handled. callback(null); } }); } }); } }); }
[ "function", "handleTask", "(", "options", ",", "config", ",", "progress", ",", "callback", ")", "{", "fs", ".", "ensureDir", "(", "options", ".", "task", ".", "workspace", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "{", "let", "ws", "=", "options", ".", "task", ".", "workspace", "+", "'/'", "+", "options", ".", "task", ".", "id", ";", "fs", ".", "ensureDir", "(", "ws", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "{", "handleResolution", "(", "options", ",", "ws", ",", "0", ",", "config", ",", "progress", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "{", "callback", "(", "null", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}" ]
It handles a download task of Web Map Services. @param {Object} options @param {Object} config See options of the {@link WMSDownloader|WMSDownloader constructor} @param {Array} progress Array of the progress of all WMSDownloader tasks. @param {Function} callback function(err){}
[ "It", "handles", "a", "download", "task", "of", "Web", "Map", "Services", "." ]
8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d
https://github.com/stadt-bielefeld/wms-downloader/blob/8e20d7d5547ed43d24d81b8fe3a2c6b4ced83f5d/src/helper/handleTask.js#L14-L59
train
iatsiuk/vuegister
src/vuegister.js
load
function load(buf, file, cfg) { if (typeof buf !== 'string') { throw new TypeError('First argument must be a string.'); } cfg = Object.assign({ maps: false, lang: {script: 'js', template: 'html'}, plugins: {}, }, cfg); let vue = {}; for (let section of extract(buf, ['script', 'template'])) { let attrs = section.attrs; let lang = has(attrs, 'lang') ? attrs.lang : cfg.lang[section.tag]; if (has(attrs, 'src')) { let dir = file ? path.dirname(file) : process.cwd(); file = path.resolve(dir, attrs.src); section.text = fs.readFileSync(file, 'utf8'); } let transpiled = transpile(lang, section.text, { file, maps: cfg.maps, offset: section.offset, extra: Object.assign({}, cfg.plugins[lang]), }); vue[section.tag] = transpiled.data; if (cfg.maps && transpiled.map) { sourceMapsCache.set(file, transpiled.map); } } vue.script += injectTemplate(vue.template); return vue.script; }
javascript
function load(buf, file, cfg) { if (typeof buf !== 'string') { throw new TypeError('First argument must be a string.'); } cfg = Object.assign({ maps: false, lang: {script: 'js', template: 'html'}, plugins: {}, }, cfg); let vue = {}; for (let section of extract(buf, ['script', 'template'])) { let attrs = section.attrs; let lang = has(attrs, 'lang') ? attrs.lang : cfg.lang[section.tag]; if (has(attrs, 'src')) { let dir = file ? path.dirname(file) : process.cwd(); file = path.resolve(dir, attrs.src); section.text = fs.readFileSync(file, 'utf8'); } let transpiled = transpile(lang, section.text, { file, maps: cfg.maps, offset: section.offset, extra: Object.assign({}, cfg.plugins[lang]), }); vue[section.tag] = transpiled.data; if (cfg.maps && transpiled.map) { sourceMapsCache.set(file, transpiled.map); } } vue.script += injectTemplate(vue.template); return vue.script; }
[ "function", "load", "(", "buf", ",", "file", ",", "cfg", ")", "{", "if", "(", "typeof", "buf", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'First argument must be a string.'", ")", ";", "}", "cfg", "=", "Object", ".", "assign", "(", "{", "maps", ":", "false", ",", "lang", ":", "{", "script", ":", "'js'", ",", "template", ":", "'html'", "}", ",", "plugins", ":", "{", "}", ",", "}", ",", "cfg", ")", ";", "let", "vue", "=", "{", "}", ";", "for", "(", "let", "section", "of", "extract", "(", "buf", ",", "[", "'script'", ",", "'template'", "]", ")", ")", "{", "let", "attrs", "=", "section", ".", "attrs", ";", "let", "lang", "=", "has", "(", "attrs", ",", "'lang'", ")", "?", "attrs", ".", "lang", ":", "cfg", ".", "lang", "[", "section", ".", "tag", "]", ";", "if", "(", "has", "(", "attrs", ",", "'src'", ")", ")", "{", "let", "dir", "=", "file", "?", "path", ".", "dirname", "(", "file", ")", ":", "process", ".", "cwd", "(", ")", ";", "file", "=", "path", ".", "resolve", "(", "dir", ",", "attrs", ".", "src", ")", ";", "section", ".", "text", "=", "fs", ".", "readFileSync", "(", "file", ",", "'utf8'", ")", ";", "}", "let", "transpiled", "=", "transpile", "(", "lang", ",", "section", ".", "text", ",", "{", "file", ",", "maps", ":", "cfg", ".", "maps", ",", "offset", ":", "section", ".", "offset", ",", "extra", ":", "Object", ".", "assign", "(", "{", "}", ",", "cfg", ".", "plugins", "[", "lang", "]", ")", ",", "}", ")", ";", "vue", "[", "section", ".", "tag", "]", "=", "transpiled", ".", "data", ";", "if", "(", "cfg", ".", "maps", "&&", "transpiled", ".", "map", ")", "{", "sourceMapsCache", ".", "set", "(", "file", ",", "transpiled", ".", "map", ")", ";", "}", "}", "vue", ".", "script", "+=", "injectTemplate", "(", "vue", ".", "template", ")", ";", "return", "vue", ".", "script", ";", "}" ]
Parses SFC, high level API. @alias module:vuegister @param {string} buf - Content of the SFC file. @param {string} [file] - Full path to the SFC. @param {object} [cfg] - Options, an object of the following format: ```js { maps: boolean, // false, provide source map lang: object, // {}, default language for tag without lang attribute, // for example: // { // {script: 'js'} // } plugins: object, // {}, user configuration for the plugins, for example: // { // babel: { // babelrc: true, // }, // } } ``` @return {string} Returns ready-to-use JavaScript with injected template.
[ "Parses", "SFC", "high", "level", "API", "." ]
38b30127df9f66a3d250229abcf2442c766c3b15
https://github.com/iatsiuk/vuegister/blob/38b30127df9f66a3d250229abcf2442c766c3b15/src/vuegister.js#L124-L165
train
iatsiuk/vuegister
src/vuegister.js
unregister
function unregister() { let list = []; // removes module and all its children from the node's require cache let unload = (id) => { let module = require.cache[id]; if (!module) return; module.children.forEach((child) => unload(child.id)); delete require.cache[id]; list.push(id); }; let sourceMapSupport = require.resolve('source-map-support'); Object.keys(require.cache).forEach((key) => { if (path.extname(key) === VUE_EXT || key === sourceMapSupport) { unload(key); } }); if (has(require.extensions, VUE_EXT)) { delete require.extensions[VUE_EXT]; } if (has(Error, 'prepareStackTrace')) { delete Error.prepareStackTrace; } sourceMapsCache.clear(); return list; }
javascript
function unregister() { let list = []; // removes module and all its children from the node's require cache let unload = (id) => { let module = require.cache[id]; if (!module) return; module.children.forEach((child) => unload(child.id)); delete require.cache[id]; list.push(id); }; let sourceMapSupport = require.resolve('source-map-support'); Object.keys(require.cache).forEach((key) => { if (path.extname(key) === VUE_EXT || key === sourceMapSupport) { unload(key); } }); if (has(require.extensions, VUE_EXT)) { delete require.extensions[VUE_EXT]; } if (has(Error, 'prepareStackTrace')) { delete Error.prepareStackTrace; } sourceMapsCache.clear(); return list; }
[ "function", "unregister", "(", ")", "{", "let", "list", "=", "[", "]", ";", "let", "unload", "=", "(", "id", ")", "=>", "{", "let", "module", "=", "require", ".", "cache", "[", "id", "]", ";", "if", "(", "!", "module", ")", "return", ";", "module", ".", "children", ".", "forEach", "(", "(", "child", ")", "=>", "unload", "(", "child", ".", "id", ")", ")", ";", "delete", "require", ".", "cache", "[", "id", "]", ";", "list", ".", "push", "(", "id", ")", ";", "}", ";", "let", "sourceMapSupport", "=", "require", ".", "resolve", "(", "'source-map-support'", ")", ";", "Object", ".", "keys", "(", "require", ".", "cache", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "if", "(", "path", ".", "extname", "(", "key", ")", "===", "VUE_EXT", "||", "key", "===", "sourceMapSupport", ")", "{", "unload", "(", "key", ")", ";", "}", "}", ")", ";", "if", "(", "has", "(", "require", ".", "extensions", ",", "VUE_EXT", ")", ")", "{", "delete", "require", ".", "extensions", "[", "VUE_EXT", "]", ";", "}", "if", "(", "has", "(", "Error", ",", "'prepareStackTrace'", ")", ")", "{", "delete", "Error", ".", "prepareStackTrace", ";", "}", "sourceMapsCache", ".", "clear", "(", ")", ";", "return", "list", ";", "}" ]
Removes requre hook. @alias module:vuegister @return {array} Returns list of unloaded modules.
[ "Removes", "requre", "hook", "." ]
38b30127df9f66a3d250229abcf2442c766c3b15
https://github.com/iatsiuk/vuegister/blob/38b30127df9f66a3d250229abcf2442c766c3b15/src/vuegister.js#L219-L252
train
iatsiuk/vuegister
src/vuegister.js
transpile
function transpile(lang, text, options) { let plugin = `vuegister-plugin-${lang}`; let langs = { js() { let map = (options.maps && options.offset > 0) ? generateMap(text, options.file, options.offset) : null; return {data: text, map}; }, html() { return {data: text, map: null}; }, error(err) { let error = `Plugin ${plugin} not found.` + os.EOL + err.message; throw new Error(error); }, }; // allows to override default html and js methods by plugins try { return require(plugin)(text, options); } catch (err) { return (langs[lang] || langs['error'](err))(); } }
javascript
function transpile(lang, text, options) { let plugin = `vuegister-plugin-${lang}`; let langs = { js() { let map = (options.maps && options.offset > 0) ? generateMap(text, options.file, options.offset) : null; return {data: text, map}; }, html() { return {data: text, map: null}; }, error(err) { let error = `Plugin ${plugin} not found.` + os.EOL + err.message; throw new Error(error); }, }; // allows to override default html and js methods by plugins try { return require(plugin)(text, options); } catch (err) { return (langs[lang] || langs['error'](err))(); } }
[ "function", "transpile", "(", "lang", ",", "text", ",", "options", ")", "{", "let", "plugin", "=", "`", "${", "lang", "}", "`", ";", "let", "langs", "=", "{", "js", "(", ")", "{", "let", "map", "=", "(", "options", ".", "maps", "&&", "options", ".", "offset", ">", "0", ")", "?", "generateMap", "(", "text", ",", "options", ".", "file", ",", "options", ".", "offset", ")", ":", "null", ";", "return", "{", "data", ":", "text", ",", "map", "}", ";", "}", ",", "html", "(", ")", "{", "return", "{", "data", ":", "text", ",", "map", ":", "null", "}", ";", "}", ",", "error", "(", "err", ")", "{", "let", "error", "=", "`", "${", "plugin", "}", "`", "+", "os", ".", "EOL", "+", "err", ".", "message", ";", "throw", "new", "Error", "(", "error", ")", ";", "}", ",", "}", ";", "try", "{", "return", "require", "(", "plugin", ")", "(", "text", ",", "options", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "(", "langs", "[", "lang", "]", "||", "langs", "[", "'error'", "]", "(", "err", ")", ")", "(", ")", ";", "}", "}" ]
Passes given code to the external plugin. @param {string} lang - Lang attribute from the tag. @param {string} text - Code for the transpiler. @param {object} options - Options, an object of the following format: ```js { file: string, // 'unknown', file name maps: boolean, // false, provide source map mapOffset: number, // 0, map offset extra: object, // {}, plugin options from the user } ``` @return {object} Returns the following object: ```js { text: string, // transpiled text from plugin map: object, // generated source map } ```
[ "Passes", "given", "code", "to", "the", "external", "plugin", "." ]
38b30127df9f66a3d250229abcf2442c766c3b15
https://github.com/iatsiuk/vuegister/blob/38b30127df9f66a3d250229abcf2442c766c3b15/src/vuegister.js#L276-L304
train
iatsiuk/vuegister
src/vuegister.js
generateMap
function generateMap(content, file, offset) { if (offset <= 0) { throw new RangeError('Offset parameter should be greater than zero.'); } let generator = new sourceMap.SourceMapGenerator(); let options = { locations: true, sourceType: 'module', }; for (let token of tokenizer(content, options)) { let position = token.loc.start; generator.addMapping({ source: file, original: {line: position.line + offset, column: position.column}, generated: position, name: token.value, }); } return generator.toJSON(); }
javascript
function generateMap(content, file, offset) { if (offset <= 0) { throw new RangeError('Offset parameter should be greater than zero.'); } let generator = new sourceMap.SourceMapGenerator(); let options = { locations: true, sourceType: 'module', }; for (let token of tokenizer(content, options)) { let position = token.loc.start; generator.addMapping({ source: file, original: {line: position.line + offset, column: position.column}, generated: position, name: token.value, }); } return generator.toJSON(); }
[ "function", "generateMap", "(", "content", ",", "file", ",", "offset", ")", "{", "if", "(", "offset", "<=", "0", ")", "{", "throw", "new", "RangeError", "(", "'Offset parameter should be greater than zero.'", ")", ";", "}", "let", "generator", "=", "new", "sourceMap", ".", "SourceMapGenerator", "(", ")", ";", "let", "options", "=", "{", "locations", ":", "true", ",", "sourceType", ":", "'module'", ",", "}", ";", "for", "(", "let", "token", "of", "tokenizer", "(", "content", ",", "options", ")", ")", "{", "let", "position", "=", "token", ".", "loc", ".", "start", ";", "generator", ".", "addMapping", "(", "{", "source", ":", "file", ",", "original", ":", "{", "line", ":", "position", ".", "line", "+", "offset", ",", "column", ":", "position", ".", "column", "}", ",", "generated", ":", "position", ",", "name", ":", "token", ".", "value", ",", "}", ")", ";", "}", "return", "generator", ".", "toJSON", "(", ")", ";", "}" ]
Generates source map for JavaScript. @param {string} content - Content of the script tag. @param {string} file - File name of the generated source. @param {number} offset - Offset for script tag @return {object} Returns the source map.
[ "Generates", "source", "map", "for", "JavaScript", "." ]
38b30127df9f66a3d250229abcf2442c766c3b15
https://github.com/iatsiuk/vuegister/blob/38b30127df9f66a3d250229abcf2442c766c3b15/src/vuegister.js#L314-L337
train
iatsiuk/vuegister
src/vuegister.js
installMapsSupport
function installMapsSupport() { require('source-map-support').install({ environment: 'node', handleUncaughtExceptions: false, retrieveSourceMap: (source) => { return sourceMapsCache.has(source) ? {map: sourceMapsCache.get(source), url: source} : null; }, }); }
javascript
function installMapsSupport() { require('source-map-support').install({ environment: 'node', handleUncaughtExceptions: false, retrieveSourceMap: (source) => { return sourceMapsCache.has(source) ? {map: sourceMapsCache.get(source), url: source} : null; }, }); }
[ "function", "installMapsSupport", "(", ")", "{", "require", "(", "'source-map-support'", ")", ".", "install", "(", "{", "environment", ":", "'node'", ",", "handleUncaughtExceptions", ":", "false", ",", "retrieveSourceMap", ":", "(", "source", ")", "=>", "{", "return", "sourceMapsCache", ".", "has", "(", "source", ")", "?", "{", "map", ":", "sourceMapsCache", ".", "get", "(", "source", ")", ",", "url", ":", "source", "}", ":", "null", ";", "}", ",", "}", ")", ";", "}" ]
Installs handler on prepareStackTrace
[ "Installs", "handler", "on", "prepareStackTrace" ]
38b30127df9f66a3d250229abcf2442c766c3b15
https://github.com/iatsiuk/vuegister/blob/38b30127df9f66a3d250229abcf2442c766c3b15/src/vuegister.js#L342-L352
train
anticoders/gagarin
lib/meteor/meteorProcess.js
kill
function kill (cb) { if (!meteor) { return cb(); } meteor.once('exit', function (code) { if (!code || code === 0 || code === 130) { cb(); } else { cb(new Error('exited with code ' + code)); } }); meteor.kill('SIGINT'); meteor = null; //-------------------------------------------- process.removeListener('exit', onProcessExit); }
javascript
function kill (cb) { if (!meteor) { return cb(); } meteor.once('exit', function (code) { if (!code || code === 0 || code === 130) { cb(); } else { cb(new Error('exited with code ' + code)); } }); meteor.kill('SIGINT'); meteor = null; //-------------------------------------------- process.removeListener('exit', onProcessExit); }
[ "function", "kill", "(", "cb", ")", "{", "if", "(", "!", "meteor", ")", "{", "return", "cb", "(", ")", ";", "}", "meteor", ".", "once", "(", "'exit'", ",", "function", "(", "code", ")", "{", "if", "(", "!", "code", "||", "code", "===", "0", "||", "code", "===", "130", ")", "{", "cb", "(", ")", ";", "}", "else", "{", "cb", "(", "new", "Error", "(", "'exited with code '", "+", "code", ")", ")", ";", "}", "}", ")", ";", "meteor", ".", "kill", "(", "'SIGINT'", ")", ";", "meteor", "=", "null", ";", "process", ".", "removeListener", "(", "'exit'", ",", "onProcessExit", ")", ";", "}" ]
Kill the meteor process and cleanup. @param {Function} cb
[ "Kill", "the", "meteor", "process", "and", "cleanup", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/meteorProcess.js#L141-L156
train
ciena-blueplanet/ember-test-utils
cli/lint-markdown.js
getIgnoredFiles
function getIgnoredFiles () { const filePath = path.join(process.cwd(), '.remarkignore') const ignoredFilesSource = fs.existsSync(filePath) ? fs.readFileSync(filePath, {encoding: 'utf8'}) : '' var ignoredFiles = ignoredFilesSource.split('\n') ignoredFiles = ignoredFiles.filter(function (item) { return item !== '' }) return ignoredFiles }
javascript
function getIgnoredFiles () { const filePath = path.join(process.cwd(), '.remarkignore') const ignoredFilesSource = fs.existsSync(filePath) ? fs.readFileSync(filePath, {encoding: 'utf8'}) : '' var ignoredFiles = ignoredFilesSource.split('\n') ignoredFiles = ignoredFiles.filter(function (item) { return item !== '' }) return ignoredFiles }
[ "function", "getIgnoredFiles", "(", ")", "{", "const", "filePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'.remarkignore'", ")", "const", "ignoredFilesSource", "=", "fs", ".", "existsSync", "(", "filePath", ")", "?", "fs", ".", "readFileSync", "(", "filePath", ",", "{", "encoding", ":", "'utf8'", "}", ")", ":", "''", "var", "ignoredFiles", "=", "ignoredFilesSource", ".", "split", "(", "'\\n'", ")", "\\n", "ignoredFiles", "=", "ignoredFiles", ".", "filter", "(", "function", "(", "item", ")", "{", "return", "item", "!==", "''", "}", ")", "}" ]
The entries in the consumer's `.remarkignore` file @returns {Array} entries
[ "The", "entries", "in", "the", "consumer", "s", ".", "remarkignore", "file" ]
7e40f35d53c488b5f12968212110bb5a5ec138ea
https://github.com/ciena-blueplanet/ember-test-utils/blob/7e40f35d53c488b5f12968212110bb5a5ec138ea/cli/lint-markdown.js#L79-L89
train
anticoders/gagarin
lib/tools/index.js
function (err) { "use strict"; var message = ''; if (typeof err === 'string') { return new Error(err); } else if (typeof err === 'object') { if (err.cause) { // probably a webdriver error try { message = JSON.parse(err.cause.value.message).errorMessage; } catch ($) { message = err.cause.value.message; } } else { message = err.message || err.toString(); } return new Error(message); } return new Error(err.toString()); }
javascript
function (err) { "use strict"; var message = ''; if (typeof err === 'string') { return new Error(err); } else if (typeof err === 'object') { if (err.cause) { // probably a webdriver error try { message = JSON.parse(err.cause.value.message).errorMessage; } catch ($) { message = err.cause.value.message; } } else { message = err.message || err.toString(); } return new Error(message); } return new Error(err.toString()); }
[ "function", "(", "err", ")", "{", "\"use strict\"", ";", "var", "message", "=", "''", ";", "if", "(", "typeof", "err", "===", "'string'", ")", "{", "return", "new", "Error", "(", "err", ")", ";", "}", "else", "if", "(", "typeof", "err", "===", "'object'", ")", "{", "if", "(", "err", ".", "cause", ")", "{", "try", "{", "message", "=", "JSON", ".", "parse", "(", "err", ".", "cause", ".", "value", ".", "message", ")", ".", "errorMessage", ";", "}", "catch", "(", "$", ")", "{", "message", "=", "err", ".", "cause", ".", "value", ".", "message", ";", "}", "}", "else", "{", "message", "=", "err", ".", "message", "||", "err", ".", "toString", "(", ")", ";", "}", "return", "new", "Error", "(", "message", ")", ";", "}", "return", "new", "Error", "(", "err", ".", "toString", "(", ")", ")", ";", "}" ]
Make an error comming from webdriver a little more readable.
[ "Make", "an", "error", "comming", "from", "webdriver", "a", "little", "more", "readable", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/tools/index.js#L231-L254
train
anticoders/gagarin
lib/tools/index.js
function () { "use strict"; return new Promise(function (resolve, reject) { var numberOfRetries = 5; (function retry () { var port = 4000 + Math.floor(Math.random() * 1000); portscanner.checkPortStatus(port, 'localhost', function (err, status) { if (err || status !== 'closed') { if (--numberOfRetries > 0) { setTimeout(retry); } else { reject('Cannot find a free port... giving up'); } } else { resolve(port); } }); })(); }); }
javascript
function () { "use strict"; return new Promise(function (resolve, reject) { var numberOfRetries = 5; (function retry () { var port = 4000 + Math.floor(Math.random() * 1000); portscanner.checkPortStatus(port, 'localhost', function (err, status) { if (err || status !== 'closed') { if (--numberOfRetries > 0) { setTimeout(retry); } else { reject('Cannot find a free port... giving up'); } } else { resolve(port); } }); })(); }); }
[ "function", "(", ")", "{", "\"use strict\"", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "numberOfRetries", "=", "5", ";", "(", "function", "retry", "(", ")", "{", "var", "port", "=", "4000", "+", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "1000", ")", ";", "portscanner", ".", "checkPortStatus", "(", "port", ",", "'localhost'", ",", "function", "(", "err", ",", "status", ")", "{", "if", "(", "err", "||", "status", "!==", "'closed'", ")", "{", "if", "(", "--", "numberOfRetries", ">", "0", ")", "{", "setTimeout", "(", "retry", ")", ";", "}", "else", "{", "reject", "(", "'Cannot find a free port... giving up'", ")", ";", "}", "}", "else", "{", "resolve", "(", "port", ")", ";", "}", "}", ")", ";", "}", ")", "(", ")", ";", "}", ")", ";", "}" ]
Find a port, nobody is listening on.
[ "Find", "a", "port", "nobody", "is", "listening", "on", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/tools/index.js#L328-L349
train
anticoders/gagarin
lib/tools/index.js
function (text, options) { "use strict"; var marginX = options.marginX !== undefined ? options.marginX : 2; var marginY = options.marginY !== undefined ? options.marginY : 1; var margin = new Array(marginX+1).join(" "); var indent = options.indent !== undefined ? options.indent : " "; var maxLength = 0; var linesOfText = text.split('\n'); var pattern = options.pattern || { T: "/", B: "/", TR: "//", BR: "//", TL: "//", BL: "//", R: "//", L: "//" }; linesOfText.forEach(function (line) { maxLength = Math.max(maxLength, line.length); }); var top = pattern.TL + new Array(2 * marginX + maxLength + 1).join(pattern.T) + pattern.TR; var empty = pattern.L + new Array(2 * marginX + maxLength + 1).join(" ") + pattern.R; var bottom = pattern.BL + new Array(2 * marginX + maxLength + 1).join(pattern.B) + pattern.BR; linesOfText = linesOfText.map(function (line) { while (line.length < maxLength) { line += " "; } return pattern.L + margin + line + margin + pattern.R; }); // vertical margin for (var i=0; i<marginY; i++) { linesOfText.unshift(empty); linesOfText.push(empty); } // top and bottom lines linesOfText.unshift(top); linesOfText.push(bottom); return linesOfText.map(function (line) { return indent + line; }).join('\n'); }
javascript
function (text, options) { "use strict"; var marginX = options.marginX !== undefined ? options.marginX : 2; var marginY = options.marginY !== undefined ? options.marginY : 1; var margin = new Array(marginX+1).join(" "); var indent = options.indent !== undefined ? options.indent : " "; var maxLength = 0; var linesOfText = text.split('\n'); var pattern = options.pattern || { T: "/", B: "/", TR: "//", BR: "//", TL: "//", BL: "//", R: "//", L: "//" }; linesOfText.forEach(function (line) { maxLength = Math.max(maxLength, line.length); }); var top = pattern.TL + new Array(2 * marginX + maxLength + 1).join(pattern.T) + pattern.TR; var empty = pattern.L + new Array(2 * marginX + maxLength + 1).join(" ") + pattern.R; var bottom = pattern.BL + new Array(2 * marginX + maxLength + 1).join(pattern.B) + pattern.BR; linesOfText = linesOfText.map(function (line) { while (line.length < maxLength) { line += " "; } return pattern.L + margin + line + margin + pattern.R; }); // vertical margin for (var i=0; i<marginY; i++) { linesOfText.unshift(empty); linesOfText.push(empty); } // top and bottom lines linesOfText.unshift(top); linesOfText.push(bottom); return linesOfText.map(function (line) { return indent + line; }).join('\n'); }
[ "function", "(", "text", ",", "options", ")", "{", "\"use strict\"", ";", "var", "marginX", "=", "options", ".", "marginX", "!==", "undefined", "?", "options", ".", "marginX", ":", "2", ";", "var", "marginY", "=", "options", ".", "marginY", "!==", "undefined", "?", "options", ".", "marginY", ":", "1", ";", "var", "margin", "=", "new", "Array", "(", "marginX", "+", "1", ")", ".", "join", "(", "\" \"", ")", ";", "var", "indent", "=", "options", ".", "indent", "!==", "undefined", "?", "options", ".", "indent", ":", "\" \"", ";", "var", "maxLength", "=", "0", ";", "var", "linesOfText", "=", "text", ".", "split", "(", "'\\n'", ")", ";", "\\n", "var", "pattern", "=", "options", ".", "pattern", "||", "{", "T", ":", "\"/\"", ",", "B", ":", "\"/\"", ",", "TR", ":", "\"//\"", ",", "BR", ":", "\"//\"", ",", "TL", ":", "\"//\"", ",", "BL", ":", "\"//\"", ",", "R", ":", "\"//\"", ",", "L", ":", "\"//\"", "}", ";", "linesOfText", ".", "forEach", "(", "function", "(", "line", ")", "{", "maxLength", "=", "Math", ".", "max", "(", "maxLength", ",", "line", ".", "length", ")", ";", "}", ")", ";", "var", "top", "=", "pattern", ".", "TL", "+", "new", "Array", "(", "2", "*", "marginX", "+", "maxLength", "+", "1", ")", ".", "join", "(", "pattern", ".", "T", ")", "+", "pattern", ".", "TR", ";", "var", "empty", "=", "pattern", ".", "L", "+", "new", "Array", "(", "2", "*", "marginX", "+", "maxLength", "+", "1", ")", ".", "join", "(", "\" \"", ")", "+", "pattern", ".", "R", ";", "var", "bottom", "=", "pattern", ".", "BL", "+", "new", "Array", "(", "2", "*", "marginX", "+", "maxLength", "+", "1", ")", ".", "join", "(", "pattern", ".", "B", ")", "+", "pattern", ".", "BR", ";", "linesOfText", "=", "linesOfText", ".", "map", "(", "function", "(", "line", ")", "{", "while", "(", "line", ".", "length", "<", "maxLength", ")", "{", "line", "+=", "\" \"", ";", "}", "return", "pattern", ".", "L", "+", "margin", "+", "line", "+", "margin", "+", "pattern", ".", "R", ";", "}", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "marginY", ";", "i", "++", ")", "{", "linesOfText", ".", "unshift", "(", "empty", ")", ";", "linesOfText", ".", "push", "(", "empty", ")", ";", "}", "linesOfText", ".", "unshift", "(", "top", ")", ";", "linesOfText", ".", "push", "(", "bottom", ")", ";", "}" ]
Creates a nice banner containing the given text. @param {object} options
[ "Creates", "a", "nice", "banner", "containing", "the", "given", "text", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/tools/index.js#L356-L398
train
css-modules/postcss-modules-resolve-imports
src/resolveDeps.js
resolveDeps
function resolveDeps(ast, result) { const { from: selfPath, graph, resolve, rootPath, rootTree, } = result.opts; const cwd = dirname(selfPath); const rootDir = dirname(rootPath); const processor = result.processor; const self = graph[selfPath] = graph[selfPath] || {}; self.mark = TEMPORARY_MARK; const moduleExports = {}; const translations = {}; ast.walkRules(moduleDeclaration, rule => { if (importDeclaration.exec(rule.selector)) { rule.walkDecls(decl => translations[decl.prop] = decl.value); const dependencyPath = RegExp.$1.replace(/['"]/g, ''); const absDependencyPath = resolveModule(dependencyPath, {cwd, resolve}); if (!absDependencyPath) throw new Error( 'Can\'t resolve module path from `' + cwd + '` to `' + dependencyPath + '`' ); if ( graph[absDependencyPath] && graph[absDependencyPath].mark === TEMPORARY_MARK ) throw new Error( 'Circular dependency was found between `' + selfPath + '` and `' + absDependencyPath + '`. ' + 'Circular dependencies lead to the unpredictable state and considered harmful.' ); if (!( graph[absDependencyPath] && graph[absDependencyPath].mark === PERMANENT_MARK )) { const css = readFileSync(absDependencyPath, 'utf8'); const lazyResult = processor.process(css, Object.assign({}, result.opts, {from: absDependencyPath})); updateTranslations(translations, lazyResult.root.exports); } else { updateTranslations(translations, graph[absDependencyPath].exports); } return void rule.remove(); } rule.walkDecls(decl => moduleExports[decl.prop] = decl.value); rule.remove(); }); replaceSymbols(ast, translations); for (const token in moduleExports) for (const genericId in translations) moduleExports[token] = moduleExports[token] .replace(genericId, translations[genericId]); self.mark = PERMANENT_MARK; self.exports = ast.exports = moduleExports; // resolve paths if (cwd !== rootDir) resolvePaths(ast, cwd, rootDir); const importNotes = comment({ parent: rootTree, raws: {before: rootTree.nodes.length === 0 ? '' : '\n\n'}, text: ` imported from ${normalizeUrl(relative(rootDir, selfPath))} `, }); const childNodes = ast.nodes.map(i => { const node = i.clone({parent: rootTree}); if ( typeof node.raws.before === 'undefined' || node.raws.before === '' ) node.raws.before = '\n\n'; return node; }); rootTree.nodes = rootTree.nodes.concat(importNotes, childNodes); }
javascript
function resolveDeps(ast, result) { const { from: selfPath, graph, resolve, rootPath, rootTree, } = result.opts; const cwd = dirname(selfPath); const rootDir = dirname(rootPath); const processor = result.processor; const self = graph[selfPath] = graph[selfPath] || {}; self.mark = TEMPORARY_MARK; const moduleExports = {}; const translations = {}; ast.walkRules(moduleDeclaration, rule => { if (importDeclaration.exec(rule.selector)) { rule.walkDecls(decl => translations[decl.prop] = decl.value); const dependencyPath = RegExp.$1.replace(/['"]/g, ''); const absDependencyPath = resolveModule(dependencyPath, {cwd, resolve}); if (!absDependencyPath) throw new Error( 'Can\'t resolve module path from `' + cwd + '` to `' + dependencyPath + '`' ); if ( graph[absDependencyPath] && graph[absDependencyPath].mark === TEMPORARY_MARK ) throw new Error( 'Circular dependency was found between `' + selfPath + '` and `' + absDependencyPath + '`. ' + 'Circular dependencies lead to the unpredictable state and considered harmful.' ); if (!( graph[absDependencyPath] && graph[absDependencyPath].mark === PERMANENT_MARK )) { const css = readFileSync(absDependencyPath, 'utf8'); const lazyResult = processor.process(css, Object.assign({}, result.opts, {from: absDependencyPath})); updateTranslations(translations, lazyResult.root.exports); } else { updateTranslations(translations, graph[absDependencyPath].exports); } return void rule.remove(); } rule.walkDecls(decl => moduleExports[decl.prop] = decl.value); rule.remove(); }); replaceSymbols(ast, translations); for (const token in moduleExports) for (const genericId in translations) moduleExports[token] = moduleExports[token] .replace(genericId, translations[genericId]); self.mark = PERMANENT_MARK; self.exports = ast.exports = moduleExports; // resolve paths if (cwd !== rootDir) resolvePaths(ast, cwd, rootDir); const importNotes = comment({ parent: rootTree, raws: {before: rootTree.nodes.length === 0 ? '' : '\n\n'}, text: ` imported from ${normalizeUrl(relative(rootDir, selfPath))} `, }); const childNodes = ast.nodes.map(i => { const node = i.clone({parent: rootTree}); if ( typeof node.raws.before === 'undefined' || node.raws.before === '' ) node.raws.before = '\n\n'; return node; }); rootTree.nodes = rootTree.nodes.concat(importNotes, childNodes); }
[ "function", "resolveDeps", "(", "ast", ",", "result", ")", "{", "const", "{", "from", ":", "selfPath", ",", "graph", ",", "resolve", ",", "rootPath", ",", "rootTree", ",", "}", "=", "result", ".", "opts", ";", "const", "cwd", "=", "dirname", "(", "selfPath", ")", ";", "const", "rootDir", "=", "dirname", "(", "rootPath", ")", ";", "const", "processor", "=", "result", ".", "processor", ";", "const", "self", "=", "graph", "[", "selfPath", "]", "=", "graph", "[", "selfPath", "]", "||", "{", "}", ";", "self", ".", "mark", "=", "TEMPORARY_MARK", ";", "const", "moduleExports", "=", "{", "}", ";", "const", "translations", "=", "{", "}", ";", "ast", ".", "walkRules", "(", "moduleDeclaration", ",", "rule", "=>", "{", "if", "(", "importDeclaration", ".", "exec", "(", "rule", ".", "selector", ")", ")", "{", "rule", ".", "walkDecls", "(", "decl", "=>", "translations", "[", "decl", ".", "prop", "]", "=", "decl", ".", "value", ")", ";", "const", "dependencyPath", "=", "RegExp", ".", "$1", ".", "replace", "(", "/", "['\"]", "/", "g", ",", "''", ")", ";", "const", "absDependencyPath", "=", "resolveModule", "(", "dependencyPath", ",", "{", "cwd", ",", "resolve", "}", ")", ";", "if", "(", "!", "absDependencyPath", ")", "throw", "new", "Error", "(", "'Can\\'t resolve module path from `'", "+", "\\'", "+", "cwd", "+", "'` to `'", "+", "dependencyPath", ")", ";", "'`'", "if", "(", "graph", "[", "absDependencyPath", "]", "&&", "graph", "[", "absDependencyPath", "]", ".", "mark", "===", "TEMPORARY_MARK", ")", "throw", "new", "Error", "(", "'Circular dependency was found between `'", "+", "selfPath", "+", "'` and `'", "+", "absDependencyPath", "+", "'`. '", "+", "'Circular dependencies lead to the unpredictable state and considered harmful.'", ")", ";", "if", "(", "!", "(", "graph", "[", "absDependencyPath", "]", "&&", "graph", "[", "absDependencyPath", "]", ".", "mark", "===", "PERMANENT_MARK", ")", ")", "{", "const", "css", "=", "readFileSync", "(", "absDependencyPath", ",", "'utf8'", ")", ";", "const", "lazyResult", "=", "processor", ".", "process", "(", "css", ",", "Object", ".", "assign", "(", "{", "}", ",", "result", ".", "opts", ",", "{", "from", ":", "absDependencyPath", "}", ")", ")", ";", "updateTranslations", "(", "translations", ",", "lazyResult", ".", "root", ".", "exports", ")", ";", "}", "else", "{", "updateTranslations", "(", "translations", ",", "graph", "[", "absDependencyPath", "]", ".", "exports", ")", ";", "}", "}", "return", "void", "rule", ".", "remove", "(", ")", ";", "rule", ".", "walkDecls", "(", "decl", "=>", "moduleExports", "[", "decl", ".", "prop", "]", "=", "decl", ".", "value", ")", ";", "}", ")", ";", "rule", ".", "remove", "(", ")", ";", "replaceSymbols", "(", "ast", ",", "translations", ")", ";", "for", "(", "const", "token", "in", "moduleExports", ")", "for", "(", "const", "genericId", "in", "translations", ")", "moduleExports", "[", "token", "]", "=", "moduleExports", "[", "token", "]", ".", "replace", "(", "genericId", ",", "translations", "[", "genericId", "]", ")", ";", "self", ".", "mark", "=", "PERMANENT_MARK", ";", "self", ".", "exports", "=", "ast", ".", "exports", "=", "moduleExports", ";", "if", "(", "cwd", "!==", "rootDir", ")", "resolvePaths", "(", "ast", ",", "cwd", ",", "rootDir", ")", ";", "const", "importNotes", "=", "comment", "(", "{", "parent", ":", "rootTree", ",", "raws", ":", "{", "before", ":", "rootTree", ".", "nodes", ".", "length", "===", "0", "?", "''", ":", "'\\n\\n'", "}", ",", "\\n", ",", "}", ")", ";", "\\n", "}" ]
Topological sorting is used to resolve the deps order, actually depth-first search algorithm. @see https://en.wikipedia.org/wiki/Topological_sorting
[ "Topological", "sorting", "is", "used", "to", "resolve", "the", "deps", "order", "actually", "depth", "-", "first", "search", "algorithm", "." ]
31ba1f0ab6b727cf7c5630f56256f1f8dd34d67f
https://github.com/css-modules/postcss-modules-resolve-imports/blob/31ba1f0ab6b727cf7c5630f56256f1f8dd34d67f/src/resolveDeps.js#L25-L115
train
anticoders/gagarin
lib/tools/closure.js
Closure
function Closure (parent, listOfKeys, accessor) { "use strict"; var closure = {}; listOfKeys = listOfKeys || []; accessor = accessor || function () {}; parent && parent.__mixin__ && parent.__mixin__(closure); listOfKeys.forEach(function (key) { closure[key] = accessor.bind(null, key); }); this.getValues = function () { var values = {}; Object.keys(closure).forEach(function (key) { values[key] = closure[key](); if (values[key] === undefined) { values[key] = null; } if (typeof values[key] === 'function') { throw new Error('a closure variable must be serializable, so you cannot use a function'); } }); return values; } this.setValues = function (values) { Object.keys(values).forEach(function (key) { closure[key](values[key]); }); } this.__mixin__ = function (object) { Object.keys(closure).forEach(function (key) { object[key] = closure[key]; }); } }
javascript
function Closure (parent, listOfKeys, accessor) { "use strict"; var closure = {}; listOfKeys = listOfKeys || []; accessor = accessor || function () {}; parent && parent.__mixin__ && parent.__mixin__(closure); listOfKeys.forEach(function (key) { closure[key] = accessor.bind(null, key); }); this.getValues = function () { var values = {}; Object.keys(closure).forEach(function (key) { values[key] = closure[key](); if (values[key] === undefined) { values[key] = null; } if (typeof values[key] === 'function') { throw new Error('a closure variable must be serializable, so you cannot use a function'); } }); return values; } this.setValues = function (values) { Object.keys(values).forEach(function (key) { closure[key](values[key]); }); } this.__mixin__ = function (object) { Object.keys(closure).forEach(function (key) { object[key] = closure[key]; }); } }
[ "function", "Closure", "(", "parent", ",", "listOfKeys", ",", "accessor", ")", "{", "\"use strict\"", ";", "var", "closure", "=", "{", "}", ";", "listOfKeys", "=", "listOfKeys", "||", "[", "]", ";", "accessor", "=", "accessor", "||", "function", "(", ")", "{", "}", ";", "parent", "&&", "parent", ".", "__mixin__", "&&", "parent", ".", "__mixin__", "(", "closure", ")", ";", "listOfKeys", ".", "forEach", "(", "function", "(", "key", ")", "{", "closure", "[", "key", "]", "=", "accessor", ".", "bind", "(", "null", ",", "key", ")", ";", "}", ")", ";", "this", ".", "getValues", "=", "function", "(", ")", "{", "var", "values", "=", "{", "}", ";", "Object", ".", "keys", "(", "closure", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "values", "[", "key", "]", "=", "closure", "[", "key", "]", "(", ")", ";", "if", "(", "values", "[", "key", "]", "===", "undefined", ")", "{", "values", "[", "key", "]", "=", "null", ";", "}", "if", "(", "typeof", "values", "[", "key", "]", "===", "'function'", ")", "{", "throw", "new", "Error", "(", "'a closure variable must be serializable, so you cannot use a function'", ")", ";", "}", "}", ")", ";", "return", "values", ";", "}", "this", ".", "setValues", "=", "function", "(", "values", ")", "{", "Object", ".", "keys", "(", "values", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "closure", "[", "key", "]", "(", "values", "[", "key", "]", ")", ";", "}", ")", ";", "}", "this", ".", "__mixin__", "=", "function", "(", "object", ")", "{", "Object", ".", "keys", "(", "closure", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "object", "[", "key", "]", "=", "closure", "[", "key", "]", ";", "}", ")", ";", "}", "}" ]
Creates a new closure manager. @param {Object} parent @param {Array} listOfKeys (names) @param {Function} accessor
[ "Creates", "a", "new", "closure", "manager", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/tools/closure.js#L11-L51
train
ionic-team/ionic-service-core
ionic-core.js
function(key, object) { // Convert object to JSON and store in localStorage var json = JSON.stringify(object); persistenceStrategy.set(key, json); // Then store it in the object cache objectCache[key] = object; }
javascript
function(key, object) { // Convert object to JSON and store in localStorage var json = JSON.stringify(object); persistenceStrategy.set(key, json); // Then store it in the object cache objectCache[key] = object; }
[ "function", "(", "key", ",", "object", ")", "{", "var", "json", "=", "JSON", ".", "stringify", "(", "object", ")", ";", "persistenceStrategy", ".", "set", "(", "key", ",", "json", ")", ";", "objectCache", "[", "key", "]", "=", "object", ";", "}" ]
Stores an object in local storage under the given key
[ "Stores", "an", "object", "in", "local", "storage", "under", "the", "given", "key" ]
8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744
https://github.com/ionic-team/ionic-service-core/blob/8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744/ionic-core.js#L28-L36
train
ionic-team/ionic-service-core
ionic-core.js
function(key) { // First check to see if it's the object cache var cached = objectCache[key]; if (cached) { return cached; } // Deserialize the object from JSON var json = persistenceStrategy.get(key); // null or undefined --> return null. if (json == null) { return null; } try { return JSON.parse(json); } catch (err) { return null; } }
javascript
function(key) { // First check to see if it's the object cache var cached = objectCache[key]; if (cached) { return cached; } // Deserialize the object from JSON var json = persistenceStrategy.get(key); // null or undefined --> return null. if (json == null) { return null; } try { return JSON.parse(json); } catch (err) { return null; } }
[ "function", "(", "key", ")", "{", "var", "cached", "=", "objectCache", "[", "key", "]", ";", "if", "(", "cached", ")", "{", "return", "cached", ";", "}", "var", "json", "=", "persistenceStrategy", ".", "get", "(", "key", ")", ";", "if", "(", "json", "==", "null", ")", "{", "return", "null", ";", "}", "try", "{", "return", "JSON", ".", "parse", "(", "json", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "null", ";", "}", "}" ]
Either retrieves the cached copy of an object, or the object itself from localStorage. Returns null if the object couldn't be found.
[ "Either", "retrieves", "the", "cached", "copy", "of", "an", "object", "or", "the", "object", "itself", "from", "localStorage", ".", "Returns", "null", "if", "the", "object", "couldn", "t", "be", "found", "." ]
8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744
https://github.com/ionic-team/ionic-service-core/blob/8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744/ionic-core.js#L43-L64
train
ionic-team/ionic-service-core
ionic-core.js
function(lockKey, asyncFunction) { var deferred = $q.defer(); // If the memory lock is set, error out. if (memoryLocks[lockKey]) { deferred.reject('in_progress'); return deferred.promise; } // If there is a stored lock but no memory lock, flag a persistence error if (persistenceStrategy.get(lockKey) === 'locked') { deferred.reject('last_call_interrupted'); deferred.promise.then(null, function() { persistenceStrategy.remove(lockKey); }); return deferred.promise; } // Set stored and memory locks memoryLocks[lockKey] = true; persistenceStrategy.set(lockKey, 'locked'); // Perform the async operation asyncFunction().then(function(successData) { deferred.resolve(successData); // Remove stored and memory locks delete memoryLocks[lockKey]; persistenceStrategy.remove(lockKey); }, function(errorData) { deferred.reject(errorData); // Remove stored and memory locks delete memoryLocks[lockKey]; persistenceStrategy.remove(lockKey); }, function(notifyData) { deferred.notify(notifyData); }); return deferred.promise; }
javascript
function(lockKey, asyncFunction) { var deferred = $q.defer(); // If the memory lock is set, error out. if (memoryLocks[lockKey]) { deferred.reject('in_progress'); return deferred.promise; } // If there is a stored lock but no memory lock, flag a persistence error if (persistenceStrategy.get(lockKey) === 'locked') { deferred.reject('last_call_interrupted'); deferred.promise.then(null, function() { persistenceStrategy.remove(lockKey); }); return deferred.promise; } // Set stored and memory locks memoryLocks[lockKey] = true; persistenceStrategy.set(lockKey, 'locked'); // Perform the async operation asyncFunction().then(function(successData) { deferred.resolve(successData); // Remove stored and memory locks delete memoryLocks[lockKey]; persistenceStrategy.remove(lockKey); }, function(errorData) { deferred.reject(errorData); // Remove stored and memory locks delete memoryLocks[lockKey]; persistenceStrategy.remove(lockKey); }, function(notifyData) { deferred.notify(notifyData); }); return deferred.promise; }
[ "function", "(", "lockKey", ",", "asyncFunction", ")", "{", "var", "deferred", "=", "$q", ".", "defer", "(", ")", ";", "if", "(", "memoryLocks", "[", "lockKey", "]", ")", "{", "deferred", ".", "reject", "(", "'in_progress'", ")", ";", "return", "deferred", ".", "promise", ";", "}", "if", "(", "persistenceStrategy", ".", "get", "(", "lockKey", ")", "===", "'locked'", ")", "{", "deferred", ".", "reject", "(", "'last_call_interrupted'", ")", ";", "deferred", ".", "promise", ".", "then", "(", "null", ",", "function", "(", ")", "{", "persistenceStrategy", ".", "remove", "(", "lockKey", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}", "memoryLocks", "[", "lockKey", "]", "=", "true", ";", "persistenceStrategy", ".", "set", "(", "lockKey", ",", "'locked'", ")", ";", "asyncFunction", "(", ")", ".", "then", "(", "function", "(", "successData", ")", "{", "deferred", ".", "resolve", "(", "successData", ")", ";", "delete", "memoryLocks", "[", "lockKey", "]", ";", "persistenceStrategy", ".", "remove", "(", "lockKey", ")", ";", "}", ",", "function", "(", "errorData", ")", "{", "deferred", ".", "reject", "(", "errorData", ")", ";", "delete", "memoryLocks", "[", "lockKey", "]", ";", "persistenceStrategy", ".", "remove", "(", "lockKey", ")", ";", "}", ",", "function", "(", "notifyData", ")", "{", "deferred", ".", "notify", "(", "notifyData", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Locks the async call represented by the given promise and lock key. Only one asyncFunction given by the lockKey can be running at any time. @param lockKey should be a string representing the name of this async call. This is required for persistence. @param asyncFunction Returns a promise of the async call. @returns A new promise, identical to the one returned by asyncFunction, but with two new errors: 'in_progress', and 'last_call_interrupted'.
[ "Locks", "the", "async", "call", "represented", "by", "the", "given", "promise", "and", "lock", "key", ".", "Only", "one", "asyncFunction", "given", "by", "the", "lockKey", "can", "be", "running", "at", "any", "time", "." ]
8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744
https://github.com/ionic-team/ionic-service-core/blob/8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744/ionic-core.js#L76-L117
train
ionic-team/ionic-service-core
ionic-core.js
function(key, value, isUnique) { if(isUnique) { return this._op(key, value, 'pushUnique'); } else { return this._op(key, value, 'push'); } }
javascript
function(key, value, isUnique) { if(isUnique) { return this._op(key, value, 'pushUnique'); } else { return this._op(key, value, 'push'); } }
[ "function", "(", "key", ",", "value", ",", "isUnique", ")", "{", "if", "(", "isUnique", ")", "{", "return", "this", ".", "_op", "(", "key", ",", "value", ",", "'pushUnique'", ")", ";", "}", "else", "{", "return", "this", ".", "_op", "(", "key", ",", "value", ",", "'push'", ")", ";", "}", "}" ]
Push the given value into the array field identified by the key. Pass true to isUnique to only push the value if the value does not already exist in the array.
[ "Push", "the", "given", "value", "into", "the", "array", "field", "identified", "by", "the", "key", ".", "Pass", "true", "to", "isUnique", "to", "only", "push", "the", "value", "if", "the", "value", "does", "not", "already", "exist", "in", "the", "array", "." ]
8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744
https://github.com/ionic-team/ionic-service-core/blob/8997fb52e8b8bc4545ba54a9a31d7e6f36b4a744/ionic-core.js#L377-L383
train
anticoders/gagarin
lib/meteor/build.js
BuildPromise
function BuildPromise(options) { "use strict"; options = options || {}; var pathToApp = options.pathToApp || path.resolve('.'); var mongoUrl = options.mongoUrl || "http://localhost:27017"; var timeout = options.timeout || 120000; var verbose = options.verbose !== undefined ? !!options.verbose : false; var pathToMain = path.join(pathToApp, '.gagarin', 'local', 'bundle', 'main.js'); var pathToLocal = path.join(pathToApp, '.gagarin', 'local'); var env = Object.create(process.env); return tools.getReleaseVersion(pathToApp).then(function (version) { return new Promise(function (resolve, reject) { var args; logs.system("detected METEOR@" + version); if (version >= '1.0.0') { args = [ 'build', '--debug', '--directory', pathToLocal ]; } else { args = [ 'bundle', '--debug', '--directory', path.join(pathToLocal, 'bundle') ]; } logs.system("spawning meteor process with the following args"); logs.system(JSON.stringify(args)); var buildTimeout = null; var meteorBinary = tools.getMeteorBinary(); //make sure that platforms file contains only server and browser //and cache this file under platforms.gagarin.backup var platformsFilePath = path.join(pathToApp,'.meteor','platforms'); var platformsBackupPath = path.join(pathToApp,'.meteor','platforms.gagarin.backup'); fs.rename(platformsFilePath,platformsBackupPath,function(err,data){ fs.writeFile(platformsFilePath,'server\nbrowser\n',function(){ spawnMeteorProcess(); }); }); var output = ""; var meteor = null; var spawnMeteorProcess = function(){ meteor = spawn(meteorBinary, args, { cwd: pathToApp, env: env, stdio: verbose ? 'inherit' : 'ignore' }); meteor.on('exit', function onExit (code) { //switch back to initial content of platforms file fs.rename(platformsBackupPath,platformsFilePath); if (code) { return reject(new Error('meteor build exited with code ' + code)); } /* var err = parseBuildErrors(output); if (err) { return reject(err); } */ logs.system('linking node_modules'); linkNodeModules(pathToApp).then(function () { logs.system('everything is fine'); resolve(pathToMain); }).catch(reject); buildTimeout = setTimeout(function () { meteor.once('exit', function () { reject(new Error('Timeout while waiting for meteor build to finish.')); }); meteor.kill('SIGINT') }, timeout); clearTimeout(buildTimeout); }); } //----------------------------------------------- /* meteor.stdout.on('data', function onData (data) { output += data.toString(); if (data.toString().match(/WARNING: The output directory is under your source tree./)) { logMeteorOutput(' creating your test build in ' + path.join(pathToLocal, 'bundle') + '\n'); return; } logMeteorOutput(data); }); meteor.stdout.on('error', function onError (data) { console.log(chalk.red(data.toString())); clearTimeout(buildTimeout); }); */ }); }); function logMeteorOutput(data) { if (!verbose) { return; } process.stdout.write(chalk.gray(stripAnsi(data))); } }
javascript
function BuildPromise(options) { "use strict"; options = options || {}; var pathToApp = options.pathToApp || path.resolve('.'); var mongoUrl = options.mongoUrl || "http://localhost:27017"; var timeout = options.timeout || 120000; var verbose = options.verbose !== undefined ? !!options.verbose : false; var pathToMain = path.join(pathToApp, '.gagarin', 'local', 'bundle', 'main.js'); var pathToLocal = path.join(pathToApp, '.gagarin', 'local'); var env = Object.create(process.env); return tools.getReleaseVersion(pathToApp).then(function (version) { return new Promise(function (resolve, reject) { var args; logs.system("detected METEOR@" + version); if (version >= '1.0.0') { args = [ 'build', '--debug', '--directory', pathToLocal ]; } else { args = [ 'bundle', '--debug', '--directory', path.join(pathToLocal, 'bundle') ]; } logs.system("spawning meteor process with the following args"); logs.system(JSON.stringify(args)); var buildTimeout = null; var meteorBinary = tools.getMeteorBinary(); //make sure that platforms file contains only server and browser //and cache this file under platforms.gagarin.backup var platformsFilePath = path.join(pathToApp,'.meteor','platforms'); var platformsBackupPath = path.join(pathToApp,'.meteor','platforms.gagarin.backup'); fs.rename(platformsFilePath,platformsBackupPath,function(err,data){ fs.writeFile(platformsFilePath,'server\nbrowser\n',function(){ spawnMeteorProcess(); }); }); var output = ""; var meteor = null; var spawnMeteorProcess = function(){ meteor = spawn(meteorBinary, args, { cwd: pathToApp, env: env, stdio: verbose ? 'inherit' : 'ignore' }); meteor.on('exit', function onExit (code) { //switch back to initial content of platforms file fs.rename(platformsBackupPath,platformsFilePath); if (code) { return reject(new Error('meteor build exited with code ' + code)); } /* var err = parseBuildErrors(output); if (err) { return reject(err); } */ logs.system('linking node_modules'); linkNodeModules(pathToApp).then(function () { logs.system('everything is fine'); resolve(pathToMain); }).catch(reject); buildTimeout = setTimeout(function () { meteor.once('exit', function () { reject(new Error('Timeout while waiting for meteor build to finish.')); }); meteor.kill('SIGINT') }, timeout); clearTimeout(buildTimeout); }); } //----------------------------------------------- /* meteor.stdout.on('data', function onData (data) { output += data.toString(); if (data.toString().match(/WARNING: The output directory is under your source tree./)) { logMeteorOutput(' creating your test build in ' + path.join(pathToLocal, 'bundle') + '\n'); return; } logMeteorOutput(data); }); meteor.stdout.on('error', function onError (data) { console.log(chalk.red(data.toString())); clearTimeout(buildTimeout); }); */ }); }); function logMeteorOutput(data) { if (!verbose) { return; } process.stdout.write(chalk.gray(stripAnsi(data))); } }
[ "function", "BuildPromise", "(", "options", ")", "{", "\"use strict\"", ";", "options", "=", "options", "||", "{", "}", ";", "var", "pathToApp", "=", "options", ".", "pathToApp", "||", "path", ".", "resolve", "(", "'.'", ")", ";", "var", "mongoUrl", "=", "options", ".", "mongoUrl", "||", "\"http://localhost:27017\"", ";", "var", "timeout", "=", "options", ".", "timeout", "||", "120000", ";", "var", "verbose", "=", "options", ".", "verbose", "!==", "undefined", "?", "!", "!", "options", ".", "verbose", ":", "false", ";", "var", "pathToMain", "=", "path", ".", "join", "(", "pathToApp", ",", "'.gagarin'", ",", "'local'", ",", "'bundle'", ",", "'main.js'", ")", ";", "var", "pathToLocal", "=", "path", ".", "join", "(", "pathToApp", ",", "'.gagarin'", ",", "'local'", ")", ";", "var", "env", "=", "Object", ".", "create", "(", "process", ".", "env", ")", ";", "return", "tools", ".", "getReleaseVersion", "(", "pathToApp", ")", ".", "then", "(", "function", "(", "version", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "args", ";", "logs", ".", "system", "(", "\"detected METEOR@\"", "+", "version", ")", ";", "if", "(", "version", ">=", "'1.0.0'", ")", "{", "args", "=", "[", "'build'", ",", "'--debug'", ",", "'--directory'", ",", "pathToLocal", "]", ";", "}", "else", "{", "args", "=", "[", "'bundle'", ",", "'--debug'", ",", "'--directory'", ",", "path", ".", "join", "(", "pathToLocal", ",", "'bundle'", ")", "]", ";", "}", "logs", ".", "system", "(", "\"spawning meteor process with the following args\"", ")", ";", "logs", ".", "system", "(", "JSON", ".", "stringify", "(", "args", ")", ")", ";", "var", "buildTimeout", "=", "null", ";", "var", "meteorBinary", "=", "tools", ".", "getMeteorBinary", "(", ")", ";", "var", "platformsFilePath", "=", "path", ".", "join", "(", "pathToApp", ",", "'.meteor'", ",", "'platforms'", ")", ";", "var", "platformsBackupPath", "=", "path", ".", "join", "(", "pathToApp", ",", "'.meteor'", ",", "'platforms.gagarin.backup'", ")", ";", "fs", ".", "rename", "(", "platformsFilePath", ",", "platformsBackupPath", ",", "function", "(", "err", ",", "data", ")", "{", "fs", ".", "writeFile", "(", "platformsFilePath", ",", "'server\\nbrowser\\n'", ",", "\\n", ")", ";", "}", ")", ";", "\\n", "function", "(", ")", "{", "spawnMeteorProcess", "(", ")", ";", "}", "var", "output", "=", "\"\"", ";", "}", ")", ";", "}", ")", ";", "var", "meteor", "=", "null", ";", "}" ]
PRIVATE BUILD PROMISE IMPLEMENTATION
[ "PRIVATE", "BUILD", "PROMISE", "IMPLEMENTATION" ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/build.js#L103-L224
train
anticoders/gagarin
lib/meteor/build.js
ensureGagarinVersionsMatch
function ensureGagarinVersionsMatch(pathToApp, verbose) { var pathToMeteorPackages = path.join(pathToApp, '.meteor', 'packages'); var nodeModuleVersion = require('../../package.json').version; return new Promise(function (resolve, reject) { utils.getGagarinPackageVersion(pathToApp).then(function (packageVersion) { if (packageVersion === nodeModuleVersion) { logs.system("node module and smart package versions match, " + packageVersion); return resolve(); } tools.getReleaseVersion(pathToApp).then(function (meteorReleaseVersion) { if (meteorReleaseVersion < "0.9.0") { // really, we can do nothing about package version // without a decent package management system logs.system("meteor version is too old to automatically fix package version"); return resolve(); } logs.system("meteor add anti:gagarin@=" + nodeModuleVersion); var meteor = spawn('meteor', [ 'add', 'anti:gagarin@=' + nodeModuleVersion ], { stdio: verbose ? 'inherit' : 'ignore', cwd: pathToApp }); /* meteor.stdout.on('data', function (data) { if (!verbose) { return; } process.stdout.write(chalk.gray(stripAnsi(data))); }); */ meteor.on('error', reject); meteor.on('exit', function (code) { if (code > 0) { return reject(new Error('meteor exited with code ' + code)); } logs.system("anti:gagarin is now in version " + nodeModuleVersion); resolve(); }); }).catch(reject); }).catch(reject); }); // Promise }
javascript
function ensureGagarinVersionsMatch(pathToApp, verbose) { var pathToMeteorPackages = path.join(pathToApp, '.meteor', 'packages'); var nodeModuleVersion = require('../../package.json').version; return new Promise(function (resolve, reject) { utils.getGagarinPackageVersion(pathToApp).then(function (packageVersion) { if (packageVersion === nodeModuleVersion) { logs.system("node module and smart package versions match, " + packageVersion); return resolve(); } tools.getReleaseVersion(pathToApp).then(function (meteorReleaseVersion) { if (meteorReleaseVersion < "0.9.0") { // really, we can do nothing about package version // without a decent package management system logs.system("meteor version is too old to automatically fix package version"); return resolve(); } logs.system("meteor add anti:gagarin@=" + nodeModuleVersion); var meteor = spawn('meteor', [ 'add', 'anti:gagarin@=' + nodeModuleVersion ], { stdio: verbose ? 'inherit' : 'ignore', cwd: pathToApp }); /* meteor.stdout.on('data', function (data) { if (!verbose) { return; } process.stdout.write(chalk.gray(stripAnsi(data))); }); */ meteor.on('error', reject); meteor.on('exit', function (code) { if (code > 0) { return reject(new Error('meteor exited with code ' + code)); } logs.system("anti:gagarin is now in version " + nodeModuleVersion); resolve(); }); }).catch(reject); }).catch(reject); }); // Promise }
[ "function", "ensureGagarinVersionsMatch", "(", "pathToApp", ",", "verbose", ")", "{", "var", "pathToMeteorPackages", "=", "path", ".", "join", "(", "pathToApp", ",", "'.meteor'", ",", "'packages'", ")", ";", "var", "nodeModuleVersion", "=", "require", "(", "'../../package.json'", ")", ".", "version", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "utils", ".", "getGagarinPackageVersion", "(", "pathToApp", ")", ".", "then", "(", "function", "(", "packageVersion", ")", "{", "if", "(", "packageVersion", "===", "nodeModuleVersion", ")", "{", "logs", ".", "system", "(", "\"node module and smart package versions match, \"", "+", "packageVersion", ")", ";", "return", "resolve", "(", ")", ";", "}", "tools", ".", "getReleaseVersion", "(", "pathToApp", ")", ".", "then", "(", "function", "(", "meteorReleaseVersion", ")", "{", "if", "(", "meteorReleaseVersion", "<", "\"0.9.0\"", ")", "{", "logs", ".", "system", "(", "\"meteor version is too old to automatically fix package version\"", ")", ";", "return", "resolve", "(", ")", ";", "}", "logs", ".", "system", "(", "\"meteor add anti:gagarin@=\"", "+", "nodeModuleVersion", ")", ";", "var", "meteor", "=", "spawn", "(", "'meteor'", ",", "[", "'add'", ",", "'anti:gagarin@='", "+", "nodeModuleVersion", "]", ",", "{", "stdio", ":", "verbose", "?", "'inherit'", ":", "'ignore'", ",", "cwd", ":", "pathToApp", "}", ")", ";", "meteor", ".", "on", "(", "'error'", ",", "reject", ")", ";", "meteor", ".", "on", "(", "'exit'", ",", "function", "(", "code", ")", "{", "if", "(", "code", ">", "0", ")", "{", "return", "reject", "(", "new", "Error", "(", "'meteor exited with code '", "+", "code", ")", ")", ";", "}", "logs", ".", "system", "(", "\"anti:gagarin is now in version \"", "+", "nodeModuleVersion", ")", ";", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ";", "}" ]
Build Check smart package version and if it's wrong, install the right one. @param {string} pathToApp
[ "Build", "Check", "smart", "package", "version", "and", "if", "it", "s", "wrong", "install", "the", "right", "one", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/build.js#L232-L286
train
anticoders/gagarin
lib/meteor/build.js
checkIfMeteorIsRunning
function checkIfMeteorIsRunning(pathToApp) { var pathToMongoLock = path.join(pathToApp, '.meteor', 'local', 'db', 'mongod.lock'); return new Promise(function (resolve, reject) { fs.readFile(pathToMongoLock, { encoding: 'utf8' }, function (err, data) { if (err) { // if the file does not exist, then we are ok anyway return err.code !== 'ENOENT' ? reject(err) : resolve(); } else { // isLocked iff the content is non empty resolve(!!data); } }); }); }
javascript
function checkIfMeteorIsRunning(pathToApp) { var pathToMongoLock = path.join(pathToApp, '.meteor', 'local', 'db', 'mongod.lock'); return new Promise(function (resolve, reject) { fs.readFile(pathToMongoLock, { encoding: 'utf8' }, function (err, data) { if (err) { // if the file does not exist, then we are ok anyway return err.code !== 'ENOENT' ? reject(err) : resolve(); } else { // isLocked iff the content is non empty resolve(!!data); } }); }); }
[ "function", "checkIfMeteorIsRunning", "(", "pathToApp", ")", "{", "var", "pathToMongoLock", "=", "path", ".", "join", "(", "pathToApp", ",", "'.meteor'", ",", "'local'", ",", "'db'", ",", "'mongod.lock'", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "pathToMongoLock", ",", "{", "encoding", ":", "'utf8'", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "err", ".", "code", "!==", "'ENOENT'", "?", "reject", "(", "err", ")", ":", "resolve", "(", ")", ";", "}", "else", "{", "resolve", "(", "!", "!", "data", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Guess if "develop" meteor is currently running. @param {string} pathToApp
[ "Guess", "if", "develop", "meteor", "is", "currently", "running", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/build.js#L294-L307
train
anticoders/gagarin
lib/meteor/build.js
smartJsonWarning
function smartJsonWarning(pathToApp) { var pathToSmartJSON = path.join(pathToApp, 'smart.json'); return new Promise(function (resolve, reject) { fs.readFile(pathToSmartJSON, { endcoding: 'urf8' }, function (err, data) { if (err) { // if the file does not exist, then we are ok anyway return err.code !== 'ENOENT' ? reject(err) : resolve(); } else { // since the file exists, first print a warning, then resolve ... process.stdout.write(chalk.yellow( tools.banner([ 'we have detected a smart.json file in ' + pathToApp, 'since Gagarin no longer supports meteorite, this file will be ignored', ].join('\n'), {}) )); process.stdout.write('\n'); resolve(); } }); }); }
javascript
function smartJsonWarning(pathToApp) { var pathToSmartJSON = path.join(pathToApp, 'smart.json'); return new Promise(function (resolve, reject) { fs.readFile(pathToSmartJSON, { endcoding: 'urf8' }, function (err, data) { if (err) { // if the file does not exist, then we are ok anyway return err.code !== 'ENOENT' ? reject(err) : resolve(); } else { // since the file exists, first print a warning, then resolve ... process.stdout.write(chalk.yellow( tools.banner([ 'we have detected a smart.json file in ' + pathToApp, 'since Gagarin no longer supports meteorite, this file will be ignored', ].join('\n'), {}) )); process.stdout.write('\n'); resolve(); } }); }); }
[ "function", "smartJsonWarning", "(", "pathToApp", ")", "{", "var", "pathToSmartJSON", "=", "path", ".", "join", "(", "pathToApp", ",", "'smart.json'", ")", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "pathToSmartJSON", ",", "{", "endcoding", ":", "'urf8'", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "err", ".", "code", "!==", "'ENOENT'", "?", "reject", "(", "err", ")", ":", "resolve", "(", ")", ";", "}", "else", "{", "process", ".", "stdout", ".", "write", "(", "chalk", ".", "yellow", "(", "tools", ".", "banner", "(", "[", "'we have detected a smart.json file in '", "+", "pathToApp", ",", "'since Gagarin no longer supports meteorite, this file will be ignored'", ",", "]", ".", "join", "(", "'\\n'", ")", ",", "\\n", ")", ")", ")", ";", "{", "}", "process", ".", "stdout", ".", "write", "(", "'\\n'", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Look for "smart.json" file. If there's one, print warning before resolving. @param {string} pathToApp
[ "Look", "for", "smart", ".", "json", "file", ".", "If", "there", "s", "one", "print", "warning", "before", "resolving", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/meteor/build.js#L315-L335
train
velop-io/server
examples/4-react-app/server.js
start
async function start() { const mainRoute = server.addReactRoute( "", path.resolve(process.cwd(), "app/Routes.js") ); await server.start(); //start server console.log("started"); }
javascript
async function start() { const mainRoute = server.addReactRoute( "", path.resolve(process.cwd(), "app/Routes.js") ); await server.start(); //start server console.log("started"); }
[ "async", "function", "start", "(", ")", "{", "const", "mainRoute", "=", "server", ".", "addReactRoute", "(", "\"\"", ",", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "\"app/Routes.js\"", ")", ")", ";", "await", "server", ".", "start", "(", ")", ";", "console", ".", "log", "(", "\"started\"", ")", ";", "}" ]
create a new instance
[ "create", "a", "new", "instance" ]
0d9521f2c6bacff0ab6b717432ab1cb87ccbc9bc
https://github.com/velop-io/server/blob/0d9521f2c6bacff0ab6b717432ab1cb87ccbc9bc/examples/4-react-app/server.js#L7-L15
train
anticoders/gagarin
meteor/backdoor.js
providePlugins
function providePlugins(code) { var chunks = []; if (typeof code === 'string') { code = code.split('\n'); } chunks.push("function (" + Object.keys(plugins).join(', ') + ") {"); chunks.push(" return " + code[0]); code.forEach(function (line, index) { if (index === 0) return; // omit the first line chunks.push(" " + line); }); chunks.push("}"); return chunks; }
javascript
function providePlugins(code) { var chunks = []; if (typeof code === 'string') { code = code.split('\n'); } chunks.push("function (" + Object.keys(plugins).join(', ') + ") {"); chunks.push(" return " + code[0]); code.forEach(function (line, index) { if (index === 0) return; // omit the first line chunks.push(" " + line); }); chunks.push("}"); return chunks; }
[ "function", "providePlugins", "(", "code", ")", "{", "var", "chunks", "=", "[", "]", ";", "if", "(", "typeof", "code", "===", "'string'", ")", "{", "code", "=", "code", ".", "split", "(", "'\\n'", ")", ";", "}", "\\n", "chunks", ".", "push", "(", "\"function (\"", "+", "Object", ".", "keys", "(", "plugins", ")", ".", "join", "(", "', '", ")", "+", "\") {\"", ")", ";", "chunks", ".", "push", "(", "\" return \"", "+", "code", "[", "0", "]", ")", ";", "code", ".", "forEach", "(", "function", "(", "line", ",", "index", ")", "{", "if", "(", "index", "===", "0", ")", "return", ";", "chunks", ".", "push", "(", "\" \"", "+", "line", ")", ";", "}", ")", ";", "chunks", ".", "push", "(", "\"}\"", ")", ";", "}" ]
Provide plugins the the local context. @param {(string|string[])} code @returns {string[]}
[ "Provide", "plugins", "the", "the", "local", "context", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/meteor/backdoor.js#L159-L173
train
anticoders/gagarin
meteor/backdoor.js
isolateScope
function isolateScope(code, closure) { if (typeof code === 'string') { code = code.split('\n'); } var keys = Object.keys(closure).map(function (key) { return stringify(key) + ": " + key; }); var chunks = []; chunks.push( "function (" + Object.keys(closure).join(', ') + ") {", " 'use strict';", " return (function (userFunc, getClosure, action) {", " try {", " return action(userFunc, getClosure);", " } catch (err) {", // this should never happen ... " return { error: err.message, closure: getClosure() };", " }", " })(" ); // the code provided by the user goes here align(code).forEach(function (line) { chunks.push(" " + line); }); chunks[chunks.length-1] += ','; chunks.push( // the function returning current state of the closure " function () {", " return { " + keys.join(', ') + " };", " },", // the custom action " arguments[arguments.length-1]", " );", "}" ); return chunks; }
javascript
function isolateScope(code, closure) { if (typeof code === 'string') { code = code.split('\n'); } var keys = Object.keys(closure).map(function (key) { return stringify(key) + ": " + key; }); var chunks = []; chunks.push( "function (" + Object.keys(closure).join(', ') + ") {", " 'use strict';", " return (function (userFunc, getClosure, action) {", " try {", " return action(userFunc, getClosure);", " } catch (err) {", // this should never happen ... " return { error: err.message, closure: getClosure() };", " }", " })(" ); // the code provided by the user goes here align(code).forEach(function (line) { chunks.push(" " + line); }); chunks[chunks.length-1] += ','; chunks.push( // the function returning current state of the closure " function () {", " return { " + keys.join(', ') + " };", " },", // the custom action " arguments[arguments.length-1]", " );", "}" ); return chunks; }
[ "function", "isolateScope", "(", "code", ",", "closure", ")", "{", "if", "(", "typeof", "code", "===", "'string'", ")", "{", "code", "=", "code", ".", "split", "(", "'\\n'", ")", ";", "}", "\\n", "var", "keys", "=", "Object", ".", "keys", "(", "closure", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "stringify", "(", "key", ")", "+", "\": \"", "+", "key", ";", "}", ")", ";", "var", "chunks", "=", "[", "]", ";", "chunks", ".", "push", "(", "\"function (\"", "+", "Object", ".", "keys", "(", "closure", ")", ".", "join", "(", "', '", ")", "+", "\") {\"", ",", "\" 'use strict';\"", ",", "\" return (function (userFunc, getClosure, action) {\"", ",", "\" try {\"", ",", "\" return action(userFunc, getClosure);\"", ",", "\" } catch (err) {\"", ",", "\" return { error: err.message, closure: getClosure() };\"", ",", "\" }\"", ",", "\" })(\"", ")", ";", "align", "(", "code", ")", ".", "forEach", "(", "function", "(", "line", ")", "{", "chunks", ".", "push", "(", "\" \"", "+", "line", ")", ";", "}", ")", ";", "chunks", "[", "chunks", ".", "length", "-", "1", "]", "+=", "','", ";", "chunks", ".", "push", "(", "\" function () {\"", ",", "\" return { \"", "+", "keys", ".", "join", "(", "', '", ")", "+", "\" };\"", ",", "\" },\"", ",", "\" arguments[arguments.length-1]\"", ",", "\" );\"", ",", "\"}\"", ")", ";", "}" ]
Make sure that the only local variables visible inside the code, are those from the closure object. @param {(string|string[])} code @param {Object} closure @returns {string[]}
[ "Make", "sure", "that", "the", "only", "local", "variables", "visible", "inside", "the", "code", "are", "those", "from", "the", "closure", "object", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/meteor/backdoor.js#L183-L224
train
anticoders/gagarin
meteor/backdoor.js
align
function align(code) { if (typeof code === 'string') { code = code.split('\n'); } var match = code[code.length-1].match(/^(\s+)\}/); var regex = null; if (match && code[0].match(/^function/)) { regex = new RegExp("^" + match[1]); return code.map(function (line) { return line.replace(regex, ""); }); } return code; }
javascript
function align(code) { if (typeof code === 'string') { code = code.split('\n'); } var match = code[code.length-1].match(/^(\s+)\}/); var regex = null; if (match && code[0].match(/^function/)) { regex = new RegExp("^" + match[1]); return code.map(function (line) { return line.replace(regex, ""); }); } return code; }
[ "function", "align", "(", "code", ")", "{", "if", "(", "typeof", "code", "===", "'string'", ")", "{", "code", "=", "code", ".", "split", "(", "'\\n'", ")", ";", "}", "\\n", "var", "match", "=", "code", "[", "code", ".", "length", "-", "1", "]", ".", "match", "(", "/", "^(\\s+)\\}", "/", ")", ";", "var", "regex", "=", "null", ";", "if", "(", "match", "&&", "code", "[", "0", "]", ".", "match", "(", "/", "^function", "/", ")", ")", "{", "regex", "=", "new", "RegExp", "(", "\"^\"", "+", "match", "[", "1", "]", ")", ";", "return", "code", ".", "map", "(", "function", "(", "line", ")", "{", "return", "line", ".", "replace", "(", "regex", ",", "\"\"", ")", ";", "}", ")", ";", "}", "}" ]
Fixes the source code indentation. @param {(string|string[])} code @returns {string[]}
[ "Fixes", "the", "source", "code", "indentation", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/meteor/backdoor.js#L232-L245
train
anticoders/gagarin
meteor/backdoor.js
compile
function compile(code, closure) { code = providePlugins(isolateScope(code, closure)).join('\n'); try { return vm.runInThisContext('(' + code + ')').apply({}, values(plugins)); } catch (err) { throw new Meteor.Error(400, err); } }
javascript
function compile(code, closure) { code = providePlugins(isolateScope(code, closure)).join('\n'); try { return vm.runInThisContext('(' + code + ')').apply({}, values(plugins)); } catch (err) { throw new Meteor.Error(400, err); } }
[ "function", "compile", "(", "code", ",", "closure", ")", "{", "code", "=", "providePlugins", "(", "isolateScope", "(", "code", ",", "closure", ")", ")", ".", "join", "(", "'\\n'", ")", ";", "\\n", "}" ]
Creates a function from the provided source code and closure object. @param {(string|string[])} code @param {Object} closure @returns {string[]}
[ "Creates", "a", "function", "from", "the", "provided", "source", "code", "and", "closure", "object", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/meteor/backdoor.js#L254-L261
train
anticoders/gagarin
lib/mocha/gagarin.js
Gagarin
function Gagarin (options) { "use strict"; var write = process.stdout.write.bind(process.stdout); var listOfFrameworks = []; var numberOfLinesPrinted = 0; // XXX gagarin user interface is defined here require('./interface'); options.settings = tools.getSettings(options.settings); options.ui = 'gagarin'; var factory = !options.parallel ? null : createParallelReporterFactory(function (allStats, elapsed) { if (numberOfLinesPrinted > 0) { write('\u001b[' + numberOfLinesPrinted + 'A') } write(' elapsed time: ' + Math.floor(elapsed / 100) / 10 + 's' + '\n\n'); numberOfLinesPrinted = 2 + table(allStats, write); }); function getMocha() { if (options.parallel === 0 && listOfFrameworks.length > 0) { return listOfFrameworks[0]; } var mocha = new Mocha(options); if (factory) { // overwrite the default reporter mocha._reporter = factory(listOfFrameworks.length); } var reporter = mocha._reporter; listOfFrameworks.push(mocha); return mocha; }; // getMocha this.options = options; this.addFile = function (file) { getMocha().addFile(file); } this.runAllFrameworks = function (callback) { var listOfErrors = []; var pending = listOfFrameworks.slice(0); var counter = 0; var running = 0; if (factory) { // looks like parallel test runner, so make sure // there are no logs which can break the table view factory.reset(); process.stdout.write('\n\n'); write = logs2.block(); logs.setSilentBuild(true); } listOfFrameworks.forEach(function (mocha) { mocha.loadFiles(); mocha.files = []; }); function finish() { if (factory) { logs2.unblock(); factory.epilogue(); } callback && callback(listOfErrors, counter); } function maybeFinish (action) { if (running <= 0 && pending <= 0) { finish(); } else { action && action(); } } function update() { var availableSlots = options.parallel > 0 ? options.parallel : 1; if (running >= availableSlots) { return false; } var next = pending.shift(); if (!next) { maybeFinish(); return false; } running += 1; try { next.run(function (numberOfFailures) { counter += numberOfFailures; running -= 1; maybeFinish(function () { // if not ... while (update()); // run as many suites as you can }); }); } catch (err) { listOfErrors.push(err); running -= 1; maybeFinish(); return false; } return true; } while (update()); // run as many suites as you can } }
javascript
function Gagarin (options) { "use strict"; var write = process.stdout.write.bind(process.stdout); var listOfFrameworks = []; var numberOfLinesPrinted = 0; // XXX gagarin user interface is defined here require('./interface'); options.settings = tools.getSettings(options.settings); options.ui = 'gagarin'; var factory = !options.parallel ? null : createParallelReporterFactory(function (allStats, elapsed) { if (numberOfLinesPrinted > 0) { write('\u001b[' + numberOfLinesPrinted + 'A') } write(' elapsed time: ' + Math.floor(elapsed / 100) / 10 + 's' + '\n\n'); numberOfLinesPrinted = 2 + table(allStats, write); }); function getMocha() { if (options.parallel === 0 && listOfFrameworks.length > 0) { return listOfFrameworks[0]; } var mocha = new Mocha(options); if (factory) { // overwrite the default reporter mocha._reporter = factory(listOfFrameworks.length); } var reporter = mocha._reporter; listOfFrameworks.push(mocha); return mocha; }; // getMocha this.options = options; this.addFile = function (file) { getMocha().addFile(file); } this.runAllFrameworks = function (callback) { var listOfErrors = []; var pending = listOfFrameworks.slice(0); var counter = 0; var running = 0; if (factory) { // looks like parallel test runner, so make sure // there are no logs which can break the table view factory.reset(); process.stdout.write('\n\n'); write = logs2.block(); logs.setSilentBuild(true); } listOfFrameworks.forEach(function (mocha) { mocha.loadFiles(); mocha.files = []; }); function finish() { if (factory) { logs2.unblock(); factory.epilogue(); } callback && callback(listOfErrors, counter); } function maybeFinish (action) { if (running <= 0 && pending <= 0) { finish(); } else { action && action(); } } function update() { var availableSlots = options.parallel > 0 ? options.parallel : 1; if (running >= availableSlots) { return false; } var next = pending.shift(); if (!next) { maybeFinish(); return false; } running += 1; try { next.run(function (numberOfFailures) { counter += numberOfFailures; running -= 1; maybeFinish(function () { // if not ... while (update()); // run as many suites as you can }); }); } catch (err) { listOfErrors.push(err); running -= 1; maybeFinish(); return false; } return true; } while (update()); // run as many suites as you can } }
[ "function", "Gagarin", "(", "options", ")", "{", "\"use strict\"", ";", "var", "write", "=", "process", ".", "stdout", ".", "write", ".", "bind", "(", "process", ".", "stdout", ")", ";", "var", "listOfFrameworks", "=", "[", "]", ";", "var", "numberOfLinesPrinted", "=", "0", ";", "require", "(", "'./interface'", ")", ";", "options", ".", "settings", "=", "tools", ".", "getSettings", "(", "options", ".", "settings", ")", ";", "options", ".", "ui", "=", "'gagarin'", ";", "var", "factory", "=", "!", "options", ".", "parallel", "?", "null", ":", "createParallelReporterFactory", "(", "function", "(", "allStats", ",", "elapsed", ")", "{", "if", "(", "numberOfLinesPrinted", ">", "0", ")", "{", "write", "(", "'\\u001b['", "+", "\\u001b", "+", "numberOfLinesPrinted", ")", "}", "'A'", "write", "(", "' elapsed time: '", "+", "Math", ".", "floor", "(", "elapsed", "/", "100", ")", "/", "10", "+", "'s'", "+", "'\\n\\n'", ")", ";", "}", ")", ";", "\\n", "\\n", "numberOfLinesPrinted", "=", "2", "+", "table", "(", "allStats", ",", "write", ")", ";", "function", "getMocha", "(", ")", "{", "if", "(", "options", ".", "parallel", "===", "0", "&&", "listOfFrameworks", ".", "length", ">", "0", ")", "{", "return", "listOfFrameworks", "[", "0", "]", ";", "}", "var", "mocha", "=", "new", "Mocha", "(", "options", ")", ";", "if", "(", "factory", ")", "{", "mocha", ".", "_reporter", "=", "factory", "(", "listOfFrameworks", ".", "length", ")", ";", "}", "var", "reporter", "=", "mocha", ".", "_reporter", ";", "listOfFrameworks", ".", "push", "(", "mocha", ")", ";", "return", "mocha", ";", "}", ";", "}" ]
Creates Gagarin with `options`. It inherits everything from Mocha except that the ui is always set to "gagarin". @param {Object} options
[ "Creates", "Gagarin", "with", "options", "." ]
4f06bbff4221d8e75b73026b638b003f11821fa5
https://github.com/anticoders/gagarin/blob/4f06bbff4221d8e75b73026b638b003f11821fa5/lib/mocha/gagarin.js#L33-L151
train
ciena-blueplanet/ember-test-utils
cli/lint-docker.js
getConfigFilePath
function getConfigFilePath () { // Look for configuration file in current working directory const files = fs.readdirSync(process.cwd()) const configFile = files.find((filePath) => { return CONFIG_FILE_NAMES.find((configFileName) => filePath.indexOf(configFileName) !== -1) }) // If no configuration file was found use recommend configuration if (!configFile) { return path.join(__dirname, '..', this.defaultConfig) } // Use configuration from current working directory return path.join(process.cwd(), configFile) }
javascript
function getConfigFilePath () { // Look for configuration file in current working directory const files = fs.readdirSync(process.cwd()) const configFile = files.find((filePath) => { return CONFIG_FILE_NAMES.find((configFileName) => filePath.indexOf(configFileName) !== -1) }) // If no configuration file was found use recommend configuration if (!configFile) { return path.join(__dirname, '..', this.defaultConfig) } // Use configuration from current working directory return path.join(process.cwd(), configFile) }
[ "function", "getConfigFilePath", "(", ")", "{", "const", "files", "=", "fs", ".", "readdirSync", "(", "process", ".", "cwd", "(", ")", ")", "const", "configFile", "=", "files", ".", "find", "(", "(", "filePath", ")", "=>", "{", "return", "CONFIG_FILE_NAMES", ".", "find", "(", "(", "configFileName", ")", "=>", "filePath", ".", "indexOf", "(", "configFileName", ")", "!==", "-", "1", ")", "}", ")", "if", "(", "!", "configFile", ")", "{", "return", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "this", ".", "defaultConfig", ")", "}", "return", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "configFile", ")", "}" ]
Get configuration options for dockerfile_lint @returns {DockerfileLintConfig} dockerfile lint configuration options
[ "Get", "configuration", "options", "for", "dockerfile_lint" ]
7e40f35d53c488b5f12968212110bb5a5ec138ea
https://github.com/ciena-blueplanet/ember-test-utils/blob/7e40f35d53c488b5f12968212110bb5a5ec138ea/cli/lint-docker.js#L32-L46
train
ciena-blueplanet/ember-test-utils
cli/lint-docker.js
lintFile
function lintFile (linter, fileName) { const fileContents = fs.readFileSync(fileName, {encoding: 'utf8'}).toString() const report = linter.validate(fileContents) const errors = report.error.count const warnings = report.warn.count if (errors || warnings) { this.printFilePath(fileName) report.error.data.forEach(logItem.bind(this)) report.warn.data.forEach(logItem.bind(this)) console.log('') // logging empty line } return report }
javascript
function lintFile (linter, fileName) { const fileContents = fs.readFileSync(fileName, {encoding: 'utf8'}).toString() const report = linter.validate(fileContents) const errors = report.error.count const warnings = report.warn.count if (errors || warnings) { this.printFilePath(fileName) report.error.data.forEach(logItem.bind(this)) report.warn.data.forEach(logItem.bind(this)) console.log('') // logging empty line } return report }
[ "function", "lintFile", "(", "linter", ",", "fileName", ")", "{", "const", "fileContents", "=", "fs", ".", "readFileSync", "(", "fileName", ",", "{", "encoding", ":", "'utf8'", "}", ")", ".", "toString", "(", ")", "const", "report", "=", "linter", ".", "validate", "(", "fileContents", ")", "const", "errors", "=", "report", ".", "error", ".", "count", "const", "warnings", "=", "report", ".", "warn", ".", "count", "if", "(", "errors", "||", "warnings", ")", "{", "this", ".", "printFilePath", "(", "fileName", ")", "report", ".", "error", ".", "data", ".", "forEach", "(", "logItem", ".", "bind", "(", "this", ")", ")", "report", ".", "warn", ".", "data", ".", "forEach", "(", "logItem", ".", "bind", "(", "this", ")", ")", "console", ".", "log", "(", "''", ")", "}", "return", "report", "}" ]
Lint a single Dockerfile @param {Object} linter - linter @param {String} fileName - name of file to lint @returns {Object} lint result
[ "Lint", "a", "single", "Dockerfile" ]
7e40f35d53c488b5f12968212110bb5a5ec138ea
https://github.com/ciena-blueplanet/ember-test-utils/blob/7e40f35d53c488b5f12968212110bb5a5ec138ea/cli/lint-docker.js#L71-L87
train
Testlio/lambda-tools
lib/helpers/newlines.js
processByte
function processByte (stream, b) { assert.equal(typeof b, 'number'); if (b === NEWLINE) { stream.emit('newline'); } }
javascript
function processByte (stream, b) { assert.equal(typeof b, 'number'); if (b === NEWLINE) { stream.emit('newline'); } }
[ "function", "processByte", "(", "stream", ",", "b", ")", "{", "assert", ".", "equal", "(", "typeof", "b", ",", "'number'", ")", ";", "if", "(", "b", "===", "NEWLINE", ")", "{", "stream", ".", "emit", "(", "'newline'", ")", ";", "}", "}" ]
Processes an individual byte being written to a stream
[ "Processes", "an", "individual", "byte", "being", "written", "to", "a", "stream" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/helpers/newlines.js#L34-L39
train
Testlio/lambda-tools
lib/helpers/logger.js
log
function log(fn, args, indent) { if (args.length === 0) { return; } // Assumes args are something you would pass into console.log // Applies appropriate nesting const indentation = _.repeat('\t', indent); // Prepend tabs to first arg (if string) if (_.isString(args[0])) { args[0] = indentation + args[0]; } else { args.splice(0, 0, indentation); } fn.apply(this, args); }
javascript
function log(fn, args, indent) { if (args.length === 0) { return; } // Assumes args are something you would pass into console.log // Applies appropriate nesting const indentation = _.repeat('\t', indent); // Prepend tabs to first arg (if string) if (_.isString(args[0])) { args[0] = indentation + args[0]; } else { args.splice(0, 0, indentation); } fn.apply(this, args); }
[ "function", "log", "(", "fn", ",", "args", ",", "indent", ")", "{", "if", "(", "args", ".", "length", "===", "0", ")", "{", "return", ";", "}", "const", "indentation", "=", "_", ".", "repeat", "(", "'\\t'", ",", "\\t", ")", ";", "indent", "if", "(", "_", ".", "isString", "(", "args", "[", "0", "]", ")", ")", "{", "args", "[", "0", "]", "=", "indentation", "+", "args", "[", "0", "]", ";", "}", "else", "{", "args", ".", "splice", "(", "0", ",", "0", ",", "indentation", ")", ";", "}", "}" ]
Internal helper for logging stuff out
[ "Internal", "helper", "for", "logging", "stuff", "out" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/helpers/logger.js#L15-L32
train
Testlio/lambda-tools
lib/cf-resources/lambda-version-resource/index.js
getFunction
function getFunction(name) { return new Promise((resolve, reject) => { lambda.getFunctionConfiguration({ FunctionName: name }, function(err, data) { if (err) return reject(err); resolve(data); }); }); }
javascript
function getFunction(name) { return new Promise((resolve, reject) => { lambda.getFunctionConfiguration({ FunctionName: name }, function(err, data) { if (err) return reject(err); resolve(data); }); }); }
[ "function", "getFunction", "(", "name", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "lambda", ".", "getFunctionConfiguration", "(", "{", "FunctionName", ":", "name", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get function configuration by its name @return {Promise} which resolves into the function configuration
[ "Get", "function", "configuration", "by", "its", "name" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/lambda-version-resource/index.js#L21-L30
train
Testlio/lambda-tools
lib/cf-resources/lambda-version-resource/index.js
getFunctionVersions
function getFunctionVersions(name, marker) { // Grab functions return new Promise((resolve, reject) => { lambda.listVersionsByFunction({ FunctionName: name, Marker: marker }, function(err, data) { if (err) return reject(err); // Check if we can grab even more if (data.NextMarker) { return getFunctionVersions(name, data.NextMarker).then((versions) => { resolve(data.Versions.concat(versions)); }); } resolve(data.Versions); }); }); }
javascript
function getFunctionVersions(name, marker) { // Grab functions return new Promise((resolve, reject) => { lambda.listVersionsByFunction({ FunctionName: name, Marker: marker }, function(err, data) { if (err) return reject(err); // Check if we can grab even more if (data.NextMarker) { return getFunctionVersions(name, data.NextMarker).then((versions) => { resolve(data.Versions.concat(versions)); }); } resolve(data.Versions); }); }); }
[ "function", "getFunctionVersions", "(", "name", ",", "marker", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "lambda", ".", "listVersionsByFunction", "(", "{", "FunctionName", ":", "name", ",", "Marker", ":", "marker", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "if", "(", "data", ".", "NextMarker", ")", "{", "return", "getFunctionVersions", "(", "name", ",", "data", ".", "NextMarker", ")", ".", "then", "(", "(", "versions", ")", "=>", "{", "resolve", "(", "data", ".", "Versions", ".", "concat", "(", "versions", ")", ")", ";", "}", ")", ";", "}", "resolve", "(", "data", ".", "Versions", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get all function versions @return {Promise} which resolves into an array of version configurations
[ "Get", "all", "function", "versions" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/lambda-version-resource/index.js#L37-L56
train
Testlio/lambda-tools
lib/cf-resources/lambda-version-resource/index.js
functionPublishVersion
function functionPublishVersion(name, description, hash) { return new Promise((resolve, reject) => { lambda.publishVersion({ FunctionName: name, Description: description, CodeSha256: hash }, function(err, data) { if (err) return reject(err); resolve(data); }); }); }
javascript
function functionPublishVersion(name, description, hash) { return new Promise((resolve, reject) => { lambda.publishVersion({ FunctionName: name, Description: description, CodeSha256: hash }, function(err, data) { if (err) return reject(err); resolve(data); }); }); }
[ "function", "functionPublishVersion", "(", "name", ",", "description", ",", "hash", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "lambda", ".", "publishVersion", "(", "{", "FunctionName", ":", "name", ",", "Description", ":", "description", ",", "CodeSha256", ":", "hash", "}", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Publish a new Lambda function version @return {Promise} which resolves into the newly published version
[ "Publish", "a", "new", "Lambda", "function", "version" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/lambda-version-resource/index.js#L63-L74
train
Testlio/lambda-tools
lib/run/execution.js
getDirectoryTree
function getDirectoryTree(dir) { const items = []; return new Promise(function(resolve) { fs.walk(dir) .on('data', function (item) { items.push(item.path); }) .on('end', function () { resolve(items); }); }); }
javascript
function getDirectoryTree(dir) { const items = []; return new Promise(function(resolve) { fs.walk(dir) .on('data', function (item) { items.push(item.path); }) .on('end', function () { resolve(items); }); }); }
[ "function", "getDirectoryTree", "(", "dir", ")", "{", "const", "items", "=", "[", "]", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "fs", ".", "walk", "(", "dir", ")", ".", "on", "(", "'data'", ",", "function", "(", "item", ")", "{", "items", ".", "push", "(", "item", ".", "path", ")", ";", "}", ")", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "resolve", "(", "items", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Helper function for capturing the state of a directory
[ "Helper", "function", "for", "capturing", "the", "state", "of", "a", "directory" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/run/execution.js#L14-L25
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/index.js
replaceVariables
function replaceVariables(localPath, variables) { return new Promise(function(resolve, reject) { // Read the file let body = fs.readFileSync(localPath, 'utf8'); // Do the replacement for all of the variables const keys = Object.keys(variables); keys.forEach(function(key) { const value = variables[key]; const re = new RegExp(`"\\$${key}"`, 'g'); // Parse the value (to see if it is falsey) try { const parsed = JSON.parse(value); body = body.replace(re, parsed ? `"${parsed}"` : `null`); } catch (err) { // Not valid JSON, treat it as a string body = body.replace(re, `"${value}"`); } }); console.log('Variables replaced', body); fs.writeFile(localPath, body, function(err) { if (err) return reject(err); resolve(localPath); }); }); }
javascript
function replaceVariables(localPath, variables) { return new Promise(function(resolve, reject) { // Read the file let body = fs.readFileSync(localPath, 'utf8'); // Do the replacement for all of the variables const keys = Object.keys(variables); keys.forEach(function(key) { const value = variables[key]; const re = new RegExp(`"\\$${key}"`, 'g'); // Parse the value (to see if it is falsey) try { const parsed = JSON.parse(value); body = body.replace(re, parsed ? `"${parsed}"` : `null`); } catch (err) { // Not valid JSON, treat it as a string body = body.replace(re, `"${value}"`); } }); console.log('Variables replaced', body); fs.writeFile(localPath, body, function(err) { if (err) return reject(err); resolve(localPath); }); }); }
[ "function", "replaceVariables", "(", "localPath", ",", "variables", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "let", "body", "=", "fs", ".", "readFileSync", "(", "localPath", ",", "'utf8'", ")", ";", "const", "keys", "=", "Object", ".", "keys", "(", "variables", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "const", "value", "=", "variables", "[", "key", "]", ";", "const", "re", "=", "new", "RegExp", "(", "`", "\\\\", "${", "key", "}", "`", ",", "'g'", ")", ";", "try", "{", "const", "parsed", "=", "JSON", ".", "parse", "(", "value", ")", ";", "body", "=", "body", ".", "replace", "(", "re", ",", "parsed", "?", "`", "${", "parsed", "}", "`", ":", "`", "`", ")", ";", "}", "catch", "(", "err", ")", "{", "body", "=", "body", ".", "replace", "(", "re", ",", "`", "${", "value", "}", "`", ")", ";", "}", "}", ")", ";", "console", ".", "log", "(", "'Variables replaced'", ",", "body", ")", ";", "fs", ".", "writeFile", "(", "localPath", ",", "body", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "localPath", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Helper function for replacing variables in the API definition @returns {Promise} which resolves into the same localPath the file was written back to
[ "Helper", "function", "for", "replacing", "variables", "in", "the", "API", "definition" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/index.js#L22-L49
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId) { return APIG.getStages({ restApiId: apiId }).promise().then(function(data) { return data.item; }); }
javascript
function(apiId) { return APIG.getStages({ restApiId: apiId }).promise().then(function(data) { return data.item; }); }
[ "function", "(", "apiId", ")", "{", "return", "APIG", ".", "getStages", "(", "{", "restApiId", ":", "apiId", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "data", ".", "item", ";", "}", ")", ";", "}" ]
Fetch existing stages for a specific API @return {Promise} which resolves to all stages for the specific API
[ "Fetch", "existing", "stages", "for", "a", "specific", "API" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L51-L57
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId, stageName) { return new Promise(function(resolve, reject) { APIG.deleteStage({ restApiId: apiId, stageName: stageName }, function(err) { if (err) { // If no such stage, then success if (err.code === 404 || err.code === 'NotFoundException') { return resolve(apiId); } return reject(err); } resolve(apiId); }); }); }
javascript
function(apiId, stageName) { return new Promise(function(resolve, reject) { APIG.deleteStage({ restApiId: apiId, stageName: stageName }, function(err) { if (err) { // If no such stage, then success if (err.code === 404 || err.code === 'NotFoundException') { return resolve(apiId); } return reject(err); } resolve(apiId); }); }); }
[ "function", "(", "apiId", ",", "stageName", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "APIG", ".", "deleteStage", "(", "{", "restApiId", ":", "apiId", ",", "stageName", ":", "stageName", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "404", "||", "err", ".", "code", "===", "'NotFoundException'", ")", "{", "return", "resolve", "(", "apiId", ")", ";", "}", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", "apiId", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Delete a specific stage on a specific API @return {Promise} which resolves to the API ID that the stage was deleted on
[ "Delete", "a", "specific", "stage", "on", "a", "specific", "API" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L71-L89
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId) { return new Promise(function(resolve, reject) { APIG.deleteRestApi({ restApiId: apiId }, function(err) { if (err) { if (err.code === 404 || err.code === 'NotFoundException') { // API didn't exist to begin with return resolve(apiId); } return reject(err); } resolve(apiId); }); }); }
javascript
function(apiId) { return new Promise(function(resolve, reject) { APIG.deleteRestApi({ restApiId: apiId }, function(err) { if (err) { if (err.code === 404 || err.code === 'NotFoundException') { // API didn't exist to begin with return resolve(apiId); } return reject(err); } resolve(apiId); }); }); }
[ "function", "(", "apiId", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "APIG", ".", "deleteRestApi", "(", "{", "restApiId", ":", "apiId", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "404", "||", "err", ".", "code", "===", "'NotFoundException'", ")", "{", "return", "resolve", "(", "apiId", ")", ";", "}", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", "apiId", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Delete the entire API ID @return {Promise} which resolves to the ID of the API that was deleted
[ "Delete", "the", "entire", "API", "ID" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L96-L113
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId) { return module.exports.fetchExistingStages(apiId).then(function(stages) { // If there are no stages, then delete the API if (!stages || stages.length === 0) { return module.exports.deleteAPI(apiId); } return apiId; }); }
javascript
function(apiId) { return module.exports.fetchExistingStages(apiId).then(function(stages) { // If there are no stages, then delete the API if (!stages || stages.length === 0) { return module.exports.deleteAPI(apiId); } return apiId; }); }
[ "function", "(", "apiId", ")", "{", "return", "module", ".", "exports", ".", "fetchExistingStages", "(", "apiId", ")", ".", "then", "(", "function", "(", "stages", ")", "{", "if", "(", "!", "stages", "||", "stages", ".", "length", "===", "0", ")", "{", "return", "module", ".", "exports", ".", "deleteAPI", "(", "apiId", ")", ";", "}", "return", "apiId", ";", "}", ")", ";", "}" ]
Delete the API if and only if there are no more stages deployed on it @return {Promise} which resolves to the ID of the API that was deleted
[ "Delete", "the", "API", "if", "and", "only", "if", "there", "are", "no", "more", "stages", "deployed", "on", "it" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L120-L129
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiName, swaggerPath) { return new Promise(function(resolve, reject) { fs.readFile(swaggerPath, function(err, data) { if (err) return reject(err); resolve(APIG.importRestApi({ body: data, failOnWarnings: false }).promise()); }); }); }
javascript
function(apiName, swaggerPath) { return new Promise(function(resolve, reject) { fs.readFile(swaggerPath, function(err, data) { if (err) return reject(err); resolve(APIG.importRestApi({ body: data, failOnWarnings: false }).promise()); }); }); }
[ "function", "(", "apiName", ",", "swaggerPath", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "swaggerPath", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "APIG", ".", "importRestApi", "(", "{", "body", ":", "data", ",", "failOnWarnings", ":", "false", "}", ")", ".", "promise", "(", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create a new API instance from a Swagger file @return {Promise} which resolves to the newly created API instance
[ "Create", "a", "new", "API", "instance", "from", "a", "Swagger", "file" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L161-L172
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/apig-utility.js
function(apiId, swaggerPath) { return new Promise(function(resolve, reject) { fs.readFile(swaggerPath, function(err, data) { if (err) return reject(err); resolve(APIG.putRestApi({ restApiId: apiId, body: data, mode: 'overwrite' }).promise()); }); }); }
javascript
function(apiId, swaggerPath) { return new Promise(function(resolve, reject) { fs.readFile(swaggerPath, function(err, data) { if (err) return reject(err); resolve(APIG.putRestApi({ restApiId: apiId, body: data, mode: 'overwrite' }).promise()); }); }); }
[ "function", "(", "apiId", ",", "swaggerPath", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "readFile", "(", "swaggerPath", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "APIG", ".", "putRestApi", "(", "{", "restApiId", ":", "apiId", ",", "body", ":", "data", ",", "mode", ":", "'overwrite'", "}", ")", ".", "promise", "(", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update an API with a specification from a Swagger file The update is done in the "overwrite" mode of API Gateway @return {Promise} which resolves to the updated API
[ "Update", "an", "API", "with", "a", "specification", "from", "a", "Swagger", "file", "The", "update", "is", "done", "in", "the", "overwrite", "mode", "of", "API", "Gateway" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/apig-utility.js#L180-L192
train
Testlio/lambda-tools
lib/deploy/bundle-lambdas-step.js
archiveDependencies
function archiveDependencies(cwd, pkg) { let result = []; if (pkg.path) { result.push({ data: pkg.path, type: 'directory', name: path.relative(cwd, pkg.path) }); } pkg.dependencies.forEach(function(dep) { if (dep.path) { result.push({ data: dep.path, type: 'directory', name: path.relative(cwd, dep.path) }); } if (dep.dependencies) { result = result.concat(archiveDependencies(cwd, dep)); } }); return result; }
javascript
function archiveDependencies(cwd, pkg) { let result = []; if (pkg.path) { result.push({ data: pkg.path, type: 'directory', name: path.relative(cwd, pkg.path) }); } pkg.dependencies.forEach(function(dep) { if (dep.path) { result.push({ data: dep.path, type: 'directory', name: path.relative(cwd, dep.path) }); } if (dep.dependencies) { result = result.concat(archiveDependencies(cwd, dep)); } }); return result; }
[ "function", "archiveDependencies", "(", "cwd", ",", "pkg", ")", "{", "let", "result", "=", "[", "]", ";", "if", "(", "pkg", ".", "path", ")", "{", "result", ".", "push", "(", "{", "data", ":", "pkg", ".", "path", ",", "type", ":", "'directory'", ",", "name", ":", "path", ".", "relative", "(", "cwd", ",", "pkg", ".", "path", ")", "}", ")", ";", "}", "pkg", ".", "dependencies", ".", "forEach", "(", "function", "(", "dep", ")", "{", "if", "(", "dep", ".", "path", ")", "{", "result", ".", "push", "(", "{", "data", ":", "dep", ".", "path", ",", "type", ":", "'directory'", ",", "name", ":", "path", ".", "relative", "(", "cwd", ",", "dep", ".", "path", ")", "}", ")", ";", "}", "if", "(", "dep", ".", "dependencies", ")", "{", "result", "=", "result", ".", "concat", "(", "archiveDependencies", "(", "cwd", ",", "dep", ")", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Helper for recursively adding all dependencies to an archive
[ "Helper", "for", "recursively", "adding", "all", "dependencies", "to", "an", "archive" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/deploy/bundle-lambdas-step.js#L26-L52
train
Testlio/lambda-tools
lib/deploy/bundle-lambdas-step.js
bundleLambda
function bundleLambda(lambda, exclude, environment, bundlePath, sourceMapPath) { environment = environment || {}; exclude = exclude || []; return new Promise(function(resolve, reject) { const bundler = new Browserify(lambda.path, { basedir: path.dirname(lambda.path), standalone: lambda.name, browserField: false, builtins: false, commondir: false, ignoreMissing: true, detectGlobals: true, debug: !!sourceMapPath, insertGlobalVars: { process: function() {} } }); // AWS SDK should always be excluded bundler.exclude('aws-sdk'); // Further things to exclude [].concat(exclude).forEach(function(module) { bundler.exclude(module); }); // Envify (doesn't purge, as there are valid values // that can be used in Lambda functions) if (environment) { bundler.transform(envify(environment), { global: true }); } let stream = bundler.bundle(); if (sourceMapPath) { stream = stream.pipe(exorcist(sourceMapPath)); } stream.pipe(fs.createWriteStream(bundlePath)); stream.on('error', function(err) { reject(err); }).on('end', function() { resolve(); }); }); }
javascript
function bundleLambda(lambda, exclude, environment, bundlePath, sourceMapPath) { environment = environment || {}; exclude = exclude || []; return new Promise(function(resolve, reject) { const bundler = new Browserify(lambda.path, { basedir: path.dirname(lambda.path), standalone: lambda.name, browserField: false, builtins: false, commondir: false, ignoreMissing: true, detectGlobals: true, debug: !!sourceMapPath, insertGlobalVars: { process: function() {} } }); // AWS SDK should always be excluded bundler.exclude('aws-sdk'); // Further things to exclude [].concat(exclude).forEach(function(module) { bundler.exclude(module); }); // Envify (doesn't purge, as there are valid values // that can be used in Lambda functions) if (environment) { bundler.transform(envify(environment), { global: true }); } let stream = bundler.bundle(); if (sourceMapPath) { stream = stream.pipe(exorcist(sourceMapPath)); } stream.pipe(fs.createWriteStream(bundlePath)); stream.on('error', function(err) { reject(err); }).on('end', function() { resolve(); }); }); }
[ "function", "bundleLambda", "(", "lambda", ",", "exclude", ",", "environment", ",", "bundlePath", ",", "sourceMapPath", ")", "{", "environment", "=", "environment", "||", "{", "}", ";", "exclude", "=", "exclude", "||", "[", "]", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "const", "bundler", "=", "new", "Browserify", "(", "lambda", ".", "path", ",", "{", "basedir", ":", "path", ".", "dirname", "(", "lambda", ".", "path", ")", ",", "standalone", ":", "lambda", ".", "name", ",", "browserField", ":", "false", ",", "builtins", ":", "false", ",", "commondir", ":", "false", ",", "ignoreMissing", ":", "true", ",", "detectGlobals", ":", "true", ",", "debug", ":", "!", "!", "sourceMapPath", ",", "insertGlobalVars", ":", "{", "process", ":", "function", "(", ")", "{", "}", "}", "}", ")", ";", "bundler", ".", "exclude", "(", "'aws-sdk'", ")", ";", "[", "]", ".", "concat", "(", "exclude", ")", ".", "forEach", "(", "function", "(", "module", ")", "{", "bundler", ".", "exclude", "(", "module", ")", ";", "}", ")", ";", "if", "(", "environment", ")", "{", "bundler", ".", "transform", "(", "envify", "(", "environment", ")", ",", "{", "global", ":", "true", "}", ")", ";", "}", "let", "stream", "=", "bundler", ".", "bundle", "(", ")", ";", "if", "(", "sourceMapPath", ")", "{", "stream", "=", "stream", ".", "pipe", "(", "exorcist", "(", "sourceMapPath", ")", ")", ";", "}", "stream", ".", "pipe", "(", "fs", ".", "createWriteStream", "(", "bundlePath", ")", ")", ";", "stream", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", ")", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Processing pipeline, all functions should return a promise Bundles the lambda code, returning the bundled code @param lambda Lambda function to bundle, should at minimum have a path property with the entry point @param exclude Array of packages to exclude from the bundle, defaults to aws-sdk @param environment Env variables to envify @param bundlePath Path to save the bundled code to @param sourceMapPath Path to save the source maps to @returns Promise that bundles the code and writes it to a file
[ "Processing", "pipeline", "all", "functions", "should", "return", "a", "promise", "Bundles", "the", "lambda", "code", "returning", "the", "bundled", "code" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/deploy/bundle-lambdas-step.js#L70-L118
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/s3-utility.js
function(bucket, key, version, localPath) { return S3.getObject({ Bucket: bucket, Key: key, VersionId: version }).promise().then(function(data) { return new Promise(function(resolve, reject) { fs.writeFile(localPath, data.Body, function(err) { if (err) return reject(err); resolve(localPath); }); }); }); }
javascript
function(bucket, key, version, localPath) { return S3.getObject({ Bucket: bucket, Key: key, VersionId: version }).promise().then(function(data) { return new Promise(function(resolve, reject) { fs.writeFile(localPath, data.Body, function(err) { if (err) return reject(err); resolve(localPath); }); }); }); }
[ "function", "(", "bucket", ",", "key", ",", "version", ",", "localPath", ")", "{", "return", "S3", ".", "getObject", "(", "{", "Bucket", ":", "bucket", ",", "Key", ":", "key", ",", "VersionId", ":", "version", "}", ")", ".", "promise", "(", ")", ".", "then", "(", "function", "(", "data", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "fs", ".", "writeFile", "(", "localPath", ",", "data", ".", "Body", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "resolve", "(", "localPath", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Download a file from remote bucket to a local path @return {Promise} which resolves to the local path the file was saved to
[ "Download", "a", "file", "from", "remote", "bucket", "to", "a", "local", "path" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/s3-utility.js#L16-L29
train
Testlio/lambda-tools
lib/cf-resources/api-gateway-resource/s3-utility.js
function(bucket, key, version) { return S3.headObject({ Bucket: bucket, Key: key, VersionId: version }).promise(); }
javascript
function(bucket, key, version) { return S3.headObject({ Bucket: bucket, Key: key, VersionId: version }).promise(); }
[ "function", "(", "bucket", ",", "key", ",", "version", ")", "{", "return", "S3", ".", "headObject", "(", "{", "Bucket", ":", "bucket", ",", "Key", ":", "key", ",", "VersionId", ":", "version", "}", ")", ".", "promise", "(", ")", ";", "}" ]
Execute a HEAD operation on a specific key in a bucket. The request can also contain an optional version for the file @returns {Promise} which resolves to the response data for the request
[ "Execute", "a", "HEAD", "operation", "on", "a", "specific", "key", "in", "a", "bucket", ".", "The", "request", "can", "also", "contain", "an", "optional", "version", "for", "the", "file" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/cf-resources/api-gateway-resource/s3-utility.js#L37-L43
train
Testlio/lambda-tools
lib/helpers/cf-template-functions.js
cloudFormationDependencies
function cloudFormationDependencies(value) { if (_.isString(value)) { return [value]; } if (!_.isObject(value)) { return []; } const keys = _.keys(value); if (keys.length !== 1) { // CF functions always have a single key return []; } const key = keys[0]; if (key === 'Fn::GetAtt') { // Logical name of resource is the first value in array return cloudFormationDependencies(value[key][0]); } if (key === 'Ref') { // Value should be the logical name (but may be a further function) return cloudFormationDependencies(value[key]); } if (key === 'Fn::Join') { // Value is the combined string, meaning parts that are not // string can all include dependencies return _.flatten(value[key][1].filter(_.isObject).map(cloudFormationDependencies)); } if (key === 'Fn::Select') { // Value is picked from an array const index = value[key][0]; const list = value[key][1]; return cloudFormationDependencies(list[index]); } // Unknown/Unhandled return []; }
javascript
function cloudFormationDependencies(value) { if (_.isString(value)) { return [value]; } if (!_.isObject(value)) { return []; } const keys = _.keys(value); if (keys.length !== 1) { // CF functions always have a single key return []; } const key = keys[0]; if (key === 'Fn::GetAtt') { // Logical name of resource is the first value in array return cloudFormationDependencies(value[key][0]); } if (key === 'Ref') { // Value should be the logical name (but may be a further function) return cloudFormationDependencies(value[key]); } if (key === 'Fn::Join') { // Value is the combined string, meaning parts that are not // string can all include dependencies return _.flatten(value[key][1].filter(_.isObject).map(cloudFormationDependencies)); } if (key === 'Fn::Select') { // Value is picked from an array const index = value[key][0]; const list = value[key][1]; return cloudFormationDependencies(list[index]); } // Unknown/Unhandled return []; }
[ "function", "cloudFormationDependencies", "(", "value", ")", "{", "if", "(", "_", ".", "isString", "(", "value", ")", ")", "{", "return", "[", "value", "]", ";", "}", "if", "(", "!", "_", ".", "isObject", "(", "value", ")", ")", "{", "return", "[", "]", ";", "}", "const", "keys", "=", "_", ".", "keys", "(", "value", ")", ";", "if", "(", "keys", ".", "length", "!==", "1", ")", "{", "return", "[", "]", ";", "}", "const", "key", "=", "keys", "[", "0", "]", ";", "if", "(", "key", "===", "'Fn::GetAtt'", ")", "{", "return", "cloudFormationDependencies", "(", "value", "[", "key", "]", "[", "0", "]", ")", ";", "}", "if", "(", "key", "===", "'Ref'", ")", "{", "return", "cloudFormationDependencies", "(", "value", "[", "key", "]", ")", ";", "}", "if", "(", "key", "===", "'Fn::Join'", ")", "{", "return", "_", ".", "flatten", "(", "value", "[", "key", "]", "[", "1", "]", ".", "filter", "(", "_", ".", "isObject", ")", ".", "map", "(", "cloudFormationDependencies", ")", ")", ";", "}", "if", "(", "key", "===", "'Fn::Select'", ")", "{", "const", "index", "=", "value", "[", "key", "]", "[", "0", "]", ";", "const", "list", "=", "value", "[", "key", "]", "[", "1", "]", ";", "return", "cloudFormationDependencies", "(", "list", "[", "index", "]", ")", ";", "}", "return", "[", "]", ";", "}" ]
Helper function for deriving the list of resources that are referenced by a CF function @param value, CF value, may be a string, or an object @returns {array} array of strings, containing all resource names that are used by the value (that the value depends on)
[ "Helper", "function", "for", "deriving", "the", "list", "of", "resources", "that", "are", "referenced", "by", "a", "CF", "function" ]
b9ae92917cfea511da5528c738985777ed87c1d3
https://github.com/Testlio/lambda-tools/blob/b9ae92917cfea511da5528c738985777ed87c1d3/lib/helpers/cf-template-functions.js#L13-L55
train
dashersw/erste
src/lib/base/eventemitter3.js
EE
function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; }
javascript
function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; }
[ "function", "EE", "(", "fn", ",", "context", ",", "once", ")", "{", "this", ".", "fn", "=", "fn", ";", "this", ".", "context", "=", "context", ";", "this", ".", "once", "=", "once", "||", "false", ";", "}" ]
Representation of a single event listener. @param {Function} fn The listener function. @param {*} context The context to invoke the listener with. @param {boolean} [once=false] Specify if the listener is a one-time listener. @constructor @private
[ "Representation", "of", "a", "single", "event", "listener", "." ]
f916bfdf87bdf6f939184d205c049bbd54a6574f
https://github.com/dashersw/erste/blob/f916bfdf87bdf6f939184d205c049bbd54a6574f/src/lib/base/eventemitter3.js#L76-L80
train
dashersw/erste
src/lib/base/eventemitter3.js
addListener
function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; }
javascript
function addListener(emitter, event, fn, context, once) { if (typeof fn !== 'function') { throw new TypeError('The listener must be a function'); } var listener = new EE(fn, context || emitter, once) , evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; }
[ "function", "addListener", "(", "emitter", ",", "event", ",", "fn", ",", "context", ",", "once", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'The listener must be a function'", ")", ";", "}", "var", "listener", "=", "new", "EE", "(", "fn", ",", "context", "||", "emitter", ",", "once", ")", ",", "evt", "=", "prefix", "?", "prefix", "+", "event", ":", "event", ";", "if", "(", "!", "emitter", ".", "_events", "[", "evt", "]", ")", "emitter", ".", "_events", "[", "evt", "]", "=", "listener", ",", "emitter", ".", "_eventsCount", "++", ";", "else", "if", "(", "!", "emitter", ".", "_events", "[", "evt", "]", ".", "fn", ")", "emitter", ".", "_events", "[", "evt", "]", ".", "push", "(", "listener", ")", ";", "else", "emitter", ".", "_events", "[", "evt", "]", "=", "[", "emitter", ".", "_events", "[", "evt", "]", ",", "listener", "]", ";", "return", "emitter", ";", "}" ]
Add a listener for a given event. @param {EventEmitter} emitter Reference to the `EventEmitter` instance. @param {(string|Symbol)} event The event name. @param {Function} fn The listener function. @param {*} context The context to invoke the listener with. @param {boolean} once Specify if the listener is a one-time listener. @returns {EventEmitter} @private
[ "Add", "a", "listener", "for", "a", "given", "event", "." ]
f916bfdf87bdf6f939184d205c049bbd54a6574f
https://github.com/dashersw/erste/blob/f916bfdf87bdf6f939184d205c049bbd54a6574f/src/lib/base/eventemitter3.js#L93-L106
train
dashersw/erste
src/lib/base/eventemitter3.js
clearEvent
function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; }
javascript
function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; }
[ "function", "clearEvent", "(", "emitter", ",", "evt", ")", "{", "if", "(", "--", "emitter", ".", "_eventsCount", "===", "0", ")", "emitter", ".", "_events", "=", "new", "Events", "(", ")", ";", "else", "delete", "emitter", ".", "_events", "[", "evt", "]", ";", "}" ]
Clear event by name. @param {EventEmitter} emitter Reference to the `EventEmitter` instance. @param {(string|Symbol|number)} evt The Event name. @private
[ "Clear", "event", "by", "name", "." ]
f916bfdf87bdf6f939184d205c049bbd54a6574f
https://github.com/dashersw/erste/blob/f916bfdf87bdf6f939184d205c049bbd54a6574f/src/lib/base/eventemitter3.js#L115-L118
train
meeroslav/gulp-inject-partials
src/index.js
handleStream
function handleStream(target, encoding, cb) { if (target.isNull()) { return cb(null, target); } if (target.isStream()) { return cb(error(target.path + ': Streams not supported for target templates!')); } try { const tagsRegExp = getRegExpTags(opt, null); target.contents = processContent(target, opt, tagsRegExp, [target.path]); this.push(target); return cb(); } catch (err) { this.emit('error', err); return cb(); } }
javascript
function handleStream(target, encoding, cb) { if (target.isNull()) { return cb(null, target); } if (target.isStream()) { return cb(error(target.path + ': Streams not supported for target templates!')); } try { const tagsRegExp = getRegExpTags(opt, null); target.contents = processContent(target, opt, tagsRegExp, [target.path]); this.push(target); return cb(); } catch (err) { this.emit('error', err); return cb(); } }
[ "function", "handleStream", "(", "target", ",", "encoding", ",", "cb", ")", "{", "if", "(", "target", ".", "isNull", "(", ")", ")", "{", "return", "cb", "(", "null", ",", "target", ")", ";", "}", "if", "(", "target", ".", "isStream", "(", ")", ")", "{", "return", "cb", "(", "error", "(", "target", ".", "path", "+", "': Streams not supported for target templates!'", ")", ")", ";", "}", "try", "{", "const", "tagsRegExp", "=", "getRegExpTags", "(", "opt", ",", "null", ")", ";", "target", ".", "contents", "=", "processContent", "(", "target", ",", "opt", ",", "tagsRegExp", ",", "[", "target", ".", "path", "]", ")", ";", "this", ".", "push", "(", "target", ")", ";", "return", "cb", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "this", ".", "emit", "(", "'error'", ",", "err", ")", ";", "return", "cb", "(", ")", ";", "}", "}" ]
Handle injection of files @param target @param encoding @param cb @returns {*}
[ "Handle", "injection", "of", "files" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.js#L40-L58
train
meeroslav/gulp-inject-partials
src/index.js
processContent
function processContent(target, opt, tagsRegExp, listOfFiles) { let targetContent = String(target.contents); const targetPath = target.path; const files = extractFilePaths(targetContent, targetPath, opt, tagsRegExp); // recursively process files files.forEach(function (fileData) { if (listOfFiles.indexOf(fileData.file.path) !== -1) { throw error("Circular definition found. File: " + fileData.file.path + " referenced in a child file."); } listOfFiles.push(fileData.file.path); const content = processContent(fileData.file, opt, tagsRegExp, listOfFiles); listOfFiles.pop(); targetContent = inject(targetContent, String(content), opt, fileData.tags); }); if (listOfFiles.length === 1 && !opt.quiet && files.length) { log( colors.cyan(files.length.toString()) + ' partials injected into ' + colors.magenta(targetPath) + '.'); } return new Buffer.from(targetContent); }
javascript
function processContent(target, opt, tagsRegExp, listOfFiles) { let targetContent = String(target.contents); const targetPath = target.path; const files = extractFilePaths(targetContent, targetPath, opt, tagsRegExp); // recursively process files files.forEach(function (fileData) { if (listOfFiles.indexOf(fileData.file.path) !== -1) { throw error("Circular definition found. File: " + fileData.file.path + " referenced in a child file."); } listOfFiles.push(fileData.file.path); const content = processContent(fileData.file, opt, tagsRegExp, listOfFiles); listOfFiles.pop(); targetContent = inject(targetContent, String(content), opt, fileData.tags); }); if (listOfFiles.length === 1 && !opt.quiet && files.length) { log( colors.cyan(files.length.toString()) + ' partials injected into ' + colors.magenta(targetPath) + '.'); } return new Buffer.from(targetContent); }
[ "function", "processContent", "(", "target", ",", "opt", ",", "tagsRegExp", ",", "listOfFiles", ")", "{", "let", "targetContent", "=", "String", "(", "target", ".", "contents", ")", ";", "const", "targetPath", "=", "target", ".", "path", ";", "const", "files", "=", "extractFilePaths", "(", "targetContent", ",", "targetPath", ",", "opt", ",", "tagsRegExp", ")", ";", "files", ".", "forEach", "(", "function", "(", "fileData", ")", "{", "if", "(", "listOfFiles", ".", "indexOf", "(", "fileData", ".", "file", ".", "path", ")", "!==", "-", "1", ")", "{", "throw", "error", "(", "\"Circular definition found. File: \"", "+", "fileData", ".", "file", ".", "path", "+", "\" referenced in a child file.\"", ")", ";", "}", "listOfFiles", ".", "push", "(", "fileData", ".", "file", ".", "path", ")", ";", "const", "content", "=", "processContent", "(", "fileData", ".", "file", ",", "opt", ",", "tagsRegExp", ",", "listOfFiles", ")", ";", "listOfFiles", ".", "pop", "(", ")", ";", "targetContent", "=", "inject", "(", "targetContent", ",", "String", "(", "content", ")", ",", "opt", ",", "fileData", ".", "tags", ")", ";", "}", ")", ";", "if", "(", "listOfFiles", ".", "length", "===", "1", "&&", "!", "opt", ".", "quiet", "&&", "files", ".", "length", ")", "{", "log", "(", "colors", ".", "cyan", "(", "files", ".", "length", ".", "toString", "(", ")", ")", "+", "' partials injected into '", "+", "colors", ".", "magenta", "(", "targetPath", ")", "+", "'.'", ")", ";", "}", "return", "new", "Buffer", ".", "from", "(", "targetContent", ")", ";", "}" ]
Parse content and create new template with all injections made @param {Object} target @param {Object} opt @param {Object} tagsRegExp @param {Array} listOfFiles @returns {Buffer}
[ "Parse", "content", "and", "create", "new", "template", "with", "all", "injections", "made" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.js#L73-L97
train
meeroslav/gulp-inject-partials
src/index.js
inject
function inject(targetContent, sourceContent, opt, tagsRegExp) { const startTag = tagsRegExp.start; const endTag = tagsRegExp.end; let startMatch; let endMatch; while ((startMatch = startTag.exec(targetContent)) !== null) { // Take care of content length change endTag.lastIndex = startTag.lastIndex; endMatch = endTag.exec(targetContent); if (!endMatch) { throw error('Missing end tag for start tag: ' + startMatch[0]); } const toInject = [sourceContent]; // content part before start tag let newContent = targetContent.slice(0, startMatch.index); if (opt.removeTags) { // Take care of content length change startTag.lastIndex -= startMatch[0].length; } else { // <startMatch> + partial body + <endMatch> toInject.unshift(startMatch[0]); toInject.push(endMatch[0]); } const previousInnerContent = targetContent.substring(startTag.lastIndex, endMatch.index); const indent = getLeadingWhitespace(previousInnerContent); // add new content newContent += toInject.join(indent); // append rest of target file newContent += targetContent.slice(endTag.lastIndex); // replace old content with new targetContent = newContent; } startTag.lastIndex = 0; endTag.lastIndex = 0; return targetContent; }
javascript
function inject(targetContent, sourceContent, opt, tagsRegExp) { const startTag = tagsRegExp.start; const endTag = tagsRegExp.end; let startMatch; let endMatch; while ((startMatch = startTag.exec(targetContent)) !== null) { // Take care of content length change endTag.lastIndex = startTag.lastIndex; endMatch = endTag.exec(targetContent); if (!endMatch) { throw error('Missing end tag for start tag: ' + startMatch[0]); } const toInject = [sourceContent]; // content part before start tag let newContent = targetContent.slice(0, startMatch.index); if (opt.removeTags) { // Take care of content length change startTag.lastIndex -= startMatch[0].length; } else { // <startMatch> + partial body + <endMatch> toInject.unshift(startMatch[0]); toInject.push(endMatch[0]); } const previousInnerContent = targetContent.substring(startTag.lastIndex, endMatch.index); const indent = getLeadingWhitespace(previousInnerContent); // add new content newContent += toInject.join(indent); // append rest of target file newContent += targetContent.slice(endTag.lastIndex); // replace old content with new targetContent = newContent; } startTag.lastIndex = 0; endTag.lastIndex = 0; return targetContent; }
[ "function", "inject", "(", "targetContent", ",", "sourceContent", ",", "opt", ",", "tagsRegExp", ")", "{", "const", "startTag", "=", "tagsRegExp", ".", "start", ";", "const", "endTag", "=", "tagsRegExp", ".", "end", ";", "let", "startMatch", ";", "let", "endMatch", ";", "while", "(", "(", "startMatch", "=", "startTag", ".", "exec", "(", "targetContent", ")", ")", "!==", "null", ")", "{", "endTag", ".", "lastIndex", "=", "startTag", ".", "lastIndex", ";", "endMatch", "=", "endTag", ".", "exec", "(", "targetContent", ")", ";", "if", "(", "!", "endMatch", ")", "{", "throw", "error", "(", "'Missing end tag for start tag: '", "+", "startMatch", "[", "0", "]", ")", ";", "}", "const", "toInject", "=", "[", "sourceContent", "]", ";", "let", "newContent", "=", "targetContent", ".", "slice", "(", "0", ",", "startMatch", ".", "index", ")", ";", "if", "(", "opt", ".", "removeTags", ")", "{", "startTag", ".", "lastIndex", "-=", "startMatch", "[", "0", "]", ".", "length", ";", "}", "else", "{", "toInject", ".", "unshift", "(", "startMatch", "[", "0", "]", ")", ";", "toInject", ".", "push", "(", "endMatch", "[", "0", "]", ")", ";", "}", "const", "previousInnerContent", "=", "targetContent", ".", "substring", "(", "startTag", ".", "lastIndex", ",", "endMatch", ".", "index", ")", ";", "const", "indent", "=", "getLeadingWhitespace", "(", "previousInnerContent", ")", ";", "newContent", "+=", "toInject", ".", "join", "(", "indent", ")", ";", "newContent", "+=", "targetContent", ".", "slice", "(", "endTag", ".", "lastIndex", ")", ";", "targetContent", "=", "newContent", ";", "}", "startTag", ".", "lastIndex", "=", "0", ";", "endTag", ".", "lastIndex", "=", "0", ";", "return", "targetContent", ";", "}" ]
Inject tags into target content between given start and end tags @param {String} targetContent @param {String} sourceContent @param {Object} opt @param {Object} tagsRegExp @returns {String}
[ "Inject", "tags", "into", "target", "content", "between", "given", "start", "and", "end", "tags" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.js#L109-L146
train
meeroslav/gulp-inject-partials
src/index.js
extractFilePaths
function extractFilePaths(content, targetPath, opt, tagsRegExp) { const files = []; const tagMatches = content.match(tagsRegExp.start); if (tagMatches) { tagMatches.forEach(function (tagMatch) { const fileUrl = tagsRegExp.startex.exec(tagMatch)[1]; const filePath = setFullPath(targetPath, opt.prefix + fileUrl); try { const fileContent = stripBomBuf(fs.readFileSync(filePath)); files.push({ file: new File({ path: filePath, cwd: __dirname, base: path.resolve(__dirname, 'expected', path.dirname(filePath)), contents: fileContent }), tags: getRegExpTags(opt, fileUrl) }); } catch (e) { if (opt.ignoreError) { log(colors.red(filePath + ' not found.')); } else { throw error(filePath + ' not found.'); } } // reset the regex tagsRegExp.startex.lastIndex = 0; }); } return files; }
javascript
function extractFilePaths(content, targetPath, opt, tagsRegExp) { const files = []; const tagMatches = content.match(tagsRegExp.start); if (tagMatches) { tagMatches.forEach(function (tagMatch) { const fileUrl = tagsRegExp.startex.exec(tagMatch)[1]; const filePath = setFullPath(targetPath, opt.prefix + fileUrl); try { const fileContent = stripBomBuf(fs.readFileSync(filePath)); files.push({ file: new File({ path: filePath, cwd: __dirname, base: path.resolve(__dirname, 'expected', path.dirname(filePath)), contents: fileContent }), tags: getRegExpTags(opt, fileUrl) }); } catch (e) { if (opt.ignoreError) { log(colors.red(filePath + ' not found.')); } else { throw error(filePath + ' not found.'); } } // reset the regex tagsRegExp.startex.lastIndex = 0; }); } return files; }
[ "function", "extractFilePaths", "(", "content", ",", "targetPath", ",", "opt", ",", "tagsRegExp", ")", "{", "const", "files", "=", "[", "]", ";", "const", "tagMatches", "=", "content", ".", "match", "(", "tagsRegExp", ".", "start", ")", ";", "if", "(", "tagMatches", ")", "{", "tagMatches", ".", "forEach", "(", "function", "(", "tagMatch", ")", "{", "const", "fileUrl", "=", "tagsRegExp", ".", "startex", ".", "exec", "(", "tagMatch", ")", "[", "1", "]", ";", "const", "filePath", "=", "setFullPath", "(", "targetPath", ",", "opt", ".", "prefix", "+", "fileUrl", ")", ";", "try", "{", "const", "fileContent", "=", "stripBomBuf", "(", "fs", ".", "readFileSync", "(", "filePath", ")", ")", ";", "files", ".", "push", "(", "{", "file", ":", "new", "File", "(", "{", "path", ":", "filePath", ",", "cwd", ":", "__dirname", ",", "base", ":", "path", ".", "resolve", "(", "__dirname", ",", "'expected'", ",", "path", ".", "dirname", "(", "filePath", ")", ")", ",", "contents", ":", "fileContent", "}", ")", ",", "tags", ":", "getRegExpTags", "(", "opt", ",", "fileUrl", ")", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "opt", ".", "ignoreError", ")", "{", "log", "(", "colors", ".", "red", "(", "filePath", "+", "' not found.'", ")", ")", ";", "}", "else", "{", "throw", "error", "(", "filePath", "+", "' not found.'", ")", ";", "}", "}", "tagsRegExp", ".", "startex", ".", "lastIndex", "=", "0", ";", "}", ")", ";", "}", "return", "files", ";", "}" ]
Parse content and get all partials to be injected @param {String} content @param {String} targetPath @param {Object} opt @param {Object} tagsRegExp @returns {Array}
[ "Parse", "content", "and", "get", "all", "partials", "to", "be", "injected" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.js#L183-L214
train
weepy/kaffeine
lib/token.js
function(child, parent) { var ctor = function(){ }; ctor.prototype = parent.prototype; child.__super__ = parent.prototype; child.prototype = new ctor(); child.prototype.constructor = child; child.fn = child.prototype }
javascript
function(child, parent) { var ctor = function(){ }; ctor.prototype = parent.prototype; child.__super__ = parent.prototype; child.prototype = new ctor(); child.prototype.constructor = child; child.fn = child.prototype }
[ "function", "(", "child", ",", "parent", ")", "{", "var", "ctor", "=", "function", "(", ")", "{", "}", ";", "ctor", ".", "prototype", "=", "parent", ".", "prototype", ";", "child", ".", "__super__", "=", "parent", ".", "prototype", ";", "child", ".", "prototype", "=", "new", "ctor", "(", ")", ";", "child", ".", "prototype", ".", "constructor", "=", "child", ";", "child", ".", "fn", "=", "child", ".", "prototype", "}" ]
var log = console.log
[ "var", "log", "=", "console", ".", "log" ]
231333e6563501235bc10b24e7efcafd2e2d9b91
https://github.com/weepy/kaffeine/blob/231333e6563501235bc10b24e7efcafd2e2d9b91/lib/token.js#L3-L10
train
sparkartgroup/gulp-markdown-to-json
lib/plugin.js
consolidateFiles
function consolidateFiles (files, config) { return Promise.resolve(files) .then(files => { var data = {}; files.forEach(file => { var path = file.relative.split('.').shift().split(Path.sep); if (path.length >= 2 && config.flattenIndex) { var relPath = path.splice(-2, 2); path = (relPath[0] === relPath[1] || relPath[1] === 'index') ? path.concat(relPath[0]) : path.concat(relPath); } data[path.join('.')] = JSON.parse(file.contents.toString()); }); data = sort(data); const tree = expand(data); const json = JSON.stringify(tree); return Promise.resolve(new Vinyl({ base: '/', cwd: '/', path: '/' + (config.name || 'content.json'), contents: new Buffer(json) })); }); }
javascript
function consolidateFiles (files, config) { return Promise.resolve(files) .then(files => { var data = {}; files.forEach(file => { var path = file.relative.split('.').shift().split(Path.sep); if (path.length >= 2 && config.flattenIndex) { var relPath = path.splice(-2, 2); path = (relPath[0] === relPath[1] || relPath[1] === 'index') ? path.concat(relPath[0]) : path.concat(relPath); } data[path.join('.')] = JSON.parse(file.contents.toString()); }); data = sort(data); const tree = expand(data); const json = JSON.stringify(tree); return Promise.resolve(new Vinyl({ base: '/', cwd: '/', path: '/' + (config.name || 'content.json'), contents: new Buffer(json) })); }); }
[ "function", "consolidateFiles", "(", "files", ",", "config", ")", "{", "return", "Promise", ".", "resolve", "(", "files", ")", ".", "then", "(", "files", "=>", "{", "var", "data", "=", "{", "}", ";", "files", ".", "forEach", "(", "file", "=>", "{", "var", "path", "=", "file", ".", "relative", ".", "split", "(", "'.'", ")", ".", "shift", "(", ")", ".", "split", "(", "Path", ".", "sep", ")", ";", "if", "(", "path", ".", "length", ">=", "2", "&&", "config", ".", "flattenIndex", ")", "{", "var", "relPath", "=", "path", ".", "splice", "(", "-", "2", ",", "2", ")", ";", "path", "=", "(", "relPath", "[", "0", "]", "===", "relPath", "[", "1", "]", "||", "relPath", "[", "1", "]", "===", "'index'", ")", "?", "path", ".", "concat", "(", "relPath", "[", "0", "]", ")", ":", "path", ".", "concat", "(", "relPath", ")", ";", "}", "data", "[", "path", ".", "join", "(", "'.'", ")", "]", "=", "JSON", ".", "parse", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "data", "=", "sort", "(", "data", ")", ";", "const", "tree", "=", "expand", "(", "data", ")", ";", "const", "json", "=", "JSON", ".", "stringify", "(", "tree", ")", ";", "return", "Promise", ".", "resolve", "(", "new", "Vinyl", "(", "{", "base", ":", "'/'", ",", "cwd", ":", "'/'", ",", "path", ":", "'/'", "+", "(", "config", ".", "name", "||", "'content.json'", ")", ",", "contents", ":", "new", "Buffer", "(", "json", ")", "}", ")", ")", ";", "}", ")", ";", "}" ]
Consolidates JSON output into a nested and sorted object whose hierarchy matches the input directory structure @param {Array} files - JSON output as Vinyl file objects @returns {Promise.<Vinyl>}
[ "Consolidates", "JSON", "output", "into", "a", "nested", "and", "sorted", "object", "whose", "hierarchy", "matches", "the", "input", "directory", "structure" ]
ef32234bec31171bb11f16a38d985d88f78640bc
https://github.com/sparkartgroup/gulp-markdown-to-json/blob/ef32234bec31171bb11f16a38d985d88f78640bc/lib/plugin.js#L85-L115
train
sparkartgroup/gulp-markdown-to-json
lib/plugin.js
isBinary
function isBinary (file) { return new Promise((resolve, reject) => { isTextOrBinary.isText(Path.basename(file.path), file.contents, (err, isText) => { if (err) return reject(err); if (isText) file.isText = true; resolve(file); }); }); }
javascript
function isBinary (file) { return new Promise((resolve, reject) => { isTextOrBinary.isText(Path.basename(file.path), file.contents, (err, isText) => { if (err) return reject(err); if (isText) file.isText = true; resolve(file); }); }); }
[ "function", "isBinary", "(", "file", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "isTextOrBinary", ".", "isText", "(", "Path", ".", "basename", "(", "file", ".", "path", ")", ",", "file", ".", "contents", ",", "(", "err", ",", "isText", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "if", "(", "isText", ")", "file", ".", "isText", "=", "true", ";", "resolve", "(", "file", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Tests if file content is ASCII @param {Vinyl} file - Vinyl file object @returns {Promise.<boolean>} @private
[ "Tests", "if", "file", "content", "is", "ASCII" ]
ef32234bec31171bb11f16a38d985d88f78640bc
https://github.com/sparkartgroup/gulp-markdown-to-json/blob/ef32234bec31171bb11f16a38d985d88f78640bc/lib/plugin.js#L146-L154
train
sparkartgroup/gulp-markdown-to-json
lib/plugin.js
isJSON
function isJSON (file) { try { JSON.parse(file.contents.toString()); return true; } catch (err) { return false; } }
javascript
function isJSON (file) { try { JSON.parse(file.contents.toString()); return true; } catch (err) { return false; } }
[ "function", "isJSON", "(", "file", ")", "{", "try", "{", "JSON", ".", "parse", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ";", "return", "true", ";", "}", "catch", "(", "err", ")", "{", "return", "false", ";", "}", "}" ]
Tests if file content is valid JSON @param {object} Vinyl file @returns {boolean} @private
[ "Tests", "if", "file", "content", "is", "valid", "JSON" ]
ef32234bec31171bb11f16a38d985d88f78640bc
https://github.com/sparkartgroup/gulp-markdown-to-json/blob/ef32234bec31171bb11f16a38d985d88f78640bc/lib/plugin.js#L163-L170
train
sparkartgroup/gulp-markdown-to-json
lib/plugin.js
toJSON
function toJSON (file, config) { if (Path.extname(file.path) === '.json') { if (!isJSON(file)) file.isInvalid = true; return Promise.resolve(file); } let jsonFile = file.clone(); return Promise.resolve(file) // parse YAML .then(file => { try { let parsed = frontmatter(file.contents.toString()); return Promise.resolve(parsed); } catch (err) { return Promise.reject(err); } // parse and render Markdown }).then(parsed => { try { let data = parsed.attributes; data.body = config.renderer.call(config.context, parsed.body); return Promise.resolve(data); } catch (err) { return Promise.reject(err); } // optional transforms and output }).then(data => { if (!data.title) { let extracted = extractTitle(data.body, config.stripTitle); if (typeof extracted === 'object') data = assign(data, extracted); } data.updatedAt = file.stat.mtime.toISOString(); if (config.transform) var transformedData = config.transform(data, file); jsonFile.extname = '.json'; jsonFile.contents = new Buffer(JSON.stringify(transformedData || data)); return Promise.resolve(jsonFile); }); }
javascript
function toJSON (file, config) { if (Path.extname(file.path) === '.json') { if (!isJSON(file)) file.isInvalid = true; return Promise.resolve(file); } let jsonFile = file.clone(); return Promise.resolve(file) // parse YAML .then(file => { try { let parsed = frontmatter(file.contents.toString()); return Promise.resolve(parsed); } catch (err) { return Promise.reject(err); } // parse and render Markdown }).then(parsed => { try { let data = parsed.attributes; data.body = config.renderer.call(config.context, parsed.body); return Promise.resolve(data); } catch (err) { return Promise.reject(err); } // optional transforms and output }).then(data => { if (!data.title) { let extracted = extractTitle(data.body, config.stripTitle); if (typeof extracted === 'object') data = assign(data, extracted); } data.updatedAt = file.stat.mtime.toISOString(); if (config.transform) var transformedData = config.transform(data, file); jsonFile.extname = '.json'; jsonFile.contents = new Buffer(JSON.stringify(transformedData || data)); return Promise.resolve(jsonFile); }); }
[ "function", "toJSON", "(", "file", ",", "config", ")", "{", "if", "(", "Path", ".", "extname", "(", "file", ".", "path", ")", "===", "'.json'", ")", "{", "if", "(", "!", "isJSON", "(", "file", ")", ")", "file", ".", "isInvalid", "=", "true", ";", "return", "Promise", ".", "resolve", "(", "file", ")", ";", "}", "let", "jsonFile", "=", "file", ".", "clone", "(", ")", ";", "return", "Promise", ".", "resolve", "(", "file", ")", ".", "then", "(", "file", "=>", "{", "try", "{", "let", "parsed", "=", "frontmatter", "(", "file", ".", "contents", ".", "toString", "(", ")", ")", ";", "return", "Promise", ".", "resolve", "(", "parsed", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "}", ")", ".", "then", "(", "parsed", "=>", "{", "try", "{", "let", "data", "=", "parsed", ".", "attributes", ";", "data", ".", "body", "=", "config", ".", "renderer", ".", "call", "(", "config", ".", "context", ",", "parsed", ".", "body", ")", ";", "return", "Promise", ".", "resolve", "(", "data", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", "}", ")", ".", "then", "(", "data", "=>", "{", "if", "(", "!", "data", ".", "title", ")", "{", "let", "extracted", "=", "extractTitle", "(", "data", ".", "body", ",", "config", ".", "stripTitle", ")", ";", "if", "(", "typeof", "extracted", "===", "'object'", ")", "data", "=", "assign", "(", "data", ",", "extracted", ")", ";", "}", "data", ".", "updatedAt", "=", "file", ".", "stat", ".", "mtime", ".", "toISOString", "(", ")", ";", "if", "(", "config", ".", "transform", ")", "var", "transformedData", "=", "config", ".", "transform", "(", "data", ",", "file", ")", ";", "jsonFile", ".", "extname", "=", "'.json'", ";", "jsonFile", ".", "contents", "=", "new", "Buffer", "(", "JSON", ".", "stringify", "(", "transformedData", "||", "data", ")", ")", ";", "return", "Promise", ".", "resolve", "(", "jsonFile", ")", ";", "}", ")", ";", "}" ]
Parse text files for YAML and Markdown, render to HTML and wrap in JSON @param {Vinyl} file - Vinyl file object @returns {Promise.<Vinyl>} @private
[ "Parse", "text", "files", "for", "YAML", "and", "Markdown", "render", "to", "HTML", "and", "wrap", "in", "JSON" ]
ef32234bec31171bb11f16a38d985d88f78640bc
https://github.com/sparkartgroup/gulp-markdown-to-json/blob/ef32234bec31171bb11f16a38d985d88f78640bc/lib/plugin.js#L179-L221
train
dashersw/erste
src/lib/base/component-manager.js
decorateEvents
function decorateEvents(comp) { const prototype = /** @type {!Function} */(comp.constructor).prototype; if (prototype.__events) return; let events = {}; if (prototype.events) { events = prototype.events; } Object.getOwnPropertyNames(prototype) .map(propertyName => handlerMethodPattern.exec(propertyName)) .filter(x => x) .forEach(([methodName, eventType, eventTarget]) => { events[eventType] = events[eventType] || {}; /** @suppress {checkTypes} */ events[eventType][eventTarget] = comp[methodName]; }) prototype.__events = events; }
javascript
function decorateEvents(comp) { const prototype = /** @type {!Function} */(comp.constructor).prototype; if (prototype.__events) return; let events = {}; if (prototype.events) { events = prototype.events; } Object.getOwnPropertyNames(prototype) .map(propertyName => handlerMethodPattern.exec(propertyName)) .filter(x => x) .forEach(([methodName, eventType, eventTarget]) => { events[eventType] = events[eventType] || {}; /** @suppress {checkTypes} */ events[eventType][eventTarget] = comp[methodName]; }) prototype.__events = events; }
[ "function", "decorateEvents", "(", "comp", ")", "{", "const", "prototype", "=", "(", "comp", ".", "constructor", ")", ".", "prototype", ";", "if", "(", "prototype", ".", "__events", ")", "return", ";", "let", "events", "=", "{", "}", ";", "if", "(", "prototype", ".", "events", ")", "{", "events", "=", "prototype", ".", "events", ";", "}", "Object", ".", "getOwnPropertyNames", "(", "prototype", ")", ".", "map", "(", "propertyName", "=>", "handlerMethodPattern", ".", "exec", "(", "propertyName", ")", ")", ".", "filter", "(", "x", "=>", "x", ")", ".", "forEach", "(", "(", "[", "methodName", ",", "eventType", ",", "eventTarget", "]", ")", "=>", "{", "events", "[", "eventType", "]", "=", "events", "[", "eventType", "]", "||", "{", "}", ";", "events", "[", "eventType", "]", "[", "eventTarget", "]", "=", "comp", "[", "methodName", "]", ";", "}", ")", "prototype", ".", "__events", "=", "events", ";", "}" ]
Fills events object of given component class from method names that match event handler pattern. @param {!Component} comp Component instance to decorate events for.
[ "Fills", "events", "object", "of", "given", "component", "class", "from", "method", "names", "that", "match", "event", "handler", "pattern", "." ]
f916bfdf87bdf6f939184d205c049bbd54a6574f
https://github.com/dashersw/erste/blob/f916bfdf87bdf6f939184d205c049bbd54a6574f/src/lib/base/component-manager.js#L191-L213
train
meeroslav/gulp-inject-partials
src/index.spec.js
expectedFile
function expectedFile(file) { const filePath = path.resolve(__dirname, 'expected', file); return new File({ path: filePath, cwd: __dirname, base: path.resolve(__dirname, 'expected', path.dirname(file)), contents: fs.readFileSync(filePath) }); }
javascript
function expectedFile(file) { const filePath = path.resolve(__dirname, 'expected', file); return new File({ path: filePath, cwd: __dirname, base: path.resolve(__dirname, 'expected', path.dirname(file)), contents: fs.readFileSync(filePath) }); }
[ "function", "expectedFile", "(", "file", ")", "{", "const", "filePath", "=", "path", ".", "resolve", "(", "__dirname", ",", "'expected'", ",", "file", ")", ";", "return", "new", "File", "(", "{", "path", ":", "filePath", ",", "cwd", ":", "__dirname", ",", "base", ":", "path", ".", "resolve", "(", "__dirname", ",", "'expected'", ",", "path", ".", "dirname", "(", "file", ")", ")", ",", "contents", ":", "fs", ".", "readFileSync", "(", "filePath", ")", "}", ")", ";", "}" ]
get expected file
[ "get", "expected", "file" ]
6a7fee734decb03f2537ee54897162da7bc0a634
https://github.com/meeroslav/gulp-inject-partials/blob/6a7fee734decb03f2537ee54897162da7bc0a634/src/index.spec.js#L131-L139
train
131/xterm2
lib/terminal.js
encode
function encode(data, ch) { if (!self.utfMouse) { if (ch === 255) return data.push(0); if (ch > 127) ch = 127; data.push(ch); } else { if (ch === 2047) return data.push(0); if (ch < 127) { data.push(ch); } else { if (ch > 2047) ch = 2047; data.push(0xC0 | (ch >> 6)); data.push(0x80 | (ch & 0x3F)); } } }
javascript
function encode(data, ch) { if (!self.utfMouse) { if (ch === 255) return data.push(0); if (ch > 127) ch = 127; data.push(ch); } else { if (ch === 2047) return data.push(0); if (ch < 127) { data.push(ch); } else { if (ch > 2047) ch = 2047; data.push(0xC0 | (ch >> 6)); data.push(0x80 | (ch & 0x3F)); } } }
[ "function", "encode", "(", "data", ",", "ch", ")", "{", "if", "(", "!", "self", ".", "utfMouse", ")", "{", "if", "(", "ch", "===", "255", ")", "return", "data", ".", "push", "(", "0", ")", ";", "if", "(", "ch", ">", "127", ")", "ch", "=", "127", ";", "data", ".", "push", "(", "ch", ")", ";", "}", "else", "{", "if", "(", "ch", "===", "2047", ")", "return", "data", ".", "push", "(", "0", ")", ";", "if", "(", "ch", "<", "127", ")", "{", "data", ".", "push", "(", "ch", ")", ";", "}", "else", "{", "if", "(", "ch", ">", "2047", ")", "ch", "=", "2047", ";", "data", ".", "push", "(", "0xC0", "|", "(", "ch", ">>", "6", ")", ")", ";", "data", ".", "push", "(", "0x80", "|", "(", "ch", "&", "0x3F", ")", ")", ";", "}", "}", "}" ]
encode button and position to characters
[ "encode", "button", "and", "position", "to", "characters" ]
d0724ac1e637241b37e7bdb6dc3ef64c22976343
https://github.com/131/xterm2/blob/d0724ac1e637241b37e7bdb6dc3ef64c22976343/lib/terminal.js#L643-L658
train
dhershman1/kyanite
src/_internals/_curry2.js
_curry2
function _curry2 (fn) { return function f2 (a, b) { if (!arguments.length) { return f2 } if (arguments.length === 1) { return function (_b) { return fn(a, _b) } } return fn(a, b) } }
javascript
function _curry2 (fn) { return function f2 (a, b) { if (!arguments.length) { return f2 } if (arguments.length === 1) { return function (_b) { return fn(a, _b) } } return fn(a, b) } }
[ "function", "_curry2", "(", "fn", ")", "{", "return", "function", "f2", "(", "a", ",", "b", ")", "{", "if", "(", "!", "arguments", ".", "length", ")", "{", "return", "f2", "}", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "return", "function", "(", "_b", ")", "{", "return", "fn", "(", "a", ",", "_b", ")", "}", "}", "return", "fn", "(", "a", ",", "b", ")", "}", "}" ]
This is an optimized internal curry function for 2 param functions @private @category Function @param {Function} fn The function to curry @return {Function} The curried function
[ "This", "is", "an", "optimized", "internal", "curry", "function", "for", "2", "param", "functions" ]
92524aaea522c3094ea339603125b149272926da
https://github.com/dhershman1/kyanite/blob/92524aaea522c3094ea339603125b149272926da/src/_internals/_curry2.js#L8-L22
train
dignifiedquire/pull-length-prefixed
src/decode.js
next
function next () { let doNext = true let decoded = false const decodeCb = (err, msg) => { decoded = true if (err) { p.end(err) doNext = false } else { p.push(msg) if (!doNext) { next() } } } while (doNext) { decoded = false _decodeFromReader(reader, opts, decodeCb) if (!decoded) { doNext = false } } }
javascript
function next () { let doNext = true let decoded = false const decodeCb = (err, msg) => { decoded = true if (err) { p.end(err) doNext = false } else { p.push(msg) if (!doNext) { next() } } } while (doNext) { decoded = false _decodeFromReader(reader, opts, decodeCb) if (!decoded) { doNext = false } } }
[ "function", "next", "(", ")", "{", "let", "doNext", "=", "true", "let", "decoded", "=", "false", "const", "decodeCb", "=", "(", "err", ",", "msg", ")", "=>", "{", "decoded", "=", "true", "if", "(", "err", ")", "{", "p", ".", "end", "(", "err", ")", "doNext", "=", "false", "}", "else", "{", "p", ".", "push", "(", "msg", ")", "if", "(", "!", "doNext", ")", "{", "next", "(", ")", "}", "}", "}", "while", "(", "doNext", ")", "{", "decoded", "=", "false", "_decodeFromReader", "(", "reader", ",", "opts", ",", "decodeCb", ")", "if", "(", "!", "decoded", ")", "{", "doNext", "=", "false", "}", "}", "}" ]
this function has to be written without recursion or it blows the stack in case of sync stream
[ "this", "function", "has", "to", "be", "written", "without", "recursion", "or", "it", "blows", "the", "stack", "in", "case", "of", "sync", "stream" ]
b22fbe1408447a0efbd6aff8d9bd4c42c9ea0366
https://github.com/dignifiedquire/pull-length-prefixed/blob/b22fbe1408447a0efbd6aff8d9bd4c42c9ea0366/src/decode.js#L26-L50
train
dignifiedquire/pull-length-prefixed
src/decode.js
decodeFromReader
function decodeFromReader (reader, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } _decodeFromReader(reader, opts, function onComplete (err, msg) { if (err) { if (err === true) return cb(new Error('Unexpected end of input from reader.')) return cb(err) } cb(null, msg) }) }
javascript
function decodeFromReader (reader, opts, cb) { if (typeof opts === 'function') { cb = opts opts = {} } _decodeFromReader(reader, opts, function onComplete (err, msg) { if (err) { if (err === true) return cb(new Error('Unexpected end of input from reader.')) return cb(err) } cb(null, msg) }) }
[ "function", "decodeFromReader", "(", "reader", ",", "opts", ",", "cb", ")", "{", "if", "(", "typeof", "opts", "===", "'function'", ")", "{", "cb", "=", "opts", "opts", "=", "{", "}", "}", "_decodeFromReader", "(", "reader", ",", "opts", ",", "function", "onComplete", "(", "err", ",", "msg", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", "===", "true", ")", "return", "cb", "(", "new", "Error", "(", "'Unexpected end of input from reader.'", ")", ")", "return", "cb", "(", "err", ")", "}", "cb", "(", "null", ",", "msg", ")", "}", ")", "}" ]
wrapper to detect sudden pull-stream disconnects
[ "wrapper", "to", "detect", "sudden", "pull", "-", "stream", "disconnects" ]
b22fbe1408447a0efbd6aff8d9bd4c42c9ea0366
https://github.com/dignifiedquire/pull-length-prefixed/blob/b22fbe1408447a0efbd6aff8d9bd4c42c9ea0366/src/decode.js#L59-L72
train
131/xterm2
demo/main.js
function(str){ var ret = new Array(str.length), len = str.length; while(len--) ret[len] = str.charCodeAt(len); return Uint8Array.from(ret); }
javascript
function(str){ var ret = new Array(str.length), len = str.length; while(len--) ret[len] = str.charCodeAt(len); return Uint8Array.from(ret); }
[ "function", "(", "str", ")", "{", "var", "ret", "=", "new", "Array", "(", "str", ".", "length", ")", ",", "len", "=", "str", ".", "length", ";", "while", "(", "len", "--", ")", "ret", "[", "len", "]", "=", "str", ".", "charCodeAt", "(", "len", ")", ";", "return", "Uint8Array", ".", "from", "(", "ret", ")", ";", "}" ]
we do not need Buffer pollyfill for now
[ "we", "do", "not", "need", "Buffer", "pollyfill", "for", "now" ]
d0724ac1e637241b37e7bdb6dc3ef64c22976343
https://github.com/131/xterm2/blob/d0724ac1e637241b37e7bdb6dc3ef64c22976343/demo/main.js#L85-L89
train
gl-vis/gl-axes3d
axes.js
parseOption
function parseOption(nest, cons, name) { if(name in options) { var opt = options[name] var prev = this[name] var next if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : Array.isArray(opt) ) { this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] } else { this[name] = next = [ cons(opt), cons(opt), cons(opt) ] } for(var i=0; i<3; ++i) { if(next[i] !== prev[i]) { return true } } } return false }
javascript
function parseOption(nest, cons, name) { if(name in options) { var opt = options[name] var prev = this[name] var next if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) : Array.isArray(opt) ) { this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ] } else { this[name] = next = [ cons(opt), cons(opt), cons(opt) ] } for(var i=0; i<3; ++i) { if(next[i] !== prev[i]) { return true } } } return false }
[ "function", "parseOption", "(", "nest", ",", "cons", ",", "name", ")", "{", "if", "(", "name", "in", "options", ")", "{", "var", "opt", "=", "options", "[", "name", "]", "var", "prev", "=", "this", "[", "name", "]", "var", "next", "if", "(", "nest", "?", "(", "Array", ".", "isArray", "(", "opt", ")", "&&", "Array", ".", "isArray", "(", "opt", "[", "0", "]", ")", ")", ":", "Array", ".", "isArray", "(", "opt", ")", ")", "{", "this", "[", "name", "]", "=", "next", "=", "[", "cons", "(", "opt", "[", "0", "]", ")", ",", "cons", "(", "opt", "[", "1", "]", ")", ",", "cons", "(", "opt", "[", "2", "]", ")", "]", "}", "else", "{", "this", "[", "name", "]", "=", "next", "=", "[", "cons", "(", "opt", ")", ",", "cons", "(", "opt", ")", ",", "cons", "(", "opt", ")", "]", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "3", ";", "++", "i", ")", "{", "if", "(", "next", "[", "i", "]", "!==", "prev", "[", "i", "]", ")", "{", "return", "true", "}", "}", "}", "return", "false", "}" ]
Option parsing helper functions
[ "Option", "parsing", "helper", "functions" ]
a7a99d8047183657a4a288dc1c9e7341103b81d9
https://github.com/gl-vis/gl-axes3d/blob/a7a99d8047183657a4a288dc1c9e7341103b81d9/axes.js#L93-L111
train
Pier1/rocketbelt
templates/js/site.js
launchPlayground
function launchPlayground(){ $('.playground-item').playground(); // Eyedropper Helper Functions $('.cp_eyedropper').on('click', function() { if ($(this).next('.cp_grid').hasClass('visuallyhidden')) { $(".cp_grid").addClass('visuallyhidden'); $(this).next(".cp_grid").removeClass('visuallyhidden'); } else { $(this).next(".cp_grid").addClass('visuallyhidden'); } }) // Hides eyedropper if you click outside eyedropper $(document).on('click', function(event) { if (!$(event.target).closest('.cp_eyedropper').length && !$(event.target).hasClass('playground-list_item')) { $(".cp_grid").addClass('visuallyhidden'); } }); // Playground Event Handler $('body').on('playgroundUpdated', '.playground-item', function(){ var $input = $(this), base = $input.data('playground'), $playground = $input.closest('.playground'), $codeEl, targetHtmlStr; if ( !$playground.length ) $playground = $input.closest('article'); $codeEl = $playground.find('.exampleWithCode code'); if ( $playground.find('.copyable').length ) { targetHtmlStr = $playground.find('.copyable')[0].outerHTML; } else if ( $playground.find('.copyable-inner').length ) { targetHtmlStr = $playground.find('.copyable-inner').html(); } else { targetHtmlStr = base.$targetEl[0].outerHTML; } $codeEl.html(escapeHtml(targetHtmlStr)); Prism.highlightElement($codeEl[0]); }); // Sets the code section on page load. $('.playground-item').trigger('input'); }
javascript
function launchPlayground(){ $('.playground-item').playground(); // Eyedropper Helper Functions $('.cp_eyedropper').on('click', function() { if ($(this).next('.cp_grid').hasClass('visuallyhidden')) { $(".cp_grid").addClass('visuallyhidden'); $(this).next(".cp_grid").removeClass('visuallyhidden'); } else { $(this).next(".cp_grid").addClass('visuallyhidden'); } }) // Hides eyedropper if you click outside eyedropper $(document).on('click', function(event) { if (!$(event.target).closest('.cp_eyedropper').length && !$(event.target).hasClass('playground-list_item')) { $(".cp_grid").addClass('visuallyhidden'); } }); // Playground Event Handler $('body').on('playgroundUpdated', '.playground-item', function(){ var $input = $(this), base = $input.data('playground'), $playground = $input.closest('.playground'), $codeEl, targetHtmlStr; if ( !$playground.length ) $playground = $input.closest('article'); $codeEl = $playground.find('.exampleWithCode code'); if ( $playground.find('.copyable').length ) { targetHtmlStr = $playground.find('.copyable')[0].outerHTML; } else if ( $playground.find('.copyable-inner').length ) { targetHtmlStr = $playground.find('.copyable-inner').html(); } else { targetHtmlStr = base.$targetEl[0].outerHTML; } $codeEl.html(escapeHtml(targetHtmlStr)); Prism.highlightElement($codeEl[0]); }); // Sets the code section on page load. $('.playground-item').trigger('input'); }
[ "function", "launchPlayground", "(", ")", "{", "$", "(", "'.playground-item'", ")", ".", "playground", "(", ")", ";", "$", "(", "'.cp_eyedropper'", ")", ".", "on", "(", "'click'", ",", "function", "(", ")", "{", "if", "(", "$", "(", "this", ")", ".", "next", "(", "'.cp_grid'", ")", ".", "hasClass", "(", "'visuallyhidden'", ")", ")", "{", "$", "(", "\".cp_grid\"", ")", ".", "addClass", "(", "'visuallyhidden'", ")", ";", "$", "(", "this", ")", ".", "next", "(", "\".cp_grid\"", ")", ".", "removeClass", "(", "'visuallyhidden'", ")", ";", "}", "else", "{", "$", "(", "this", ")", ".", "next", "(", "\".cp_grid\"", ")", ".", "addClass", "(", "'visuallyhidden'", ")", ";", "}", "}", ")", "$", "(", "document", ")", ".", "on", "(", "'click'", ",", "function", "(", "event", ")", "{", "if", "(", "!", "$", "(", "event", ".", "target", ")", ".", "closest", "(", "'.cp_eyedropper'", ")", ".", "length", "&&", "!", "$", "(", "event", ".", "target", ")", ".", "hasClass", "(", "'playground-list_item'", ")", ")", "{", "$", "(", "\".cp_grid\"", ")", ".", "addClass", "(", "'visuallyhidden'", ")", ";", "}", "}", ")", ";", "$", "(", "'body'", ")", ".", "on", "(", "'playgroundUpdated'", ",", "'.playground-item'", ",", "function", "(", ")", "{", "var", "$input", "=", "$", "(", "this", ")", ",", "base", "=", "$input", ".", "data", "(", "'playground'", ")", ",", "$playground", "=", "$input", ".", "closest", "(", "'.playground'", ")", ",", "$codeEl", ",", "targetHtmlStr", ";", "if", "(", "!", "$playground", ".", "length", ")", "$playground", "=", "$input", ".", "closest", "(", "'article'", ")", ";", "$codeEl", "=", "$playground", ".", "find", "(", "'.exampleWithCode code'", ")", ";", "if", "(", "$playground", ".", "find", "(", "'.copyable'", ")", ".", "length", ")", "{", "targetHtmlStr", "=", "$playground", ".", "find", "(", "'.copyable'", ")", "[", "0", "]", ".", "outerHTML", ";", "}", "else", "if", "(", "$playground", ".", "find", "(", "'.copyable-inner'", ")", ".", "length", ")", "{", "targetHtmlStr", "=", "$playground", ".", "find", "(", "'.copyable-inner'", ")", ".", "html", "(", ")", ";", "}", "else", "{", "targetHtmlStr", "=", "base", ".", "$targetEl", "[", "0", "]", ".", "outerHTML", ";", "}", "$codeEl", ".", "html", "(", "escapeHtml", "(", "targetHtmlStr", ")", ")", ";", "Prism", ".", "highlightElement", "(", "$codeEl", "[", "0", "]", ")", ";", "}", ")", ";", "$", "(", "'.playground-item'", ")", ".", "trigger", "(", "'input'", ")", ";", "}" ]
Sets up all playground elements and makes the code copy function for dynamic elements
[ "Sets", "up", "all", "playground", "elements", "and", "makes", "the", "code", "copy", "function", "for", "dynamic", "elements" ]
73e1243e7fcedb731591dbafcc8ecf480ec4700f
https://github.com/Pier1/rocketbelt/blob/73e1243e7fcedb731591dbafcc8ecf480ec4700f/templates/js/site.js#L86-L129
train
gl-vis/gl-axes3d
example/example.js
f
function f(x,y,z) { return x*x + y*y + z*z - 2.0 }
javascript
function f(x,y,z) { return x*x + y*y + z*z - 2.0 }
[ "function", "f", "(", "x", ",", "y", ",", "z", ")", "{", "return", "x", "*", "x", "+", "y", "*", "y", "+", "z", "*", "z", "-", "2.0", "}" ]
Plot level set of f = 0
[ "Plot", "level", "set", "of", "f", "=", "0" ]
a7a99d8047183657a4a288dc1c9e7341103b81d9
https://github.com/gl-vis/gl-axes3d/blob/a7a99d8047183657a4a288dc1c9e7341103b81d9/example/example.js#L17-L19
train
Pier1/rocketbelt
rocketbelt/base/animation/rocketbelt.animate.js
animate
function animate(animationName, configOrCallback) { return this.each(function eachAnimate() { return window.rb.animate.animate(this, animationName, configOrCallback); }); }
javascript
function animate(animationName, configOrCallback) { return this.each(function eachAnimate() { return window.rb.animate.animate(this, animationName, configOrCallback); }); }
[ "function", "animate", "(", "animationName", ",", "configOrCallback", ")", "{", "return", "this", ".", "each", "(", "function", "eachAnimate", "(", ")", "{", "return", "window", ".", "rb", ".", "animate", ".", "animate", "(", "this", ",", "animationName", ",", "configOrCallback", ")", ";", "}", ")", ";", "}" ]
Add a Rocketbelt animation to a jQuery object. @param {string} animationName The Rocketbelt animation name. @param {(object|function)} configOrCallback A configuration object or a callback to run after the animation finishes. @returns {object} A chainable jQuery object.
[ "Add", "a", "Rocketbelt", "animation", "to", "a", "jQuery", "object", "." ]
73e1243e7fcedb731591dbafcc8ecf480ec4700f
https://github.com/Pier1/rocketbelt/blob/73e1243e7fcedb731591dbafcc8ecf480ec4700f/rocketbelt/base/animation/rocketbelt.animate.js#L145-L149
train
saneef/qgen
dist/lib/file-helpers.js
isFileOrDir
function isFileOrDir(filePath) { let fsStat; try { fsStat = fs.statSync(filePath); } catch (error) { return error; } let r = 'file'; if (fsStat.isDirectory()) { r = 'directory'; } return r; }
javascript
function isFileOrDir(filePath) { let fsStat; try { fsStat = fs.statSync(filePath); } catch (error) { return error; } let r = 'file'; if (fsStat.isDirectory()) { r = 'directory'; } return r; }
[ "function", "isFileOrDir", "(", "filePath", ")", "{", "let", "fsStat", ";", "try", "{", "fsStat", "=", "fs", ".", "statSync", "(", "filePath", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "error", ";", "}", "let", "r", "=", "'file'", ";", "if", "(", "fsStat", ".", "isDirectory", "(", ")", ")", "{", "r", "=", "'directory'", ";", "}", "return", "r", ";", "}" ]
Check if a path points to a file or a directory @param {String} filePath - Path to a file or directory @return {String} 'directory' if paths points a directory, 'file' if path points to a file
[ "Check", "if", "a", "path", "points", "to", "a", "file", "or", "a", "directory" ]
c413d902f4ea79b628b0006fa08e9ae727738831
https://github.com/saneef/qgen/blob/c413d902f4ea79b628b0006fa08e9ae727738831/dist/lib/file-helpers.js#L12-L26
train
dhershman1/kyanite
src/_internals/_curry3.js
_curry3
function _curry3 (fn) { return function f3 (a, b, c) { switch (arguments.length) { case 0: return f3 case 1: return _curry2(function (_b, _c) { return fn(a, _b, _c) }) case 2: return function (_c) { return fn(a, b, _c) } default: return fn(a, b, c) } } }
javascript
function _curry3 (fn) { return function f3 (a, b, c) { switch (arguments.length) { case 0: return f3 case 1: return _curry2(function (_b, _c) { return fn(a, _b, _c) }) case 2: return function (_c) { return fn(a, b, _c) } default: return fn(a, b, c) } } }
[ "function", "_curry3", "(", "fn", ")", "{", "return", "function", "f3", "(", "a", ",", "b", ",", "c", ")", "{", "switch", "(", "arguments", ".", "length", ")", "{", "case", "0", ":", "return", "f3", "case", "1", ":", "return", "_curry2", "(", "function", "(", "_b", ",", "_c", ")", "{", "return", "fn", "(", "a", ",", "_b", ",", "_c", ")", "}", ")", "case", "2", ":", "return", "function", "(", "_c", ")", "{", "return", "fn", "(", "a", ",", "b", ",", "_c", ")", "}", "default", ":", "return", "fn", "(", "a", ",", "b", ",", "c", ")", "}", "}", "}" ]
This is an optimized internal curry function for 3 param functions @private @category Function @param {Function} fn The function to curry @return {Function} The curried function
[ "This", "is", "an", "optimized", "internal", "curry", "function", "for", "3", "param", "functions" ]
92524aaea522c3094ea339603125b149272926da
https://github.com/dhershman1/kyanite/blob/92524aaea522c3094ea339603125b149272926da/src/_internals/_curry3.js#L10-L27
train
saneef/qgen
src/qgen.js
qgen
function qgen(options) { const defaultOptions = { dest: DEFAULT_DESTINATION, cwd: process.cwd(), directory: 'qgen-templates', config: './qgen.json', helpers: undefined, force: false, preview: false }; const configfilePath = createConfigFilePath(defaultOptions, options); const configfileOptions = loadConfig(configfilePath); const config = Object.assign(defaultOptions, configfileOptions, options); /** Throw error if qgen template directory is missing */ if (isFileOrDir(config.directory) !== 'directory') { throw new QGenError(`qgen templates directory '${config.directory}' not found.`); } /** * Lists the available template names * * @return {Array} available template names */ const templates = () => { return globby.sync(['*'], { cwd: path.join(config.cwd, config.directory), expandDirectories: false, onlyFiles: false }); }; /** * Render the template file and save to the destination path * @param {String} template The name of the template * @param {String} destination Destination path */ const render = async (template, destination) => { const templatePath = path.join(config.directory, template); const templateType = isFileOrDir(path.join(config.cwd, templatePath)); const templateConfig = createTemplateConfig(config, template, DEFAULT_DESTINATION); const filepathRenderer = templateRenderer({ helpers: config.helpers, cwd: config.cwd }); // Override config dest with passed destination if (destination) { templateConfig.dest = destination; } let fileObjects; if (templateType === 'directory') { const files = globby.sync(['**/*'], { cwd: path.join(config.cwd, templatePath), nodir: true }); fileObjects = files.map(filePath => { return { src: path.join(templatePath, filePath), dest: path.join(templateConfig.cwd, templateConfig.dest, filepathRenderer.render(filePath, config)) }; }); } else if (templateType === 'file') { fileObjects = [{ src: templatePath, dest: path.join(templateConfig.cwd, templateConfig.dest, template) }]; } else { throw new QGenError(`Template '${templatePath}' not found.`); } const filesForRender = config.preview ? fileObjects : await enquireToOverwrite(fileObjects, config.force); if (!filesForRender.some(f => f.abort)) { renderFiles(filesForRender, templateConfig, config.preview); } }; return Object.freeze({ templates, render }); }
javascript
function qgen(options) { const defaultOptions = { dest: DEFAULT_DESTINATION, cwd: process.cwd(), directory: 'qgen-templates', config: './qgen.json', helpers: undefined, force: false, preview: false }; const configfilePath = createConfigFilePath(defaultOptions, options); const configfileOptions = loadConfig(configfilePath); const config = Object.assign(defaultOptions, configfileOptions, options); /** Throw error if qgen template directory is missing */ if (isFileOrDir(config.directory) !== 'directory') { throw new QGenError(`qgen templates directory '${config.directory}' not found.`); } /** * Lists the available template names * * @return {Array} available template names */ const templates = () => { return globby.sync(['*'], { cwd: path.join(config.cwd, config.directory), expandDirectories: false, onlyFiles: false }); }; /** * Render the template file and save to the destination path * @param {String} template The name of the template * @param {String} destination Destination path */ const render = async (template, destination) => { const templatePath = path.join(config.directory, template); const templateType = isFileOrDir(path.join(config.cwd, templatePath)); const templateConfig = createTemplateConfig(config, template, DEFAULT_DESTINATION); const filepathRenderer = templateRenderer({ helpers: config.helpers, cwd: config.cwd }); // Override config dest with passed destination if (destination) { templateConfig.dest = destination; } let fileObjects; if (templateType === 'directory') { const files = globby.sync(['**/*'], { cwd: path.join(config.cwd, templatePath), nodir: true }); fileObjects = files.map(filePath => { return { src: path.join(templatePath, filePath), dest: path.join(templateConfig.cwd, templateConfig.dest, filepathRenderer.render(filePath, config)) }; }); } else if (templateType === 'file') { fileObjects = [{ src: templatePath, dest: path.join(templateConfig.cwd, templateConfig.dest, template) }]; } else { throw new QGenError(`Template '${templatePath}' not found.`); } const filesForRender = config.preview ? fileObjects : await enquireToOverwrite(fileObjects, config.force); if (!filesForRender.some(f => f.abort)) { renderFiles(filesForRender, templateConfig, config.preview); } }; return Object.freeze({ templates, render }); }
[ "function", "qgen", "(", "options", ")", "{", "const", "defaultOptions", "=", "{", "dest", ":", "DEFAULT_DESTINATION", ",", "cwd", ":", "process", ".", "cwd", "(", ")", ",", "directory", ":", "'qgen-templates'", ",", "config", ":", "'./qgen.json'", ",", "helpers", ":", "undefined", ",", "force", ":", "false", ",", "preview", ":", "false", "}", ";", "const", "configfilePath", "=", "createConfigFilePath", "(", "defaultOptions", ",", "options", ")", ";", "const", "configfileOptions", "=", "loadConfig", "(", "configfilePath", ")", ";", "const", "config", "=", "Object", ".", "assign", "(", "defaultOptions", ",", "configfileOptions", ",", "options", ")", ";", "if", "(", "isFileOrDir", "(", "config", ".", "directory", ")", "!==", "'directory'", ")", "{", "throw", "new", "QGenError", "(", "`", "${", "config", ".", "directory", "}", "`", ")", ";", "}", "const", "templates", "=", "(", ")", "=>", "{", "return", "globby", ".", "sync", "(", "[", "'*'", "]", ",", "{", "cwd", ":", "path", ".", "join", "(", "config", ".", "cwd", ",", "config", ".", "directory", ")", ",", "expandDirectories", ":", "false", ",", "onlyFiles", ":", "false", "}", ")", ";", "}", ";", "const", "render", "=", "async", "(", "template", ",", "destination", ")", "=>", "{", "const", "templatePath", "=", "path", ".", "join", "(", "config", ".", "directory", ",", "template", ")", ";", "const", "templateType", "=", "isFileOrDir", "(", "path", ".", "join", "(", "config", ".", "cwd", ",", "templatePath", ")", ")", ";", "const", "templateConfig", "=", "createTemplateConfig", "(", "config", ",", "template", ",", "DEFAULT_DESTINATION", ")", ";", "const", "filepathRenderer", "=", "templateRenderer", "(", "{", "helpers", ":", "config", ".", "helpers", ",", "cwd", ":", "config", ".", "cwd", "}", ")", ";", "if", "(", "destination", ")", "{", "templateConfig", ".", "dest", "=", "destination", ";", "}", "let", "fileObjects", ";", "if", "(", "templateType", "===", "'directory'", ")", "{", "const", "files", "=", "globby", ".", "sync", "(", "[", "'**/*'", "]", ",", "{", "cwd", ":", "path", ".", "join", "(", "config", ".", "cwd", ",", "templatePath", ")", ",", "nodir", ":", "true", "}", ")", ";", "fileObjects", "=", "files", ".", "map", "(", "filePath", "=>", "{", "return", "{", "src", ":", "path", ".", "join", "(", "templatePath", ",", "filePath", ")", ",", "dest", ":", "path", ".", "join", "(", "templateConfig", ".", "cwd", ",", "templateConfig", ".", "dest", ",", "filepathRenderer", ".", "render", "(", "filePath", ",", "config", ")", ")", "}", ";", "}", ")", ";", "}", "else", "if", "(", "templateType", "===", "'file'", ")", "{", "fileObjects", "=", "[", "{", "src", ":", "templatePath", ",", "dest", ":", "path", ".", "join", "(", "templateConfig", ".", "cwd", ",", "templateConfig", ".", "dest", ",", "template", ")", "}", "]", ";", "}", "else", "{", "throw", "new", "QGenError", "(", "`", "${", "templatePath", "}", "`", ")", ";", "}", "const", "filesForRender", "=", "config", ".", "preview", "?", "fileObjects", ":", "await", "enquireToOverwrite", "(", "fileObjects", ",", "config", ".", "force", ")", ";", "if", "(", "!", "filesForRender", ".", "some", "(", "f", "=>", "f", ".", "abort", ")", ")", "{", "renderFiles", "(", "filesForRender", ",", "templateConfig", ",", "config", ".", "preview", ")", ";", "}", "}", ";", "return", "Object", ".", "freeze", "(", "{", "templates", ",", "render", "}", ")", ";", "}" ]
Creates new qgen object @param {Object} options - Options such as dest, config file path etc. @returns {qgen} qgen object
[ "Creates", "new", "qgen", "object" ]
c413d902f4ea79b628b0006fa08e9ae727738831
https://github.com/saneef/qgen/blob/c413d902f4ea79b628b0006fa08e9ae727738831/src/qgen.js#L71-L157
train
Pier1/rocketbelt
rocketbelt/components/dialogs/rocketbelt.dialogs.js
trapTabKey
function trapTabKey(node, event) { var focusableChildren = getFocusableChildren(node); var focusedItemIndex = focusableChildren.index($(document.activeElement)); if (event.shiftKey && focusedItemIndex === 0) { focusableChildren[focusableChildren.length - 1].focus(); event.preventDefault(); } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) { focusableChildren[0].focus(); event.preventDefault(); } }
javascript
function trapTabKey(node, event) { var focusableChildren = getFocusableChildren(node); var focusedItemIndex = focusableChildren.index($(document.activeElement)); if (event.shiftKey && focusedItemIndex === 0) { focusableChildren[focusableChildren.length - 1].focus(); event.preventDefault(); } else if (!event.shiftKey && focusedItemIndex === focusableChildren.length - 1) { focusableChildren[0].focus(); event.preventDefault(); } }
[ "function", "trapTabKey", "(", "node", ",", "event", ")", "{", "var", "focusableChildren", "=", "getFocusableChildren", "(", "node", ")", ";", "var", "focusedItemIndex", "=", "focusableChildren", ".", "index", "(", "$", "(", "document", ".", "activeElement", ")", ")", ";", "if", "(", "event", ".", "shiftKey", "&&", "focusedItemIndex", "===", "0", ")", "{", "focusableChildren", "[", "focusableChildren", ".", "length", "-", "1", "]", ".", "focus", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}", "else", "if", "(", "!", "event", ".", "shiftKey", "&&", "focusedItemIndex", "===", "focusableChildren", ".", "length", "-", "1", ")", "{", "focusableChildren", "[", "0", "]", ".", "focus", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "}", "}" ]
Helper function trapping the tab key inside a node
[ "Helper", "function", "trapping", "the", "tab", "key", "inside", "a", "node" ]
73e1243e7fcedb731591dbafcc8ecf480ec4700f
https://github.com/Pier1/rocketbelt/blob/73e1243e7fcedb731591dbafcc8ecf480ec4700f/rocketbelt/components/dialogs/rocketbelt.dialogs.js#L149-L160
train
jonschlinkert/regex-cache
index.js
regexCache
function regexCache(fn, str, opts) { var key = '_default_', regex, cached; if (!str && !opts) { if (typeof fn !== 'function') { return fn; } return basic[key] || (basic[key] = fn(str)); } var isString = typeof str === 'string'; if (isString) { if (!opts) { return basic[str] || (basic[str] = fn(str)); } key = str; } else { opts = str; } cached = cache[key]; if (cached && equal(cached.opts, opts)) { return cached.regex; } memo(key, opts, (regex = fn(str, opts))); return regex; }
javascript
function regexCache(fn, str, opts) { var key = '_default_', regex, cached; if (!str && !opts) { if (typeof fn !== 'function') { return fn; } return basic[key] || (basic[key] = fn(str)); } var isString = typeof str === 'string'; if (isString) { if (!opts) { return basic[str] || (basic[str] = fn(str)); } key = str; } else { opts = str; } cached = cache[key]; if (cached && equal(cached.opts, opts)) { return cached.regex; } memo(key, opts, (regex = fn(str, opts))); return regex; }
[ "function", "regexCache", "(", "fn", ",", "str", ",", "opts", ")", "{", "var", "key", "=", "'_default_'", ",", "regex", ",", "cached", ";", "if", "(", "!", "str", "&&", "!", "opts", ")", "{", "if", "(", "typeof", "fn", "!==", "'function'", ")", "{", "return", "fn", ";", "}", "return", "basic", "[", "key", "]", "||", "(", "basic", "[", "key", "]", "=", "fn", "(", "str", ")", ")", ";", "}", "var", "isString", "=", "typeof", "str", "===", "'string'", ";", "if", "(", "isString", ")", "{", "if", "(", "!", "opts", ")", "{", "return", "basic", "[", "str", "]", "||", "(", "basic", "[", "str", "]", "=", "fn", "(", "str", ")", ")", ";", "}", "key", "=", "str", ";", "}", "else", "{", "opts", "=", "str", ";", "}", "cached", "=", "cache", "[", "key", "]", ";", "if", "(", "cached", "&&", "equal", "(", "cached", ".", "opts", ",", "opts", ")", ")", "{", "return", "cached", ".", "regex", ";", "}", "memo", "(", "key", ",", "opts", ",", "(", "regex", "=", "fn", "(", "str", ",", "opts", ")", ")", ")", ";", "return", "regex", ";", "}" ]
Memoize the results of a call to the new RegExp constructor. @param {Function} fn [description] @param {String} str [description] @param {Options} options [description] @param {Boolean} nocompare [description] @return {RegExp}
[ "Memoize", "the", "results", "of", "a", "call", "to", "the", "new", "RegExp", "constructor", "." ]
1c001df1e266328fa9e34906660c79169ab9fa4f
https://github.com/jonschlinkert/regex-cache/blob/1c001df1e266328fa9e34906660c79169ab9fa4f/index.js#L30-L57
train
y-js/y-webrtc
src/WebRTC.js
function () { // check if the clients still exists var peer = self.swr.webrtc.getPeers(uid)[0] var success if (peer) { // success is true, if the message is successfully sent success = peer.sendDirectly('simplewebrtc', 'yjs', message) } if (!success) { // resend the message if it didn't work setTimeout(send, 500) } }
javascript
function () { // check if the clients still exists var peer = self.swr.webrtc.getPeers(uid)[0] var success if (peer) { // success is true, if the message is successfully sent success = peer.sendDirectly('simplewebrtc', 'yjs', message) } if (!success) { // resend the message if it didn't work setTimeout(send, 500) } }
[ "function", "(", ")", "{", "var", "peer", "=", "self", ".", "swr", ".", "webrtc", ".", "getPeers", "(", "uid", ")", "[", "0", "]", "var", "success", "if", "(", "peer", ")", "{", "success", "=", "peer", ".", "sendDirectly", "(", "'simplewebrtc'", ",", "'yjs'", ",", "message", ")", "}", "if", "(", "!", "success", ")", "{", "setTimeout", "(", "send", ",", "500", ")", "}", "}" ]
we have to make sure that the message is sent under all circumstances
[ "we", "have", "to", "make", "sure", "that", "the", "message", "is", "sent", "under", "all", "circumstances" ]
1c6559b57dae9f9e5da18b6755afd92577fda878
https://github.com/y-js/y-webrtc/blob/1c6559b57dae9f9e5da18b6755afd92577fda878/src/WebRTC.js#L73-L85
train
libp2p/js-libp2p-ping
src/handler.js
next
function next () { shake.read(PING_LENGTH, (err, buf) => { if (err === true) { // stream closed return } if (err) { return log.error(err) } shake.write(buf) return next() }) }
javascript
function next () { shake.read(PING_LENGTH, (err, buf) => { if (err === true) { // stream closed return } if (err) { return log.error(err) } shake.write(buf) return next() }) }
[ "function", "next", "(", ")", "{", "shake", ".", "read", "(", "PING_LENGTH", ",", "(", "err", ",", "buf", ")", "=>", "{", "if", "(", "err", "===", "true", ")", "{", "return", "}", "if", "(", "err", ")", "{", "return", "log", ".", "error", "(", "err", ")", "}", "shake", ".", "write", "(", "buf", ")", "return", "next", "(", ")", "}", ")", "}" ]
receive and echo back
[ "receive", "and", "echo", "back" ]
349eecf68ae5f5fb7c35333cdb42c138bbf5c766
https://github.com/libp2p/js-libp2p-ping/blob/349eecf68ae5f5fb7c35333cdb42c138bbf5c766/src/handler.js#L19-L32
train
jeffijoe/yenv
lib/applyEnv.js
raw
function raw(obj) { const result = {} for (const key in obj) { const value = obj[key] if (value !== null && value !== undefined) { result[key] = value.toString() } } return result }
javascript
function raw(obj) { const result = {} for (const key in obj) { const value = obj[key] if (value !== null && value !== undefined) { result[key] = value.toString() } } return result }
[ "function", "raw", "(", "obj", ")", "{", "const", "result", "=", "{", "}", "for", "(", "const", "key", "in", "obj", ")", "{", "const", "value", "=", "obj", "[", "key", "]", "if", "(", "value", "!==", "null", "&&", "value", "!==", "undefined", ")", "{", "result", "[", "key", "]", "=", "value", ".", "toString", "(", ")", "}", "}", "return", "result", "}" ]
Serializes env values as strings.
[ "Serializes", "env", "values", "as", "strings", "." ]
fb3eaca3550718c89853fa891ecef837eecc2992
https://github.com/jeffijoe/yenv/blob/fb3eaca3550718c89853fa891ecef837eecc2992/lib/applyEnv.js#L38-L47
train
jeffijoe/yenv
lib/composeSections.js
circularSectionsError
function circularSectionsError(sectionName, path) { const joinedPath = path.join(' -> ') const message = `Circular sections! Path: ${joinedPath} -> [${sectionName}]` return new Error(message) }
javascript
function circularSectionsError(sectionName, path) { const joinedPath = path.join(' -> ') const message = `Circular sections! Path: ${joinedPath} -> [${sectionName}]` return new Error(message) }
[ "function", "circularSectionsError", "(", "sectionName", ",", "path", ")", "{", "const", "joinedPath", "=", "path", ".", "join", "(", "' -> '", ")", "const", "message", "=", "`", "${", "joinedPath", "}", "${", "sectionName", "}", "`", "return", "new", "Error", "(", "message", ")", "}" ]
Returns a new error indicating circular sections. @param {String} sectionName The section at which the circularity was determined. @param {String[]} path The circular sections path. @return {Error} Our beautiful error.
[ "Returns", "a", "new", "error", "indicating", "circular", "sections", "." ]
fb3eaca3550718c89853fa891ecef837eecc2992
https://github.com/jeffijoe/yenv/blob/fb3eaca3550718c89853fa891ecef837eecc2992/lib/composeSections.js#L17-L21
train
jeffijoe/yenv
lib/processImports.js
circularImportsError
function circularImportsError(fileBeingImported, importTrail) { const message = `Circular import of "${fileBeingImported}".\r\n` + 'Import trace:\r\n' + importTrail.map(f => ` -> ${f}`).join('\r\n') return new Error(message) }
javascript
function circularImportsError(fileBeingImported, importTrail) { const message = `Circular import of "${fileBeingImported}".\r\n` + 'Import trace:\r\n' + importTrail.map(f => ` -> ${f}`).join('\r\n') return new Error(message) }
[ "function", "circularImportsError", "(", "fileBeingImported", ",", "importTrail", ")", "{", "const", "message", "=", "`", "${", "fileBeingImported", "}", "\\r", "\\n", "`", "+", "'Import trace:\\r\\n'", "+", "\\r", "\\n", "}" ]
Constructs a circular imports error. @param {string} fileBeingImported The file being imported. @param {string} importingFile The file that imported. @return {Error} An error.
[ "Constructs", "a", "circular", "imports", "error", "." ]
fb3eaca3550718c89853fa891ecef837eecc2992
https://github.com/jeffijoe/yenv/blob/fb3eaca3550718c89853fa891ecef837eecc2992/lib/processImports.js#L25-L31
train
jeffijoe/yenv
lib/processImports.js
mapFiles
function mapFiles(files, relative, required) { if (!files) { return [] } if (Array.isArray(files) === false) { files = [files] } return files.map(f => ({ file: resolvePath(relative, f), required: required })) }
javascript
function mapFiles(files, relative, required) { if (!files) { return [] } if (Array.isArray(files) === false) { files = [files] } return files.map(f => ({ file: resolvePath(relative, f), required: required })) }
[ "function", "mapFiles", "(", "files", ",", "relative", ",", "required", ")", "{", "if", "(", "!", "files", ")", "{", "return", "[", "]", "}", "if", "(", "Array", ".", "isArray", "(", "files", ")", "===", "false", ")", "{", "files", "=", "[", "files", "]", "}", "return", "files", ".", "map", "(", "f", "=>", "(", "{", "file", ":", "resolvePath", "(", "relative", ",", "f", ")", ",", "required", ":", "required", "}", ")", ")", "}" ]
Maps file paths as well as whether not they are required to descriptors.
[ "Maps", "file", "paths", "as", "well", "as", "whether", "not", "they", "are", "required", "to", "descriptors", "." ]
fb3eaca3550718c89853fa891ecef837eecc2992
https://github.com/jeffijoe/yenv/blob/fb3eaca3550718c89853fa891ecef837eecc2992/lib/processImports.js#L98-L111
train
KleeGroup/focus-core
src/definition/validator/validate.js
validate
function validate(property, validators) { //console.log("validate", property, validators); let errors = [], res, validator; if (validators) { for (let i = 0, _len = validators.length; i < _len; i++) { validator = validators[i]; res = validateProperty(property, validator); if (!isNull(res) && !isUndefined(res)) { errors.push(res); } } } //Check what's the good type to return. return { name: property.name, value: property.value, isValid: 0 === errors.length, errors: errors }; }
javascript
function validate(property, validators) { //console.log("validate", property, validators); let errors = [], res, validator; if (validators) { for (let i = 0, _len = validators.length; i < _len; i++) { validator = validators[i]; res = validateProperty(property, validator); if (!isNull(res) && !isUndefined(res)) { errors.push(res); } } } //Check what's the good type to return. return { name: property.name, value: property.value, isValid: 0 === errors.length, errors: errors }; }
[ "function", "validate", "(", "property", ",", "validators", ")", "{", "let", "errors", "=", "[", "]", ",", "res", ",", "validator", ";", "if", "(", "validators", ")", "{", "for", "(", "let", "i", "=", "0", ",", "_len", "=", "validators", ".", "length", ";", "i", "<", "_len", ";", "i", "++", ")", "{", "validator", "=", "validators", "[", "i", "]", ";", "res", "=", "validateProperty", "(", "property", ",", "validator", ")", ";", "if", "(", "!", "isNull", "(", "res", ")", "&&", "!", "isUndefined", "(", "res", ")", ")", "{", "errors", ".", "push", "(", "res", ")", ";", "}", "}", "}", "return", "{", "name", ":", "property", ".", "name", ",", "value", ":", "property", ".", "value", ",", "isValid", ":", "0", "===", "errors", ".", "length", ",", "errors", ":", "errors", "}", ";", "}" ]
Validae a property given validators. @param {object} property - Property to validate which should be as follows: `{name: "field_name",value: "field_value", validators: [{...}] }`. @param {array} validators - The validators to apply on the property. @return {object} - The validation status.
[ "Validae", "a", "property", "given", "validators", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/definition/validator/validate.js#L19-L38
train
KleeGroup/focus-core
src/definition/validator/validate.js
getErrorLabel
function getErrorLabel(type, fieldName, options = {}) { options = options || {}; const translationKey = options.translationKey ? options.translationKey : `domain.validation.${type}`; const opts = { fieldName: translate(fieldName), ...options }; return translate(translationKey, opts); }
javascript
function getErrorLabel(type, fieldName, options = {}) { options = options || {}; const translationKey = options.translationKey ? options.translationKey : `domain.validation.${type}`; const opts = { fieldName: translate(fieldName), ...options }; return translate(translationKey, opts); }
[ "function", "getErrorLabel", "(", "type", ",", "fieldName", ",", "options", "=", "{", "}", ")", "{", "options", "=", "options", "||", "{", "}", ";", "const", "translationKey", "=", "options", ".", "translationKey", "?", "options", ".", "translationKey", ":", "`", "${", "type", "}", "`", ";", "const", "opts", "=", "{", "fieldName", ":", "translate", "(", "fieldName", ")", ",", "...", "options", "}", ";", "return", "translate", "(", "translationKey", ",", "opts", ")", ";", "}" ]
Get the error label from a type and a field name. @param {string} type - The type name. @param {string} fieldName - The field name. @param {object} options - The options to put such as the translationKey which could be defined in the domain. @return {string} The formatted error.
[ "Get", "the", "error", "label", "from", "a", "type", "and", "a", "field", "name", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/definition/validator/validate.js#L100-L105
train
KleeGroup/focus-core
src/list/load-action/builder.js
orderAndSort
function orderAndSort(sortConf) { return { sortFieldName: sortConf.sortBy, sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc }; }
javascript
function orderAndSort(sortConf) { return { sortFieldName: sortConf.sortBy, sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc }; }
[ "function", "orderAndSort", "(", "sortConf", ")", "{", "return", "{", "sortFieldName", ":", "sortConf", ".", "sortBy", ",", "sortDesc", ":", "sortConf", ".", "sortAsc", "===", "undefined", "?", "false", ":", "!", "sortConf", ".", "sortAsc", "}", ";", "}" ]
Build sort infotmation. @param {object} sortConf - The sort configuration. @return {object} - The builded sort configuration.
[ "Build", "sort", "infotmation", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/list/load-action/builder.js#L7-L12
train
KleeGroup/focus-core
src/list/load-action/builder.js
pagination
function pagination(opts) { let { isScroll, dataList, totalCount, nbElement } = opts; if (isScroll) { if (!isArray(dataList)) { throw new Error('The data list options sould exist and be an array') } if (dataList.length < totalCount) { return { top: nbElement, skip: dataList.length }; } } return { top: nbElement, skip: 0 } }
javascript
function pagination(opts) { let { isScroll, dataList, totalCount, nbElement } = opts; if (isScroll) { if (!isArray(dataList)) { throw new Error('The data list options sould exist and be an array') } if (dataList.length < totalCount) { return { top: nbElement, skip: dataList.length }; } } return { top: nbElement, skip: 0 } }
[ "function", "pagination", "(", "opts", ")", "{", "let", "{", "isScroll", ",", "dataList", ",", "totalCount", ",", "nbElement", "}", "=", "opts", ";", "if", "(", "isScroll", ")", "{", "if", "(", "!", "isArray", "(", "dataList", ")", ")", "{", "throw", "new", "Error", "(", "'The data list options sould exist and be an array'", ")", "}", "if", "(", "dataList", ".", "length", "<", "totalCount", ")", "{", "return", "{", "top", ":", "nbElement", ",", "skip", ":", "dataList", ".", "length", "}", ";", "}", "}", "return", "{", "top", ":", "nbElement", ",", "skip", ":", "0", "}", "}" ]
Build the pagination configuration given the options. @param {object} opts - The pagination options should be : isScroll (:bool) - Are we in a scroll context. totalCount (:number) - The total number of element. (intresting only in the scroll case) nbSearchElement (:number) - The number of elements you want to get back from the search. @return {object} - An object with {top, skip}.
[ "Build", "the", "pagination", "configuration", "given", "the", "options", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/list/load-action/builder.js#L22-L36
train
reflux/reflux-promise
src/index.js
triggerPromise
function triggerPromise() { var me = this; var args = arguments; var canHandlePromise = this.children.indexOf("completed") >= 0 && this.children.indexOf("failed") >= 0; var createdPromise = new PromiseFactory(function(resolve, reject) { // If `listenAndPromise` is listening // patch `promise` w/ context-loaded resolve/reject if (me.willCallPromise) { _.nextTick(function() { var previousPromise = me.promise; me.promise = function (inputPromise) { inputPromise.then(resolve, reject); // Back to your regularly schedule programming. me.promise = previousPromise; return me.promise.apply(me, arguments); }; me.trigger.apply(me, args); }); return; } if (canHandlePromise) { var removeSuccess = me.completed.listen(function () { var args = Array.prototype.slice.call(arguments); removeSuccess(); removeFailed(); resolve(args.length > 1 ? args : args[0]); }); var removeFailed = me.failed.listen(function () { var args = Array.prototype.slice.call(arguments); removeSuccess(); removeFailed(); reject(args.length > 1 ? args : args[0]); }); } _.nextTick(function () { me.trigger.apply(me, args); }); if (!canHandlePromise) { resolve(); } }); // Ensure that the promise does trigger "Uncaught (in promise)" errors in console if no error handler is added // See: https://github.com/reflux/reflux-promise/issues/4 createdPromise.catch(function() {}); return createdPromise; }
javascript
function triggerPromise() { var me = this; var args = arguments; var canHandlePromise = this.children.indexOf("completed") >= 0 && this.children.indexOf("failed") >= 0; var createdPromise = new PromiseFactory(function(resolve, reject) { // If `listenAndPromise` is listening // patch `promise` w/ context-loaded resolve/reject if (me.willCallPromise) { _.nextTick(function() { var previousPromise = me.promise; me.promise = function (inputPromise) { inputPromise.then(resolve, reject); // Back to your regularly schedule programming. me.promise = previousPromise; return me.promise.apply(me, arguments); }; me.trigger.apply(me, args); }); return; } if (canHandlePromise) { var removeSuccess = me.completed.listen(function () { var args = Array.prototype.slice.call(arguments); removeSuccess(); removeFailed(); resolve(args.length > 1 ? args : args[0]); }); var removeFailed = me.failed.listen(function () { var args = Array.prototype.slice.call(arguments); removeSuccess(); removeFailed(); reject(args.length > 1 ? args : args[0]); }); } _.nextTick(function () { me.trigger.apply(me, args); }); if (!canHandlePromise) { resolve(); } }); // Ensure that the promise does trigger "Uncaught (in promise)" errors in console if no error handler is added // See: https://github.com/reflux/reflux-promise/issues/4 createdPromise.catch(function() {}); return createdPromise; }
[ "function", "triggerPromise", "(", ")", "{", "var", "me", "=", "this", ";", "var", "args", "=", "arguments", ";", "var", "canHandlePromise", "=", "this", ".", "children", ".", "indexOf", "(", "\"completed\"", ")", ">=", "0", "&&", "this", ".", "children", ".", "indexOf", "(", "\"failed\"", ")", ">=", "0", ";", "var", "createdPromise", "=", "new", "PromiseFactory", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "me", ".", "willCallPromise", ")", "{", "_", ".", "nextTick", "(", "function", "(", ")", "{", "var", "previousPromise", "=", "me", ".", "promise", ";", "me", ".", "promise", "=", "function", "(", "inputPromise", ")", "{", "inputPromise", ".", "then", "(", "resolve", ",", "reject", ")", ";", "me", ".", "promise", "=", "previousPromise", ";", "return", "me", ".", "promise", ".", "apply", "(", "me", ",", "arguments", ")", ";", "}", ";", "me", ".", "trigger", ".", "apply", "(", "me", ",", "args", ")", ";", "}", ")", ";", "return", ";", "}", "if", "(", "canHandlePromise", ")", "{", "var", "removeSuccess", "=", "me", ".", "completed", ".", "listen", "(", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "removeSuccess", "(", ")", ";", "removeFailed", "(", ")", ";", "resolve", "(", "args", ".", "length", ">", "1", "?", "args", ":", "args", "[", "0", "]", ")", ";", "}", ")", ";", "var", "removeFailed", "=", "me", ".", "failed", ".", "listen", "(", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "removeSuccess", "(", ")", ";", "removeFailed", "(", ")", ";", "reject", "(", "args", ".", "length", ">", "1", "?", "args", ":", "args", "[", "0", "]", ")", ";", "}", ")", ";", "}", "_", ".", "nextTick", "(", "function", "(", ")", "{", "me", ".", "trigger", ".", "apply", "(", "me", ",", "args", ")", ";", "}", ")", ";", "if", "(", "!", "canHandlePromise", ")", "{", "resolve", "(", ")", ";", "}", "}", ")", ";", "createdPromise", ".", "catch", "(", "function", "(", ")", "{", "}", ")", ";", "return", "createdPromise", ";", "}" ]
Returns a Promise for the triggered action @return {Promise} Resolved by completed child action. Rejected by failed child action. If listenAndPromise'd, then promise associated to this trigger. Otherwise, the promise is for next child action completion.
[ "Returns", "a", "Promise", "for", "the", "triggered", "action" ]
fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6
https://github.com/reflux/reflux-promise/blob/fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6/src/index.js#L14-L69
train
reflux/reflux-promise
src/index.js
promise
function promise(p) { var me = this; var canHandlePromise = this.children.indexOf("completed") >= 0 && this.children.indexOf("failed") >= 0; if (!canHandlePromise){ throw new Error("Publisher must have \"completed\" and \"failed\" child publishers"); } p.then(function(response) { return me.completed(response); }, function(error) { return me.failed(error); }); }
javascript
function promise(p) { var me = this; var canHandlePromise = this.children.indexOf("completed") >= 0 && this.children.indexOf("failed") >= 0; if (!canHandlePromise){ throw new Error("Publisher must have \"completed\" and \"failed\" child publishers"); } p.then(function(response) { return me.completed(response); }, function(error) { return me.failed(error); }); }
[ "function", "promise", "(", "p", ")", "{", "var", "me", "=", "this", ";", "var", "canHandlePromise", "=", "this", ".", "children", ".", "indexOf", "(", "\"completed\"", ")", ">=", "0", "&&", "this", ".", "children", ".", "indexOf", "(", "\"failed\"", ")", ">=", "0", ";", "if", "(", "!", "canHandlePromise", ")", "{", "throw", "new", "Error", "(", "\"Publisher must have \\\"completed\\\" and \\\"failed\\\" child publishers\"", ")", ";", "}", "\\\"", "}" ]
Attach handlers to promise that trigger the completed and failed child publishers, if available. @param {Object} p The promise to attach to
[ "Attach", "handlers", "to", "promise", "that", "trigger", "the", "completed", "and", "failed", "child", "publishers", "if", "available", "." ]
fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6
https://github.com/reflux/reflux-promise/blob/fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6/src/index.js#L77-L93
train
reflux/reflux-promise
src/index.js
listenAndPromise
function listenAndPromise(callback, bindContext) { var me = this; bindContext = bindContext || this; this.willCallPromise = (this.willCallPromise || 0) + 1; var removeListen = this.listen(function() { if (!callback) { throw new Error("Expected a function returning a promise but got " + callback); } var args = arguments, returnedPromise = callback.apply(bindContext, args); return me.promise.call(me, returnedPromise); }, bindContext); return function () { me.willCallPromise--; removeListen.call(me); }; }
javascript
function listenAndPromise(callback, bindContext) { var me = this; bindContext = bindContext || this; this.willCallPromise = (this.willCallPromise || 0) + 1; var removeListen = this.listen(function() { if (!callback) { throw new Error("Expected a function returning a promise but got " + callback); } var args = arguments, returnedPromise = callback.apply(bindContext, args); return me.promise.call(me, returnedPromise); }, bindContext); return function () { me.willCallPromise--; removeListen.call(me); }; }
[ "function", "listenAndPromise", "(", "callback", ",", "bindContext", ")", "{", "var", "me", "=", "this", ";", "bindContext", "=", "bindContext", "||", "this", ";", "this", ".", "willCallPromise", "=", "(", "this", ".", "willCallPromise", "||", "0", ")", "+", "1", ";", "var", "removeListen", "=", "this", ".", "listen", "(", "function", "(", ")", "{", "if", "(", "!", "callback", ")", "{", "throw", "new", "Error", "(", "\"Expected a function returning a promise but got \"", "+", "callback", ")", ";", "}", "var", "args", "=", "arguments", ",", "returnedPromise", "=", "callback", ".", "apply", "(", "bindContext", ",", "args", ")", ";", "return", "me", ".", "promise", ".", "call", "(", "me", ",", "returnedPromise", ")", ";", "}", ",", "bindContext", ")", ";", "return", "function", "(", ")", "{", "me", ".", "willCallPromise", "--", ";", "removeListen", ".", "call", "(", "me", ")", ";", "}", ";", "}" ]
Subscribes the given callback for action triggered, which should return a promise that in turn is passed to `this.promise` @param {Function} callback The callback to register as event handler
[ "Subscribes", "the", "given", "callback", "for", "action", "triggered", "which", "should", "return", "a", "promise", "that", "in", "turn", "is", "passed", "to", "this", ".", "promise" ]
fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6
https://github.com/reflux/reflux-promise/blob/fa0633ee09f776f7b6d6d4d8fa2e9d3a3ef81cd6/src/index.js#L101-L122
train
KleeGroup/focus-core
src/user/index.js
hasRole
function hasRole(role) { role = isArray(role) ? role : [role]; return 0 < intersection(role, userBuiltInStore.getRoles()).length; }
javascript
function hasRole(role) { role = isArray(role) ? role : [role]; return 0 < intersection(role, userBuiltInStore.getRoles()).length; }
[ "function", "hasRole", "(", "role", ")", "{", "role", "=", "isArray", "(", "role", ")", "?", "role", ":", "[", "role", "]", ";", "return", "0", "<", "intersection", "(", "role", ",", "userBuiltInStore", ".", "getRoles", "(", ")", ")", ".", "length", ";", "}" ]
Check if a user has the givent role or roles. @param {string | array} role - Check if the user has one or many roles. @return {Boolean} - True if the user has at least on of the givent roles.
[ "Check", "if", "a", "user", "has", "the", "givent", "role", "or", "roles", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/user/index.js#L19-L22
train
ExtraHop/metalsmith-sitemap
lib/index.js
check
function check(file, frontmatter) { // Only process files that match the pattern if (!match(file, pattern)[0]) { return false; } // Don't process private files if (get(frontmatter, privateProperty)) { return false; } return true; }
javascript
function check(file, frontmatter) { // Only process files that match the pattern if (!match(file, pattern)[0]) { return false; } // Don't process private files if (get(frontmatter, privateProperty)) { return false; } return true; }
[ "function", "check", "(", "file", ",", "frontmatter", ")", "{", "if", "(", "!", "match", "(", "file", ",", "pattern", ")", "[", "0", "]", ")", "{", "return", "false", ";", "}", "if", "(", "get", "(", "frontmatter", ",", "privateProperty", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks whether files should be processed
[ "Checks", "whether", "files", "should", "be", "processed" ]
6b69101e96c1d3c6e7fedac74fbd45a867615944
https://github.com/ExtraHop/metalsmith-sitemap/blob/6b69101e96c1d3c6e7fedac74fbd45a867615944/lib/index.js#L77-L89
train
ExtraHop/metalsmith-sitemap
lib/index.js
buildUrl
function buildUrl(file, frontmatter) { // Frontmatter settings take precedence var canonicalUrl = get(frontmatter, urlProperty); if (is.string(canonicalUrl)) { return canonicalUrl; } // Remove index.html if necessary var indexFile = 'index.html'; if (omitIndex && path.basename(file) === indexFile) { return replaceBackslash(file.slice(0, 0 - indexFile.length)); } // Remove extension if necessary if (omitExtension) { return replaceBackslash(file.slice(0, 0 - path.extname(file).length)); } // Otherwise just use 'file' return replaceBackslash(file); }
javascript
function buildUrl(file, frontmatter) { // Frontmatter settings take precedence var canonicalUrl = get(frontmatter, urlProperty); if (is.string(canonicalUrl)) { return canonicalUrl; } // Remove index.html if necessary var indexFile = 'index.html'; if (omitIndex && path.basename(file) === indexFile) { return replaceBackslash(file.slice(0, 0 - indexFile.length)); } // Remove extension if necessary if (omitExtension) { return replaceBackslash(file.slice(0, 0 - path.extname(file).length)); } // Otherwise just use 'file' return replaceBackslash(file); }
[ "function", "buildUrl", "(", "file", ",", "frontmatter", ")", "{", "var", "canonicalUrl", "=", "get", "(", "frontmatter", ",", "urlProperty", ")", ";", "if", "(", "is", ".", "string", "(", "canonicalUrl", ")", ")", "{", "return", "canonicalUrl", ";", "}", "var", "indexFile", "=", "'index.html'", ";", "if", "(", "omitIndex", "&&", "path", ".", "basename", "(", "file", ")", "===", "indexFile", ")", "{", "return", "replaceBackslash", "(", "file", ".", "slice", "(", "0", ",", "0", "-", "indexFile", ".", "length", ")", ")", ";", "}", "if", "(", "omitExtension", ")", "{", "return", "replaceBackslash", "(", "file", ".", "slice", "(", "0", ",", "0", "-", "path", ".", "extname", "(", "file", ")", ".", "length", ")", ")", ";", "}", "return", "replaceBackslash", "(", "file", ")", ";", "}" ]
Builds a url
[ "Builds", "a", "url" ]
6b69101e96c1d3c6e7fedac74fbd45a867615944
https://github.com/ExtraHop/metalsmith-sitemap/blob/6b69101e96c1d3c6e7fedac74fbd45a867615944/lib/index.js#L92-L112
train
KleeGroup/focus-core
src/definition/formatter/number.js
init
function init(format = DEFAULT_FORMAT, locale = 'fr') { numeral.locale(locale); numeral.defaultFormat(format); }
javascript
function init(format = DEFAULT_FORMAT, locale = 'fr') { numeral.locale(locale); numeral.defaultFormat(format); }
[ "function", "init", "(", "format", "=", "DEFAULT_FORMAT", ",", "locale", "=", "'fr'", ")", "{", "numeral", ".", "locale", "(", "locale", ")", ";", "numeral", ".", "defaultFormat", "(", "format", ")", ";", "}" ]
Initialize numeral locale and default format. @param {string} [format='0,0'] format to use @param {string} [locale='fr'] locale to use
[ "Initialize", "numeral", "locale", "and", "default", "format", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/definition/formatter/number.js#L21-L24
train
KleeGroup/focus-core
src/network/fetch.js
updateRequestStatus
function updateRequestStatus(request) { if (!request || !request.id || !request.status) { return; } dispatcher.handleViewAction({ data: { request: request }, type: 'update' }); return request; }
javascript
function updateRequestStatus(request) { if (!request || !request.id || !request.status) { return; } dispatcher.handleViewAction({ data: { request: request }, type: 'update' }); return request; }
[ "function", "updateRequestStatus", "(", "request", ")", "{", "if", "(", "!", "request", "||", "!", "request", ".", "id", "||", "!", "request", ".", "status", ")", "{", "return", ";", "}", "dispatcher", ".", "handleViewAction", "(", "{", "data", ":", "{", "request", ":", "request", "}", ",", "type", ":", "'update'", "}", ")", ";", "return", "request", ";", "}" ]
Update the request status. @param {object} request - The request to treat. @return {object} - The request to dispatch.
[ "Update", "the", "request", "status", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/network/fetch.js#L22-L29
train
KleeGroup/focus-core
src/network/fetch.js
getResponseContent
function getResponseContent(response, dataType) { const { type, status, ok } = response; // Handling errors if (type === 'opaque') { console.error('You tried to make a Cross Domain Request with no-cors options'); return Promise.reject({ status: status, globalErrors: ['error.noCorsOptsOnCors'] }); } if (type === 'error') { console.error('An unknown network issue has happened'); return Promise.reject({ status: status, globalErrors: ['error.unknownNetworkIssue'] }); } if (!ok && dataType === 'json') { return response.json().catch(err => Promise.reject({ globalErrors: [err] })).then(data => Promise.reject({ status, ...data })); } if (!ok) { return response.text().then(text => Promise.reject({ status, globalErrors: [text] })); } // Handling success if (ok && status === '204') { return Promise.resolve(null); } return ['arrayBuffer', 'blob', 'formData', 'json'].includes(dataType) ? response[dataType]().catch(err => Promise.reject({ globalErrors: [err] })) : response.text(); }
javascript
function getResponseContent(response, dataType) { const { type, status, ok } = response; // Handling errors if (type === 'opaque') { console.error('You tried to make a Cross Domain Request with no-cors options'); return Promise.reject({ status: status, globalErrors: ['error.noCorsOptsOnCors'] }); } if (type === 'error') { console.error('An unknown network issue has happened'); return Promise.reject({ status: status, globalErrors: ['error.unknownNetworkIssue'] }); } if (!ok && dataType === 'json') { return response.json().catch(err => Promise.reject({ globalErrors: [err] })).then(data => Promise.reject({ status, ...data })); } if (!ok) { return response.text().then(text => Promise.reject({ status, globalErrors: [text] })); } // Handling success if (ok && status === '204') { return Promise.resolve(null); } return ['arrayBuffer', 'blob', 'formData', 'json'].includes(dataType) ? response[dataType]().catch(err => Promise.reject({ globalErrors: [err] })) : response.text(); }
[ "function", "getResponseContent", "(", "response", ",", "dataType", ")", "{", "const", "{", "type", ",", "status", ",", "ok", "}", "=", "response", ";", "if", "(", "type", "===", "'opaque'", ")", "{", "console", ".", "error", "(", "'You tried to make a Cross Domain Request with no-cors options'", ")", ";", "return", "Promise", ".", "reject", "(", "{", "status", ":", "status", ",", "globalErrors", ":", "[", "'error.noCorsOptsOnCors'", "]", "}", ")", ";", "}", "if", "(", "type", "===", "'error'", ")", "{", "console", ".", "error", "(", "'An unknown network issue has happened'", ")", ";", "return", "Promise", ".", "reject", "(", "{", "status", ":", "status", ",", "globalErrors", ":", "[", "'error.unknownNetworkIssue'", "]", "}", ")", ";", "}", "if", "(", "!", "ok", "&&", "dataType", "===", "'json'", ")", "{", "return", "response", ".", "json", "(", ")", ".", "catch", "(", "err", "=>", "Promise", ".", "reject", "(", "{", "globalErrors", ":", "[", "err", "]", "}", ")", ")", ".", "then", "(", "data", "=>", "Promise", ".", "reject", "(", "{", "status", ",", "...", "data", "}", ")", ")", ";", "}", "if", "(", "!", "ok", ")", "{", "return", "response", ".", "text", "(", ")", ".", "then", "(", "text", "=>", "Promise", ".", "reject", "(", "{", "status", ",", "globalErrors", ":", "[", "text", "]", "}", ")", ")", ";", "}", "if", "(", "ok", "&&", "status", "===", "'204'", ")", "{", "return", "Promise", ".", "resolve", "(", "null", ")", ";", "}", "return", "[", "'arrayBuffer'", ",", "'blob'", ",", "'formData'", ",", "'json'", "]", ".", "includes", "(", "dataType", ")", "?", "response", "[", "dataType", "]", "(", ")", ".", "catch", "(", "err", "=>", "Promise", ".", "reject", "(", "{", "globalErrors", ":", "[", "err", "]", "}", ")", ")", ":", "response", ".", "text", "(", ")", ";", "}" ]
Extract the data from the response, and handle network or server errors or wrong data format. @param {Response} response the response to extract from @param {string} dataType the datatype (can be 'arrayBuffer', 'blob', 'formData', 'json' or 'text') @returns {Promise} a Promise containing response data, or error data
[ "Extract", "the", "data", "from", "the", "response", "and", "handle", "network", "or", "server", "errors", "or", "wrong", "data", "format", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/network/fetch.js#L38-L65
train
KleeGroup/focus-core
src/network/fetch.js
checkErrors
function checkErrors(response, xhrErrors) { let { status, ok } = response; if (!ok) { if (xhrErrors[status]) { xhrErrors[status](response); } } }
javascript
function checkErrors(response, xhrErrors) { let { status, ok } = response; if (!ok) { if (xhrErrors[status]) { xhrErrors[status](response); } } }
[ "function", "checkErrors", "(", "response", ",", "xhrErrors", ")", "{", "let", "{", "status", ",", "ok", "}", "=", "response", ";", "if", "(", "!", "ok", ")", "{", "if", "(", "xhrErrors", "[", "status", "]", ")", "{", "xhrErrors", "[", "status", "]", "(", "response", ")", ";", "}", "}", "}" ]
Check if a special treatment is specify for a specific error code @param {Object} response The fetch response @param {Object} xhrErrors The specific treatment
[ "Check", "if", "a", "special", "treatment", "is", "specify", "for", "a", "specific", "error", "code" ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/network/fetch.js#L73-L80
train
KleeGroup/focus-core
src/network/fetch.js
wrappingFetch
function wrappingFetch({ url, method, data }, optionsArg) { let requestStatus = createRequestStatus(); // Here we are using destruct to filter properties we do not want to give to fetch. // CORS and isCORS are useless legacy code, xhrErrors is used only in error parsing // eslint-disable-next-line no-unused-vars let { CORS, isCORS, xhrErrors, ...config } = configGetter(); const { noStringify, ...options } = optionsArg || {}; const reqOptions = merge({ headers: {} }, config, options, { method, body: noStringify ? data : JSON.stringify(data) }); //By default, add json content-type if (!reqOptions.noContentType && !reqOptions.headers['Content-Type']) { reqOptions.headers['Content-Type'] = 'application/json'; } // Set the requesting as pending updateRequestStatus({ id: requestStatus.id, status: 'pending' }); // Do the request return fetch(url, reqOptions) // Catch the possible TypeError from fetch .catch(error => { updateRequestStatus({ id: requestStatus.id, status: 'error' }); return Promise.reject({ globalErrors: [error] }); }).then(response => { updateRequestStatus({ id: requestStatus.id, status: response.ok ? 'success' : 'error' }); const contentType = response.headers.get('content-type'); return getResponseContent(response, reqOptions.dataType ? reqOptions.dataType : contentType && contentType.includes('application/json') ? 'json' : 'text'); }).catch(data => { checkErrors(data, xhrErrors); return Promise.reject(data); }); }
javascript
function wrappingFetch({ url, method, data }, optionsArg) { let requestStatus = createRequestStatus(); // Here we are using destruct to filter properties we do not want to give to fetch. // CORS and isCORS are useless legacy code, xhrErrors is used only in error parsing // eslint-disable-next-line no-unused-vars let { CORS, isCORS, xhrErrors, ...config } = configGetter(); const { noStringify, ...options } = optionsArg || {}; const reqOptions = merge({ headers: {} }, config, options, { method, body: noStringify ? data : JSON.stringify(data) }); //By default, add json content-type if (!reqOptions.noContentType && !reqOptions.headers['Content-Type']) { reqOptions.headers['Content-Type'] = 'application/json'; } // Set the requesting as pending updateRequestStatus({ id: requestStatus.id, status: 'pending' }); // Do the request return fetch(url, reqOptions) // Catch the possible TypeError from fetch .catch(error => { updateRequestStatus({ id: requestStatus.id, status: 'error' }); return Promise.reject({ globalErrors: [error] }); }).then(response => { updateRequestStatus({ id: requestStatus.id, status: response.ok ? 'success' : 'error' }); const contentType = response.headers.get('content-type'); return getResponseContent(response, reqOptions.dataType ? reqOptions.dataType : contentType && contentType.includes('application/json') ? 'json' : 'text'); }).catch(data => { checkErrors(data, xhrErrors); return Promise.reject(data); }); }
[ "function", "wrappingFetch", "(", "{", "url", ",", "method", ",", "data", "}", ",", "optionsArg", ")", "{", "let", "requestStatus", "=", "createRequestStatus", "(", ")", ";", "let", "{", "CORS", ",", "isCORS", ",", "xhrErrors", ",", "...", "config", "}", "=", "configGetter", "(", ")", ";", "const", "{", "noStringify", ",", "...", "options", "}", "=", "optionsArg", "||", "{", "}", ";", "const", "reqOptions", "=", "merge", "(", "{", "headers", ":", "{", "}", "}", ",", "config", ",", "options", ",", "{", "method", ",", "body", ":", "noStringify", "?", "data", ":", "JSON", ".", "stringify", "(", "data", ")", "}", ")", ";", "if", "(", "!", "reqOptions", ".", "noContentType", "&&", "!", "reqOptions", ".", "headers", "[", "'Content-Type'", "]", ")", "{", "reqOptions", ".", "headers", "[", "'Content-Type'", "]", "=", "'application/json'", ";", "}", "updateRequestStatus", "(", "{", "id", ":", "requestStatus", ".", "id", ",", "status", ":", "'pending'", "}", ")", ";", "return", "fetch", "(", "url", ",", "reqOptions", ")", ".", "catch", "(", "error", "=>", "{", "updateRequestStatus", "(", "{", "id", ":", "requestStatus", ".", "id", ",", "status", ":", "'error'", "}", ")", ";", "return", "Promise", ".", "reject", "(", "{", "globalErrors", ":", "[", "error", "]", "}", ")", ";", "}", ")", ".", "then", "(", "response", "=>", "{", "updateRequestStatus", "(", "{", "id", ":", "requestStatus", ".", "id", ",", "status", ":", "response", ".", "ok", "?", "'success'", ":", "'error'", "}", ")", ";", "const", "contentType", "=", "response", ".", "headers", ".", "get", "(", "'content-type'", ")", ";", "return", "getResponseContent", "(", "response", ",", "reqOptions", ".", "dataType", "?", "reqOptions", ".", "dataType", ":", "contentType", "&&", "contentType", ".", "includes", "(", "'application/json'", ")", "?", "'json'", ":", "'text'", ")", ";", "}", ")", ".", "catch", "(", "data", "=>", "{", "checkErrors", "(", "data", ",", "xhrErrors", ")", ";", "return", "Promise", ".", "reject", "(", "data", ")", ";", "}", ")", ";", "}" ]
Fetch function to ease http request. @param {object} obj - method: http verb, url: http url, data:The json to save. @param {object} options - The options object. @return {CancellablePromise} The promise of the execution of the HTTP request.
[ "Fetch", "function", "to", "ease", "http", "request", "." ]
6ce70638e0c5acdd25830a14ce3b154f84a17405
https://github.com/KleeGroup/focus-core/blob/6ce70638e0c5acdd25830a14ce3b154f84a17405/src/network/fetch.js#L88-L116
train