_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q600
customRenderFn
train
function customRenderFn(renderFn) { // The loader context. var _this = this return function (engine, template, locals, options) { return renderFn.call(_this, template, locals, options) } }
javascript
{ "resource": "" }
q601
render
train
function render(engine, str, locals, engineOptions) { try { var output = engine.render(engine.engine, str, locals, engineOptions) } catch(e) { throw new Error( NAME + ': there was a problem rendering the template:\n' + e) } return output }
javascript
{ "resource": "" }
q602
init
train
function init(type) { return function(params) { if (!params) { params = {}; } var settings = { proxyUrl: params.proxyUrl || defaults.proxyUrl, channel: params.channel || defaults.channel, keepalive: parseFalsey(params.keepalive, defaults.keep...
javascript
{ "resource": "" }
q603
train
function (path, errorMessage) { if (!shell.test('-e', path)) { shell.echo('Error: ' + errorMessage); shell.exit(1); } }
javascript
{ "resource": "" }
q604
merge
train
function merge(dest) { if (dest) { Array.prototype.slice.call(arguments, 1).forEach(function(arg) { Object.keys(arg).forEach(function(key) { dest[key] = arg[key] }) }) } return dest }
javascript
{ "resource": "" }
q605
calculateClockOffset
train
function calculateClockOffset() { const start = Date.now(); let cur = start; // Limit the iterations, just in case we're running in an environment where Date.now() has been mocked and is // constant. for (let i = 0; i < 1e6 && cur === start; i++) { cur = Date.now(); } // At this point |cur| "just" be...
javascript
{ "resource": "" }
q606
train
function (cb) { // check if we have a custom index file set if (settings.index) { // generate the real index file path var indexFile = process.cwd() + '/' + settings.index; // check if the file exists, throw an error otherwise if (!grunt.file.exists(indexFile)) { grunt.log.error...
javascript
{ "resource": "" }
q607
train
function (patternFolder, patterns, cb) { getSourceFile(function generatePatterns(content) { patterns.forEach(function (file) { content += '<hr/>'; content += '<div class="pattern"><div class="display">'; content += file.content; content += '</div><div class="source"><textarea r...
javascript
{ "resource": "" }
q608
train
function (patternFolder, files, cb) { var file, patterns = []; files.forEach(function readPattern(pattern) { file = {filename: pattern}; file.content = grunt.file.read(patternFolder + '/' + file.filename); patterns.push(file); }); // call the outputPatterns function that generates ...
javascript
{ "resource": "" }
q609
train
function (patternFolder, cb) { // read pattern folder fs.readdir(patternFolder, function (err, contents) { // check for errors if (err !== null && err.code === 'ENOENT') { grunt.log.error('Cannot find patterns folder:', patternFolder); cb('Cannot find patterns folder: ' + patternFold...
javascript
{ "resource": "" }
q610
train
function (item) { let x; switch (item.type) { case Type.STRING: case Type.NUMBER: case Type.BOOLEAN: case Type.UNDEFINED: return item.value; case Type.ARRAY: x = []; item.value.forEach(function (e...
javascript
{ "resource": "" }
q611
Persistable
train
function Persistable (key, value) { const __self = this; __self.key = key; // Set value and type of object. if (value === undefined || value === null) { __self.value = undefined; __self.type = typeof undefined; } else if (value instanceof Array) { ...
javascript
{ "resource": "" }
q612
train
function (item) { item.value.sort(function (a, b) { if (a.key < b.key) { return -1; } /* istanbul ignore next */ // Below line exists only for the sake of completeness. Generally the array will // always be sorted, and therefore it is i...
javascript
{ "resource": "" }
q613
addTracingToResolvers
train
function addTracingToResolvers(schema) { // XXX this is a hacky way of making sure that the schema only gets decorated // with tracer once. if (schema._apolloTracerApplied) { // console.log('Tracing already added to resolve functions. Not adding again.'); return; } // eslint-disable-next-line no-param...
javascript
{ "resource": "" }
q614
instrumentSchemaForExpressGraphQL
train
function instrumentSchemaForExpressGraphQL(schema) { addTracingToResolvers(schema); addSchemaLevelResolveFunction(schema, (root, args, ctx, info) => { const operation = print(info.operation); const fragments = Object.keys(info.fragments).map(k => print(info.fragments[k])).join('\n'); ctx.tracer.log('re...
javascript
{ "resource": "" }
q615
indexOfNode
train
function indexOfNode (host, node) { const chs = host.childNodes; const chsLen = chs.length; for (let a = 0; a < chsLen; a++) { if (chs[a] === node) { return a; } } return -1; }
javascript
{ "resource": "" }
q616
registerNode
train
function registerNode (host, node, insertBefore, func) { const index = indexOfNode(host, insertBefore); eachNodeOrFragmentNodes(node, (eachNode, eachIndex) => { func(eachNode, eachIndex); if (canPatchNativeAccessors) { nodeToParentNodeMap.set(eachNode, host); } else { staticProp(eachNode, '...
javascript
{ "resource": "" }
q617
addNodeToSlot
train
function addNodeToSlot (slot, node, insertBefore) { const isInDefaultMode = slot.assignedNodes().length === 0; registerNode(slot, node, insertBefore, eachNode => { if (isInDefaultMode) { slot.__insertBefore(eachNode, insertBefore !== undefined ? insertBefore : null); } }); }
javascript
{ "resource": "" }
q618
train
function () { if (!window.ove.context.isInitialized) { log.debug('Requesting an update of state configuration from server'); window.ove.socket.send({ action: Constants.Action.READ }); } }
javascript
{ "resource": "" }
q619
train
function (req, res) { let sectionId = req.query.oveSectionId; if (sectionId === undefined) { log.debug('Returning parsed result of ' + Constants.SPACES_JSON_FILENAME); Utils.sendMessage(res, HttpStatus.OK, JSON.stringify(server.spaces)); } else if (!server.state.get('sect...
javascript
{ "resource": "" }
q620
train
function () { if (Utils.isNullOrEmpty(server.spaceGeometries) && !Utils.isNullOrEmpty(server.spaces)) { Object.keys(server.spaces).forEach(function (s) { const geometry = { w: Number.MIN_VALUE, h: Number.MIN_VALUE }; server.spaces[s].forEach(function (e) { ...
javascript
{ "resource": "" }
q621
train
function (req, res) { const spaceName = req.params.name; const geometry = _getSpaceGeometries()[spaceName]; if (Utils.isNullOrEmpty(geometry)) { log.error('Invalid Space', 'name:', spaceName); Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid...
javascript
{ "resource": "" }
q622
train
function (sectionId) { let section = server.state.get('sections[' + sectionId + ']'); if (section.app && section.app.url) { log.debug('Flushing application at URL:', section.app.url); request.post(section.app.url + '/instances/' + sectionId + '/flush', _handleRequestError); ...
javascript
{ "resource": "" }
q623
train
function (req, res) { _updateSections({ moveTo: req.body }, req.query.space, req.query.groupId, res); }
javascript
{ "resource": "" }
q624
train
function (req, res) { let sectionId = req.params.id; let s = server.state.get('sections[' + sectionId + ']'); if (Utils.isNullOrEmpty(s)) { log.debug('Unable to read configuration for section id:', sectionId); Utils.sendEmptySuccess(res); return; } ...
javascript
{ "resource": "" }
q625
train
function (req, res) { let sectionId = req.params.id; if (Utils.isNullOrEmpty(server.state.get('sections[' + sectionId + ']'))) { log.error('Invalid Section Id:', sectionId); Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid section id' })); }...
javascript
{ "resource": "" }
q626
train
function (groupId, operation, req, res) { const validateSections = function (group) { let valid = true; const sections = server.state.get('sections'); group.forEach(function (e) { if (Utils.isNullOrEmpty(sections[e])) { valid = false; ...
javascript
{ "resource": "" }
q627
train
function (req, res) { let groupId = req.params.id; if (Utils.isNullOrEmpty(server.state.get('groups[' + groupId + ']'))) { log.error('Invalid Group Id:', groupId); Utils.sendMessage(res, HttpStatus.BAD_REQUEST, JSON.stringify({ error: 'invalid group id' })); } else { ...
javascript
{ "resource": "" }
q628
train
function (groupId) { server.state.set('groups[' + groupId + ']', []); let hasNonEmptyGroups = false; server.state.get('groups').forEach(function (e) { if (!Utils.isNullOrEmpty(e)) { hasNonEmptyGroups = true; } }); if (hasNonEmptyGroups) { ...
javascript
{ "resource": "" }
q629
train
function (peerURL) { let host = peerURL; /* istanbul ignore else */ // The host should never be null, empty or undefined based on how this method is used. // This check is an additional precaution. if (host) { if (host.indexOf('//') >= 0) { host = host...
javascript
{ "resource": "" }
q630
focusAtEnd
train
function focusAtEnd(change) { const { value } = change; const document = value.document; return change.collapseToEndOf(document); }
javascript
{ "resource": "" }
q631
ContentAuth
train
function ContentAuth (pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf) { if (!(this instanceof ContentAuth)) { return new ContentAuth(pubkey, sig, blockhashbuf, blockheightnum, parenthashbuf, date, address, contentbuf) } this.initialize() this.fromObject({pubkey, sig, blo...
javascript
{ "resource": "" }
q632
stackChain
train
function stackChain() { this.extend = new TraceModifier(); this.filter = new TraceModifier(); this.format = new StackFormater(); this.version = require('./package.json').version; }
javascript
{ "resource": "" }
q633
BriToPbn
train
function BriToPbn(opts) { if (!(this instanceof BriToPbn)) return new BriToPbn(opts); opts = opts || {}; this.needDirectives = true; this.boardNumber = opts.boardNumber || 1; stream.Transform.call(this, opts); }
javascript
{ "resource": "" }
q634
DgeToPbn
train
function DgeToPbn(opts) { if (!(this instanceof DgeToPbn)) return new DgeToPbn(opts); opts = opts || {}; this.needDirectives = true; this.boardNumber = opts.boardNumber || 1; stream.Transform.call(this, opts); }
javascript
{ "resource": "" }
q635
train
function (manifest, file, callback) { generate(file.src, options, function (err, sriData) { // Make relative if a cwd is specified if (file.orig && file.orig.cwd) { file.id = file.id.replace(file.orig.cwd, ""); sriData.path = sriData.pa...
javascript
{ "resource": "" }
q636
train
function (err, manifest) { if (err) { // Error generating SRI hashes grunt.log.error("Error loading resource: " + err); return done(false); } return saveJson( options, manifest, writeLog(...
javascript
{ "resource": "" }
q637
DupToPbn
train
function DupToPbn(opts) { if (!(this instanceof DupToPbn)) return new DupToPbn(opts); opts = opts || {}; this.needDirectives = true; this.boardNumber = opts.boardNumber || 1; stream.Transform.call(this, opts); }
javascript
{ "resource": "" }
q638
TrailingBlock
train
function TrailingBlock(opts) { opts = opts || {}; opts.type = opts.type || 'paragraph'; opts.match = opts.match || (node => node.type === opts.type); return { validateNode: (node) => { if (node.object !== 'document') { return undefined; } ...
javascript
{ "resource": "" }
q639
relative
train
function relative(a, b, stat) { if (typeof a !== 'string') { throw new TypeError('relative expects a string.'); } if (a == '' && !b) return a; var len = arguments.length; if (len === 1) { b = a; a = process.cwd(); stat = null; } if (len === 2 && typeof b === 'boolean') { b = a; a = process....
javascript
{ "resource": "" }
q640
isDir
train
function isDir(fp, stat) { if (endsWith(fp, '/')) { return true; } if (stat === null) { // try to get the directory info if it hasn't been done yet // to ensure directories containing dots are well handle stat = tryStats(fp); } if (isObject(stat) && typeof stat.isDirectory === 'function') { ...
javascript
{ "resource": "" }
q641
isFile
train
function isFile(fp, stat) { if (stat === true) { stat = tryStats(fp); } return !isDir(fp, stat); }
javascript
{ "resource": "" }
q642
getIntervalRunner
train
function getIntervalRunner (context, actions) { return function itervalRunner () { var i = 0; var len = actions.length; var actionData = null; for (; i < len; i += 1) { actionData = actions[i]; context.executeAction(actionData.action, actionData.params); ...
javascript
{ "resource": "" }
q643
train
function (uuid, action, params, interval) { var actions = null; if (typeof uuid !== 'string' || typeof action !== 'function') { return false; } if (interval === undefined) { if (typeof params === 'number') { interval = params; ...
javascript
{ "resource": "" }
q644
train
function () { var i = 0; var len = 0; var actionData = null; if (!(this.constructor.periodicActions instanceof Array)) { return; } len = this.constructor.periodicActions.length; for (; i < len; i += 1) { actionData = this.constructor.per...
javascript
{ "resource": "" }
q645
train
function (uuid) { var intervalData = null; var i = 0; var len = 0; var actionData = null; if (typeof uuid !== 'string') { return false; } intervalData = uuidMap[uuid]; if (!intervalData) { return false; } uuidMap...
javascript
{ "resource": "" }
q646
train
function () { var i = 0; var len = 0; var uuid = ''; if (!this._periodicActionUUIDs) { return; } len = this._periodicActionUUIDs.length; for (; i < len; i += 1) { uuid = this._periodicActionUUIDs[i]; this.stopPeriodicAction(u...
javascript
{ "resource": "" }
q647
_xmlFileSet
train
function _xmlFileSet(file, element, attributeMapping, options) { const doc = loadXmlFile(file, options); const node = getXmlNode(doc, element); const result = []; if (_.isReallyObject(attributeMapping)) { _.each(attributeMapping, (value, attributeName) => { if (_.isFunction(value)) { result.p...
javascript
{ "resource": "" }
q648
deleteIfEmpty
train
function deleteIfEmpty(file, options) { options = _.opts(options, {deleteDirs: true}); return fileDelete(file, _.extend(_.opts(options), {onlyEmptyDirs: true})); }
javascript
{ "resource": "" }
q649
attachKeybindings
train
function attachKeybindings (binding, method) { if (!binding) return console.warn('attachKeybinding requires character or object for binding'); if (typeof binding === 'string' && !method) console.warn('attachKeybindings requries method as second arg'); if (hasKeybinding(binding, method)) return console.warn(`attac...
javascript
{ "resource": "" }
q650
removeKeybindings
train
function removeKeybindings (bindings, method) { if (!bindings) return; if (typeof bindings === 'string' && !method) console.warn('removeKeybindings requries method as second arg'); if (typeof bindings === 'string') return removeMethod(bindings, method); Object.keys(bindings).forEach((key) => removeMethod(key, b...
javascript
{ "resource": "" }
q651
addMethod
train
function addMethod (char, method) { var keyIsBound = hasKeybinding(char); var listener = keyupHandler.bind(null, char, method); bindings[char] = bindings[char] || {methods: [], listeners: []}; if (keyIsBound) window.removeEventListener('keyup', bindings[char].listeners[0]); bindings[char].methods.unshift(m...
javascript
{ "resource": "" }
q652
removeMethod
train
function removeMethod (char, method) { if (!hasKeybinding(char, method)) return; var fnIndex = bindings[char].methods.indexOf(method); window.removeEventListener('keyup', bindings[char].listeners[fnIndex]); bindings[char].methods.splice(fnIndex, 1); bindings[char].listeners.splice(fnIndex, 1); if (!binding...
javascript
{ "resource": "" }
q653
hasKeybinding
train
function hasKeybinding (key, method) { if (!bindings[key]) return false; return method ? !!~bindings[key].methods.indexOf(method) : true; }
javascript
{ "resource": "" }
q654
keyupHandler
train
function keyupHandler (matchChar, method, evt) { // except for esc, we don't want to fire events when somebody is typing in an input if ((evt.target.tagName !== 'INPUT' && evt.target.tagName !== 'TEXTAREA' && !evt.target.hasAttribute('contenteditable')) || keysMatch(evt, 'esc')) { if (keysMatch(evt, matchChar))...
javascript
{ "resource": "" }
q655
parse
train
function parse(schema, opts) { var attrs = files.load(schema); return attrs.protocol ? protocols.createProtocol(attrs, opts) : types.createType(attrs, opts); }
javascript
{ "resource": "" }
q656
extractFileHeader
train
function extractFileHeader(path, opts) { opts = opts || {}; var decode = opts.decode === undefined ? true : !!opts.decode; var size = Math.max(opts.size || 4096, 4); var fd = fs.openSync(path, 'r'); var buf = new Buffer(size); var pos = 0; var tap = new utils.Tap(buf); var header = null; while (pos ...
javascript
{ "resource": "" }
q657
evaluate
train
function evaluate(conf, parent) { if (!conf || conf.constructor.name !== 'Object') return conf; var val; for (var key in conf) { val = conf[key]; if (typeof val === 'function') val = reduceVal(parent, val); conf[key] = evaluate(val, parent); } return conf; }
javascript
{ "resource": "" }
q658
reduceVal
train
function reduceVal(conf, val) { val = val.call(conf); return typeof val === 'function' ? reduceVal(conf, val) : val; }
javascript
{ "resource": "" }
q659
generateColors
train
function generateColors(conf) { for (var key in conf.color) { if (typeof conf.color[key] !== 'string') continue; conf.color[key] = new Color(conf.color[key]); } return conf; }
javascript
{ "resource": "" }
q660
getUserGroups
train
function getUserGroups(user) { try { const output = runProgram('groups', [user]).trim(); const groupsText = isBusyboxCommand('groups') ? output : output.split(':')[1].trim(); return groupsText.split(/\s+/); } catch (e) { throw new Error(`Cannot resolve user ${user}`); } }
javascript
{ "resource": "" }
q661
fileDelete
train
function fileDelete(src, options) { options = _.sanitize(options, {exclude: [], deleteDirs: true, onlyEmptyDirs: false}); let result = true; const files = _matchingFilesArray(src, options); _.each(files, (f) => { const fileWasDeleted = _fileDelete(f, options); result = result && fileWasDeleted; }); ...
javascript
{ "resource": "" }
q662
rand
train
function rand(options) { options = _.opts(options, {size: 32, ascii: false, alphanumeric: false, numeric: false}); const size = options.size; let data = ''; while (data.length < size) { // ASCII is in range of 0 to 127 let randBytes = crypto.pseudoRandomBytes(Math.max(size, 32)).toString(); /* eslin...
javascript
{ "resource": "" }
q663
base64
train
function base64(text, operation) { operation = operation || 'encode'; if (operation === 'decode') { return (new Buffer(text, 'base64')).toString(); } else { return (new Buffer(text)).toString('base64'); } }
javascript
{ "resource": "" }
q664
createTempFile
train
function createTempFile(options) { options = _.opts(options, {cleanup: true}); return _createTemporaryPath((f) => fs.writeFileSync(f, ''), options.cleanup); }
javascript
{ "resource": "" }
q665
createTempDir
train
function createTempDir(options) { options = _.opts(options, {cleanup: true}); return _createTemporaryPath(fs.mkdirSync, options.cleanup); }
javascript
{ "resource": "" }
q666
parseJson
train
function parseJson(name, type, value) { try { return typeof value === 'string' ? JSON.parse(value) : value; } catch (e) { throwError(name, type, value); } }
javascript
{ "resource": "" }
q667
renderTemplateText
train
function renderTemplateText(template, data, options) { data = _.opts(data, {}); options = _.opts(options, {noEscape: true, compact: false}); // TODO: We should support recursively resolving, as in IB return hb.compile(template, options)(_.defaults(data, globalSettings), {helpers: globalHelpers}); }
javascript
{ "resource": "" }
q668
renderTemplate
train
function renderTemplate(templateFile, data, options) { return renderTemplateText(read(normalizeTemplate(templateFile)), data, options); }
javascript
{ "resource": "" }
q669
renderTemplateToFile
train
function renderTemplateToFile(templateFile, destFile, data, options) { renderTemplateTextToFile(read(templateFile), normalizeFile(destFile), data, options); }
javascript
{ "resource": "" }
q670
stripPathPrefix
train
function stripPathPrefix(p, prefix, options) { if (!prefix) return p; options = _.sanitize(options, {force: false}); p = _fileCleanPath(p); prefix = _fileCleanPath(prefix); if (options.force) { return path.relative(prefix, p); } else { const pathSplit = split(p); const prefixSplit = split(prefix...
javascript
{ "resource": "" }
q671
isEmptyDir
train
function isEmptyDir(dir) { try { return !(fs.readdirSync(dir).length > 0); } catch (e) { if (e.code === 'ENOENT') { // We consider non-existent as empty return true; } throw e; } }
javascript
{ "resource": "" }
q672
size
train
function size(file) { if (!exists(file) || !isFile(file)) { return -1; } else { try { return _fileStats(file).size; } catch (e) { return -1; } } }
javascript
{ "resource": "" }
q673
chmod
train
function chmod(file, permissions, options) { if (!isPlatform('unix')) return; if (!exists(file)) throw new Error(`Path '${file}' does not exists`); const isDir = isDirectory(file); options = _.sanitize(options, {recursive: false}); let filePermissions = null; let dirPermissions = null; if (_.isReallyObje...
javascript
{ "resource": "" }
q674
infer
train
function infer(val, opts) { opts = opts || {}; // Optional custom inference hook. if (opts.valueHook) { var type = opts.valueHook(val, opts); if (type !== undefined) { if (!types.Type.isType(type)) { throw new Error(f('invalid value hook return value: %j', type)); } return type;...
javascript
{ "resource": "" }
q675
createType
train
function createType(attrs, opts) { if (attrs === null) { // Let's be helpful for this common error. throw new Error('invalid type: null (did you mean "null"?)'); } if (Type.isType(attrs)) { return attrs; } opts = opts || {}; opts.registry = opts.registry || {}; var type; if (opts.typeHook ...
javascript
{ "resource": "" }
q676
WrappedUnionType
train
function WrappedUnionType(attrs, opts) { UnionType.call(this, attrs, opts); this._constructors = this._types.map(function (type) { // jshint -W054 var name = type.getName(true); if (name === 'null') { return null; } function ConstructorFunction(name) { return function Branch$(val) ...
javascript
{ "resource": "" }
q677
FixedType
train
function FixedType(attrs, opts) { Type.call(this, attrs, opts); if (attrs.size !== (attrs.size | 0) || attrs.size < 1) { throw new Error(f('invalid %s fixed size', this.getName(true))); } this._size = attrs.size | 0; }
javascript
{ "resource": "" }
q678
MapType
train
function MapType(attrs, opts) { Type.call(this); if (!attrs.values) { throw new Error(f('missing map values: %j', attrs)); } this._values = createType(attrs.values, opts); // Addition by Edwin Elia var keys = attrs.keys; if (!keys) { keys = 'string'; } this._keys = createType(keys, opts); }
javascript
{ "resource": "" }
q679
ArrayType
train
function ArrayType(attrs, opts) { Type.call(this); if (!attrs.items) { throw new Error(f('missing array items: %j', attrs)); } this._items = createType(attrs.items, opts); }
javascript
{ "resource": "" }
q680
stringify
train
function stringify(obj, opts) { EXPORT_ATTRS = opts && opts.exportAttrs; var noDeref = opts && opts.noDeref; // Since JS objects are unordered, this implementation (unfortunately) // relies on engines returning properties in the same order that they are // inserted in. This is not in the JS spec, but can be ...
javascript
{ "resource": "" }
q681
matches
train
function matches(file, patternList, excludePatterList, options) { options = _.sanitize(options, {minimatch: false}); let shouldInclude = false; let shouldExclude = false; const matcher = options.minimatch ? (f, pattern) => minimatch(f, pattern, {dot: true, matchBase: true}) : globMatch; if (!_.isEmpty(patter...
javascript
{ "resource": "" }
q682
userExists
train
function userExists(user) { if (_.isEmpty(findUser(user, {refresh: true, throwIfNotFound: false}))) { return false; } else { return true; } }
javascript
{ "resource": "" }
q683
addQueryToUrl
train
function addQueryToUrl ({ query, decamelizeQuery=true, url }) { if (!query) return const transformedQuery = decamelizeQuery ? decamelizeKeys(query) : query return { url: url + '?' + stringify(transformedQuery) } }
javascript
{ "resource": "" }
q684
load
train
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
{ "resource": "" }
q685
copyBuffer
train
function copyBuffer(buf, pos, len) { var copy = new Buffer(len); buf.copy(copy, 0, pos, pos + len); return copy; }
javascript
{ "resource": "" }
q686
deleteGroup
train
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 (...
javascript
{ "resource": "" }
q687
kill
train
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 { ...
javascript
{ "resource": "" }
q688
contains
train
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
{ "resource": "" }
q689
serializeBody
train
function serializeBody ({ decamelizeBody=true, headers, body }) { if (!body || !isJSONRequest(headers)) return const transformedBody = decamelizeBody ? decamelizeKeys(body) : body return { body: JSON.stringify(transformedBody) } }
javascript
{ "resource": "" }
q690
createProtocol
train
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.names...
javascript
{ "resource": "" }
q691
Protocol
train
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...
javascript
{ "resource": "" }
q692
MessageEmitter
train
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.s...
javascript
{ "resource": "" }
q693
StatelessEmitter
train
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) { t...
javascript
{ "resource": "" }
q694
emit
train
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); ...
javascript
{ "resource": "" }
q695
StatelessListener
train
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, fun...
javascript
{ "resource": "" }
q696
Message
train
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'...
javascript
{ "resource": "" }
q697
Adapter
train
function Adapter(clientPtcl, serverPtcl, fingerprint) { this._clientPtcl = clientPtcl; this._serverPtcl = serverPtcl; this._fingerprint = fingerprint; // Convenience. this._rsvs = clientPtcl.equals(serverPtcl) ? null : this._createResolvers(); }
javascript
{ "resource": "" }
q698
wrapError
train
function wrapError(message, cause) { var err = new Error(f('%s: %s', message, cause.message)); err.cause = cause; return err; }
javascript
{ "resource": "" }
q699
encodeError
train
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
{ "resource": "" }