_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q28800
train
function(name, params, callback) { // If we get (name, callback) instead of (name, params, callback) // do the necessary variable swap if (utils.isFunction(params) && !callback) { callback = params; params = {}; } params = params || {}; callback = callback || function(){}; name = name.replace(/ /g, "_"); var that = this; return this.post("", {name: name, description: JSON.stringify(params)}, function(err, response) { if (err) { callback(err); } else { var dataModel = new root.DataModel(that.service, response.data.entry[0].name, that.namespace, response.data.entry[0]); callback(null, dataModel); } }); }
javascript
{ "resource": "" }
q28801
train
function(callback) { callback = callback || function() {}; var that = this; var params = { count: this._pagesize, offset: this._offset }; return this._endpoint(params, function(err, results) { if (err) { callback(err); } else { var numResults = (results.rows ? results.rows.length : 0); that._offset += numResults; callback(null, results, numResults > 0); } }); }
javascript
{ "resource": "" }
q28802
EventWriter
train
function EventWriter(output, error) { this._out = utils.isUndefined(output) ? process.stdout : output; this._err = utils.isUndefined(error) ? process.stderr : error; // Has the opening <stream> tag been written yet? this._headerWritten = false; }
javascript
{ "resource": "" }
q28803
Scheme
train
function Scheme(title) { this.title = utils.isUndefined(title) ? "" : title; // Set the defaults. this.description = null; this.useExternalValidation = true; this.useSingleInstance = false; this.streamingMode = Scheme.streamingModeXML; // List of Argument objects, each to be represented by an <arg> tag. this.args = []; }
javascript
{ "resource": "" }
q28804
stringifyArray
train
function stringifyArray(arr, prefix) { var ret = []; if (!prefix) throw new TypeError('stringify expects an object'); for (var i = 0; i < arr.length; i++) { ret.push(stringify(arr[i], prefix + '[]')); } return ret.join('&'); }
javascript
{ "resource": "" }
q28805
lastBraceInKey
train
function lastBraceInKey(str) { var len = str.length , brace , c; for (var i = 0; i < len; ++i) { c = str[i]; if (']' == c) brace = false; if ('[' == c) brace = true; if ('=' == c && !brace) return i; } }
javascript
{ "resource": "" }
q28806
train
function(a, b) { c = this; if (!b) { return c.options[a]; } else { c._u(a, b); } }
javascript
{ "resource": "" }
q28807
train
function( a, b ) { this.id = b.attr('id'); this.instances = []; this.element = b; this.options = jQuery.extend(this.options, a); this._create(); if ( this._init ) { this._init(); } }
javascript
{ "resource": "" }
q28808
train
function(a, b) { var map = this.get('map'); jQuery.extend(this.options, { 'center': map.getCenter(), 'mapTypeId': map.getMapTypeId(), 'zoom': map.getZoom() } ); if (a && b) { this.options[a] = b; } map.setOptions(this.options); // FIXME: Temp fix for bounds... if (!(a && b)) { var c = map.getBounds(); if (c) { map.panToBounds(c); } } }
javascript
{ "resource": "" }
q28809
train
function(a) { this.get('bounds', new google.maps.LatLngBounds()).extend(this._latLng(a)); this.get('map').fitBounds(this.get('bounds')); }
javascript
{ "resource": "" }
q28810
train
function(a, b, c) { var d = this.get('map'); var c = c || google.maps.Marker; a.position = (a.position) ? this._latLng(a.position) : null; var e = new c( jQuery.extend({'map': d, 'bounds': false}, a) ); var f = this.get('markers', []); if ( e.id ) { f[e.id] = e; } else { f.push(e); } if ( e.bounds ) { this.addBounds(e.getPosition()); } this._call(b, d, e); return $(e); }
javascript
{ "resource": "" }
q28811
train
function(a, b) { var c = new google.maps.InfoWindow(a); this._call(b, c); return $(c); }
javascript
{ "resource": "" }
q28812
train
function(a, b) { var c = this.instances[this.id]; if (!c[a]) { if ( a.indexOf('>') > -1 ) { var e = a.replace(/ /g, '').split('>'); for ( var i = 0; i < e.length; i++ ) { if ( !c[e[i]] ) { if (b) { c[e[i]] = ( (i + 1) < e.length ) ? [] : b; } else { return null; } } c = c[e[i]]; } return c; } else if ( b && !c[a] ) { this.set(a, b); } } return c[a]; }
javascript
{ "resource": "" }
q28813
train
function(a, b) { this.get('iw', new google.maps.InfoWindow).setOptions(a); this.get('iw').open(this.get('map'), this._unwrap(b)); }
javascript
{ "resource": "" }
q28814
train
function() { this.clear('markers'); this.clear('services'); this.clear('overlays'); var a = this.instances[this.id]; for ( b in a ) { a[b] = null; } }
javascript
{ "resource": "" }
q28815
train
function(a) { if ( $.isFunction(a) ) { a.apply(this, Array.prototype.slice.call(arguments, 1)); } }
javascript
{ "resource": "" }
q28816
train
function(a) { if ( a instanceof google.maps.LatLng ) { return a; } else { var b = a.replace(/ /g,'').split(','); return new google.maps.LatLng(b[0], b[1]); } }
javascript
{ "resource": "" }
q28817
train
function(sourceDir, newDirLocation, opts) { if (!opts || !opts.preserve) { try { if(fs.statSync(newDirLocation).isDirectory()) { exports.rmdirSyncRecursive(newDirLocation); } } catch(e) { } } /* Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */ var checkDir = fs.statSync(sourceDir); try { fs.mkdirSync(newDirLocation, checkDir.mode); } catch (e) { //if the directory already exists, that's okay if (e.code !== 'EEXIST') { throw e; } } var files = fs.readdirSync(sourceDir); for(var i = 0; i < files.length; i++) { var currFile = fs.lstatSync(sourceDir + "/" + files[i]); if(currFile.isDirectory()) { /* recursion this thing right on back. */ copyDirectoryRecursiveSync(sourceDir + "/" + files[i], newDirLocation + "/" + files[i], opts); } else if(currFile.isSymbolicLink()) { var symlinkFull = fs.readlinkSync(sourceDir + "/" + files[i]); fs.symlinkSync(symlinkFull, newDirLocation + "/" + files[i]); } else { /* At this point, we've hit a file actually worth copying... so copy it on over. */ var contents = fs.readFileSync(sourceDir + "/" + files[i]); fs.writeFileSync(newDirLocation + "/" + files[i], contents); } } }
javascript
{ "resource": "" }
q28818
train
function(job, done) { Async.whilst( function() { return !job.properties().isDone; }, function(iterationDone) { job.fetch(function(err, job) { if (err) { callback(err); } else { // If the user asked for verbose output, // then write out the status of the search var properties = job.properties(); if (isVerbose) { var progress = (properties.doneProgress * 100.0) + "%"; var scanned = properties.scanCount; var matched = properties.eventCount; var results = properties.resultCount; var stats = "-- " + progress + " done | " + scanned + " scanned | " + matched + " matched | " + results + " results"; print("\r" + stats + " "); } Async.sleep(1000, iterationDone); } }); }, function(err) { if (isVerbose) { print("\r"); } done(err, job); } ); }
javascript
{ "resource": "" }
q28819
train
function(results) { for(var i = 0; i < results.rows.length; i++) { console.log("Result " + (i + 1) + ": "); var row = results.rows[i]; for(var j = 0; j < results.fields.length; j++) { var field = results.fields[j]; var value = row[j]; console.log(" " + field + " = " + value); } } }
javascript
{ "resource": "" }
q28820
train
function(results) { var rows = []; var cols = results.columns; var mapFirst = function(col) { return col.shift(); }; while(cols.length > 0 && cols[0].length > 0) { rows.push(cols.map(mapFirst)); } results.rows = rows; return results; }
javascript
{ "resource": "" }
q28821
train
function(results) { if (results) { var isRows = !!results.rows; var numResults = (results.rows ? results.rows.length : (results.columns[0] || []).length); console.log("====== " + numResults + " RESULTS (preview: " + !!results.preview + ") ======"); // If it is in column-major form, transpose it. if (!isRows) { results = transpose(results); } printRows(results); } }
javascript
{ "resource": "" }
q28822
train
function(params, extra) { var output = [params]; if(extra != undefined) { output.push(extra); } else { output.push(null); } return { start: function(completeCallback, errorCallback, messageCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; messageCallback = messageCallback || function() {}; exec(function(result) { if(result === "OK") { completeCallback(result); } else { var requestCode = result["_ACTION_requestCode_"]; delete result["_ACTION_requestCode_"]; var resultCode = result["_ACTION_resultCode_"]; delete result["_ACTION_resultCode_"]; messageCallback(result, requestCode, resultCode); } }, errorCallback, "startApp", "start", output); }, check: function(completeCallback, errorCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; exec(completeCallback, errorCallback, "startApp", "check", output); }, receiver: function(completeCallback, errorCallback, messageCallback) { completeCallback = completeCallback || function() {}; errorCallback = errorCallback || function() {}; messageCallback = messageCallback || function() {}; exec(function(result) { if(/\d+/.test(result)) { completeCallback(result); } else { var action = result["_ACTION_VALUE_FORMAT_"]; delete result["_ACTION_VALUE_FORMAT_"]; messageCallback(action, result); } }, errorCallback, "startApp", "receiver", output); } } }
javascript
{ "resource": "" }
q28823
render
train
function render(source, config, options) { config = config || {}; config.raml2HtmlVersion = pjson.version; // Check if option is old boolean `validation` to keep backward compatibility if (typeof options === 'boolean') { options = { validate: options, }; } if (options === undefined) { options = { validate: false, }; } return raml2obj .parse(source, { validate: options.validate, extensionsAndOverlays: options.extensionsAndOverlays, }) .then(ramlObj => { if (config.processRamlObj) { return config.processRamlObj(ramlObj, config, options).then(html => { if (config.postProcessHtml) { return config.postProcessHtml(html, config, options); } return html; }); } return ramlObj; }); }
javascript
{ "resource": "" }
q28824
getPlistFilenames
train
function getPlistFilenames(xcode) { return unique( flattenDeep( xcode.document.projects.map(project => { return project.targets.filter(Boolean).map(target => { return target.buildConfigurationsList.buildConfigurations.map( config => { return config.ast.value.get("buildSettings").get("INFOPLIST_FILE") .text; } ); }); }) ) ); }
javascript
{ "resource": "" }
q28825
isExpoProject
train
function isExpoProject(projPath) { try { let module = resolveFrom(projPath, "expo"); let appInfo = require(`${projPath}/app.json`); return !!(module && appInfo.expo); } catch (err) { return false; } }
javascript
{ "resource": "" }
q28826
log
train
function log(msg, silent) { if (!silent) { console.log("[RNV]", chalk[msg.style || "reset"](msg.text)); } }
javascript
{ "resource": "" }
q28827
Quat2Angle
train
function Quat2Angle(x, y, z, w) { const test = x * y + z * w; // singularity at north pole if (test > 0.499) { const yaw = 2 * Math.atan2(x, w); const pitch = Math.PI / 2; const roll = 0; return new THREE.Vector3(pitch, roll, yaw); } // singularity at south pole if (test < -0.499) { const yaw = -2 * Math.atan2(x, w); const pitch = -Math.PI / 2; const roll = 0; return new THREE.Vector3(pitch, roll, yaw); } const sqx = x * x; const sqy = y * y; const sqz = z * z; const yaw = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); const pitch = Math.asin(2 * test); const roll = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); return new THREE.Vector3(pitch, roll, yaw); }
javascript
{ "resource": "" }
q28828
toCodePoint
train
function toCodePoint(input, separator = "-") { const codePoints = []; for (let codePoint of input) { codePoints.push(codePoint.codePointAt(0).toString(16)); } return codePoints.join(separator); }
javascript
{ "resource": "" }
q28829
registerFilters
train
function registerFilters (filters) { if (isArray(filters)) { lazyStringFilters = lazyStringFilters.concat(filters) } else if (isObject(filters)) { Object.keys(filters).forEach(name => { addFilter(name, filters[name]) }) } }
javascript
{ "resource": "" }
q28830
getMarkup
train
function getMarkup(webserver, provider) { var markup = renderToString(provider), styles = ""; if (process.env.NODE_ENV === "production") { styles = `<link href="${webserver}/dist/main.css" rel="stylesheet"></link>`; } return `<!doctype html> <html> <head> <title>Redux Auth – Isomorphic Example</title> <script> window.__API_URL__ = "${global.__API_URL__}"; </script> ${styles} </head> <body> <div id="react-root">${markup}</div> <script src="${webserver}/dist/client.js"></script> </body> </html>`; }
javascript
{ "resource": "" }
q28831
takePhoto
train
function takePhoto () { let sizeFactor = 1; let imageType = IMAGE_TYPES.JPG; let imageCompression = 1; let config = { sizeFactor, imageType, imageCompression }; let dataUri = cameraPhoto.getDataUri(config); imgElement.src = dataUri; }
javascript
{ "resource": "" }
q28832
train
function () { require('ts-node').register({ project: 'e2e/tsconfig.e2e.json' }); console.log("Connecting local"); return new Promise(function (resolve, reject) { exports.bs_local = new browserstack.Local(); exports.bs_local.start({'key': exports.config.capabilities['browserstack.key']}, function (error) { if (error) return reject(error); console.log('Connected. Now testing...'); resolve(); }); }); }
javascript
{ "resource": "" }
q28833
relayEvents
train
function relayEvents(listener, emitter, events) { events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); }
javascript
{ "resource": "" }
q28834
retrieveEJSON
train
function retrieveEJSON() { let EJSON = null; try { EJSON = requireOptional('mongodb-extjson'); } catch (error) {} // eslint-disable-line if (!EJSON) { EJSON = { parse: noEJSONError, deserialize: noEJSONError, serialize: noEJSONError, stringify: noEJSONError, setBSONModule: noEJSONError, BSON: noEJSONError }; } return EJSON; }
javascript
{ "resource": "" }
q28835
maxWireVersion
train
function maxWireVersion(topologyOrServer) { if (topologyOrServer.ismaster) { return topologyOrServer.ismaster.maxWireVersion; } if (topologyOrServer.description) { return topologyOrServer.description.maxWireVersion; } return null; }
javascript
{ "resource": "" }
q28836
writableServerSelector
train
function writableServerSelector() { return function(topologyDescription, servers) { return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); }; }
javascript
{ "resource": "" }
q28837
tagSetMatch
train
function tagSetMatch(tagSet, serverTags) { const keys = Object.keys(tagSet); const serverTagKeys = Object.keys(serverTags); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { return false; } } return true; }
javascript
{ "resource": "" }
q28838
tagSetReducer
train
function tagSetReducer(readPreference, servers) { if ( readPreference.tags == null || (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) ) { return servers; } for (let i = 0; i < readPreference.tags.length; ++i) { const tagSet = readPreference.tags[i]; const serversMatchingTagset = servers.reduce((matched, server) => { if (tagSetMatch(tagSet, server.tags)) matched.push(server); return matched; }, []); if (serversMatchingTagset.length) { return serversMatchingTagset; } } return []; }
javascript
{ "resource": "" }
q28839
defaultAuthProviders
train
function defaultAuthProviders(bson) { return { mongocr: new MongoCR(bson), x509: new X509(bson), plain: new Plain(bson), gssapi: new GSSAPI(bson), sspi: new SSPI(bson), 'scram-sha-1': new ScramSHA1(bson), 'scram-sha-256': new ScramSHA256(bson) }; }
javascript
{ "resource": "" }
q28840
canCompress
train
function canCompress(command) { const commandDoc = command instanceof Msg ? command.command : command.query; const commandName = Object.keys(commandDoc)[0]; return uncompressibleCommands.indexOf(commandName) === -1; }
javascript
{ "resource": "" }
q28841
remove
train
function remove(connection, connections) { for (var i = 0; i < connections.length; i++) { if (connections[i] === connection) { connections.splice(i, 1); return true; } } }
javascript
{ "resource": "" }
q28842
retrieveSnappy
train
function retrieveSnappy() { var snappy = null; try { snappy = require_optional('snappy'); } catch (error) {} // eslint-disable-line if (!snappy) { snappy = { compress: noSnappyWarning, uncompress: noSnappyWarning, compressSync: noSnappyWarning, uncompressSync: noSnappyWarning }; } return snappy; }
javascript
{ "resource": "" }
q28843
matchesParentDomain
train
function matchesParentDomain(srvAddress, parentDomain) { const regex = /^.*?\./; const srv = `.${srvAddress.replace(regex, '')}`; const parent = `.${parentDomain.replace(regex, '')}`; return srv.endsWith(parent); }
javascript
{ "resource": "" }
q28844
parseSrvConnectionString
train
function parseSrvConnectionString(uri, options, callback) { const result = URL.parse(uri, true); if (result.hostname.split('.').length < 3) { return callback(new MongoParseError('URI does not have hostname, domain name and tld')); } result.domainLength = result.hostname.split('.').length; if (result.pathname && result.pathname.match(',')) { return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); } if (result.port) { return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); } // Resolve the SRV record and use the result as the list of hosts to connect to. const lookupAddress = result.host; dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { if (err) return callback(err); if (addresses.length === 0) { return callback(new MongoParseError('No addresses found at host')); } for (let i = 0; i < addresses.length; i++) { if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { return callback( new MongoParseError('Server record does not share hostname with parent URI') ); } } // Convert the original URL to a non-SRV URL. result.protocol = 'mongodb'; result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); // Default to SSL true if it's not specified. if ( !('ssl' in options) && (!result.search || !('ssl' in result.query) || result.query.ssl === null) ) { result.query.ssl = true; } // Resolve TXT record and add options from there if they exist. dns.resolveTxt(lookupAddress, (err, record) => { if (err) { if (err.code !== 'ENODATA') { return callback(err); } record = null; } if (record) { if (record.length > 1) { return callback(new MongoParseError('Multiple text records not allowed')); } record = qs.parse(record[0].join('')); if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { return callback( new MongoParseError('Text record must only set `authSource` or `replicaSet`') ); } Object.assign(result.query, record); } // Set completed options back into the URL object. result.search = qs.stringify(result.query); const finalString = URL.format(result); parseConnectionString(finalString, options, callback); }); }); }
javascript
{ "resource": "" }
q28845
parseQueryStringItemValue
train
function parseQueryStringItemValue(key, value) { if (Array.isArray(value)) { // deduplicate and simplify arrays value = value.filter((v, idx) => value.indexOf(v) === idx); if (value.length === 1) value = value[0]; } else if (value.indexOf(':') > 0) { value = value.split(',').reduce((result, pair) => { const parts = pair.split(':'); result[parts[0]] = parseQueryStringItemValue(key, parts[1]); return result; }, {}); } else if (value.indexOf(',') > 0) { value = value.split(',').map(v => { return parseQueryStringItemValue(key, v); }); } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { value = value.toLowerCase() === 'true'; } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { const numericValue = parseFloat(value); if (!Number.isNaN(numericValue)) { value = parseFloat(value); } } return value; }
javascript
{ "resource": "" }
q28846
applyConnectionStringOption
train
function applyConnectionStringOption(obj, key, value, options) { // simple key translation if (key === 'journal') { key = 'j'; } else if (key === 'wtimeoutms') { key = 'wtimeout'; } // more complicated translation if (BOOLEAN_OPTIONS.has(key)) { value = value === 'true' || value === true; } else if (key === 'appname') { value = decodeURIComponent(value); } else if (key === 'readconcernlevel') { obj['readConcernLevel'] = value; key = 'readconcern'; value = { level: value }; } // simple validation if (key === 'compressors') { value = Array.isArray(value) ? value : [value]; if (!value.every(c => c === 'snappy' || c === 'zlib')) { throw new MongoParseError( 'Value for `compressors` must be at least one of: `snappy`, `zlib`' ); } } if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { throw new MongoParseError( 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' ); } if (key === 'readpreference' && !ReadPreference.isValid(value)) { throw new MongoParseError( 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' ); } if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); } // special cases if (key === 'compressors' || key === 'zlibcompressionlevel') { obj.compression = obj.compression || {}; obj = obj.compression; } if (key === 'authmechanismproperties') { if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; } } if (key === 'readpreferencetags' && Array.isArray(value)) { value = splitArrayOfMultipleReadPreferenceTags(value); } // set the actual value if (options.caseTranslate && CASE_TRANSLATION[key]) { obj[CASE_TRANSLATION[key]] = value; return; } obj[key] = value; }
javascript
{ "resource": "" }
q28847
applyAuthExpectations
train
function applyAuthExpectations(parsed) { if (parsed.options == null) { return; } const options = parsed.options; const authSource = options.authsource || options.authSource; if (authSource != null) { parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); } const authMechanism = options.authmechanism || options.authMechanism; if (authMechanism != null) { if ( USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && (!parsed.auth || parsed.auth.username == null) ) { throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); } if (authMechanism === 'GSSAPI') { if (authSource != null && authSource !== '$external') { throw new MongoParseError( `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` ); } parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } if (authMechanism === 'MONGODB-X509') { if (parsed.auth && parsed.auth.password != null) { throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); } if (authSource != null && authSource !== '$external') { throw new MongoParseError( `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` ); } parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } if (authMechanism === 'PLAIN') { if (parsed.auth && parsed.auth.db == null) { parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); } } } // default to `admin` if nothing else was resolved if (parsed.auth && parsed.auth.db == null) { parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); } return parsed; }
javascript
{ "resource": "" }
q28848
checkTLSOptions
train
function checkTLSOptions(queryString) { const queryStringKeys = Object.keys(queryString); if ( queryStringKeys.indexOf('tlsInsecure') !== -1 && (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) ) { throw new MongoParseError( 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' ); } const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); if (tlsValue != null && sslValue != null) { if (tlsValue !== sslValue) { throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); } } }
javascript
{ "resource": "" }
q28849
train
function(self, server, cb) { // Measure running time var start = new Date().getTime(); // Emit the server heartbeat start emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); // Execute ismaster // Set the socketTimeout for a monitoring message to a low number // Ensuring ismaster calls are timed out quickly server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, r) { if (self.state === DESTROYED || self.state === UNREFERENCED) { server.destroy({ force: true }); return cb(err, r); } // Calculate latency var latencyMS = new Date().getTime() - start; // Set the last updatedTime var hrTime = process.hrtime(); // Calculate the last update time server.lastUpdateTime = hrTime[0] * 1000 + Math.round(hrTime[1] / 1000); // We had an error, remove it from the state if (err) { // Emit the server heartbeat failure emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: server.name }); // Remove server from the state self.s.replicaSetState.remove(server); } else { // Update the server ismaster server.ismaster = r.result; // Check if we have a lastWriteDate convert it to MS // and store on the server instance for later use if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); } // Do we have a brand new server if (server.lastIsMasterMS === -1) { server.lastIsMasterMS = latencyMS; } else if (server.lastIsMasterMS) { // After the first measurement, average RTT MUST be computed using an // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. // If the prior average is denoted old_rtt, then the new average (new_rtt) is // computed from a new RTT measurement (x) using the following formula: // alpha = 0.2 // new_rtt = alpha * x + (1 - alpha) * old_rtt server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; } if (self.s.replicaSetState.update(server)) { // Primary lastIsMaster store it if (server.lastIsMaster() && server.lastIsMaster().ismaster) { self.ismaster = server.lastIsMaster(); } } // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: server.name }); } // Calculate the staleness for this server self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); // Callback cb(err, r); } ); }
javascript
{ "resource": "" }
q28850
train
function(host, self, options) { // If this is not the initial scan // Is this server already being monitoried, then skip monitoring if (!options.haInterval) { for (var i = 0; i < self.intervalIds.length; i++) { if (self.intervalIds[i].__host === host) { return; } } } // Get the haInterval var _process = options.haInterval ? Timeout : Interval; var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; // Create the interval var intervalId = new _process(function() { if (self.state === DESTROYED || self.state === UNREFERENCED) { // clearInterval(intervalId); intervalId.stop(); return; } // Do we already have server connection available for this host var _server = self.s.replicaSetState.get(host); // Check if we have a known server connection and reuse if (_server) { // Ping the server return pingServer(self, _server, function(err) { if (err) { // NOTE: should something happen here? return; } if (self.state === DESTROYED || self.state === UNREFERENCED) { intervalId.stop(); return; } // Filter out all called intervaliIds self.intervalIds = self.intervalIds.filter(function(intervalId) { return intervalId.isRunning(); }); // Initial sweep if (_process === Timeout) { if ( self.state === CONNECTING && ((self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) || self.s.replicaSetState.hasPrimary()) ) { self.state = CONNECTED; // Emit connected sign process.nextTick(function() { self.emit('connect', self); }); // Start topology interval check topologyMonitor(self, {}); } } else { if ( self.state === DISCONNECTED && ((self.s.replicaSetState.hasSecondary() && self.s.options.secondaryOnlyConnectionAllowed) || self.s.replicaSetState.hasPrimary()) ) { self.state = CONNECTED; // Rexecute any stalled operation rexecuteOperations(self); // Emit connected sign process.nextTick(function() { self.emit('reconnect', self); }); } } if ( self.initialConnectState.connect && !self.initialConnectState.fullsetup && self.s.replicaSetState.hasPrimaryAndSecondary() ) { // Set initial connect state self.initialConnectState.fullsetup = true; self.initialConnectState.all = true; process.nextTick(function() { self.emit('fullsetup', self); self.emit('all', self); }); } }); } }, _haInterval); // Start the interval intervalId.start(); // Add the intervalId host name intervalId.__host = host; // Add the intervalId to our list of intervalIds self.intervalIds.push(intervalId); }
javascript
{ "resource": "" }
q28851
executeReconnect
train
function executeReconnect(self) { return function() { if (self.state === DESTROYED || self.state === UNREFERENCED) { return; } connectNewServers(self, self.s.replicaSetState.unknownServers, function() { var monitoringFrequencey = self.s.replicaSetState.hasPrimary() ? _haInterval : self.s.minHeartbeatFrequencyMS; // Create a timeout self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); }); }; }
javascript
{ "resource": "" }
q28852
emitSDAMEvent
train
function emitSDAMEvent(self, event, description) { if (self.listeners(event).length > 0) { self.emit(event, description); } }
javascript
{ "resource": "" }
q28853
executeWriteOperation
train
function executeWriteOperation(args, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // TODO: once we drop Node 4, use destructuring either here or in arguments. const self = args.self; const op = args.op; const ns = args.ns; const ops = args.ops; if (self.state === DESTROYED) { return callback(new MongoError(f('topology was destroyed'))); } const willRetryWrite = !args.retrying && !!options.retryWrites && options.session && isRetryableWritesSupported(self) && !options.session.inTransaction(); if (!self.s.replicaSetState.hasPrimary()) { if (self.s.disconnectHandler) { // Not connected but we have a disconnecthandler return self.s.disconnectHandler.add(op, ns, ops, options, callback); } else if (!willRetryWrite) { // No server returned we had an error return callback(new MongoError('no primary server found')); } } const handler = (err, result) => { if (!err) return callback(null, result); if (!isRetryableError(err)) { return callback(err); } if (willRetryWrite) { const newArgs = Object.assign({}, args, { retrying: true }); return executeWriteOperation(newArgs, options, callback); } // Per SDAM, remove primary from replicaset if (self.s.replicaSetState.primary) { self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); } return callback(err); }; if (callback.operationId) { handler.operationId = callback.operationId; } // increment and assign txnNumber if (willRetryWrite) { options.session.incrementTransactionNumber(); options.willRetryWrite = willRetryWrite; } self.s.replicaSetState.primary[op](ns, ops, options, handler); }
javascript
{ "resource": "" }
q28854
xor
train
function xor(a, b) { if (!Buffer.isBuffer(a)) a = Buffer.from(a); if (!Buffer.isBuffer(b)) b = Buffer.from(b); const length = Math.max(a.length, b.length); const res = []; for (let i = 0; i < length; i += 1) { res.push(a[i] ^ b[i]); } return Buffer.from(res).toString('base64'); }
javascript
{ "resource": "" }
q28855
isRetryableError
train
function isRetryableError(error) { return ( RETRYABLE_ERROR_CODES.has(error.code) || error instanceof MongoNetworkError || error.message.match(/not master/) || error.message.match(/node is recovering/) ); }
javascript
{ "resource": "" }
q28856
parseServerType
train
function parseServerType(ismaster) { if (!ismaster || !ismaster.ok) { return ServerType.Unknown; } if (ismaster.isreplicaset) { return ServerType.RSGhost; } if (ismaster.msg && ismaster.msg === 'isdbgrid') { return ServerType.Mongos; } if (ismaster.setName) { if (ismaster.hidden) { return ServerType.RSOther; } else if (ismaster.ismaster) { return ServerType.RSPrimary; } else if (ismaster.secondary) { return ServerType.RSSecondary; } else if (ismaster.arbiterOnly) { return ServerType.RSArbiter; } else { return ServerType.RSOther; } } return ServerType.Standalone; }
javascript
{ "resource": "" }
q28857
destroyServer
train
function destroyServer(server, topology, callback) { LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); server.destroy(() => { topology.emit( 'serverClosed', new monitoring.ServerClosedEvent(topology.s.id, server.description.address) ); if (typeof callback === 'function') callback(null, null); }); }
javascript
{ "resource": "" }
q28858
parseStringSeedlist
train
function parseStringSeedlist(seedlist) { return seedlist.split(',').map(seed => ({ host: seed.split(':')[0], port: seed.split(':')[1] || 27017 })); }
javascript
{ "resource": "" }
q28859
resetServerState
train
function resetServerState(server, error, options) { options = Object.assign({}, { clearPool: false }, options); function resetState() { server.emit( 'descriptionReceived', new ServerDescription(server.description.address, null, { error }) ); } if (options.clearPool && server.pool) { server.pool.reset(() => resetState()); return; } resetState(); }
javascript
{ "resource": "" }
q28860
train
function(seedlist, options) { options = options || {}; // Get replSet Id this.id = id++; // Internal state this.s = { options: Object.assign({}, options), // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // Logger instance logger: Logger('Mongos', options), // Seedlist seedlist: seedlist, // Ha interval haInterval: options.haInterval ? options.haInterval : 10000, // Disconnect handler disconnectHandler: options.disconnectHandler, // Server selection index index: 0, // Connect function options passed in connectOptions: {}, // Are we running in debug mode debug: typeof options.debug === 'boolean' ? options.debug : false, // localThresholdMS localThresholdMS: options.localThresholdMS || 15, // Client info clientInfo: createClientInfo(options) }; // Set the client info this.s.options.clientInfo = createClientInfo(options); // Log info warning if the socketTimeout < haInterval as it will cause // a lot of recycled connections to happen. if ( this.s.logger.isWarn() && this.s.options.socketTimeout !== 0 && this.s.options.socketTimeout < this.s.haInterval ) { this.s.logger.warn( f( 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', this.s.options.socketTimeout, this.s.haInterval ) ); } // Disconnected state this.state = DISCONNECTED; // Current proxies we are connecting to this.connectingProxies = []; // Currently connected proxies this.connectedProxies = []; // Disconnected proxies this.disconnectedProxies = []; // Index of proxy to run operations against this.index = 0; // High availability timeout id this.haTimeoutId = null; // Last ismaster this.ismaster = null; // Description of the Replicaset this.topologyDescription = { topologyType: 'Unknown', servers: [] }; // Highest clusterTime seen in responses from the current deployment this.clusterTime = null; // Add event listener EventEmitter.call(this); }
javascript
{ "resource": "" }
q28861
pingServer
train
function pingServer(_self, _server, cb) { // Measure running time var start = new Date().getTime(); // Emit the server heartbeat start emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); // Execute ismaster _server.command( 'admin.$cmd', { ismaster: true }, { monitoring: true, socketTimeout: self.s.options.connectionTimeout || 2000 }, function(err, r) { if (self.state === DESTROYED || self.state === UNREFERENCED) { // Move from connectingProxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); _server.destroy(); return cb(err, r); } // Calculate latency var latencyMS = new Date().getTime() - start; // We had an error, remove it from the state if (err) { // Emit the server heartbeat failure emitSDAMEvent(self, 'serverHeartbeatFailed', { durationMS: latencyMS, failure: err, connectionId: _server.name }); // Move from connected proxies to disconnected proxies moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); } else { // Update the server ismaster _server.ismaster = r.result; _server.lastIsMasterMS = latencyMS; // Server heart beat event emitSDAMEvent(self, 'serverHeartbeatSucceeded', { durationMS: latencyMS, reply: r.result, connectionId: _server.name }); } cb(err, r); } ); }
javascript
{ "resource": "" }
q28862
resolveClusterTime
train
function resolveClusterTime(topology, $clusterTime) { if (topology.clusterTime == null) { topology.clusterTime = $clusterTime; } else { if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { topology.clusterTime = $clusterTime; } } }
javascript
{ "resource": "" }
q28863
train
function(topology) { const maxWireVersion = topology.lastIsMaster().maxWireVersion; if (maxWireVersion < RETRYABLE_WIRE_VERSION) { return false; } if (!topology.logicalSessionTimeoutMinutes) { return false; } if (topologyType(topology) === TopologyType.Single) { return false; } return true; }
javascript
{ "resource": "" }
q28864
train
function(readPreference, servers) { if (readPreference.tags == null) return servers; var filteredServers = []; var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; // Iterate over the tags for (var j = 0; j < tagsArray.length; j++) { var tags = tagsArray[j]; // Iterate over all the servers for (var i = 0; i < servers.length; i++) { var serverTag = servers[i].lastIsMaster().tags || {}; // Did we find the a matching server var found = true; // Check if the server is valid for (var name in tags) { if (serverTag[name] !== tags[name]) { found = false; } } // Add to candidate list if (found) { filteredServers.push(servers[i]); } } } // Returned filtered servers return filteredServers; }
javascript
{ "resource": "" }
q28865
train
function(options) { options = options || {}; // Add event listener EventEmitter.call(this); // Server instance id this.id = id++; // Internal state this.s = { // Options options: options, // Logger logger: Logger('Server', options), // Factory overrides Cursor: options.cursorFactory || BasicCursor, // BSON instance bson: options.bson || new BSON([ BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128, BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey, BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp ]), // Pool pool: null, // Disconnect handler disconnectHandler: options.disconnectHandler, // Monitor thread (keeps the connection alive) monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, // Is the server in a topology inTopology: !!options.parent, // Monitoring timeout monitoringInterval: typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, // Topology id topologyId: -1, compression: { compressors: createCompressionInfo(options) }, // Optional parent topology parent: options.parent }; // If this is a single deployment we need to track the clusterTime here if (!this.s.parent) { this.s.clusterTime = null; } // Curent ismaster this.ismaster = null; // Current ping time this.lastIsMasterMS = -1; // The monitoringProcessId this.monitoringProcessId = null; // Initial connection this.initialConnect = true; // Default type this._type = 'server'; // Set the client info this.clientInfo = createClientInfo(options); // Max Stalleness values // last time we updated the ismaster state this.lastUpdateTime = 0; // Last write time this.lastWriteDate = 0; // Stalleness this.staleness = 0; }
javascript
{ "resource": "" }
q28866
train
function(message) { return { length: message.readInt32LE(0), requestId: message.readInt32LE(4), responseTo: message.readInt32LE(8), opCode: message.readInt32LE(12) }; }
javascript
{ "resource": "" }
q28867
TCPConnection
train
function TCPConnection(user) { this.user = user; // Pick a CM randomly if (!user._cmList || !user._cmList.tcp_servers) { throw new Error("Nothing to connect to: " + (user._cmList ? "no TCP server list" : "no CM list")); } let tcpCm = user._cmList.tcp_servers[Math.floor(Math.random() * user._cmList.tcp_servers.length)]; user.emit('debug', 'Connecting to TCP CM: ' + tcpCm); let cmParts = tcpCm.split(':'); let cmHost = cmParts[0]; let cmPort = parseInt(cmParts[1], 10); if (user.options.httpProxy) { let url = URL.parse(user.options.httpProxy); url.method = 'CONNECT'; url.path = tcpCm; url.localAddress = user.options.localAddress; url.localPort = user.options.localPort; if (url.auth) { url.headers = {"Proxy-Authorization": "Basic " + (new Buffer(url.auth, 'utf8')).toString('base64')}; delete url.auth; } let connectionEstablished = false; let req = HTTP.request(url); req.end(); req.setTimeout(user.options.proxyTimeout || 5000); req.on('connect', (res, socket) => { if (connectionEstablished) { // somehow we're already connected, or we aborted socket.end(); return; } connectionEstablished = true; req.setTimeout(0); // disable timeout if (res.statusCode != 200) { this.user.emit('error', new Error('HTTP CONNECT ' + res.statusCode + ' ' + res.statusMessage)); return; } this.stream = socket; this._setupStream(); }); req.on('timeout', () => { connectionEstablished = true; this.user.emit('error', new Error('Proxy connection timed out')); }); req.on('error', (err) => { connectionEstablished = true; this.user.emit('error', err); }); } else { let socket = new Socket(); this.stream = socket; this._setupStream(); socket.connect({ "port": cmPort, "host": cmHost, "localAddress": user.options.localAddress, "localPort": user.options.localPort }); this.stream.setTimeout(this.user._connectTimeout); } }
javascript
{ "resource": "" }
q28868
toChatID
train
function toChatID(steamID) { steamID = Helpers.steamID(steamID); if (steamID.type == SteamID.Type.CLAN) { steamID.type = SteamID.Type.CHAT; steamID.instance |= SteamID.ChatInstanceFlags.Clan; } return steamID; }
javascript
{ "resource": "" }
q28869
fromChatID
train
function fromChatID(steamID) { steamID = Helpers.steamID(steamID); if (steamID.isGroupChat()) { steamID.type = SteamID.Type.CLAN; steamID.instance &= ~SteamID.ChatInstanceFlags.Clan; } return steamID; }
javascript
{ "resource": "" }
q28870
decomposeChatFlags
train
function decomposeChatFlags(chat, chatFlags) { chat.private = !!(chatFlags & SteamUser.EChatFlags.Locked); chat.invisibleToFriends = !!(chatFlags & SteamUser.EChatFlags.InvisibleToFriends); chat.officersOnlyChat = !!(chatFlags & SteamUser.EChatFlags.Moderated); chat.unjoinable = !!(chatFlags & SteamUser.EChatFlags.Unjoinable); }
javascript
{ "resource": "" }
q28871
processChatRoomSummaryPair
train
function processChatRoomSummaryPair(summaryPair, preProcessed) { if (!preProcessed) { summaryPair = preProcessObject(summaryPair); } summaryPair.group_state = processUserChatGroupState(summaryPair.user_chat_group_state, true); summaryPair.group_summary = processChatGroupSummary(summaryPair.group_summary, true); delete summaryPair.user_chat_group_state; return summaryPair; }
javascript
{ "resource": "" }
q28872
processChatGroupSummary
train
function processChatGroupSummary(groupSummary, preProcessed) { if (!preProcessed) { groupSummary = preProcessObject(groupSummary); } if (groupSummary.top_members) { groupSummary.top_members = groupSummary.top_members.map(accountid => SteamID.fromIndividualAccountID(accountid)); } return groupSummary; }
javascript
{ "resource": "" }
q28873
preProcessObject
train
function preProcessObject(obj) { for (let key in obj) { if (!obj.hasOwnProperty(key)) { continue; } let val = obj[key]; if (key.match(/^steamid_/) && typeof val === 'string' && val != '0') { obj[key] = new SteamID(val.toString()); } else if (key == 'timestamp' || key.match(/^time_/) || key.match(/_timestamp$/)) { if (val === 0) { obj[key] = null; } else if (val !== null) { obj[key] = new Date(val * 1000); } } else if (key == 'clanid' && typeof val === 'number') { let id = new SteamID(); id.universe = SteamID.Universe.PUBLIC; id.type = SteamID.Type.CLAN; id.instance = SteamID.Instance.ALL; id.accountid = val; obj[key] = id; } else if ((key == 'accountid' || key.match(/^accountid_/) || key.match(/_accountid$/)) && (typeof val === 'number' || val === null)) { let newKey = key == 'accountid' ? 'steamid' : key.replace('accountid_', 'steamid_').replace('_accountid', '_steamid'); obj[newKey] = val === 0 || val === null ? null : SteamID.fromIndividualAccountID(val); delete obj[key]; } else if (key.includes('avatar_sha')) { let url = null; if (obj[key] && obj[key].length) { url = "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/chaticons/"; url += obj[key][0].toString(16) + '/'; url += obj[key][1].toString(16) + '/'; url += obj[key][2].toString(16) + '/'; url += obj[key].toString('hex') + '_256.jpg'; } obj[key.replace('avatar_sha', 'avatar_url')] = url; } else if (key.match(/^can_/) && obj[key] === null) { obj[key] = false; } else if (isDataObject(val)) { obj[key] = preProcessObject(val); } else if (Array.isArray(val) && val.every(isDataObject)) { obj[key] = val.map(v => preProcessObject(v)); } } return obj; }
javascript
{ "resource": "" }
q28874
extractFonts
train
function extractFonts (state) { var list = String(state.list.buffer).split(',') var res = list.filter(function (font) { var extname = path.extname(font) return extname === '.woff' || extname === '.woff2' || extname === '.eot' || extname === '.ttf' }) return res }
javascript
{ "resource": "" }
q28875
init
train
function init (dirname, done) { dirname = path.join(basedir, dirname) fs.access(dirname, function (err) { if (err) return done() readdir(dirname, function (err, _list) { if (err) return done(err) list = list.concat(_list) done() }) }) }
javascript
{ "resource": "" }
q28876
matchSorter
train
function matchSorter(items, value, options = {}) { // not performing any search/sort if value(search term) is empty if (!value) return items const {keys, threshold = rankings.MATCHES} = options const matchedItems = items.reduce(reduceItemsToRanked, []) return matchedItems.sort(sortRankedItems).map(({item}) => item) function reduceItemsToRanked(matches, item, index) { const {rank, keyIndex, keyThreshold = threshold} = getHighestRanking( item, keys, value, options, ) if (rank >= keyThreshold) { matches.push({item, rank, index, keyIndex}) } return matches } }
javascript
{ "resource": "" }
q28877
getHighestRanking
train
function getHighestRanking(item, keys, value, options) { if (!keys) { return { rank: getMatchRanking(item, value, options), keyIndex: -1, keyThreshold: options.threshold, } } const valuesToRank = getAllValuesToRank(item, keys) return valuesToRank.reduce( ({rank, keyIndex, keyThreshold}, {itemValue, attributes}, i) => { let newRank = getMatchRanking(itemValue, value, options) const {minRanking, maxRanking, threshold} = attributes if (newRank < minRanking && newRank >= rankings.MATCHES) { newRank = minRanking } else if (newRank > maxRanking) { newRank = maxRanking } if (newRank > rank) { rank = newRank keyIndex = i keyThreshold = threshold } return {rank, keyIndex, keyThreshold} }, {rank: rankings.NO_MATCH, keyIndex: -1, keyThreshold: options.threshold}, ) }
javascript
{ "resource": "" }
q28878
getMatchRanking
train
function getMatchRanking(testString, stringToRank, options) { /* eslint complexity:[2, 12] */ testString = prepareValueForComparison(testString, options) stringToRank = prepareValueForComparison(stringToRank, options) // too long if (stringToRank.length > testString.length) { return rankings.NO_MATCH } // case sensitive equals if (testString === stringToRank) { return rankings.CASE_SENSITIVE_EQUAL } const caseRank = getCaseRanking(testString) const isPartial = isPartialOfCase(testString, stringToRank, caseRank) const isCasedAcronym = isCaseAcronym(testString, stringToRank, caseRank) // Lower casing before further comparison testString = testString.toLowerCase() stringToRank = stringToRank.toLowerCase() // case insensitive equals if (testString === stringToRank) { return rankings.EQUAL + caseRank } // starts with if (testString.indexOf(stringToRank) === 0) { return rankings.STARTS_WITH + caseRank } // word starts with if (testString.indexOf(` ${stringToRank}`) !== -1) { return rankings.WORD_STARTS_WITH + caseRank } // is a part inside a cased string if (isPartial) { return rankings.STRING_CASE + caseRank } // is acronym for a cased string if (caseRank > 0 && isCasedAcronym) { return rankings.STRING_CASE_ACRONYM + caseRank } // contains if (testString.indexOf(stringToRank) !== -1) { return rankings.CONTAINS + caseRank } else if (stringToRank.length === 1) { // If the only character in the given stringToRank // isn't even contained in the testString, then // it's definitely not a match. return rankings.NO_MATCH } // acronym if (getAcronym(testString).indexOf(stringToRank) !== -1) { return rankings.ACRONYM + caseRank } // will return a number between rankings.MATCHES and // rankings.MATCHES + 1 depending on how close of a match it is. return getClosenessRanking(testString, stringToRank) }
javascript
{ "resource": "" }
q28879
getCaseRanking
train
function getCaseRanking(testString) { const containsUpperCase = testString.toLowerCase() !== testString const containsDash = testString.indexOf('-') >= 0 const containsUnderscore = testString.indexOf('_') >= 0 if (!containsUpperCase && !containsUnderscore && containsDash) { return caseRankings.KEBAB } if (!containsUpperCase && containsUnderscore && !containsDash) { return caseRankings.SNAKE } if (containsUpperCase && !containsDash && !containsUnderscore) { const startsWithUpperCase = testString[0].toUpperCase() === testString[0] if (startsWithUpperCase) { return caseRankings.PASCAL } return caseRankings.CAMEL } return caseRankings.NO_CASE }
javascript
{ "resource": "" }
q28880
isCaseAcronym
train
function isCaseAcronym(testString, stringToRank, caseRank) { let splitValue = null switch (caseRank) { case caseRankings.SNAKE: splitValue = '_' break case caseRankings.KEBAB: splitValue = '-' break case caseRankings.PASCAL: case caseRankings.CAMEL: splitValue = /(?=[A-Z])/ break default: splitValue = null } const splitTestString = testString.split(splitValue) return stringToRank .toLowerCase() .split('') .reduce((correct, char, charIndex) => { const splitItem = splitTestString[charIndex] return correct && splitItem && splitItem[0].toLowerCase() === char }, true) }
javascript
{ "resource": "" }
q28881
getClosenessRanking
train
function getClosenessRanking(testString, stringToRank) { let charNumber = 0 function findMatchingCharacter(matchChar, string, index) { for (let j = index; j < string.length; j++) { const stringChar = string[j] if (stringChar === matchChar) { return j + 1 } } return -1 } function getRanking(spread) { const matching = spread - stringToRank.length + 1 const ranking = rankings.MATCHES + 1 / matching return ranking } const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0) if (firstIndex < 0) { return rankings.NO_MATCH } charNumber = firstIndex for (let i = 1; i < stringToRank.length; i++) { const matchChar = stringToRank[i] charNumber = findMatchingCharacter(matchChar, testString, charNumber) const found = charNumber > -1 if (!found) { return rankings.NO_MATCH } } const spread = charNumber - firstIndex return getRanking(spread) }
javascript
{ "resource": "" }
q28882
sortRankedItems
train
function sortRankedItems(a, b) { const aFirst = -1 const bFirst = 1 const {rank: aRank, index: aIndex, keyIndex: aKeyIndex} = a const {rank: bRank, index: bIndex, keyIndex: bKeyIndex} = b const same = aRank === bRank if (same) { if (aKeyIndex === bKeyIndex) { return aIndex < bIndex ? aFirst : bFirst } else { return aKeyIndex < bKeyIndex ? aFirst : bFirst } } else { return aRank > bRank ? aFirst : bFirst } }
javascript
{ "resource": "" }
q28883
getItemValues
train
function getItemValues(item, key) { if (typeof key === 'object') { key = key.key } let value if (typeof key === 'function') { value = key(item) // eslint-disable-next-line no-negated-condition } else if (key.indexOf('.') !== -1) { // handle nested keys value = key .split('.') .reduce( (itemObj, nestedKey) => (itemObj ? itemObj[nestedKey] : null), item, ) } else { value = item[key] } // concat because `value` can be a string or an array // eslint-disable-next-line return value != null ? [].concat(value) : null }
javascript
{ "resource": "" }
q28884
getAllValuesToRank
train
function getAllValuesToRank(item, keys) { return keys.reduce((allVals, key) => { const values = getItemValues(item, key) if (values) { values.forEach(itemValue => { allVals.push({ itemValue, attributes: getKeyAttributes(key), }) }) } return allVals }, []) }
javascript
{ "resource": "" }
q28885
getKeyAttributes
train
function getKeyAttributes(key) { if (typeof key === 'string') { key = {key} } return { maxRanking: Infinity, minRanking: -Infinity, ...key, } }
javascript
{ "resource": "" }
q28886
sqSegBoxDist
train
function sqSegBoxDist(a, b, bbox) { if (inside(a, bbox) || inside(b, bbox)) return 0; var d1 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.maxX, bbox.minY); if (d1 === 0) return 0; var d2 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.minY, bbox.minX, bbox.maxY); if (d2 === 0) return 0; var d3 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.maxX, bbox.minY, bbox.maxX, bbox.maxY); if (d3 === 0) return 0; var d4 = sqSegSegDist(a[0], a[1], b[0], b[1], bbox.minX, bbox.maxY, bbox.maxX, bbox.maxY); if (d4 === 0) return 0; return Math.min(d1, d2, d3, d4); }
javascript
{ "resource": "" }
q28887
updateBBox
train
function updateBBox(node) { var p1 = node.p; var p2 = node.next.p; node.minX = Math.min(p1[0], p2[0]); node.minY = Math.min(p1[1], p2[1]); node.maxX = Math.max(p1[0], p2[0]); node.maxY = Math.max(p1[1], p2[1]); return node; }
javascript
{ "resource": "" }
q28888
fastConvexHull
train
function fastConvexHull(points) { var left = points[0]; var top = points[0]; var right = points[0]; var bottom = points[0]; // find the leftmost, rightmost, topmost and bottommost points for (var i = 0; i < points.length; i++) { var p = points[i]; if (p[0] < left[0]) left = p; if (p[0] > right[0]) right = p; if (p[1] < top[1]) top = p; if (p[1] > bottom[1]) bottom = p; } // filter out points that are inside the resulting quadrilateral var cull = [left, top, right, bottom]; var filtered = cull.slice(); for (i = 0; i < points.length; i++) { if (!pointInPolygon(points[i], cull)) filtered.push(points[i]); } // get convex hull around the filtered points var indices = convexHull(filtered); // return the hull as array of points (rather than indices) var hull = []; for (i = 0; i < indices.length; i++) hull.push(filtered[indices[i]]); return hull; }
javascript
{ "resource": "" }
q28889
insertNode
train
function insertNode(p, prev) { var node = { p: p, prev: null, next: null, minX: 0, minY: 0, maxX: 0, maxY: 0 }; if (!prev) { node.prev = node; node.next = node; } else { node.next = prev.next; node.prev = prev; prev.next.prev = node; prev.next = node; } return node; }
javascript
{ "resource": "" }
q28890
getSqDist
train
function getSqDist(p1, p2) { var dx = p1[0] - p2[0], dy = p1[1] - p2[1]; return dx * dx + dy * dy; }
javascript
{ "resource": "" }
q28891
Snapshot
train
function Snapshot (id, obj) { if (!id) { var errIdMsg = 'id not injected!'; debug(errIdMsg); throw new Error(errIdMsg); } if (!obj) { var errObjMsg = 'object not injected!'; debug(errObjMsg); throw new Error(errObjMsg); } if (!obj.aggregateId) { var errAggIdMsg = 'object.aggregateId not injected!'; debug(errAggIdMsg); throw new Error(errAggIdMsg); } if (!obj.data) { var errDataMsg = 'object.data not injected!'; debug(errDataMsg); throw new Error(errDataMsg); } this.id = id; this.streamId = obj.aggregateId; this.aggregateId = obj.aggregateId; this.aggregate = obj.aggregate || null; this.context = obj.context || null; this.commitStamp = null; this.revision = obj.revision; this.version = obj.version; this.data = obj.data; }
javascript
{ "resource": "" }
q28892
EventStream
train
function EventStream (eventstore, query, events) { if (!eventstore) { var errESMsg = 'eventstore not injected!'; debug(errESMsg); throw new Error(errESMsg); } if (typeof eventstore.commit !== 'function') { var errESfnMsg = 'eventstore.commit not injected!'; debug(errESfnMsg); throw new Error(errESfnMsg); } if (!query) { var errQryMsg = 'query not injected!'; debug(errQryMsg); throw new Error(errQryMsg); } if (!query.aggregateId) { var errAggIdMsg = 'query.aggregateId not injected!'; debug(errAggIdMsg); throw new Error(errAggIdMsg); } if (events) { if (!_.isArray(events)) { var errEvtsArrMsg = 'events should be an array!'; debug(errEvtsArrMsg); throw new Error(errEvtsArrMsg); } for (var i = 0, len = events.length; i < len; i++) { var evt = events[i]; if (evt.streamRevision === undefined || evt.streamRevision === null) { var errEvtMsg = 'The events passed should all have a streamRevision!'; debug(errEvtMsg); throw new Error(errEvtMsg); } } } this.eventstore = eventstore; this.streamId = query.aggregateId; this.aggregateId = query.aggregateId; this.aggregate = query.aggregate; this.context = query.context; this.events = events || []; this.uncommittedEvents = []; this.lastRevision = -1; this.events = _.sortBy(this.events, 'streamRevision'); // to update lastRevision... this.currentRevision(); }
javascript
{ "resource": "" }
q28893
train
function() { for (var i = 0, len = this.events.length; i < len; i++) { if (this.events[i].streamRevision > this.lastRevision) { this.lastRevision = this.events[i].streamRevision; } } return this.lastRevision; }
javascript
{ "resource": "" }
q28894
train
function(events) { if (!_.isArray(events)) { var errEvtsArrMsg = 'events should be an array!'; debug(errEvtsArrMsg); throw new Error(errEvtsArrMsg); } var self = this; _.each(events, function(evt) { self.addEvent(evt); }); }
javascript
{ "resource": "" }
q28895
trigger
train
function trigger (dispatcher) { var queue = dispatcher.undispatchedEventsQueue || [] var event; // if the last loop is still in progress leave this loop if (dispatcher.isRunning) return; dispatcher.isRunning = true; (function next (e) { // dipatch one event in queue and call the _next_ callback, which // will call _process_ for the next undispatched event in queue. function process (event, nxt) { // Publish it now... debug('publish event...'); dispatcher.publisher(event.payload, function(err) { if (err) { return debug(err); } // ...and set the published event to dispatched. debug('set event to dispatched...'); dispatcher.store.setEventToDispatched(event, function(err) { if (err) { debug(err); } else { debug('event set to dispatched'); } }); }); nxt(); } // serial process all events in queue if (!e && queue.length) { process(queue.shift(), next) } else { debug(e); } })(); dispatcher.isRunning = false; }
javascript
{ "resource": "" }
q28896
process
train
function process (event, nxt) { // Publish it now... debug('publish event...'); dispatcher.publisher(event.payload, function(err) { if (err) { return debug(err); } // ...and set the published event to dispatched. debug('set event to dispatched...'); dispatcher.store.setEventToDispatched(event, function(err) { if (err) { debug(err); } else { debug('event set to dispatched'); } }); }); nxt(); }
javascript
{ "resource": "" }
q28897
train
function(events) { var self = this; events.forEach(function(event) { self.undispatchedEventsQueue.push(event); }); trigger(this); }
javascript
{ "resource": "" }
q28898
train
function(callback) { if (typeof this.publisher !== 'function') { var pubErrMsg = 'publisher not injected!'; debug(pubErrMsg); if (callback) callback(new Error(pubErrMsg)); return; } if (!this.store || typeof this.store.getUndispatchedEvents !== 'function' || typeof this.store.setEventToDispatched !== 'function') { var storeErrMsg = 'store not injected!'; debug(storeErrMsg); if (callback) callback(new Error(storeErrMsg)) return; } var self = this; // Get all undispatched events from store and queue them // before all other events passed in by the addUndispatchedEvents function. this.store.getUndispatchedEvents(function(err, events) { if (err) { debug(err); if (callback) callback(err); return; } var triggered = false; if (events) { for (var i = 0, len = events.length; i < len; i++) { self.undispatchedEventsQueue.push(events[i]); // If there are a lot of events then we can hit issues with the call stack size when processing in one go triggered = false; if (i % 1000 === 0){ triggered = true; trigger(self); } } } if (!triggered) { trigger(self); } if (callback) callback(null); }); }
javascript
{ "resource": "" }
q28899
train
function (fn) { if (fn.length === 1) { fn = _.wrap(fn, function(func, evt, callback) { func(evt); callback(null); }); } this.publisher = fn; return this; }
javascript
{ "resource": "" }