_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q24200
_addOneHandler
train
async function _addOneHandler( ownerModel, ownerId, childModel, childId, associationName, request, Log ) { try { let ownerObject = await ownerModel .findOne({ _id: ownerId }) .select(associationName) let payload = Object.assign({}, request.payload) if (ownerObject) { if (!payload) { payload = {} } payload.childId = childId payload = [payload] try { if ( ownerModel.routeOptions && ownerModel.routeOptions.add && ownerModel.routeOptions.add[associationName] && ownerModel.routeOptions.add[associationName].pre ) { payload = await ownerModel.routeOptions.add[associationName].pre( payload, request, Log ) } } catch (err) { handleError( err, 'There was a preprocessing error while setting the association.', Boom.badRequest, Log ) } try { await _setAssociation( ownerModel, ownerObject, childModel, childId, associationName, payload, Log ) } catch (err) { handleError( err, 'There was a database error while setting the association.', Boom.badImplementation, Log ) } return true } else { throw Boom.notFound('No resource was found with that id.') } } catch (err) { handleError(err, null, null, Log) } }
javascript
{ "resource": "" }
q24201
_removeOne
train
function _removeOne( ownerModel, ownerId, childModel, childId, associationName, Log ) { let request = { params: { ownerId: ownerId, childId: childId } } return _removeOneHandler( ownerModel, ownerId, childModel, childId, associationName, request, Log ) }
javascript
{ "resource": "" }
q24202
_removeOneHandler
train
async function _removeOneHandler( ownerModel, ownerId, childModel, childId, associationName, request, Log ) { try { let ownerObject = await ownerModel .findOne({ _id: ownerId }) .select(associationName) if (ownerObject) { try { if ( ownerModel.routeOptions && ownerModel.routeOptions.remove && ownerModel.routeOptions.remove[associationName] && ownerModel.routeOptions.remove[associationName].pre ) { await ownerModel.routeOptions.remove[associationName].pre( {}, request, Log ) } } catch (err) { handleError( err, 'There was a preprocessing error while removing the association.', Boom.badRequest, Log ) } try { await _removeAssociation( ownerModel, ownerObject, childModel, childId, associationName, Log ) } catch (err) { handleError( err, 'There was a database error while removing the association.', Boom.badImplementation, Log ) } return true } else { throw Boom.notFound('No resource was found with that id.') } } catch (err) { handleError(err, null, null, Log) } }
javascript
{ "resource": "" }
q24203
_addMany
train
function _addMany( ownerModel, ownerId, childModel, associationName, payload, Log ) { let request = { params: { ownerId: ownerId }, payload: payload } return _addManyHandler( ownerModel, ownerId, childModel, associationName, request, Log ) }
javascript
{ "resource": "" }
q24204
_addManyHandler
train
async function _addManyHandler( ownerModel, ownerId, childModel, associationName, request, Log ) { try { // EXPL: make a copy of the payload so that request.payload remains unchanged let payload = request.payload.map(item => { return _.isObject(item) ? _.assignIn({}, item) : item }) if (_.isEmpty(request.payload)) { throw Boom.badRequest('Payload is empty.') } let ownerObject = await ownerModel .findOne({ _id: ownerId }) .select(associationName) if (ownerObject) { try { if ( ownerModel.routeOptions && ownerModel.routeOptions.add && ownerModel.routeOptions.add[associationName] && ownerModel.routeOptions.add[associationName].pre ) { payload = await ownerModel.routeOptions.add[associationName].pre( payload, request, Log ) } } catch (err) { handleError( err, 'There was a preprocessing error while setting the association.', Boom.badRequest, Log ) } let childIds = [] // EXPL: the payload is an array of Ids if ( typeof payload[0] === 'string' || payload[0] instanceof String || payload[0]._bsontype === 'ObjectID' ) { childIds = payload } else { // EXPL: the payload contains extra fields childIds = payload.map(object => { return object.childId }) } for (let childId of childIds) { try { await _setAssociation( ownerModel, ownerObject, childModel, childId, associationName, payload, Log ) } catch (err) { handleError( err, 'There was an internal error while setting the associations.', Boom.badImplementation, Log ) } } return true } else { throw Boom.notFound('No owner resource was found with that id.') } } catch (err) { handleError(err, null, null, Log) } }
javascript
{ "resource": "" }
q24205
_removeMany
train
function _removeMany( ownerModel, ownerId, childModel, associationName, payload, Log ) { let request = { params: { ownerId: ownerId }, payload: payload } return _removeManyHandler( ownerModel, ownerId, childModel, associationName, request, Log ) }
javascript
{ "resource": "" }
q24206
_removeManyHandler
train
async function _removeManyHandler( ownerModel, ownerId, childModel, associationName, request, Log ) { try { // EXPL: make a copy of the payload so that request.payload remains unchanged let payload = request.payload.map(item => { return _.isObject(item) ? _.assignIn({}, item) : item }) if (_.isEmpty(request.payload)) { throw Boom.badRequest('Payload is empty.') } let ownerObject = await ownerModel .findOne({ _id: ownerId }) .select(associationName) if (ownerObject) { try { if ( ownerModel.routeOptions && ownerModel.routeOptions.remove && ownerModel.routeOptions.remove[associationName] && ownerModel.routeOptions.remove[associationName].pre ) { payload = await ownerModel.routeOptions.remove[associationName].pre( payload, request, Log ) } } catch (err) { handleError( err, 'There was a preprocessing error while removing the association.', Boom.badRequest, Log ) } for (let childId of payload) { try { await _removeAssociation( ownerModel, ownerObject, childModel, childId, associationName, Log ) } catch (err) { handleError( err, 'There was an internal error while removing the associations.', Boom.badImplementation, Log ) } } return true } else { throw Boom.notFound('No owner resource was found with that id.') } } catch (err) { handleError(err, null, null, Log) } }
javascript
{ "resource": "" }
q24207
_getAll
train
function _getAll(ownerModel, ownerId, childModel, associationName, query, Log) { let request = { params: { ownerId: ownerId }, query: query } return _getAllHandler( ownerModel, ownerId, childModel, associationName, request, Log ) }
javascript
{ "resource": "" }
q24208
filterDeletedEmbeds
train
function filterDeletedEmbeds(result, parent, parentkey, depth, Log) { if (_.isArray(result)) { result = result.filter(function(obj) { let keep = filterDeletedEmbeds(obj, result, parentkey, depth + 1, Log) // Log.log("KEEP:", keep); return keep }) // Log.log("UPDATED:", parentkey); // Log.note("AFTER:", result); parent[parentkey] = result } else { for (let key in result) { // Log.debug("KEY:", key); // Log.debug("VALUE:", result[key]); if (_.isArray(result[key])) { // Log.log("JUMPING IN ARRAY"); filterDeletedEmbeds(result[key], result, key, depth + 1, Log) } else if (_.isObject(result[key]) && result[key]._id) { // Log.log("JUMPING IN OBJECT"); let keep = filterDeletedEmbeds(result[key], result, key, depth + 1, Log) if (!keep) { return false } } else if (key === 'isDeleted' && result[key] === true && depth > 0) { // Log.log("DELETED", depth); return false } } // Log.log("JUMPING OUT"); return true } }
javascript
{ "resource": "" }
q24209
train
function(model, logger) { assert( model.schema, "model not mongoose format. 'schema' property required." ) assert( model.schema.paths, "model not mongoose format. 'schema.paths' property required." ) assert( model.schema.tree, "model not mongoose format. 'schema.tree' property required." ) let fields = model.schema.paths let fieldNames = Object.keys(fields) assert( model.routeOptions, "model not mongoose format. 'routeOptions' property required." ) for (let i = 0; i < fieldNames.length; i++) { let fieldName = fieldNames[i] assert( fields[fieldName].options, "field not mongoose format. 'options' parameter required." ) } return true }
javascript
{ "resource": "" }
q24210
train
function(server, model, options, logger) { const Log = logger.bind('Password Update') let Boom = require('boom') let collectionName = model.collectionDisplayName || model.modelName Log.note('Generating Password Update endpoint for ' + collectionName) let handler = async function(request, h) { try { let hashedPassword = model.generatePasswordHash( request.payload.password ) await model.findByIdAndUpdate(request.params._id, { password: hashedPassword }) return h.response('Password updated.').code(200) } catch (err) { Log.error(err) throw Boom.badImplementation(err) } } server.route({ method: 'PUT', path: '/user/{_id}/password', config: { handler: handler, auth: null, description: "Update a user's password.", tags: ['api', 'User', 'Password'], validate: { params: { _id: RestHapi.joiHelper.joiObjectId().required() }, payload: { password: Joi.string() .required() .description("The user's new password") } }, plugins: { 'hapi-swagger': { responseMessages: [ { code: 200, message: 'Success' }, { code: 400, message: 'Bad Request' }, { code: 404, message: 'Not Found' }, { code: 500, message: 'Internal Server Error' } ] } } } }) }
javascript
{ "resource": "" }
q24211
getLogger
train
function getLogger(label) { let config = defaultConfig extend(true, config, module.exports.config) let rootLogger = logging.getLogger(chalk.gray(label)) rootLogger.logLevel = config.loglevel return rootLogger }
javascript
{ "resource": "" }
q24212
mongooseInit
train
function mongooseInit(mongoose, logger, config) { const Log = logger.bind('mongoose-init') mongoose.Promise = Promise logUtil.logActionStart( Log, 'Connecting to Database', _.omit(config.mongo, ['pass']) ) mongoose.connect(config.mongo.URI) globals.mongoose = mongoose Log.log('mongoose connected') return mongoose }
javascript
{ "resource": "" }
q24213
registerMrHorse
train
async function registerMrHorse(server, logger, config) { const Log = logger.bind('register-MrHorse') let policyPath = '' if (config.enablePolicies) { if (config.absolutePolicyPath === true) { policyPath = config.policyPath } else { policyPath = __dirname.replace( 'node_modules/rest-hapi', config.policyPath ) } } else { policyPath = path.join(__dirname, '/policies') } await server.register([ { plugin: Mrhorse, options: { policyDirectory: policyPath } } ]) if (config.enablePolicies) { await server.plugins.mrhorse.loadPolicies(server, { policyDirectory: path.join(__dirname, '/policies') }) } Log.info('MrHorse plugin registered') }
javascript
{ "resource": "" }
q24214
registerHapiSwagger
train
async function registerHapiSwagger(server, logger, config) { const Log = logger.bind('register-hapi-swagger') let swaggerOptions = { documentationPath: '/', host: config.swaggerHost, expanded: config.docExpansion, swaggerUI: config.enableSwaggerUI, documentationPage: config.enableSwaggerUI, schemes: config.enableSwaggerHttps ? ['https'] : ['http'] } // if swagger config is defined, use that if (config.swaggerOptions) { swaggerOptions = { ...swaggerOptions, ...config.swaggerOptions } } // override some options for safety if (!swaggerOptions.info) { swaggerOptions.info = {} } swaggerOptions.info.title = config.appTitle swaggerOptions.info.version = config.version swaggerOptions.reuseDefinitions = false await server.register([ Inert, Vision, { plugin: HapiSwagger, options: swaggerOptions } ]) Log.info('hapi-swagger plugin registered') }
javascript
{ "resource": "" }
q24215
train
function(model, query, mongooseQuery, logger) { // This line has to come first validationHelper.validateModel(model, logger) const Log = logger.bind() // (email == 'test@user.com' && (firstName == 'test2@user.com' || firstName == 'test4@user.com')) && (age < 15 || age > 30) // LITERAL // { // and: { // email: { // equal: 'test@user.com', // }, // or: { // firstName: { // equal: ['test2@user.com', 'test4@user.com'] // } // }, // age: { // gt: '15', // lt: '30' // } // } // { // and[email][equal]=test@user.com&and[or][firstName][equal]=test2@user.com&and[or][firstName][equal]=test4@user.com&and[age][gt]=15 // ABBREVIATED // { // email:'test@user.com', // firstName: ['test2@user.com', 'test4@user.com'], // age: { // $or: { // $gt: '15', // $lt: '30' // } // } // } // [email]=test@user.com&[firstName]=test2@user.com&[firstName]=test4@user.com&[age][gt]=15&[age][lt]=30 delete query[''] // EXPL: hack due to bug in hapi-swagger-docs delete query.$count mongooseQuery = this.setExclude(query, mongooseQuery, Log) let attributesFilter = this.createAttributesFilter(query, model, Log) if (attributesFilter === '') { attributesFilter = '_id' } let result = this.populateEmbeddedDocs( query, mongooseQuery, attributesFilter, model.routeOptions.associations, model, Log ) mongooseQuery = result.mongooseQuery attributesFilter = result.attributesFilter mongooseQuery = this.setSort(query, mongooseQuery, Log) mongooseQuery.select(attributesFilter) if (typeof query.$where === 'string') { query.$where = JSON.parse(query.$where) } if (query.$where) { mongooseQuery.where(query.$where) delete query.$where } // EXPL: Support single (string) inputs or multiple "or'd" inputs (arrays) for field queries for (let fieldQueryKey in query) { let fieldQuery = query[fieldQueryKey] if (!Array.isArray(fieldQuery)) { fieldQuery = tryParseJSON(query[fieldQueryKey]) } if ( fieldQuery && Array.isArray(fieldQuery) && fieldQueryKey !== '$searchFields' ) { query[fieldQueryKey] = { $in: fieldQuery } // EXPL: "or" the inputs } } // EXPL: handle full text search if (query.$text) { query.$text = { $search: query.$text } } // EXPL: handle regex search this.setTermSearch(query, model, Log) let whereQuery = _.extend({}, query) // EXPL: delete pagination parameters delete whereQuery.$limit delete whereQuery.$skip delete whereQuery.$page mongooseQuery.where(whereQuery) return mongooseQuery }
javascript
{ "resource": "" }
q24216
train
function(model, logger) { // This line has to come first validationHelper.validateModel(model, logger) let readableFields = [] let fields = model.schema.paths for (let fieldName in fields) { let field = fields[fieldName].options if (!field.exclude && fieldName !== '__v') { readableFields.push(fieldName) } } return readableFields }
javascript
{ "resource": "" }
q24217
train
function(model, logger) { // This line has to come first validationHelper.validateModel(model, logger) const Log = logger.bind() let sortableFields = this.getReadableFields(model, Log) for (let i = sortableFields.length - 1; i >= 0; i--) { let descendingField = '-' + sortableFields[i] sortableFields.splice(i, 0, descendingField) } return sortableFields }
javascript
{ "resource": "" }
q24218
train
function(model, logger) { // This line has to come first validationHelper.validateModel(model, logger) let queryableFields = [] let fields = model.schema.paths let fieldNames = Object.keys(fields) let associations = model.routeOptions ? model.routeOptions.associations : null for (let i = 0; i < fieldNames.length; i++) { let fieldName = fieldNames[i] if (fields[fieldName] && fieldName !== '__v' && fieldName !== '__t') { let field = fields[fieldName].options let association = associations ? associations[fields[fieldName].path] || {} : {} // EXPL: by default we don't include MANY_MANY array references if ( field.queryable !== false && !field.exclude && association.type !== 'MANY_MANY' ) { queryableFields.push(fieldName) } } } return queryableFields }
javascript
{ "resource": "" }
q24219
train
function(query, mongooseQuery, logger) { const Log = logger.bind() if (query.$page) { mongooseQuery = this.setPage(query, mongooseQuery, Log) } else { mongooseQuery = this.setSkip(query, mongooseQuery, Log) } mongooseQuery = this.setLimit(query, mongooseQuery, Log) return mongooseQuery }
javascript
{ "resource": "" }
q24220
train
function(query, mongooseQuery, logger) { if (query.$exclude) { if (!Array.isArray(query.$exclude)) { query.$exclude = query.$exclude.split(',') } mongooseQuery.where({ _id: { $nin: query.$exclude } }) delete query.$exclude } return mongooseQuery }
javascript
{ "resource": "" }
q24221
train
function(query, model, logger) { const Log = logger.bind() if (query.$term) { query.$or = [] // TODO: allow option to choose ANDing or ORing of searchFields/queryableFields let queryableFields = this.getQueryableFields(model, Log) let stringFields = this.getStringFields(model, Log) // EXPL: we can only search fields that are a string type queryableFields = queryableFields.filter(function(field) { return stringFields.indexOf(field) > -1 }) // EXPL: search only specified fields if included if (query.$searchFields) { if (!Array.isArray(query.$searchFields)) { query.$searchFields = query.$searchFields.split(',') } // EXPL: we can only search fields that are a string type query.$searchFields = query.$searchFields.filter(function(field) { return stringFields.indexOf(field) > -1 }) query.$searchFields.forEach(function(field) { let obj = {} obj[field] = new RegExp(query.$term, 'i') query.$or.push(obj) }) } else { queryableFields.forEach(function(field) { let obj = {} obj[field] = new RegExp(query.$term, 'i') query.$or.push(obj) }) } } delete query.$searchFields delete query.$term }
javascript
{ "resource": "" }
q24222
train
function(query, mongooseQuery, logger) { if (query.$sort) { if (Array.isArray(query.$sort)) { query.$sort = query.$sort.join(' ') } mongooseQuery.sort(query.$sort) delete query.$sort } return mongooseQuery }
javascript
{ "resource": "" }
q24223
getReference
train
function getReference(model, embed, logger) { let property = model.schema.obj[embed] while (_.isArray(property)) { property = property[0] } if (property && property.ref) { return { model: property.ref, include: { model: globals.mongoose.model(property.ref), as: embed } } } else { return null } }
javascript
{ "resource": "" }
q24224
train
function(model, type, logger) { let routeScope = model.routeOptions.routeScope || {} let rootScope = routeScope.rootScope let scope = [] let additionalScope = null switch (type) { case 'create': additionalScope = routeScope.createScope break case 'read': additionalScope = routeScope.readScope break case 'update': additionalScope = routeScope.updateScope break case 'delete': additionalScope = routeScope.deleteScope break case 'associate': additionalScope = routeScope.associateScope break default: if (routeScope[type]) { scope = routeScope[type] if (!_.isArray(scope)) { scope = [scope] } } return scope } if (rootScope && _.isArray(rootScope)) { scope = scope.concat(rootScope) } else if (rootScope) { scope.push(rootScope) } if (additionalScope && _.isArray(additionalScope)) { scope = scope.concat(additionalScope) } else if (additionalScope) { scope.push(additionalScope) } return scope }
javascript
{ "resource": "" }
q24225
showError
train
function showError(error) { console.error(logSymbols.error, "Error"); console.error(`${error.message}\n`); console.error(logSymbols.error, "Stack trace"); console.error(error.stack); }
javascript
{ "resource": "" }
q24226
parse
train
function parse(text) { const ast = remark.parse(text); const src = new StructuredSource(text); traverse(ast).forEach(function(node) { // eslint-disable-next-line no-invalid-this if (this.notLeaf) { if (node.type) { const replacedType = SyntaxMap[node.type]; if (!replacedType) { debug(`replacedType : ${replacedType} , node.type: ${node.type}`); } else { node.type = replacedType; } } // map `range`, `loc` and `raw` to node if (node.position) { const position = node.position; const positionCompensated = { start: { line: position.start.line, column: position.start.column - 1 }, end: { line: position.end.line, column: position.end.column - 1 } }; const range = src.locationToRange(positionCompensated); node.loc = positionCompensated; node.range = range; node.raw = text.slice(range[0], range[1]); // Compatible for https://github.com/wooorm/unist, but hidden Object.defineProperty(node, "position", { enumerable: false, configurable: false, writable: false, value: position }); } } }); return ast; }
javascript
{ "resource": "" }
q24227
createParagraph
train
function createParagraph(nodes) { const firstNode = nodes[0]; const lastNode = nodes[nodes.length - 1]; return { type: Syntax.Paragraph, raw: nodes .map(function(node) { return node.raw; }) .join(""), range: [firstNode.range[0], lastNode.range[1]], loc: { start: { line: firstNode.loc.start.line, column: firstNode.loc.start.column }, end: { line: lastNode.loc.end.line, column: lastNode.loc.end.column } }, children: nodes }; }
javascript
{ "resource": "" }
q24228
parse
train
function parse(text) { const textLineByLine = text.split(LINEBREAKE_MARK); // it should be alternately Str and Break let startIndex = 0; const lastLineIndex = textLineByLine.length - 1; const isLasEmptytLine = (line, index) => { return index === lastLineIndex && line === ""; }; const isEmptyLine = (line, index) => { return index !== lastLineIndex && line === ""; }; const children = textLineByLine.reduce(function(result, currentLine, index) { const lineNumber = index + 1; if (isLasEmptytLine(currentLine, index)) { return result; } // \n if (isEmptyLine(currentLine, index)) { const emptyBreakNode = createBRNode(lineNumber, startIndex); startIndex += emptyBreakNode.raw.length; result.push(emptyBreakNode); return result; } // (Paragraph > Str) -> Br? const strNode = parseLine(currentLine, lineNumber, startIndex); const paragraph = createParagraph([strNode]); startIndex += paragraph.raw.length; result.push(paragraph); if (index !== lastLineIndex) { const breakNode = createEndedBRNode(paragraph); startIndex += breakNode.raw.length; result.push(breakNode); } return result; }, []); return { type: Syntax.Document, raw: text, range: [0, text.length], loc: { start: { line: 1, column: 0 }, end: { line: textLineByLine.length, column: textLineByLine[textLineByLine.length - 1].length } }, children }; }
javascript
{ "resource": "" }
q24229
time
train
function time(cmd, runs, runNumber, results, cb) { var start = process.hrtime(); exec(cmd, { silent: true }, function() { var diff = process.hrtime(start), actual = diff[0] * 1e3 + diff[1] / 1e6; // ms results.push(actual); echo("Performance Run #" + runNumber + ": %dms", actual); if (runs > 1) { time(cmd, runs - 1, runNumber + 1, results, cb); } else { return cb(results); } }); }
javascript
{ "resource": "" }
q24230
getParents
train
function getParents(node) { var result = []; var parent = node.parent; while (parent != null) { result.push(parent); parent = parent.parent; } return result; }
javascript
{ "resource": "" }
q24231
isNodeWrapped
train
function isNodeWrapped(node, types) { var parents = getParents(node); var parentsTypes = parents.map(function(parent) { return parent.type; }); return types.some(function(type) { return parentsTypes.some(function(parentType) { return parentType === type; }); }); }
javascript
{ "resource": "" }
q24232
cubism_graphiteParse
train
function cubism_graphiteParse(text) { var i = text.indexOf("|"), meta = text.substring(0, i), c = meta.lastIndexOf(","), b = meta.lastIndexOf(",", c - 1), a = meta.lastIndexOf(",", b - 1), start = meta.substring(a + 1, b) * 1000, step = meta.substring(c + 1) * 1000; return text .substring(i + 1) .split(",") .slice(1) // the first value is always None? .map(function(d) { return +d; }); }
javascript
{ "resource": "" }
q24233
prepare
train
function prepare(start1, stop) { var steps = Math.min(size, Math.round((start1 - start) / step)); if (!steps || fetching) return; // already fetched, or fetching! fetching = true; steps = Math.min(size, steps + cubism_metricOverlap); var start0 = new Date(stop - steps * step); request(start0, stop, step, function(error, data) { fetching = false; if (error) return console.warn(error); var i = isFinite(start) ? Math.round((start0 - start) / step) : 0; for (var j = 0, m = data.length; j < m; ++j) values[j + i] = data[j]; event.change.call(metric, start, stop); }); }
javascript
{ "resource": "" }
q24234
beforechange
train
function beforechange(start1, stop1) { if (!isFinite(start)) start = start1; values.splice(0, Math.max(0, Math.min(size, Math.round((start1 - start) / step)))); start = start1; stop = stop1; }
javascript
{ "resource": "" }
q24235
cubism_metricShift
train
function cubism_metricShift(request, offset) { return function(start, stop, step, callback) { request(new Date(+start + offset), new Date(+stop + offset), step, callback); }; }
javascript
{ "resource": "" }
q24236
expireSessionIDs
train
function expireSessionIDs(){ var tssec = Date.now(); var expired = []; for(var sid in sessionIDs){ if(sessionIDs[sid] < (tssec + 500)){ expired.push(sid); } } for(var i=0;i<expired.length;i++){ delete sessionIDs[expired[i]]; debug('Session ID expired: %s', expired[i]); } }
javascript
{ "resource": "" }
q24237
processOptions
train
function processOptions(options){ if(!options) return; for(var op in swsUtil.supportedOptions){ if(op in options){ swsOptions[op] = options[op]; } } // update standard path pathUI = swsOptions.uriPath+'/ui'; pathDist = swsOptions.uriPath+'/dist'; pathStats = swsOptions.uriPath+'/stats'; pathMetrics = swsOptions.uriPath+'/metrics'; pathLogout = swsOptions.uriPath+'/logout'; if( swsOptions.authentication ){ setInterval(expireSessionIDs,500); } }
javascript
{ "resource": "" }
q24238
train
function (options) { processOptions(options); processor = new swsProcessor(); processor.init(swsOptions); return function trackingMiddleware(req, res, next) { // Respond to requests handled by swagger-stats // swagger-stats requests will not be counted in statistics if(req.url.startsWith(pathStats)) { return processGetStats(req, res); }else if(req.url.startsWith(pathMetrics)){ return processGetMetrics(req,res); }else if(req.url.startsWith(pathLogout)){ processLogout(req,res); return; }else if(req.url.startsWith(pathUI) ){ res.status(200).send(uiMarkup); return; }else if(req.url.startsWith(pathDist)) { var fileName = req.url.replace(pathDist+'/',''); var qidx = fileName.indexOf('?'); if(qidx!=-1) fileName = fileName.substring(0,qidx); var options = { root: path.join(__dirname,'..','dist'), dotfiles: 'deny' // TODO Caching }; res.sendFile(fileName, options, function (err) { if (err) { debug('unable to send file: %s',fileName); } }); return; } handleRequest(req, res); return next(); }; }
javascript
{ "resource": "" }
q24239
getIPs
train
function getIPs(callback) { if (typeof document === 'undefined' || typeof document.getElementById !== 'function') { return; } var ipDuplicates = {}; //compatibility for firefox and chrome var RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; var useWebKit = !!window.webkitRTCPeerConnection; // bypass naive webrtc blocking using an iframe if (!RTCPeerConnection) { var iframe = document.getElementById('iframe'); if (!iframe) { //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe> throw 'NOTE: you need to have an iframe in the page right above the script tag.'; } var win = iframe.contentWindow; RTCPeerConnection = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection; useWebKit = !!win.webkitRTCPeerConnection; } // if still no RTCPeerConnection then it is not supported by the browser so just return if (!RTCPeerConnection) { return; } //minimal requirements for data connection var mediaConstraints = { optional: [{ RtpDataChannels: true }] }; //firefox already has a default stun server in about:config // media.peerconnection.default_iceservers = // [{"url": "stun:stun.services.mozilla.com"}] var servers; //add same stun server for chrome if (useWebKit) { servers = { iceServers: [{ urls: 'stun:stun.services.mozilla.com' }] }; if (typeof DetectRTC !== 'undefined' && DetectRTC.browser.isFirefox && DetectRTC.browser.version <= 38) { servers[0] = { url: servers[0].urls }; } } //construct a new RTCPeerConnection var pc = new RTCPeerConnection(servers, mediaConstraints); function handleCandidate(candidate) { //match just the IP address var ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/; var match = ipRegex.exec(candidate); if (!match) { console.warn('Could not match IP address in', candidate); return; } var ipAddress = match[1]; //remove duplicates if (ipDuplicates[ipAddress] === undefined) { callback(ipAddress); } ipDuplicates[ipAddress] = true; } //listen for candidate events pc.onicecandidate = function(ice) { //skip non-candidate events if (ice.candidate) { handleCandidate(ice.candidate.candidate); } }; //create a bogus data channel pc.createDataChannel(''); //create an offer sdp pc.createOffer(function(result) { //trigger the stun server request pc.setLocalDescription(result, function() {}, function() {}); }, function() {}); //wait for a while to let everything done setTimeout(function() { //read candidate info from local description var lines = pc.localDescription.sdp.split('\n'); lines.forEach(function(line) { if (line.indexOf('a=candidate:') === 0) { handleCandidate(line); } }); }, 1000); }
javascript
{ "resource": "" }
q24240
getObject
train
function getObject() { return objectPool.pop() || { 'array': null, 'cache': null, 'criteria': null, 'false': false, 'index': 0, 'null': false, 'number': null, 'object': null, 'push': null, 'string': null, 'true': false, 'undefined': false, 'value': null }; }
javascript
{ "resource": "" }
q24241
releaseArray
train
function releaseArray(array) { array.length = 0; if (arrayPool.length < maxPoolSize) { arrayPool.push(array); } }
javascript
{ "resource": "" }
q24242
releaseObject
train
function releaseObject(object) { var cache = object.cache; if (cache) { releaseObject(cache); } object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; if (objectPool.length < maxPoolSize) { objectPool.push(object); } }
javascript
{ "resource": "" }
q24243
create
train
function create(prototype, properties) { var result = baseCreate(prototype); return properties ? assign(result, properties) : result; }
javascript
{ "resource": "" }
q24244
memoize
train
function memoize(func, resolver) { if (!isFunction(func)) { throw new TypeError; } var memoized = function() { var cache = memoized.cache, key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); } memoized.cache = {}; return memoized; }
javascript
{ "resource": "" }
q24245
boolMatch
train
function boolMatch(s, matchers) { var i, matcher, down = s.toLowerCase(); matchers = [].concat(matchers); for (i = 0; i < matchers.length; i += 1) { matcher = matchers[i]; if (!matcher) continue; if (matcher.test && matcher.test(s)) return true; if (matcher.toLowerCase() === down) return true; } }
javascript
{ "resource": "" }
q24246
compareArrays
train
function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; }
javascript
{ "resource": "" }
q24247
getLangDefinition
train
function getLangDefinition(key) { var i = 0, j, lang, next, split, get = function (k) { if (!languages[k] && hasModule) { try { require('./lang/' + k); } catch (e) { } } return languages[k]; }; if (!key) { return moment.fn._lang; } if (!isArray(key)) { //short-circuit everything else lang = get(key); if (lang) { return lang; } key = [key]; } //pick the language from the array //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root while (i < key.length) { split = normalizeLanguage(key[i]).split('-'); j = split.length; next = normalizeLanguage(key[i + 1]); next = next ? next.split('-') : null; while (j > 0) { lang = get(split.slice(0, j).join('-')); if (lang) { return lang; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return moment.fn._lang; }
javascript
{ "resource": "" }
q24248
makeGetterAndSetter
train
function makeGetterAndSetter(name, key) { moment.fn[name] = moment.fn[name + 's'] = function (input) { var utc = this._isUTC ? 'UTC' : ''; if (input != null) { this._d['set' + utc + key](input); moment.updateOffset(this); return this; } else { return this._d['get' + utc + key](); } }; }
javascript
{ "resource": "" }
q24249
unformatNumeral
train
function unformatNumeral (n, string) { var stringOriginal = string, thousandRegExp, millionRegExp, billionRegExp, trillionRegExp, suffixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], bytesMultiplier = false, power; if (string.indexOf(':') > -1) { n._value = unformatTime(string); } else { if (string === zeroFormat) { n._value = 0; } else { if (languages[currentLanguage].delimiters.decimal !== '.') { string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.'); } // see if abbreviations are there so that we can multiply to the correct number thousandRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); millionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); billionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); trillionRegExp = new RegExp('[^a-zA-Z]' + languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); // see if bytes are there so that we can multiply to the correct number for (power = 0; power <= suffixes.length; power++) { bytesMultiplier = (string.indexOf(suffixes[power]) > -1) ? Math.pow(1024, power + 1) : false; if (bytesMultiplier) { break; } } // do some math to create our number n._value = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * (((string.split('-').length + Math.min(string.split('(').length-1, string.split(')').length-1)) % 2)? 1: -1) * Number(string.replace(/[^0-9\.]+/g, '')); // round if we are talking about bytes n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value; } } return n._value; }
javascript
{ "resource": "" }
q24250
multiplier
train
function multiplier(x) { var parts = x.toString().split('.'); if (parts.length < 2) { return 1; } return Math.pow(10, parts[1].length); }
javascript
{ "resource": "" }
q24251
correctionFactor
train
function correctionFactor() { var args = Array.prototype.slice.call(arguments); return args.reduce(function (prev, next) { var mp = multiplier(prev), mn = multiplier(next); return mp > mn ? mp : mn; }, -Infinity); }
javascript
{ "resource": "" }
q24252
dot
train
function dot(arr, arg) { if (!isArray(arr[0])) arr = [ arr ]; if (!isArray(arg[0])) arg = [ arg ]; // convert column to row vector var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr, right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg, res = [], row = 0, nrow = left.length, ncol = left[0].length, sum, col; for (; row < nrow; row++) { res[row] = []; sum = 0; for (col = 0; col < ncol; col++) sum += left[row][col] * right[row][col]; res[row] = sum; } return (res.length === 1) ? res[0] : res; }
javascript
{ "resource": "" }
q24253
pow
train
function pow(arr, arg) { return jStat.map(arr, function(value) { return Math.pow(value, arg); }); }
javascript
{ "resource": "" }
q24254
aug
train
function aug(a, b) { var newarr = a.slice(), i = 0; for (; i < newarr.length; i++) { push.apply(newarr[i], b[i]); } return newarr; }
javascript
{ "resource": "" }
q24255
det
train
function det(a) { var alen = a.length, alend = alen * 2, vals = new Array(alend), rowshift = alen - 1, colshift = alend - 1, mrow = rowshift - alen + 1, mcol = colshift, i = 0, result = 0, j; // check for special 2x2 case if (alen === 2) { return a[0][0] * a[1][1] - a[0][1] * a[1][0]; } for (; i < alend; i++) { vals[i] = 1; } for (i = 0; i < alen; i++) { for (j = 0; j < alen; j++) { vals[(mrow < 0) ? mrow + alen : mrow ] *= a[i][j]; vals[(mcol < alen) ? mcol + alen : mcol ] *= a[i][j]; mrow++; mcol--; } mrow = --rowshift - alen + 1; mcol = --colshift; } for (i = 0; i < alen; i++) { result += vals[i]; } for (; i < alend; i++) { result -= vals[i]; } return result; }
javascript
{ "resource": "" }
q24256
train
function () { if (this.done) { return this.EOF; } if (!this._input) { this.done = true; } var token, match, tempMatch, index; if (!this._more) { this.yytext = ''; this.match = ''; } var rules = this._currentRules(); for (var i = 0; i < rules.length; i++) { tempMatch = this._input.match(this.rules[rules[i]]); if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { match = tempMatch; index = i; if (this.options.backtrack_lexer) { token = this.test_match(tempMatch, rules[i]); if (token !== false) { return token; } else if (this._backtrack) { match = false; continue; // rule action called reject() implying a rule MISmatch. } else { // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) return false; } } else if (!this.options.flex) { break; } } } if (match) { token = this.test_match(match, rules[index]); if (token !== false) { return token; } // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) return false; } if (this._input === "") { return this.EOF; } else { return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno }); } }
javascript
{ "resource": "" }
q24257
train
function (type) { var error = Exception.errors.filter(function (item) { return item.type === type || item.output === type; })[0]; return error ? error.output : null; }
javascript
{ "resource": "" }
q24258
train
function (id) { var filtered = instance.matrix.data.filter(function (cell) { if (cell.deps) { return cell.deps.indexOf(id) > -1; } }); var deps = []; filtered.forEach(function (cell) { if (deps.indexOf(cell.id) === -1) { deps.push(cell.id); } }); return deps; }
javascript
{ "resource": "" }
q24259
train
function (id) { var deps = getDependencies(id); if (deps.length) { deps.forEach(function (refId) { if (allDependencies.indexOf(refId) === -1) { allDependencies.push(refId); var item = instance.matrix.getItem(refId); if (item.deps.length) { getTotalDependencies(refId); } } }); } }
javascript
{ "resource": "" }
q24260
train
function (element) { var allDependencies = instance.matrix.getElementDependencies(element), id = element.getAttribute('id'); allDependencies.forEach(function (refId) { var item = instance.matrix.getItem(refId); if (item && item.formula) { var refElement = document.getElementById(refId); calculateElementFormula(item.formula, refElement); } }); }
javascript
{ "resource": "" }
q24261
train
function (formula, element) { // to avoid double translate formulas, update item data in parser var parsed = parse(formula, element), value = parsed.result, error = parsed.error, nodeName = element.nodeName.toUpperCase(); instance.matrix.updateElementItem(element, {value: value, error: error}); if (['INPUT'].indexOf(nodeName) === -1) { element.innerText = value || error; } element.value = value || error; return parsed; }
javascript
{ "resource": "" }
q24262
train
function (element) { var id = element.getAttribute('id'), formula = element.getAttribute('data-formula'); if (formula) { // add item with basic properties to data array instance.matrix.addItem({ id: id, formula: formula }); calculateElementFormula(formula, element); } }
javascript
{ "resource": "" }
q24263
train
function (element) { var id = element.getAttribute('id'); // on db click show formula element.addEventListener('dblclick', function () { var item = instance.matrix.getItem(id); if (item && item.formula) { item.formulaEdit = true; element.value = '=' + item.formula; } }); element.addEventListener('blur', function () { var item = instance.matrix.getItem(id); if (item) { if (item.formulaEdit) { element.value = item.value || item.error; } item.formulaEdit = false; } }); // if pressed ESC restore original value element.addEventListener('keyup', function (event) { switch (event.keyCode) { case 13: // ENTER case 27: // ESC // leave cell listen(); break; } }); // re-calculate formula if ref cells value changed element.addEventListener('change', function () { // reset and remove item instance.matrix.removeItem(id); // check if inserted text could be the formula var value = element.value; if (value[0] === '=') { element.setAttribute('data-formula', value.substr(1)); registerElementInMatrix(element); } // get ref cells and re-calculate formulas recalculateElementDependencies(element); }); }
javascript
{ "resource": "" }
q24264
train
function (cell) { var num = cell.match(/\d+$/), alpha = cell.replace(num, ''); return { alpha: alpha, num: parseInt(num[0], 10) } }
javascript
{ "resource": "" }
q24265
train
function (cell, counter) { var alphaNum = instance.utils.getCellAlphaNum(cell), alpha = alphaNum.alpha, col = alpha, row = parseInt(alphaNum.num + counter, 10); if (row < 1) { row = 1; } return col + '' + row; }
javascript
{ "resource": "" }
q24266
train
function (cell, counter) { var alphaNum = instance.utils.getCellAlphaNum(cell), alpha = alphaNum.alpha, col = instance.utils.toChar(parseInt(instance.utils.toNum(alpha) + counter, 10)), row = alphaNum.num; if (!col || col.length === 0) { col = 'A'; } var fixedCol = alpha[0] === '$' || false, fixedRow = alpha[alpha.length - 1] === '$' || false; col = (fixedCol ? '$' : '') + col; row = (fixedRow ? '$' : '') + row; return col + '' + row; }
javascript
{ "resource": "" }
q24267
train
function (formula, direction, delta) { var type, counter; // left, right -> col if (['left', 'right'].indexOf(direction) !== -1) { type = 'col'; } else if (['up', 'down'].indexOf(direction) !== -1) { type = 'row' } // down, up -> row if (['down', 'right'].indexOf(direction) !== -1) { counter = delta * 1; } else if(['up', 'left'].indexOf(direction) !== -1) { counter = delta * (-1); } if (type && counter) { return formula.replace(/(\$?[A-Za-z]+\$?[0-9]+)/g, function (match) { var alpha = instance.utils.getCellAlphaNum(match).alpha; var fixedCol = alpha[0] === '$' || false, fixedRow = alpha[alpha.length - 1] === '$' || false; if (type === 'row' && fixedRow) { return match; } if (type === 'col' && fixedCol) { return match; } return (type === 'row' ? instance.utils.changeRowIndex(match, counter) : instance.utils.changeColIndex(match, counter)); }); } return formula; }
javascript
{ "resource": "" }
q24268
train
function (cell) { var num = cell.match(/\d+$/), alpha = cell.replace(num, ''); return { row: parseInt(num[0], 10) - 1, col: instance.utils.toNum(alpha) }; }
javascript
{ "resource": "" }
q24269
train
function (startCell, endCell, callback) { var result = { index: [], // list of cell index: A1, A2, A3 value: [] // list of cell value }; var cols = { start: 0, end: 0 }; if (endCell.col >= startCell.col) { cols = { start: startCell.col, end: endCell.col }; } else { cols = { start: endCell.col, end: startCell.col }; } var rows = { start: 0, end: 0 }; if (endCell.row >= startCell.row) { rows = { start: startCell.row, end: endCell.row }; } else { rows = { start: endCell.row, end: startCell.row }; } for (var column = cols.start; column <= cols.end; column++) { for (var row = rows.start; row <= rows.end; row++) { var cellIndex = instance.utils.toChar(column) + (row + 1), cellValue = instance.helper.cellValue.call(this, cellIndex); result.index.push(cellIndex); result.value.push(cellValue); } } if (instance.utils.isFunction(callback)) { return callback.apply(callback, [result]); } else { return result; } }
javascript
{ "resource": "" }
q24270
train
function (type, exp1, exp2) { var result; switch (type) { case '&': result = exp1.toString() + exp2.toString(); break; } return result; }
javascript
{ "resource": "" }
q24271
train
function (type, exp1, exp2) { var result; switch (type) { case '=': result = (exp1 === exp2); break; case '>': result = (exp1 > exp2); break; case '<': result = (exp1 < exp2); break; case '>=': result = (exp1 >= exp2); break; case '<=': result = (exp1 === exp2); break; case '<>': result = (exp1 != exp2); break; case 'NOT': result = (exp1 != exp2); break; } return result; }
javascript
{ "resource": "" }
q24272
train
function (type, number1, number2) { var result; number1 = helper.number(number1); number2 = helper.number(number2); if (isNaN(number1) || isNaN(number2)) { if (number1[0] === '=' || number2[0] === '=') { throw Error('NEED_UPDATE'); } throw Error('VALUE'); } switch (type) { case '+': result = number1 + number2; break; case '-': result = number1 - number2; break; case '/': result = number1 / number2; if (result == Infinity) { throw Error('DIV_ZERO'); } else if (isNaN(result)) { throw Error('VALUE'); } break; case '*': result = number1 * number2; break; case '^': result = Math.pow(number1, number2); break; } return result; }
javascript
{ "resource": "" }
q24273
train
function (fn, args) { fn = fn.toUpperCase(); args = args || []; if (instance.helper.SUPPORTED_FORMULAS.indexOf(fn) > -1) { if (instance.formulas[fn]) { return instance.formulas[fn].apply(this, args); } } throw Error('NAME'); }
javascript
{ "resource": "" }
q24274
train
function (args) { args = args || []; var str = args[0]; if (str) { str = str.toUpperCase(); if (instance.formulas[str]) { return ((typeof instance.formulas[str] === 'function') ? instance.formulas[str].apply(this, args) : instance.formulas[str]); } } throw Error('NAME'); }
javascript
{ "resource": "" }
q24275
train
function (cell) { var value, fnCellValue = instance.custom.cellValue, element = this, item = instance.matrix.getItem(cell); // check if custom cellValue fn exists if (instance.utils.isFunction(fnCellValue)) { var cellCoords = instance.utils.cellCoords(cell), cellId = instance.utils.translateCellCoords({row: element.row, col: element.col}); // get value value = item ? item.value : fnCellValue(cellCoords.row, cellCoords.col); if (instance.utils.isNull(value)) { value = 0; } if (cellId) { //update dependencies instance.matrix.updateItem(cellId, {deps: [cell]}); } } else { // get value value = item ? item.value : document.getElementById(cell).value; //update dependencies instance.matrix.updateElementItem(element, {deps: [cell]}); } // check references error if (item && item.deps) { if (item.deps.indexOf(cellId) !== -1) { throw Error('REF'); } } // check if any error occurs if (item && item.error) { throw Error(item.error); } // return value if is set if (instance.utils.isSet(value)) { var result = instance.helper.number(value); return !isNaN(result) ? result : value; } // cell is not available throw Error('NOT_AVAILABLE'); }
javascript
{ "resource": "" }
q24276
train
function (start, end) { var fnCellValue = instance.custom.cellValue, coordsStart = instance.utils.cellCoords(start), coordsEnd = instance.utils.cellCoords(end), element = this; // iterate cells to get values and indexes var cells = instance.utils.iterateCells.call(this, coordsStart, coordsEnd), result = []; // check if custom cellValue fn exists if (instance.utils.isFunction(fnCellValue)) { var cellId = instance.utils.translateCellCoords({row: element.row, col: element.col}); //update dependencies instance.matrix.updateItem(cellId, {deps: cells.index}); } else { //update dependencies instance.matrix.updateElementItem(element, {deps: cells.index}); } result.push(cells.value); return result; }
javascript
{ "resource": "" }
q24277
train
function (id) { id = id.replace(/\$/g, ''); return instance.helper.cellValue.call(this, id); }
javascript
{ "resource": "" }
q24278
train
function (start, end) { start = start.replace(/\$/g, ''); end = end.replace(/\$/g, ''); return instance.helper.cellRangeValue.call(this, start, end); }
javascript
{ "resource": "" }
q24279
train
function (formula, element) { var result = null, error = null; try { parser.setObj(element); result = parser.parse(formula); var id; if (element instanceof HTMLElement) { id = element.getAttribute('id'); } else if (element && element.id) { id = element.id; } var deps = instance.matrix.getDependencies(id); if (deps.indexOf(id) !== -1) { result = null; deps.forEach(function (id) { instance.matrix.updateItem(id, {value: null, error: Exception.get('REF')}); }); throw Error('REF'); } } catch (ex) { var message = Exception.get(ex.message); if (message) { error = message; } else { error = Exception.get('ERROR'); } //console.debug(ex.prop); //debugger; //error = ex.message; //error = Exception.get('ERROR'); } return { error: error, result: result } }
javascript
{ "resource": "" }
q24280
train
function () { instance = this; parser = new FormulaParser(instance); instance.formulas = Formula; instance.matrix = new Matrix(); instance.custom = {}; if (rootElement) { instance.matrix.scan(); } }
javascript
{ "resource": "" }
q24281
train
function (connection, mechanisms) { this.connection = connection; this.transport = new Transport(connection.amqp_transport.identifier, SASL_PROTOCOL_ID, frames.TYPE_SASL, this); this.next = connection.amqp_transport; this.mechanisms = mechanisms; this.mechanism = undefined; this.outcome = undefined; this.username = undefined; var mechlist = Object.getOwnPropertyNames(mechanisms); this.transport.encode(frames.sasl_frame(frames.sasl_mechanisms({sasl_server_mechanisms:mechlist}))); }
javascript
{ "resource": "" }
q24282
train
function(){ if (this.options.placeholder) return this.options.placeholder; if (this.options.language){ var firstLanguage = this.options.language.split(",")[0]; var language = subtag.language(firstLanguage); var localizedValue = localization.placeholder[language]; if (localizedValue) return localizedValue; } return 'Search'; }
javascript
{ "resource": "" }
q24283
train
function(language){ var browserLocale = navigator.language || navigator.userLanguage || navigator.browserLanguage; this.options.language = language || this.options.language || browserLocale; return this; }
javascript
{ "resource": "" }
q24284
train
function(selected){ // clean up any old marker that might be present this._removeMarker(); var defaultMarkerOptions = { color: '#4668F2' } var markerOptions = extend({}, defaultMarkerOptions, this.options.marker) this.mapMarker = new this._mapboxgl.Marker(markerOptions); this.mapMarker .setLngLat(selected.center) .addTo(this._map); return this; }
javascript
{ "resource": "" }
q24285
MapboxEventManager
train
function MapboxEventManager(options) { this.origin = options.origin || 'https://api.mapbox.com'; this.endpoint = 'events/v2'; this.access_token = options.accessToken; this.version = '0.2.0' this.sessionID = this.generateSessionID(); this.userAgent = this.getUserAgent(); this.options = options; this.send = this.send.bind(this); // parse global options to be sent with each request this.countries = (options.countries) ? options.countries.split(",") : null; this.types = (options.types) ? options.types.split(",") : null; this.bbox = (options.bbox) ? options.bbox : null; this.language = (options.language) ? options.language.split(",") : null; this.limit = (options.limit) ? +options.limit : null; this.locale = navigator.language || null; this.enableEventLogging = this.shouldEnableLogging(options); this.eventQueue = new Array(); this.flushInterval = options.flushInterval || 1000; this.maxQueueSize = options.maxQueueSize || 100; this.timer = (this.flushInterval) ? setTimeout(this.flush.bind(this), this.flushInterval) : null; // keep some state to deduplicate requests if necessary this.lastSentInput = ""; this.lastSentIndex = 0; }
javascript
{ "resource": "" }
q24286
train
function(selected, geocoder){ var resultIndex = this.getSelectedIndex(selected, geocoder); var payload = this.getEventPayload('search.select', geocoder); payload.resultIndex = resultIndex; payload.resultPlaceName = selected.place_name; payload.resultId = selected.id; if ((resultIndex === this.lastSentIndex && payload.queryString === this.lastSentInput) || resultIndex == -1) { // don't log duplicate events if the user re-selected the same feature on the same search return; } this.lastSentIndex = resultIndex; this.lastSentInput = payload.queryString; if (!payload.queryString) return; // will be rejected return this.push(payload) }
javascript
{ "resource": "" }
q24287
train
function (payload, callback) { if (!this.enableEventLogging) { if (callback) return callback(); return; } var options = this.getRequestOptions(payload); this.request(options, function(err){ if (err) return this.handleError(err, callback); if (callback) { return callback(); } }.bind(this)) }
javascript
{ "resource": "" }
q24288
train
function(payload){ if (!Array.isArray(payload)) payload = [payload]; var options = { // events must be sent with POST method: "POST", host: this.origin, path: this.endpoint + "?access_token=" + this.access_token, headers: { 'Content-Type': 'application/json' }, body:JSON.stringify(payload) //events are arrays } return options }
javascript
{ "resource": "" }
q24289
train
function (event, geocoder) { var proximity; if (!geocoder.options.proximity) proximity = null; else proximity = [geocoder.options.proximity.longitude, geocoder.options.proximity.latitude]; var zoom = (geocoder._map) ? geocoder._map.getZoom() : null; var payload = { event: event, created: +new Date(), sessionIdentifier: this.sessionID, country: this.countries, userAgent: this.userAgent, language: this.language, bbox: this.bbox, types: this.types, endpoint: 'mapbox.places', // fuzzyMatch: search.fuzzy, //todo --> add to plugin proximity: proximity, limit: geocoder.options.limit, // routing: search.routing, //todo --> add to plugin mapZoom: zoom, keyboardLocale: this.locale } // get the text in the search bar if (event === "search.select"){ payload.queryString = geocoder.inputString; }else if (event != "search.select" && geocoder._inputEl){ payload.queryString = geocoder._inputEl.value; }else{ payload.queryString = geocoder.inputString; } return payload; }
javascript
{ "resource": "" }
q24290
train
function (opts, callback) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 ) { if (this.status == 204){ //success return callback(null); }else { return callback(this.statusText); } } }; xhttp.open(opts.method, opts.host + '/' + opts.path, true); for (var header in opts.headers){ var headerValue = opts.headers[header]; xhttp.setRequestHeader(header, headerValue) } xhttp.send(opts.body); }
javascript
{ "resource": "" }
q24291
train
function(selected, geocoder){ if (!geocoder._typeahead) return; var results = geocoder._typeahead.data; var selectedID = selected.id; var resultIDs = results.map(function (feature) { return feature.id; }); var selectedIdx = resultIDs.indexOf(selectedID); return selectedIdx; }
javascript
{ "resource": "" }
q24292
train
function(options){ if (options.enableEventLogging === false) return false; if (options.origin && options.origin.indexOf('api.mapbox.com') == -1) return false; // hard to make sense of events when a local instance is suplementing results from origin if (options.localGeocoder) return false; // hard to make sense of events when a custom filter is in use if (options.filter) return false; return true; }
javascript
{ "resource": "" }
q24293
train
function(){ if (this.eventQueue.length > 0){ this.send(this.eventQueue); this.eventQueue = new Array(); } // //reset the timer if (this.timer) clearTimeout(this.timer); if (this.flushInterval) this.timer = setTimeout(this.flush.bind(this), this.flushInterval) }
javascript
{ "resource": "" }
q24294
train
function(evt, forceFlush){ this.eventQueue.push(evt); if (this.eventQueue.length >= this.maxQueueSize || forceFlush){ this.flush(); } }
javascript
{ "resource": "" }
q24295
buildConsoleLogger
train
function buildConsoleLogger (level = 'info') { return function (api) { return winston.createLogger({ format: winston.format.combine( winston.format.timestamp(), winston.format.colorize(), winston.format.printf(info => { return `${api.id} @ ${info.timestamp} - ${info.level}: ${info.message} ${stringifyExtraMessagePropertiesForConsole(info)}` }) ), level, levels: winston.config.syslog.levels, transports: [ new winston.transports.Console() ] }) } }
javascript
{ "resource": "" }
q24296
getListeners
train
function getListeners(element) { var id = idHandler.get(element); if (id === undefined) { return []; } return eventListeners[id] || []; }
javascript
{ "resource": "" }
q24297
addListener
train
function addListener(element, listener) { var id = idHandler.get(element); if(!eventListeners[id]) { eventListeners[id] = []; } eventListeners[id].push(listener); }
javascript
{ "resource": "" }
q24298
getId
train
function getId(element) { var state = getState(element); if (state && state.id !== undefined) { return state.id; } return null; }
javascript
{ "resource": "" }
q24299
setId
train
function setId(element) { var state = getState(element); if (!state) { throw new Error("setId required the element to have a resize detection state."); } var id = idGenerator.generate(); state.id = id; return id; }
javascript
{ "resource": "" }