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
bitnami/nami-utils
lib/file/rename.js
rename
function rename(source, destination) { const parent = path.dirname(destination); if (exists(destination)) { if (isDirectory(destination)) { destination = path.join(destination, path.basename(source)); } else { if (isDirectory(source)) { throw new Error(`Cannot rename directory ${source} into existing file ${destination}`); } } } else if (!exists(parent)) { mkdir(parent); } try { fs.renameSync(source, destination); } catch (e) { if (e.code !== 'EXDEV') throw e; // Fallback for moving across devices copy(source, destination); fileDelete(source); } }
javascript
function rename(source, destination) { const parent = path.dirname(destination); if (exists(destination)) { if (isDirectory(destination)) { destination = path.join(destination, path.basename(source)); } else { if (isDirectory(source)) { throw new Error(`Cannot rename directory ${source} into existing file ${destination}`); } } } else if (!exists(parent)) { mkdir(parent); } try { fs.renameSync(source, destination); } catch (e) { if (e.code !== 'EXDEV') throw e; // Fallback for moving across devices copy(source, destination); fileDelete(source); } }
[ "function", "rename", "(", "source", ",", "destination", ")", "{", "const", "parent", "=", "path", ".", "dirname", "(", "destination", ")", ";", "if", "(", "exists", "(", "destination", ")", ")", "{", "if", "(", "isDirectory", "(", "destination", ")", ")", "{", "destination", "=", "path", ".", "join", "(", "destination", ",", "path", ".", "basename", "(", "source", ")", ")", ";", "}", "else", "{", "if", "(", "isDirectory", "(", "source", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "source", "}", "${", "destination", "}", "`", ")", ";", "}", "}", "}", "else", "if", "(", "!", "exists", "(", "parent", ")", ")", "{", "mkdir", "(", "parent", ")", ";", "}", "try", "{", "fs", ".", "renameSync", "(", "source", ",", "destination", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "code", "!==", "'EXDEV'", ")", "throw", "e", ";", "copy", "(", "source", ",", "destination", ")", ";", "fileDelete", "(", "source", ")", ";", "}", "}" ]
Rename file or directory @function $file~rename @param {string} source @param {string} destination @example // Rename default configuration file $file.move('conf/php.ini-production', 'conf/php.ini'); Alias of {@link $file~rename} @function $file~move
[ "Rename", "file", "or", "directory" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/rename.js#L25-L46
train
DirektoratetForByggkvalitet/losen
src/web/components/blocks/Block.js
getBlock
function getBlock(type) { switch (type) { case 'Radio': case 'Bool': return Radio; case 'Checkbox': return Checkbox; case 'Number': return Number; case 'Select': return Select; case 'Image': return Image; case 'Text': return Text; case 'Input': return Input; case 'Textarea': return Textarea; case 'Data': return Data; case 'Evaluation': return Evaluation; case 'FetchOrg': return FetchOrg; case 'Table': return Table; case 'Signature': return Signature; case 'Summary': return Summary; case 'Sum': return Sum; case 'Switch': return Switch; case 'Information': return Information; default: return null; } }
javascript
function getBlock(type) { switch (type) { case 'Radio': case 'Bool': return Radio; case 'Checkbox': return Checkbox; case 'Number': return Number; case 'Select': return Select; case 'Image': return Image; case 'Text': return Text; case 'Input': return Input; case 'Textarea': return Textarea; case 'Data': return Data; case 'Evaluation': return Evaluation; case 'FetchOrg': return FetchOrg; case 'Table': return Table; case 'Signature': return Signature; case 'Summary': return Summary; case 'Sum': return Sum; case 'Switch': return Switch; case 'Information': return Information; default: return null; } }
[ "function", "getBlock", "(", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "'Radio'", ":", "case", "'Bool'", ":", "return", "Radio", ";", "case", "'Checkbox'", ":", "return", "Checkbox", ";", "case", "'Number'", ":", "return", "Number", ";", "case", "'Select'", ":", "return", "Select", ";", "case", "'Image'", ":", "return", "Image", ";", "case", "'Text'", ":", "return", "Text", ";", "case", "'Input'", ":", "return", "Input", ";", "case", "'Textarea'", ":", "return", "Textarea", ";", "case", "'Data'", ":", "return", "Data", ";", "case", "'Evaluation'", ":", "return", "Evaluation", ";", "case", "'FetchOrg'", ":", "return", "FetchOrg", ";", "case", "'Table'", ":", "return", "Table", ";", "case", "'Signature'", ":", "return", "Signature", ";", "case", "'Summary'", ":", "return", "Summary", ";", "case", "'Sum'", ":", "return", "Sum", ";", "case", "'Switch'", ":", "return", "Switch", ";", "case", "'Information'", ":", "return", "Information", ";", "default", ":", "return", "null", ";", "}", "}" ]
Determine which component to use based on the node type @param string type Type string from schema
[ "Determine", "which", "component", "to", "use", "based", "on", "the", "node", "type" ]
e13103d5641983bd15e5714afe87017b59e778bb
https://github.com/DirektoratetForByggkvalitet/losen/blob/e13103d5641983bd15e5714afe87017b59e778bb/src/web/components/blocks/Block.js#L46-L103
train
bitnami/nami-utils
lib/file/ini/get.js
iniFileGet
function iniFileGet(file, section, key, options) { options = _.sanitize(options, {encoding: 'utf-8', default: ''}); if (!exists(file)) { return ''; } else if (!isFile(file)) { throw new Error(`File '${file}' is not a file`); } const config = ini.parse(read(file, _.pick(options, 'encoding'))); let value; if (section in config) { value = config[section][key]; } else if (_.isEmpty(section)) { // global section value = config[key]; } return _.isUndefined(value) ? options.default : value; }
javascript
function iniFileGet(file, section, key, options) { options = _.sanitize(options, {encoding: 'utf-8', default: ''}); if (!exists(file)) { return ''; } else if (!isFile(file)) { throw new Error(`File '${file}' is not a file`); } const config = ini.parse(read(file, _.pick(options, 'encoding'))); let value; if (section in config) { value = config[section][key]; } else if (_.isEmpty(section)) { // global section value = config[key]; } return _.isUndefined(value) ? options.default : value; }
[ "function", "iniFileGet", "(", "file", ",", "section", ",", "key", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "encoding", ":", "'utf-8'", ",", "default", ":", "''", "}", ")", ";", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "return", "''", ";", "}", "else", "if", "(", "!", "isFile", "(", "file", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "file", "}", "`", ")", ";", "}", "const", "config", "=", "ini", ".", "parse", "(", "read", "(", "file", ",", "_", ".", "pick", "(", "options", ",", "'encoding'", ")", ")", ")", ";", "let", "value", ";", "if", "(", "section", "in", "config", ")", "{", "value", "=", "config", "[", "section", "]", "[", "key", "]", ";", "}", "else", "if", "(", "_", ".", "isEmpty", "(", "section", ")", ")", "{", "value", "=", "config", "[", "key", "]", ";", "}", "return", "_", ".", "isUndefined", "(", "value", ")", "?", "options", ".", "default", ":", "value", ";", "}" ]
Get value from ini file @function $file~ini/get @param {string} file - Ini File to read the value from @param {string} section - Section from which to read the key (null if global section) @param {string} key @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @param {string} [options.default=''] - Default value if key not found @return {string} @throws Will throw an error if the path is not a file @example // Get 'opcache.enable' property under the 'opcache' section $file.ini.get('etc/php.ini', 'opcache', 'opcache.enable'); // => '1'
[ "Get", "value", "from", "ini", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/ini/get.js#L26-L42
train
bitnami/nami-utils
lib/util/sleep.js
sleep
function sleep(seconds) { const time = parseFloat(seconds, 10); if (!_.isFinite(time)) { throw new Error(`invalid time interval '${seconds}'`); } runProgram('sleep', [time], {logCommand: false}); }
javascript
function sleep(seconds) { const time = parseFloat(seconds, 10); if (!_.isFinite(time)) { throw new Error(`invalid time interval '${seconds}'`); } runProgram('sleep', [time], {logCommand: false}); }
[ "function", "sleep", "(", "seconds", ")", "{", "const", "time", "=", "parseFloat", "(", "seconds", ",", "10", ")", ";", "if", "(", "!", "_", ".", "isFinite", "(", "time", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "seconds", "}", "`", ")", ";", "}", "runProgram", "(", "'sleep'", ",", "[", "time", "]", ",", "{", "logCommand", ":", "false", "}", ")", ";", "}" ]
Wait the specified amount of seconds @function $util~sleep @param {string} seconds - Seconds to wait @example // Wait for 5 seconds $util.sleep(5);
[ "Wait", "the", "specified", "amount", "of", "seconds" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/util/sleep.js#L14-L18
train
baby-loris/bla
blocks/bla-error/bla-error.js
ApiError
function ApiError(type, message, data) { this.name = 'ApiError'; this.type = type; this.message = message; this.data = data; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } }
javascript
function ApiError(type, message, data) { this.name = 'ApiError'; this.type = type; this.message = message; this.data = data; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } }
[ "function", "ApiError", "(", "type", ",", "message", ",", "data", ")", "{", "this", ".", "name", "=", "'ApiError'", ";", "this", ".", "type", "=", "type", ";", "this", ".", "message", "=", "message", ";", "this", ".", "data", "=", "data", ";", "if", "(", "Error", ".", "captureStackTrace", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "}", "}" ]
API error. @param {String} type Error type. @param {String} message Human-readable description of the error. @param {Object} data Extra data (stack trace, for example).
[ "API", "error", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla-error/bla-error.js#L10-L19
train
bitnami/nami-utils
lib/file/strip-path-elements.js
stripPathElements
function stripPathElements(filePath, nelements, from) { if (!nelements || nelements <= 0) return filePath; from = from || 'start'; filePath = filePath.replace(/\/+$/, ''); let splitPath = split(filePath); if (from === 'start' && path.isAbsolute(filePath) && splitPath[0] === '/') splitPath = splitPath.slice(1); let start = 0; let end = splitPath.length; if (from === 'start') { start = nelements; end = splitPath.length; } else { start = 0; end = splitPath.length - nelements; } return join(splitPath.slice(start, end)); }
javascript
function stripPathElements(filePath, nelements, from) { if (!nelements || nelements <= 0) return filePath; from = from || 'start'; filePath = filePath.replace(/\/+$/, ''); let splitPath = split(filePath); if (from === 'start' && path.isAbsolute(filePath) && splitPath[0] === '/') splitPath = splitPath.slice(1); let start = 0; let end = splitPath.length; if (from === 'start') { start = nelements; end = splitPath.length; } else { start = 0; end = splitPath.length - nelements; } return join(splitPath.slice(start, end)); }
[ "function", "stripPathElements", "(", "filePath", ",", "nelements", ",", "from", ")", "{", "if", "(", "!", "nelements", "||", "nelements", "<=", "0", ")", "return", "filePath", ";", "from", "=", "from", "||", "'start'", ";", "filePath", "=", "filePath", ".", "replace", "(", "/", "\\/+$", "/", ",", "''", ")", ";", "let", "splitPath", "=", "split", "(", "filePath", ")", ";", "if", "(", "from", "===", "'start'", "&&", "path", ".", "isAbsolute", "(", "filePath", ")", "&&", "splitPath", "[", "0", "]", "===", "'/'", ")", "splitPath", "=", "splitPath", ".", "slice", "(", "1", ")", ";", "let", "start", "=", "0", ";", "let", "end", "=", "splitPath", ".", "length", ";", "if", "(", "from", "===", "'start'", ")", "{", "start", "=", "nelements", ";", "end", "=", "splitPath", ".", "length", ";", "}", "else", "{", "start", "=", "0", ";", "end", "=", "splitPath", ".", "length", "-", "nelements", ";", "}", "return", "join", "(", "splitPath", ".", "slice", "(", "start", ",", "end", ")", ")", ";", "}" ]
Return the provided path with nelements path elements removed @function $file~stripPath @param {string} path - File path to modify @param {number} nelements - Number of path elements to strip @param {string} [from=start] - Strip from the beginning (start) or end (end) @returns {string} - The stripped path @example // Remove first two elements of a path $file.stripPath('/foo/bar/file', 2); // => 'file' @example // Remove last element of a path $file.stripPath('/foo/bar/file', 1, 'end'); // => '/foo/bar'
[ "Return", "the", "provided", "path", "with", "nelements", "path", "elements", "removed" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/strip-path-elements.js#L23-L39
train
bitnami/nami-utils
lib/file/list-dir-contents.js
listDirContents
function listDirContents(prefix, options) { prefix = path.resolve(prefix); options = _.sanitize(options, {stripPrefix: false, includeTopDir: false, compact: true, getAllAttrs: false, include: ['*'], exclude: [], onlyFiles: false, rootDir: null, prefix: null, followSymLinks: false, listSymLinks: true}); const results = []; // TODO: prefix is an alias to rootDir. Remove it const root = options.rootDir || options.prefix || prefix; walkDir(prefix, (file, data) => { if (!matches(file, options.include, options.exclude)) return; if (data.type === 'directory' && options.onlyFiles) return; if (data.type === 'link' && !options.listSymLinks) return; if (data.topDir && !options.includeTopDir) return; const filename = options.stripPrefix ? data.file : file; if (options.compact) { results.push(filename); } else { let fileInfo = {file: filename, type: data.type}; if (options.getAllAttrs) { fileInfo = _getFileMetadata(file, fileInfo); fileInfo.srcPath = file; } results.push(fileInfo); } }, {prefix: root}); return results; }
javascript
function listDirContents(prefix, options) { prefix = path.resolve(prefix); options = _.sanitize(options, {stripPrefix: false, includeTopDir: false, compact: true, getAllAttrs: false, include: ['*'], exclude: [], onlyFiles: false, rootDir: null, prefix: null, followSymLinks: false, listSymLinks: true}); const results = []; // TODO: prefix is an alias to rootDir. Remove it const root = options.rootDir || options.prefix || prefix; walkDir(prefix, (file, data) => { if (!matches(file, options.include, options.exclude)) return; if (data.type === 'directory' && options.onlyFiles) return; if (data.type === 'link' && !options.listSymLinks) return; if (data.topDir && !options.includeTopDir) return; const filename = options.stripPrefix ? data.file : file; if (options.compact) { results.push(filename); } else { let fileInfo = {file: filename, type: data.type}; if (options.getAllAttrs) { fileInfo = _getFileMetadata(file, fileInfo); fileInfo.srcPath = file; } results.push(fileInfo); } }, {prefix: root}); return results; }
[ "function", "listDirContents", "(", "prefix", ",", "options", ")", "{", "prefix", "=", "path", ".", "resolve", "(", "prefix", ")", ";", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "stripPrefix", ":", "false", ",", "includeTopDir", ":", "false", ",", "compact", ":", "true", ",", "getAllAttrs", ":", "false", ",", "include", ":", "[", "'*'", "]", ",", "exclude", ":", "[", "]", ",", "onlyFiles", ":", "false", ",", "rootDir", ":", "null", ",", "prefix", ":", "null", ",", "followSymLinks", ":", "false", ",", "listSymLinks", ":", "true", "}", ")", ";", "const", "results", "=", "[", "]", ";", "const", "root", "=", "options", ".", "rootDir", "||", "options", ".", "prefix", "||", "prefix", ";", "walkDir", "(", "prefix", ",", "(", "file", ",", "data", ")", "=>", "{", "if", "(", "!", "matches", "(", "file", ",", "options", ".", "include", ",", "options", ".", "exclude", ")", ")", "return", ";", "if", "(", "data", ".", "type", "===", "'directory'", "&&", "options", ".", "onlyFiles", ")", "return", ";", "if", "(", "data", ".", "type", "===", "'link'", "&&", "!", "options", ".", "listSymLinks", ")", "return", ";", "if", "(", "data", ".", "topDir", "&&", "!", "options", ".", "includeTopDir", ")", "return", ";", "const", "filename", "=", "options", ".", "stripPrefix", "?", "data", ".", "file", ":", "file", ";", "if", "(", "options", ".", "compact", ")", "{", "results", ".", "push", "(", "filename", ")", ";", "}", "else", "{", "let", "fileInfo", "=", "{", "file", ":", "filename", ",", "type", ":", "data", ".", "type", "}", ";", "if", "(", "options", ".", "getAllAttrs", ")", "{", "fileInfo", "=", "_getFileMetadata", "(", "file", ",", "fileInfo", ")", ";", "fileInfo", ".", "srcPath", "=", "file", ";", "}", "results", ".", "push", "(", "fileInfo", ")", ";", "}", "}", ",", "{", "prefix", ":", "root", "}", ")", ";", "return", "results", ";", "}" ]
List content in a directory @private @param {string} prefix - Directory to walk over @param {Object} [options] @param {boolean} [options.stripPrefix=false] - Strip prefix from filename. @param {boolean} [options.includeTopDir=false] - Include top directory in the returned list. @param {boolean} [options.compact=true] - Return only the filename instead of filename and additional information of the file. @param {boolean} [options.getAllAttrs=false] - Add even more information about the file. @param {boolean} [options.include=['*']] - Files to include. @param {boolean} [options.exclude=[]] - Files to exclude. @param {boolean} [options.onlyFiles=false] - Exclude directories. @param {boolean} [options.followSymLinks=false] - Follow symbolic links. @param {boolean} [options.listSymLinks=true] - List symbolic links.
[ "List", "content", "in", "a", "directory" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/list-dir-contents.js#L30-L56
train
bitnami/nami-utils
lib/file/get-owner-and-group.js
getOwnerAndGroup
function getOwnerAndGroup(file) { const data = fs.lstatSync(file); const groupname = getGroupname(data.gid, {throwIfNotFound: false}) || null; const username = getUsername(data.uid, {throwIfNotFound: false}) || null; return {uid: data.uid, gid: data.gid, username: username, groupname: groupname}; }
javascript
function getOwnerAndGroup(file) { const data = fs.lstatSync(file); const groupname = getGroupname(data.gid, {throwIfNotFound: false}) || null; const username = getUsername(data.uid, {throwIfNotFound: false}) || null; return {uid: data.uid, gid: data.gid, username: username, groupname: groupname}; }
[ "function", "getOwnerAndGroup", "(", "file", ")", "{", "const", "data", "=", "fs", ".", "lstatSync", "(", "file", ")", ";", "const", "groupname", "=", "getGroupname", "(", "data", ".", "gid", ",", "{", "throwIfNotFound", ":", "false", "}", ")", "||", "null", ";", "const", "username", "=", "getUsername", "(", "data", ".", "uid", ",", "{", "throwIfNotFound", ":", "false", "}", ")", "||", "null", ";", "return", "{", "uid", ":", "data", ".", "uid", ",", "gid", ":", "data", ".", "gid", ",", "username", ":", "username", ",", "groupname", ":", "groupname", "}", ";", "}" ]
Get file owner and group information @function $file~getOwnerAndGroup @param {string} file @returns {object} - Object containing the file ownership attributes: groupname, username, uid, gid @example // Get owner and group information of 'conf/my.cnf' $file.getOwnerAndGroup('conf/my.cnf'); // => { uid: 1001, gid: 1001, username: 'mysql', groupname: 'mysql' }
[ "Get", "file", "owner", "and", "group", "information" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/get-owner-and-group.js#L17-L22
train
bitnami/nami-utils
lib/file/chown.js
_chown
function _chown(file, uid, gid, options) { options = _.opts(options, {abortOnError: true}); uid = parseInt(uid, 10); uid = _.isFinite(uid) ? uid : getUid(_fileStats(file).uid, {refresh: false}); gid = parseInt(gid, 10); gid = _.isFinite(gid) ? gid : getGid(_fileStats(file).gid, {refresh: false}); try { if (options.abortOnError) { nodeFs.chownSync(file, uid, gid); } else { fs.chownSync(file, uid, gid); } } catch (e) { if (options.abortOnError) { throw e; } } }
javascript
function _chown(file, uid, gid, options) { options = _.opts(options, {abortOnError: true}); uid = parseInt(uid, 10); uid = _.isFinite(uid) ? uid : getUid(_fileStats(file).uid, {refresh: false}); gid = parseInt(gid, 10); gid = _.isFinite(gid) ? gid : getGid(_fileStats(file).gid, {refresh: false}); try { if (options.abortOnError) { nodeFs.chownSync(file, uid, gid); } else { fs.chownSync(file, uid, gid); } } catch (e) { if (options.abortOnError) { throw e; } } }
[ "function", "_chown", "(", "file", ",", "uid", ",", "gid", ",", "options", ")", "{", "options", "=", "_", ".", "opts", "(", "options", ",", "{", "abortOnError", ":", "true", "}", ")", ";", "uid", "=", "parseInt", "(", "uid", ",", "10", ")", ";", "uid", "=", "_", ".", "isFinite", "(", "uid", ")", "?", "uid", ":", "getUid", "(", "_fileStats", "(", "file", ")", ".", "uid", ",", "{", "refresh", ":", "false", "}", ")", ";", "gid", "=", "parseInt", "(", "gid", ",", "10", ")", ";", "gid", "=", "_", ".", "isFinite", "(", "gid", ")", "?", "gid", ":", "getGid", "(", "_fileStats", "(", "file", ")", ".", "gid", ",", "{", "refresh", ":", "false", "}", ")", ";", "try", "{", "if", "(", "options", ".", "abortOnError", ")", "{", "nodeFs", ".", "chownSync", "(", "file", ",", "uid", ",", "gid", ")", ";", "}", "else", "{", "fs", ".", "chownSync", "(", "file", ",", "uid", ",", "gid", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "if", "(", "options", ".", "abortOnError", ")", "{", "throw", "e", ";", "}", "}", "}" ]
this is a strict function signature version of _chown, it also do not worry about recursivity
[ "this", "is", "a", "strict", "function", "signature", "version", "of", "_chown", "it", "also", "do", "not", "worry", "about", "recursivity" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/chown.js#L17-L34
train
bitnami/nami-utils
lib/file/chown.js
chown
function chown(file, uid, gid, options) { if (!isPlatform('unix')) return; if (_.isObject(uid)) { options = gid; const ownerInfo = uid; uid = (ownerInfo.uid || ownerInfo.owner || ownerInfo.user || ownerInfo.username); gid = (ownerInfo.gid || ownerInfo.group); } options = _.sanitize(options, {abortOnError: true, recursive: false}); let recurse = false; try { if (uid) uid = getUid(uid, {refresh: false}); if (gid) gid = getGid(gid, {refresh: false}); if (!exists(file)) throw new Error(`Path '${file}' does not exists`); recurse = options.recursive && isDirectory(file); } catch (e) { if (options.abortOnError) { throw e; } else { return; } } if (recurse) { _.each(listDirContents(file, {includeTopDir: true}), function(f) { _chown(f, uid, gid, options); }); } else { _chown(file, uid, gid, options); } }
javascript
function chown(file, uid, gid, options) { if (!isPlatform('unix')) return; if (_.isObject(uid)) { options = gid; const ownerInfo = uid; uid = (ownerInfo.uid || ownerInfo.owner || ownerInfo.user || ownerInfo.username); gid = (ownerInfo.gid || ownerInfo.group); } options = _.sanitize(options, {abortOnError: true, recursive: false}); let recurse = false; try { if (uid) uid = getUid(uid, {refresh: false}); if (gid) gid = getGid(gid, {refresh: false}); if (!exists(file)) throw new Error(`Path '${file}' does not exists`); recurse = options.recursive && isDirectory(file); } catch (e) { if (options.abortOnError) { throw e; } else { return; } } if (recurse) { _.each(listDirContents(file, {includeTopDir: true}), function(f) { _chown(f, uid, gid, options); }); } else { _chown(file, uid, gid, options); } }
[ "function", "chown", "(", "file", ",", "uid", ",", "gid", ",", "options", ")", "{", "if", "(", "!", "isPlatform", "(", "'unix'", ")", ")", "return", ";", "if", "(", "_", ".", "isObject", "(", "uid", ")", ")", "{", "options", "=", "gid", ";", "const", "ownerInfo", "=", "uid", ";", "uid", "=", "(", "ownerInfo", ".", "uid", "||", "ownerInfo", ".", "owner", "||", "ownerInfo", ".", "user", "||", "ownerInfo", ".", "username", ")", ";", "gid", "=", "(", "ownerInfo", ".", "gid", "||", "ownerInfo", ".", "group", ")", ";", "}", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "abortOnError", ":", "true", ",", "recursive", ":", "false", "}", ")", ";", "let", "recurse", "=", "false", ";", "try", "{", "if", "(", "uid", ")", "uid", "=", "getUid", "(", "uid", ",", "{", "refresh", ":", "false", "}", ")", ";", "if", "(", "gid", ")", "gid", "=", "getGid", "(", "gid", ",", "{", "refresh", ":", "false", "}", ")", ";", "if", "(", "!", "exists", "(", "file", ")", ")", "throw", "new", "Error", "(", "`", "${", "file", "}", "`", ")", ";", "recurse", "=", "options", ".", "recursive", "&&", "isDirectory", "(", "file", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "options", ".", "abortOnError", ")", "{", "throw", "e", ";", "}", "else", "{", "return", ";", "}", "}", "if", "(", "recurse", ")", "{", "_", ".", "each", "(", "listDirContents", "(", "file", ",", "{", "includeTopDir", ":", "true", "}", ")", ",", "function", "(", "f", ")", "{", "_chown", "(", "f", ",", "uid", ",", "gid", ",", "options", ")", ";", "}", ")", ";", "}", "else", "{", "_chown", "(", "file", ",", "uid", ",", "gid", ",", "options", ")", ";", "}", "}" ]
Change file owner @function $file~chown @param {string} file - File which owner and grop will be modified @param {string|number} uid - Username or uid number to set. Can be provided as null @param {string|number} gid - Group or gid number to set. Can be provided as null @param {Object} [options] @param {boolean} [options.abortOnError=true] - Throw an error if the function fails to execute @param {boolean} [options.recursive=false] - Change directory owner recursively @example // Set the owner of 'conf/my.cnf' to 'mysql' $file.chown('conf/my.cnf', 'mysql'); @example // Change 'plugins' directory owner user and group recursively $file.chown('plugins', 'daemon', 'daemon', {recursive: true});
[ "Change", "file", "owner" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/chown.js#L52-L82
train
bitnami/nami-utils
lib/net/is-port-in-use.js
isPortInUse
function isPortInUse(port) { _validatePortFormat(port); if (isPlatform('unix')) { if (isPlatform('linux') && fileExists('/proc/net')) { return _isPortInUseRaw(port); } else if (isInPath('netstat')) { return _isPortInUseNetstat(port); } else { throw new Error('Cannot check port status'); } } else { throw new Error('Port checking not supported on this platform'); } }
javascript
function isPortInUse(port) { _validatePortFormat(port); if (isPlatform('unix')) { if (isPlatform('linux') && fileExists('/proc/net')) { return _isPortInUseRaw(port); } else if (isInPath('netstat')) { return _isPortInUseNetstat(port); } else { throw new Error('Cannot check port status'); } } else { throw new Error('Port checking not supported on this platform'); } }
[ "function", "isPortInUse", "(", "port", ")", "{", "_validatePortFormat", "(", "port", ")", ";", "if", "(", "isPlatform", "(", "'unix'", ")", ")", "{", "if", "(", "isPlatform", "(", "'linux'", ")", "&&", "fileExists", "(", "'/proc/net'", ")", ")", "{", "return", "_isPortInUseRaw", "(", "port", ")", ";", "}", "else", "if", "(", "isInPath", "(", "'netstat'", ")", ")", "{", "return", "_isPortInUseNetstat", "(", "port", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Cannot check port status'", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "'Port checking not supported on this platform'", ")", ";", "}", "}" ]
Check if the given port is in use @function $net~isPortInUse @param {string} port - Port to check @returns {boolean} - Whether the port is in use or not @example // Check if the port 8080 is already in use $net.isPortInUse(8080); => false
[ "Check", "if", "the", "given", "port", "is", "in", "use" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/net/is-port-in-use.js#L75-L88
train
cdapio/ui-schema-parser
lib/files.js
load
function load(schema) { var obj; if (typeof schema == 'string' && schema !== 'null') { // This last predicate is to allow `avro.parse('null')` to work similarly // to `avro.parse('int')` and other primitives (null needs to be handled // separately since it is also a valid JSON identifier). try { obj = JSON.parse(schema); } catch (err) { if (~schema.indexOf('/')) { // This can't be a valid name, so we interpret is as a filepath. This // makes is always feasible to read a file, independent of its name // (i.e. even if its name is valid JSON), by prefixing it with `./`. obj = JSON.parse(fs.readFileSync(schema)); } } } if (obj === undefined) { obj = schema; } return obj; }
javascript
function load(schema) { var obj; if (typeof schema == 'string' && schema !== 'null') { // This last predicate is to allow `avro.parse('null')` to work similarly // to `avro.parse('int')` and other primitives (null needs to be handled // separately since it is also a valid JSON identifier). try { obj = JSON.parse(schema); } catch (err) { if (~schema.indexOf('/')) { // This can't be a valid name, so we interpret is as a filepath. This // makes is always feasible to read a file, independent of its name // (i.e. even if its name is valid JSON), by prefixing it with `./`. obj = JSON.parse(fs.readFileSync(schema)); } } } if (obj === undefined) { obj = schema; } return obj; }
[ "function", "load", "(", "schema", ")", "{", "var", "obj", ";", "if", "(", "typeof", "schema", "==", "'string'", "&&", "schema", "!==", "'null'", ")", "{", "try", "{", "obj", "=", "JSON", ".", "parse", "(", "schema", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "~", "schema", ".", "indexOf", "(", "'/'", ")", ")", "{", "obj", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "schema", ")", ")", ";", "}", "}", "}", "if", "(", "obj", "===", "undefined", ")", "{", "obj", "=", "schema", ";", "}", "return", "obj", ";", "}" ]
Try to load a schema. This method will attempt to load schemas from a file if the schema passed is a string which isn't valid JSON and contains at least one slash.
[ "Try", "to", "load", "a", "schema", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/files.js#L23-L44
train
cdapio/ui-schema-parser
lib/files.js
createImportHook
function createImportHook() { var imports = {}; return function (fpath, kind, cb) { if (imports[fpath]) { // Already imported, return nothing to avoid duplicating attributes. process.nextTick(cb); return; } imports[fpath] = true; fs.readFile(fpath, {encoding: 'utf8'}, cb); }; }
javascript
function createImportHook() { var imports = {}; return function (fpath, kind, cb) { if (imports[fpath]) { // Already imported, return nothing to avoid duplicating attributes. process.nextTick(cb); return; } imports[fpath] = true; fs.readFile(fpath, {encoding: 'utf8'}, cb); }; }
[ "function", "createImportHook", "(", ")", "{", "var", "imports", "=", "{", "}", ";", "return", "function", "(", "fpath", ",", "kind", ",", "cb", ")", "{", "if", "(", "imports", "[", "fpath", "]", ")", "{", "process", ".", "nextTick", "(", "cb", ")", ";", "return", ";", "}", "imports", "[", "fpath", "]", "=", "true", ";", "fs", ".", "readFile", "(", "fpath", ",", "{", "encoding", ":", "'utf8'", "}", ",", "cb", ")", ";", "}", ";", "}" ]
Default file loading function for assembling IDLs.
[ "Default", "file", "loading", "function", "for", "assembling", "IDLs", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/files.js#L50-L61
train
bitnami/nami-utils
lib/os/pid-find.js
pidFind
function pidFind(pid) { if (!_.isFinite(pid)) return false; try { if (runningAsRoot()) { return process.kill(pid, 0); } else { return !!ps(pid); } } catch (e) { return false; } }
javascript
function pidFind(pid) { if (!_.isFinite(pid)) return false; try { if (runningAsRoot()) { return process.kill(pid, 0); } else { return !!ps(pid); } } catch (e) { return false; } }
[ "function", "pidFind", "(", "pid", ")", "{", "if", "(", "!", "_", ".", "isFinite", "(", "pid", ")", ")", "return", "false", ";", "try", "{", "if", "(", "runningAsRoot", "(", ")", ")", "{", "return", "process", ".", "kill", "(", "pid", ",", "0", ")", ";", "}", "else", "{", "return", "!", "!", "ps", "(", "pid", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Check if the given PID exists @function $os~pidFind @param {number} pid - Process ID @returns {boolean} @example // Check if the PID 123213 exists $os.pidFind(123213); // => true
[ "Check", "if", "the", "given", "PID", "exists" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/pid-find.js#L17-L28
train
bitnami/nami-utils
lib/os/user-management/get-gid.js
getGid
function getGid(groupname, options) { const gid = _.tryOnce(findGroup(groupname, options), 'id'); return _.isUndefined(gid) ? null : gid; }
javascript
function getGid(groupname, options) { const gid = _.tryOnce(findGroup(groupname, options), 'id'); return _.isUndefined(gid) ? null : gid; }
[ "function", "getGid", "(", "groupname", ",", "options", ")", "{", "const", "gid", "=", "_", ".", "tryOnce", "(", "findGroup", "(", "groupname", ",", "options", ")", ",", "'id'", ")", ";", "return", "_", ".", "isUndefined", "(", "gid", ")", "?", "null", ":", "gid", ";", "}" ]
Get group GID @function $os~getGid @param {string} groupname @param {Object} [options] @param {boolean} [options.refresh=true] - Setting this to false allows operating over a cached database of groups, for improved performance. It may result in incorrect results if the affected group changes @param {boolean} [options.throwIfNotFound=true] - By default, this function throws an error if the specified group cannot be found @returns {number|null} - The group ID or null, if it cannot be found @example // Get GID of 'mysql' group $os.getGid('mysql'); // => 1001
[ "Get", "group", "GID" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/get-gid.js#L21-L24
train
bitnami/nami-utils
lib/file/get-attrs.js
getAttrs
function getAttrs(file) { const sstat = fs.lstatSync(file); return { mode: _getUnixPermFromMode(sstat.mode), type: fileType(file), atime: sstat.atime, ctime: sstat.ctime, mtime: sstat.mtime }; }
javascript
function getAttrs(file) { const sstat = fs.lstatSync(file); return { mode: _getUnixPermFromMode(sstat.mode), type: fileType(file), atime: sstat.atime, ctime: sstat.ctime, mtime: sstat.mtime }; }
[ "function", "getAttrs", "(", "file", ")", "{", "const", "sstat", "=", "fs", ".", "lstatSync", "(", "file", ")", ";", "return", "{", "mode", ":", "_getUnixPermFromMode", "(", "sstat", ".", "mode", ")", ",", "type", ":", "fileType", "(", "file", ")", ",", "atime", ":", "sstat", ".", "atime", ",", "ctime", ":", "sstat", ".", "ctime", ",", "mtime", ":", "sstat", ".", "mtime", "}", ";", "}" ]
Get file attributes @function $file~getAttrs @param {string} file @returns {object} - Object containing the file attributes: mode, atime, ctime, mtime, type @example // Get file attributes of 'conf/my.cnf' $file.getAttrs('conf/my.cnf'); // => { mode: '0660', atime: Thu Jan 21 2016 13:09:58 GMT+0100 (CET), ctime: Thu Jan 21 2016 13:09:58 GMT+0100 (CET), mtime: Thu Jan 21 2016 13:09:58 GMT+0100 (CET), type: 'file' }
[ "Get", "file", "attributes" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/get-attrs.js#L27-L33
train
LaunchPadLab/lp-requests
src/http/middleware/set-auth-headers.js
addAuthHeaders
function addAuthHeaders ({ auth, bearerToken, headers, overrideHeaders=false, }) { if (overrideHeaders) return if (bearerToken) return { headers: { ...headers, Authorization: `Bearer ${ bearerToken }` } } if (auth) { const username = auth.username || '' const password = auth.password || '' const encodedToken = Base64.btoa(`${ username }:${ password }`) return { headers: { ...headers, Authorization: `Basic ${ encodedToken }` } } } }
javascript
function addAuthHeaders ({ auth, bearerToken, headers, overrideHeaders=false, }) { if (overrideHeaders) return if (bearerToken) return { headers: { ...headers, Authorization: `Bearer ${ bearerToken }` } } if (auth) { const username = auth.username || '' const password = auth.password || '' const encodedToken = Base64.btoa(`${ username }:${ password }`) return { headers: { ...headers, Authorization: `Basic ${ encodedToken }` } } } }
[ "function", "addAuthHeaders", "(", "{", "auth", ",", "bearerToken", ",", "headers", ",", "overrideHeaders", "=", "false", ",", "}", ")", "{", "if", "(", "overrideHeaders", ")", "return", "if", "(", "bearerToken", ")", "return", "{", "headers", ":", "{", "...", "headers", ",", "Authorization", ":", "`", "${", "bearerToken", "}", "`", "}", "}", "if", "(", "auth", ")", "{", "const", "username", "=", "auth", ".", "username", "||", "''", "const", "password", "=", "auth", ".", "password", "||", "''", "const", "encodedToken", "=", "Base64", ".", "btoa", "(", "`", "${", "username", "}", "${", "password", "}", "`", ")", "return", "{", "headers", ":", "{", "...", "headers", ",", "Authorization", ":", "`", "${", "encodedToken", "}", "`", "}", "}", "}", "}" ]
Sets auth headers if necessary
[ "Sets", "auth", "headers", "if", "necessary" ]
139294b1594b2d62ba8403c9ac6e97d5e84961f3
https://github.com/LaunchPadLab/lp-requests/blob/139294b1594b2d62ba8403c9ac6e97d5e84961f3/src/http/middleware/set-auth-headers.js#L5-L23
train
bitnami/nami-utils
lib/os/user-management/get-uid.js
getUid
function getUid(username, options) { const uid = _.tryOnce(findUser(username, options), 'id'); return _.isUndefined(uid) ? null : uid; }
javascript
function getUid(username, options) { const uid = _.tryOnce(findUser(username, options), 'id'); return _.isUndefined(uid) ? null : uid; }
[ "function", "getUid", "(", "username", ",", "options", ")", "{", "const", "uid", "=", "_", ".", "tryOnce", "(", "findUser", "(", "username", ",", "options", ")", ",", "'id'", ")", ";", "return", "_", ".", "isUndefined", "(", "uid", ")", "?", "null", ":", "uid", ";", "}" ]
Get user UID @function $os~getUid @param {string} username @param {Object} [options] @param {boolean} [options.refresh=true] - Setting this to false allows operating over a cached database of users, for improved performance. It may result in incorrect results if the affected user changes @param {boolean} [options.throwIfNotFound=true] - By default, this function throws an error if the specified user cannot be found @returns {number|null} - The user ID or null, if it cannot be found @example // Get UID of user 'mysql' $os.getUid('mysql'); // => 1001
[ "Get", "user", "UID" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/get-uid.js#L21-L24
train
LaunchPadLab/lp-requests
src/http/middleware/include-csrf-token.js
includeCSRFToken
function includeCSRFToken ({ method, csrf=true, headers }) { if (!csrf || !CSRF_METHODS.includes(method)) return const token = getTokenFromDocument(csrf) if (!token) return return { headers: { ...headers, 'X-CSRF-Token': token } } }
javascript
function includeCSRFToken ({ method, csrf=true, headers }) { if (!csrf || !CSRF_METHODS.includes(method)) return const token = getTokenFromDocument(csrf) if (!token) return return { headers: { ...headers, 'X-CSRF-Token': token } } }
[ "function", "includeCSRFToken", "(", "{", "method", ",", "csrf", "=", "true", ",", "headers", "}", ")", "{", "if", "(", "!", "csrf", "||", "!", "CSRF_METHODS", ".", "includes", "(", "method", ")", ")", "return", "const", "token", "=", "getTokenFromDocument", "(", "csrf", ")", "if", "(", "!", "token", ")", "return", "return", "{", "headers", ":", "{", "...", "headers", ",", "'X-CSRF-Token'", ":", "token", "}", "}", "}" ]
Adds a CSRF token in a header if a 'csrf' option is provided
[ "Adds", "a", "CSRF", "token", "in", "a", "header", "if", "a", "csrf", "option", "is", "provided" ]
139294b1594b2d62ba8403c9ac6e97d5e84961f3
https://github.com/LaunchPadLab/lp-requests/blob/139294b1594b2d62ba8403c9ac6e97d5e84961f3/src/http/middleware/include-csrf-token.js#L19-L26
train
matrix-org/matrix-mock-request
src/index.js
HttpBackend
function HttpBackend() { this.requests = []; this.expectedRequests = []; const self = this; // All the promises our flush requests have returned. When all these promises are // resolved or rejected, there are no more flushes in progress. // For simplicity we never remove promises from this loop: this is a mock utility // for short duration tests, so this keeps it simpler. this._flushPromises = []; // the request function dependency that the SDK needs. this.requestFn = function(opts, callback) { const req = new Request(opts, callback); console.log(`${Date.now()} HTTP backend received request: ${req}`); self.requests.push(req); const abort = function() { const idx = self.requests.indexOf(req); if (idx >= 0) { console.log("Aborting HTTP request: %s %s", opts.method, opts.uri); self.requests.splice(idx, 1); req.callback("aborted"); } }; return { abort: abort, }; }; // very simplistic mapping from the whatwg fetch interface onto the request // interface, so we can use the same mock backend for both. this.fetchFn = function(input, init) { init = init || {}; const requestOpts = { uri: input, method: init.method || 'GET', body: init.body, }; return new Promise((resolve, reject) => { function callback(err, response, body) { if (err) { reject(err); } resolve({ ok: response.statusCode >= 200 && response.statusCode < 300, json: () => JSON.parse(body), }); }; const req = new Request(requestOpts, callback); console.log(`HTTP backend received request: ${req}`); self.requests.push(req); }); }; }
javascript
function HttpBackend() { this.requests = []; this.expectedRequests = []; const self = this; // All the promises our flush requests have returned. When all these promises are // resolved or rejected, there are no more flushes in progress. // For simplicity we never remove promises from this loop: this is a mock utility // for short duration tests, so this keeps it simpler. this._flushPromises = []; // the request function dependency that the SDK needs. this.requestFn = function(opts, callback) { const req = new Request(opts, callback); console.log(`${Date.now()} HTTP backend received request: ${req}`); self.requests.push(req); const abort = function() { const idx = self.requests.indexOf(req); if (idx >= 0) { console.log("Aborting HTTP request: %s %s", opts.method, opts.uri); self.requests.splice(idx, 1); req.callback("aborted"); } }; return { abort: abort, }; }; // very simplistic mapping from the whatwg fetch interface onto the request // interface, so we can use the same mock backend for both. this.fetchFn = function(input, init) { init = init || {}; const requestOpts = { uri: input, method: init.method || 'GET', body: init.body, }; return new Promise((resolve, reject) => { function callback(err, response, body) { if (err) { reject(err); } resolve({ ok: response.statusCode >= 200 && response.statusCode < 300, json: () => JSON.parse(body), }); }; const req = new Request(requestOpts, callback); console.log(`HTTP backend received request: ${req}`); self.requests.push(req); }); }; }
[ "function", "HttpBackend", "(", ")", "{", "this", ".", "requests", "=", "[", "]", ";", "this", ".", "expectedRequests", "=", "[", "]", ";", "const", "self", "=", "this", ";", "this", ".", "_flushPromises", "=", "[", "]", ";", "this", ".", "requestFn", "=", "function", "(", "opts", ",", "callback", ")", "{", "const", "req", "=", "new", "Request", "(", "opts", ",", "callback", ")", ";", "console", ".", "log", "(", "`", "${", "Date", ".", "now", "(", ")", "}", "${", "req", "}", "`", ")", ";", "self", ".", "requests", ".", "push", "(", "req", ")", ";", "const", "abort", "=", "function", "(", ")", "{", "const", "idx", "=", "self", ".", "requests", ".", "indexOf", "(", "req", ")", ";", "if", "(", "idx", ">=", "0", ")", "{", "console", ".", "log", "(", "\"Aborting HTTP request: %s %s\"", ",", "opts", ".", "method", ",", "opts", ".", "uri", ")", ";", "self", ".", "requests", ".", "splice", "(", "idx", ",", "1", ")", ";", "req", ".", "callback", "(", "\"aborted\"", ")", ";", "}", "}", ";", "return", "{", "abort", ":", "abort", ",", "}", ";", "}", ";", "this", ".", "fetchFn", "=", "function", "(", "input", ",", "init", ")", "{", "init", "=", "init", "||", "{", "}", ";", "const", "requestOpts", "=", "{", "uri", ":", "input", ",", "method", ":", "init", ".", "method", "||", "'GET'", ",", "body", ":", "init", ".", "body", ",", "}", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "function", "callback", "(", "err", ",", "response", ",", "body", ")", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "resolve", "(", "{", "ok", ":", "response", ".", "statusCode", ">=", "200", "&&", "response", ".", "statusCode", "<", "300", ",", "json", ":", "(", ")", "=>", "JSON", ".", "parse", "(", "body", ")", ",", "}", ")", ";", "}", ";", "const", "req", "=", "new", "Request", "(", "requestOpts", ",", "callback", ")", ";", "console", ".", "log", "(", "`", "${", "req", "}", "`", ")", ";", "self", ".", "requests", ".", "push", "(", "req", ")", ";", "}", ")", ";", "}", ";", "}" ]
Construct a mock HTTP backend, heavily inspired by Angular.js. @constructor
[ "Construct", "a", "mock", "HTTP", "backend", "heavily", "inspired", "by", "Angular", ".", "js", "." ]
004e1edb1250754775eafffa36e1a2eb749b94b6
https://github.com/matrix-org/matrix-mock-request/blob/004e1edb1250754775eafffa36e1a2eb749b94b6/src/index.js#L26-L84
train
matrix-org/matrix-mock-request
src/index.js
function(opts) { opts = opts || {}; if (this.expectedRequests.length === 0) { // calling flushAllExpected when there are no expectations is a // silly thing to do, and probably means that your test isn't // doing what you think it is doing (or it is racy). Hence we // reject this, rather than resolving immediately. return Promise.reject(new Error( `flushAllExpected called with an empty expectation list`, )); } const waitTime = opts.timeout === undefined ? 1000 : opts.timeout; const endTime = waitTime + Date.now(); let flushed = 0; const iterate = () => { const timeRemaining = endTime - Date.now(); if (timeRemaining <= 0) { throw new Error( `Timed out after flushing ${flushed} requests; `+ `${this.expectedRequests.length} remaining`, ); } return this.flush( undefined, undefined, timeRemaining, ).then((f) => { flushed += f; if (this.expectedRequests.length === 0) { // we're done return null; } return iterate(); }); }; const prom = new Promise((resolve, reject) => { iterate().then(() => { resolve(flushed); }, (e) => { reject(e); }); }); this._flushPromises.push(prom); return prom; }
javascript
function(opts) { opts = opts || {}; if (this.expectedRequests.length === 0) { // calling flushAllExpected when there are no expectations is a // silly thing to do, and probably means that your test isn't // doing what you think it is doing (or it is racy). Hence we // reject this, rather than resolving immediately. return Promise.reject(new Error( `flushAllExpected called with an empty expectation list`, )); } const waitTime = opts.timeout === undefined ? 1000 : opts.timeout; const endTime = waitTime + Date.now(); let flushed = 0; const iterate = () => { const timeRemaining = endTime - Date.now(); if (timeRemaining <= 0) { throw new Error( `Timed out after flushing ${flushed} requests; `+ `${this.expectedRequests.length} remaining`, ); } return this.flush( undefined, undefined, timeRemaining, ).then((f) => { flushed += f; if (this.expectedRequests.length === 0) { // we're done return null; } return iterate(); }); }; const prom = new Promise((resolve, reject) => { iterate().then(() => { resolve(flushed); }, (e) => { reject(e); }); }); this._flushPromises.push(prom); return prom; }
[ "function", "(", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "this", ".", "expectedRequests", ".", "length", "===", "0", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "`", "`", ",", ")", ")", ";", "}", "const", "waitTime", "=", "opts", ".", "timeout", "===", "undefined", "?", "1000", ":", "opts", ".", "timeout", ";", "const", "endTime", "=", "waitTime", "+", "Date", ".", "now", "(", ")", ";", "let", "flushed", "=", "0", ";", "const", "iterate", "=", "(", ")", "=>", "{", "const", "timeRemaining", "=", "endTime", "-", "Date", ".", "now", "(", ")", ";", "if", "(", "timeRemaining", "<=", "0", ")", "{", "throw", "new", "Error", "(", "`", "${", "flushed", "}", "`", "+", "`", "${", "this", ".", "expectedRequests", ".", "length", "}", "`", ",", ")", ";", "}", "return", "this", ".", "flush", "(", "undefined", ",", "undefined", ",", "timeRemaining", ",", ")", ".", "then", "(", "(", "f", ")", "=>", "{", "flushed", "+=", "f", ";", "if", "(", "this", ".", "expectedRequests", ".", "length", "===", "0", ")", "{", "return", "null", ";", "}", "return", "iterate", "(", ")", ";", "}", ")", ";", "}", ";", "const", "prom", "=", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "iterate", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "resolve", "(", "flushed", ")", ";", "}", ",", "(", "e", ")", "=>", "{", "reject", "(", "e", ")", ";", "}", ")", ";", "}", ")", ";", "this", ".", "_flushPromises", ".", "push", "(", "prom", ")", ";", "return", "prom", ";", "}" ]
Repeatedly flush requests until the list of expectations is empty. There is a total timeout (of 1000ms by default), after which the returned promise is rejected. @param {Object=} opts Options object @param {Number=} opts.timeout Total timeout, in ms. 1000 by default. @return {Promise} resolves when there is nothing left to flush, with the number of requests flushed
[ "Repeatedly", "flush", "requests", "until", "the", "list", "of", "expectations", "is", "empty", "." ]
004e1edb1250754775eafffa36e1a2eb749b94b6
https://github.com/matrix-org/matrix-mock-request/blob/004e1edb1250754775eafffa36e1a2eb749b94b6/src/index.js#L172-L221
train
matrix-org/matrix-mock-request
src/index.js
function(method, path, data) { const pendingReq = new ExpectedRequest(method, path, data); this.expectedRequests.push(pendingReq); return pendingReq; }
javascript
function(method, path, data) { const pendingReq = new ExpectedRequest(method, path, data); this.expectedRequests.push(pendingReq); return pendingReq; }
[ "function", "(", "method", ",", "path", ",", "data", ")", "{", "const", "pendingReq", "=", "new", "ExpectedRequest", "(", "method", ",", "path", ",", "data", ")", ";", "this", ".", "expectedRequests", ".", "push", "(", "pendingReq", ")", ";", "return", "pendingReq", ";", "}" ]
Create an expected request. @param {string} method The HTTP method @param {string} path The path (which can be partial) @param {Object} data The expected data. @return {Request} An expected request.
[ "Create", "an", "expected", "request", "." ]
004e1edb1250754775eafffa36e1a2eb749b94b6
https://github.com/matrix-org/matrix-mock-request/blob/004e1edb1250754775eafffa36e1a2eb749b94b6/src/index.js#L313-L317
train
matrix-org/matrix-mock-request
src/index.js
ExpectedRequest
function ExpectedRequest(method, path, data) { this.method = method; this.path = path; this.data = data; this.response = null; this.checks = []; }
javascript
function ExpectedRequest(method, path, data) { this.method = method; this.path = path; this.data = data; this.response = null; this.checks = []; }
[ "function", "ExpectedRequest", "(", "method", ",", "path", ",", "data", ")", "{", "this", ".", "method", "=", "method", ";", "this", ".", "path", "=", "path", ";", "this", ".", "data", "=", "data", ";", "this", ".", "response", "=", "null", ";", "this", ".", "checks", "=", "[", "]", ";", "}" ]
Represents the expectation of a request. <p>Includes the conditions to be matched against, the checks to be made, and the response to be returned. @constructor @param {string} method @param {string} path @param {object?} data
[ "Represents", "the", "expectation", "of", "a", "request", "." ]
004e1edb1250754775eafffa36e1a2eb749b94b6
https://github.com/matrix-org/matrix-mock-request/blob/004e1edb1250754775eafffa36e1a2eb749b94b6/src/index.js#L338-L344
train
matrix-org/matrix-mock-request
src/index.js
function(code, data, rawBody) { this.response = { response: { statusCode: code, headers: { 'content-type': 'application/json', }, }, body: data || "", err: null, rawBody: rawBody || false, }; }
javascript
function(code, data, rawBody) { this.response = { response: { statusCode: code, headers: { 'content-type': 'application/json', }, }, body: data || "", err: null, rawBody: rawBody || false, }; }
[ "function", "(", "code", ",", "data", ",", "rawBody", ")", "{", "this", ".", "response", "=", "{", "response", ":", "{", "statusCode", ":", "code", ",", "headers", ":", "{", "'content-type'", ":", "'application/json'", ",", "}", ",", "}", ",", "body", ":", "data", "||", "\"\"", ",", "err", ":", "null", ",", "rawBody", ":", "rawBody", "||", "false", ",", "}", ";", "}" ]
Respond with the given data when this request is satisfied. @param {Number} code The HTTP status code. @param {Object|Function?} data The response body object. If this is a function, it will be invoked when the response body is required (which should be returned). @param {Boolean} rawBody true if the response should be returned directly rather than json-stringifying it first.
[ "Respond", "with", "the", "given", "data", "when", "this", "request", "is", "satisfied", "." ]
004e1edb1250754775eafffa36e1a2eb749b94b6
https://github.com/matrix-org/matrix-mock-request/blob/004e1edb1250754775eafffa36e1a2eb749b94b6/src/index.js#L369-L381
train
matrix-org/matrix-mock-request
src/index.js
function(code, err) { this.response = { response: { statusCode: code, headers: {}, }, body: null, err: err, }; }
javascript
function(code, err) { this.response = { response: { statusCode: code, headers: {}, }, body: null, err: err, }; }
[ "function", "(", "code", ",", "err", ")", "{", "this", ".", "response", "=", "{", "response", ":", "{", "statusCode", ":", "code", ",", "headers", ":", "{", "}", ",", "}", ",", "body", ":", "null", ",", "err", ":", "err", ",", "}", ";", "}" ]
Fail with an Error when this request is satisfied. @param {Number} code The HTTP status code. @param {Error} err The error to throw (e.g. Network Error)
[ "Fail", "with", "an", "Error", "when", "this", "request", "is", "satisfied", "." ]
004e1edb1250754775eafffa36e1a2eb749b94b6
https://github.com/matrix-org/matrix-mock-request/blob/004e1edb1250754775eafffa36e1a2eb749b94b6/src/index.js#L388-L397
train
matrix-org/matrix-mock-request
src/index.js
Request
function Request(opts, callback) { this.opts = opts; this.callback = callback; Object.defineProperty(this, 'method', { get: function() { return opts.method; }, }); Object.defineProperty(this, 'path', { get: function() { return opts.uri; }, }); /** * Parse the body of the request as a JSON object and return it. */ Object.defineProperty(this, 'data', { get: function() { return opts.body ? JSON.parse(opts.body) : opts.body; }, }); /** * Return the raw body passed to request */ Object.defineProperty(this, 'rawData', { get: function() { return opts.body; }, }); Object.defineProperty(this, 'queryParams', { get: function() { return opts.qs; }, }); Object.defineProperty(this, 'headers', { get: function() { return opts.headers || {}; }, }); }
javascript
function Request(opts, callback) { this.opts = opts; this.callback = callback; Object.defineProperty(this, 'method', { get: function() { return opts.method; }, }); Object.defineProperty(this, 'path', { get: function() { return opts.uri; }, }); /** * Parse the body of the request as a JSON object and return it. */ Object.defineProperty(this, 'data', { get: function() { return opts.body ? JSON.parse(opts.body) : opts.body; }, }); /** * Return the raw body passed to request */ Object.defineProperty(this, 'rawData', { get: function() { return opts.body; }, }); Object.defineProperty(this, 'queryParams', { get: function() { return opts.qs; }, }); Object.defineProperty(this, 'headers', { get: function() { return opts.headers || {}; }, }); }
[ "function", "Request", "(", "opts", ",", "callback", ")", "{", "this", ".", "opts", "=", "opts", ";", "this", ".", "callback", "=", "callback", ";", "Object", ".", "defineProperty", "(", "this", ",", "'method'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "opts", ".", "method", ";", "}", ",", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'path'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "opts", ".", "uri", ";", "}", ",", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'data'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "opts", ".", "body", "?", "JSON", ".", "parse", "(", "opts", ".", "body", ")", ":", "opts", ".", "body", ";", "}", ",", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'rawData'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "opts", ".", "body", ";", "}", ",", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'queryParams'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "opts", ".", "qs", ";", "}", ",", "}", ")", ";", "Object", ".", "defineProperty", "(", "this", ",", "'headers'", ",", "{", "get", ":", "function", "(", ")", "{", "return", "opts", ".", "headers", "||", "{", "}", ";", "}", ",", "}", ")", ";", "}" ]
Represents a request made by the app. @constructor @param {object} opts opts passed to request() @param {function} callback
[ "Represents", "a", "request", "made", "by", "the", "app", "." ]
004e1edb1250754775eafffa36e1a2eb749b94b6
https://github.com/matrix-org/matrix-mock-request/blob/004e1edb1250754775eafffa36e1a2eb749b94b6/src/index.js#L407-L452
train
bitnami/nami-utils
lib/os/user-management/find-user.js
findUser
function findUser(user, options) { options = _.opts(options, {refresh: true, throwIfNotFound: true}); if (_.isString(user) && user.match(/^[0-9]+$/)) { user = parseInt(user, 10); } return _findUser(user, options); }
javascript
function findUser(user, options) { options = _.opts(options, {refresh: true, throwIfNotFound: true}); if (_.isString(user) && user.match(/^[0-9]+$/)) { user = parseInt(user, 10); } return _findUser(user, options); }
[ "function", "findUser", "(", "user", ",", "options", ")", "{", "options", "=", "_", ".", "opts", "(", "options", ",", "{", "refresh", ":", "true", ",", "throwIfNotFound", ":", "true", "}", ")", ";", "if", "(", "_", ".", "isString", "(", "user", ")", "&&", "user", ".", "match", "(", "/", "^[0-9]+$", "/", ")", ")", "{", "user", "=", "parseInt", "(", "user", ",", "10", ")", ";", "}", "return", "_findUser", "(", "user", ",", "options", ")", ";", "}" ]
Lookup system user information @function $os~findUser @param {string|number} user - Username or user id to look for @param {Object} [options] @param {boolean} [options.refresh=true] - Setting this to false allows operating over a cached database of users, for improved performance. It may result in incorrect results if the affected user changes @param {boolean} [options.throwIfNotFound=true] - By default, this function throws an error if the specified user cannot be found @returns {object|null} - Object containing the user id and name: ( { id: 0, name: root } ) or null if not found and throwIfNotFound is set to false @example // Get user information of 'mysql' $os.findUser('mysql'); // => { name: 'mysql', id: 1001 }
[ "Lookup", "system", "user", "information" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/find-user.js#L32-L38
train
timbeadle/grunt-tv4
lib/runner.js
forAsync
function forAsync(items, iter, callback) { var keys = Object.keys(items); var step = function (err, callback) { nextTick(function () { if (err) { return callback(err); } if (keys.length === 0) { return callback(); } var key = keys.pop(); iter(items[key], key, function (err) { step(err, callback); }); }); }; step(null, callback); }
javascript
function forAsync(items, iter, callback) { var keys = Object.keys(items); var step = function (err, callback) { nextTick(function () { if (err) { return callback(err); } if (keys.length === 0) { return callback(); } var key = keys.pop(); iter(items[key], key, function (err) { step(err, callback); }); }); }; step(null, callback); }
[ "function", "forAsync", "(", "items", ",", "iter", ",", "callback", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "items", ")", ";", "var", "step", "=", "function", "(", "err", ",", "callback", ")", "{", "nextTick", "(", "function", "(", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "keys", ".", "length", "===", "0", ")", "{", "return", "callback", "(", ")", ";", "}", "var", "key", "=", "keys", ".", "pop", "(", ")", ";", "iter", "(", "items", "[", "key", "]", ",", "key", ",", "function", "(", "err", ")", "{", "step", "(", "err", ",", "callback", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "step", "(", "null", ",", "callback", ")", ";", "}" ]
for-each async style
[ "for", "-", "each", "async", "style" ]
146cf5bb829a2b36939cc9fd373750aae3eb00d8
https://github.com/timbeadle/grunt-tv4/blob/146cf5bb829a2b36939cc9fd373750aae3eb00d8/lib/runner.js#L21-L38
train
timbeadle/grunt-tv4
lib/runner.js
getOptions
function getOptions(merge) { var options = { root: null, schemas: {}, add: [], formats: {}, fresh: false, multi: false, timeout: 5000, checkRecursive: false, banUnknownProperties: false, languages: {}, language: null }; return copyProps(options, merge); }
javascript
function getOptions(merge) { var options = { root: null, schemas: {}, add: [], formats: {}, fresh: false, multi: false, timeout: 5000, checkRecursive: false, banUnknownProperties: false, languages: {}, language: null }; return copyProps(options, merge); }
[ "function", "getOptions", "(", "merge", ")", "{", "var", "options", "=", "{", "root", ":", "null", ",", "schemas", ":", "{", "}", ",", "add", ":", "[", "]", ",", "formats", ":", "{", "}", ",", "fresh", ":", "false", ",", "multi", ":", "false", ",", "timeout", ":", "5000", ",", "checkRecursive", ":", "false", ",", "banUnknownProperties", ":", "false", ",", "languages", ":", "{", "}", ",", "language", ":", "null", "}", ";", "return", "copyProps", "(", "options", ",", "merge", ")", ";", "}" ]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-" ]
146cf5bb829a2b36939cc9fd373750aae3eb00d8
https://github.com/timbeadle/grunt-tv4/blob/146cf5bb829a2b36939cc9fd373750aae3eb00d8/lib/runner.js#L85-L100
train
timbeadle/grunt-tv4
lib/runner.js
loadSchemaList
function loadSchemaList(job, uris, callback) { uris = uris.filter(function (value) { return !!value; }); if (uris.length === 0) { nextTick(function () { callback(); }); return; } var sweep = function () { if (uris.length === 0) { nextTick(callback); return; } forAsync(uris, function (uri, i, callback) { if (!uri) { out.writeln('> ' + style.error('cannot load') + ' "' + tweakURI(uri) + '"'); callback(); } out.writeln('> ' + style.accent('load') + ' + ' + tweakURI(uri)); loader.load(uri, job.context.options, function (err, schema) { if (err) { return callback(err); } job.context.tv4.addSchema(uri, schema); uris = job.context.tv4.getMissingUris(); callback(); }); }, function (err) { if (err) { job.error = err; return callback(null); } // sweep again sweep(); }); }; sweep(); }
javascript
function loadSchemaList(job, uris, callback) { uris = uris.filter(function (value) { return !!value; }); if (uris.length === 0) { nextTick(function () { callback(); }); return; } var sweep = function () { if (uris.length === 0) { nextTick(callback); return; } forAsync(uris, function (uri, i, callback) { if (!uri) { out.writeln('> ' + style.error('cannot load') + ' "' + tweakURI(uri) + '"'); callback(); } out.writeln('> ' + style.accent('load') + ' + ' + tweakURI(uri)); loader.load(uri, job.context.options, function (err, schema) { if (err) { return callback(err); } job.context.tv4.addSchema(uri, schema); uris = job.context.tv4.getMissingUris(); callback(); }); }, function (err) { if (err) { job.error = err; return callback(null); } // sweep again sweep(); }); }; sweep(); }
[ "function", "loadSchemaList", "(", "job", ",", "uris", ",", "callback", ")", "{", "uris", "=", "uris", ".", "filter", "(", "function", "(", "value", ")", "{", "return", "!", "!", "value", ";", "}", ")", ";", "if", "(", "uris", ".", "length", "===", "0", ")", "{", "nextTick", "(", "function", "(", ")", "{", "callback", "(", ")", ";", "}", ")", ";", "return", ";", "}", "var", "sweep", "=", "function", "(", ")", "{", "if", "(", "uris", ".", "length", "===", "0", ")", "{", "nextTick", "(", "callback", ")", ";", "return", ";", "}", "forAsync", "(", "uris", ",", "function", "(", "uri", ",", "i", ",", "callback", ")", "{", "if", "(", "!", "uri", ")", "{", "out", ".", "writeln", "(", "'> '", "+", "style", ".", "error", "(", "'cannot load'", ")", "+", "' \"'", "+", "tweakURI", "(", "uri", ")", "+", "'\"'", ")", ";", "callback", "(", ")", ";", "}", "out", ".", "writeln", "(", "'> '", "+", "style", ".", "accent", "(", "'load'", ")", "+", "' + '", "+", "tweakURI", "(", "uri", ")", ")", ";", "loader", ".", "load", "(", "uri", ",", "job", ".", "context", ".", "options", ",", "function", "(", "err", ",", "schema", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "job", ".", "context", ".", "tv4", ".", "addSchema", "(", "uri", ",", "schema", ")", ";", "uris", "=", "job", ".", "context", ".", "tv4", ".", "getMissingUris", "(", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "job", ".", "error", "=", "err", ";", "return", "callback", "(", "null", ")", ";", "}", "sweep", "(", ")", ";", "}", ")", ";", "}", ";", "sweep", "(", ")", ";", "}" ]
load and add batch of schema by uri, repeat until all missing are solved
[ "load", "and", "add", "batch", "of", "schema", "by", "uri", "repeat", "until", "all", "missing", "are", "solved" ]
146cf5bb829a2b36939cc9fd373750aae3eb00d8
https://github.com/timbeadle/grunt-tv4/blob/146cf5bb829a2b36939cc9fd373750aae3eb00d8/lib/runner.js#L193-L235
train
timbeadle/grunt-tv4
lib/runner.js
validateObject
function validateObject(job, object, callback) { if (typeof object.value === 'undefined') { var onLoad = function (err, obj) { if (err) { job.error = err; return callback(err); } object.value = obj; doValidateObject(job, object, callback); }; var opts = { timeout: (job.context.options.timeout || 5000) }; //TODO verify http:, file: and plain paths all load properly if (object.path) { loader.loadPath(object.path, opts, onLoad); } else if (object.url) { loader.load(object.url, opts, onLoad); } else { callback(new Error('object missing value, path or url')); } } else { doValidateObject(job, object, callback); } }
javascript
function validateObject(job, object, callback) { if (typeof object.value === 'undefined') { var onLoad = function (err, obj) { if (err) { job.error = err; return callback(err); } object.value = obj; doValidateObject(job, object, callback); }; var opts = { timeout: (job.context.options.timeout || 5000) }; //TODO verify http:, file: and plain paths all load properly if (object.path) { loader.loadPath(object.path, opts, onLoad); } else if (object.url) { loader.load(object.url, opts, onLoad); } else { callback(new Error('object missing value, path or url')); } } else { doValidateObject(job, object, callback); } }
[ "function", "validateObject", "(", "job", ",", "object", ",", "callback", ")", "{", "if", "(", "typeof", "object", ".", "value", "===", "'undefined'", ")", "{", "var", "onLoad", "=", "function", "(", "err", ",", "obj", ")", "{", "if", "(", "err", ")", "{", "job", ".", "error", "=", "err", ";", "return", "callback", "(", "err", ")", ";", "}", "object", ".", "value", "=", "obj", ";", "doValidateObject", "(", "job", ",", "object", ",", "callback", ")", ";", "}", ";", "var", "opts", "=", "{", "timeout", ":", "(", "job", ".", "context", ".", "options", ".", "timeout", "||", "5000", ")", "}", ";", "if", "(", "object", ".", "path", ")", "{", "loader", ".", "loadPath", "(", "object", ".", "path", ",", "opts", ",", "onLoad", ")", ";", "}", "else", "if", "(", "object", ".", "url", ")", "{", "loader", ".", "load", "(", "object", ".", "url", ",", "opts", ",", "onLoad", ")", ";", "}", "else", "{", "callback", "(", "new", "Error", "(", "'object missing value, path or url'", ")", ")", ";", "}", "}", "else", "{", "doValidateObject", "(", "job", ",", "object", ",", "callback", ")", ";", "}", "}" ]
validate single object
[ "validate", "single", "object" ]
146cf5bb829a2b36939cc9fd373750aae3eb00d8
https://github.com/timbeadle/grunt-tv4/blob/146cf5bb829a2b36939cc9fd373750aae3eb00d8/lib/runner.js#L292-L319
train
bitnami/nami-utils
lib/os/user-management/add-group.js
addGroup
function addGroup(group, options) { options = _.opts(options, {gid: null}); if (!runningAsRoot()) return; if (!group) throw new Error('You must provide a group'); if (groupExists(group)) { return; } if (isPlatform('linux')) { _addGroupLinux(group, options); } else if (isPlatform('osx')) { _addGroupOsx(group, options); } else if (isPlatform('windows')) { throw new Error(`Don't know how to add group ${group} on Windows`); } else { throw new Error(`Don't know how to add group ${group} in current platform`); } }
javascript
function addGroup(group, options) { options = _.opts(options, {gid: null}); if (!runningAsRoot()) return; if (!group) throw new Error('You must provide a group'); if (groupExists(group)) { return; } if (isPlatform('linux')) { _addGroupLinux(group, options); } else if (isPlatform('osx')) { _addGroupOsx(group, options); } else if (isPlatform('windows')) { throw new Error(`Don't know how to add group ${group} on Windows`); } else { throw new Error(`Don't know how to add group ${group} in current platform`); } }
[ "function", "addGroup", "(", "group", ",", "options", ")", "{", "options", "=", "_", ".", "opts", "(", "options", ",", "{", "gid", ":", "null", "}", ")", ";", "if", "(", "!", "runningAsRoot", "(", ")", ")", "return", ";", "if", "(", "!", "group", ")", "throw", "new", "Error", "(", "'You must provide a group'", ")", ";", "if", "(", "groupExists", "(", "group", ")", ")", "{", "return", ";", "}", "if", "(", "isPlatform", "(", "'linux'", ")", ")", "{", "_addGroupLinux", "(", "group", ",", "options", ")", ";", "}", "else", "if", "(", "isPlatform", "(", "'osx'", ")", ")", "{", "_addGroupOsx", "(", "group", ",", "options", ")", ";", "}", "else", "if", "(", "isPlatform", "(", "'windows'", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "group", "}", "`", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "`", "${", "group", "}", "`", ")", ";", "}", "}" ]
Add a group to the system @function $os~addGroup @param {string} group - Groupname @param {Object} [options] @param {string|number} [options.gid=null] - Group ID @example // Creates group 'mysql' $os.addGroup('mysql');
[ "Add", "a", "group", "to", "the", "system" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/add-group.js#L45-L62
train
DirektoratetForByggkvalitet/losen
src/shared/utils/validator/index.js
assertProperties
function assertProperties(object, path, properties) { let errors = []; (properties || []).forEach((property) => { if (get(object, property, undefined) === undefined) { errors = [...errors, { path, id: object.id, error: `${object.type} is missing the '${property}' property` }]; } }); return errors; }
javascript
function assertProperties(object, path, properties) { let errors = []; (properties || []).forEach((property) => { if (get(object, property, undefined) === undefined) { errors = [...errors, { path, id: object.id, error: `${object.type} is missing the '${property}' property` }]; } }); return errors; }
[ "function", "assertProperties", "(", "object", ",", "path", ",", "properties", ")", "{", "let", "errors", "=", "[", "]", ";", "(", "properties", "||", "[", "]", ")", ".", "forEach", "(", "(", "property", ")", "=>", "{", "if", "(", "get", "(", "object", ",", "property", ",", "undefined", ")", "===", "undefined", ")", "{", "errors", "=", "[", "...", "errors", ",", "{", "path", ",", "id", ":", "object", ".", "id", ",", "error", ":", "`", "${", "object", ".", "type", "}", "${", "property", "}", "`", "}", "]", ";", "}", "}", ")", ";", "return", "errors", ";", "}" ]
Assert properties exist. Returns array of errors
[ "Assert", "properties", "exist", ".", "Returns", "array", "of", "errors" ]
e13103d5641983bd15e5714afe87017b59e778bb
https://github.com/DirektoratetForByggkvalitet/losen/blob/e13103d5641983bd15e5714afe87017b59e778bb/src/shared/utils/validator/index.js#L54-L64
train
DirektoratetForByggkvalitet/losen
src/shared/utils/validator/index.js
assertDeprecations
function assertDeprecations(object, path, properties) { let errors = []; (properties || []).forEach(({ property, use }) => { if (get(object, property, undefined) !== undefined) { errors = [ ...errors, { path, id: object.id, error: `${object.type} is using the '${property}' property. It's deprecated and will be removed.${use ? ` Use '${use}' instead` : ''}.`, }, ]; } }); return errors; }
javascript
function assertDeprecations(object, path, properties) { let errors = []; (properties || []).forEach(({ property, use }) => { if (get(object, property, undefined) !== undefined) { errors = [ ...errors, { path, id: object.id, error: `${object.type} is using the '${property}' property. It's deprecated and will be removed.${use ? ` Use '${use}' instead` : ''}.`, }, ]; } }); return errors; }
[ "function", "assertDeprecations", "(", "object", ",", "path", ",", "properties", ")", "{", "let", "errors", "=", "[", "]", ";", "(", "properties", "||", "[", "]", ")", ".", "forEach", "(", "(", "{", "property", ",", "use", "}", ")", "=>", "{", "if", "(", "get", "(", "object", ",", "property", ",", "undefined", ")", "!==", "undefined", ")", "{", "errors", "=", "[", "...", "errors", ",", "{", "path", ",", "id", ":", "object", ".", "id", ",", "error", ":", "`", "${", "object", ".", "type", "}", "${", "property", "}", "${", "use", "?", "`", "${", "use", "}", "`", ":", "''", "}", "`", ",", "}", ",", "]", ";", "}", "}", ")", ";", "return", "errors", ";", "}" ]
Check for deprecated properties on the node. Returns array of errors
[ "Check", "for", "deprecated", "properties", "on", "the", "node", ".", "Returns", "array", "of", "errors" ]
e13103d5641983bd15e5714afe87017b59e778bb
https://github.com/DirektoratetForByggkvalitet/losen/blob/e13103d5641983bd15e5714afe87017b59e778bb/src/shared/utils/validator/index.js#L69-L86
train
DirektoratetForByggkvalitet/losen
src/shared/utils/validator/index.js
validatePage
function validatePage(page, path) { let errors = []; // Check for required properties errors = [...errors, ...assertProperties(page, path, requiredProperties[page.type])]; if (page.children) { // Check that children is an array if (!Array.isArray(page.children)) { errors = [...errors, { path, error: 'Children must be an array' }]; return errors; } page.children.forEach((node, index) => { errors = [...errors, ...validateNode(node, [...path, 'children', index], [page])]; }); } return errors; }
javascript
function validatePage(page, path) { let errors = []; // Check for required properties errors = [...errors, ...assertProperties(page, path, requiredProperties[page.type])]; if (page.children) { // Check that children is an array if (!Array.isArray(page.children)) { errors = [...errors, { path, error: 'Children must be an array' }]; return errors; } page.children.forEach((node, index) => { errors = [...errors, ...validateNode(node, [...path, 'children', index], [page])]; }); } return errors; }
[ "function", "validatePage", "(", "page", ",", "path", ")", "{", "let", "errors", "=", "[", "]", ";", "errors", "=", "[", "...", "errors", ",", "...", "assertProperties", "(", "page", ",", "path", ",", "requiredProperties", "[", "page", ".", "type", "]", ")", "]", ";", "if", "(", "page", ".", "children", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "page", ".", "children", ")", ")", "{", "errors", "=", "[", "...", "errors", ",", "{", "path", ",", "error", ":", "'Children must be an array'", "}", "]", ";", "return", "errors", ";", "}", "page", ".", "children", ".", "forEach", "(", "(", "node", ",", "index", ")", "=>", "{", "errors", "=", "[", "...", "errors", ",", "...", "validateNode", "(", "node", ",", "[", "...", "path", ",", "'children'", ",", "index", "]", ",", "[", "page", "]", ")", "]", ";", "}", ")", ";", "}", "return", "errors", ";", "}" ]
Validate a page, checking that the required properties are in place
[ "Validate", "a", "page", "checking", "that", "the", "required", "properties", "are", "in", "place" ]
e13103d5641983bd15e5714afe87017b59e778bb
https://github.com/DirektoratetForByggkvalitet/losen/blob/e13103d5641983bd15e5714afe87017b59e778bb/src/shared/utils/validator/index.js#L199-L219
train
bitnami/nami-utils
lib/file/prepend.js
prepend
function prepend(file, text, options) { options = _.sanitize(options, {encoding: 'utf-8'}); const encoding = options.encoding; if (!exists(file)) { write(file, text, {encoding: encoding}); } else { const currentText = read(file, {encoding: encoding}); write(file, text + currentText, {encoding: encoding}); } }
javascript
function prepend(file, text, options) { options = _.sanitize(options, {encoding: 'utf-8'}); const encoding = options.encoding; if (!exists(file)) { write(file, text, {encoding: encoding}); } else { const currentText = read(file, {encoding: encoding}); write(file, text + currentText, {encoding: encoding}); } }
[ "function", "prepend", "(", "file", ",", "text", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "encoding", ":", "'utf-8'", "}", ")", ";", "const", "encoding", "=", "options", ".", "encoding", ";", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "write", "(", "file", ",", "text", ",", "{", "encoding", ":", "encoding", "}", ")", ";", "}", "else", "{", "const", "currentText", "=", "read", "(", "file", ",", "{", "encoding", ":", "encoding", "}", ")", ";", "write", "(", "file", ",", "text", "+", "currentText", ",", "{", "encoding", ":", "encoding", "}", ")", ";", "}", "}" ]
Add text at the beginning of a file @function $file~prepend @param {string} file - File to add text to @param {string} text - Text to add @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read/write the file @example // Prepend new lines to 'Changelog' file $file.prepend('Changelog', 'Latest Changes:\n * Added new plugins\n');
[ "Add", "text", "at", "the", "beginning", "of", "a", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/prepend.js#L19-L28
train
baby-loris/bla
lib/help-formatters/html.js
getHtml
function getHtml(methods) { return [ '<!doctype html>', '<html lang="en">', '<head>', '<title>API Index</title>', '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>', '<link rel="stylesheet" href="//yastatic.net/bootstrap/3.1.1/css/bootstrap.min.css"/>', '</head>', '<body class="container">', '<div class="col-md-7">', Object.keys(methods).map(function (name) { return getMethodHtml(methods[name]); }).join(''), '</div>', '</body>', '</html>' ].join(''); }
javascript
function getHtml(methods) { return [ '<!doctype html>', '<html lang="en">', '<head>', '<title>API Index</title>', '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>', '<link rel="stylesheet" href="//yastatic.net/bootstrap/3.1.1/css/bootstrap.min.css"/>', '</head>', '<body class="container">', '<div class="col-md-7">', Object.keys(methods).map(function (name) { return getMethodHtml(methods[name]); }).join(''), '</div>', '</body>', '</html>' ].join(''); }
[ "function", "getHtml", "(", "methods", ")", "{", "return", "[", "'<!doctype html>'", ",", "'<html lang=\"en\">'", ",", "'<head>'", ",", "'<title>API Index</title>'", ",", "'<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>'", ",", "'<link rel=\"stylesheet\" href=\"//yastatic.net/bootstrap/3.1.1/css/bootstrap.min.css\"/>'", ",", "'</head>'", ",", "'<body class=\"container\">'", ",", "'<div class=\"col-md-7\">'", ",", "Object", ".", "keys", "(", "methods", ")", ".", "map", "(", "function", "(", "name", ")", "{", "return", "getMethodHtml", "(", "methods", "[", "name", "]", ")", ";", "}", ")", ".", "join", "(", "''", ")", ",", "'</div>'", ",", "'</body>'", ",", "'</html>'", "]", ".", "join", "(", "''", ")", ";", "}" ]
Genereates HTML for documentation page. @param {ApiMethod[]} methods @returns {String}
[ "Genereates", "HTML", "for", "documentation", "page", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/lib/help-formatters/html.js#L20-L38
train
baby-loris/bla
lib/help-formatters/html.js
getMethodHtml
function getMethodHtml(method) { var params = method.getParams(); return [ '<h3>', method.getName(), '</h3>', method.getOption('executeOnServerOnly') && '<span class="label label-primary" style="font-size:0.5em;vertical-align:middle">server only</span>', '<p>', method.getDescription(), '</p>', Object.keys(params).length && [ '<table class="table table-bordered table-condensed">', '<thead>', '<tr>', '<th class="col-md-2">Name</th>', '<th class="col-md-2">Type</th>', '<th>Description</th>', '</tr>', '</thead>', '<tbody>', Object.keys(params).map(function (key) { return getMethodParamHtml(key, params[key]); }).join(''), '</tbody>', '</table>' ].join('') ].filter(Boolean).join(''); }
javascript
function getMethodHtml(method) { var params = method.getParams(); return [ '<h3>', method.getName(), '</h3>', method.getOption('executeOnServerOnly') && '<span class="label label-primary" style="font-size:0.5em;vertical-align:middle">server only</span>', '<p>', method.getDescription(), '</p>', Object.keys(params).length && [ '<table class="table table-bordered table-condensed">', '<thead>', '<tr>', '<th class="col-md-2">Name</th>', '<th class="col-md-2">Type</th>', '<th>Description</th>', '</tr>', '</thead>', '<tbody>', Object.keys(params).map(function (key) { return getMethodParamHtml(key, params[key]); }).join(''), '</tbody>', '</table>' ].join('') ].filter(Boolean).join(''); }
[ "function", "getMethodHtml", "(", "method", ")", "{", "var", "params", "=", "method", ".", "getParams", "(", ")", ";", "return", "[", "'<h3>'", ",", "method", ".", "getName", "(", ")", ",", "'</h3>'", ",", "method", ".", "getOption", "(", "'executeOnServerOnly'", ")", "&&", "'<span class=\"label label-primary\" style=\"font-size:0.5em;vertical-align:middle\">server only</span>'", ",", "'<p>'", ",", "method", ".", "getDescription", "(", ")", ",", "'</p>'", ",", "Object", ".", "keys", "(", "params", ")", ".", "length", "&&", "[", "'<table class=\"table table-bordered table-condensed\">'", ",", "'<thead>'", ",", "'<tr>'", ",", "'<th class=\"col-md-2\">Name</th>'", ",", "'<th class=\"col-md-2\">Type</th>'", ",", "'<th>Description</th>'", ",", "'</tr>'", ",", "'</thead>'", ",", "'<tbody>'", ",", "Object", ".", "keys", "(", "params", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "getMethodParamHtml", "(", "key", ",", "params", "[", "key", "]", ")", ";", "}", ")", ".", "join", "(", "''", ")", ",", "'</tbody>'", ",", "'</table>'", "]", ".", "join", "(", "''", ")", "]", ".", "filter", "(", "Boolean", ")", ".", "join", "(", "''", ")", ";", "}" ]
Genereates documentation for API method. @param {ApiMethod} method @returns {String}
[ "Genereates", "documentation", "for", "API", "method", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/lib/help-formatters/html.js#L46-L72
train
baby-loris/bla
lib/help-formatters/html.js
getMethodParamHtml
function getMethodParamHtml(name, param) { return [ '<tr>', '<td>', name, param.required ? '<span title="Required field" style="color:red;cursor:default">&nbsp;*</span>' : '', '</td>', '<td>', param.type || 'As is', '</td>', '<td>', param.description, '</td>', '</tr>' ].join(''); }
javascript
function getMethodParamHtml(name, param) { return [ '<tr>', '<td>', name, param.required ? '<span title="Required field" style="color:red;cursor:default">&nbsp;*</span>' : '', '</td>', '<td>', param.type || 'As is', '</td>', '<td>', param.description, '</td>', '</tr>' ].join(''); }
[ "function", "getMethodParamHtml", "(", "name", ",", "param", ")", "{", "return", "[", "'<tr>'", ",", "'<td>'", ",", "name", ",", "param", ".", "required", "?", "'<span title=\"Required field\" style=\"color:red;cursor:default\">&nbsp;*</span>'", ":", "''", ",", "'</td>'", ",", "'<td>'", ",", "param", ".", "type", "||", "'As is'", ",", "'</td>'", ",", "'<td>'", ",", "param", ".", "description", ",", "'</td>'", ",", "'</tr>'", "]", ".", "join", "(", "''", ")", ";", "}" ]
Genereates documentation for API method param. @param {String} name @param {Object} param @returns {String}
[ "Genereates", "documentation", "for", "API", "method", "param", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/lib/help-formatters/html.js#L81-L93
train
baby-loris/bla
examples/middleware/build_method_name.js
buildMethodName
function buildMethodName(req) { return [ req.params.service, req.params.subservice ].filter(Boolean).join('-'); }
javascript
function buildMethodName(req) { return [ req.params.service, req.params.subservice ].filter(Boolean).join('-'); }
[ "function", "buildMethodName", "(", "req", ")", "{", "return", "[", "req", ".", "params", ".", "service", ",", "req", ".", "params", ".", "subservice", "]", ".", "filter", "(", "Boolean", ")", ".", "join", "(", "'-'", ")", ";", "}" ]
Build a custom method name. @param {express.Request} req @returns {String}
[ "Build", "a", "custom", "method", "name", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/examples/middleware/build_method_name.js#L12-L17
train
bitnami/nami-utils
lib/file/each-line.js
eachLine
function eachLine(file, lineProcessFn, finallyFn, options) { if (arguments.length === 2) { if (_.isFunction(lineProcessFn)) { finallyFn = null; options = {}; } else { options = lineProcessFn; lineProcessFn = null; } } else if (arguments.length === 3) { if (_.isFunction(finallyFn)) { options = {}; } else { finallyFn = null; options = finallyFn; } } options = _.sanitize(options, {reverse: false, eachLine: null, finally: null, encoding: 'utf-8'}); finallyFn = finallyFn || options.finally; lineProcessFn = lineProcessFn || options.eachLine; const data = read(file, _.pick(options, 'encoding')); const lines = data.split('\n'); if (options.reverse) lines.reverse(); const newLines = []; _.each(lines, (line, index) => { const res = lineProcessFn(line, index); newLines.push(res); // Returning false from lineProcessFn will allow us early aborting the loop return res; }); if (options.reverse) newLines.reverse(); if (finallyFn !== null) finallyFn(newLines.join('\n')); }
javascript
function eachLine(file, lineProcessFn, finallyFn, options) { if (arguments.length === 2) { if (_.isFunction(lineProcessFn)) { finallyFn = null; options = {}; } else { options = lineProcessFn; lineProcessFn = null; } } else if (arguments.length === 3) { if (_.isFunction(finallyFn)) { options = {}; } else { finallyFn = null; options = finallyFn; } } options = _.sanitize(options, {reverse: false, eachLine: null, finally: null, encoding: 'utf-8'}); finallyFn = finallyFn || options.finally; lineProcessFn = lineProcessFn || options.eachLine; const data = read(file, _.pick(options, 'encoding')); const lines = data.split('\n'); if (options.reverse) lines.reverse(); const newLines = []; _.each(lines, (line, index) => { const res = lineProcessFn(line, index); newLines.push(res); // Returning false from lineProcessFn will allow us early aborting the loop return res; }); if (options.reverse) newLines.reverse(); if (finallyFn !== null) finallyFn(newLines.join('\n')); }
[ "function", "eachLine", "(", "file", ",", "lineProcessFn", ",", "finallyFn", ",", "options", ")", "{", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "if", "(", "_", ".", "isFunction", "(", "lineProcessFn", ")", ")", "{", "finallyFn", "=", "null", ";", "options", "=", "{", "}", ";", "}", "else", "{", "options", "=", "lineProcessFn", ";", "lineProcessFn", "=", "null", ";", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "if", "(", "_", ".", "isFunction", "(", "finallyFn", ")", ")", "{", "options", "=", "{", "}", ";", "}", "else", "{", "finallyFn", "=", "null", ";", "options", "=", "finallyFn", ";", "}", "}", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "reverse", ":", "false", ",", "eachLine", ":", "null", ",", "finally", ":", "null", ",", "encoding", ":", "'utf-8'", "}", ")", ";", "finallyFn", "=", "finallyFn", "||", "options", ".", "finally", ";", "lineProcessFn", "=", "lineProcessFn", "||", "options", ".", "eachLine", ";", "const", "data", "=", "read", "(", "file", ",", "_", ".", "pick", "(", "options", ",", "'encoding'", ")", ")", ";", "const", "lines", "=", "data", ".", "split", "(", "'\\n'", ")", ";", "\\n", "if", "(", "options", ".", "reverse", ")", "lines", ".", "reverse", "(", ")", ";", "const", "newLines", "=", "[", "]", ";", "_", ".", "each", "(", "lines", ",", "(", "line", ",", "index", ")", "=>", "{", "const", "res", "=", "lineProcessFn", "(", "line", ",", "index", ")", ";", "newLines", ".", "push", "(", "res", ")", ";", "return", "res", ";", "}", ")", ";", "if", "(", "options", ".", "reverse", ")", "newLines", ".", "reverse", "(", ")", ";", "}" ]
Callback for processing file lines @callback lineProcessCallback @param {string} line - The line to process @param {number} index - The current index of the file Callback to execute after processing a file @callback afterFileProcessCallback @param {string} text - Full processed text Iterate over and process the lines of a file @function $file~eachLine @param {string} file @param {lineProcessCallback} [lineProcessCallback] - The callback to run over the line. @param {afterFileProcessCallback} [finallyCallback] - The callback to execute after all the lines have been processed. @param {} [options] @param {boolean} [options.reverse=false] - Iterate over the lines in reverse order @param {string} [options.encoding=utf-8] - Encoding used to read the file @example // Parse each line of a file $file.eachLine('file.txt', function(line) { console.log(line); }, function() { console.log('File processed'); }); // => This is a text File processed
[ "Callback", "for", "processing", "file", "lines" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/each-line.js#L40-L74
train
bitnami/nami-utils
lib/file/write.js
write
function write(file, text, options) { options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true}); file = normalize(file); try { fs.writeFileSync(file, text, options); } catch (e) { if (e.code === 'ENOENT' && options.retryOnENOENT) { // If trying to create the parent failed, there is no point on retrying try { mkdir(path.dirname(file)); } catch (emkdir) { throw e; } write(file, text, _.opts(options, {retryOnENOENT: false}, {mode: 'overwite'})); } else { throw e; } } }
javascript
function write(file, text, options) { options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true}); file = normalize(file); try { fs.writeFileSync(file, text, options); } catch (e) { if (e.code === 'ENOENT' && options.retryOnENOENT) { // If trying to create the parent failed, there is no point on retrying try { mkdir(path.dirname(file)); } catch (emkdir) { throw e; } write(file, text, _.opts(options, {retryOnENOENT: false}, {mode: 'overwite'})); } else { throw e; } } }
[ "function", "write", "(", "file", ",", "text", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "encoding", ":", "'utf-8'", ",", "retryOnENOENT", ":", "true", "}", ")", ";", "file", "=", "normalize", "(", "file", ")", ";", "try", "{", "fs", ".", "writeFileSync", "(", "file", ",", "text", ",", "options", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "code", "===", "'ENOENT'", "&&", "options", ".", "retryOnENOENT", ")", "{", "try", "{", "mkdir", "(", "path", ".", "dirname", "(", "file", ")", ")", ";", "}", "catch", "(", "emkdir", ")", "{", "throw", "e", ";", "}", "write", "(", "file", ",", "text", ",", "_", ".", "opts", "(", "options", ",", "{", "retryOnENOENT", ":", "false", "}", ",", "{", "mode", ":", "'overwite'", "}", ")", ")", ";", "}", "else", "{", "throw", "e", ";", "}", "}", "}" ]
Writes text to a file @function $file~write @param {string} file - File to write to @param {string} text - Text to write @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @param {boolean} [options.retryOnENOENT=true] - Retry if writing files because of the parent directory does not exists
[ "Writes", "text", "to", "a", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/write.js#L19-L37
train
bitnami/nami-utils
lib/file/walk-dir.js
walkDir
function walkDir(file, callback, options) { file = path.resolve(file); if (!_.isFunction(callback)) throw new Error('You must provide a callback function'); options = _.opts(options, {followSymLinks: false, maxDepth: Infinity}); const prefix = options.prefix || file; function _walkDir(f, depth) { const type = fileType(f); const relativePath = stripPathPrefix(f, prefix); const metaData = {type: type, file: relativePath}; if (file === f) metaData.topDir = true; const result = callback(f, metaData); if (result === false) return false; if (type === 'directory' || (type === 'link' && options.followSymLinks && isDirectory(f, options.followSymLinks))) { let shouldContinue = true; if (depth >= options.maxDepth) { return; } _.each(fs.readdirSync(f), (elem) => { shouldContinue = _walkDir(path.join(f, elem), depth + 1); return shouldContinue; }); } } _walkDir(file, 0); }
javascript
function walkDir(file, callback, options) { file = path.resolve(file); if (!_.isFunction(callback)) throw new Error('You must provide a callback function'); options = _.opts(options, {followSymLinks: false, maxDepth: Infinity}); const prefix = options.prefix || file; function _walkDir(f, depth) { const type = fileType(f); const relativePath = stripPathPrefix(f, prefix); const metaData = {type: type, file: relativePath}; if (file === f) metaData.topDir = true; const result = callback(f, metaData); if (result === false) return false; if (type === 'directory' || (type === 'link' && options.followSymLinks && isDirectory(f, options.followSymLinks))) { let shouldContinue = true; if (depth >= options.maxDepth) { return; } _.each(fs.readdirSync(f), (elem) => { shouldContinue = _walkDir(path.join(f, elem), depth + 1); return shouldContinue; }); } } _walkDir(file, 0); }
[ "function", "walkDir", "(", "file", ",", "callback", ",", "options", ")", "{", "file", "=", "path", ".", "resolve", "(", "file", ")", ";", "if", "(", "!", "_", ".", "isFunction", "(", "callback", ")", ")", "throw", "new", "Error", "(", "'You must provide a callback function'", ")", ";", "options", "=", "_", ".", "opts", "(", "options", ",", "{", "followSymLinks", ":", "false", ",", "maxDepth", ":", "Infinity", "}", ")", ";", "const", "prefix", "=", "options", ".", "prefix", "||", "file", ";", "function", "_walkDir", "(", "f", ",", "depth", ")", "{", "const", "type", "=", "fileType", "(", "f", ")", ";", "const", "relativePath", "=", "stripPathPrefix", "(", "f", ",", "prefix", ")", ";", "const", "metaData", "=", "{", "type", ":", "type", ",", "file", ":", "relativePath", "}", ";", "if", "(", "file", "===", "f", ")", "metaData", ".", "topDir", "=", "true", ";", "const", "result", "=", "callback", "(", "f", ",", "metaData", ")", ";", "if", "(", "result", "===", "false", ")", "return", "false", ";", "if", "(", "type", "===", "'directory'", "||", "(", "type", "===", "'link'", "&&", "options", ".", "followSymLinks", "&&", "isDirectory", "(", "f", ",", "options", ".", "followSymLinks", ")", ")", ")", "{", "let", "shouldContinue", "=", "true", ";", "if", "(", "depth", ">=", "options", ".", "maxDepth", ")", "{", "return", ";", "}", "_", ".", "each", "(", "fs", ".", "readdirSync", "(", "f", ")", ",", "(", "elem", ")", "=>", "{", "shouldContinue", "=", "_walkDir", "(", "path", ".", "join", "(", "f", ",", "elem", ")", ",", "depth", "+", "1", ")", ";", "return", "shouldContinue", ";", "}", ")", ";", "}", "}", "_walkDir", "(", "file", ",", "0", ")", ";", "}" ]
Navigate through directory contents @private @param {string} file - Directory to walk over @param {function} callback - Callback to execute for each file. @param {Object} [options] @param {boolean} [options.followSymLinks=false] - Follow symbolic links. @param {boolean} [options.maxDepth=Infinity] - Maximum directory depth to keep iterating
[ "Navigate", "through", "directory", "contents" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/walk-dir.js#L19-L45
train
bitnami/nami-utils
lib/file/yaml/get.js
yamlFileGet
function yamlFileGet(file, keyPath, options) { if (_.isPlainObject(keyPath) && arguments.length === 2) { options = keyPath; keyPath = undefined; } options = _.sanitize(options, {encoding: 'utf-8', default: ''}); const content = yaml.safeLoad(read(file, _.pick(options, 'encoding'))); const value = _extractValue(content, keyPath); return _.isUndefined(value) ? options.default : value; }
javascript
function yamlFileGet(file, keyPath, options) { if (_.isPlainObject(keyPath) && arguments.length === 2) { options = keyPath; keyPath = undefined; } options = _.sanitize(options, {encoding: 'utf-8', default: ''}); const content = yaml.safeLoad(read(file, _.pick(options, 'encoding'))); const value = _extractValue(content, keyPath); return _.isUndefined(value) ? options.default : value; }
[ "function", "yamlFileGet", "(", "file", ",", "keyPath", ",", "options", ")", "{", "if", "(", "_", ".", "isPlainObject", "(", "keyPath", ")", "&&", "arguments", ".", "length", "===", "2", ")", "{", "options", "=", "keyPath", ";", "keyPath", "=", "undefined", ";", "}", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "encoding", ":", "'utf-8'", ",", "default", ":", "''", "}", ")", ";", "const", "content", "=", "yaml", ".", "safeLoad", "(", "read", "(", "file", ",", "_", ".", "pick", "(", "options", ",", "'encoding'", ")", ")", ")", ";", "const", "value", "=", "_extractValue", "(", "content", ",", "keyPath", ")", ";", "return", "_", ".", "isUndefined", "(", "value", ")", "?", "options", ".", "default", ":", "value", ";", "}" ]
Get value from .yaml file @function $file~yaml/get @param {string} file - Yaml File to read the value from @param {string} keyPath to read (it can read nested keys: `'outerKey/innerKey'` or `'/outerKey/innerKey'`. `null` or `'/'` will match all the document). Alternative format: ['outerKey', 'innerKey']. @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @param {string} [options.default=''] - Default value if key not found @returns {string|Number|boolean|Array|Object} Returns the field extracted from the yaml or the default value @throws Will throw an error if the path is not a file
[ "Get", "value", "from", ".", "yaml", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/yaml/get.js#L77-L86
train
bitnami/nami-utils
lib/file/set-attrs.js
setAttrs
function setAttrs(file, attrs) { if (isLink(file)) return; if (_.every([attrs.atime, attrs.mtime], _.identity)) { fs.utimesSync(file, new Date(attrs.atime), new Date(attrs.mtime)); } if (attrs.mode) { chmod(file, attrs.mode); } }
javascript
function setAttrs(file, attrs) { if (isLink(file)) return; if (_.every([attrs.atime, attrs.mtime], _.identity)) { fs.utimesSync(file, new Date(attrs.atime), new Date(attrs.mtime)); } if (attrs.mode) { chmod(file, attrs.mode); } }
[ "function", "setAttrs", "(", "file", ",", "attrs", ")", "{", "if", "(", "isLink", "(", "file", ")", ")", "return", ";", "if", "(", "_", ".", "every", "(", "[", "attrs", ".", "atime", ",", "attrs", ".", "mtime", "]", ",", "_", ".", "identity", ")", ")", "{", "fs", ".", "utimesSync", "(", "file", ",", "new", "Date", "(", "attrs", ".", "atime", ")", ",", "new", "Date", "(", "attrs", ".", "mtime", ")", ")", ";", "}", "if", "(", "attrs", ".", "mode", ")", "{", "chmod", "(", "file", ",", "attrs", ".", "mode", ")", ";", "}", "}" ]
Set file attributes @function $file~setAttrs @param {string} file @param {Object} [options] - Object containing the file attributes: mode, atime, mtime @param {Date|string|number} [options.atime] - File access time @param {Date|string|number} [options.mtime] - File modification time @param {string} [options.mode] - File permissions @example // Update modification time and permissions of a file $file.setAttrs('timestamp', {mtime: new Date(), mode: '664'});
[ "Set", "file", "attributes" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/set-attrs.js#L20-L28
train
bitnami/nami-utils
lib/os/user-management/group-exists.js
groupExists
function groupExists(group) { if (isPlatform('windows')) { throw new Error('Don\'t know how to check for group existence on Windows'); } else { if (_.isEmpty(findGroup(group, {refresh: true, throwIfNotFound: false}))) { return false; } else { return true; } } }
javascript
function groupExists(group) { if (isPlatform('windows')) { throw new Error('Don\'t know how to check for group existence on Windows'); } else { if (_.isEmpty(findGroup(group, {refresh: true, throwIfNotFound: false}))) { return false; } else { return true; } } }
[ "function", "groupExists", "(", "group", ")", "{", "if", "(", "isPlatform", "(", "'windows'", ")", ")", "{", "throw", "new", "Error", "(", "'Don\\'t know how to check for group existence on Windows'", ")", ";", "}", "else", "\\'", "}" ]
Check for group existence @function $os~groupExists @param {string|number} group - Groupname or group id @returns {boolean} - Whether the group exists or not @example // Check if group 'mysql' exists $os.groupExists('mysql'); // => true
[ "Check", "for", "group", "existence" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/group-exists.js#L17-L27
train
bitnami/nami-utils
lib/file/access/index.js
readable
function readable(file) { if (!exists(file)) { return false; } else { try { fs.accessSync(file, fs.R_OK); } catch (e) { return false; } return true; } }
javascript
function readable(file) { if (!exists(file)) { return false; } else { try { fs.accessSync(file, fs.R_OK); } catch (e) { return false; } return true; } }
[ "function", "readable", "(", "file", ")", "{", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "return", "false", ";", "}", "else", "{", "try", "{", "fs", ".", "accessSync", "(", "file", ",", "fs", ".", "R_OK", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "}" ]
Check whether a file is readable or not @function $file~readable @param {string} file @returns {boolean} @example // Check if /bin/ls is readable by the current user $file.readable('/bin/ls') // => true
[ "Check", "whether", "a", "file", "is", "readable", "or", "not" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/access/index.js#L37-L48
train
bitnami/nami-utils
lib/file/access/index.js
readableBy
function readableBy(file, user) { if (!exists(file)) { return readableBy(path.dirname(file), user); } const userData = findUser(user); if (userData.id === 0) { return true; } else if (userData.id === process.getuid()) { return readable(file); } else { return _accesibleByUser(userData, file, fs.R_OK); } }
javascript
function readableBy(file, user) { if (!exists(file)) { return readableBy(path.dirname(file), user); } const userData = findUser(user); if (userData.id === 0) { return true; } else if (userData.id === process.getuid()) { return readable(file); } else { return _accesibleByUser(userData, file, fs.R_OK); } }
[ "function", "readableBy", "(", "file", ",", "user", ")", "{", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "return", "readableBy", "(", "path", ".", "dirname", "(", "file", ")", ",", "user", ")", ";", "}", "const", "userData", "=", "findUser", "(", "user", ")", ";", "if", "(", "userData", ".", "id", "===", "0", ")", "{", "return", "true", ";", "}", "else", "if", "(", "userData", ".", "id", "===", "process", ".", "getuid", "(", ")", ")", "{", "return", "readable", "(", "file", ")", ";", "}", "else", "{", "return", "_accesibleByUser", "(", "userData", ",", "file", ",", "fs", ".", "R_OK", ")", ";", "}", "}" ]
Check whether a file is readable or not by a given user @function $file~readableBy @param {string} file @param {string|number} user - Username or user id to check permissions for @returns {boolean} @example // Check if 'conf/my.cnf' is readable by the 'nobody' user $file.readableBy('conf/my.cnf', 'nobody'); // => false
[ "Check", "whether", "a", "file", "is", "readable", "or", "not", "by", "a", "given", "user" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/access/index.js#L60-L72
train
bitnami/nami-utils
lib/file/access/index.js
writable
function writable(file) { if (!exists(file)) { return writable(path.dirname(file)); } else { try { fs.accessSync(file, fs.W_OK); } catch (e) { return false; } return true; } }
javascript
function writable(file) { if (!exists(file)) { return writable(path.dirname(file)); } else { try { fs.accessSync(file, fs.W_OK); } catch (e) { return false; } return true; } }
[ "function", "writable", "(", "file", ")", "{", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "return", "writable", "(", "path", ".", "dirname", "(", "file", ")", ")", ";", "}", "else", "{", "try", "{", "fs", ".", "accessSync", "(", "file", ",", "fs", ".", "W_OK", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "}" ]
Check whether a file is writable or not @function $file~writable @param {string} file @returns {boolean} @example // Check if 'conf/my.cnf' is writable by the current user $file.writable('conf/my.cnf'); // => true
[ "Check", "whether", "a", "file", "is", "writable", "or", "not" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/access/index.js#L84-L95
train
bitnami/nami-utils
lib/file/access/index.js
writableBy
function writableBy(file, user) { function _writableBy(f, userData) { if (!exists(f)) { return _writableBy(path.dirname(f), userData); } else { return _accesibleByUser(userData, f, fs.W_OK); } } const uData = findUser(user); // root can always write if (uData.id === 0) { return true; } else if (uData.id === process.getuid()) { return writable(file); } else { return _writableBy(file, uData); } }
javascript
function writableBy(file, user) { function _writableBy(f, userData) { if (!exists(f)) { return _writableBy(path.dirname(f), userData); } else { return _accesibleByUser(userData, f, fs.W_OK); } } const uData = findUser(user); // root can always write if (uData.id === 0) { return true; } else if (uData.id === process.getuid()) { return writable(file); } else { return _writableBy(file, uData); } }
[ "function", "writableBy", "(", "file", ",", "user", ")", "{", "function", "_writableBy", "(", "f", ",", "userData", ")", "{", "if", "(", "!", "exists", "(", "f", ")", ")", "{", "return", "_writableBy", "(", "path", ".", "dirname", "(", "f", ")", ",", "userData", ")", ";", "}", "else", "{", "return", "_accesibleByUser", "(", "userData", ",", "f", ",", "fs", ".", "W_OK", ")", ";", "}", "}", "const", "uData", "=", "findUser", "(", "user", ")", ";", "if", "(", "uData", ".", "id", "===", "0", ")", "{", "return", "true", ";", "}", "else", "if", "(", "uData", ".", "id", "===", "process", ".", "getuid", "(", ")", ")", "{", "return", "writable", "(", "file", ")", ";", "}", "else", "{", "return", "_writableBy", "(", "file", ",", "uData", ")", ";", "}", "}" ]
Check whether a file is writable or not by a given user @function $file~writableBy @param {string} file @param {string|number} user - Username or user id to check permissions for @returns {boolean} @example // Check if 'conf/my.cnf' is writable by the 'nobody' user $file.writableBy('conf/my.cnf', 'nobody'); // => false
[ "Check", "whether", "a", "file", "is", "writable", "or", "not", "by", "a", "given", "user" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/access/index.js#L108-L125
train
bitnami/nami-utils
lib/file/access/index.js
executable
function executable(file) { try { fs.accessSync(file, fs.X_OK); return true; } catch (e) { return false; } }
javascript
function executable(file) { try { fs.accessSync(file, fs.X_OK); return true; } catch (e) { return false; } }
[ "function", "executable", "(", "file", ")", "{", "try", "{", "fs", ".", "accessSync", "(", "file", ",", "fs", ".", "X_OK", ")", ";", "return", "true", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Check whether a file is executable or not @function $file~executable @param {string} file @returns {boolean} @example // Check if '/bin/ls' is executable by the current user $file.executable('/bin/ls'); // => true
[ "Check", "whether", "a", "file", "is", "executable", "or", "not" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/access/index.js#L137-L144
train
bitnami/nami-utils
lib/file/access/index.js
executableBy
function executableBy(file, user) { if (!exists(file)) { return false; } const userData = findUser(user); if (userData.id === 0) { // Root can do anything but execute a file with no exec permissions const mode = fs.lstatSync(file).mode; return !!(mode & parseInt('00111', 8)); } else if (userData.id === process.getuid()) { return executable(file); } else { return _accesibleByUser(userData, file, fs.X_OK); } }
javascript
function executableBy(file, user) { if (!exists(file)) { return false; } const userData = findUser(user); if (userData.id === 0) { // Root can do anything but execute a file with no exec permissions const mode = fs.lstatSync(file).mode; return !!(mode & parseInt('00111', 8)); } else if (userData.id === process.getuid()) { return executable(file); } else { return _accesibleByUser(userData, file, fs.X_OK); } }
[ "function", "executableBy", "(", "file", ",", "user", ")", "{", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "return", "false", ";", "}", "const", "userData", "=", "findUser", "(", "user", ")", ";", "if", "(", "userData", ".", "id", "===", "0", ")", "{", "const", "mode", "=", "fs", ".", "lstatSync", "(", "file", ")", ".", "mode", ";", "return", "!", "!", "(", "mode", "&", "parseInt", "(", "'00111'", ",", "8", ")", ")", ";", "}", "else", "if", "(", "userData", ".", "id", "===", "process", ".", "getuid", "(", ")", ")", "{", "return", "executable", "(", "file", ")", ";", "}", "else", "{", "return", "_accesibleByUser", "(", "userData", ",", "file", ",", "fs", ".", "X_OK", ")", ";", "}", "}" ]
Check whether a file is executable or not by a given user @function $file~executable @param {string} file @param {string|number} user - Username or user id to check permissions for @returns {boolean} @example // Check if '/bin/ls' is executable by the 'nobody' user $file.executable('/bin/ls', 'nobody'); // => true
[ "Check", "whether", "a", "file", "is", "executable", "or", "not", "by", "a", "given", "user" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/access/index.js#L157-L171
train
bitnami/nami-utils
lib/file/split.js
split
function split(p) { const components = p.replace(/\/+/g, '/').replace(/\/+$/, '').split(path.sep); if (path.isAbsolute(p) && components[0] === '') { components[0] = '/'; } return components; }
javascript
function split(p) { const components = p.replace(/\/+/g, '/').replace(/\/+$/, '').split(path.sep); if (path.isAbsolute(p) && components[0] === '') { components[0] = '/'; } return components; }
[ "function", "split", "(", "p", ")", "{", "const", "components", "=", "p", ".", "replace", "(", "/", "\\/+", "/", "g", ",", "'/'", ")", ".", "replace", "(", "/", "\\/+$", "/", ",", "''", ")", ".", "split", "(", "path", ".", "sep", ")", ";", "if", "(", "path", ".", "isAbsolute", "(", "p", ")", "&&", "components", "[", "0", "]", "===", "''", ")", "{", "components", "[", "0", "]", "=", "'/'", ";", "}", "return", "components", ";", "}" ]
Get an array formed with the file components @function $file~split @param {string} path - File path to split @returns {string[]} - The path components of the path @example // Split '/foo/bar/file' into its path components $file.split('/foo/bar/file'); // => [ '/', 'foo', 'bar', 'file' ]
[ "Get", "an", "array", "formed", "with", "the", "file", "components" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/split.js#L15-L21
train
bitnami/nami-utils
lib/file/join.js
join
function join() { const components = _.isArray(arguments[0]) ? arguments[0] : _.toArray(arguments); return path.join.apply(null, components).replace(/(.+)\/+$/, '$1'); }
javascript
function join() { const components = _.isArray(arguments[0]) ? arguments[0] : _.toArray(arguments); return path.join.apply(null, components).replace(/(.+)\/+$/, '$1'); }
[ "function", "join", "(", ")", "{", "const", "components", "=", "_", ".", "isArray", "(", "arguments", "[", "0", "]", ")", "?", "arguments", "[", "0", "]", ":", "_", ".", "toArray", "(", "arguments", ")", ";", "return", "path", ".", "join", ".", "apply", "(", "null", ",", "components", ")", ".", "replace", "(", "/", "(.+)\\/+$", "/", ",", "'$1'", ")", ";", "}" ]
Get a path from a group of elements @function $file~join @param {string[]|...string} components - Components of the path @returns {string} - The path @example // Get a path from an array $file.join(['/foo', 'bar', 'sample']) // => '/foo/bar/sample' @example // Join the application installation directory with the 'conf' folder $file.join($app.installdir, 'conf') // => '/opt/bitnami/mysql/conf'
[ "Get", "a", "path", "from", "a", "group", "of", "elements" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/join.js#L20-L23
train
bitnami/nami-utils
lib/file/backup.js
backup
function backup(source, options) { options = _.sanitize(options, {destination: null}); let dest = options.destination; if (dest === null) { dest = `${source.replace(/\/*$/, '')}_${Date.now()}`; } copy(source, dest); return dest; }
javascript
function backup(source, options) { options = _.sanitize(options, {destination: null}); let dest = options.destination; if (dest === null) { dest = `${source.replace(/\/*$/, '')}_${Date.now()}`; } copy(source, dest); return dest; }
[ "function", "backup", "(", "source", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "destination", ":", "null", "}", ")", ";", "let", "dest", "=", "options", ".", "destination", ";", "if", "(", "dest", "===", "null", ")", "{", "dest", "=", "`", "${", "source", ".", "replace", "(", "/", "\\/*$", "/", ",", "''", ")", "}", "${", "Date", ".", "now", "(", ")", "}", "`", ";", "}", "copy", "(", "source", ",", "dest", ")", ";", "return", "dest", ";", "}" ]
Backup a file or directory @function $file~backup @param {string} source @param {Object} [options] @param {Object} [options.destination] - Destination path to use when copying. By default, the backup will be placed in the same directory, adding a timestamp @returns {string} - The final destination @example // Backup a file (it will automatically append a timestamp to it: 'conf/my.cnf_1453811340') $file.backup('conf/my.cnf'}); @example // Backup a file with a specific name and location 'conf/my.cnf.default' $file.backup('conf/my.cnf', {destination: 'conf/my.cnf.default'});
[ "Backup", "a", "file", "or", "directory" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/backup.js#L21-L29
train
pex-gl/pex-math
quat.js
fromEuler
function fromEuler (q, euler) { var x = euler[0] var y = euler[1] var z = euler[2] var cx = Math.cos(x / 2) var cy = Math.cos(y / 2) var cz = Math.cos(z / 2) var sx = Math.sin(x / 2) var sy = Math.sin(y / 2) var sz = Math.sin(z / 2) q[0] = sx * cy * cz + cx * sy * sz q[1] = cx * sy * cz - sx * cy * sz q[2] = cx * cy * sz + sx * sy * cz q[3] = cx * cy * cz - sx * sy * sz return q }
javascript
function fromEuler (q, euler) { var x = euler[0] var y = euler[1] var z = euler[2] var cx = Math.cos(x / 2) var cy = Math.cos(y / 2) var cz = Math.cos(z / 2) var sx = Math.sin(x / 2) var sy = Math.sin(y / 2) var sz = Math.sin(z / 2) q[0] = sx * cy * cz + cx * sy * sz q[1] = cx * sy * cz - sx * cy * sz q[2] = cx * cy * sz + sx * sy * cz q[3] = cx * cy * cz - sx * sy * sz return q }
[ "function", "fromEuler", "(", "q", ",", "euler", ")", "{", "var", "x", "=", "euler", "[", "0", "]", "var", "y", "=", "euler", "[", "1", "]", "var", "z", "=", "euler", "[", "2", "]", "var", "cx", "=", "Math", ".", "cos", "(", "x", "/", "2", ")", "var", "cy", "=", "Math", ".", "cos", "(", "y", "/", "2", ")", "var", "cz", "=", "Math", ".", "cos", "(", "z", "/", "2", ")", "var", "sx", "=", "Math", ".", "sin", "(", "x", "/", "2", ")", "var", "sy", "=", "Math", ".", "sin", "(", "y", "/", "2", ")", "var", "sz", "=", "Math", ".", "sin", "(", "z", "/", "2", ")", "q", "[", "0", "]", "=", "sx", "*", "cy", "*", "cz", "+", "cx", "*", "sy", "*", "sz", "q", "[", "1", "]", "=", "cx", "*", "sy", "*", "cz", "-", "sx", "*", "cy", "*", "sz", "q", "[", "2", "]", "=", "cx", "*", "cy", "*", "sz", "+", "sx", "*", "sy", "*", "cz", "q", "[", "3", "]", "=", "cx", "*", "cy", "*", "cz", "-", "sx", "*", "sy", "*", "sz", "return", "q", "}" ]
x = yaw, y = pitch, z = roll assumes XYZ order
[ "x", "=", "yaw", "y", "=", "pitch", "z", "=", "roll", "assumes", "XYZ", "order" ]
9069753b0e0076a79d6337d8e98469ec2fd89f05
https://github.com/pex-gl/pex-math/blob/9069753b0e0076a79d6337d8e98469ec2fd89f05/quat.js#L97-L114
train
bitnami/nami-utils
lib/file/yaml/set.js
yamlFileSet
function yamlFileSet(file, keyPath, value, options) { if (_.isPlainObject(keyPath)) { // key is keyMapping if (!_.isUndefined(options)) { throw new Error('Wrong parameters. Cannot specify a keymapping and a value at the same time.'); } if (_.isPlainObject(value)) { options = value; value = null; } else { options = {}; } } else if (!_.isString(keyPath) && !_.isArray(keyPath)) { throw new Error('Wrong parameter `keyPath`.'); } options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true}); if (!exists(file)) { touch(file); } let content = yaml.safeLoad(read(file, _.pick(options, 'encoding'))); if (_.isUndefined(content)) { content = {}; } content = _setValue(content, keyPath, value); write(file, yaml.safeDump(content), options); }
javascript
function yamlFileSet(file, keyPath, value, options) { if (_.isPlainObject(keyPath)) { // key is keyMapping if (!_.isUndefined(options)) { throw new Error('Wrong parameters. Cannot specify a keymapping and a value at the same time.'); } if (_.isPlainObject(value)) { options = value; value = null; } else { options = {}; } } else if (!_.isString(keyPath) && !_.isArray(keyPath)) { throw new Error('Wrong parameter `keyPath`.'); } options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true}); if (!exists(file)) { touch(file); } let content = yaml.safeLoad(read(file, _.pick(options, 'encoding'))); if (_.isUndefined(content)) { content = {}; } content = _setValue(content, keyPath, value); write(file, yaml.safeDump(content), options); }
[ "function", "yamlFileSet", "(", "file", ",", "keyPath", ",", "value", ",", "options", ")", "{", "if", "(", "_", ".", "isPlainObject", "(", "keyPath", ")", ")", "{", "if", "(", "!", "_", ".", "isUndefined", "(", "options", ")", ")", "{", "throw", "new", "Error", "(", "'Wrong parameters. Cannot specify a keymapping and a value at the same time.'", ")", ";", "}", "if", "(", "_", ".", "isPlainObject", "(", "value", ")", ")", "{", "options", "=", "value", ";", "value", "=", "null", ";", "}", "else", "{", "options", "=", "{", "}", ";", "}", "}", "else", "if", "(", "!", "_", ".", "isString", "(", "keyPath", ")", "&&", "!", "_", ".", "isArray", "(", "keyPath", ")", ")", "{", "throw", "new", "Error", "(", "'Wrong parameter `keyPath`.'", ")", ";", "}", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "encoding", ":", "'utf-8'", ",", "retryOnENOENT", ":", "true", "}", ")", ";", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "touch", "(", "file", ")", ";", "}", "let", "content", "=", "yaml", ".", "safeLoad", "(", "read", "(", "file", ",", "_", ".", "pick", "(", "options", ",", "'encoding'", ")", ")", ")", ";", "if", "(", "_", ".", "isUndefined", "(", "content", ")", ")", "{", "content", "=", "{", "}", ";", "}", "content", "=", "_setValue", "(", "content", ",", "keyPath", ",", "value", ")", ";", "write", "(", "file", ",", "yaml", ".", "safeDump", "(", "content", ")", ",", "options", ")", ";", "}" ]
Set value in yaml file @function $file~yaml/set @param {string} file - Yaml file to write the value to @param {string} keyPath (it can read nested keys: `'outerKey/innerKey'` or `'/outerKey/innerKey'`. `null` or `'/'` will match all the document). Alternative format: ['outerKey', 'innerKey']. @param {string|Number|boolean|Array|Object} value @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @param {boolean} [options.retryOnENOENT=true] - Retry if writing files because of the parent directory does not exists @throws Will throw an error if the path is not a file Set value in yaml file @function $file~yaml/set² @param {string} file - Yaml file to write the value to @param {Object} keyMapping - key-value map to set in the file @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @param {boolean} [options.retryOnENOENT=true] - Retry if writing files because of the parent directory does not exists @throws Will throw an error if the path is not a file
[ "Set", "value", "in", "yaml", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/yaml/set.js#L73-L98
train
bitnami/nami-utils
lib/file/is-file.js
isFile
function isFile(file, options) { options = _.sanitize(options, {acceptLinks: true}); try { return _fileStats(file, options).isFile(); } catch (e) { return false; } }
javascript
function isFile(file, options) { options = _.sanitize(options, {acceptLinks: true}); try { return _fileStats(file, options).isFile(); } catch (e) { return false; } }
[ "function", "isFile", "(", "file", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "acceptLinks", ":", "true", "}", ")", ";", "try", "{", "return", "_fileStats", "(", "file", ",", "options", ")", ".", "isFile", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Check whether a given path is a file @function $file~isFile @param {string} file @param {Object} [options] @param {boolean} [options.acceptLinks=true] - Accept links to files as files @returns {boolean} @example // Checks if the file 'conf/my.cnf' is a file $file.isFile('conf/my.cnf'); // => true
[ "Check", "whether", "a", "given", "path", "is", "a", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/is-file.js#L18-L25
train
bitnami/nami-utils
lib/os/user-management/find-group.js
findGroup
function findGroup(group, options) { options = _.opts(options, {refresh: true, throwIfNotFound: true}); if (_.isString(group) && group.match(/^[0-9]+$/)) { group = parseInt(group, 10); } return _findGroup(group, options); }
javascript
function findGroup(group, options) { options = _.opts(options, {refresh: true, throwIfNotFound: true}); if (_.isString(group) && group.match(/^[0-9]+$/)) { group = parseInt(group, 10); } return _findGroup(group, options); }
[ "function", "findGroup", "(", "group", ",", "options", ")", "{", "options", "=", "_", ".", "opts", "(", "options", ",", "{", "refresh", ":", "true", ",", "throwIfNotFound", ":", "true", "}", ")", ";", "if", "(", "_", ".", "isString", "(", "group", ")", "&&", "group", ".", "match", "(", "/", "^[0-9]+$", "/", ")", ")", "{", "group", "=", "parseInt", "(", "group", ",", "10", ")", ";", "}", "return", "_findGroup", "(", "group", ",", "options", ")", ";", "}" ]
Lookup system group information @function $os~findGroup @param {string|number} group - Groupname or group id to look for @param {Object} [options] @param {boolean} [options.refresh=true] - Setting this to false allows operating over a cached database of groups, for improved performance. It may result in incorrect results if the affected group changes @param {boolean} [options.throwIfNotFound=true] - By default, this function throws an error if the specified group cannot be found @returns {object|null} - Object containing the group id and name: ( { id: 0, name: wheel } ) or null if not found and throwIfNotFound is set to false @example // Get group information of 'mysql' $os.findGroup('mysql'); // => { name: 'mysql', id: 1001 }
[ "Lookup", "system", "group", "information" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/find-group.js#L32-L38
train
bitnami/nami-utils
lib/os/user-management/add-user.js
addUser
function addUser(user, options) { if (!runningAsRoot()) return; if (!user) throw new Error('You must provide an username'); options = _.opts(options, {systemUser: false, home: null, password: null, gid: null, uid: null, groups: []}); if (userExists(user)) { return; } if (isPlatform('linux')) { _addUserLinux(user, options); } else if (isPlatform('osx')) { _addUserOsx(user, options); } else if (isPlatform('windows')) { throw new Error("Don't know how to add user in Windows"); } else { throw new Error("Don't know how to add user in current platform"); } }
javascript
function addUser(user, options) { if (!runningAsRoot()) return; if (!user) throw new Error('You must provide an username'); options = _.opts(options, {systemUser: false, home: null, password: null, gid: null, uid: null, groups: []}); if (userExists(user)) { return; } if (isPlatform('linux')) { _addUserLinux(user, options); } else if (isPlatform('osx')) { _addUserOsx(user, options); } else if (isPlatform('windows')) { throw new Error("Don't know how to add user in Windows"); } else { throw new Error("Don't know how to add user in current platform"); } }
[ "function", "addUser", "(", "user", ",", "options", ")", "{", "if", "(", "!", "runningAsRoot", "(", ")", ")", "return", ";", "if", "(", "!", "user", ")", "throw", "new", "Error", "(", "'You must provide an username'", ")", ";", "options", "=", "_", ".", "opts", "(", "options", ",", "{", "systemUser", ":", "false", ",", "home", ":", "null", ",", "password", ":", "null", ",", "gid", ":", "null", ",", "uid", ":", "null", ",", "groups", ":", "[", "]", "}", ")", ";", "if", "(", "userExists", "(", "user", ")", ")", "{", "return", ";", "}", "if", "(", "isPlatform", "(", "'linux'", ")", ")", "{", "_addUserLinux", "(", "user", ",", "options", ")", ";", "}", "else", "if", "(", "isPlatform", "(", "'osx'", ")", ")", "{", "_addUserOsx", "(", "user", ",", "options", ")", ";", "}", "else", "if", "(", "isPlatform", "(", "'windows'", ")", ")", "{", "throw", "new", "Error", "(", "\"Don't know how to add user in Windows\"", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Don't know how to add user in current platform\"", ")", ";", "}", "}" ]
Add a user to the system @function $os~addUser @param {string} user - Username @param {Object} [options] @param {boolean} [options.systemUser=false] - Set user as system user (UID within 100 and 999) @param {string} [options.home=null] - User home directory @param {string} [options.password=null] - User password @param {string|number} [options.gid=null] - User Main Group ID @param {string|number} [options.uid=null] - User ID @param {string[]} [options.groups=[]] - Extra groups for the user @example // Creates a 'mysql' user and add it to 'mysql' group $os.addUser('mysql', {gid: $os.getGid('mysql')});
[ "Add", "a", "user", "to", "the", "system" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/add-user.js#L116-L132
train
pex-gl/pex-math
euler.js
fromQuat
function fromQuat (v, q) { var sqx = q[0] * q[0] var sqy = q[1] * q[1] var sqz = q[2] * q[2] var sqw = q[3] * q[3] v[0] = Math.atan2(2 * (q[0] * q[3] - q[1] * q[2]), (sqw - sqx - sqy + sqz)) v[1] = Math.asin(clamp(2 * (q[0] * q[2] + q[1] * q[3]), -1, 1)) v[2] = Math.atan2(2 * (q[2] * q[3] - q[0] * q[1]), (sqw + sqx - sqy - sqz)) return v }
javascript
function fromQuat (v, q) { var sqx = q[0] * q[0] var sqy = q[1] * q[1] var sqz = q[2] * q[2] var sqw = q[3] * q[3] v[0] = Math.atan2(2 * (q[0] * q[3] - q[1] * q[2]), (sqw - sqx - sqy + sqz)) v[1] = Math.asin(clamp(2 * (q[0] * q[2] + q[1] * q[3]), -1, 1)) v[2] = Math.atan2(2 * (q[2] * q[3] - q[0] * q[1]), (sqw + sqx - sqy - sqz)) return v }
[ "function", "fromQuat", "(", "v", ",", "q", ")", "{", "var", "sqx", "=", "q", "[", "0", "]", "*", "q", "[", "0", "]", "var", "sqy", "=", "q", "[", "1", "]", "*", "q", "[", "1", "]", "var", "sqz", "=", "q", "[", "2", "]", "*", "q", "[", "2", "]", "var", "sqw", "=", "q", "[", "3", "]", "*", "q", "[", "3", "]", "v", "[", "0", "]", "=", "Math", ".", "atan2", "(", "2", "*", "(", "q", "[", "0", "]", "*", "q", "[", "3", "]", "-", "q", "[", "1", "]", "*", "q", "[", "2", "]", ")", ",", "(", "sqw", "-", "sqx", "-", "sqy", "+", "sqz", ")", ")", "v", "[", "1", "]", "=", "Math", ".", "asin", "(", "clamp", "(", "2", "*", "(", "q", "[", "0", "]", "*", "q", "[", "2", "]", "+", "q", "[", "1", "]", "*", "q", "[", "3", "]", ")", ",", "-", "1", ",", "1", ")", ")", "v", "[", "2", "]", "=", "Math", ".", "atan2", "(", "2", "*", "(", "q", "[", "2", "]", "*", "q", "[", "3", "]", "-", "q", "[", "0", "]", "*", "q", "[", "1", "]", ")", ",", "(", "sqw", "+", "sqx", "-", "sqy", "-", "sqz", ")", ")", "return", "v", "}" ]
assumes XYZ order
[ "assumes", "XYZ", "order" ]
9069753b0e0076a79d6337d8e98469ec2fd89f05
https://github.com/pex-gl/pex-math/blob/9069753b0e0076a79d6337d8e98469ec2fd89f05/euler.js#L7-L16
train
baby-loris/bla
blocks/bla/bla.js
sendAjaxRequest
function sendAjaxRequest(url, data, execOptions) { var xhr = new XMLHttpRequest(); var d = vow.defer(); xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { d.resolve(JSON.parse(xhr.responseText)); } else { d.reject(xhr); } } }; xhr.ontimeout = function () { d.reject(new ApiError(ApiError.TIMEOUT, 'Timeout was reached while waiting for ' + url)); xhr.abort(); }; // shim for browsers which don't support timeout/ontimeout if (typeof xhr.timeout !== 'number' && execOptions.timeout) { var timeoutId = setTimeout(xhr.ontimeout.bind(xhr), execOptions.timeout); var oldHandler = xhr.onreadystatechange; xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE) { clearTimeout(timeoutId); } oldHandler(); }; } xhr.open('POST', url, true); xhr.timeout = execOptions.timeout; xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01'); xhr.setRequestHeader('Content-type', 'application/json'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(data); return d.promise(); }
javascript
function sendAjaxRequest(url, data, execOptions) { var xhr = new XMLHttpRequest(); var d = vow.defer(); xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { d.resolve(JSON.parse(xhr.responseText)); } else { d.reject(xhr); } } }; xhr.ontimeout = function () { d.reject(new ApiError(ApiError.TIMEOUT, 'Timeout was reached while waiting for ' + url)); xhr.abort(); }; // shim for browsers which don't support timeout/ontimeout if (typeof xhr.timeout !== 'number' && execOptions.timeout) { var timeoutId = setTimeout(xhr.ontimeout.bind(xhr), execOptions.timeout); var oldHandler = xhr.onreadystatechange; xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE) { clearTimeout(timeoutId); } oldHandler(); }; } xhr.open('POST', url, true); xhr.timeout = execOptions.timeout; xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01'); xhr.setRequestHeader('Content-type', 'application/json'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(data); return d.promise(); }
[ "function", "sendAjaxRequest", "(", "url", ",", "data", ",", "execOptions", ")", "{", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "var", "d", "=", "vow", ".", "defer", "(", ")", ";", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "===", "XMLHttpRequest", ".", "DONE", ")", "{", "if", "(", "xhr", ".", "status", "===", "200", ")", "{", "d", ".", "resolve", "(", "JSON", ".", "parse", "(", "xhr", ".", "responseText", ")", ")", ";", "}", "else", "{", "d", ".", "reject", "(", "xhr", ")", ";", "}", "}", "}", ";", "xhr", ".", "ontimeout", "=", "function", "(", ")", "{", "d", ".", "reject", "(", "new", "ApiError", "(", "ApiError", ".", "TIMEOUT", ",", "'Timeout was reached while waiting for '", "+", "url", ")", ")", ";", "xhr", ".", "abort", "(", ")", ";", "}", ";", "if", "(", "typeof", "xhr", ".", "timeout", "!==", "'number'", "&&", "execOptions", ".", "timeout", ")", "{", "var", "timeoutId", "=", "setTimeout", "(", "xhr", ".", "ontimeout", ".", "bind", "(", "xhr", ")", ",", "execOptions", ".", "timeout", ")", ";", "var", "oldHandler", "=", "xhr", ".", "onreadystatechange", ";", "xhr", ".", "onreadystatechange", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "readyState", "===", "XMLHttpRequest", ".", "DONE", ")", "{", "clearTimeout", "(", "timeoutId", ")", ";", "}", "oldHandler", "(", ")", ";", "}", ";", "}", "xhr", ".", "open", "(", "'POST'", ",", "url", ",", "true", ")", ";", "xhr", ".", "timeout", "=", "execOptions", ".", "timeout", ";", "xhr", ".", "setRequestHeader", "(", "'Accept'", ",", "'application/json, text/javascript, */*; q=0.01'", ")", ";", "xhr", ".", "setRequestHeader", "(", "'Content-type'", ",", "'application/json'", ")", ";", "xhr", ".", "setRequestHeader", "(", "'X-Requested-With'", ",", "'XMLHttpRequest'", ")", ";", "xhr", ".", "send", "(", "data", ")", ";", "return", "d", ".", "promise", "(", ")", ";", "}" ]
Makes an ajax request. @param {String} url A string containing the URL to which the request is sent. @param {String} data Data to be sent to the server. @param {Object} execOptions Exec-specific options. @param {Number} execOptions.timeout Request timeout. @returns {vow.Promise}
[ "Makes", "an", "ajax", "request", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L20-L57
train
baby-loris/bla
blocks/bla/bla.js
Api
function Api(basePath, options) { this._basePath = basePath; options = options || {}; this._options = { enableBatching: options.hasOwnProperty('enableBatching') ? options.enableBatching : true, timeout: options.timeout || 0 }; this._batch = []; this._deferreds = {}; }
javascript
function Api(basePath, options) { this._basePath = basePath; options = options || {}; this._options = { enableBatching: options.hasOwnProperty('enableBatching') ? options.enableBatching : true, timeout: options.timeout || 0 }; this._batch = []; this._deferreds = {}; }
[ "function", "Api", "(", "basePath", ",", "options", ")", "{", "this", ".", "_basePath", "=", "basePath", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_options", "=", "{", "enableBatching", ":", "options", ".", "hasOwnProperty", "(", "'enableBatching'", ")", "?", "options", ".", "enableBatching", ":", "true", ",", "timeout", ":", "options", ".", "timeout", "||", "0", "}", ";", "this", ".", "_batch", "=", "[", "]", ";", "this", ".", "_deferreds", "=", "{", "}", ";", "}" ]
Api provider. @param {String} basePath Url path to the middleware root. @param {Object} [options] Extra options. @param {Boolean} [options.enableBatching=true] Enables batching. @param {Number} [options.timeout=0] Global timeout for all requests.
[ "Api", "provider", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L67-L78
train
baby-loris/bla
blocks/bla/bla.js
function (methodName, params, execOptions) { execOptions = execOptions || {}; var options = { enableBatching: execOptions.hasOwnProperty('enableBatching') ? execOptions.enableBatching : this._options.enableBatching, timeout: execOptions.timeout || this._options.timeout }; return options.enableBatching ? this._execWithBatching(methodName, params, options) : this._execWithoutBatching(methodName, params, options); }
javascript
function (methodName, params, execOptions) { execOptions = execOptions || {}; var options = { enableBatching: execOptions.hasOwnProperty('enableBatching') ? execOptions.enableBatching : this._options.enableBatching, timeout: execOptions.timeout || this._options.timeout }; return options.enableBatching ? this._execWithBatching(methodName, params, options) : this._execWithoutBatching(methodName, params, options); }
[ "function", "(", "methodName", ",", "params", ",", "execOptions", ")", "{", "execOptions", "=", "execOptions", "||", "{", "}", ";", "var", "options", "=", "{", "enableBatching", ":", "execOptions", ".", "hasOwnProperty", "(", "'enableBatching'", ")", "?", "execOptions", ".", "enableBatching", ":", "this", ".", "_options", ".", "enableBatching", ",", "timeout", ":", "execOptions", ".", "timeout", "||", "this", ".", "_options", ".", "timeout", "}", ";", "return", "options", ".", "enableBatching", "?", "this", ".", "_execWithBatching", "(", "methodName", ",", "params", ",", "options", ")", ":", "this", ".", "_execWithoutBatching", "(", "methodName", ",", "params", ",", "options", ")", ";", "}" ]
Executes api by path with specified parameters. @param {String} methodName Method name. @param {Object} params Data should be sent to the method. @param {Object} [execOptions] Exec-specific options. @param {Boolean} [execOptions.enableBatching=true] Should the current call of the method be batched. method be batched. @param {Number} [execOptions.timeout=0] Request timeout. @returns {vow.Promise}
[ "Executes", "api", "by", "path", "with", "specified", "parameters", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L94-L107
train
baby-loris/bla
blocks/bla/bla.js
function (methodName, params, execOptions) { var defer = vow.defer(); var url = this._basePath + methodName; var data = JSON.stringify(params); sendAjaxRequest(url, data, execOptions).then( this._resolvePromise.bind(this, defer), this._rejectPromise.bind(this, defer) ); return defer.promise(); }
javascript
function (methodName, params, execOptions) { var defer = vow.defer(); var url = this._basePath + methodName; var data = JSON.stringify(params); sendAjaxRequest(url, data, execOptions).then( this._resolvePromise.bind(this, defer), this._rejectPromise.bind(this, defer) ); return defer.promise(); }
[ "function", "(", "methodName", ",", "params", ",", "execOptions", ")", "{", "var", "defer", "=", "vow", ".", "defer", "(", ")", ";", "var", "url", "=", "this", ".", "_basePath", "+", "methodName", ";", "var", "data", "=", "JSON", ".", "stringify", "(", "params", ")", ";", "sendAjaxRequest", "(", "url", ",", "data", ",", "execOptions", ")", ".", "then", "(", "this", ".", "_resolvePromise", ".", "bind", "(", "this", ",", "defer", ")", ",", "this", ".", "_rejectPromise", ".", "bind", "(", "this", ",", "defer", ")", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}" ]
Executes method immediately. @param {String} methodName Method name. @param {Object} params Data should be sent to the method. @param {Object} execOptions Exec-specific options. @returns {vow.Promise}
[ "Executes", "method", "immediately", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L117-L128
train
baby-loris/bla
blocks/bla/bla.js
function (methodName, params, execOptions) { var requestId = this._getRequestId(methodName, params); var promise = this._getRequestPromise(requestId); if (!promise) { this._addToBatch(methodName, params); promise = this._createPromise(requestId); this._run(execOptions); } return promise; }
javascript
function (methodName, params, execOptions) { var requestId = this._getRequestId(methodName, params); var promise = this._getRequestPromise(requestId); if (!promise) { this._addToBatch(methodName, params); promise = this._createPromise(requestId); this._run(execOptions); } return promise; }
[ "function", "(", "methodName", ",", "params", ",", "execOptions", ")", "{", "var", "requestId", "=", "this", ".", "_getRequestId", "(", "methodName", ",", "params", ")", ";", "var", "promise", "=", "this", ".", "_getRequestPromise", "(", "requestId", ")", ";", "if", "(", "!", "promise", ")", "{", "this", ".", "_addToBatch", "(", "methodName", ",", "params", ")", ";", "promise", "=", "this", ".", "_createPromise", "(", "requestId", ")", ";", "this", ".", "_run", "(", "execOptions", ")", ";", "}", "return", "promise", ";", "}" ]
Executes method with a little delay, adding it to batch. @param {String} methodName Method name. @param {Object} params Data should be sent to the method. @param {Object} execOptions Exec-specific options. @returns {vow.Promise}
[ "Executes", "method", "with", "a", "little", "delay", "adding", "it", "to", "batch", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L138-L149
train
baby-loris/bla
blocks/bla/bla.js
function (execOptions) { var url = this._basePath + 'batch'; var data = JSON.stringify({methods: this._batch}); sendAjaxRequest(url, data, execOptions).then( this._resolvePromises.bind(this, this._batch), this._rejectPromises.bind(this, this._batch) ); this._batch = []; }
javascript
function (execOptions) { var url = this._basePath + 'batch'; var data = JSON.stringify({methods: this._batch}); sendAjaxRequest(url, data, execOptions).then( this._resolvePromises.bind(this, this._batch), this._rejectPromises.bind(this, this._batch) ); this._batch = []; }
[ "function", "(", "execOptions", ")", "{", "var", "url", "=", "this", ".", "_basePath", "+", "'batch'", ";", "var", "data", "=", "JSON", ".", "stringify", "(", "{", "methods", ":", "this", ".", "_batch", "}", ")", ";", "sendAjaxRequest", "(", "url", ",", "data", ",", "execOptions", ")", ".", "then", "(", "this", ".", "_resolvePromises", ".", "bind", "(", "this", ",", "this", ".", "_batch", ")", ",", "this", ".", "_rejectPromises", ".", "bind", "(", "this", ",", "this", ".", "_batch", ")", ")", ";", "this", ".", "_batch", "=", "[", "]", ";", "}" ]
Performs batch request. @param {Object} execOptions Exec-specific options.
[ "Performs", "batch", "request", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L217-L226
train
baby-loris/bla
blocks/bla/bla.js
function (defer, response) { var error = response.error; if (error) { defer.reject(new ApiError(error.type, error.message, error.data)); } else { defer.resolve(response.data); } }
javascript
function (defer, response) { var error = response.error; if (error) { defer.reject(new ApiError(error.type, error.message, error.data)); } else { defer.resolve(response.data); } }
[ "function", "(", "defer", ",", "response", ")", "{", "var", "error", "=", "response", ".", "error", ";", "if", "(", "error", ")", "{", "defer", ".", "reject", "(", "new", "ApiError", "(", "error", ".", "type", ",", "error", ".", "message", ",", "error", ".", "data", ")", ")", ";", "}", "else", "{", "defer", ".", "resolve", "(", "response", ".", "data", ")", ";", "}", "}" ]
Resolve deferred promise. @param {vow.Deferred} defer @param {Object} response Server response.
[ "Resolve", "deferred", "promise", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L234-L241
train
baby-loris/bla
blocks/bla/bla.js
function (batch, response) { var data = response.data; for (var i = 0, requestId; i < batch.length; i++) { requestId = this._getRequestId(batch[i].method, batch[i].params); this._resolvePromise(this._deferreds[requestId], data[i]); delete this._deferreds[requestId]; } }
javascript
function (batch, response) { var data = response.data; for (var i = 0, requestId; i < batch.length; i++) { requestId = this._getRequestId(batch[i].method, batch[i].params); this._resolvePromise(this._deferreds[requestId], data[i]); delete this._deferreds[requestId]; } }
[ "function", "(", "batch", ",", "response", ")", "{", "var", "data", "=", "response", ".", "data", ";", "for", "(", "var", "i", "=", "0", ",", "requestId", ";", "i", "<", "batch", ".", "length", ";", "i", "++", ")", "{", "requestId", "=", "this", ".", "_getRequestId", "(", "batch", "[", "i", "]", ".", "method", ",", "batch", "[", "i", "]", ".", "params", ")", ";", "this", ".", "_resolvePromise", "(", "this", ".", "_deferreds", "[", "requestId", "]", ",", "data", "[", "i", "]", ")", ";", "delete", "this", ".", "_deferreds", "[", "requestId", "]", ";", "}", "}" ]
Resolves deferred promises. @param {Object[]} batch Batch request data. @param {Object} response Server response.
[ "Resolves", "deferred", "promises", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L249-L256
train
baby-loris/bla
blocks/bla/bla.js
function (defer, xhr) { var errorType = xhr.type || xhr.status; var errorMessage = xhr.responseText || xhr.message || xhr.statusText; defer.reject(new ApiError(errorType, errorMessage)); }
javascript
function (defer, xhr) { var errorType = xhr.type || xhr.status; var errorMessage = xhr.responseText || xhr.message || xhr.statusText; defer.reject(new ApiError(errorType, errorMessage)); }
[ "function", "(", "defer", ",", "xhr", ")", "{", "var", "errorType", "=", "xhr", ".", "type", "||", "xhr", ".", "status", ";", "var", "errorMessage", "=", "xhr", ".", "responseText", "||", "xhr", ".", "message", "||", "xhr", ".", "statusText", ";", "defer", ".", "reject", "(", "new", "ApiError", "(", "errorType", ",", "errorMessage", ")", ")", ";", "}" ]
Rejects deferred promise. @param {vow.Deferred} defer @param {XMLHttpRequest} xhr
[ "Rejects", "deferred", "promise", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L264-L268
train
baby-loris/bla
blocks/bla/bla.js
function (batch, xhr) { for (var i = 0, requestId; i < batch.length; i++) { requestId = this._getRequestId(batch[i].method, batch[i].params); this._rejectPromise(this._deferreds[requestId], xhr); delete this._deferreds[requestId]; } }
javascript
function (batch, xhr) { for (var i = 0, requestId; i < batch.length; i++) { requestId = this._getRequestId(batch[i].method, batch[i].params); this._rejectPromise(this._deferreds[requestId], xhr); delete this._deferreds[requestId]; } }
[ "function", "(", "batch", ",", "xhr", ")", "{", "for", "(", "var", "i", "=", "0", ",", "requestId", ";", "i", "<", "batch", ".", "length", ";", "i", "++", ")", "{", "requestId", "=", "this", ".", "_getRequestId", "(", "batch", "[", "i", "]", ".", "method", ",", "batch", "[", "i", "]", ".", "params", ")", ";", "this", ".", "_rejectPromise", "(", "this", ".", "_deferreds", "[", "requestId", "]", ",", "xhr", ")", ";", "delete", "this", ".", "_deferreds", "[", "requestId", "]", ";", "}", "}" ]
Rejects deferred promises. @param {Object[]} batch Batch request data. @param {XMLHttpRequest} xhr
[ "Rejects", "deferred", "promises", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/blocks/bla/bla.js#L276-L282
train
bitnami/nami-utils
lib/file/append.js
append
function append(file, text, options) { options = _.sanitize(options, {atNewLine: false, encoding: 'utf-8'}); if (!exists(file)) { write(file, text, {encoding: options.encoding}); } else { if (options.atNewLine && !text.match(/^\n/) && exists(file)) text = `\n${text}`; fs.appendFileSync(file, text, {encoding: options.encoding}); } }
javascript
function append(file, text, options) { options = _.sanitize(options, {atNewLine: false, encoding: 'utf-8'}); if (!exists(file)) { write(file, text, {encoding: options.encoding}); } else { if (options.atNewLine && !text.match(/^\n/) && exists(file)) text = `\n${text}`; fs.appendFileSync(file, text, {encoding: options.encoding}); } }
[ "function", "append", "(", "file", ",", "text", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "atNewLine", ":", "false", ",", "encoding", ":", "'utf-8'", "}", ")", ";", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "write", "(", "file", ",", "text", ",", "{", "encoding", ":", "options", ".", "encoding", "}", ")", ";", "}", "else", "{", "if", "(", "options", ".", "atNewLine", "&&", "!", "text", ".", "match", "(", "/", "^\\n", "/", ")", "&&", "exists", "(", "file", ")", ")", "text", "=", "`", "\\n", "${", "text", "}", "`", ";", "fs", ".", "appendFileSync", "(", "file", ",", "text", ",", "{", "encoding", ":", "options", ".", "encoding", "}", ")", ";", "}", "}" ]
Add text to file @function $file~append @param {string} file - File to add text to @param {string} text - Text to add @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read/write the file @param {boolean} [options.atNewLine=false] - Force the added text to start at a new line @example // Append new lines to 'Changelog' file $file.append('Changelog', 'Added new plugins');
[ "Add", "text", "to", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/append.js#L20-L29
train
baby-loris/bla
tools/release.js
vowExec
function vowExec(cmd) { var defer = vow.defer(); exec(cmd, function (err, stdout, stderr) { if (err) { defer.reject({err: err, stderr: stderr}); } else { defer.resolve(stdout.trim()); } }); return defer.promise(); }
javascript
function vowExec(cmd) { var defer = vow.defer(); exec(cmd, function (err, stdout, stderr) { if (err) { defer.reject({err: err, stderr: stderr}); } else { defer.resolve(stdout.trim()); } }); return defer.promise(); }
[ "function", "vowExec", "(", "cmd", ")", "{", "var", "defer", "=", "vow", ".", "defer", "(", ")", ";", "exec", "(", "cmd", ",", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "err", ")", "{", "defer", ".", "reject", "(", "{", "err", ":", "err", ",", "stderr", ":", "stderr", "}", ")", ";", "}", "else", "{", "defer", ".", "resolve", "(", "stdout", ".", "trim", "(", ")", ")", ";", "}", "}", ")", ";", "return", "defer", ".", "promise", "(", ")", ";", "}" ]
Runs a command. @param {String} cmd The command to be run. @returns {vow.Promise} Promise that will be fulfilled when the command exits with 0 return code and rejected if return code is non-zero.
[ "Runs", "a", "command", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/tools/release.js#L38-L48
train
baby-loris/bla
tools/release.js
compareVersions
function compareVersions(fstVer, sndVer) { if (semver.lt(fstVer, sndVer)) { return 1; } if (semver.gt(fstVer, sndVer)) { return -1; } return 0; }
javascript
function compareVersions(fstVer, sndVer) { if (semver.lt(fstVer, sndVer)) { return 1; } if (semver.gt(fstVer, sndVer)) { return -1; } return 0; }
[ "function", "compareVersions", "(", "fstVer", ",", "sndVer", ")", "{", "if", "(", "semver", ".", "lt", "(", "fstVer", ",", "sndVer", ")", ")", "{", "return", "1", ";", "}", "if", "(", "semver", ".", "gt", "(", "fstVer", ",", "sndVer", ")", ")", "{", "return", "-", "1", ";", "}", "return", "0", ";", "}" ]
Compares to semver versions. @param {String} fstVer @param {String} sndVer @returns {Number} -1 if fstVer if older than sndVer, 1 if newer and 0 if versions are equal.
[ "Compares", "to", "semver", "versions", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/tools/release.js#L95-L103
train
baby-loris/bla
tools/release.js
commitAllChanges
function commitAllChanges(msg) { return vowExec(util.format('git commit -a -m "%s" -n', msg)) .fail(function (res) { return vow.reject('Commit failed:\n' + res.stderr); }); }
javascript
function commitAllChanges(msg) { return vowExec(util.format('git commit -a -m "%s" -n', msg)) .fail(function (res) { return vow.reject('Commit failed:\n' + res.stderr); }); }
[ "function", "commitAllChanges", "(", "msg", ")", "{", "return", "vowExec", "(", "util", ".", "format", "(", "'git commit -a -m \"%s\" -n'", ",", "msg", ")", ")", ".", "fail", "(", "function", "(", "res", ")", "{", "return", "vow", ".", "reject", "(", "'Commit failed:\\n'", "+", "\\n", ")", ";", "}", ")", ";", "}" ]
Commits changes in tracked files. @param {String} msg Commit message. @returns {vow.Promise} Promise that'll be fulfilled on success.
[ "Commits", "changes", "in", "tracked", "files", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/tools/release.js#L130-L135
train
baby-loris/bla
tools/release.js
changelog
function changelog(from, to) { return vowExec(util.format('git log --format="%%s" %s..%s', from, to)) .then(function (stdout) { return stdout.split('\n'); }); }
javascript
function changelog(from, to) { return vowExec(util.format('git log --format="%%s" %s..%s', from, to)) .then(function (stdout) { return stdout.split('\n'); }); }
[ "function", "changelog", "(", "from", ",", "to", ")", "{", "return", "vowExec", "(", "util", ".", "format", "(", "'git log --format=\"%%s\" %s..%s'", ",", "from", ",", "to", ")", ")", ".", "then", "(", "function", "(", "stdout", ")", "{", "return", "stdout", ".", "split", "(", "'\\n'", ")", ";", "}", ")", ";", "}" ]
Extracts changes from git history. @param {String} from Reference to a point in the history, starting from which changes will be extracted. Starting point will be the very first commit if an empty string's provided. @param {String} to Reference to a point in the history, up to which changes will be extracted. If an empty string's provided change'll include all commits after the starting point. @param {vow.Promise} Promise that'll be fulfilled with an array of commits' subject strings.
[ "Extracts", "changes", "from", "git", "history", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/tools/release.js#L149-L154
train
baby-loris/bla
tools/release.js
mdLogEntry
function mdLogEntry(version, log) { return util.format( '### %s\n%s\n\n', version, log.map(function (logItem) { return ' * ' + logItem; }).join('\n') ); }
javascript
function mdLogEntry(version, log) { return util.format( '### %s\n%s\n\n', version, log.map(function (logItem) { return ' * ' + logItem; }).join('\n') ); }
[ "function", "mdLogEntry", "(", "version", ",", "log", ")", "{", "return", "util", ".", "format", "(", "'### %s\\n%s\\n\\n'", ",", "\\n", ",", "\\n", ")", ";", "}" ]
Generates markdown text for new a changelog entry. @param {String} version Version of the entry. @param {String[]} log Changes in the new version. @param {String} Markdown.
[ "Generates", "markdown", "text", "for", "new", "a", "changelog", "entry", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/tools/release.js#L163-L171
train
bitnami/nami-utils
lib/file/ini/set.js
iniFileSet
function iniFileSet(file, section, key, value, options) { options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true}); if (typeof key === 'object') { if (typeof value === 'object') { options = value; } else { options = {}; } } if (!exists(file)) { touch(file, '', options); } else if (!isFile(file)) { throw new Error(`File ${file} is not a file`); } const config = ini.parse(read(file, {encoding: options.encoding})); if (!_.isEmpty(section)) { config[section] = config[section] || {}; section = config[section]; } else { section = config; } if (typeof key === 'string') { section[key] = value; } else { _.merge(section, key); } write(file, ini.stringify(config), options); }
javascript
function iniFileSet(file, section, key, value, options) { options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true}); if (typeof key === 'object') { if (typeof value === 'object') { options = value; } else { options = {}; } } if (!exists(file)) { touch(file, '', options); } else if (!isFile(file)) { throw new Error(`File ${file} is not a file`); } const config = ini.parse(read(file, {encoding: options.encoding})); if (!_.isEmpty(section)) { config[section] = config[section] || {}; section = config[section]; } else { section = config; } if (typeof key === 'string') { section[key] = value; } else { _.merge(section, key); } write(file, ini.stringify(config), options); }
[ "function", "iniFileSet", "(", "file", ",", "section", ",", "key", ",", "value", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "encoding", ":", "'utf-8'", ",", "retryOnENOENT", ":", "true", "}", ")", ";", "if", "(", "typeof", "key", "===", "'object'", ")", "{", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "options", "=", "value", ";", "}", "else", "{", "options", "=", "{", "}", ";", "}", "}", "if", "(", "!", "exists", "(", "file", ")", ")", "{", "touch", "(", "file", ",", "''", ",", "options", ")", ";", "}", "else", "if", "(", "!", "isFile", "(", "file", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "file", "}", "`", ")", ";", "}", "const", "config", "=", "ini", ".", "parse", "(", "read", "(", "file", ",", "{", "encoding", ":", "options", ".", "encoding", "}", ")", ")", ";", "if", "(", "!", "_", ".", "isEmpty", "(", "section", ")", ")", "{", "config", "[", "section", "]", "=", "config", "[", "section", "]", "||", "{", "}", ";", "section", "=", "config", "[", "section", "]", ";", "}", "else", "{", "section", "=", "config", ";", "}", "if", "(", "typeof", "key", "===", "'string'", ")", "{", "section", "[", "key", "]", "=", "value", ";", "}", "else", "{", "_", ".", "merge", "(", "section", ",", "key", ")", ";", "}", "write", "(", "file", ",", "ini", ".", "stringify", "(", "config", ")", ",", "options", ")", ";", "}" ]
Set value in ini file @function $file~ini/set @param {string} file - Ini File to write the value to @param {string} section - Section in which to add the key (null if global section) @param {string} key @param {string} value @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @param {boolean} [options.retryOnENOENT=true] - Retry if writing files because of the parent directory does not exists @throws Will throw an error if the path is not a file @example // Set a single property 'opcache.enable' under the 'opcache' section to 1 $file.ini.set('etc/php.ini', 'opcache', 'opcache.enable', 1); Set value in ini file @function $file~ini/set² @param {string} file - Ini File to write the value to @param {string} section - Section in which to add the key (null if global section) @param {Object} keyMapping - key-value map to set in the file @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @param {boolean} [options.retryOnENOENT=true] - Retry if writing files because of the parent directory does not exists @throws Will throw an error if the path is not a file @example // Set several properties under the 'opcache' section to 1 $file.ini.set('etc/php.ini', 'opcache', {'opcache.enable': 1, 'opcache.enable_cli': 1});
[ "Set", "value", "in", "ini", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/ini/set.js#L44-L71
train
bitnami/nami-utils
lib/file/puts.js
puts
function puts(file, text, options) { options = _.sanitize(options, {atNewLine: false, encoding: 'utf-8'}); append(file, `${text}\n`, options); }
javascript
function puts(file, text, options) { options = _.sanitize(options, {atNewLine: false, encoding: 'utf-8'}); append(file, `${text}\n`, options); }
[ "function", "puts", "(", "file", ",", "text", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "atNewLine", ":", "false", ",", "encoding", ":", "'utf-8'", "}", ")", ";", "append", "(", "file", ",", "`", "${", "text", "}", "\\n", "`", ",", "options", ")", ";", "}" ]
Add new text to a file with a trailing new line. @function $file~puts @param {string} file - File to 'echo' text into @param {string} text - Text to add @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read/write the file @param {boolean} [options.atNewLine=false] - Force the added text to start at a new line @example // Append new lines to 'Changelog' file $file.puts('Changelog', 'Added new plugins'); // Append multiple entries to a 'Changelog' file with extra new line $file.puts('Changelog', 'Added new plugins'); $file.puts('Changelog', 'Updated to 5.3.2'); $file.puts('Changelog', 'Fixed documentation typo'); // Added new plugins // Updated to 5.3.2 // Fixed documentation typo
[ "Add", "new", "text", "to", "a", "file", "with", "a", "trailing", "new", "line", "." ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/puts.js#L25-L28
train
baby-loris/bla
examples/api/get-kittens.api.js
getPhotoUrl
function getPhotoUrl(data) { return FLICK_PHOTO_URL_TEMPLATE .replace('{farm-id}', data.farm) .replace('{server-id}', data.server) .replace('{id}', data.id) .replace('{secret}', data.secret) .replace('{size}', 'm'); }
javascript
function getPhotoUrl(data) { return FLICK_PHOTO_URL_TEMPLATE .replace('{farm-id}', data.farm) .replace('{server-id}', data.server) .replace('{id}', data.id) .replace('{secret}', data.secret) .replace('{size}', 'm'); }
[ "function", "getPhotoUrl", "(", "data", ")", "{", "return", "FLICK_PHOTO_URL_TEMPLATE", ".", "replace", "(", "'{farm-id}'", ",", "data", ".", "farm", ")", ".", "replace", "(", "'{server-id}'", ",", "data", ".", "server", ")", ".", "replace", "(", "'{id}'", ",", "data", ".", "id", ")", ".", "replace", "(", "'{secret}'", ",", "data", ".", "secret", ")", ".", "replace", "(", "'{size}'", ",", "'m'", ")", ";", "}" ]
Build url for a photo. @see ../../tests/examples/api/get-kittens.test.js Tests for the API method. @param {Object} data Data for the flickr photo. @return {String}
[ "Build", "url", "for", "a", "photo", "." ]
d40bdfc4991ce4758345989df18d44543e064509
https://github.com/baby-loris/bla/blob/d40bdfc4991ce4758345989df18d44543e064509/examples/api/get-kittens.api.js#L14-L21
train
bitnami/nami-utils
lib/file/link.js
link
function link(target, location, options) { options = _.sanitize(options, {force: false}); if (options.force && isLink(location)) { fileDelete(location); } if (!path.isAbsolute(target)) { const cwd = process.cwd(); process.chdir(path.dirname(location)); try { fs.symlinkSync(target, path.basename(location)); } finally { try { process.chdir(cwd); } catch (e) { /* not empty */ } } } else { fs.symlinkSync(target, location); } }
javascript
function link(target, location, options) { options = _.sanitize(options, {force: false}); if (options.force && isLink(location)) { fileDelete(location); } if (!path.isAbsolute(target)) { const cwd = process.cwd(); process.chdir(path.dirname(location)); try { fs.symlinkSync(target, path.basename(location)); } finally { try { process.chdir(cwd); } catch (e) { /* not empty */ } } } else { fs.symlinkSync(target, location); } }
[ "function", "link", "(", "target", ",", "location", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "force", ":", "false", "}", ")", ";", "if", "(", "options", ".", "force", "&&", "isLink", "(", "location", ")", ")", "{", "fileDelete", "(", "location", ")", ";", "}", "if", "(", "!", "path", ".", "isAbsolute", "(", "target", ")", ")", "{", "const", "cwd", "=", "process", ".", "cwd", "(", ")", ";", "process", ".", "chdir", "(", "path", ".", "dirname", "(", "location", ")", ")", ";", "try", "{", "fs", ".", "symlinkSync", "(", "target", ",", "path", ".", "basename", "(", "location", ")", ")", ";", "}", "finally", "{", "try", "{", "process", ".", "chdir", "(", "cwd", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "}", "else", "{", "fs", ".", "symlinkSync", "(", "target", ",", "location", ")", ";", "}", "}" ]
Create symbolic link @function $file~link @param {string} target - Target of the link @param {string} location - Location of the link @param {Object} [options] @param {boolean} [options.force=false] - Force creation of the link even if it already exists @example // Create a symbolic link 'libsample.so' pointing to '/usr/lib/libsample.so.1' $file.link('/usr/lib/libsample.so.1', 'libsample.so');
[ "Create", "symbolic", "link" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/link.js#L20-L36
train
LaunchPadLab/lp-requests
src/http/middleware/set-defaults.js
setDefaults
function setDefaults ({ headers={}, overrideHeaders=false, ...rest }) { return { ...DEFAULTS, headers: overrideHeaders ? headers : { ...DEFAULT_HEADERS, ...headers }, ...rest, } }
javascript
function setDefaults ({ headers={}, overrideHeaders=false, ...rest }) { return { ...DEFAULTS, headers: overrideHeaders ? headers : { ...DEFAULT_HEADERS, ...headers }, ...rest, } }
[ "function", "setDefaults", "(", "{", "headers", "=", "{", "}", ",", "overrideHeaders", "=", "false", ",", "...", "rest", "}", ")", "{", "return", "{", "...", "DEFAULTS", ",", "headers", ":", "overrideHeaders", "?", "headers", ":", "{", "...", "DEFAULT_HEADERS", ",", "...", "headers", "}", ",", "...", "rest", ",", "}", "}" ]
Sets default request options
[ "Sets", "default", "request", "options" ]
139294b1594b2d62ba8403c9ac6e97d5e84961f3
https://github.com/LaunchPadLab/lp-requests/blob/139294b1594b2d62ba8403c9ac6e97d5e84961f3/src/http/middleware/set-defaults.js#L20-L26
train
bitnami/nami-utils
lib/os/user-management/delete-user.js
deleteUser
function deleteUser(user) { if (!runningAsRoot()) return; if (!user) throw new Error('You must provide an username'); if (!userExists(user)) { return; } const userdelBin = _safeLocateBinary('userdel'); const deluserBin = _safeLocateBinary('deluser'); if (isPlatform('linux')) { if (userdelBin !== null) { // most modern systems runProgram(userdelBin, [user]); } else { if (_isBusyboxBinary(deluserBin)) { // busybox-based systems runProgram(deluserBin, [user]); } else { throw new Error(`Don't know how to delete user ${user} on this strange linux`); } } } else if (isPlatform('osx')) { runProgram('dscl', ['.', '-delete', `/Users/${user}`]); } else if (isPlatform('windows')) { throw new Error('Don\'t know how to delete user in Windows'); } else { throw new Error('Don\'t know how to delete user in current platform'); } }
javascript
function deleteUser(user) { if (!runningAsRoot()) return; if (!user) throw new Error('You must provide an username'); if (!userExists(user)) { return; } const userdelBin = _safeLocateBinary('userdel'); const deluserBin = _safeLocateBinary('deluser'); if (isPlatform('linux')) { if (userdelBin !== null) { // most modern systems runProgram(userdelBin, [user]); } else { if (_isBusyboxBinary(deluserBin)) { // busybox-based systems runProgram(deluserBin, [user]); } else { throw new Error(`Don't know how to delete user ${user} on this strange linux`); } } } else if (isPlatform('osx')) { runProgram('dscl', ['.', '-delete', `/Users/${user}`]); } else if (isPlatform('windows')) { throw new Error('Don\'t know how to delete user in Windows'); } else { throw new Error('Don\'t know how to delete user in current platform'); } }
[ "function", "deleteUser", "(", "user", ")", "{", "if", "(", "!", "runningAsRoot", "(", ")", ")", "return", ";", "if", "(", "!", "user", ")", "throw", "new", "Error", "(", "'You must provide an username'", ")", ";", "if", "(", "!", "userExists", "(", "user", ")", ")", "{", "return", ";", "}", "const", "userdelBin", "=", "_safeLocateBinary", "(", "'userdel'", ")", ";", "const", "deluserBin", "=", "_safeLocateBinary", "(", "'deluser'", ")", ";", "if", "(", "isPlatform", "(", "'linux'", ")", ")", "{", "if", "(", "userdelBin", "!==", "null", ")", "{", "runProgram", "(", "userdelBin", ",", "[", "user", "]", ")", ";", "}", "else", "{", "if", "(", "_isBusyboxBinary", "(", "deluserBin", ")", ")", "{", "runProgram", "(", "deluserBin", ",", "[", "user", "]", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "`", "${", "user", "}", "`", ")", ";", "}", "}", "}", "else", "if", "(", "isPlatform", "(", "'osx'", ")", ")", "{", "runProgram", "(", "'dscl'", ",", "[", "'.'", ",", "'-delete'", ",", "`", "${", "user", "}", "`", "]", ")", ";", "}", "else", "if", "(", "isPlatform", "(", "'windows'", ")", ")", "{", "throw", "new", "Error", "(", "'Don\\'t know how to delete user in Windows'", ")", ";", "}", "else", "\\'", "}" ]
Delete system user @function $os~deleteUser @param {string|number} user - Username or user id @example // Delete mysql user $os.deleteUser('mysql');
[ "Delete", "system", "user" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/delete-user.js#L18-L44
train
bitnami/nami-utils
lib/common.js
lookForBinary
function lookForBinary(binary, pathList) { let envPath = _.toArrayIfNeeded(pathList); if (_.isEmpty(envPath)) { envPath = (process.env.PATH || '').split(path.delimiter); } const foundPath = _.first(_.filter(envPath, (dir) => { return fileExists(path.join(dir, binary)); })); return foundPath ? path.join(foundPath, binary) : null; }
javascript
function lookForBinary(binary, pathList) { let envPath = _.toArrayIfNeeded(pathList); if (_.isEmpty(envPath)) { envPath = (process.env.PATH || '').split(path.delimiter); } const foundPath = _.first(_.filter(envPath, (dir) => { return fileExists(path.join(dir, binary)); })); return foundPath ? path.join(foundPath, binary) : null; }
[ "function", "lookForBinary", "(", "binary", ",", "pathList", ")", "{", "let", "envPath", "=", "_", ".", "toArrayIfNeeded", "(", "pathList", ")", ";", "if", "(", "_", ".", "isEmpty", "(", "envPath", ")", ")", "{", "envPath", "=", "(", "process", ".", "env", ".", "PATH", "||", "''", ")", ".", "split", "(", "path", ".", "delimiter", ")", ";", "}", "const", "foundPath", "=", "_", ".", "first", "(", "_", ".", "filter", "(", "envPath", ",", "(", "dir", ")", "=>", "{", "return", "fileExists", "(", "path", ".", "join", "(", "dir", ",", "binary", ")", ")", ";", "}", ")", ")", ";", "return", "foundPath", "?", "path", ".", "join", "(", "foundPath", ",", "binary", ")", ":", "null", ";", "}" ]
Get full path to a binary in the provided list of directories @function lookForBinary @private @param {string} binary - Binary to look for @param {string[]} [pathList] - List of directories in which to locate the binary. If it is not provided or is empty, the system PATH will be used @returns {string} - The full path to the binary or null if it is not in the PATH @example // Get the path of the 'node' binary in the System PATH lookForBinary('node'); => '/usr/local/bin/node'
[ "Get", "full", "path", "to", "a", "binary", "in", "the", "provided", "list", "of", "directories" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/common.js#L32-L41
train
cdapio/ui-schema-parser
lib/schemas.js
parse
function parse(str, opts) { var parser = new Parser(str, opts); return {attrs: parser._readProtocol(), imports: parser._imports}; }
javascript
function parse(str, opts) { var parser = new Parser(str, opts); return {attrs: parser._readProtocol(), imports: parser._imports}; }
[ "function", "parse", "(", "str", ",", "opts", ")", "{", "var", "parser", "=", "new", "Parser", "(", "str", ",", "opts", ")", ";", "return", "{", "attrs", ":", "parser", ".", "_readProtocol", "(", ")", ",", "imports", ":", "parser", ".", "_imports", "}", ";", "}" ]
Parse an IDL into attributes. Not to be confused with `avro.parse` which parses attributes into types.
[ "Parse", "an", "IDL", "into", "attributes", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/schemas.js#L150-L153
train
cdapio/ui-schema-parser
lib/schemas.js
Tokenizer
function Tokenizer(str) { this._str = str; this._pos = 0; this._queue = new BoundedQueue(3); // Bounded queue of last emitted tokens. this._token = undefined; // Current token. this._doc = undefined; // Javadoc. }
javascript
function Tokenizer(str) { this._str = str; this._pos = 0; this._queue = new BoundedQueue(3); // Bounded queue of last emitted tokens. this._token = undefined; // Current token. this._doc = undefined; // Javadoc. }
[ "function", "Tokenizer", "(", "str", ")", "{", "this", ".", "_str", "=", "str", ";", "this", ".", "_pos", "=", "0", ";", "this", ".", "_queue", "=", "new", "BoundedQueue", "(", "3", ")", ";", "this", ".", "_token", "=", "undefined", ";", "this", ".", "_doc", "=", "undefined", ";", "}" ]
Helpers. Simple class to split an input string into tokens. There are different types of tokens, characterized by their `id`: + `number` numbers. + `name` references. + `string` double-quoted. + `operator`, anything else, always single character. + `json`, special, must be asked for (the tokenizer doesn't have enough context to predict these). This tokenizer also handles Javadoc extraction, via the `addJavadoc` method.
[ "Helpers", ".", "Simple", "class", "to", "split", "an", "input", "string", "into", "tokens", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/schemas.js#L172-L178
train
cdapio/ui-schema-parser
lib/schemas.js
Parser
function Parser(str, opts) { this._oneWayVoid = !!(opts && opts.oneWayVoid); this._reassignJavadoc = !!(opts && opts.reassignJavadoc); this._imports = []; this._tk = new Tokenizer(str); this._tk.next(); // Prime tokenizer. }
javascript
function Parser(str, opts) { this._oneWayVoid = !!(opts && opts.oneWayVoid); this._reassignJavadoc = !!(opts && opts.reassignJavadoc); this._imports = []; this._tk = new Tokenizer(str); this._tk.next(); // Prime tokenizer. }
[ "function", "Parser", "(", "str", ",", "opts", ")", "{", "this", ".", "_oneWayVoid", "=", "!", "!", "(", "opts", "&&", "opts", ".", "oneWayVoid", ")", ";", "this", ".", "_reassignJavadoc", "=", "!", "!", "(", "opts", "&&", "opts", ".", "reassignJavadoc", ")", ";", "this", ".", "_imports", "=", "[", "]", ";", "this", ".", "_tk", "=", "new", "Tokenizer", "(", "str", ")", ";", "this", ".", "_tk", ".", "next", "(", ")", ";", "}" ]
Parser from tokens to attributes.
[ "Parser", "from", "tokens", "to", "attributes", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/schemas.js#L359-L365
train
cdapio/ui-schema-parser
lib/schemas.js
reassignJavadoc
function reassignJavadoc(from, to) { if (!(from.doc instanceof Javadoc)) { // Nothing to transfer. return from; } to.doc = from.doc; delete from.doc; return Object.keys(from).length === 1 ? from.type : from; }
javascript
function reassignJavadoc(from, to) { if (!(from.doc instanceof Javadoc)) { // Nothing to transfer. return from; } to.doc = from.doc; delete from.doc; return Object.keys(from).length === 1 ? from.type : from; }
[ "function", "reassignJavadoc", "(", "from", ",", "to", ")", "{", "if", "(", "!", "(", "from", ".", "doc", "instanceof", "Javadoc", ")", ")", "{", "return", "from", ";", "}", "to", ".", "doc", "=", "from", ".", "doc", ";", "delete", "from", ".", "doc", ";", "return", "Object", ".", "keys", "(", "from", ")", ".", "length", "===", "1", "?", "from", ".", "type", ":", "from", ";", "}" ]
Transfer a key from an object to another and return the new source. If the source becomes an object with a single type attribute set, its `type` attribute is returned instead.
[ "Transfer", "a", "key", "from", "an", "object", "to", "another", "and", "return", "the", "new", "source", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/schemas.js#L685-L693
train
bitnami/nami-utils
lib/file/xml/get.js
xmlFileGet
function xmlFileGet(file, element, attributeName, options) { options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true, default: null}); const doc = loadXmlFile(file, options); const node = getXmlNode(doc, element); let value; if (_.isEmpty(attributeName)) { value = _.map(node.childNodes, 'nodeValue'); } else { value = node.getAttribute(attributeName); // Always return an array value = [value]; } return _.isUndefined(value) ? options.default : value; }
javascript
function xmlFileGet(file, element, attributeName, options) { options = _.sanitize(options, {encoding: 'utf-8', retryOnENOENT: true, default: null}); const doc = loadXmlFile(file, options); const node = getXmlNode(doc, element); let value; if (_.isEmpty(attributeName)) { value = _.map(node.childNodes, 'nodeValue'); } else { value = node.getAttribute(attributeName); // Always return an array value = [value]; } return _.isUndefined(value) ? options.default : value; }
[ "function", "xmlFileGet", "(", "file", ",", "element", ",", "attributeName", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "encoding", ":", "'utf-8'", ",", "retryOnENOENT", ":", "true", ",", "default", ":", "null", "}", ")", ";", "const", "doc", "=", "loadXmlFile", "(", "file", ",", "options", ")", ";", "const", "node", "=", "getXmlNode", "(", "doc", ",", "element", ")", ";", "let", "value", ";", "if", "(", "_", ".", "isEmpty", "(", "attributeName", ")", ")", "{", "value", "=", "_", ".", "map", "(", "node", ".", "childNodes", ",", "'nodeValue'", ")", ";", "}", "else", "{", "value", "=", "node", ".", "getAttribute", "(", "attributeName", ")", ";", "value", "=", "[", "value", "]", ";", "}", "return", "_", ".", "isUndefined", "(", "value", ")", "?", "options", ".", "default", ":", "value", ";", "}" ]
Get value from XML file @function $file~xml/get @param {string} file - XML File to read the value from @param {string} element - XPath expression to the element from which to read the attribute (null if text node) @param {string} attribute - Attribute to get the value from (if empty, will return the text of the node element) @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @param {string} [options.default=''] - Default value if key not found @throws Will throw an error if the path is not a file @throws Will throw an error if the XPath is not valid @throws Will throw an error if the XPath is not found @example // Get 'charset' atribute of node //html/head/meta $file.ini.get('index.html', '//html/head/meta', 'charset'); // => 'UTF-8'
[ "Get", "value", "from", "XML", "file" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/xml/get.js#L25-L40
train
bitnami/nami-utils
lib/file/exists.js
exists
function exists(file) { try { fs.lstatSync(file); return true; } catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') { return false; } else { throw e; } } }
javascript
function exists(file) { try { fs.lstatSync(file); return true; } catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') { return false; } else { throw e; } } }
[ "function", "exists", "(", "file", ")", "{", "try", "{", "fs", ".", "lstatSync", "(", "file", ")", ";", "return", "true", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", ".", "code", "===", "'ENOENT'", "||", "e", ".", "code", "===", "'ENOTDIR'", ")", "{", "return", "false", ";", "}", "else", "{", "throw", "e", ";", "}", "}", "}" ]
Check whether a file exists or not @memberof $file @param {string} file @returns {boolean} @example // Check if file exists $file.exists('/opt/bitnami/properties.ini') // => true
[ "Check", "whether", "a", "file", "exists", "or", "not" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/exists.js#L15-L26
train
zetapush/zetapush
packages/cometd/lib/browser/Transports.js
getOverloadedConfigFromEnvironment
function getOverloadedConfigFromEnvironment() { var env = typeof document === 'undefined' ? {} : document.documentElement.dataset; var platformUrl = env.zpPlatformUrl; var appName = env.zpSandboxid; return { platformUrl: platformUrl, appName: appName }; }
javascript
function getOverloadedConfigFromEnvironment() { var env = typeof document === 'undefined' ? {} : document.documentElement.dataset; var platformUrl = env.zpPlatformUrl; var appName = env.zpSandboxid; return { platformUrl: platformUrl, appName: appName }; }
[ "function", "getOverloadedConfigFromEnvironment", "(", ")", "{", "var", "env", "=", "typeof", "document", "===", "'undefined'", "?", "{", "}", ":", "document", ".", "documentElement", ".", "dataset", ";", "var", "platformUrl", "=", "env", ".", "zpPlatformUrl", ";", "var", "appName", "=", "env", ".", "zpSandboxid", ";", "return", "{", "platformUrl", ":", "platformUrl", ",", "appName", ":", "appName", "}", ";", "}" ]
Get overloaded config from environment
[ "Get", "overloaded", "config", "from", "environment" ]
ad3383b8e332050eaecd55be9bdff6cf76db699e
https://github.com/zetapush/zetapush/blob/ad3383b8e332050eaecd55be9bdff6cf76db699e/packages/cometd/lib/browser/Transports.js#L56-L64
train
ArnaudBuchholz/gpf-js
lost+found/src/attributes.js
_gpfDefAttr
function _gpfDefAttr (name, base, definition) { var isAlias = name.charAt(0) === "$", fullName, result; if (isAlias) { name = name.substr(1); fullName = name + "Attribute"; } else { fullName = name; } result = _gpfDefAttrBase(fullName, base, definition); if (isAlias) { _gpfAlias(result, name); } return result; }
javascript
function _gpfDefAttr (name, base, definition) { var isAlias = name.charAt(0) === "$", fullName, result; if (isAlias) { name = name.substr(1); fullName = name + "Attribute"; } else { fullName = name; } result = _gpfDefAttrBase(fullName, base, definition); if (isAlias) { _gpfAlias(result, name); } return result; }
[ "function", "_gpfDefAttr", "(", "name", ",", "base", ",", "definition", ")", "{", "var", "isAlias", "=", "name", ".", "charAt", "(", "0", ")", "===", "\"$\"", ",", "fullName", ",", "result", ";", "if", "(", "isAlias", ")", "{", "name", "=", "name", ".", "substr", "(", "1", ")", ";", "fullName", "=", "name", "+", "\"Attribute\"", ";", "}", "else", "{", "fullName", "=", "name", ";", "}", "result", "=", "_gpfDefAttrBase", "(", "fullName", ",", "base", ",", "definition", ")", ";", "if", "(", "isAlias", ")", "{", "_gpfAlias", "(", "result", ",", "name", ")", ";", "}", "return", "result", ";", "}" ]
gpf.define for attributes @param {String} name Attribute name. If it contains a dot, it is treated as absolute contextual. Otherwise, it is relative to "gpf.attributes". If starting with $ (and no dot), the contextual name will be the "gpf.attributes." + name(without $) + "Attribute" and an alias is automatically created @param {Function|string} [base=undefined] base Base attribute (or contextual name) @param {Object} [definition=undefined] definition Attribute definition @return {Function}
[ "gpf", ".", "define", "for", "attributes" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/attributes.js#L81-L97
train
ArnaudBuchholz/gpf-js
lost+found/src/attributes.js
function (expectedClass) { _gpfAssertAttributeClassOnly(expectedClass); var result = new _gpfA.Array(); result._array = this._array.filter(function (attribute) { return attribute instanceof expectedClass; }); return result; }
javascript
function (expectedClass) { _gpfAssertAttributeClassOnly(expectedClass); var result = new _gpfA.Array(); result._array = this._array.filter(function (attribute) { return attribute instanceof expectedClass; }); return result; }
[ "function", "(", "expectedClass", ")", "{", "_gpfAssertAttributeClassOnly", "(", "expectedClass", ")", ";", "var", "result", "=", "new", "_gpfA", ".", "Array", "(", ")", ";", "result", ".", "_array", "=", "this", ".", "_array", ".", "filter", "(", "function", "(", "attribute", ")", "{", "return", "attribute", "instanceof", "expectedClass", ";", "}", ")", ";", "return", "result", ";", "}" ]
Returns a new array with all attributes matching the expected class @param {Function} expectedClass the class to match @return {gpf.attributes.Array}
[ "Returns", "a", "new", "array", "with", "all", "attributes", "matching", "the", "expected", "class" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/attributes.js#L206-L213
train
ArnaudBuchholz/gpf-js
lost+found/src/attributes.js
function (to, callback, param) { _gpfObjectForEach(this._members, function (attributeArray, member) { member = _gpfDecodeAttributeMember(member); attributeArray._array.forEach(function (attribute) { if (!callback || callback(member, attribute, param)) { to.add(member, attribute); } }); }); return to; }
javascript
function (to, callback, param) { _gpfObjectForEach(this._members, function (attributeArray, member) { member = _gpfDecodeAttributeMember(member); attributeArray._array.forEach(function (attribute) { if (!callback || callback(member, attribute, param)) { to.add(member, attribute); } }); }); return to; }
[ "function", "(", "to", ",", "callback", ",", "param", ")", "{", "_gpfObjectForEach", "(", "this", ".", "_members", ",", "function", "(", "attributeArray", ",", "member", ")", "{", "member", "=", "_gpfDecodeAttributeMember", "(", "member", ")", ";", "attributeArray", ".", "_array", ".", "forEach", "(", "function", "(", "attribute", ")", "{", "if", "(", "!", "callback", "||", "callback", "(", "member", ",", "attribute", ",", "param", ")", ")", "{", "to", ".", "add", "(", "member", ",", "attribute", ")", ";", "}", "}", ")", ";", "}", ")", ";", "return", "to", ";", "}" ]
Copy the content of this map to a new one @param {gpf.attributes.Map} to recipient of the copy @param {Function} [callback=undefined] callback function to test if the mapping should be added @param {*} [param=undefined] param additional parameter for the callback @return {gpf.attributes.Map} to
[ "Copy", "the", "content", "of", "this", "map", "to", "a", "new", "one" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/attributes.js#L257-L267
train
ArnaudBuchholz/gpf-js
lost+found/src/attributes.js
function (classDef) { var attributes, Super; while (classDef) { // !undefined && !null attributes = classDef._attributes; if (attributes) { attributes._copy(this); } Super = classDef._Super; if (Super === Object) { // Can't go upper break; } else { classDef = _gpfGetClassDefinition(Super); } } return this; }
javascript
function (classDef) { var attributes, Super; while (classDef) { // !undefined && !null attributes = classDef._attributes; if (attributes) { attributes._copy(this); } Super = classDef._Super; if (Super === Object) { // Can't go upper break; } else { classDef = _gpfGetClassDefinition(Super); } } return this; }
[ "function", "(", "classDef", ")", "{", "var", "attributes", ",", "Super", ";", "while", "(", "classDef", ")", "{", "attributes", "=", "classDef", ".", "_attributes", ";", "if", "(", "attributes", ")", "{", "attributes", ".", "_copy", "(", "this", ")", ";", "}", "Super", "=", "classDef", ".", "_Super", ";", "if", "(", "Super", "===", "Object", ")", "{", "break", ";", "}", "else", "{", "classDef", "=", "_gpfGetClassDefinition", "(", "Super", ")", ";", "}", "}", "return", "this", ";", "}" ]
Fill the map using class definition object @param {gpf.classDef} classDef class definition @gpf:chainable
[ "Fill", "the", "map", "using", "class", "definition", "object" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/attributes.js#L301-L317
train
ArnaudBuchholz/gpf-js
lost+found/src/attributes.js
function (member, attribute) { _gpfAssertAttributeOnly(attribute); member = _gpfEncodeAttributeMember(member); var array = this._members[member]; if (undefined === array) { array = this._members[member] = new _gpfA.Array(); } array._array.push(attribute); ++this._count; }
javascript
function (member, attribute) { _gpfAssertAttributeOnly(attribute); member = _gpfEncodeAttributeMember(member); var array = this._members[member]; if (undefined === array) { array = this._members[member] = new _gpfA.Array(); } array._array.push(attribute); ++this._count; }
[ "function", "(", "member", ",", "attribute", ")", "{", "_gpfAssertAttributeOnly", "(", "attribute", ")", ";", "member", "=", "_gpfEncodeAttributeMember", "(", "member", ")", ";", "var", "array", "=", "this", ".", "_members", "[", "member", "]", ";", "if", "(", "undefined", "===", "array", ")", "{", "array", "=", "this", ".", "_members", "[", "member", "]", "=", "new", "_gpfA", ".", "Array", "(", ")", ";", "}", "array", ".", "_array", ".", "push", "(", "attribute", ")", ";", "++", "this", ".", "_count", ";", "}" ]
Associate an attribute to a member @param {String} member member name @param {gpf.attributes.Attribute} attribute attribute to map
[ "Associate", "an", "attribute", "to", "a", "member" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/attributes.js#L340-L349
train
ArnaudBuchholz/gpf-js
lost+found/src/attributes.js
function (member) { member = _gpfEncodeAttributeMember(member); var result = this._members[member]; if (undefined === result || !(result instanceof _gpfA.Array)) { return _gpfEmptyMemberArray; } return result; }
javascript
function (member) { member = _gpfEncodeAttributeMember(member); var result = this._members[member]; if (undefined === result || !(result instanceof _gpfA.Array)) { return _gpfEmptyMemberArray; } return result; }
[ "function", "(", "member", ")", "{", "member", "=", "_gpfEncodeAttributeMember", "(", "member", ")", ";", "var", "result", "=", "this", ".", "_members", "[", "member", "]", ";", "if", "(", "undefined", "===", "result", "||", "!", "(", "result", "instanceof", "_gpfA", ".", "Array", ")", ")", "{", "return", "_gpfEmptyMemberArray", ";", "}", "return", "result", ";", "}" ]
Returns the array of attributes associated to a member @param {String} member @return {gpf.attributes.Array}
[ "Returns", "the", "array", "of", "attributes", "associated", "to", "a", "member" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/attributes.js#L369-L376
train
ArnaudBuchholz/gpf-js
lost+found/src/attributes.js
function () { var result = []; _gpfObjectForEach(this._members, function (attributes, member) { _gpfIgnore(attributes); result.push(_gpfDecodeAttributeMember(member)); }); return result; }
javascript
function () { var result = []; _gpfObjectForEach(this._members, function (attributes, member) { _gpfIgnore(attributes); result.push(_gpfDecodeAttributeMember(member)); }); return result; }
[ "function", "(", ")", "{", "var", "result", "=", "[", "]", ";", "_gpfObjectForEach", "(", "this", ".", "_members", ",", "function", "(", "attributes", ",", "member", ")", "{", "_gpfIgnore", "(", "attributes", ")", ";", "result", ".", "push", "(", "_gpfDecodeAttributeMember", "(", "member", ")", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Returns the list of members stored in this map @return {String[]}
[ "Returns", "the", "list", "of", "members", "stored", "in", "this", "map" ]
0888295c99a1ff285ead60273cc7ef656e7fd812
https://github.com/ArnaudBuchholz/gpf-js/blob/0888295c99a1ff285ead60273cc7ef656e7fd812/lost+found/src/attributes.js#L383-L390
train
edertone/TurboCommons
TurboCommons-Java/.turboBuilder/Utils.js
loadFileAsString
function loadFileAsString(path, replaceWhiteSpaces){ var file = new java.io.File(path); var fr = new java.io.FileReader(file); var br = new java.io.BufferedReader(fr); var line; var lines = ""; while((line = br.readLine()) != null){ if(replaceWhiteSpaces){ lines = lines + line.replace(" ", ""); }else{ lines = lines + line; } } return lines; }
javascript
function loadFileAsString(path, replaceWhiteSpaces){ var file = new java.io.File(path); var fr = new java.io.FileReader(file); var br = new java.io.BufferedReader(fr); var line; var lines = ""; while((line = br.readLine()) != null){ if(replaceWhiteSpaces){ lines = lines + line.replace(" ", ""); }else{ lines = lines + line; } } return lines; }
[ "function", "loadFileAsString", "(", "path", ",", "replaceWhiteSpaces", ")", "{", "var", "file", "=", "new", "java", ".", "io", ".", "File", "(", "path", ")", ";", "var", "fr", "=", "new", "java", ".", "io", ".", "FileReader", "(", "file", ")", ";", "var", "br", "=", "new", "java", ".", "io", ".", "BufferedReader", "(", "fr", ")", ";", "var", "line", ";", "var", "lines", "=", "\"\"", ";", "while", "(", "(", "line", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "if", "(", "replaceWhiteSpaces", ")", "{", "lines", "=", "lines", "+", "line", ".", "replace", "(", "\" \"", ",", "\"\"", ")", ";", "}", "else", "{", "lines", "=", "lines", "+", "line", ";", "}", "}", "return", "lines", ";", "}" ]
Utility methods used by TurboBuilder Load all the file contents and return it as a string
[ "Utility", "methods", "used", "by", "TurboBuilder", "Load", "all", "the", "file", "contents", "and", "return", "it", "as", "a", "string" ]
275d4971ec19d8632b92ac466d9ce5b7db50acfa
https://github.com/edertone/TurboCommons/blob/275d4971ec19d8632b92ac466d9ce5b7db50acfa/TurboCommons-Java/.turboBuilder/Utils.js#L11-L33
train
edertone/TurboCommons
TurboCommons-Java/.turboBuilder/Utils.js
getFilesList
function getFilesList(path, includes, excludes){ // Init default vars values includes = (includes === undefined || includes == null || includes == '') ? "**" : includes; excludes = (excludes === undefined || excludes == null || excludes == '') ? "" : excludes; var fs = project.createDataType("fileset"); fs.setDir(new java.io.File(path)); if(includes != ""){ fs.setIncludes(includes); } if(excludes != ""){ fs.setExcludes(excludes); } var srcFiles = fs.getDirectoryScanner(project).getIncludedFiles(); var result = []; for (var i = 0; i<srcFiles.length; i++){ result.push(srcFiles[i]); } return result; }
javascript
function getFilesList(path, includes, excludes){ // Init default vars values includes = (includes === undefined || includes == null || includes == '') ? "**" : includes; excludes = (excludes === undefined || excludes == null || excludes == '') ? "" : excludes; var fs = project.createDataType("fileset"); fs.setDir(new java.io.File(path)); if(includes != ""){ fs.setIncludes(includes); } if(excludes != ""){ fs.setExcludes(excludes); } var srcFiles = fs.getDirectoryScanner(project).getIncludedFiles(); var result = []; for (var i = 0; i<srcFiles.length; i++){ result.push(srcFiles[i]); } return result; }
[ "function", "getFilesList", "(", "path", ",", "includes", ",", "excludes", ")", "{", "includes", "=", "(", "includes", "===", "undefined", "||", "includes", "==", "null", "||", "includes", "==", "''", ")", "?", "\"**\"", ":", "includes", ";", "excludes", "=", "(", "excludes", "===", "undefined", "||", "excludes", "==", "null", "||", "excludes", "==", "''", ")", "?", "\"\"", ":", "excludes", ";", "var", "fs", "=", "project", ".", "createDataType", "(", "\"fileset\"", ")", ";", "fs", ".", "setDir", "(", "new", "java", ".", "io", ".", "File", "(", "path", ")", ")", ";", "if", "(", "includes", "!=", "\"\"", ")", "{", "fs", ".", "setIncludes", "(", "includes", ")", ";", "}", "if", "(", "excludes", "!=", "\"\"", ")", "{", "fs", ".", "setExcludes", "(", "excludes", ")", ";", "}", "var", "srcFiles", "=", "fs", ".", "getDirectoryScanner", "(", "project", ")", ".", "getIncludedFiles", "(", ")", ";", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "srcFiles", ".", "length", ";", "i", "++", ")", "{", "result", ".", "push", "(", "srcFiles", "[", "i", "]", ")", ";", "}", "return", "result", ";", "}" ]
Get a list with all the files inside the specified path and all of its subfolders. @param path A full file system path from which we want to get the list of files @param includes comma- or space-separated list of patterns of files that must be included; all files are included when omitted. @param excludes comma- or space-separated list of patterns of files that must be excluded; no files (except default excludes) are excluded when omitted. @returns An array containing all the matching files inside the given path and subfolders. Each array element will be the full filename plus the relative path to the provided path. For example, if we provide "src/main" as path, resulting files may be like "php/managers/BigManager.php", ... and so.
[ "Get", "a", "list", "with", "all", "the", "files", "inside", "the", "specified", "path", "and", "all", "of", "its", "subfolders", "." ]
275d4971ec19d8632b92ac466d9ce5b7db50acfa
https://github.com/edertone/TurboCommons/blob/275d4971ec19d8632b92ac466d9ce5b7db50acfa/TurboCommons-Java/.turboBuilder/Utils.js#L47-L77
train