id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
29,200
cdapio/ui-schema-parser
etc/browser/lib/files.js
load
function load(schema) { var obj; if (typeof schema == 'string' && schema !== 'null') { try { obj = JSON.parse(schema); } catch (err) { // No file loading here. } } if (obj === undefined) { obj = schema; } return obj; }
javascript
function load(schema) { var obj; if (typeof schema == 'string' && schema !== 'null') { try { obj = JSON.parse(schema); } catch (err) { // No file loading here. } } if (obj === undefined) { obj = schema; } return obj; }
[ "function", "load", "(", "schema", ")", "{", "var", "obj", ";", "if", "(", "typeof", "schema", "==", "'string'", "&&", "schema", "!==", "'null'", ")", "{", "try", "{", "obj", "=", "JSON", ".", "parse", "(", "schema", ")", ";", "}", "catch", "(", ...
Schema loader, without file-system access.
[ "Schema", "loader", "without", "file", "-", "system", "access", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/etc/browser/lib/files.js#L55-L68
29,201
cdapio/ui-schema-parser
lib/containers.js
copyBuffer
function copyBuffer(buf, pos, len) { var copy = new Buffer(len); buf.copy(copy, 0, pos, pos + len); return copy; }
javascript
function copyBuffer(buf, pos, len) { var copy = new Buffer(len); buf.copy(copy, 0, pos, pos + len); return copy; }
[ "function", "copyBuffer", "(", "buf", ",", "pos", ",", "len", ")", "{", "var", "copy", "=", "new", "Buffer", "(", "len", ")", ";", "buf", ".", "copy", "(", "copy", ",", "0", ",", "pos", ",", "pos", "+", "len", ")", ";", "return", "copy", ";", ...
Copy a buffer. This avoids having to create a slice of the original buffer.
[ "Copy", "a", "buffer", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/containers.js#L572-L576
29,202
bitnami/nami-utils
lib/os/user-management/delete-group.js
deleteGroup
function deleteGroup(group) { if (!runningAsRoot()) return; if (!group) throw new Error('You must provide a group to delete'); if (!groupExists(group)) { return; } const groupdelBin = _safeLocateBinary('groupdel'); const delgroupBin = _safeLocateBinary('delgroup'); if (isPlatform('linux')) { if (groupdelBin !== null) { // most modern systems runProgram(groupdelBin, [group]); } else { if (_isBusyboxBinary(delgroupBin)) { // busybox-based systems runProgram(delgroupBin, [group]); } else { throw new Error(`Don't know how to delete group ${group} on this strange linux`); } } } else if (isPlatform('osx')) { runProgram('dscl', ['.', '-delete', `/Groups/${group}`]); } else if (isPlatform('windows')) { throw new Error(`Don't know how to delete group ${group} on Windows`); } else { throw new Error(`Don't know how to delete group ${group} on the current platformp`); } }
javascript
function deleteGroup(group) { if (!runningAsRoot()) return; if (!group) throw new Error('You must provide a group to delete'); if (!groupExists(group)) { return; } const groupdelBin = _safeLocateBinary('groupdel'); const delgroupBin = _safeLocateBinary('delgroup'); if (isPlatform('linux')) { if (groupdelBin !== null) { // most modern systems runProgram(groupdelBin, [group]); } else { if (_isBusyboxBinary(delgroupBin)) { // busybox-based systems runProgram(delgroupBin, [group]); } else { throw new Error(`Don't know how to delete group ${group} on this strange linux`); } } } else if (isPlatform('osx')) { runProgram('dscl', ['.', '-delete', `/Groups/${group}`]); } else if (isPlatform('windows')) { throw new Error(`Don't know how to delete group ${group} on Windows`); } else { throw new Error(`Don't know how to delete group ${group} on the current platformp`); } }
[ "function", "deleteGroup", "(", "group", ")", "{", "if", "(", "!", "runningAsRoot", "(", ")", ")", "return", ";", "if", "(", "!", "group", ")", "throw", "new", "Error", "(", "'You must provide a group to delete'", ")", ";", "if", "(", "!", "groupExists", ...
Delete system group @function $os~deleteGroup @param {string|number} group - Groupname or group id @example // Delete mysql group $os.deleteGroup('mysql');
[ "Delete", "system", "group" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/user-management/delete-group.js#L18-L44
29,203
bitnami/nami-utils
lib/os/kill.js
kill
function kill(pid, signal) { signal = _.isUndefined(signal) ? 'SIGINT' : signal; // process.kill does not recognize many of the well known numeric signals, // only by name if (_.isFinite(signal) && _.has(signalsMap, signal)) { signal = signalsMap[signal]; } if (!_.isFinite(pid)) return false; try { process.kill(pid, signal); } catch (e) { return false; } return true; }
javascript
function kill(pid, signal) { signal = _.isUndefined(signal) ? 'SIGINT' : signal; // process.kill does not recognize many of the well known numeric signals, // only by name if (_.isFinite(signal) && _.has(signalsMap, signal)) { signal = signalsMap[signal]; } if (!_.isFinite(pid)) return false; try { process.kill(pid, signal); } catch (e) { return false; } return true; }
[ "function", "kill", "(", "pid", ",", "signal", ")", "{", "signal", "=", "_", ".", "isUndefined", "(", "signal", ")", "?", "'SIGINT'", ":", "signal", ";", "// process.kill does not recognize many of the well known numeric signals,", "// only by name", "if", "(", "_",...
Send signal to process @function $os~kill @param {number} pid - Process ID @param {number|string} [signal=SIGINT] - Signal number or name @returns {boolean} - True if it successed to kill the process @example // Send 'SIGKILL' signal to process 123213 $os.kill(123213, 'SIGKILL') // => true
[ "Send", "signal", "to", "process" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/os/kill.js#L17-L32
29,204
bitnami/nami-utils
lib/file/contains.js
contains
function contains(file, pattern, options) { options = _.sanitize(options, {encoding: 'utf-8'}); if (!exists(file)) return false; const text = read(file, options); if (_.isRegExp(pattern)) { return !!text.match(pattern); } else { return (text.search(_escapeRegExp(pattern)) !== -1); } }
javascript
function contains(file, pattern, options) { options = _.sanitize(options, {encoding: 'utf-8'}); if (!exists(file)) return false; const text = read(file, options); if (_.isRegExp(pattern)) { return !!text.match(pattern); } else { return (text.search(_escapeRegExp(pattern)) !== -1); } }
[ "function", "contains", "(", "file", ",", "pattern", ",", "options", ")", "{", "options", "=", "_", ".", "sanitize", "(", "options", ",", "{", "encoding", ":", "'utf-8'", "}", ")", ";", "if", "(", "!", "exists", "(", "file", ")", ")", "return", "fa...
Check if file contents contains a given pattern @function $file~contains @param {string} file - File path to check its contents @param {string|RegExp} pattern - Glob like pattern or regexp to match @param {Object} [options] @param {string} [options.encoding=utf-8] - Encoding used to read the file @returns {boolean} - Whether the contents of the file match or not the pattern @example // Check if service has started successfully $file.contains('logs/service.log', /.*service.*started\s*successfully/); // => true
[ "Check", "if", "file", "contents", "contains", "a", "given", "pattern" ]
1b34424b6cb93593db7ba2c238dbfe301ab9defc
https://github.com/bitnami/nami-utils/blob/1b34424b6cb93593db7ba2c238dbfe301ab9defc/lib/file/contains.js#L21-L30
29,205
LaunchPadLab/lp-requests
src/http/middleware/serialize-body.js
serializeBody
function serializeBody ({ decamelizeBody=true, headers, body }) { if (!body || !isJSONRequest(headers)) return const transformedBody = decamelizeBody ? decamelizeKeys(body) : body return { body: JSON.stringify(transformedBody) } }
javascript
function serializeBody ({ decamelizeBody=true, headers, body }) { if (!body || !isJSONRequest(headers)) return const transformedBody = decamelizeBody ? decamelizeKeys(body) : body return { body: JSON.stringify(transformedBody) } }
[ "function", "serializeBody", "(", "{", "decamelizeBody", "=", "true", ",", "headers", ",", "body", "}", ")", "{", "if", "(", "!", "body", "||", "!", "isJSONRequest", "(", "headers", ")", ")", "return", "const", "transformedBody", "=", "decamelizeBody", "?"...
Serializes the request body if necessary
[ "Serializes", "the", "request", "body", "if", "necessary" ]
139294b1594b2d62ba8403c9ac6e97d5e84961f3
https://github.com/LaunchPadLab/lp-requests/blob/139294b1594b2d62ba8403c9ac6e97d5e84961f3/src/http/middleware/serialize-body.js#L9-L15
29,206
cdapio/ui-schema-parser
lib/protocols.js
createProtocol
function createProtocol(attrs, opts) { opts = opts || {}; var name = attrs.protocol; if (!name) { throw new Error('missing protocol name'); } if (attrs.namespace !== undefined) { opts.namespace = attrs.namespace; } else { var match = /^(.*)\.[^.]+$/.exec(name); if (match) { opts.namespace = match[1]; } } name = types.qualify(name, opts.namespace); if (attrs.types) { attrs.types.forEach(function (obj) { types.createType(obj, opts); }); } var messages = {}; if (attrs.messages) { Object.keys(attrs.messages).forEach(function (key) { messages[key] = new Message(key, attrs.messages[key], opts); }); } return new Protocol(name, messages, opts.registry || {}); }
javascript
function createProtocol(attrs, opts) { opts = opts || {}; var name = attrs.protocol; if (!name) { throw new Error('missing protocol name'); } if (attrs.namespace !== undefined) { opts.namespace = attrs.namespace; } else { var match = /^(.*)\.[^.]+$/.exec(name); if (match) { opts.namespace = match[1]; } } name = types.qualify(name, opts.namespace); if (attrs.types) { attrs.types.forEach(function (obj) { types.createType(obj, opts); }); } var messages = {}; if (attrs.messages) { Object.keys(attrs.messages).forEach(function (key) { messages[key] = new Message(key, attrs.messages[key], opts); }); } return new Protocol(name, messages, opts.registry || {}); }
[ "function", "createProtocol", "(", "attrs", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "var", "name", "=", "attrs", ".", "protocol", ";", "if", "(", "!", "name", ")", "{", "throw", "new", "Error", "(", "'missing protocol name'", ...
Protocol generation function. This should be used instead of the protocol constructor. The protocol's constructor performs no logic to better support efficient protocol copy.
[ "Protocol", "generation", "function", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L80-L108
29,207
cdapio/ui-schema-parser
lib/protocols.js
Protocol
function Protocol(name, messages, types, handlers) { if (types === undefined) { // Let's be helpful in case this class is instantiated directly. return createProtocol(name, messages); } this._name = name; this._messages = messages; this._types = types; // Shared with subprotocols (via the prototype chain, overwriting is safe). this._handlers = handlers || {}; // We cache a string rather than a buffer to not retain an entire slab. This // also lets us use hashes as keys inside maps (e.g. for resolvers). this._hs = utils.getHash(this.getSchema()).toString('binary'); }
javascript
function Protocol(name, messages, types, handlers) { if (types === undefined) { // Let's be helpful in case this class is instantiated directly. return createProtocol(name, messages); } this._name = name; this._messages = messages; this._types = types; // Shared with subprotocols (via the prototype chain, overwriting is safe). this._handlers = handlers || {}; // We cache a string rather than a buffer to not retain an entire slab. This // also lets us use hashes as keys inside maps (e.g. for resolvers). this._hs = utils.getHash(this.getSchema()).toString('binary'); }
[ "function", "Protocol", "(", "name", ",", "messages", ",", "types", ",", "handlers", ")", "{", "if", "(", "types", "===", "undefined", ")", "{", "// Let's be helpful in case this class is instantiated directly.", "return", "createProtocol", "(", "name", ",", "messag...
An Avro protocol.
[ "An", "Avro", "protocol", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L114-L128
29,208
cdapio/ui-schema-parser
lib/protocols.js
MessageEmitter
function MessageEmitter(ptcl, opts) { opts = opts || {}; events.EventEmitter.call(this); this._ptcl = ptcl; this._strict = !!opts.strictErrors; this._endWritable = !!utils.getOption(opts, 'endWritable', true); this._timeout = utils.getOption(opts, 'timeout', 10000); this._prefix = normalizedPrefix(opts.scope); this._cache = opts.cache || {}; var fgpt = opts.serverFingerprint; var adapter; if (fgpt) { adapter = this._cache[fgpt]; } if (!adapter) { // This might happen even if the server fingerprint option was set, in // cases where the cache doesn't contain the corresponding adapter. fgpt = ptcl.getFingerprint(); adapter = this._cache[fgpt] = new Adapter(ptcl, ptcl, fgpt); } this._adapter = adapter; this._registry = new Registry(this, PREFIX_LENGTH); this._destroyed = false; this._interrupted = false; this.once('_eot', function (pending) { this.emit('eot', pending); }); }
javascript
function MessageEmitter(ptcl, opts) { opts = opts || {}; events.EventEmitter.call(this); this._ptcl = ptcl; this._strict = !!opts.strictErrors; this._endWritable = !!utils.getOption(opts, 'endWritable', true); this._timeout = utils.getOption(opts, 'timeout', 10000); this._prefix = normalizedPrefix(opts.scope); this._cache = opts.cache || {}; var fgpt = opts.serverFingerprint; var adapter; if (fgpt) { adapter = this._cache[fgpt]; } if (!adapter) { // This might happen even if the server fingerprint option was set, in // cases where the cache doesn't contain the corresponding adapter. fgpt = ptcl.getFingerprint(); adapter = this._cache[fgpt] = new Adapter(ptcl, ptcl, fgpt); } this._adapter = adapter; this._registry = new Registry(this, PREFIX_LENGTH); this._destroyed = false; this._interrupted = false; this.once('_eot', function (pending) { this.emit('eot', pending); }); }
[ "function", "MessageEmitter", "(", "ptcl", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_ptcl", "=", "ptcl", ";", "this", ".", "_strict", "=", "!",...
Base message emitter class. See below for the two available variants.
[ "Base", "message", "emitter", "class", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L364-L392
29,209
cdapio/ui-schema-parser
lib/protocols.js
StatelessEmitter
function StatelessEmitter(ptcl, writableFactory, opts) { MessageEmitter.call(this, ptcl, opts); this._writableFactory = writableFactory; if (!opts || !opts.noPing) { // Ping the server to check whether the remote protocol is compatible. this.emitMessage('', {}, function (err) { if (err) { this.emit('error', err); } }); } }
javascript
function StatelessEmitter(ptcl, writableFactory, opts) { MessageEmitter.call(this, ptcl, opts); this._writableFactory = writableFactory; if (!opts || !opts.noPing) { // Ping the server to check whether the remote protocol is compatible. this.emitMessage('', {}, function (err) { if (err) { this.emit('error', err); } }); } }
[ "function", "StatelessEmitter", "(", "ptcl", ",", "writableFactory", ",", "opts", ")", "{", "MessageEmitter", ".", "call", "(", "this", ",", "ptcl", ",", "opts", ")", ";", "this", ".", "_writableFactory", "=", "writableFactory", ";", "if", "(", "!", "opts"...
Factory-based emitter. This emitter doesn't keep a persistent connection to the server and requires prepending a handshake to each message emitted. Usage examples include talking to an HTTP server (where the factory returns an HTTP request). Since each message will use its own writable/readable stream pair, the advantage of this emitter is that it is able to keep track of which response corresponds to each request without relying on transport ordering. In particular, this means these emitters are compatible with any server implementation.
[ "Factory", "-", "based", "emitter", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L541-L553
29,210
cdapio/ui-schema-parser
lib/protocols.js
emit
function emit(retry) { if (self._interrupted) { // The request's callback will already have been called. return; } var hreq = self._createHandshakeRequest(adapter, !retry); var writable = self._writableFactory.call(self, function (err, readable) { if (err) { cb(err); return; } readable.on('data', function (obj) { debug('received response %s', obj.id); // We don't check that the prefix matches since the ID likely hasn't // been propagated to the response (see default stateless codec). var buf = Buffer.concat(obj.payload); try { var parts = readHead(HANDSHAKE_RESPONSE_TYPE, buf); var hres = parts.head; if (hres.serverHash) { adapter = self._getAdapter(hres); } } catch (err) { cb(err); return; } self.emit('handshake', hreq, hres); if (hres.match === 'NONE') { process.nextTick(function() { emit(true); }); return; } // Change the default adapter. self._adapter = adapter; cb(null, parts.tail, adapter); }); }); writable.write({ id: id, payload: [HANDSHAKE_REQUEST_TYPE.toBuffer(hreq), reqBuf] }); if (self._endWritable) { writable.end(); } }
javascript
function emit(retry) { if (self._interrupted) { // The request's callback will already have been called. return; } var hreq = self._createHandshakeRequest(adapter, !retry); var writable = self._writableFactory.call(self, function (err, readable) { if (err) { cb(err); return; } readable.on('data', function (obj) { debug('received response %s', obj.id); // We don't check that the prefix matches since the ID likely hasn't // been propagated to the response (see default stateless codec). var buf = Buffer.concat(obj.payload); try { var parts = readHead(HANDSHAKE_RESPONSE_TYPE, buf); var hres = parts.head; if (hres.serverHash) { adapter = self._getAdapter(hres); } } catch (err) { cb(err); return; } self.emit('handshake', hreq, hres); if (hres.match === 'NONE') { process.nextTick(function() { emit(true); }); return; } // Change the default adapter. self._adapter = adapter; cb(null, parts.tail, adapter); }); }); writable.write({ id: id, payload: [HANDSHAKE_REQUEST_TYPE.toBuffer(hreq), reqBuf] }); if (self._endWritable) { writable.end(); } }
[ "function", "emit", "(", "retry", ")", "{", "if", "(", "self", ".", "_interrupted", ")", "{", "// The request's callback will already have been called.", "return", ";", "}", "var", "hreq", "=", "self", ".", "_createHandshakeRequest", "(", "adapter", ",", "!", "r...
Each writable is only used once, no risk of buffering.
[ "Each", "writable", "is", "only", "used", "once", "no", "risk", "of", "buffering", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L563-L609
29,211
cdapio/ui-schema-parser
lib/protocols.js
StatelessListener
function StatelessListener(ptcl, readableFactory, opts) { MessageListener.call(this, ptcl, opts); var self = this; var readable; process.nextTick(function () { // Delay listening to allow handlers to be attached even if the factory is // purely synchronous. readable = readableFactory.call(this, function (err, writable) { if (err) { self.emit('error', err); // Since stateless listeners are only used once, it is safe to destroy. onFinish(); return; } self._writable = writable.on('finish', onFinish); self.emit('_writable'); }).on('data', onRequest) .on('end', onEnd); }); function onRequest(obj) { var id = obj.id; var buf = Buffer.concat(obj.payload); var err = null; try { var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf); var hreq = parts.head; var adapter = self._getAdapter(hreq); } catch (cause) { err = wrapError('invalid handshake request', cause); } if (err) { done(encodeError(err)); } else { self._receive(parts.tail, adapter, done); } function done(resBuf) { if (!self._writable) { self.once('_writable', function () { done(resBuf); }); return; } var hres = self._createHandshakeResponse(err, hreq); self.emit('handshake', hreq, hres); var payload = [ HANDSHAKE_RESPONSE_TYPE.toBuffer(hres), resBuf ]; self._writable.write({id: id, payload: payload}); if (self._endWritable) { self._writable.end(); } } } function onEnd() { self.destroy(); } function onFinish() { if (readable) { readable .removeListener('data', onRequest) .removeListener('end', onEnd); } self.destroy(true); } }
javascript
function StatelessListener(ptcl, readableFactory, opts) { MessageListener.call(this, ptcl, opts); var self = this; var readable; process.nextTick(function () { // Delay listening to allow handlers to be attached even if the factory is // purely synchronous. readable = readableFactory.call(this, function (err, writable) { if (err) { self.emit('error', err); // Since stateless listeners are only used once, it is safe to destroy. onFinish(); return; } self._writable = writable.on('finish', onFinish); self.emit('_writable'); }).on('data', onRequest) .on('end', onEnd); }); function onRequest(obj) { var id = obj.id; var buf = Buffer.concat(obj.payload); var err = null; try { var parts = readHead(HANDSHAKE_REQUEST_TYPE, buf); var hreq = parts.head; var adapter = self._getAdapter(hreq); } catch (cause) { err = wrapError('invalid handshake request', cause); } if (err) { done(encodeError(err)); } else { self._receive(parts.tail, adapter, done); } function done(resBuf) { if (!self._writable) { self.once('_writable', function () { done(resBuf); }); return; } var hres = self._createHandshakeResponse(err, hreq); self.emit('handshake', hreq, hres); var payload = [ HANDSHAKE_RESPONSE_TYPE.toBuffer(hres), resBuf ]; self._writable.write({id: id, payload: payload}); if (self._endWritable) { self._writable.end(); } } } function onEnd() { self.destroy(); } function onFinish() { if (readable) { readable .removeListener('data', onRequest) .removeListener('end', onEnd); } self.destroy(true); } }
[ "function", "StatelessListener", "(", "ptcl", ",", "readableFactory", ",", "opts", ")", "{", "MessageListener", ".", "call", "(", "this", ",", "ptcl", ",", "opts", ")", ";", "var", "self", "=", "this", ";", "var", "readable", ";", "process", ".", "nextTi...
MessageListener for stateless transport. This listener expect a handshake to precede each message.
[ "MessageListener", "for", "stateless", "transport", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L923-L990
29,212
cdapio/ui-schema-parser
lib/protocols.js
Message
function Message(name, attrs, opts) { opts = opts || {}; if (!types.isValidName(name)) { throw new Error(f('invalid message name: %s', name)); } this._name = name; var recordName = f('org.apache.avro.ipc.%sRequest', name); this._requestType = types.createType({ name: recordName, type: 'record', namespace: opts.namespace || '', // Don't leak request namespace. fields: attrs.request }, opts); // We remove the record from the registry to prevent it from being exported // in the protocol's schema. delete opts.registry[recordName]; if (!attrs.response) { throw new Error('missing response'); } this._responseType = types.createType(attrs.response, opts); var errors = attrs.errors || []; errors.unshift('string'); this._errorType = types.createType(errors, opts); this._oneWay = !!attrs['one-way']; if (this._oneWay) { if (this._responseType.getTypeName() !== 'null' || errors.length > 1) { throw new Error('unapplicable one-way parameter'); } } }
javascript
function Message(name, attrs, opts) { opts = opts || {}; if (!types.isValidName(name)) { throw new Error(f('invalid message name: %s', name)); } this._name = name; var recordName = f('org.apache.avro.ipc.%sRequest', name); this._requestType = types.createType({ name: recordName, type: 'record', namespace: opts.namespace || '', // Don't leak request namespace. fields: attrs.request }, opts); // We remove the record from the registry to prevent it from being exported // in the protocol's schema. delete opts.registry[recordName]; if (!attrs.response) { throw new Error('missing response'); } this._responseType = types.createType(attrs.response, opts); var errors = attrs.errors || []; errors.unshift('string'); this._errorType = types.createType(errors, opts); this._oneWay = !!attrs['one-way']; if (this._oneWay) { if (this._responseType.getTypeName() !== 'null' || errors.length > 1) { throw new Error('unapplicable one-way parameter'); } } }
[ "function", "Message", "(", "name", ",", "attrs", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "!", "types", ".", "isValidName", "(", "name", ")", ")", "{", "throw", "new", "Error", "(", "f", "(", "'invalid message na...
An Avro message. It contains the various types used to send it (request, error, response).
[ "An", "Avro", "message", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L1081-L1115
29,213
cdapio/ui-schema-parser
lib/protocols.js
Adapter
function Adapter(clientPtcl, serverPtcl, fingerprint) { this._clientPtcl = clientPtcl; this._serverPtcl = serverPtcl; this._fingerprint = fingerprint; // Convenience. this._rsvs = clientPtcl.equals(serverPtcl) ? null : this._createResolvers(); }
javascript
function Adapter(clientPtcl, serverPtcl, fingerprint) { this._clientPtcl = clientPtcl; this._serverPtcl = serverPtcl; this._fingerprint = fingerprint; // Convenience. this._rsvs = clientPtcl.equals(serverPtcl) ? null : this._createResolvers(); }
[ "function", "Adapter", "(", "clientPtcl", ",", "serverPtcl", ",", "fingerprint", ")", "{", "this", ".", "_clientPtcl", "=", "clientPtcl", ";", "this", ".", "_serverPtcl", "=", "serverPtcl", ";", "this", ".", "_fingerprint", "=", "fingerprint", ";", "// Conveni...
Protocol resolution helper. It is used both by emitters and listeners, to respectively decode errors and responses, or requests.
[ "Protocol", "resolution", "helper", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L1204-L1209
29,214
cdapio/ui-schema-parser
lib/protocols.js
wrapError
function wrapError(message, cause) { var err = new Error(f('%s: %s', message, cause.message)); err.cause = cause; return err; }
javascript
function wrapError(message, cause) { var err = new Error(f('%s: %s', message, cause.message)); err.cause = cause; return err; }
[ "function", "wrapError", "(", "message", ",", "cause", ")", "{", "var", "err", "=", "new", "Error", "(", "f", "(", "'%s: %s'", ",", "message", ",", "cause", ".", "message", ")", ")", ";", "err", ".", "cause", "=", "cause", ";", "return", "err", ";"...
Wrap something in an error. @param message {String} The new error's message. @param cause {Error} The cause of the error. It is available as `cause` field on the outer error. This is used to keep the argument of emitters' `'error'` event errors.
[ "Wrap", "something", "in", "an", "error", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L1482-L1486
29,215
cdapio/ui-schema-parser
lib/protocols.js
encodeError
function encodeError(err, header) { return Buffer.concat([ header || new Buffer([0]), // Recover the header if possible. new Buffer([1, 0]), // Error flag and first union index. STRING_TYPE.toBuffer(err.message) ]); }
javascript
function encodeError(err, header) { return Buffer.concat([ header || new Buffer([0]), // Recover the header if possible. new Buffer([1, 0]), // Error flag and first union index. STRING_TYPE.toBuffer(err.message) ]); }
[ "function", "encodeError", "(", "err", ",", "header", ")", "{", "return", "Buffer", ".", "concat", "(", "[", "header", "||", "new", "Buffer", "(", "[", "0", "]", ")", ",", "// Recover the header if possible.", "new", "Buffer", "(", "[", "1", ",", "0", ...
Encode an error and optional header into a valid Avro response. @param err {Error} Error to encode. @param header {Object} Optional response header.
[ "Encode", "an", "error", "and", "optional", "header", "into", "a", "valid", "Avro", "response", "." ]
7fa333e0fe1208de6adc17e597ec847f5ae84124
https://github.com/cdapio/ui-schema-parser/blob/7fa333e0fe1208de6adc17e597ec847f5ae84124/lib/protocols.js#L1506-L1512
29,216
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", ")", ...
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
29,217
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", ";",...
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
29,218
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", "(", "!", "exis...
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
29,219
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", "}", "`"...
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
29,220
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"...
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
29,221
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", ...
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
29,222
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", ":"...
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
29,223
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", "}", ")", "||", "...
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
29,224
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", ")", ";", ...
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
29,225
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", ";", "c...
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
29,226
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'", ")", ")", "{", ...
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
29,227
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'", ")", "{", "// This last predicate is to allow `avro.parse('null')` to work similarly", "// to `avro.parse('int')` and other pr...
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
29,228
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", "]", ")", "{", "// Already imported, return nothing to avoid duplic...
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
29,229
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", ...
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
29,230
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...
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
29,231
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", ")", "...
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
29,232
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", ":", "{", ...
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
29,233
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", ...
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
29,234
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", "=", "getTokenFromDocume...
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
29,235
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", ";", "// All the promises our flush requests have returned. When all these promises are", "// re...
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
29,236
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", ")", "{", "// calling flushAllExpected when there are no expectations is a", "// silly thing to do, and probably means t...
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
29,237
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", ...
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
29,238
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", ";", "t...
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
29,239
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", ...
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
29,240
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
29,241
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", "(", ...
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
29,242
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", ")"...
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
29,243
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", "(", ...
for-each async style
[ "for", "-", "each", "async", "style" ]
146cf5bb829a2b36939cc9fd373750aae3eb00d8
https://github.com/timbeadle/grunt-tv4/blob/146cf5bb829a2b36939cc9fd373750aae3eb00d8/lib/runner.js#L21-L38
29,244
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", ...
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[ "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "...
146cf5bb829a2b36939cc9fd373750aae3eb00d8
https://github.com/timbeadle/grunt-tv4/blob/146cf5bb829a2b36939cc9fd373750aae3eb00d8/lib/runner.js#L85-L100
29,245
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", "===",...
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
29,246
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", ")"...
validate single object
[ "validate", "single", "object" ]
146cf5bb829a2b36939cc9fd373750aae3eb00d8
https://github.com/timbeadle/grunt-tv4/blob/146cf5bb829a2b36939cc9fd373750aae3eb00d8/lib/runner.js#L292-L319
29,247
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",...
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
29,248
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", "(", "obje...
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
29,249
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"...
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
29,250
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", "=", "[", "]", ";", "// Check for required properties", "errors", "=", "[", "...", "errors", ",", "...", "assertProperties", "(", "page", ",", "path", ",", "requiredProperties", ...
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
29,251
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", "("...
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
29,252
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\"...
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
29,253
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", "(", "'executeOnServ...
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
29,254
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...
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
29,255
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
29,256
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", "="...
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
29,257
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", "(", "fil...
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
29,258
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 pro...
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
29,259
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", "=", "undefi...
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
29,260
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", "...
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
29,261
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", "{", "if", "(", "_", ".", "isEmpty",...
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
29,262
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", "("...
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
29,263
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", "=", "findUs...
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
29,264
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"...
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
29,265
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", ")", ",...
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
29,266
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
29,267
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", "===",...
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
29,268
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", ")", ";", "i...
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
29,269
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", ".", "...
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
29,270
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", "==="...
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
29,271
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", ...
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
29,272
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", ")", ")", "{", "// key is keyMapping", "if", "(", "!", "_", ".", "isUndefined", "(", "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
29,273
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...
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
29,274
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", ...
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
29,275
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", "=", "_", "."...
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
29,276
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", "["...
assumes XYZ order
[ "assumes", "XYZ", "order" ]
9069753b0e0076a79d6337d8e98469ec2fd89f05
https://github.com/pex-gl/pex-math/blob/9069753b0e0076a79d6337d8e98469ec2fd89f05/euler.js#L7-L16
29,277
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", "("...
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
29,278
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", "(",...
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
29,279
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'", ")", "?", "e...
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
29,280
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", "(...
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
29,281
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", ")", ...
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
29,282
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", "...
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
29,283
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", ",", "er...
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
29,284
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", ...
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
29,285
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", ";", "d...
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
29,286
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", "]", "....
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
29,287
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", "(", "fil...
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
29,288
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", "...
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
29,289
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", ")", ")", "...
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
29,290
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", "(", "'C...
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
29,291
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", "stdo...
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
29,292
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'", ",", "version", ",", "log", ".", "map", "(", "function", "(", "logItem", ")", "{", "return", "' * '", "+", "logItem", ";", "}", ...
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
29,293
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", "}", ")", ";", "...
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
29,294
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", ",", "`", "${"...
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
29,295
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}'", ...
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
29,296
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", ...
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
29,297
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_HE...
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
29,298
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", "(", "u...
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
29,299
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", ".", ...
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