_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q49100
removeIgnoredLevels
train
function removeIgnoredLevels(response, options) { try { const filteredLevels = getLevelsToAudit(options); if (filteredLevels && filteredLevels.indexOf(auditLevel.low) >= 0) { return response; } const filteredResponse = JSON.parse(JSON.stringify(response, null, 2)); const ignoredVulnerabilities = []; const advisories = filteredResponse.advisories || {}; for (const key in advisories) { const advisory = advisories[key]; if ( advisory && advisory.severity && advisory.id && filteredLevels.indexOf(advisory.severity) < 0 ) { ignoredVulnerabilities.push(advisory.id); } } ignoredVulnerabilities.forEach((ignoredVulnerabilityId) => { delete filteredResponse.advisories[`${ignoredVulnerabilityId}`]; }); const severities = {}; for (const key in advisories) { const advisory = advisories[key]; if (advisory && advisory.severity && advisory.id) { severities[`${advisory.id}`] = advisory.severity; } } /* prettier-ignore */ filteredResponse.actions = filteredResponse.actions ? filteredResponse.actions .map((action) => { action.resolves = action.resolves.filter( (resolve) => ignoredVulnerabilities.indexOf(resolve.id) < 0 ); return action; }) .filter((action) => action.resolves.length > 0) : []; const vulnerabilitiesMetadata = { info: 0, low: 0, moderate: 0, high: 0, critical: 0, }; filteredResponse.actions.forEach((action) => { action.resolves.forEach((resolve) => { if (resolve && resolve.id) { vulnerabilitiesMetadata[severities[`${resolve.id}`]] += 1; } }); }); filteredResponse.metadata.vulnerabilities = vulnerabilitiesMetadata; return filteredResponse; } catch (error) { if (response) { response.internalErrors = response.internalErrors || []; response.internalErrors.push(error); return response; } return response; } }
javascript
{ "resource": "" }
q49101
addSensitiveDataInfosIn
train
function addSensitiveDataInfosIn(response) { const allSensitiveDataPatterns = getSensitiveData(process.cwd()); const augmentedResponse = JSON.parse(JSON.stringify(response, null, 2)); const files = augmentedResponse.files || []; files.forEach((file) => { if (file && isSensitiveData(file.path, allSensitiveDataPatterns)) { file.isSensitiveData = true; return; } if (file) { file.isSensitiveData = false; } }); return augmentedResponse; }
javascript
{ "resource": "" }
q49102
isSensitiveData
train
function isSensitiveData(filepath, allSensitiveDataPatterns) { if ( filepath && allSensitiveDataPatterns && allSensitiveDataPatterns.ignoredData && globMatching.any(filepath, allSensitiveDataPatterns.ignoredData, { matchBase: true, nocase: true, }) ) { return false; } if ( filepath && allSensitiveDataPatterns && allSensitiveDataPatterns.sensitiveData && globMatching.any(filepath, allSensitiveDataPatterns.sensitiveData, { matchBase: true, nocase: true, }) ) { return true; } return false; }
javascript
{ "resource": "" }
q49103
updateSensitiveDataInfosOfIgnoredFilesIn
train
function updateSensitiveDataInfosOfIgnoredFilesIn(response, options) { const ignoredData = getIgnoredSensitiveData(options); const updatedResponse = JSON.parse(JSON.stringify(response, null, 2)); const files = updatedResponse.files || []; files.forEach((file) => { if ( file && file.isSensitiveData && isIgnoredData(file.path, ignoredData) ) { file.isSensitiveData = false; return; } }); return updatedResponse; }
javascript
{ "resource": "" }
q49104
getIgnoredSensitiveData
train
function getIgnoredSensitiveData(options) { try { const sensitiveDataIgnoreFile = pathJoin( options.directoryToPackage, '.publishrc' ); const publishPleaseConfiguration = JSON.parse( readFile(sensitiveDataIgnoreFile).toString() ); const result = publishPleaseConfiguration && publishPleaseConfiguration.validations && publishPleaseConfiguration.validations.sensitiveData && Array.isArray( publishPleaseConfiguration.validations.sensitiveData.ignore ) ? publishPleaseConfiguration.validations.sensitiveData.ignore : []; return result; } catch (error) { return []; } }
javascript
{ "resource": "" }
q49105
removePackageTarFileFrom
train
function removePackageTarFileFrom(projectDir, response) { try { const file = pathJoin(projectDir, response.filename); unlink(file); return response; } catch (error) { if (error.code === 'ENOENT') { return response; } if (response) { response.internalErrors = response.internalErrors || []; response.internalErrors.push(error); return response; } return response; } }
javascript
{ "resource": "" }
q49106
getCustomSensitiveData
train
function getCustomSensitiveData(projectDir) { const sensitiveDataFile = pathJoin(projectDir, '.sensitivedata'); const content = readFile(sensitiveDataFile).toString(); const allPatterns = content .split(/\n|\r/) .map((line) => line.replace(/[\t]/g, ' ')) .map((line) => line.trim()) .filter((line) => line && line.length > 0) .filter((line) => !line.startsWith('#')); const sensitiveData = allPatterns.filter( (pattern) => !pattern.startsWith('!') ); const ignoredData = allPatterns .filter((pattern) => pattern.startsWith('!')) .map((pattern) => pattern.replace('!', '')) .map((pattern) => pattern.trim()); return { sensitiveData, ignoredData, }; }
javascript
{ "resource": "" }
q49107
createNodeServer
train
function createNodeServer(http, nodePort, webSocketPort, watchFiles, tsWarning, tsError, target) { return http.createServer(async (req, res) => { try { const fileExtension = req.url.slice(req.url.lastIndexOf('.') + 1); switch (fileExtension) { case '/': { const indexFileContents = (await fs.readFile(`./index.html`)).toString(); const modifiedIndexFileContents = modifyHTML(indexFileContents, 'index.html', watchFiles, webSocketPort); watchFile(`./index.html`, watchFiles); res.end(modifiedIndexFileContents); return; } case 'js': { await handleScriptExtension(req, res, fileExtension); return; } case 'mjs': { await handleScriptExtension(req, res, fileExtension); return; } case 'ts': { await handleScriptExtension(req, res, fileExtension); return; } case 'tsx': { await handleScriptExtension(req, res, fileExtension); return; } case 'jsx': { await handleScriptExtension(req, res, fileExtension); return; } case 'wast': { await handleWASTExtension(req, res, fileExtension); return; } case 'wasm': { await handleWASMExtension(req, res, fileExtension); return; } default: { await handleGenericFile(req, res, fileExtension); return; } } } catch(error) { console.log(error); } }); }
javascript
{ "resource": "" }
q49108
styleToFilters
train
function styleToFilters(style) { var layers = {}; // Store layers and filters used in style if (style && style.layers) { for (var i = 0; i < style.layers.length; i++) { var layerName = style.layers[i]['source-layer']; if (layerName) { // if the layer already exists in our filters, update it if (layers[layerName]) { // Update zoom levels var styleMin = style.layers[i].minzoom || 0; var styleMax = style.layers[i].maxzoom || 22; if (styleMin < layers[layerName].minzoom) layers[layerName].minzoom = styleMin; if (styleMax > layers[layerName].maxzoom) layers[layerName].maxzoom = styleMax; // Modify filter if (layers[layerName].filters === true || !style.layers[i].filter) { layers[layerName].filters = true; } else { layers[layerName].filters.push(style.layers[i].filter); } } else { // otherwise create the layer & filter array, with min/max zoom layers[layerName] = {}; layers[layerName].filters = style.layers[i].filter ? ['any', style.layers[i].filter] : true; layers[layerName].minzoom = style.layers[i].minzoom || 0; layers[layerName].maxzoom = style.layers[i].maxzoom || 22; } // Collect the used properties // 1. from paint, layout, and filter layers[layerName].properties = layers[layerName].properties || []; ['paint', 'layout'].forEach(item => { let itemObject = style.layers[i][item]; itemObject && getPropertyFromLayoutAndPainter(itemObject, layers[layerName].properties); }); // 2. from filter if (style.layers[i].filter) { getPropertyFromFilter(style.layers[i].filter, layers[layerName].properties); } } } } // remove duplicate propertys and fix choose all the propertys in layers[i].properties Object.keys(layers).forEach(layerId => { let properties = layers[layerId].properties; if (properties.indexOf(true) !== -1) { layers[layerId].properties = true; } else { let unique = {}; properties.forEach(function(i) { if (!unique[i]) { unique[i] = true; } }); layers[layerId].properties = Object.keys(unique); } }); return layers; }
javascript
{ "resource": "" }
q49109
createMessage
train
function createMessage(type, transaction) { const msg = new StunMessage(); msg.setType(type); msg.setTransactionID(transaction || createTransaction()); return msg; }
javascript
{ "resource": "" }
q49110
createDgramServer
train
function createDgramServer(options = {}) { let isExternalSocket = false; if (options.socket instanceof dgram.Socket) { isExternalSocket = true; } const socket = isExternalSocket ? options.socket : dgram.createSocket('udp4'); const server = new StunServer(socket); if (!isExternalSocket) { socket.on('error', error => server.emit('error', error)); server.once('close', () => socket.close()); } return server; }
javascript
{ "resource": "" }
q49111
normalize
train
function normalize(gj) { if (!gj || !gj.type) return null; var type = types[gj.type]; if (!type) return null; if (type === 'geometry') { return { type: 'FeatureCollection', features: [{ type: 'Feature', properties: {}, geometry: gj }] }; } else if (type === 'feature') { return { type: 'FeatureCollection', features: [gj] }; } else if (type === 'featurecollection') { return gj; } }
javascript
{ "resource": "" }
q49112
establishServerSession
train
function establishServerSession(req, path, newPage, reset, newControllerId, sessions, controllers, nonObjTemplatelogLevel) { let applicationConfig = AmorphicContext.applicationConfig; // Retrieve configuration information let config = applicationConfig[path]; if (!config) { throw new Error('Semotus: establishServerSession called with a path of ' + path + ' which was not registered'); } let initObjectTemplate = config.initObjectTemplate; let controllerPath = config.appPath + '/' + (config.appConfig.controller || 'controller.js'); let objectCacheExpiration = config.objectCacheExpiration; let sessionExpiration = config.sessionExpiration; let sessionStore = config.sessionStore; let appVersion = config.appVersion; let session = req.session; let sessionData = getSessionCache(path, req.session.id, false, sessions); if (newPage === 'initial') { sessionData.sequence = 1; // For a new page determine if a controller is to be omitted if (config.appConfig.createControllerFor && !session.semotus) { let referer = ''; if (req.headers['referer']) { referer = url.parse(req.headers['referer'], true).path; } let createControllerFor = config.appConfig.createControllerFor; if (!referer.match(createControllerFor) && createControllerFor !== 'yes') { return establishInitialServerSession(req, controllerPath, initObjectTemplate, path, appVersion, sessionExpiration); } } } return establishContinuedServerSession(req, controllerPath, initObjectTemplate, path, appVersion, sessionExpiration, session, sessionStore, newControllerId, objectCacheExpiration, newPage, controllers, nonObjTemplatelogLevel, sessions, reset); }
javascript
{ "resource": "" }
q49113
processPost
train
function processPost(req, res, sessions, controllers, nonObjTemplatelogLevel) { let session = req.session; let path = url.parse(req.originalUrl, true).query.path; establishServerSession(req, path, false, false, null, sessions, controllers, nonObjTemplatelogLevel) .then(function ff(semotus) { let ourObjectTemplate = semotus.objectTemplate; let remoteSessionId = req.session.id; if (typeof(ourObjectTemplate.controller.processPost) === 'function') { Bluebird.resolve(ourObjectTemplate.controller.processPost(null, req.body)) .then(function gg(controllerResp) { ourObjectTemplate.setSession(remoteSessionId); semotus.save(path, session, req); res.writeHead(controllerResp.status, controllerResp.headers || {'Content-Type': 'text/plain'}); res.end(controllerResp.body); }) .catch(function hh(e) { ourObjectTemplate.logger.info({ component: 'amorphic', module: 'processPost', activity: 'error' }, 'Error ' + e.message + e.stack); res.writeHead(500, {'Content-Type': 'text/plain'}); res.end('Internal Error'); }); } else { throw 'Not Accepting Posts'; } }) .catch(function ii(error) { logMessage('Error establishing session for processPost ', req.session.id, error.message + error.stack); res.writeHead(500, {'Content-Type': 'text/plain'}); res.end('Internal Error'); }); }
javascript
{ "resource": "" }
q49114
train
function () { if (this.state == 'zombie') { this.expireController(); // Toss anything that might have happened RemoteObjectTemplate.enableSendMessage(true, this.sendMessage); // Re-enable sending this.state = 'live'; this.rootId = null; // Cancel forcing our controller on server this.refreshSession(); console.log('Getting live again - fetching state from server'); } this.setCookie('session' + this.app, this.session, 0); }
javascript
{ "resource": "" }
q49115
train
function () { if (RemoteObjectTemplate.getPendingCallCount() == 0 && this.getCookie('session' + this.app) != this.session) { if (this.state != 'zombie') { this.state = 'zombie'; this.expireController(); RemoteObjectTemplate.enableSendMessage(false); // Queue stuff as a zombie we will toss it later console.log('Another browser took over, entering zombie state'); } } }
javascript
{ "resource": "" }
q49116
train
function () { var self = this; self.activity = false; if (self.heartBeat) { clearTimeout(self.heartBeat); } self.heartBeat = setTimeout(function () { if (self.state == 'live') { if (self.activity) { console.log('Server session ready to expire, activity detected, keeping alive'); self.pingSession(); // Will setup new timer } else if (self.controller.clientExpire && this.controller.clientExpire()) { // See if expiration handled by controller console.log('Server session ready to expire, controller resetting itself to be offline'); return; // No new timer } else { console.log('Server session ready to expire, resetting controller to be offline'); self.expireController(); } } }, self.sessionExpiration - self.sessionExpirationCushion); }
javascript
{ "resource": "" }
q49117
setUpInjectObjectTemplate
train
function setUpInjectObjectTemplate(appName, config, schema) { let amorphicOptions = AmorphicContext.amorphicOptions || {}; let dbConfig = buildDbConfig(appName, config); let connectToDbIfNeedBe = Bluebird.resolve(false); // Default to no need. if (dbConfig.dbName && dbConfig.dbPath) { if (dbConfig.dbDriver === 'mongo') { let MongoClient = require('mongodb-bluebird'); connectToDbIfNeedBe = MongoClient.connect(dbConfig.dbPath + dbConfig.dbName); } else if (dbConfig.dbDriver === 'knex') { let knex = require('knex')({ client: dbConfig.dbType, debug: dbConfig.knexDebug, connection: { host: dbConfig.dbPath, database: dbConfig.dbName, user: dbConfig.dbUser, password: dbConfig.dbPassword, port: dbConfig.dbPort, application_name: appName }, pool: { min: 0, max: dbConfig.dbConnections }, acquireConnectionTimeout: dbConfig.dbConnectionTimeout }); connectToDbIfNeedBe = Bluebird.resolve(knex); // require('knex') is a synchronous call that already connects } } return connectToDbIfNeedBe .then(returnBoundInjectTemplate.bind(this, amorphicOptions, config, dbConfig, schema)); }
javascript
{ "resource": "" }
q49118
buildDbConfig
train
function buildDbConfig(appName, config) { var dbDriver = fetchFromConfig(appName, config, 'dbDriver') || 'mongo'; var defaultPort = dbDriver === 'mongo' ? 27017 : 5432; return { dbName: fetchFromConfig(appName, config, 'dbName'), dbPath: fetchFromConfig(appName, config, 'dbPath'), dbDriver: dbDriver, dbType: fetchFromConfig(appName, config, 'dbType') || 'mongo', dbUser: fetchFromConfig(appName, config, 'dbUser') || 'nodejs', dbPassword: fetchFromConfig(appName, config, 'dbPassword') || null, dbConnections: parseInt(fetchFromConfig(appName, config, 'dbConnections')) || 20, dbConcurrency: parseInt(fetchFromConfig(appName, config, 'dbConcurrency')) || 5, dbConnectionTimeout: parseInt(fetchFromConfig(appName, config, 'dbConnectionTimeout')) || 60000, dbPort: fetchFromConfig(appName, config, 'dbPort') || defaultPort, knexDebug: fetchFromConfig(appName, config, 'knexDebug') || false }; }
javascript
{ "resource": "" }
q49119
fetchFromConfig
train
function fetchFromConfig(appName, config, toFetch) { let lowerCase = toFetch.toLowerCase(); return config.nconf.get(appName + '_' + toFetch) || config.nconf.get(toFetch) || config.nconf.get(lowerCase); }
javascript
{ "resource": "" }
q49120
returnBoundInjectTemplate
train
function returnBoundInjectTemplate(amorphicOptions, config, dbConfig, schema, db) { // Return the bound version so we always keep the config and dbConfig. return injectObjectTemplate.bind(null, amorphicOptions, config, dbConfig, db, schema); }
javascript
{ "resource": "" }
q49121
loadAppConfigToContext
train
function loadAppConfigToContext(appName, config, path, commonPath, initObjectTemplateFunc, sessionStore) { let amorphicOptions = AmorphicContext.amorphicOptions; AmorphicContext.applicationConfig[appName] = { appPath: path, commonPath: commonPath, initObjectTemplate: initObjectTemplateFunc, sessionExpiration: amorphicOptions.sessionExpiration, objectCacheExpiration: amorphicOptions.objectCacheExpiration, sessionStore: sessionStore, appVersion: config.ver, appConfig: config, logLevel: fetchFromConfig(appName, config, 'logLevel') || 'info' }; }
javascript
{ "resource": "" }
q49122
loadTemplates
train
function loadTemplates(appName) { let appConfig = AmorphicContext.applicationConfig[appName] || {}; let applicationSource = AmorphicContext.applicationSource; let applicationSourceMap = AmorphicContext.applicationSourceMap; let controllerPath = (appConfig.appConfig.controller || 'controller.js'); let matches = controllerPath.match(/(.*?)([0-9A-Za-z_]*)\.js$/); let prop = matches[2]; let baseTemplate = buildBaseTemplate(appConfig); applicationSource[appName] = ''; applicationSourceMap[appName] = ''; // Inject into it any db or persist attributes needed for application if (appConfig.initObjectTemplate && typeof appConfig.initObjectTemplate === 'function') { appConfig.initObjectTemplate(baseTemplate); } return [ baseTemplate, getTemplates(baseTemplate, appConfig.appPath, [prop + '.js'], appConfig, appName) ]; }
javascript
{ "resource": "" }
q49123
checkTypes
train
function checkTypes(classes) { var classCount = 0, nullType = 0, nullOf = 0, propCount = 0; for (var classKey in classes) { ++classCount; for (var definePropertyKey in classes[classKey].amorphicProperties) { var defineProperty = classes[classKey].amorphicProperties[definePropertyKey]; if (!defineProperty.type) { ++nullType; console.log('Warning: ' + classKey + '.' + definePropertyKey + ' has no type'); } if (defineProperty instanceof Array && !defineProperty.of) { console.log('Warning: ' + classKey + '.' + definePropertyKey + ' has no of'); ++nullOf } ++propCount; } } console.log(classCount + ' classes loaded with ' + propCount + ' properties (' + nullType + ' null types, ' + nullOf + ' null ofs)'); }
javascript
{ "resource": "" }
q49124
establishContinuedServerSession
train
function establishContinuedServerSession(req, controllerPath, initObjectTemplate, path, appVersion, sessionExpiration, session, sessionStore, newControllerId, objectCacheExpiration, newPage, controllers, nonObjTemplatelogLevel, sessions, reset) { let applicationConfig = AmorphicContext.applicationConfig; let applicationPersistorProps = AmorphicContext.applicationPersistorProps; let config = applicationConfig[path]; newControllerId = newControllerId || null; // Create or restore the controller let shouldReset = false; let newSession = false; let controller; let ret; if (!session.semotus || !session.semotus.controllers[path] || reset || newControllerId) { shouldReset = true; // TODO what is newSession, why do this? newSession = !newControllerId; if (!session.semotus) { session.semotus = getDefaultSemotus(); } if (!session.semotus.loggingContext[path]) { session.semotus.loggingContext[path] = getLoggingContext(path, null); } } controller = getController(path, controllerPath, initObjectTemplate, session, objectCacheExpiration, sessionStore, newPage, shouldReset, newControllerId, req, controllers, nonObjTemplatelogLevel, sessions); let sessionData = getSessionCache(path, req.session.id, true, sessions); let ourObjectTemplate = getObjectTemplate(controller); ourObjectTemplate.memSession = sessionData; ourObjectTemplate.reqSession = req.session; controller.__request = req; controller.__sessionExpiration = sessionExpiration; req.amorphicTracking.addServerTask({name: 'Create Controller'}, process.hrtime()); ret = { appVersion: appVersion, newSession: newSession, objectTemplate: ourObjectTemplate, getMessage: function gotMessage() { let message = this.objectTemplate.getMessage(session.id, true); // TODO Why is newSession always true here? message.newSession = true; message.rootId = controller.__id__; message.startingSequence = this.objectTemplate.maxClientSequence + 100000; message.sessionExpiration = sessionExpiration; message.ver = this.appVersion; return message; }, getServerConnectString: function yelo() { return JSON.stringify({ url: '/amorphic/xhr?path=' + path, message: this.getMessage() }); }, getServerConfigString: function yolo() { return getServerConfigString(config); }, save: function surve(path, session, req) { saveSession(path, session, controller, req, sessions); }, restoreSession: function rastaSess() { return restoreSession(path, session, controller, sessions); }, getPersistorProps: function getPersistorProps() { return applicationPersistorProps[path] || (this.getPersistorProps ? this.getPersistorProps() : {}); } }; if (newPage) { saveSession(path, session, controller, req, sessions); } return Bluebird.try(function g() { return ret; }); }
javascript
{ "resource": "" }
q49125
Remoteable
train
function Remoteable (Base) { return (function n(_super) { __extends(classOne, _super); function classOne() { return _super !== null && _super.apply(this, arguments) || this; } return classOne; }(Base)); }
javascript
{ "resource": "" }
q49126
bindDecorators
train
function bindDecorators (objectTemplate) { // TODO: In what situation would objectTemplate be null and why is it acceptable just to use this as a replacement? objectTemplate = objectTemplate || this; this.Amorphic = objectTemplate; this.amorphicStatic = objectTemplate; /** * Purpose unknown * * @param {unknown} target unknown * @param {unknown} props unknown * * @returns {unknown} unknown. */ this.supertypeClass = function supertypeClass(target, props) { if (objectTemplate.supertypeClass) { return objectTemplate.supertypeClass(target, props, objectTemplate); } else { return SupertypeDefinition.supertypeClass(target, props, objectTemplate); } }; /** * Purpose unknown * * @returns {unknown} unknown. */ this.Supertype = function Supertype() { if (objectTemplate.Supertype) { return objectTemplate.Supertype.call(this, objectTemplate); } else { return SupertypeDefinition.Supertype.call(this, objectTemplate); } }; this.Supertype.prototype = SupertypeDefinition.Supertype.prototype; /** * Purpose unknown * * @param {unknown} props unknown * * @returns {unknown} unknown. */ this.property = function property(props) { if (objectTemplate.property) { return objectTemplate.property(props, objectTemplate); } else { return SupertypeDefinition.property(props, objectTemplate); } }; /** * Purpose unknown * * @param {unknown} defineProperty unknown * * @returns {unknown} unknown. */ this.remote = function remote(defineProperty) { if (objectTemplate.remote) { return objectTemplate.remote(defineProperty, objectTemplate); } else { return SupertypeDefinition.remote(defineProperty, objectTemplate); } }; /** * Purpose unknown * * @returns {unknown} unknown. */ this.Amorphic.create = function create() { objectTemplate.connect = unitTestConfig.startup; return objectTemplate; }; this.Amorphic.getInstance = function getInstance() { return objectTemplate; }; }
javascript
{ "resource": "" }
q49127
teamOutAction
train
function teamOutAction() { sessionStore.get(sessionId, function aa(_error, expressSession) { if (!expressSession) { log(1, sessionId, 'Session has expired', nonObjTemplatelogLevel); } if (!expressSession || cachedController.controller.__template__.objectTemplate.getPendingCallCount() === 0) { controllers[sessionId + path] = null; log(1, sessionId, 'Expiring controller cache for ' + path, nonObjTemplatelogLevel); } else { cachedController.timeout = setTimeout(timeoutAction, objectCacheExpiration); log(2, sessionId, 'Extending controller cache timeout because of pending calls for ' + path, - nonObjTemplatelogLevel); } }); }
javascript
{ "resource": "" }
q49128
readFile
train
function readFile(file) { if (file && fs.existsSync(file)) { return fs.readFileSync(file); } return null; }
javascript
{ "resource": "" }
q49129
setupLogger
train
function setupLogger(logger, path, context, applicationConfig) { logger.startContext(context); logger.setLevel(applicationConfig[path].logLevel); if (AmorphicContext.appContext.sendToLog) { logger.sendToLog = AmorphicContext.appContext.sendToLog; } }
javascript
{ "resource": "" }
q49130
getSessionCache
train
function getSessionCache(path, sessionId, keepTimeout, sessions) { let key = path + '-' + sessionId; let session = sessions[key] || {sequence: 1, serializationTimeStamp: null, timeout: null, semotus: {}}; sessions[key] = session; if (!keepTimeout) { if (session.timeout) { clearTimeout(session.timeout); } session.timeout = setTimeout(function jj() { if (sessions[key]) { delete sessions[key]; } }, AmorphicContext.amorphicOptions.sessionExpiration); } return session; }
javascript
{ "resource": "" }
q49131
train
function(isVisible) { var self = this, $textEl = self.$el.find(self.options.toggleTextSelector); if (isVisible) { $textEl.text(self.$el.data('expanded-text')); } else { $textEl.text(self.$el.data('collapsed-text')); } $textEl.attr('aria-expanded', isVisible); self.$el.toggleClass(self.options.isCollapsedClass, !isVisible); }
javascript
{ "resource": "" }
q49132
train
function(name, path) { return function(requiredPaths, moduleFunction) { var requiredModules = [], pathCount = requiredPaths.length, requiredModule, module, i; for (i = 0; i < pathCount; i += 1) { requiredModule = registeredModules[requiredPaths[i]]; requiredModules.push(requiredModule); } module = moduleFunction.apply(GlobalLoader, requiredModules); registeredModules[path] = module; edx[name] = module; }; }
javascript
{ "resource": "" }
q49133
train
function(page) { var oldPage = this.state.currentPage, self = this, deferred = $.Deferred(); this.getPage(page - (1 - this.state.firstPage), {reset: true}).then( function() { self.isStale = false; self.trigger('page_changed'); deferred.resolve(); }, function() { self.state.currentPage = oldPage; deferred.fail(); } ); return deferred.promise(); }
javascript
{ "resource": "" }
q49134
train
function() { var deferred = $.Deferred(); if (this.isStale) { this.setPage(1) .done(function() { deferred.resolve(); }); } else { deferred.resolve(); } return deferred.promise(); }
javascript
{ "resource": "" }
q49135
train
function(fields, fieldName, displayName) { var newField = {}; newField[fieldName] = { displayName: displayName }; _.extend(fields, newField); }
javascript
{ "resource": "" }
q49136
train
function(fieldName, toggleDirection) { var direction = toggleDirection ? 0 - this.state.order : this.state.order; if (fieldName !== this.state.sortKey || toggleDirection) { this.setSorting(fieldName, direction); this.isStale = true; } }
javascript
{ "resource": "" }
q49137
train
function(fieldName) { return _.has(this.filterableFields, fieldName) && !_.isUndefined(this.filterableFields[fieldName].displayName); }
javascript
{ "resource": "" }
q49138
train
function(fieldName) { return _.has(this.filterableFields, fieldName) && !_.isNull(this.filterableFields[fieldName].value); }
javascript
{ "resource": "" }
q49139
train
function(filterFieldName) { var val = this.getActiveFilterFields(true)[filterFieldName]; return (_.isNull(val) || _.isUndefined(val)) ? null : val; }
javascript
{ "resource": "" }
q49140
train
function(fieldName, value) { var queryStringValue; if (!this.hasRegisteredFilterField(fieldName)) { this.registerFilterableField(fieldName, ''); } this.filterableFields[fieldName].value = value; if (_.isArray(value)) { queryStringValue = value.join(','); } else { queryStringValue = value; } this.queryParams[fieldName] = function() { return queryStringValue || null; }; this.isStale = true; }
javascript
{ "resource": "" }
q49141
writeOptimizedImages
train
function writeOptimizedImages(imageData) { return Promise.all( imageData.map(item => pify(fs.writeFile)(item.path, item.data).then(() => item.path) ) ); }
javascript
{ "resource": "" }
q49142
createSizeSuffix
train
function createSizeSuffix(width, height) { let result = String(width); if (height !== undefined) result += `x${String(height)}`; return result; }
javascript
{ "resource": "" }
q49143
getCropper
train
function getCropper(name) { // See http://sharp.dimens.io/en/stable/api-resize/#crop // // Possible attributes of sharp.gravity are north, northeast, east, southeast, south, // southwest, west, northwest, center and centre. if (sharp.gravity[name] !== undefined) { return sharp.gravity[name]; } // The experimental strategy-based approach resizes so one dimension is at its target // length then repeatedly ranks edge regions, discarding the edge with the lowest // score based on the selected strategy. // - entropy: focus on the region with the highest Shannon entropy. // - attention: focus on the region with the highest luminance frequency, // colour saturation and presence of skin tones. if (sharp.strategy[name] !== undefined) { return sharp.strategy[name]; } throw new UsageError( `"${name}" is not a valid crop value. Consult http://sharp.dimens.io/en/stable/api-resize/#crop` ); }
javascript
{ "resource": "" }
q49144
generateSizes
train
function generateSizes(entry, inputDirectory, outputDirectory) { const imageFileName = path.join(inputDirectory, entry.basename); return pify(fs.readFile)(imageFileName).then(imageBuffer => { const sharpFile = sharp(imageBuffer); return Promise.all( entry.sizes.map(size => { const sizeSuffix = createSizeSuffix(size.width, size.height); const ext = path.extname(entry.basename); const extlessBasename = path.basename(entry.basename, ext); const outputFilename = path.join( outputDirectory, `${extlessBasename}-${sizeSuffix}${ext}` ); const transform = sharpFile.resize(size.width, size.height); if (size.crop !== undefined) { transform.crop(getCropper(size.crop)); } return transform.toFile(outputFilename).then(() => outputFilename); }) ); }); }
javascript
{ "resource": "" }
q49145
clearPriorOutput
train
function clearPriorOutput(directory, sourceImageBasename) { const ext = path.extname(sourceImageBasename); const extlessBasename = path.basename(sourceImageBasename, ext); return del(path.join(directory, `${extlessBasename}*.*`)); }
javascript
{ "resource": "" }
q49146
install
train
function install(deps, options, exec) { options = options || {}; const dev = options.dev !== false; const run = options.yarn || isUsingYarn() ? runYarn : runNpm; // options.versions is a min versions mapping, // the list of packages to install will be taken from deps let versions = options.versions || {}; if (_.isPlainObject(deps)) { // deps is an object with required versions versions = deps; deps = Object.keys(deps); } deps = _.castArray(deps); const newDeps = getUnsatisfiedDeps(deps, versions, { dev }); if (newDeps.length === 0) { return; } log.info(`Installing ${listify(newDeps)}...`); const versionedDeps = newDeps.map(dep => getVersionedDep(dep, versions)); run(versionedDeps, { dev }, exec); }
javascript
{ "resource": "" }
q49147
runNpm
train
function runNpm(deps, options, exec) { options = options || {}; exec = exec || spawnSync; const args = [ options.remove ? 'uninstall' : 'install', options.dev ? '--save-dev' : '--save', ].concat(deps); return exec('npm', args, { stdio: options.stdio === undefined ? 'inherit' : options.stdio, cwd: options.cwd, }); }
javascript
{ "resource": "" }
q49148
runYarn
train
function runYarn(deps, options, exec) { options = options || {}; exec = exec || spawnSync; const add = options.dev ? ['add', '--dev'] : ['add']; const remove = ['remove']; const args = (options.remove ? remove : add).concat(deps); return exec('yarn', args, { stdio: options.stdio === undefined ? 'inherit' : options.stdio, cwd: options.cwd, }); }
javascript
{ "resource": "" }
q49149
getUnsatisfiedDeps
train
function getUnsatisfiedDeps(deps, versions, options) { const ownDependencies = getOwnDependencies(options); return deps.filter(dep => { const required = versions[dep]; if (required && !semver.validRange(required)) { throw new MrmError( `Invalid npm version: ${required}. Use proper semver range syntax.` ); } const installed = getInstalledVersion(dep); // Package isn’t installed yet if (!installed) { return true; } // Module is installed but not in package.json dependencies if (!ownDependencies[dep]) { return true; } // No required version specified if (!required) { // Install if the pacakge isn’t installed return !installed; } // Install if installed version doesn't satisfy range return !semver.satisfies(installed, required); }); }
javascript
{ "resource": "" }
q49150
getStyleForFile
train
function getStyleForFile(filepath) { const editorconfigFile = findEditorConfig(filepath); if (editorconfigFile) { return editorconfig.parseFromFilesSync(filepath, [ { name: editorconfigFile, contents: readFile(editorconfigFile) }, ]); } return {}; }
javascript
{ "resource": "" }
q49151
format
train
function format(source, style) { if (style.insert_final_newline !== undefined) { const has = hasTrailingNewLine(source); if (style.insert_final_newline && !has) { source += '\n'; } else if (!style.insert_final_newline && has) { source = source.replace(TRAILING_NEW_LINE_REGEXP, ''); } } return source; }
javascript
{ "resource": "" }
q49152
updateFile
train
function updateFile(filename, content, exists) { fs.mkdirpSync(path.dirname(filename)); fs.writeFileSync(filename, content); log.added(`${exists ? 'Update' : 'Create'} ${filename}`); }
javascript
{ "resource": "" }
q49153
copyFiles
train
function copyFiles(sourceDir, files, options = {}) { const { overwrite = true, errorOnExist } = options; _.castArray(files).forEach(file => { const sourcePath = path.resolve(sourceDir, file); if (!fs.existsSync(sourcePath)) { throw new MrmError(`copyFiles: source file not found: ${sourcePath}`); } const targetExist = fs.existsSync(file); if (targetExist && !overwrite) { if (errorOnExist) { throw new MrmError(`copyFiles: target file already exists: ${file}`); } return; } const content = read(sourcePath); // Skip copy if file contents are the same if (content === read(file)) { return; } updateFile(file, content, targetExist); }); }
javascript
{ "resource": "" }
q49154
deleteFiles
train
function deleteFiles(files) { _.castArray(files).forEach(file => { if (!fs.existsSync(file)) { return; } log.removed(`Delete ${file}`); fs.removeSync(file); }); }
javascript
{ "resource": "" }
q49155
withRetries
train
async function withRetries(opts, fn) { const maxRetries = opts.maxRetries || 7 const verbose = opts.verbose || false let tryCount = 0 while (tryCount < maxRetries) { try { return await fn() // Do our action. } catch (e) { // Double wait time each failure let waitTime = 1000 * 2**(tryCount - 1) // Randomly jiggle wait time by 20% either way. No thundering herd. waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4)) // Max out at two minutes waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS) if (verbose) { console.log('retryable error:', e.message) console.log(`will retry in ${waitTime / 1000} seconds`) } tryCount += 1 await new Promise(resolve => setTimeout(resolve, waitTime)) } } throw new Error('number of retries exceeded') }
javascript
{ "resource": "" }
q49156
runApp
train
function runApp(config) { const app = express() const token = new Token(config) // Configure rate limiting. Allow at most 1 request per IP every 60 sec. const opts = { points: 1, // Point budget. duration: 60, // Reset points consumption every 60 sec. } const rateLimiter = new RateLimiterMemory(opts) const rateLimiterMiddleware = (req, res, next) => { // Rate limiting only applies to the /tokens route. if (req.url.startsWith('/tokens')) { rateLimiter.consume(req.connection.remoteAddress) .then(() => { // Allow request and consume 1 point. next() }) .catch((err) => { // Not enough points. Block the request. console.log(`Rejecting request due to rate limiting.`) res.status(429).send('<h2>Too Many Requests</h2>') }) } else { next() } } // Note: register rate limiting middleware *before* all routes // so that it gets executed first. app.use(rateLimiterMiddleware) // Configure directory for public assets. app.use(express.static(__dirname + '/public')) // Register the /tokens route for crediting tokens. app.get('/tokens', async function (req, res, next) { const networkId = req.query.network_id const wallet = req.query.wallet if (!req.query.wallet) { res.send('<h2>Error: A wallet address must be supplied.</h2>') } else if (!Web3.utils.isAddress(wallet)) { res.send(`<h2>Error: ${wallet} is a malformed wallet address.</h2>`) return } try { // Transfer NUM_TOKENS to specified wallet. const value = token.toNaturalUnit(NUM_TOKENS) const contractAddress = token.contractAddress(networkId) const receipt = await token.credit(networkId, wallet, value) const txHash = receipt.transactionHash console.log(`${NUM_TOKENS} OGN -> ${wallet} TxHash=${txHash}`) // Send response back to client. const resp = `Credited ${NUM_TOKENS} OGN tokens to wallet ${wallet}<br>` + `TxHash = ${txHash}<br>` + `OGN token contract address = ${contractAddress}` res.send(resp) } catch (err) { next(err) // Errors will be passed to Express. } }) // Start the server. app.listen( config.port || DEFAULT_SERVER_PORT, () => console.log(`Origin faucet app listening on port ${config.port}!`)) }
javascript
{ "resource": "" }
q49157
liveTracking
train
async function liveTracking(config) { setupOriginJS(config) const context = await new Context(config).init() let lastLogBlock = getLastBlock(config) let lastCheckedBlock = 0 const checkIntervalSeconds = 5 let start const check = async () => { await withRetrys(async () => { start = new Date() const currentBlockNumber = await web3.eth.getBlockNumber() if (currentBlockNumber == lastCheckedBlock) { console.log('No new block.') return scheduleNextCheck() } console.log('New block: ' + currentBlockNumber) const toBlock = Math.min(lastLogBlock+MAX_BATCH_BLOCKS, currentBlockNumber) const opts = { fromBlock: lastLogBlock + 1, toBlock: toBlock } await runBatch(opts, context) lastLogBlock = toBlock setLastBlock(config, toBlock) lastCheckedBlock = currentBlockNumber return scheduleNextCheck() }) } const scheduleNextCheck = async () => { const elapsed = new Date() - start const delay = Math.max(checkIntervalSeconds * 1000 - elapsed, 1) setTimeout(check, delay) } check() }
javascript
{ "resource": "" }
q49158
runBatch
train
async function runBatch(opts, context) { const fromBlock = opts.fromBlock const toBlock = opts.toBlock let lastLogBlock = undefined console.log( 'Looking for logs from block ' + fromBlock + ' to ' + (toBlock || 'Latest') ) const eventTopics = Object.keys(context.signatureToRules) const logs = await web3.eth.getPastLogs({ fromBlock: web3.utils.toHex(fromBlock), // Hex required for infura toBlock: toBlock ? web3.utils.toHex(toBlock) : "latest", // Hex required for infura topics: [eventTopics] }) if (logs.length > 0) { console.log('' + logs.length + ' logs found') } for (const log of logs) { const contractVersion = context.addressToVersion[log.address] if (contractVersion == undefined) { continue // Skip - Not a trusted contract } const contractName = contractVersion.contractName const rule = context.signatureToRules[log.topics[0]][contractName] if (rule == undefined) { continue // Skip - No handler defined } lastLogBlock = log.blockNumber // Process it await handleLog(log, rule, contractVersion, context) } return lastLogBlock }
javascript
{ "resource": "" }
q49159
withRetrys
train
async function withRetrys(fn) { let tryCount = 0 while (true) { try { return await fn() // Do our action. } catch (e) { // Roughly double wait time each failure let waitTime = Math.pow(100, 1 + tryCount / 6) // Randomly jiggle wait time by 20% either way. No thundering herd. waitTime = Math.floor(waitTime * (1.2 - Math.random() * 0.4)) // Max out at two minutes waitTime = Math.min(waitTime, MAX_RETRY_WAIT_MS) console.log('ERROR', e) console.log(`will retry in ${waitTime / 1000} seconds`) tryCount += 1 await new Promise(resolve => setTimeout(resolve, waitTime)) } if (tryCount >= MAX_RETRYS) { console.log('Exiting. Maximum number of retrys reached.') // Now it's up to our environment to restart us. // Hopefully with a clean start, things will work better process.exit(1) } } }
javascript
{ "resource": "" }
q49160
handleLog
train
async function handleLog(log, rule, contractVersion, context) { log.decoded = web3.eth.abi.decodeLog( rule.eventAbi.inputs, log.data, log.topics.slice(1) ) log.contractName = contractVersion.contractName log.eventName = rule.eventName log.contractVersionKey = contractVersion.versionKey log.networkId = context.networkId console.log( `Processing log \ blockNumber=${log.blockNumber} \ transactionIndex=${log.transactionIndex} \ eventName=${log.eventName} \ contractName=${log.contractName}` ) // Note: we run the rule with a retry since we've seen in production cases where we fail loading // from smart contracts the data pointed to by the event. This may occur due to load balancing // across ethereum nodes and if some nodes are lagging. For example the ethereum node we // end up connecting to for reading the data may lag compared to the node received the event from. let ruleResults = undefined await withRetrys(async () => { ruleResults = await rule.ruleFn(log) }) const output = { log: log, related: ruleResults } const json = JSON.stringify(output, null, 2) if (context.config.verbose) { console.log(json) console.log('\n----\n') } const userAddress = log.decoded.party const ipfsHash = log.decoded.ipfsHash //TODO: remove binary data from pictures in a proper way. const listing = output.related.listing delete listing.ipfs.data.pictures const listingId = listing.id // Data consistency: check listingId from the JSON stored in IPFS // matches with listingID emitted in the event. // TODO: use method utils/id.js:parseListingId // DVF: this should really be handled in origin js - origin.js should throw // an error if this happens. const ipfsListingId = listingId.split('-')[2] if (ipfsListingId !== log.decoded.listingID) { throw `ListingId mismatch: ${ipfsListingId} !== ${log.decoded.listingID}` } // TODO: This kind of verification logic should live in origin.js if(output.related.listing.ipfs.data.price === undefined){ return } if (context.config.elasticsearch) { console.log('INDEXING ', listingId) await withRetrys(async () => { await search.Listing.index( listingId, userAddress, ipfsHash, listing ) }) if (output.related.offer !== undefined) { const offer = output.related.offer await withRetrys(async () => { await search.Offer.index(offer, listing) }) } if (output.related.seller !== undefined) { await withRetrys(async () => { await search.User.index(output.related.seller) }) } if (output.related.buyer !== undefined) { await withRetrys(async () => { await search.User.index(output.related.buyer) }) } } if (context.config.db) { await withRetrys(async () => { await db.Listing.insert( listingId, userAddress, ipfsHash, listing.ipfs.data ) }) } if (context.config.webhook) { console.log('\n-- WEBHOOK to ' + context.config.webhook + ' --\n') await withRetrys(async () => { await postToWebhook(context.config.webhook, json) }) } }
javascript
{ "resource": "" }
q49161
relatedUserResolver
train
function relatedUserResolver(walletAddress, info){ const requestedFields = info.fieldNodes[0].selectionSet.selections const isIdOnly = requestedFields.filter(x => x.name.value !== 'walletAddress') .length === 0 if (isIdOnly) { return { walletAddress: walletAddress } } else { return search.User.get(walletAddress) } }
javascript
{ "resource": "" }
q49162
Mapper
train
function Mapper(mapper, flusher) { Transform.call(this, { objectMode: true, // Patch from 0.11.7 // https://github.com/joyent/node/commit/ba72570eae938957d10494be28eac28ed75d256f highWaterMark: 16 }) this.mapper = mapper this.flusher = flusher }
javascript
{ "resource": "" }
q49163
assert_length
train
function assert_length(buf, name, length) { if(buf.length !== length) throw new Error('expected '+name+' to have length' + length + ', but was:'+buf.length) }
javascript
{ "resource": "" }
q49164
Source
train
function Source(id, callback) { var uri = url.parse(id); if (!uri || (uri.protocol && uri.protocol !== 'overlaydata:')) { return callback('Only the overlaydata protocol is supported'); } var data = id.replace('overlaydata://', ''); var retina = false; var legacy = false; if (data.indexOf('2x:') === 0) { retina = true; data = data.replace(/^2x:/, ''); } if (data.indexOf('legacy:') === 0) { legacy = true; data = data.replace(/^legacy:/, ''); } var parsed; try { parsed = JSON.parse(data); } catch(e) { return callback('invalid geojson'); } mapnikify(parsed, retina, function(err, xml) { if (err) return callback(err); this._xml = xml; this._size = retina && !legacy ? 512 : 256; this._bufferSize = retina ? 128 : 64; callback(null, this); }.bind(this)); }
javascript
{ "resource": "" }
q49165
numberWithCommas
train
function numberWithCommas(n) { const parts = n.toString().split('.'); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ','); return parts.join('.'); }
javascript
{ "resource": "" }
q49166
timeout
train
function timeout (time, options) { var opts = options || {} var delay = typeof time === 'string' ? ms(time) : Number(time || 5000) var respond = opts.respond === undefined || opts.respond === true return function (req, res, next) { var id = setTimeout(function () { req.timedout = true req.emit('timeout', delay) }, delay) if (respond) { req.on('timeout', onTimeout(delay, next)) } req.clearTimeout = function () { clearTimeout(id) } req.timedout = false onFinished(res, function () { clearTimeout(id) }) onHeaders(res, function () { clearTimeout(id) }) next() } }
javascript
{ "resource": "" }
q49167
_initialiseFromFields
train
function _initialiseFromFields(userFields) { if (util.isDefined(userFields.MType)) { var MTypeNo; if (util.isNumber(userFields.MType)) { MTypeNo = userFields.MType; } else if (util.isString(userFields.MType)) { var mhdr_idx = constants.MTYPE_DESCRIPTIONS.indexOf(userFields.MType); if (mhdr_idx >= 0) { MTypeNo = mhdr_idx; } else { throw new Error("MType is unknown"); } } else { throw new Error("MType is required in a suitable format"); } if(MTypeNo == constants.MTYPE_JOIN_REQUEST) { _initialiseJoinRequestPacketFromFields(userFields); } else if(MTypeNo == constants.MTYPE_JOIN_ACCEPT) { _initialiseJoinAcceptPacketFromFields(userFields); } else { _initialiseDataPacketFromFields(userFields); } } else { if (_isPlausibleDataPacket(userFields) === true) { _initialiseDataPacketFromFields(userFields); } else if (_isPlausibleJoinRequestPacket(userFields) === true) { _initialiseJoinRequestPacketFromFields(userFields); } else if (_isPlausibleJoinAcceptPacket(userFields) === true) { _initialiseJoinAcceptPacketFromFields(userFields); } else { throw new Error("No plausible packet"); } } }
javascript
{ "resource": "" }
q49168
ClientSSLSecurity
train
function ClientSSLSecurity(key, cert, ca, defaults) { if (key) { if(Buffer.isBuffer(key)) { this.key = key; } else if (typeof key === 'string') { this.key = fs.readFileSync(key); } else { throw new Error('key should be a buffer or a string!'); } } if (cert) { if(Buffer.isBuffer(cert)) { this.cert = cert; } else if (typeof cert === 'string') { this.cert = fs.readFileSync(cert); } else { throw new Error('cert should be a buffer or a string!'); } } if (ca) { if(Buffer.isBuffer(ca) || Array.isArray(ca)) { this.ca = ca; } else if (typeof ca === 'string') { this.ca = fs.readFileSync(ca); } else { defaults = ca; this.ca = null; } } this.defaults = {}; _.merge(this.defaults, defaults); this.agent = null; }
javascript
{ "resource": "" }
q49169
ClientSSLSecurityPFX
train
function ClientSSLSecurityPFX(pfx, passphrase, defaults) { if (typeof passphrase === 'object') { defaults = passphrase; } if (pfx) { if (Buffer.isBuffer(pfx)) { this.pfx = pfx; } else if (typeof pfx === 'string') { this.pfx = fs.readFileSync(pfx); } else { throw new Error('supplied pfx file should be a buffer or a file location'); } } if (passphrase) { if (typeof passphrase === 'string') { this.passphrase = passphrase; } } this.defaults = {}; _.merge(this.defaults, defaults); }
javascript
{ "resource": "" }
q49170
svg
train
function svg(name, attrs, children) { var elem = document.createElementNS(SVG_NS, name); for(var attrName in attrs) { elem.setAttribute(attrName, attrs[attrName]); } if(children) { children.forEach(function(c) { elem.appendChild(c); }); } return elem; }
javascript
{ "resource": "" }
q49171
getDialCoords
train
function getDialCoords(radius, startAngle, endAngle) { var cx = GaugeDefaults.centerX, cy = GaugeDefaults.centerY; return { end: getCartesian(cx, cy, radius, endAngle), start: getCartesian(cx, cy, radius, startAngle) }; }
javascript
{ "resource": "" }
q49172
multibase
train
function multibase (nameOrCode, buf) { if (!buf) { throw new Error('requires an encoded buffer') } const base = getBase(nameOrCode) const codeBuf = Buffer.from(base.code) const name = base.name validEncode(name, buf) return Buffer.concat([codeBuf, buf]) }
javascript
{ "resource": "" }
q49173
encode
train
function encode (nameOrCode, buf) { const base = getBase(nameOrCode) const name = base.name return multibase(name, Buffer.from(base.encode(buf))) }
javascript
{ "resource": "" }
q49174
decode
train
function decode (bufOrString) { if (Buffer.isBuffer(bufOrString)) { bufOrString = bufOrString.toString() } const code = bufOrString.substring(0, 1) bufOrString = bufOrString.substring(1, bufOrString.length) if (typeof bufOrString === 'string') { bufOrString = Buffer.from(bufOrString) } const base = getBase(code) return Buffer.from(base.decode(bufOrString.toString())) }
javascript
{ "resource": "" }
q49175
isEncoded
train
function isEncoded (bufOrString) { if (Buffer.isBuffer(bufOrString)) { bufOrString = bufOrString.toString() } // Ensure bufOrString is a string if (Object.prototype.toString.call(bufOrString) !== '[object String]') { return false } const code = bufOrString.substring(0, 1) try { const base = getBase(code) return base.name } catch (err) { return false } }
javascript
{ "resource": "" }
q49176
queryParamsState
train
function queryParamsState(queryParamsArray, controller) { return queryParamsArray.reduce( (state, qp) => { let value = qp.value(controller); state[qp.key] = { value, serializedValue: qp.serializedValue(controller), as: qp.as, defaultValue: qp.defaultValue, changed: JSON.stringify(value) !== JSON.stringify(qp.defaultValue) }; return state; }, {}, undefined ); }
javascript
{ "resource": "" }
q49177
Account
train
function Account (client, opts) { var self = this if (!(self instanceof Account)) return new Account(client, opts) if (!opts) opts = {} self.client = client }
javascript
{ "resource": "" }
q49178
SKBlob
train
function SKBlob (data) { var self = this if (!(self instanceof SKBlob)) return new SKBlob(data) if (!(data instanceof Buffer)) { data = new Buffer(data) } self._data = data self._type = fileType(data) self._isImage = BufferUtils.isImage(data) self._isMPEG4 = BufferUtils.isMPEG4(data) self._isVideo = self._isMPEG4 self._isMedia = BufferUtils.isMedia(data) // TODO self._overlay = null }
javascript
{ "resource": "" }
q49179
Friends
train
function Friends (client, opts) { var self = this if (!(self instanceof Friends)) return new Friends(client, opts) if (!opts) opts = {} self.client = client }
javascript
{ "resource": "" }
q49180
Snaps
train
function Snaps (client, opts) { var self = this if (!(self instanceof Snaps)) return new Snaps(client, opts) if (!opts) opts = {} self.client = client }
javascript
{ "resource": "" }
q49181
Stories
train
function Stories (client, opts) { var self = this if (!(self instanceof Stories)) return new Stories(client, opts) if (!opts) opts = {} self.client = client }
javascript
{ "resource": "" }
q49182
SKLocation
train
function SKLocation (params) { var self = this if (!(self instanceof SKLocation)) return new SKLocation(params) self.weather = params['weather'] self.ourStoryAuths = params['our_story_auths'] self.preCacheGeofilters = params['pre_cache_geofilters'] self.filters = params['filters'].map(function (filter) { return new Filter(filter) }) }
javascript
{ "resource": "" }
q49183
Request
train
function Request (opts) { var self = this if (!(self instanceof Request)) return new Request(opts) if (!opts) opts = {} self.HTTPMethod = opts.method self.HTTPHeaders = {} self.opts = opts if (opts.method === 'POST') { if (opts.endpoint) { self._initPOST(opts) } else if (opts.url) { self._initPOSTURL(opts) } else { throw new Error('invalid request') } } else if (opts.method === 'GET') { self._initGET(opts) } else { throw new Error('invalid request') } }
javascript
{ "resource": "" }
q49184
train
function(q) { // Prepare var promises = [], loading = 0, values = []; // Create a new promise to handle all requests return pinkyswear(function(pinky) { // Basic request method var method_index = -1, createMethod = function(method) { return function(url, data, options, before) { var index = ++method_index; ++loading; promises.push(qwest(method, pinky.base + url, data, options, before).then(function(xhr, response) { values[index] = arguments; if(!--loading) { pinky(true, values.length == 1 ? values[0] : [values]); } }, function() { pinky(false, arguments); })); return pinky; }; }; // Define external API pinky.get = createMethod('GET'); pinky.post = createMethod('POST'); pinky.put = createMethod('PUT'); pinky['delete'] = createMethod('DELETE'); pinky['catch'] = function(f) { return pinky.then(null, f); }; pinky.complete = function(f) { var func = function() { f(); // otherwise arguments will be passed to the callback }; return pinky.then(func, func); }; pinky.map = function(type, url, data, options, before) { return createMethod(type.toUpperCase()).call(this, url, data, options, before); }; // Populate methods from external object for(var prop in q) { if(!(prop in pinky)) { pinky[prop] = q[prop]; } } // Set last methods pinky.send = function() { for(var i=0, j=promises.length; i<j; ++i) { promises[i].send(); } return pinky; }; pinky.abort = function() { for(var i=0, j=promises.length; i<j; ++i) { promises[i].abort(); } return pinky; }; return pinky; }); }
javascript
{ "resource": "" }
q49185
train
function(method) { return function(url, data, options, before) { var index = ++method_index; ++loading; promises.push(qwest(method, pinky.base + url, data, options, before).then(function(xhr, response) { values[index] = arguments; if(!--loading) { pinky(true, values.length == 1 ? values[0] : [values]); } }, function() { pinky(false, arguments); })); return pinky; }; }
javascript
{ "resource": "" }
q49186
getTemplates
train
function getTemplates(config) { var templates = {}; Object.keys(templatePaths).forEach(function(key) { if (config.templates && (config.templates[key] && config.templates[key] !== true)) { templates[key] = config.templates[key]; } else { templates[key] = fs.readFileSync(__dirname + templatePaths[key], "utf-8"); } }); return templates; }
javascript
{ "resource": "" }
q49187
transformData
train
function transformData(data, config, done) { data.baseSize = config.baseSize; data.svgPath = config.svgPath.replace("%f", config.svg.sprite); data.pngPath = config.pngPath.replace("%f", config.svg.sprite.replace(/\.svg$/, ".png")); data.svg = data.svg.map(function(item) { item.relHeight = item.height / config.baseSize; item.relWidth = item.width / config.baseSize; item.relPositionX = item.positionX / config.baseSize - config.padding / config.baseSize; item.relPositionY = item.positionY / config.baseSize - config.padding / config.baseSize; item.normal = true; if (item.name.match(/~/g)) { if (config.mode !== "sprite") { return false; } else { var segs = item.name.split("~"); item.name = item.selector[0].expression + ":" + segs[1]; item.normal = false; } } else { item.name = item.selector[0].expression; } return item; }); data.svg = data.svg.filter(function(item) { return item; }); data.relWidth = data.swidth / config.baseSize; data.relHeight = data.sheight / config.baseSize; if (config.asyncTransforms) { return done(data); } return data; }
javascript
{ "resource": "" }
q49188
run
train
function run() { var bin = path.resolve(__dirname, '../node_modules/.bin/mocha'); var args = Array.prototype.slice.call(arguments); var fn = args.pop(); var cmd = [bin].concat(args).join(' ') + ' --no-colors'; exec(cmd, fn); }
javascript
{ "resource": "" }
q49189
assertSubstrings
train
function assertSubstrings(str, substrings) { substrings.forEach(function(substring) { assert(str.indexOf(substring) !== -1, str + ' - string does not contain: ' + substring); }); }
javascript
{ "resource": "" }
q49190
patchHooks
train
function patchHooks(hooks) { var original = {}; var restore; hookTypes.map(function(key) { original[key] = global[key]; global[key] = function(title, fn) { // Hooks accept an optional title, though they're // ignored here for simplicity if (!fn) fn = title; hooks[key] = createWrapper(fn); }; }); restore = function() { hookTypes.forEach(function(key) { global[key] = original[key]; }); }; return restore; }
javascript
{ "resource": "" }
q49191
createWrapper
train
function createWrapper(fn, ctx) { return function() { return new Promise(function(resolve, reject) { var start = Date.now(); var cb = function(err) { if (err) return reject(err); resolve(Date.now() - start); }; // Wrap generator functions if (fn && fn.constructor.name === 'GeneratorFunction') { fn = Promise.coroutine(fn); } var res = fn.call(ctx || this, cb); // Synchronous spec, or using promises rather than callbacks if (!fn.length || (res && res.then)) { Promise.resolve(res).then(function() { resolve(Date.now() - start); }, reject); } }); }; }
javascript
{ "resource": "" }
q49192
patchUncaught
train
function patchUncaught() { var name = 'uncaughtException'; var originalListener = process.listeners(name).pop(); if (originalListener) { process.removeListener(name, originalListener); } return function() { if (!originalListener) return; process.on(name, originalListener); }; }
javascript
{ "resource": "" }
q49193
_done
train
function _done (cb, message) { var valid = false if (typeof message === 'string') { message = [message] } else if (Object.prototype.toString.call(message) === '[object Array]') { if (message.length === 0) { valid = true } } else { valid = true } if (isFunction(cb)) { if (valid) { cb(valid, []) } else { cb(valid, message) } } return valid }
javascript
{ "resource": "" }
q49194
_customDefinitions
train
function _customDefinitions (type, object) { var errors if (isFunction(definitions[type])) { try { errors = definitions[type](object) } catch (e) { errors = ['Problem with custom definition for '+type+': '+e] } if (typeof result === 'string') { errors = [errors] } if (Object.prototype.toString.call(errors) === '[object Array]') { return errors } } return [] }
javascript
{ "resource": "" }
q49195
explode
train
function explode (field) { switch (field.type) { case 'structure': field.fields = field.fields.map(explode) break case 'alternation': field.select = explode(field.select) field.choose.forEach(function (option) { option.read.field = explode(option.read.field) option.write.field = explode(option.write.field) }) break case 'lengthEncoded': field.length = explode(field.length) field.element = explode(field.element) break case 'integer': var little = field.endianness === 'l' if (field.bits == null && field.fields != null) { field.bits = field.fields.reduce(function (sum, value) { return sum + value.bits }, 0) } var bytes = field.bits / 8 field = { name: field.name || null, length: field.length || null, endianness: field.endianness, type: 'integer', little: little, bite: little ? 0 : bytes - 1, direction: little ? 1 : -1, stop: little ? bytes : -1, bits: field.bits, bytes: bytes, fields: packing(field.fields) } break } return field }
javascript
{ "resource": "" }
q49196
validStyles
train
function validStyles(styleAttr) { var result = ''; var styleArray = styleAttr.split(';'); angular.forEach(styleArray, function (value) { var v = value.split(':'); if (v.length === 2) { var key = trim(v[0].toLowerCase()); value = trim(v[1].toLowerCase()); if ( (key === 'color' || key === 'background-color') && ( value.match(/^rgb\([0-9%,\. ]*\)$/i) || value.match(/^rgba\([0-9%,\. ]*\)$/i) || value.match(/^hsl\([0-9%,\. ]*\)$/i) || value.match(/^hsla\([0-9%,\. ]*\)$/i) || value.match(/^#[0-9a-f]{3,6}$/i) || value.match(/^[a-z]*$/i) ) || key === 'text-align' && ( value === 'left' || value === 'right' || value === 'center' || value === 'justify' ) || key === 'float' && ( value === 'left' || value === 'right' || value === 'none' ) || key === 'direction' && ( value === 'rtl' || value === 'ltr' ) || key === 'font-family' && ( value === 'arial,helvetica,sans-serif' || value === 'georgia,serif' || value === 'impact,charcoal,sans-serif' || value === 'tahoma,geneva,sans-serif' || value === "'times new roman',times,serif" || value === 'verdana,geneva,sans-serif' ) || (key === 'width' || key === 'height' || key === 'font-size' || key === 'margin-left') && ( value.match(/[0-9\.]*(px|em|rem|%)/) ) ) { result += key + ': ' + value + ';'; } } }); return result; }
javascript
{ "resource": "" }
q49197
validCustomTag
train
function validCustomTag(tag, attrs, lkey, value) { // catch the div placeholder for the iframe replacement if (tag === 'img' && attrs['ta-insert-video']) { if (lkey === 'ta-insert-video' || lkey === 'allowfullscreen' || lkey === 'frameborder' || (lkey === 'contenteditble' && value === 'false')) { return true; } } return false; }
javascript
{ "resource": "" }
q49198
buildTree
train
function buildTree(memo, data) { if (data.level === memo.level) { memo.pointer.tree.push(data); } else if (data.level > memo.level) { var up = memo.pointer; memo.pointer = memo.pointer.tree[ memo.pointer.tree.length - 1]; memo.pointer.tree.push(data); memo.pointer.up = up; memo.level = data.level; } else if (data.level < memo.level) { // the jump up in the stack may be by more than one, so ascend // until we're at the right level. while (data.level <= memo.pointer.level && memo.pointer.up) { memo.pointer = memo.pointer.up; } memo.pointer.tree.push(data); memo.level = data.level; } return memo; }
javascript
{ "resource": "" }
q49199
resolveEntityOrId
train
function resolveEntityOrId(entityOrId, entities, schema) { const key = schema.key; let entity = entityOrId; let id = entityOrId; if (isObject(entityOrId)) { const mutableEntity = isImmutable(entity) ? entity.toJS() : entity; id = schema.getId(mutableEntity) || getIn(entity, ['id']); } else { entity = getIn(entities, [key, id]); } return { entity, id }; }
javascript
{ "resource": "" }