_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q28900
train
function (callback) { var self = this; function initDispatcher() { debug('init event dispatcher'); self.dispatcher = new EventDispatcher(self.publisher, self); self.dispatcher.start(callback); } this.store.on('connect', function () { self.emit('connect'); }); this.store.on('disconnect', function () { self.emit('disconnect'); }); process.nextTick(function() { tolerate(function(callback) { self.store.connect(callback); }, self.options.timeout || 0, function (err) { if (err) { debug(err); if (callback) callback(err); return; } if (!self.publisher) { debug('no publisher defined'); if (callback) callback(null); return; } initDispatcher(); }); }); }
javascript
{ "resource": "" }
q28901
train
function (query, skip, limit) { if (!this.store.streamEvents) { throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.'); } if (typeof query === 'number') { limit = skip; skip = query; query = {}; }; if (typeof query === 'string') { query = { aggregateId: query }; } return this.store.streamEvents(query, skip, limit); }
javascript
{ "resource": "" }
q28902
train
function (commitStamp, skip, limit) { if (!this.store.streamEvents) { throw new Error('Streaming API is not suppoted by '+(this.options.type || 'inmemory') +' db implementation.'); } if (!commitStamp) { var err = new Error('Please pass in a date object!'); debug(err); throw err; } var self = this; commitStamp = new Date(commitStamp); return this.store.streamEventsSince(commitStamp, skip, limit); }
javascript
{ "resource": "" }
q28903
train
function (query, revMin, revMax) { if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } return this.store.streamEventsByRevision(query, revMin, revMax); }
javascript
{ "resource": "" }
q28904
train
function (commitStamp, skip, limit, callback) { if (!commitStamp) { var err = new Error('Please pass in a date object!'); debug(err); throw err; } if (typeof skip === 'function') { callback = skip; skip = 0; limit = -1; } else if (typeof limit === 'function') { callback = limit; limit = -1; } var self = this; function nextFn(callback) { if (limit < 0) { var resEvts = []; resEvts.next = nextFn; return process.nextTick(function () { callback(null, resEvts) }); } skip += limit; _getEventsSince(commitStamp, skip, limit, callback); } commitStamp = new Date(commitStamp); function _getEventsSince(commitStamp, skip, limit, callback) { self.store.getEventsSince(commitStamp, skip, limit, function (err, evts) { if (err) return callback(err); evts.next = nextFn; callback(null, evts); }); } _getEventsSince(commitStamp, skip, limit, callback); }
javascript
{ "resource": "" }
q28905
train
function (query, revMin, revMax, callback) { if (typeof revMin === 'function') { callback = revMin; revMin = 0; revMax = -1; } else if (typeof revMax === 'function') { callback = revMax; revMax = -1; } if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } var self = this; this.getEventsByRevision(query, revMin, revMax, function(err, evts) { if (err) { return callback(err); } callback(null, new EventStream(self, query, evts)); }); }
javascript
{ "resource": "" }
q28906
train
function (query, revMax, callback) { if (typeof revMax === 'function') { callback = revMax; revMax = -1; } if (typeof query === 'string') { query = { aggregateId: query }; } if (!query.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } var self = this; async.waterfall([ function getSnapshot(callback) { self.store.getSnapshot(query, revMax, callback); }, function getEventStream(snap, callback) { var rev = 0; if (snap && (snap.revision !== undefined && snap.revision !== null)) { rev = snap.revision + 1; } self.getEventStream(query, rev, revMax, function(err, stream) { if (err) { return callback(err); } if (rev > 0 && stream.lastRevision == -1) { stream.lastRevision = snap.revision; } callback(null, snap, stream); }); }], callback ); }
javascript
{ "resource": "" }
q28907
train
function(obj, callback) { if (obj.streamId && !obj.aggregateId) { obj.aggregateId = obj.streamId; } if (!obj.aggregateId) { var err = new Error('An aggregateId should be passed!'); debug(err); if (callback) callback(err); return; } obj.streamId = obj.aggregateId; var self = this; async.waterfall([ function getNewIdFromStorage(callback) { self.getNewId(callback); }, function commit(id, callback) { try { var snap = new Snapshot(id, obj); snap.commitStamp = new Date(); } catch (err) { return callback(err); } self.store.addSnapshot(snap, function(error) { if (self.options.maxSnapshotsCount) { self.store.cleanSnapshots(_.pick(obj, 'aggregateId', 'aggregate', 'context'), callback); } else { callback(error); } }); }], callback ); }
javascript
{ "resource": "" }
q28908
train
function(eventstream, callback) { var self = this; async.waterfall([ function getNewCommitId(callback) { self.getNewId(callback); }, function commitEvents(id, callback) { // start committing. var event, currentRevision = eventstream.currentRevision(), uncommittedEvents = [].concat(eventstream.uncommittedEvents); eventstream.uncommittedEvents = []; self.store.getNextPositions(uncommittedEvents.length, function(err, positions) { if (err) return callback(err) for (var i = 0, len = uncommittedEvents.length; i < len; i++) { event = uncommittedEvents[i]; event.id = id + i.toString(); event.commitId = id; event.commitSequence = i; event.restInCommitStream = len - 1 - i; event.commitStamp = new Date(); currentRevision++; event.streamRevision = currentRevision; if (positions) event.position = positions[i]; event.applyMappings(); } self.store.addEvents(uncommittedEvents, function(err) { if (err) { // add uncommitted events back to eventstream eventstream.uncommittedEvents = uncommittedEvents.concat(eventstream.uncommittedEvents); return callback(err); } if (self.publisher && self.dispatcher) { // push to undispatchedQueue self.dispatcher.addUndispatchedEvents(uncommittedEvents); } else { eventstream.eventsToDispatch = [].concat(uncommittedEvents); } // move uncommitted events to events eventstream.events = eventstream.events.concat(uncommittedEvents); eventstream.currentRevision(); callback(null, eventstream); }); }); }], callback ); }
javascript
{ "resource": "" }
q28909
train
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } this.store.getUndispatchedEvents(query, callback); }
javascript
{ "resource": "" }
q28910
train
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } this.store.getLastEvent(query, callback); }
javascript
{ "resource": "" }
q28911
train
function (query, callback) { if (!callback) { callback = query; query = null; } if (typeof query === 'string') { query = { aggregateId: query }; } var self = this; this.store.getLastEvent(query, function (err, evt) { if (err) return callback(err); callback(null, new EventStream(self, query, evt ? [evt] : [])); }); }
javascript
{ "resource": "" }
q28912
train
function (evtOrId, callback) { if (typeof evtOrId === 'object') { evtOrId = evtOrId.id; } this.store.setEventToDispatched(evtOrId, callback); }
javascript
{ "resource": "" }
q28913
getSections
train
function getSections($, root, relative) { var items = []; var sections = root.children("section[data-type], div[data-type='part']"); sections.each(function(index, el) { var jel = $(el); var header = jel.find("> header"); // create section item var item = { id: jel.attr("id"), type: jel.attr("data-type") }; // find title of section var title = header.length ? header.find("> h1, > h2, > h3, > h4, > h5") : jel.find("> h1, > h2, > h3, > h4, > h5"); if(title.length) { item.label = title.first().text(); } // find level of section var level; if(item.type in levels) { level = levels[item.type]; } else { return; } // find href of section item.relative = relative; if(level <= maxLevel) { item.children = getSections($, jel, relative); } items.push(item); }); return items; }
javascript
{ "resource": "" }
q28914
train
function(config, stream, extras, callback) { var tocFiles = this.tocFiles = []; // First run through every file and get a tree of the section // navigation within that file. Save to our nav object. stream = stream.pipe(through.obj(function(file, enc, cb) { // create cheerio element for file if not present file.$el = file.$el || cheerio.load(file.contents.toString()); // make this work whether or not we have a // full HTML file. var root = file.$el.root(); var body = file.$el('body'); if(body.length) root = body; // add sections to plugin array for use later in the pipeline tocFiles.push({ file: file, sections: getSections(file.$el, root, file.relative) }); cb(null, file); })); callback(null, config, stream, extras); }
javascript
{ "resource": "" }
q28915
relativeTOC
train
function relativeTOC(file, parent) { _.each(parent.children, function(child) { if(child.relative) { var href = ""; if(config.format != "pdf") { var relativeFolder = path.relative(path.dirname(file.relative), path.dirname(child.relative)); href = path.join(relativeFolder, path.basename(child.relative)) } if(child.id) { href += "#" + child.id; } child.href = href; } if(child.children) { child = relativeTOC(file, child); } }); return parent; }
javascript
{ "resource": "" }
q28916
loadConfig
train
function loadConfig(path) { try { var configJSON = JSON.parse(fs.readFileSync(process.cwd() + "/" + path)); console.log("Config file detected: " + path) return configJSON; } catch(e) { console.log("Config file: " + e.toString()) } }
javascript
{ "resource": "" }
q28917
triggerBuild
train
function triggerBuild() { // Pick command lines options that take precedence var cmdConfig = _.pick(argv, ['files', 'verbose']);; // load config file and merge into config var jsonConfig = loadConfig(argv.config || 'magicbook.json'); _.defaults(cmdConfig, jsonConfig); // trigger the build with the new config buildFunction(cmdConfig); return cmdConfig; }
javascript
{ "resource": "" }
q28918
train
function(config, extras, callback) { // load all files in the source folder vfs.src(config.fonts.files) // vinyl-fs dest automatically determines whether a file // should be updated or not, based on the mtime timestamp. // so we don't need to do that manually. .pipe(vfs.dest(path.join(extras.destination, config.fonts.destination))) .on('finish', function() { callback(null, config, extras); }); }
javascript
{ "resource": "" }
q28919
train
function(config, stream, extras, callback) { // Finish the stream so we get a full array of files, that // we can use to figure out whether add prev/next placeholders. streamHelpers.finishWithFiles(stream, function(files) { // loop through each file and get the title of the heading // as well as the relative file path. _.each(files, function(file, i) { var nav = {}; // if there was a file before this one, add placeholders if(files[i-1]) { file.prev = files[i-1]; nav.prev = { label: "MBINSERTPREVLABEL", href: "MBINSERTPREVHREF" } } // if there is a file after this one, add placeholders if(files[i+1]) { file.next = files[i+1]; nav.next = { label: "MBINSERTNEXTLABEL", href: "MBINSERTNEXTHREF" } } _.set(file, "pageLocals.navigation", nav); _.set(file, "layoutLocals.navigation", nav); }); // create new stream from the files stream = streamHelpers.streamFromArray(files); callback(null, config, stream, extras); }); }
javascript
{ "resource": "" }
q28920
train
function(config, stream, extras, callback) { stream = stream.pipe(through.obj(function(file, enc, cb) { var contents = file.contents.toString(); var changed = false; if(file.prev) { changed = true; file.prev.$el = file.prev.$el || cheerio.load(file.prev.contents.toString()); var title = file.prev.$el('h1').first().text(); contents = contents.replace(/MBINSERTPREVLABEL/g, title); var href = path.relative(path.dirname(file.relative), file.prev.relative); contents = contents.replace(/MBINSERTPREVHREF/g, href); } if(file.next) { changed = true; file.next.$el = file.next.$el || cheerio.load(file.next.contents.toString()); var title = file.next.$el('h1').first().text(); contents = contents.replace(/MBINSERTNEXTLABEL/g, title); var href = path.relative(path.dirname(file.relative), file.next.relative); contents = contents.replace(/MBINSERTNEXTHREF/g, href); } if(changed) { file.contents = new Buffer(contents); file.$el = undefined; } cb(null, file); })); callback(null, config, stream, extras); }
javascript
{ "resource": "" }
q28921
mapImages
train
function mapImages(imageMap, srcFolder, destFolder) { return through.obj(function(file, enc, cb) { // find the relative path to image. If any pipe has changed the filename, // it's the original is set in orgRelative, so we look at that first. var relativeFrom = file.orgRelative || file.relative; var relativeTo = path.join(destFolder, file.relative); imageMap[relativeFrom] = relativeTo; cb(null, file); }); }
javascript
{ "resource": "" }
q28922
replaceSrc
train
function replaceSrc(imageMap) { return through.obj(function(file, enc, cb) { file.$el = file.$el || cheerio.load(file.contents.toString()); var changed = false; // loop over each image file.$el("img").each(function(i, el) { // convert el to cheerio el var jel = file.$el(this); var src = jel.attr("src"); // if this image exists in source folder, // replace src with new source if (imageMap[src]) { // this file has changed changed = true; // find the relative path from the image to the file var srcRelative = path.relative( path.dirname(file.relative), imageMap[src] ); jel.attr("src", srcRelative); } else if (!src.match(/^http/)) { console.log("image not found in source folder: " + src); } }); // only if we find an image, replace contents in file if (changed) { file.contents = new Buffer(file.$el("body").html()); } cb(null, file); }); }
javascript
{ "resource": "" }
q28923
serializeParams
train
function serializeParams(params) { for (var key in params) { var param = params[key]; if (param instanceof MediaObject || (param && (params.object !== undefined || params.hub !== undefined || params.sink !== undefined))) { if (param && param.id != null) { params[key] = param.id; } } }; return params; }
javascript
{ "resource": "" }
q28924
encodeRpc
train
function encodeRpc(transaction, method, params, callback) { if (transaction) return transactionOperation.call(transaction, method, params, callback); var object = params.object; if (object && object.transactions && object.transactions.length) { var error = new TransactionNotCommitedException(); error.method = method; error.params = params; return setTimeout(callback, 0, error) }; for (var key in params.operationParams) { var object = params.operationParams[key]; if (object && object.transactions && object.transactions.length) { var error = new TransactionNotCommitedException(); error.method = method; error.params = params; return setTimeout(callback, 0, error) }; } if (transactionsManager.length) return transactionOperation.call(transactionsManager, method, params, callback); var promise = new Promise(function (resolve, reject) { function callback2(error, result) { if (error) return reject(error); resolve(result); }; prevRpc = deferred(params.object, params.operationParams, prevRpc, function (error) { if (error) throw error params = serializeParams(params); params.operationParams = serializeParams(params .operationParams); return encode(method, params, callback2); }) .catch(reject) }); prevRpc_result = promiseCallback(promise, callback); if (method == 'release') prevRpc = prevRpc_result; }
javascript
{ "resource": "" }
q28925
disguise
train
function disguise(target, source, unthenable) { if (source == null || target === source) return target for (var key in source) { if (target[key] !== undefined) continue if (unthenable && (key === 'then' || key === 'catch')) continue if (typeof source[key] === 'function') var descriptor = { value: source[key] } else var descriptor = { get: function () { return source[key] }, set: function (value) { source[key] = value } } descriptor.enumerable = true Object.defineProperty(target, key, descriptor) } return target }
javascript
{ "resource": "" }
q28926
disguiseThenable
train
function disguiseThenable(target, source) { if (target === source) return target if (target.then instanceof Function) { var target_then = target.then function then(onFulfilled, onRejected) { if (onFulfilled != null) onFulfilled = onFulfilled.bind(target) if (onRejected != null) onRejected = onRejected.bind(target) var promise = target_then.call(target, onFulfilled, onRejected) return disguiseThenable(promise, source) } Object.defineProperties(target, { then: { value: then }, catch: { value: promiseCatch } }) } return disguise(target, source) }
javascript
{ "resource": "" }
q28927
getConstructor
train
function getConstructor(type, strict) { var result = register.classes[type.qualifiedType] || register.abstracts[type .qualifiedType] || register.classes[type.type] || register.abstracts[type.type] || register.classes[type] || register.abstracts[type]; if (result) return result; if (type.hierarchy != undefined) { for (var i = 0; i <= type.hierarchy.length - 1; i++) { var result = register.classes[type.hierarchy[i]] || register.abstracts[ type.hierarchy[i]]; if (result) return result; }; } if (strict) { var error = new SyntaxError("Unknown type '" + type + "'") error.type = type throw error } console.warn("Unknown type '", type, "', using MediaObject instead"); return register.abstracts.MediaObject; }
javascript
{ "resource": "" }
q28928
createMediaObject
train
function createMediaObject(item, callback) { var transaction = item.transaction; delete item.transaction; var constructor = createConstructor(item, strict); item = constructor.item; delete constructor.item; var params = item.params || {}; delete item.params; if (params.mediaPipeline == undefined && host instanceof register.classes .MediaPipeline) params.mediaPipeline = host; var params_ = extend({}, params) item.constructorParams = checkParams(params_, constructor.constructorParams, item.type); if (Object.keys(params_)) { item.properties = params_; } if (!Object.keys(item.constructorParams).length) delete item.constructorParams; try { var mediaObject = createObject(constructor) } catch (error) { return callback(error) }; Object.defineProperty(item, 'object', { value: mediaObject }); encodeCreate(transaction, item, callback); return mediaObject }
javascript
{ "resource": "" }
q28929
exec
train
function exec(command, args) { execa.sync(command, args, { stdio: 'inherit', preferLocal: true, }); }
javascript
{ "resource": "" }
q28930
codePointAt
train
function codePointAt(str, idx){ if(idx === undefined){ idx = 0; } var code = str.charCodeAt(idx); // if a high surrogate if (0xD800 <= code && code <= 0xDBFF && idx < str.length - 1){ var hi = code; var low = str.charCodeAt(idx + 1); if (0xDC00 <= low && low <= 0xDFFF){ return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } return hi; } // if a low surrogate if (0xDC00 <= code && code <= 0xDFFF && idx >= 1){ var hi = str.charCodeAt(idx - 1); var low = code; if (0xD800 <= hi && hi <= 0xDBFF){ return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } return low; } //just return the char if an unmatched surrogate half or a //single-char codepoint return code; }
javascript
{ "resource": "" }
q28931
expandFiles
train
function expandFiles(files, workingDirectory) { const promises = []; files.forEach((file) => { if ( file.path !== './package.json' && file.path !== './npm-shrinkwrap.json' ) { promises.push(Promise.resolve(file)); return; } findPackageDependencies(workingDirectory, true).forEach((dep) => { let resolvedPath; try { resolvedPath = forwardSlashes(path.relative( workingDirectory, requireRelative.resolve(dep, workingDirectory), )); if (!resolvedPath.startsWith('.')) { // path.relative won't add "./", but we need it further down the line resolvedPath = `./${resolvedPath}`; } } catch (e) { winston.error(`Failed to resolve "${dep}" relative to ${workingDirectory}`); return; } promises.push(lastUpdate.failSafe(resolvedPath, workingDirectory) .then(({ mtime }) => Promise.resolve({ path: resolvedPath, mtime, packageName: dep, }))); }); }); return Promise.all(promises); }
javascript
{ "resource": "" }
q28932
findAliasesForExports
train
function findAliasesForExports(nodes) { const result = new Set(['exports']); nodes.forEach((node) => { if (node.type !== 'VariableDeclaration') { return; } node.declarations.forEach(({ id, init }) => { if (!init) { return; } if (init.type !== 'Identifier') { return; } if (init.name !== 'exports') { return; } // We have something like // var foo = exports; result.add(id.name); }); }); return result; }
javascript
{ "resource": "" }
q28933
stringify
train
function stringify (gj) { if (gj.type === 'Feature') { gj = gj.geometry; } function pairWKT (c) { return c.join(' '); } function ringWKT (r) { return r.map(pairWKT).join(', '); } function ringsWKT (r) { return r.map(ringWKT).map(wrapParens).join(', '); } function multiRingsWKT (r) { return r.map(ringsWKT).map(wrapParens).join(', '); } function wrapParens (s) { return '(' + s + ')'; } switch (gj.type) { case 'Point': return 'POINT (' + pairWKT(gj.coordinates) + ')'; case 'LineString': return 'LINESTRING (' + ringWKT(gj.coordinates) + ')'; case 'Polygon': return 'POLYGON (' + ringsWKT(gj.coordinates) + ')'; case 'MultiPoint': return 'MULTIPOINT (' + ringWKT(gj.coordinates) + ')'; case 'MultiPolygon': return 'MULTIPOLYGON (' + multiRingsWKT(gj.coordinates) + ')'; case 'MultiLineString': return 'MULTILINESTRING (' + ringsWKT(gj.coordinates) + ')'; case 'GeometryCollection': return 'GEOMETRYCOLLECTION (' + gj.geometries.map(stringify).join(', ') + ')'; default: throw new Error('stringify requires a valid GeoJSON Feature or geometry object as input'); } }
javascript
{ "resource": "" }
q28934
sendVerificationEmail
train
function sendVerificationEmail (req, res, next) { // skip if we don't need to send the email if (!req.sendVerificationEmail) { next() // send the email } else { var user = req.user var ttl = (settings.emailVerification && settings.emailVerification.tokenTTL) || (3600 * 24 * 7) OneTimeToken.issue({ ttl: ttl, sub: user._id, use: 'emailVerification' }, function (err, token) { if (err) { return next(err) } var params = { token: token._id } ;[ 'redirect_uri', 'client_id', 'response_type', 'scope' ] .forEach(function (key) { var value = req.connectParams[key] if (value) { params[key] = value } }) // build email link var verifyURL = url.parse(settings.issuer) verifyURL.pathname = 'email/verify' verifyURL.query = params // email template data var locals = { email: user.email, name: { first: user.givenName, last: user.familyName }, verifyURL: url.format(verifyURL) } // Send verification email mailer.getMailer().sendMail('verifyEmail', locals, { to: user.email, subject: 'Verify your e-mail address' }, function (err, responseStatus) { if (err) { } // TODO: REQUIRES REFACTOR TO MAIL QUEUE next() }) }) } }
javascript
{ "resource": "" }
q28935
determineProvider
train
function determineProvider (req, res, next) { var providerID = req.params.provider || req.body.provider if (providerID && settings.providers[providerID]) { req.provider = providers[providerID] } next() }
javascript
{ "resource": "" }
q28936
setUserOnRequest
train
function setUserOnRequest (req, res, next) { if (!req.session || !req.session.user) { return next() } User.get(req.session.user, function (err, user) { if (err) { return next(err) } if (!user) { delete req.session.user return next() } req.user = user next() }) }
javascript
{ "resource": "" }
q28937
hashPassword
train
function hashPassword (data) { var password = data.password var hash = data.hash if (password) { var salt = bcrypt.genSaltSync(10) hash = bcrypt.hashSync(password, salt) } this.hash = hash }
javascript
{ "resource": "" }
q28938
train
function (req, callback) { var params = req.body var clientId = params.client_id var clientSecret = params.client_secret // missing credentials if (!clientId || !clientSecret) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Missing client credentials', statusCode: 400 })) } Client.get(clientId, function (err, client) { if (err) { return callback(err) } // Unknown client if (!client) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Unknown client identifier', statusCode: 401 })) } // Mismatching secret if (client.client_secret !== clientSecret) { return callback(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Mismatching client secret', statusCode: 401 })) } callback(null, client) }) }
javascript
{ "resource": "" }
q28939
dnToDomain
train
function dnToDomain (dn) { if (!dn || typeof dn !== 'string') { return null } var matches = domainDnRegex.exec(dn) if (matches) { return matches[1].replace(dnPartRegex, '$1.').toLowerCase() } else { return null } }
javascript
{ "resource": "" }
q28940
normalizeDN
train
function normalizeDN (dn) { if (!dn || typeof dn !== 'string') { return null } var normalizedDN = '' // Take advantage of replace() to grab the matched segments of the DN. If what // is left over contains unexpected characters, we assume the original DN was // malformed. var extra = dn.replace(dnPartRegex, function (match) { normalizedDN += match.toLowerCase() + ',' return '' }) if (!normalizedDN) { return null } if (badExtra.test(extra)) { return null } return normalizedDN.substr(0, normalizedDN.length - 1) }
javascript
{ "resource": "" }
q28941
authorizationCodeGrant
train
function authorizationCodeGrant (code, done) { var endpoint = this.endpoints.token var provider = this.provider var client = this.client var url = endpoint.url var method = endpoint.method && endpoint.method.toLowerCase() var auth = endpoint.auth var parser = endpoint.parser var accept = endpoint.accept || 'application/json' var params = {} // required token parameters params.grant_type = 'authorization_code' params.code = code params.redirect_uri = provider.redirect_uri // start building the request var req = request[method || 'post'](url) // Authenticate the client with HTTP Basic if (auth === 'client_secret_basic') { req.set('Authorization', 'Basic ' + this.base64credentials()) } // Authenticate the client with POST params if (auth === 'client_secret_post') { params.client_id = client.client_id params.client_secret = client.client_secret } // Add request body params and set other headers req.send(qs.stringify(params)) req.set('accept', accept) req.set('user-agent', agent) // Execute the request return req.end(function (err, res) { if (err) { return done(err) } var response = (parser === 'x-www-form-urlencoded') ? qs.parse(res.text) : res.body if (res.statusCode !== 200) { return done(response) } done(null, response) }) }
javascript
{ "resource": "" }
q28942
train
function (done) { Client.listByTrusted('true', { select: [ '_id', 'client_name', 'client_uri', 'application_type', 'logo_uri', 'trusted', 'scopes', 'created', 'modified' ] }, function (err, clients) { if (err) { return done(err) } done(null, clients) }) }
javascript
{ "resource": "" }
q28943
train
function (done) { user.authorizedScope(function (err, scopes) { if (err) { return done(err) } done(null, scopes) }) }
javascript
{ "resource": "" }
q28944
train
function (done) { var index = 'users:' + user._id + ':clients' Client.__client.zrevrange(index, 0, -1, function (err, ids) { if (err) { return done(err) } done(null, ids) }) }
javascript
{ "resource": "" }
q28945
setOPBrowserState
train
function setOPBrowserState (event) { var key = 'anvil.connect.op.state' var current = localStorage[key] var update = event.data if (current !== update) { document.cookie = 'anvil.connect.op.state=' + update localStorage['anvil.connect.op.state'] = update } }
javascript
{ "resource": "" }
q28946
pushToRP
train
function pushToRP (event) { if (source) { console.log('updating RP: changed') source.postMessage('changed', origin) } else { console.log('updateRP called but source undefined') } }
javascript
{ "resource": "" }
q28947
respondToRPMessage
train
function respondToRPMessage (event) { var parser, messenger, clientId, rpss, salt, opbs, input, opss, comparison // Parse message origin origin = event.origin parser = document.createElement('a') parser.href = document.referrer messenger = parser.protocol + '//' + parser.host // Ignore the message if origin doesn't match if (origin !== messenger) { return } // get a reference to the source so we can message it // immediately in response to a change in sessionState source = event.source // Parse the message clientId = event.data.split(' ')[0] rpss = event.data.split(' ')[1] salt = rpss.split('.')[1] // Validate message syntax if (!clientId || !rpss || !salt) { event.source.postMessage('error', origin) } // Get the OP browser state opbs = getOPBrowserState() // Recalculate session state for comparison input = [clientId, origin, opbs, salt].join(' ') opss = [CryptoJS.SHA256(input), salt].join('.') // Compare the RP session state with the OP session state comparison = compareSessionState(rpss, opss) // Compare session state and reply to RP event.source.postMessage(comparison, origin) }
javascript
{ "resource": "" }
q28948
getBearerToken
train
function getBearerToken (req, res, next) { // check for access token in the authorization header if (req.authorization.scheme && req.authorization.scheme.match(/Bearer/i)) { req.bearer = req.authorization.credentials } // check for access token in the query params if (req.query && req.query.access_token) { if (req.bearer) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Multiple authentication methods', statusCode: 400 })) } req.bearer = req.query.access_token } // check for access token in the request body if (req.body && req.body.access_token) { if (req.bearer) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Multiple authentication methods', statusCode: 400 })) } if (req.headers && req.headers['content-type'] !== 'application/x-www-form-urlencoded') { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid content-type', statusCode: 400 })) } req.bearer = req.body.access_token } next() }
javascript
{ "resource": "" }
q28949
selectConnectParams
train
function selectConnectParams (req, res, next) { req.connectParams = req[lookupField[req.method]] || {} next() }
javascript
{ "resource": "" }
q28950
train
function (done) { // the token is random if (token.indexOf('.') === -1) { AccessToken.get(token, function (err, instance) { if (err) { return done(err) } if (!instance) { return done(new UnauthorizedError({ realm: 'user', error: 'invalid_request', error_description: 'Unknown access token', statusCode: 401 })) } done(null, { jti: instance.at, iss: instance.iss, sub: instance.uid, aud: instance.cid, iat: instance.created, exp: instance.created + instance.ei, scope: instance.scope }) }) // the token is not random } else { done() } }
javascript
{ "resource": "" }
q28951
determineClientScope
train
function determineClientScope (req, res, next) { var params = req.connectParams var subject = req.client var scope = params.scope || subject.default_client_scope if (params.grant_type === 'client_credentials') { Scope.determine(scope, subject, function (err, scope, scopes) { if (err) { return next(err) } req.scope = scope req.scopes = scopes next() }) } else { next() } }
javascript
{ "resource": "" }
q28952
unstashParams
train
function unstashParams (req, res, next) { // OAuth 2.0 callbacks should have a state param // OAuth 1.0 must use the session to store the state value var id = req.query.state || req.session.state var key = 'authorization:' + id if (!id) { // && request is OAuth 2.0 return next(new MissingStateError()) } client.get(key, function (err, params) { if (err) { return next(err) } // This handles expired and mismatching state params if (!params) { return next(new ExpiredAuthorizationRequestError()) } try { req.connectParams = JSON.parse(params) } catch (err) { next(err) } next() }) }
javascript
{ "resource": "" }
q28953
verifyAuthorizationCode
train
function verifyAuthorizationCode (req, res, next) { var params = req.connectParams if (params.grant_type === 'authorization_code') { AuthorizationCode.getByCode(params.code, function (err, ac) { if (err) { return next(err) } // Can't find authorization code if (!ac) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization not found', statusCode: 400 })) } // Authorization code has been previously used if (ac.used === true) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization code invalid', statusCode: 400 })) } // Authorization code is expired if (nowSeconds() > ac.expires_at) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Authorization code expired', statusCode: 400 })) } // Mismatching redirect uri if (ac.redirect_uri !== params.redirect_uri) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Mismatching redirect uri', statusCode: 400 })) } // Mismatching client id if (ac.client_id !== req.client._id) { return next(new AuthorizationError({ error: 'invalid_grant', error_description: 'Mismatching client id', statusCode: 400 })) } // Mismatching user id // if (ac.user_id !== req.user._id) { // return next(new AuthorizationError({ // error: 'invalid_grant', // error_description: 'Mismatching client id', // statusCode: 400 // })) // } req.code = ac // Update the code to show that it's been used. AuthorizationCode.patch(ac._id, { used: true }, function (err) { next(err) }) }) } else { next() } }
javascript
{ "resource": "" }
q28954
parseAuthorizationHeader
train
function parseAuthorizationHeader (req, res, next) { // parse the header if it's present in the request if (req.headers && req.headers.authorization) { var components = req.headers.authorization.split(' ') var scheme = components[0] var credentials = components[1] // ensure the correct number of components if (components.length !== 2) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid authorization header', statusCode: 400 })) } // ensure the scheme is valid if (!scheme.match(/Basic|Bearer|Digest/i)) { return next(new UnauthorizedError({ error: 'invalid_request', error_description: 'Invalid authorization scheme', statusCode: 400 })) } req.authorization = { scheme: scheme, credentials: credentials } // otherwise add an empty authorization object } else { req.authorization = {} } next() }
javascript
{ "resource": "" }
q28955
createUser
train
function createUser (req, res, next) { User.insert(req.body, { private: true }, function (err, user) { if (err) { res.render('signup', { params: qs.stringify(req.body), request: req.body, providers: settings.providers, error: err.message }) } else { authenticator.dispatch('password', req, res, next, function (err, user, info) { if (err) { return next(err) } if (!user) { } else { authenticator.login(req, user) req.sendVerificationEmail = req.provider.emailVerification.enable req.flash('isNewUser', true) next() } }) } }) }
javascript
{ "resource": "" }
q28956
verifyClientToken
train
function verifyClientToken (req, res, next) { var header = req.headers['authorization'] // missing header if (!header) { return next(new UnauthorizedError({ realm: 'client', error: 'unauthorized_client', error_description: 'Missing authorization header', statusCode: 403 })) // header found } else { var jwt = header.replace('Bearer ', '') var token = ClientToken.decode(jwt, settings.keys.sig.pub) // failed to decode if (!token || token instanceof Error) { next(new UnauthorizedError({ realm: 'client', error: 'unauthorized_client', error_description: 'Invalid access token', statusCode: 403 })) // decoded successfully } else { // validate token req.token = token next() } } }
javascript
{ "resource": "" }
q28957
render
train
function render (template, locals, callback) { var engineExt = engineName.charAt(0) === '.' ? engineName : ('.' + engineName) var tmplPath = path.join(templatesDir, template + engineExt) var origTmplPath = path.join(origTemplatesDir, template + engineExt) function renderToText (html) { var text = htmlToText.fromString(html, { wordwrap: 72 // A little less than 80 characters per line is the de-facto // standard for e-mails to allow for some room for quoting // and e-mail client UI elements (e.g. scrollbar) }) callback(null, html, text) } engine(tmplPath, locals) .then(renderToText) .catch(function () { engine(origTmplPath, locals) .then(renderToText) .catch(function (err) { callback(err) }) }) }
javascript
{ "resource": "" }
q28958
sendMail
train
function sendMail (template, locals, options, callback) { var self = this this.render(template, locals, function (err, html, text) { if (err) { return callback(err) } self.transport.sendMail({ from: options.from || defaultFrom, to: options.to, subject: options.subject, html: html, text: text }, callback) }) }
javascript
{ "resource": "" }
q28959
setSessionAmr
train
function setSessionAmr (session, amr) { if (amr) { if (!Array.isArray(amr)) { session.amr = [amr] } else if (session.amr.indexOf(amr) === -1) { session.amr.push(amr) } } }
javascript
{ "resource": "" }
q28960
isOOB
train
function isOOB (cb) { User.listByRoles('authority', function (err, users) { if (err) { return cb(err) } // return true if there are no authority users return cb(null, !users || !users.length) }) }
javascript
{ "resource": "" }
q28961
readSetupToken
train
function readSetupToken (cb) { var token var write = false try { // try to read setup token from filesystem token = keygen.loadSetupToken() // if token is blank, try to generate a new token and save it if (!token.trim()) { write = true } } catch (err) { // if unable to read, try to generate a new token and save it write = true } if (write) { try { token = keygen.generateSetupToken() } catch (err) { // if we can't write the token to disk, something is very wrong return cb(err) } } // return the token cb(null, token) }
javascript
{ "resource": "" }
q28962
verifyClientIdentifiers
train
function verifyClientIdentifiers (req, res, next) { // mismatching client identifiers if (req.token.payload.sub !== req.params.clientId) { return next(new AuthorizationError({ error: 'unauthorized_client', error_description: 'Mismatching client id', statusCode: 403 })) // all's well } else { next() } }
javascript
{ "resource": "" }
q28963
verifyRedirectURI
train
function verifyRedirectURI (req, res, next) { var params = req.connectParams Client.get(params.client_id, { private: true }, function (err, client) { if (err) { return next(err) } // The client must be registered. if (!client || client.redirect_uris.indexOf(params.redirect_uri) === -1) { delete req.connectParams.client_id delete req.connectParams.redirect_uri delete req.connectParams.response_type delete req.connectParams.scope return next() } // Make client available to downstream middleware. req.client = client next() }) }
javascript
{ "resource": "" }
q28964
determineUserScope
train
function determineUserScope (req, res, next) { var params = req.connectParams var scope = params.scope var subject = req.user Scope.determine(scope, subject, function (err, scope, scopes) { if (err) { return next(err) } req.scope = scope req.scopes = scopes next() }) }
javascript
{ "resource": "" }
q28965
promptToAuthorize
train
function promptToAuthorize (req, res, next) { var params = req.connectParams var client = req.client var user = req.user var scopes = req.scopes // The client is not trusted and the user has yet to decide on consent if (client.trusted !== true && typeof params.authorize === 'undefined') { // check for pre-existing consent AccessToken.exists(user._id, client._id, function (err, exists) { if (err) { return next(err) } // if there's an existin authorization, // reuse it and continue if (exists) { params.authorize = 'true' next() // otherwise, prompt for consent } else { // render the consent view if (req.path === '/authorize') { res.render('authorize', { request: params, client: client, user: user, scopes: scopes }) // redirect to the authorize endpoint } else { res.redirect('/authorize?' + qs.stringify(params)) } } }) // The client is trusted and consent is implied. } else if (client.trusted === true) { params.authorize = 'true' next() // The client is not trusted and consent is decided } else { next() } }
javascript
{ "resource": "" }
q28966
verifyClientRegistration
train
function verifyClientRegistration (req, res, next) { // check if we have a token and a token is required var registration = req.body var claims = req.claims var clientRegType = settings.client_registration var required = (registration.trusted || clientRegType !== 'dynamic') var trustedRegScope = settings.trusted_registration_scope var regScope = settings.registration_scope // can't continue because we don't have a token if (!(claims && claims.sub) && required) { return next(new UnauthorizedError({ realm: 'user', error: 'invalid_request', error_description: 'Missing access token', statusCode: 400 })) } // we have a token, so let's verify it if (claims && claims.sub) { // verify the trusted registration scope if (registration.trusted && !hasScope(claims, trustedRegScope)) { return next(new UnauthorizedError({ realm: 'user', error: 'insufficient_scope', error_description: 'User does not have permission', statusCode: 403 })) } // verify the registration scope if (!registration.trusted && clientRegType === 'scoped' && !hasScope(claims, regScope)) { return next(new UnauthorizedError({ realm: 'user', error: 'insufficient_scope', error_description: 'User does not have permission', statusCode: 403 })) } next() // authorization not required/provided } else { next() } }
javascript
{ "resource": "" }
q28967
validateTokenParams
train
function validateTokenParams (req, res, next) { var params = req.body // missing grant type if (!params.grant_type) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing grant type', statusCode: 400 })) } // unsupported grant type if (grantTypes.indexOf(params.grant_type) === -1) { return next(new AuthorizationError({ error: 'unsupported_grant_type', error_description: 'Unsupported grant type', statusCode: 400 })) } // missing authorization code if (params.grant_type === 'authorization_code' && !params.code) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing authorization code', statusCode: 400 })) } // missing redirect uri if (params.grant_type === 'authorization_code' && !params.redirect_uri) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing redirect uri', statusCode: 400 })) } // missing refresh token if (params.grant_type === 'refresh_token' && !params.refresh_token) { return next(new AuthorizationError({ error: 'invalid_request', error_description: 'Missing refresh token', statusCode: 400 })) } next() }
javascript
{ "resource": "" }
q28968
stashParams
train
function stashParams (req, res, next) { var id = crypto.randomBytes(10).toString('hex') var key = 'authorization:' + id var ttl = 1200 // 20 minutes var params = JSON.stringify(req.connectParams) var multi = client.multi() req.session.state = id req.authorizationId = id multi.set(key, params) multi.expire(key, ttl) multi.exec(function (err) { return next(err) }) }
javascript
{ "resource": "" }
q28969
getAuthorizedScopes
train
function getAuthorizedScopes (req, res, next) { // Get the scopes authorized for the verified and decoded token var scopeNames = req.claims.scope && req.claims.scope.split(' ') Scope.get(scopeNames, function (err, scopes) { if (err) { return next(err) } req.scopes = scopes next() }) }
javascript
{ "resource": "" }
q28970
writev
train
function writev (chunks, cb) { var buffers = new Array(chunks.length) for (var i = 0; i < chunks.length; i++) { if (typeof chunks[i].chunk === 'string') { buffers[i] = Buffer.from(chunks[i], 'utf8') } else { buffers[i] = chunks[i].chunk } } this._write(Buffer.concat(buffers), 'binary', cb) }
javascript
{ "resource": "" }
q28971
onTriggerClick
train
function onTriggerClick(e, noFocus) { toggleSubmenu(elements.trigger, (_, done) => { Classlist(elements.trigger).toggle(ACTIVE_CLASS); const wasActive = Classlist(elements.menu).contains(ACTIVE_CLASS); const first = wasActive ? ACTIVE_CLASS : 'dqpl-show'; const second = first === ACTIVE_CLASS ? 'dqpl-show' : ACTIVE_CLASS; Classlist(elements.menu).toggle(first); if (elements.scrim) { Classlist(elements.scrim).toggle('dqpl-scrim-show'); } setTimeout(() => { Classlist(elements.menu).toggle(second); if (elements.scrim) { Classlist(elements.scrim).toggle('dqpl-scrim-fade-in'); } setTimeout(() => done(noFocus)); }, 100); }); }
javascript
{ "resource": "" }
q28972
toggleSubmenu
train
function toggleSubmenu(trigger, toggleFn) { const droplet = document.getElementById(trigger.getAttribute('aria-controls')); if (!droplet) { return; } toggleFn(droplet, (noFocus, focusTarget) => { const prevExpanded = droplet.getAttribute('aria-expanded'); const wasCollapsed = !prevExpanded || prevExpanded === 'false'; droplet.setAttribute('aria-expanded', wasCollapsed ? 'true' : 'false'); if (focusTarget) { focusTarget.focus(); } else if (!noFocus) { let active = queryAll('.dqpl-menuitem-selected', droplet).filter(isVisible); active = active.length ? active : queryAll('[role="menuitem"][tabindex="0"]', droplet).filter(isVisible); let focusMe = wasCollapsed ? active[0] : closest(droplet, '[aria-controls][role="menuitem"]'); focusMe = focusMe || elements.trigger; if (focusMe) { focusMe.focus(); } } }); }
javascript
{ "resource": "" }
q28973
rndid
train
function rndid(len) { len = len || 8; const id = rndm(len); if (document.getElementById(id)) { return rndid(len); } return id; }
javascript
{ "resource": "" }
q28974
init
train
function init (options) { if (typeof options === 'string') { options = { base: options } } options = options || {} // There is probably 99% chance that the project root directory in located // above the node_modules directory var base = nodePath.resolve( options.base || nodePath.join(__dirname, '../..') ) var packagePath = base.replace(/\/package\.json$/, '') + '/package.json' try { var npmPackage = require(packagePath) } catch (e) { // Do nothing } if (typeof npmPackage !== 'object') { throw new Error('Unable to read ' + packagePath) } // // Import aliases // var aliases = npmPackage._moduleAliases || {} for (var alias in aliases) { if (aliases[alias][0] !== '/') { aliases[alias] = nodePath.join(base, aliases[alias]) } } addAliases(aliases) // // Register custom module directories (like node_modules) // if (npmPackage._moduleDirectories instanceof Array) { npmPackage._moduleDirectories.forEach(function (dir) { if (dir === 'node_modules') return var modulePath = nodePath.join(base, dir) addPath(modulePath) }) } }
javascript
{ "resource": "" }
q28975
train
function() { console.log('start : init test : ' + bench.initFcts.length); for (let i = 0; i < bench.initFcts.length; i++) { console.log( 'initializing test data ' + (i + 1) + '/' + bench.initFcts.length ); if (bench.initFcts[i]) { bench.initFcts[i].call(this, bench.CONN.MARIADB.drv); } } this.currentNb = 0; console.log('initializing test data done'); }
javascript
{ "resource": "" }
q28976
train
function(event) { this.currentNb++; if (this.currentNb < this.length) pingAll(connList); //to avoid mysql2 taking all the server memory if (promiseMysql2 && promiseMysql2.clearParserCache) promiseMysql2.clearParserCache(); if (mysql2 && mysql2.clearParserCache) mysql2.clearParserCache(); console.log(event.target.toString()); const drvType = event.target.options.drvType; const benchTitle = event.target.options.benchTitle + ' ( sql: ' + event.target.options.displaySql + ' )'; const iteration = 1 / event.target.times.period; const variation = event.target.stats.rme; if (!bench.reportData[benchTitle]) { bench.reportData[benchTitle] = []; } if (drvType !== 'warmup') { bench.reportData[benchTitle].push({ drvType: drvType, iteration: iteration, variation: variation }); } }
javascript
{ "resource": "" }
q28977
train
function(pool, iteration, timeoutEnd) { return new Promise(function(resolve, reject) { const creationTryout = function(resolve, reject) { if (closed) { reject( Errors.createError( 'Cannot create new connection to pool, pool closed', true, null, '08S01', Errors.ER_ADD_CONNECTION_CLOSED_POOL, null ) ); return; } iteration++; createConnectionPool(pool) .then(conn => { resolve(conn); }) .catch(err => { //if timeout is reached or authentication fail return error if ( closed || (err.errno && (err.errno === 1524 || err.errno === 1045 || err.errno === 1698)) || timeoutEnd < Date.now() ) { reject(err); return; } setTimeout(creationTryout.bind(null, resolve, reject), 500); }); }; //initial without timeout creationTryout(resolve, reject); }); }
javascript
{ "resource": "" }
q28978
train
function(pool) { if ( !connectionInCreation && pool.idleConnections() < opts.minimumIdle && pool.totalConnections() < opts.connectionLimit && !closed ) { connectionInCreation = true; process.nextTick(() => { const timeoutEnd = Date.now() + opts.initializationTimeout; if (!closed) { connectionCreationLoop(pool, 0, timeoutEnd) .then(conn => { if (closed) { return conn.forceEnd().catch(err => {}); } addPoolConnection(pool, conn); }) .catch(err => { if (pool.totalConnections() === 0) { const task = taskQueue.shift(); if (task) { firstTaskTimeout = clearTimeout(firstTaskTimeout); process.nextTick(task.reject, err); resetTimeoutToNextTask(); } } else if (!closed) { console.error( `pool fail to create connection (${err.message})` ); } //delay next try setTimeout(() => { connectionInCreation = false; if (taskQueue.size() > 0) { ensurePoolSize(pool); } }, 500); }); } }); } }
javascript
{ "resource": "" }
q28979
train
function(pool) { let toRemove = Math.max(1, pool.idleConnections() - opts.minimumIdle); while (toRemove > 0) { const conn = idleConnections.peek(); --toRemove; if (conn && conn.lastUse + opts.idleTimeout * 1000 < Date.now()) { idleConnections.shift(); conn.forceEnd().catch(err => {}); conn.releaseWithoutError(); continue; } break; } ensurePoolSize(pool); }
javascript
{ "resource": "" }
q28980
train
function() { firstTaskTimeout = clearTimeout(firstTaskTimeout); const task = taskQueue.shift(); if (task) { const conn = idleConnections.shift(); if (conn) { activeConnections[conn.threadId] = conn; resetTimeoutToNextTask(); processTask(conn, task.sql, task.values, task.isBatch) .then(task.resolve) .catch(task.reject); } else { taskQueue.unshift(task); } } }
javascript
{ "resource": "" }
q28981
train
function(authFailHandler) { _timeout = null; const handshake = _receiveQueue.peekFront(); authFailHandler( Errors.createError( 'Connection timeout', true, info, '08S01', Errors.ER_CONNECTION_TIMEOUT, handshake ? handshake.stack : null ) ); }
javascript
{ "resource": "" }
q28982
train
function() { const err = Errors.createError( 'socket timeout', true, info, '08S01', Errors.ER_SOCKET_TIMEOUT ); const packetMsgs = info.getLastPackets(); if (packetMsgs !== '') { err.message = err.message + '\nlast received packets:\n' + packetMsgs; } _fatalError(err, true); }
javascript
{ "resource": "" }
q28983
train
function(authFailHandler, err) { if (_status === Status.CLOSING || _status === Status.CLOSED) return; _socket.writeBuf = () => {}; _socket.flush = () => {}; //socket has been ended without error if (!err) { err = Errors.createError( 'socket has unexpectedly been closed', true, info, '08S01', Errors.ER_SOCKET_UNEXPECTED_CLOSE ); } else { err.fatal = true; this.sqlState = 'HY000'; } const packetMsgs = info.getLastPackets(); if (packetMsgs !== '') { err.message += '\nlast received packets:\n' + packetMsgs; } switch (_status) { case Status.CONNECTING: case Status.AUTHENTICATING: const currentCmd = _receiveQueue.peekFront(); if (currentCmd && currentCmd.stack && err) { err.stack += '\n From event:\n' + currentCmd.stack.substring(currentCmd.stack.indexOf('\n') + 1); } authFailHandler(err); break; default: _fatalError(err, false); } }
javascript
{ "resource": "" }
q28984
FilteredPoolCluster
train
function FilteredPoolCluster(poolCluster, patternArg, selectorArg) { const cluster = poolCluster; const pattern = patternArg; const selector = selectorArg; /** * Get a connection according to previously indicated pattern and selector. * * @return {Promise} */ this.getConnection = () => { return cluster.getConnection(pattern, selector); }; /** * Execute a query on one connection from available pools matching pattern * in cluster. * * @param sql sql command * @param value parameter value of sql command (not mandatory) * @return {Promise} */ this.query = function(sql, value) { return cluster .getConnection(pattern, selector) .then(conn => { return conn .query(sql, value) .then(res => { conn.end(); return res; }) .catch(err => { conn.end(); return Promise.reject(err); }); }) .catch(err => { return Promise.reject(err); }); }; /** * Execute a batch on one connection from available pools matching pattern * in cluster. * * @param sql sql command * @param value parameter value of sql command * @return {Promise} */ this.batch = function(sql, value) { return cluster .getConnection(pattern, selector) .then(conn => { return conn .batch(sql, value) .then(res => { conn.end(); return res; }) .catch(err => { conn.end(); return Promise.reject(err); }); }) .catch(err => { return Promise.reject(err); }); }; }
javascript
{ "resource": "" }
q28985
train
function(pool) { const conn = new Connection(options.connOptions); return conn .connect() .then(() => { if (pool.closed) { conn .end() .then(() => {}) .catch(() => {}); return Promise.reject( Errors.createError( 'Cannot create new connection to pool, pool closed', true, null, '08S01', Errors.ER_ADD_CONNECTION_CLOSED_POOL, null ) ); } conn.releaseWithoutError = () => { conn.release().catch(() => {}); }; conn.forceEnd = conn.end; conn.release = () => { if (pool.closed) { pool._discardConnection(conn); return Promise.resolve(); } if (options.noControlAfterUse) { pool._releaseConnection(conn); return Promise.resolve(); } //if server permit it, reset the connection, or rollback only if not let revertFunction = conn.rollback; if ( options.resetAfterUse && ((conn.info.isMariaDB() && conn.info.hasMinVersion(10, 2, 4)) || (!conn.info.isMariaDB() && conn.info.hasMinVersion(5, 7, 3))) ) { revertFunction = conn.reset; } return revertFunction() .then(() => { pool._releaseConnection(conn); return Promise.resolve(); }) .catch(err => { //uncertain connection state. // discard it pool._discardConnection(conn); return Promise.resolve(); }); }; conn.end = conn.release; return Promise.resolve(conn); }) .catch(err => { return Promise.reject(err); }); }
javascript
{ "resource": "" }
q28986
checkAllowableRegions
train
function checkAllowableRegions(touchCoordinates, x, y) { for (var i = 0; i < touchCoordinates.length; i += 2) { if (hit(touchCoordinates[i], touchCoordinates[i+1], x, y)) { touchCoordinates.splice(i, i + 2); return true; // allowable region } } return false; // No allowable region; bust it. }
javascript
{ "resource": "" }
q28987
preventGhostClick
train
function preventGhostClick(x, y) { if (!touchCoordinates) { $rootElement[0].addEventListener('click', onClick, true); $rootElement[0].addEventListener('touchstart', onTouchStart, true); touchCoordinates = []; } lastPreventedTime = Date.now(); checkAllowableRegions(touchCoordinates, x, y); }
javascript
{ "resource": "" }
q28988
Tweenable
train
function Tweenable (opt_initialState, opt_config) { this._currentState = opt_initialState || {}; this._configured = false; this._scheduleFunction = DEFAULT_SCHEDULE_FUNCTION; // To prevent unnecessary calls to setConfig do not set default configuration here. // Only set default configuration immediately before tweening if none has been set. if (typeof opt_config !== 'undefined') { this.setConfig(opt_config); } }
javascript
{ "resource": "" }
q28989
aggregate
train
function aggregate (weights, values) { const max = 10 * R.sum(weights); const min = 1 * R.sum(weights); const sum = R.sum(R.zipWith(R.multiply, weights, values)); return score(min, max, sum); }
javascript
{ "resource": "" }
q28990
findNodes
train
function findNodes(body, nodeName) { let nodesArray = []; if (body) { nodesArray = body.filter(node => node.type === nodeName); } return nodesArray; }
javascript
{ "resource": "" }
q28991
isGlobalCallExpression
train
function isGlobalCallExpression(node, destructuredName, aliases) { const isDestructured = node && node.callee && node.callee.name === destructuredName; const isGlobalCall = node.callee && aliases.indexOf(node.callee.name) > -1; return !isDestructured && isGlobalCall; }
javascript
{ "resource": "" }
q28992
getSize
train
function getSize(node) { return (node.loc.end.line - node.loc.start.line) + 1; }
javascript
{ "resource": "" }
q28993
parseCallee
train
function parseCallee(node) { const parsedCallee = []; let callee; if (isCallExpression(node) || isNewExpression(node)) { callee = node.callee; while (isMemberExpression(callee)) { if (isIdentifier(callee.property)) { parsedCallee.push(callee.property.name); } callee = callee.object; } if (isIdentifier(callee)) { parsedCallee.push(callee.name); } } return parsedCallee.reverse(); }
javascript
{ "resource": "" }
q28994
parseArgs
train
function parseArgs(node) { let parsedArgs = []; if (isCallExpression(node)) { parsedArgs = node.arguments .filter(argument => isLiteral(argument) && argument.value) .map(argument => argument.value); } return parsedArgs; }
javascript
{ "resource": "" }
q28995
findUnorderedProperty
train
function findUnorderedProperty(arr) { for (let i = 0; i < arr.length - 1; i++) { if (arr[i].order > arr[i + 1].order) { return arr[i]; } } return null; }
javascript
{ "resource": "" }
q28996
getPropertyValue
train
function getPropertyValue(node, path) { const parts = typeof path === 'string' ? path.split('.') : path; if (parts.length === 1) { return node[path]; } const property = node[parts[0]]; if (property && parts.length > 1) { parts.shift(); return getPropertyValue(property, parts); } return property; }
javascript
{ "resource": "" }
q28997
collectObjectPatternBindings
train
function collectObjectPatternBindings(node, initialObjToBinding) { if (!isObjectPattern(node.id)) return []; const identifiers = Object.keys(initialObjToBinding); const objBindingName = node.init.name; const bindingIndex = identifiers.indexOf(objBindingName); if (bindingIndex === -1) return []; const binding = identifiers[bindingIndex]; return node.id.properties .filter(props => initialObjToBinding[binding].indexOf(props.key.name) > -1) .map(props => props.value.name); }
javascript
{ "resource": "" }
q28998
isEmptyMethod
train
function isEmptyMethod(node) { return node.value.body && node.value.body.body && node.value.body.body.length <= 0; }
javascript
{ "resource": "" }
q28999
getParent
train
function getParent(node, predicate) { let currentNode = node; while (currentNode) { if (predicate(currentNode)) { return currentNode; } currentNode = currentNode.parent; } return null; }
javascript
{ "resource": "" }