_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q60100
cleanup
validation
function cleanup(ctx, cb) { cleanupRun = true var msg = "Shutting down Sauce Connector" console.log(msg) ctx.comment(msg) if (connectorProc) connectorProc.kill("SIGINT") // Give Sauce Connector 5 seconds to gracefully stop before sending SIGKILL setTimeout(function() { if (connectorProc) connectorProc.kill("SIGKILL") fs.unlink(PIDFILE, function() {}) msg = "Sauce Connector successfully shut down" console.log(msg) ctx.comment(msg) return cb(0) }, 5000) }
javascript
{ "resource": "" }
q60101
startConnector
validation
function startConnector(username, apiKey, exitCb) { var jarPath = process.env.SAUCE_JAR || path.join(__dirname, "thirdparty", "Sauce-Connect.jar") var jcmd = "java" var jargs = ["-Xmx64m", "-jar", jarPath, username, apiKey] var screencmd = "java -Xmx64m -jar " + jarPath + " [USERNAME] [API KEY]" ctx.comment("Starting Sauce Connector") var opts = { cwd: ctx.workingDir, cmd: { command: jcmd, args: jargs, screen: screencmd } } connectorProc = ctx.cmd(opts, exitCb) // Wait until connector outputs "You may start your tests" // before returning connectorProc.stdout.on('data', function(data) { console.log(">>", data); if (/Connected! You may start your tests./.exec(data) !== null) { console.log(">> STRIDER-SAUCE :: TUNNEL READY") return cb(null, true) } }) }
javascript
{ "resource": "" }
q60102
parseResponseType
validation
function parseResponseType (req) { if (req.query && req.query.responseType) { if (req.query.responseType == 'modal') { // suport for old we.js contentOnly api req.query.responseType = req.we.config.defaultResponseType; req.query.contentOnly = true; } req.headers.accept = mime.getType(req.query.responseType.toLowerCase()); } if (req.accepts(req.we.config.responseTypes)) return; req.headers.accept = req.we.config.defaultResponseType; }
javascript
{ "resource": "" }
q60103
Plugin
validation
function Plugin (pluginPath) { this.pluginPath = pluginPath; this.we = we; this.events = this.we.events; this.hooks = this.we.hooks; this.router = this.we.router; /** * Plugin Assets * @type {Object} */ this.assets = { js: {}, css: {} }; this['package.json'] = require( path.join( pluginPath , 'package.json') ); this.controllersPath = path.join( this.pluginPath, this.controllerFolder ); this.modelsPath = path.join( this.pluginPath, this.modelFolder ); this.modelHooksPath = path.join( this.pluginPath, this.modelHookFolder ); this.modelInstanceMethodsPath = path.join( this.pluginPath, this.modelInstanceMethodFolder ); this.modelClassMethodsPath = path.join( this.pluginPath, this.modelClassMethodFolder ); this.searchParsersPath = path.join( this.pluginPath, this.searchParsersFolder ); this.searchTargetsPath = path.join( this.pluginPath, this.searchTargetsFolder ); this.templatesPath = this.pluginPath + '/server/templates'; this.helpersPath = this.pluginPath + '/server/helpers'; this.resourcesPath = this.pluginPath + '/server/resources'; this.routesPath = this.pluginPath + '/server/routes'; this.helpers = {}; this.layouts = {}; this.templates = {}; /** * Default plugin config object * * @type {Object} */ this.configs = {}; /** * Default plugin resources * * @type {Object} */ this.controllers = {}; this.models = {}; this.routes = {}; this.appFiles = []; this.appAdminFiles = []; }
javascript
{ "resource": "" }
q60104
validation
function(inputPath, outputPath, outputCharset){ var target = path.resolve(inputPath), result = { 'success': true, 'files': [] }; if(fs.existsSync(target)){ if(fs.statSync(target).isDirectory()) { var targets = fs.readdirSync(target); for (var i in targets) { if(!ModuleCompiler.isFileIgnored(targets[i])){ var inputFile = path.resolve(target, targets[i]), outputFile = path.join(outputPath, targets[i]); if(path.extname(inputFile)==='.js') { result.files.push(ModuleCompiler.build(inputFile, outputFile, outputCharset)); } } } } else { result.files.push(ModuleCompiler.build(target, outputPath, outputCharset)); } }else{ // MC.build('pkgName/abc'); var modulePath = ModuleCompiler.getModulePath(inputPath); if(modulePath){ result.files.push(ModuleCompiler.build(modulePath, outputPath, outputCharset)); }else{ result.success = false; !ModuleCompiler._config.silent && console.info('[err]'.bold.red + ' cannot find target: %s', target); } } return result; }
javascript
{ "resource": "" }
q60105
Theme
validation
function Theme (name, projectPath, options) { if (!name || (typeof name !== 'string') ) { return new Error('Param name is required for instantiate a new Theme object'); } if (!options) options = {}; this.we = we; this.hooks = this.we.hooks; this.events = this.we.events; const self = this; this.config = {}; this.projectPath = projectPath; // npm theme path / folder this.config.themeFolder = options.themeFolder || path.resolve(projectPath, 'node_modules', name); this.config.shortThemeFolder = options.themeFolder || 'node_modules' + '/' + name; // load theme module delete require.cache[require.resolve(this.config.themeFolder)]; const npmModule = require(this.config.themeFolder); // always initialize all instance properties this.name = name; const packageJSONPath = this.config.themeFolder+'/package.json'; delete require.cache[require.resolve(packageJSONPath)]; this['package.json'] = require(packageJSONPath); // shortcut for get installed theme version this.version = this['package.json'].version; this.templates = {}; this.layouts = {}; this.widgets = {}; this.tplsFolder = path.resolve(self.config.themeFolder, 'templates/server'); _.merge(this, npmModule); }
javascript
{ "resource": "" }
q60106
parseRecord
validation
function parseRecord(req, res, record) { for (var associationName in res.locals.Model.associations) { if (!record[associationName]) { if ( record.dataValues[ associationName + 'Id' ] ) { record.dataValues[ associationName ] = record[ associationName + 'Id' ]; } } else { if (record.dataValues[ associationName + 'Id' ]) { record.dataValues[ associationName ] = record[ associationName + 'Id' ]; } else if ( isObject(record[ associationName ] && record[ associationName ].id) ) { record.dataValues[ associationName ] = record[ associationName ].id; // if is a NxN association } else if( req.we.utils.isNNAssoc ( record[ associationName ] ) ) { record.dataValues[ associationName ] = record[ associationName ].id; } else { for (var i = record.dataValues[ associationName ].length - 1; i >= 0; i--) { record.dataValues[ associationName ][i] = record.dataValues[ associationName ][i].id; } } } } return record; }
javascript
{ "resource": "" }
q60107
Compiler
validation
function Compiler(config, op){ this.outputFilePath = op; this.modules = {}; this.fileList = []; this.analyzedModules = []; this.combinedModules = []; this.buildComboModules = []; this.buildAnalyzedModules = []; this.config = config; this.packages = config.packages; }
javascript
{ "resource": "" }
q60108
PluginManager
validation
function PluginManager (we) { this.we = we; projectPath = we.projectPath; // npm module folder from node_modules this.nodeModulesPath = path.resolve(projectPath, 'node_modules'); this.configs = we.configs; this.plugins = {}; this.pluginNames = this.getPluginsList(); // a list of plugin.js files get from npm module folder this.pluginFiles = {}; // array with all plugin paths this.pluginPaths = []; // plugin records from db this.records = []; // a list of plugins to install this.pluginsToInstall = {}; }
javascript
{ "resource": "" }
q60109
staticConfig
validation
function staticConfig (projectPath, app) { if (!projectPath) throw new Error('project path is required for load static configs'); // return configs if already is loaded if (app.staticConfigsIsLoad) return app.config; // - load and merge project configs let projectConfigFolder = app.projectConfigFolder; let files = []; try { files = fs.readdirSync(projectConfigFolder); } catch(e) { if (e.code != 'ENOENT') console.error('Error on load project config folder: ', e); } let file; for (let i = 0; i < files.length; i++) { if (files[i] == 'local.js') continue; // skip locals.js to load after all if (!files[i].endsWith('.js')) continue; // only accepts .js config files file = path.resolve(projectConfigFolder, files[i]); // skip dirs if (fs.lstatSync(file).isDirectory()) continue; _.merge(app.config, require(file)); } let jsonConfiguration = staticConfig.readJsonConfiguration(projectConfigFolder); let localConfigFile = staticConfig.readLocalConfigFile(projectConfigFolder); // load project local config file _.merge(app.config, jsonConfiguration, localConfigFile); app.staticConfigsIsLoad = true; return app.config; }
javascript
{ "resource": "" }
q60110
normalizePort
validation
function normalizePort (val) { let port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; }
javascript
{ "resource": "" }
q60111
onListening
validation
function onListening () { let addr = server.address(), bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; we.log.info('Run in '+we.env+' enviroment and listening on ' + bind); if (process.send) { process.send('ready'); } }
javascript
{ "resource": "" }
q60112
dateToDateTime
validation
function dateToDateTime(d) { if (d) { var date = moment(d); // return null if not is valid if (!date.isValid()) return null; // return data in datetime format return date.format('YYYY-MM-DD HH:mm:ss'); } else { return null; } }
javascript
{ "resource": "" }
q60113
oldIsPlugin
validation
function oldIsPlugin (nodeModulePath) { // then check if the npm module is one plugin try { if (fs.statSync( path.resolve( nodeModulePath, 'plugin.js' ) )) { return true; } else { return false; } } catch (e) { return false; } }
javascript
{ "resource": "" }
q60114
resolveTreeGreedy
validation
function resolveTreeGreedy (module, opts, cb) { if(!cb) cb = opts, opts = null opts = opts || {} opts.filter = function (pkg, root) { if(!pkg) return if(!root.tree[pkg.name]) { root.tree[pkg.name] = pkg pkg.parent = root } else { pkg.parent.tree[pkg.name] = pkg } return pkg } resolveTree(module, opts, cb) }
javascript
{ "resource": "" }
q60115
listRecusively
validation
function listRecusively (marker) { options.marker = marker; self.listObjectsPage( options, function (error, nextMarker, s3Objects) { if (error) { return callback(error); } // Send all of these S3 object definitions to be piped onwards. s3Objects.forEach(function (object) { object.Bucket = options.bucket; self.push(object); }); if (nextMarker) { listRecusively(nextMarker); } else { callback(); } } ); }
javascript
{ "resource": "" }
q60116
createClass
validation
function createClass() { var mixins, definition; switch(arguments.length) { case 0: throw new Error('class definition required'); break; case 1: mixins = []; definition = arguments[0]; break; default: mixins = arguments[0]; definition = arguments[1]; break; } var newclass = definition['constructor']; if(typeof newclass !== 'function') throw new Error('constructor function required'); if(typeof newclass.name === 'string' && newclass.name.length === 0) throw new Error('constructor name required, it will be used as new class name'); newclass.prototype = definition; newclass.prototype.instanceOf = instanceOf; newclass.prototype.Super = superMethod; // if no mixin given, just create a base class if(!mixins) return newclass; if(Array.isArray(mixins)) { // multi inheritance, if mixins is an array of base classes for(var i=mixins.length-1; i>=0; i--) { newclass = mixin(newclass, mixins[i]); } return newclass; } else { // single inheritance return mixin(newclass, mixins); } }
javascript
{ "resource": "" }
q60117
superMethod
validation
function superMethod(methodname) { var func = null; var p = this.__proto__; if(!p) throw new Error('invalid parameters'); for(p = p.__proto__; !isEmpty(p); p = p.__proto__) { var method = p[methodname]; if(typeof method === 'function') { func = method; break; } } if(! func) throw new Error('super method not found: ' + methodname); return func; }
javascript
{ "resource": "" }
q60118
subOf
validation
function subOf(child, mixin) { if(child === mixin) return true; if(child && child.constructors) { for(var i in child.constructors) { var parent = child.constructors[i]; // avoid dead loop if(parent === child) continue; if(parent === mixin) return true; if(subOf(parent, mixin)) return true; } } return false; }
javascript
{ "resource": "" }
q60119
_zero
validation
function _zero(_arg, _cb) { if (!_arg.create) { _cb(); return; } // We need to stub this out now since we won't write the file to manta // until writeback runs on this file. var now = new Date().toUTCString(); var info = { extension: 'bin', type: 'application/octet-stream', parent: path.dirname(p), size: 0, headers: { 'last-modified': now } }; var opts = {}; if (_arg.exclusive) { // exclusive applies only to the local file in the cache opts.flag = 'wx'; } else { opts.flag = 'w'; } self._stat(p, info, function (s_err, stats) { if (s_err) { _cb(s_err); return; } fs.writeFile(stats._cacheFile, new Buffer(0), opts, function (err) { if (err) { _cb(err); return; } // mark file as dirty in the cache self.cache.dirty(p, stats._fhandle, function (d_err) { if (d_err) { log.warn(d_err, 'dirty(%s): failed', p); _cb(d_err); } else { self.cache.add_to_pdir(p, _cb); } }); }); }); }
javascript
{ "resource": "" }
q60120
rename
validation
function rename(obj) { return rename_(function(parsedPath) { return { extname: obj.extname || parsedPath.extname, dirname: (obj.dirnamePrefix || '') + parsedPath.dirname, basename: parsedPath.basename }; }); }
javascript
{ "resource": "" }
q60121
update_db
validation
function update_db(p, stats, _cb) { var key = sprintf(FILES_KEY_FMT, p); var k1 = sprintf(FHANDLE_KEY_FMT, p); var k2 = sprintf(FNAME_KEY_FMT, stats._fhandle); self.db.batch() .put(key, stats) .put(k1, stats._fhandle) .put(k2, p) .write(function onBatchWrite(err2) { if (err2) { log.error(err2, 'update_db(%s): failed', p); _cb(errno(err2)); } else { log.trace('update_db(%s): done', p); self.cache.set(key, stats); _cb(null); } }); }
javascript
{ "resource": "" }
q60122
process_entry
validation
function process_entry(val, nextent) { if (!val || !val._tmp_pathname) { // if this is somehow missing, just skip it since we can't check // to see if the file is dirty nextent(); return; } var nm = val._tmp_pathname; delete val._tmp_pathname; // if in-use or dirty, skip it if (val._no_evict || val._in_flight || wb_pending[nm] || wb_inprogress[nm]) { nextent(); return; } // if we've gotten under the limit, skip over the rest of the objects if (self.curr_size < self.max_size) { nextent(); return; } fs.stat(val._cacheFile, function (serr, stats) { if (serr) { // just assume an error is ENOENT meaning object is not cached // this is common nextent(); return; } // recheck after callback if in-use or dirty and skip it if (val._no_evict || val._in_flight || wb_pending[nm] || wb_inprogress[nm]) { nextent(); return; } fs.unlink(val._cacheFile, function (uerr) { // ignore errors deleting the cachefile but if no // error, that means we should adjust our size if (!uerr) { self._reduce_cache(nm, stats.size); log.trace('evicted(%s, %d): %d', nm, size, self.curr_size); } nextent(); }); }); }
javascript
{ "resource": "" }
q60123
_prepopulate_metadata
validation
function _prepopulate_metadata(_arg, _cb) { var entry; try { entry = JSON.parse(_arg); } catch (e) { _cb(); return; } var nm = path.join(entry.parent, entry.name); var k = sprintf(FILES_KEY_FMT, nm); // if already in LRU cache, return var stats = self.cache.get(k); if (stats) { _cb(); return; } self.db.get(k, function (err, val) { // if already in db, return if (!err) { _cb(); return; } var fh = uuid.v4(); var info; var cfile = path.join(self.location, 'fscache', fh); if (entry.type !== 'directory') { info = { name: entry.name, extension: 'bin', type: 'application/octet-stream', size: entry.size, headers: { 'last-modified': entry.mtime }, _fhandle: fh, _cacheFile: cfile, last_stat: now }; } else { info = { name: entry.name, extension: 'directory', type: 'application/x-json-stream; type=directory', headers: { 'last-modified': entry.mtime, 'result-set-size': 3 }, last_modified: entry.mtime, _fhandle: fh, _cacheFile: cfile, last_stat: now }; } var k1 = sprintf(FHANDLE_KEY_FMT, nm); var k2 = sprintf(FNAME_KEY_FMT, fh); self.db.batch() .put(k, info) .put(k1, fh) .put(k2, nm) .write(function (err2) { if (!err2) self.cache.set(k, info); _cb(); }); }); }
javascript
{ "resource": "" }
q60124
check_object
validation
function check_object(now, key, p, c_info) { // keep track of how many files we're in the process of checking via // callback so we can know when to emit the 'ready' event stale_check_cnt++; if (!c_info.last_stat || (now - c_info.last_stat) > self.ttl_ms) { // consider it stale, cleanup locally cached file, if it exists fs.unlink(c_info._cacheFile, function (u_err) { // ignore errors deleting the cachefile, which may not exist log.trace('stale, discard: %s', p); stale_check_cnt--; if (db_keys_done && stale_check_cnt === 0) self.emit('ready'); }); } else { // Our metadata is fresh, see if we have the object cached so we // can track its size. fs.stat(c_info._cacheFile, function (err, stats) { if (!err) { // The file is still fresh, add to the current cache space // used. log.trace('not stale, keep: %s', p); self._grow_cache(p, stats.size); } stale_check_cnt--; if (db_keys_done && stale_check_cnt === 0) self.emit('ready'); }); } }
javascript
{ "resource": "" }
q60125
validation
function (soajs, id, cb) { checkForMongo(soajs); var id1; try { id1 = mongo.ObjectId(id); return id1; } catch (e) { soajs.log.error(e); throw e; } }
javascript
{ "resource": "" }
q60126
validation
function (soajs, combo, cb) { checkForMongo(soajs); mongo.findOne(combo.collection, combo.condition || {}, combo.fields || null, combo.options || null, cb); }
javascript
{ "resource": "" }
q60127
validation
function (soajs, combo, cb) { checkForMongo(soajs); mongo.remove(combo.collection, combo.condition, cb); }
javascript
{ "resource": "" }
q60128
call
validation
function call() { var args = [xdhq, 3]; var i = 0; while (i < arguments.length) args.push(arguments[i++]); njsq._call.apply(null, args); }
javascript
{ "resource": "" }
q60129
initBLModel
validation
function initBLModel(req, res, cb) { let modelName = config.model; if (req.soajs.servicesConfig && req.soajs.servicesConfig.model) { modelName = req.soajs.servicesConfig.model; } if (process.env.SOAJS_TEST && req.soajs.inputmaskData.model) { modelName = req.soajs.inputmaskData.model; } BLModule.init(modelName, function (error, BL) { if (error) { req.soajs.log.error(error); return res.json(req.soajs.buildResponse({"code": 601, "msg": config.errors[601]})); } else { return cb(BL); } }); }
javascript
{ "resource": "" }
q60130
getAssetDir
validation
function getAssetDir() { var dir = path.dirname(process.argv[1]); if (isDev()) { let epeiosPath = getEpeiosPath(); return path.resolve(epeiosPath, "tools/xdhq/examples/common/", path.relative(path.resolve(epeiosPath, "tools/xdhq/examples/NJS/"), path.resolve(dir))); // No final '/'. } else return path.resolve(dir); }
javascript
{ "resource": "" }
q60131
validation
function (req, cb) { let config = req.soajs.config; let loginMode = config.loginMode; if (req.soajs.tenantOauth && req.soajs.tenantOauth.loginMode) { loginMode = req.soajs.tenantOauth.loginMode; } function getLocal() { let condition = {'userId': req.soajs.inputmaskData['username']}; let combo = { collection: userCollectionName, condition: condition }; libProduct.model.findEntry(req.soajs, combo, function (err, record) { if (record) { let hashConfig = { "hashIterations": config.hashIterations, "seedLength": config.seedLength }; if (req.soajs.servicesConfig && req.soajs.servicesConfig.oauth) { if (req.soajs.servicesConfig.oauth.hashIterations && req.soajs.servicesConfig.oauth.seedLength) { hashConfig = { "hashIterations": req.soajs.servicesConfig.oauth.hashIterations, "seedLength": req.soajs.servicesConfig.oauth.seedLength }; } } coreHasher.init(hashConfig); coreHasher.compare(req.soajs.inputmaskData.password, record.password, function (err, result) { if (err || !result) { return cb(413); } delete record.password; if (record.tId && req.soajs.tenant) { if (record.tId.toString() !== req.soajs.tenant.id) { return cb(403); } } //TODO: keys here if (record) { record.loginMode = loginMode; } return cb(null, record); }); } else { req.soajs.log.error("Username " + req.soajs.inputmaskData['username'] + " not found"); return cb(401); } }); } if (loginMode === 'urac') { let data = { 'username': req.soajs.inputmaskData['username'], 'password': req.soajs.inputmaskData['password'] }; uracDriver.login(req.soajs, data, function (errCode, record) { if (errCode) { return cb(errCode); } if (record) { record.loginMode = loginMode; } return cb(null, record); }); } else { getLocal(); } }
javascript
{ "resource": "" }
q60132
validation
function (req, cb) { let config = req.soajs.config; let loginMode = config.loginMode; if (req.soajs.tenantOauth && req.soajs.tenantOauth.loginMode) { loginMode = req.soajs.tenantOauth.loginMode; } let criteria = { "userId.loginMode": loginMode, "userId.id": req.soajs.inputmaskData.userId }; let combo = { collection: tokenCollectionName, condition: criteria }; libProduct.model.removeEntry(req.soajs, combo, function (error, result) { let data = {config: req.soajs.config, error: error, code: 404}; checkIfError(req, cb, data, function () { return cb(null, result.result); }); }); }
javascript
{ "resource": "" }
q60133
validation
function (req, cb) { let criteria = { "clientId": req.soajs.inputmaskData.clientId }; let combo = { collection: tokenCollectionName, condition: criteria }; libProduct.model.removeEntry(req.soajs, combo, function (error, result) { let data = {config: req.soajs.config, error: error, code: 404}; checkIfError(req, cb, data, function () { return cb(null, result.result); }); }); }
javascript
{ "resource": "" }
q60134
validation
function (req, cb) { if (req.soajs && req.soajs.tenantOauth && req.soajs.tenantOauth.secret && req.soajs.tenant && req.soajs.tenant.id) { let secret = req.soajs.tenantOauth.secret; let tenantId = req.soajs.tenant.id.toString(); let basic = Auth.generate(tenantId, secret); return cb(null, basic); } else return cb({"code": 406, "msg": req.soajs.config.errors[406]}); }
javascript
{ "resource": "" }
q60135
requireModel
validation
function requireModel(filePath, cb) { //check if file exist. if not return error fs.exists(filePath, function (exists) { if (!exists) { return cb(new Error("Requested Model Not Found!")); } libProduct.model = require(filePath); return cb(null, libProduct); }); }
javascript
{ "resource": "" }
q60136
noCallbackHandler
validation
function noCallbackHandler(ctx, connectMiddleware, next) { connectMiddleware(ctx.req, ctx.res) return next() }
javascript
{ "resource": "" }
q60137
withCallbackHandler
validation
function withCallbackHandler(ctx, connectMiddleware, next) { return new Promise((resolve, reject) => { connectMiddleware(ctx.req, ctx.res, err => { if (err) reject(err) else resolve(next()) }) }) }
javascript
{ "resource": "" }
q60138
koaConnect
validation
function koaConnect(connectMiddleware) { const handler = connectMiddleware.length < 3 ? noCallbackHandler : withCallbackHandler return function koaConnect(ctx, next) { return handler(ctx, connectMiddleware, next) } }
javascript
{ "resource": "" }
q60139
makeOrdinal
validation
function makeOrdinal(words) { // Ends with *00 (100, 1000, etc.) or *teen (13, 14, 15, 16, 17, 18, 19) if (ENDS_WITH_DOUBLE_ZERO_PATTERN.test(words) || ENDS_WITH_TEEN_PATTERN.test(words)) { return words + 'th'; } // Ends with *y (20, 30, 40, 50, 60, 70, 80, 90) else if (ENDS_WITH_Y_PATTERN.test(words)) { return words.replace(ENDS_WITH_Y_PATTERN, 'ieth'); } // Ends with one through twelve else if (ENDS_WITH_ZERO_THROUGH_TWELVE_PATTERN.test(words)) { return words.replace(ENDS_WITH_ZERO_THROUGH_TWELVE_PATTERN, replaceWithOrdinalVariant); } return words; }
javascript
{ "resource": "" }
q60140
getPermission
validation
function getPermission() { var permission = NotificationAPI.permission; /** * True if permission is granted, else false. * * @memberof! webNotification * @alias webNotification.permissionGranted * @public */ var permissionGranted = false; if (permission === 'granted') { permissionGranted = true; } return permissionGranted; }
javascript
{ "resource": "" }
q60141
validation
function (title, options, callback) { var autoClose = 0; if (options.autoClose && (typeof options.autoClose === 'number')) { autoClose = options.autoClose; } //defaults the notification icon to the website favicon.ico if (!options.icon) { options.icon = '/favicon.ico'; } var onNotification = function (notification) { //add onclick handler if (options.onClick && notification) { notification.onclick = options.onClick; } var hideNotification = function () { notification.close(); }; if (autoClose) { setTimeout(hideNotification, autoClose); } callback(null, hideNotification); }; var serviceWorkerRegistration = options.serviceWorkerRegistration; if (serviceWorkerRegistration) { delete options.serviceWorkerRegistration; if (!options.tag) { tagCounter++; options.tag = 'webnotification-' + Date.now() + '-' + tagCounter; } var tag = options.tag; serviceWorkerRegistration.showNotification(title, options).then(function onCreate() { serviceWorkerRegistration.getNotifications({ tag: tag }).then(function notificationsFetched(notifications) { if (notifications && notifications.length) { onNotification(notifications[0]); } else { callback(new Error('Unable to find notification.')); } }).catch(callback); }).catch(callback); } else { var instance; try { instance = new NotificationAPI(title, options); } catch (error) { callback(error); } //in case of no errors if (instance) { onNotification(instance); } } }
javascript
{ "resource": "" }
q60142
validation
function (argumentsArray) { //callback is always the last argument var callback = noop; if (argumentsArray.length && (typeof argumentsArray[argumentsArray.length - 1] === 'function')) { callback = argumentsArray.pop(); } var title = null; var options = null; if (argumentsArray.length === 2) { title = argumentsArray[0]; options = argumentsArray[1]; } else if (argumentsArray.length === 1) { var value = argumentsArray.pop(); if (typeof value === 'string') { title = value; options = {}; } else { title = ''; options = value; } } //set defaults title = title || ''; options = options || {}; return { callback: callback, title: title, options: options }; }
javascript
{ "resource": "" }
q60143
OktaAPIGroups
validation
function OktaAPIGroups(apiToken, domain, preview) { if(apiToken == undefined || domain == undefined) { throw new Error("OktaAPI requires an API token and a domain"); } this.domain = domain; if(preview == undefined) this.preview = false; else this.preview = preview; this.request = new NetworkAbstraction(apiToken, domain, preview); this.helpers = require('./OktaAPIGroupsHelpers.js') }
javascript
{ "resource": "" }
q60144
OktaAPISessions
validation
function OktaAPISessions(apiToken, domain, preview) { if(apiToken == undefined || domain == undefined) { throw new Error("OktaAPI requires an API token and a domain"); } this.domain = domain; if(preview == undefined) this.preview = false; else this.preview = preview; this.request = new NetworkAbstraction(apiToken, domain, preview); }
javascript
{ "resource": "" }
q60145
OktaAPI
validation
function OktaAPI(apiToken, domain, preview) { if(apiToken == undefined || domain == undefined) { throw new Error("OktaAPI requires an API token and a domain"); } this.domain = domain; if(preview == undefined) this.preview = false; else this.preview = preview; this.request = new NetworkAbstraction(apiToken, domain, preview); this.users = new OktaAPIUsers(apiToken, domain, preview); this.groups = new OktaAPIGroups(apiToken, domain, preview); this.sessions = new OktaAPISessions(apiToken, domain, preview); this.apps = new OktaAPIApps(apiToken, domain, preview); this.events = new OktaAPIEvents(apiToken, domain, preview); }
javascript
{ "resource": "" }
q60146
constructGroup
validation
function constructGroup(name, description) { var profile = {}; profile.name = name; profile.description = description; return profile; }
javascript
{ "resource": "" }
q60147
change
validation
function change(evt) { evt = evt || win.event; if ('readystatechange' === evt.type) { readystate.change(docReadyState()); if (complete !== docReadyState()) return; } if ('load' === evt.type) readystate.change('complete'); else readystate.change('interactive'); // // House keeping, remove our assigned event listeners. // (evt.type === 'load' ? win : doc)[off](evt.type, change, false); }
javascript
{ "resource": "" }
q60148
UTF8ArrayToString
validation
function UTF8ArrayToString(u8Array, idx) { var u0, u1, u2, u3, u4, u5; var str = ''; while (1) { // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629 u0 = u8Array[idx++]; if (!u0) return str; if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; } u1 = u8Array[idx++] & 63; if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } u2 = u8Array[idx++] & 63; if ((u0 & 0xF0) == 0xE0) { u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; } else { u3 = u8Array[idx++] & 63; if ((u0 & 0xF8) == 0xF0) { u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | u3; } else { u4 = u8Array[idx++] & 63; if ((u0 & 0xFC) == 0xF8) { u0 = ((u0 & 3) << 24) | (u1 << 18) | (u2 << 12) | (u3 << 6) | u4; } else { u5 = u8Array[idx++] & 63; u0 = ((u0 & 1) << 30) | (u1 << 24) | (u2 << 18) | (u3 << 12) | (u4 << 6) | u5; } } } if (u0 < 0x10000) { str += String.fromCharCode(u0); } else { var ch = u0 - 0x10000; str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); } } }
javascript
{ "resource": "" }
q60149
lengthBytesUTF32
validation
function lengthBytesUTF32(str) { var len = 0; for (var i = 0; i < str.length; ++i) { // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! We must decode the string to UTF-32 to the heap. // See http://unicode.org/faq/utf_bom.html#utf16-3 var codeUnit = str.charCodeAt(i); if (codeUnit >= 0xD800 && codeUnit <= 0xDFFF) ++i; // possibly a lead surrogate, so skip over the tail surrogate. len += 4; } return len; }
javascript
{ "resource": "" }
q60150
constructProfile
validation
function constructProfile(firstName, lastName, email, login, mobilePhone, customAttribs) { var profile = {}; profile.login = (login ? login : email); profile.email = email; profile.firstName = firstName; profile.lastName = lastName; profile.mobilePhone = mobilePhone; if(customAttribs != undefined) { for(prop in customAttribs) { profile[prop] = customAttribs[prop]; } } return profile; }
javascript
{ "resource": "" }
q60151
constructCredentials
validation
function constructCredentials(password, question, answer) { var credentials = {}; if(password) credentials.password = constructPassword(password); if(question && answer) credentials.recovery_question = constructRecoveryQuestion(question, answer); return credentials; }
javascript
{ "resource": "" }
q60152
validation
function(method, where, what, query, callback) { var opts = {}; if(what == undefined) opts.body = ""; else opts.body = JSON.stringify(what); opts.headers = {}; opts.headers['Content-Length'] = opts.body.length; opts.headers['Content-Type'] = "application/json"; opts.headers['Authorization'] = "SSWS " + apiKey; opts.method = method; opts.uri = url.parse(where); if(query != null) opts.qs = query; request(opts, function(error, clientResp, resp) { handleResponse(error, false, clientResp, resp, callback) }); }
javascript
{ "resource": "" }
q60153
constructAppModel
validation
function constructAppModel(id, name, label, created, lastUpdated, status, features, signOnMode, accessibility, visibility, credentials, settings, links, embedded) { var model = {}; if(id) model.id = id; if(name) model.name = name; if(label) model.label = label; if(created) model.created = created; if(lastUpdated) model.lastUpdated = lastUpdated; if(status) model.status = status; if(features) model.features = features; if(signOnMode) model.signOnMode = signOnMode; if(accessibility) model.accessibility = accessibility; if(visibility) model.visibility = visibility; if(credentials) model.credentials = credentials; if(settings) model.settings = settings; if(links) model.links = links; if(embedded) model.embedded = embedded; return model; }
javascript
{ "resource": "" }
q60154
constructAppUserModel
validation
function constructAppUserModel(id, externalId, created, lastUpdated, scope, status, statusChanged, passwordChanged, syncState, lastSync, credentials, lastSync, links) { var model = {}; if(id) model.id = id; if(externalId) model.externalId = externalId; if(created) model.created = created; if(lastUpdated) model.lastUpdated = lastUpdated; if(scope) model.scope = scope; if(status) model.status = status; if(statusChanged) model.statusChanged = statusChanged; if(passwordChanged) model.passwordChanged = passwordChanged; if(syncState) model.syncState = syncState; if(lastSync) model.lastSync = lastSync; if(credentials) model.credentials = credentials; if(lastSync) model.lastSync = lastSync; if(links) model.links = links; return model; }
javascript
{ "resource": "" }
q60155
constructAppGroupModel
validation
function constructAppGroupModel(id, lastUpdated, priority, links) { var model = {}; if(id) model.id = id; if(lastUpdated) model.lastUpdated = lastUpdated; if(priority) model.priority = priority; if(links) model.links = links; return model; }
javascript
{ "resource": "" }
q60156
validation
function (rawErrors) { var normalizedErrors = []; if ( typeof rawErrors === 'string' || (typeof rawErrors === 'object' && !Array.isArray(rawErrors)) ) { // Only one error set, which we can assume was for a single property rawErrors = [rawErrors]; } if (rawErrors != null) { canReflect.eachIndex(rawErrors, function (error) { [].push.apply(normalizedErrors, parseErrorItem(error)); }); } return normalizedErrors; }
javascript
{ "resource": "" }
q60157
getResultSeverity
validation
function getResultSeverity (result, config) { // Count all errors return result.reduce((previous, message) => { let severity if (message.fatal) { return previous + 1 } severity = message.messages[0] ? message.messages[0].severity : 0 if (severity === 2) { return previous + 1 } return previous }, 0) }
javascript
{ "resource": "" }
q60158
validation
function (inputNode, options = {}) { this.formatter = require('eslint/lib/formatters/stylish') if (!(this instanceof StandardValidationFilter)) { return new StandardValidationFilter(inputNode, options) } // set inputTree Filter.call(this, inputNode) this.node = inputNode this.console = options.console || console this.internalOptions = { format: options.format ? options.format : undefined, throwOnError: options.throwOnError ? options.throwOnError : false, logOutput: options.logOutput ? options.logOutput : false, fix: options.fix ? options.fix : false, globals: options.globals || options.global } this.ignore = options.ignore ? options.ignore : function () { return false } if (typeof options.testGenerator === 'string') { const testGenerators = require('./test-generators') this.testGenerator = testGenerators[options.testGenerator] if (!this.testGenerator) { throw new Error(`Could not find '${this.internalOptions.testGenerator}' test generator.`) } } else { this.testGenerator = options.testGenerator } if (this.testGenerator) { this.targetExtension = 'lint-test.js' } // set formatter this.formatter = require(this.internalOptions.format ? this.internalOptions.format : 'eslint/lib/formatters/stylish') }
javascript
{ "resource": "" }
q60159
_boolToNum
validation
function _boolToNum(value, numTrue, numFalse, defaultVal) { if (typeof value === 'boolean') { return value ? numTrue : numFalse; } return typeof value === 'number' ? value : defaultVal; }
javascript
{ "resource": "" }
q60160
validation
function() { if ((cachedWidth = element.offsetWidth) != lastWidth || (cachedHeight = element.offsetHeight) != lastHeight) { dirty = true; lastWidth = cachedWidth; lastHeight = cachedHeight; } reset(); }
javascript
{ "resource": "" }
q60161
validation
function(element, callback) { var me = this; var elementType = Object.prototype.toString.call(element); var isCollectionTyped = me._isCollectionTyped = ('[object Array]' === elementType || ('[object NodeList]' === elementType) || ('[object HTMLCollection]' === elementType) || ('undefined' !== typeof jQuery && element instanceof window.jQuery) || //jquery ('undefined' !== typeof Elements && element instanceof window.Elements) //mootools ); me._element = element; if (isCollectionTyped) { var i = 0, j = element.length; for (; i < j; i++) { attachResizeEvent(element[i], callback); } } else { attachResizeEvent(element, callback); } }
javascript
{ "resource": "" }
q60162
wrapFn
validation
function wrapFn(mocker, fn) { return function() { //Copy the arguments this function was called with var args = Array.prototype.slice.call(arguments); //Save the arguments to the log mocker.history.push(args); return fn.apply(this, arguments); }; }
javascript
{ "resource": "" }
q60163
pass
validation
function pass(part, suiteIndex, testIndex) { var o; var isSuite = false; if (typeof testIndex === 'number') { o = suites[suiteIndex].tests[testIndex]; } else { isSuite = true; o = suites[suiteIndex]; } display.pass(part, o); if ( isSuite ) { // Suite ---------------------------- if (part === 'setup') { // setup completed o.setup.status = true; // run the next test in suite if (!testIndex) { testIndex = 0; } else { testIndex = testIndex + 1; } if (typeof o.tests[testIndex] === 'object') { run('beforeEach', suiteIndex, testIndex); } else { run('takedown', suiteIndex); } } else if (part === 'takedown') { // takedown completed o.takedown.status = true; if (o.next) { // move on to the next suite run('setup', suiteIndex + 1); } else { // finished, show summary results showSummary(); } } } else { // Test ---------------------------------------------- if (part === 'beforeEach') { // beforeEach completed o.beforeEach.status = true; // run the test setup run('setup', suiteIndex, testIndex); } else if (part === 'setup') { // setup completed o.setup.status = true; // run the test run('actual', suiteIndex, testIndex); } else if (part === 'takedown') { // takedown completed o.takedown.status = true; // call afterEach run('afterEach', suiteIndex, testIndex); } else if (part === 'afterEach') { // afterEach completed o.afterEach.status = true; if (typeof o.parent.tests[testIndex + 1] === 'object') { o.parent.testIndex = testIndex + 1; run('beforeEach', suiteIndex, testIndex + 1); } else { // run suites takedown run('takedown', suiteIndex); } } else { // test is complete o.status = true; run('takedown', suiteIndex, testIndex); } } }
javascript
{ "resource": "" }
q60164
fail
validation
function fail(part, suiteIndex, testIndex, msg) { if (typeof testIndex === 'string') { msg = testIndex; testIndex = undefined; } var o; var isSuite = false; if (typeof testIndex === 'number') { o = suites[suiteIndex].tests[testIndex]; if (typeof msg === 'string') { suites[suiteIndex].tests[testIndex][part].failmsg = msg; } display.details('test', o); } else { isSuite = true; o = suites[suiteIndex]; if (typeof msg === 'string') { suites[suiteIndex][part].failmsg = msg; } display.details('suite', o); } display.fail(part, o); // if we've failed, we always perform the takedown. if (part === 'takedown') { // takedown has been done o.takedown.status = false; if (( isSuite ) && (! o.abortOnFail)) { // run next suite run('setup', o.next); } else { // run afterEach for this test run('afterEach', suiteIndex, testIndex); } } else if (part === 'afterEach') { o.afterEach.status = false; if (typeof o.parent.tests[o.parent.testIndex] === 'object') { if (! o.parent.abortOnFail) { var ti = o.parent.testIndex; o.parent.testIndex = o.parent.testIndex + 1; run('beforeEach', suiteIndex, ti); } } else { // run suites takedown run('takedown', suiteIndex); } } else if (part === 'beforeEach') { o.beforeEach.status = false; run('afterEach', suiteIndex, testIndex); } else if (part === 'setup') { o.setup.status = false; run('takedown', suiteIndex, testIndex); } else if (part === 'actual') { // the actual test o.status = false; if (o.parent.abortOnFail) { display.print('test failed with abortOnFail set... aborting.'); showSummary(); } run('takedown', suiteIndex, testIndex); } else { throw new Error('no part specified in run()'); } }
javascript
{ "resource": "" }
q60165
prepareJson
validation
function prepareJson(shares) { /*jshint maxcomplexity:11 */ /*jshint maxstatements:23 */ let json = []; for (let i = 0; i < shares.length; i++) { let share = shares[i]; json[i] = {}; json[i].id = share.id; let status = '?'; switch (share.state) { case 0: status = 'stopped'; break; case 1: status = 'running'; break; case 2: status = 'errored'; break; default: status = 'unknown'; } json[i].status = status; json[i].configPath = share.config.storagePath; json[i].uptime = prettyMs(share.meta.uptimeMs); json[i].restarts = share.meta.numRestarts || 0; json[i].peers = share.meta.farmerState.totalPeers || 0; json[i].allocs = fixContractValue( share.meta.farmerState.contractCount ); json[i].dataReceivedCount = fixContractValue( share.meta.farmerState.dataReceivedCount ); json[i].delta = share.meta.farmerState.ntpStatus.delta; json[i].port = share.meta.farmerState.portStatus.listenPort; json[i].shared = share.meta.farmerState.spaceUsed; json[i].sharedPercent = share.meta.farmerState.percentUsed; var bridgeCxStat = share.meta.farmerState.bridgesConnectionStatus; switch (bridgeCxStat) { case 0: json[i].bridgeConnectionStatus = 'disconnected'; break; case 1: json[i].bridgeConnectionStatus = 'connecting'; break; case 2: json[i].bridgeConnectionStatus = 'confirming'; break; case 3: json[i].bridgeConnectionStatus = 'connected'; break; default: break; } } return JSON.stringify(json); }
javascript
{ "resource": "" }
q60166
validation
function (content) { // Test against regex list var interpolateTest = _.templateSettings.interpolate.test(content); if (interpolateTest) { _.templateSettings.interpolate.lastIndex = 0; return true; } var evaluateTest = _.templateSettings.evaluate.test(content); if (evaluateTest) { _.templateSettings.evaluate.lastIndex = 0; return true; } var escapeTest = _.templateSettings.escape.test(content); _.templateSettings.escape.lastIndex = 0; return escapeTest; }
javascript
{ "resource": "" }
q60167
validation
function (match, strUntilValue, name, value, index) { var self = this; var expression = value; if (!this.isRelevantTagAttr(this.currentTag, name)) { return; } // Try and set "root" directory when a dynamic attribute is found if (isTemplate(value)) { if (pathIsAbsolute(value) && self.root !== undefined && self.parseDynamicRoutes) { // Generate new value for replacement expression = loaderUtils.urlToRequest(value, self.root); } } this.matches.push({ start: index + strUntilValue.length, length: value.length, value: value, expression: expression }); }
javascript
{ "resource": "" }
q60168
refresh
validation
function refresh(entry) { if (entry !== freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd === entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } }
javascript
{ "resource": "" }
q60169
link
validation
function link(nextEntry, prevEntry) { if (nextEntry !== prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } }
javascript
{ "resource": "" }
q60170
validation
function(key, value, writeAttr, attrName) { // TODO: decide whether or not to throw an error if "class" // is set through this function since it may cause $updateClass to // become unstable. var node = this.$$element[0], booleanKey = getBooleanAttrName(node, key), aliasedKey = getAliasedAttrName(key), observer = key, nodeName; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } else if (aliasedKey) { this[aliasedKey] = value; observer = aliasedKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } nodeName = nodeName_(this.$$element); // Sanitize img[srcset] values. if (nodeName === 'img' && key === 'srcset') { this[key] = value = sanitizeSrcset(value, '$set(\'srcset\', value)'); } if (writeAttr !== false) { if (value === null || isUndefined(value)) { this.$$element.removeAttr(attrName); } else { if (SIMPLE_ATTR_NAME.test(attrName)) { this.$$element.attr(attrName, value); } else { setSpecialAttr(this.$$element[0], attrName, value); } } } // fire observers var $$observers = this.$$observers; if ($$observers) { forEach($$observers[observer], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); } }
javascript
{ "resource": "" }
q60171
groupScan
validation
function groupScan(node, attrStart, attrEnd) { var nodes = []; var depth = 0; if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { do { if (!node) { throw $compileMinErr('uterdir', 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.', attrStart, attrEnd); } if (node.nodeType === NODE_TYPE_ELEMENT) { if (node.hasAttribute(attrStart)) depth++; if (node.hasAttribute(attrEnd)) depth--; } nodes.push(node); node = node.nextSibling; } while (depth > 0); } else { nodes.push(node); } return jqLite(nodes); }
javascript
{ "resource": "" }
q60172
mergeTemplateAttributes
validation
function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) !== '$') { if (src[key] && src[key] !== value) { if (value.length) { value += (key === 'style' ? ';' : ' ') + src[key]; } else { value = src[key]; } } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { // Check if we already set this attribute in the loop above. // `dst` will never contain hasOwnProperty as DOM parser won't let it. // You will get an "InvalidCharacterError: DOM Exception 5" error if you // have an attribute like "has-own-property" or "data-has-own-property", etc. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') { dst[key] = value; if (key !== 'class' && key !== 'style') { dstAttr[key] = srcAttr[key]; } } }); }
javascript
{ "resource": "" }
q60173
replaceWith
validation
function replaceWith($rootElement, elementsToRemove, newNode) { var firstElementToRemove = elementsToRemove[0], removeCount = elementsToRemove.length, parent = firstElementToRemove.parentNode, i, ii; if ($rootElement) { for (i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] === firstElementToRemove) { $rootElement[i++] = newNode; for (var j = i, j2 = j + removeCount - 1, jj = $rootElement.length; j < jj; j++, j2++) { if (j2 < jj) { $rootElement[j] = $rootElement[j2]; } else { delete $rootElement[j]; } } $rootElement.length -= removeCount - 1; // If the replaced element is also the jQuery .context then replace it // .context is a deprecated jQuery api, so we should set it only when jQuery set it // http://api.jquery.com/context/ if ($rootElement.context === firstElementToRemove) { $rootElement.context = newNode; } break; } } } if (parent) { parent.replaceChild(newNode, firstElementToRemove); } // Append all the `elementsToRemove` to a fragment. This will... // - remove them from the DOM // - allow them to still be traversed with .nextSibling // - allow a single fragment.qSA to fetch all elements being removed var fragment = window.document.createDocumentFragment(); for (i = 0; i < removeCount; i++) { fragment.appendChild(elementsToRemove[i]); } if (jqLite.hasData(firstElementToRemove)) { // Copy over user data (that includes AngularJS's $scope etc.). Don't copy private // data here because there's no public interface in jQuery to do that and copying over // event listeners (which is the main use of private data) wouldn't work anyway. jqLite.data(newNode, jqLite.data(firstElementToRemove)); // Remove $destroy event listeners from `firstElementToRemove` jqLite(firstElementToRemove).off('$destroy'); } // Cleanup any data/listeners on the elements and children. // This includes invoking the $destroy event on any elements with listeners. jqLite.cleanData(fragment.querySelectorAll('*')); // Update the jqLite collection to only contain the `newNode` for (i = 1; i < removeCount; i++) { delete elementsToRemove[i]; } elementsToRemove[0] = newNode; elementsToRemove.length = 1; }
javascript
{ "resource": "" }
q60174
encodePath
validation
function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { // decode forward slashes to prevent them from being double encoded segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/')); } return segments.join('/'); }
javascript
{ "resource": "" }
q60175
isPure
validation
function isPure(node, parentIsPure) { switch (node.type) { // Computed members might invoke a stateful toString() case AST.MemberExpression: if (node.computed) { return false; } break; // Unary always convert to primative case AST.UnaryExpression: return PURITY_ABSOLUTE; // The binary + operator can invoke a stateful toString(). case AST.BinaryExpression: return node.operator !== '+' ? PURITY_ABSOLUTE : false; // Functions / filters probably read state from within objects case AST.CallExpression: return false; } return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure; }
javascript
{ "resource": "" }
q60176
$$SanitizeUriProvider
validation
function $$SanitizeUriProvider() { var aHrefSanitizationWhitelist = /^\s*(https?|s?ftp|mailto|tel|file):/, imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via HTML anchor links. * * Any url due to be assigned to an `a[href]` attribute via interpolation is marked as requiring * the $sce.URL security context. When interpolation occurs a call is made to `$sce.trustAsUrl(url)` * which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize the potentially malicious URL. * * If the URL matches the `aHrefSanitizationWhitelist` regular expression, it is returned unchanged. * * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written * to the DOM it is inactive and potentially malicious code will not be executed. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.aHrefSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { aHrefSanitizationWhitelist = regexp; return this; } return aHrefSanitizationWhitelist; }; /** * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via HTML image src links. * * Any URL due to be assigned to an `img[src]` attribute via interpolation is marked as requiring * the $sce.MEDIA_URL security context. When interpolation occurs a call is made to * `$sce.trustAsMediaUrl(url)` which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize * the potentially malicious URL. * * If the URL matches the `aImgSanitizationWhitelist` regular expression, it is returned unchanged. * * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written * to the DOM it is inactive and potentially malicious code will not be executed. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.imgSrcSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { imgSrcSanitizationWhitelist = regexp; return this; } return imgSrcSanitizationWhitelist; }; this.$get = function() { return function sanitizeUri(uri, isMediaUrl) { // if (!uri) return uri; var regex = isMediaUrl ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; var normalizedVal = urlResolve(uri && uri.trim()).href; if (normalizedVal !== '' && !normalizedVal.match(regex)) { return 'unsafe:' + normalizedVal; } return uri; }; }; }
javascript
{ "resource": "" }
q60177
urlsAreSameOrigin
validation
function urlsAreSameOrigin(url1, url2) { url1 = urlResolve(url1); url2 = urlResolve(url2); return (url1.protocol === url2.protocol && url1.host === url2.host); }
javascript
{ "resource": "" }
q60178
getBaseUrl
validation
function getBaseUrl() { if (window.document.baseURI) { return window.document.baseURI; } // `document.baseURI` is available everywhere except IE if (!baseUrlParsingNode) { baseUrlParsingNode = window.document.createElement('a'); baseUrlParsingNode.href = '.'; // Work-around for IE bug described in Implementation Notes. The fix in `urlResolve()` is not // suitable here because we need to track changes to the base URL. baseUrlParsingNode = baseUrlParsingNode.cloneNode(false); } return baseUrlParsingNode.href; }
javascript
{ "resource": "" }
q60179
formatNumber
validation
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (!(isString(number) || isNumber(number)) || isNaN(number)) return ''; var isInfinity = !isFinite(number); var isZero = false; var numStr = Math.abs(number) + '', formattedText = '', parsedNumber; if (isInfinity) { formattedText = '\u221e'; } else { parsedNumber = parse(numStr); roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac); var digits = parsedNumber.d; var integerLen = parsedNumber.i; var exponent = parsedNumber.e; var decimals = []; isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true); // pad zeros for small numbers while (integerLen < 0) { digits.unshift(0); integerLen++; } // extract decimals digits if (integerLen > 0) { decimals = digits.splice(integerLen, digits.length); } else { decimals = digits; digits = [0]; } // format the integer digits with grouping separators var groups = []; if (digits.length >= pattern.lgSize) { groups.unshift(digits.splice(-pattern.lgSize, digits.length).join('')); } while (digits.length > pattern.gSize) { groups.unshift(digits.splice(-pattern.gSize, digits.length).join('')); } if (digits.length) { groups.unshift(digits.join('')); } formattedText = groups.join(groupSep); // append the decimal digits if (decimals.length) { formattedText += decimalSep + decimals.join(''); } if (exponent) { formattedText += 'e+' + exponent; } } if (number < 0 && !isZero) { return pattern.negPre + formattedText + pattern.negSuf; } else { return pattern.posPre + formattedText + pattern.posSuf; } }
javascript
{ "resource": "" }
q60180
defaults
validation
function defaults(dst, src) { forEach(src, function(value, key) { if (!isDefined(dst[key])) { dst[key] = value; } }); }
javascript
{ "resource": "" }
q60181
validation
function(playAnimation) { if (!animationCompleted) { animationPaused = !playAnimation; if (timings.animationDuration) { var value = blockKeyframeAnimations(node, animationPaused); if (animationPaused) { temporaryStyles.push(value); } else { removeFromArray(temporaryStyles, value); } } } else if (animationPaused && playAnimation) { animationPaused = false; close(); } }
javascript
{ "resource": "" }
q60182
validation
function(scope, $element, attrs, ctrl, $transclude) { var previousElement, previousScope; scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) { if (previousElement) { $animate.leave(previousElement); } if (previousScope) { previousScope.$destroy(); previousScope = null; } if (value || value === 0) { $transclude(function(clone, childScope) { previousElement = clone; previousScope = childScope; $animate.enter(clone, null, $element); }); } }); }
javascript
{ "resource": "" }
q60183
validation
function($scope, element, attrs) { var src = attrs.ngMessagesInclude || attrs.src; $templateRequest(src).then(function(html) { if ($scope.$$destroyed) return; if (isString(html) && !html.trim()) { // Empty template - nothing to compile replaceElementWithMarker(element, src); } else { // Non-empty template - compile and link $compile(html)($scope, function(contents) { element.after(contents); replaceElementWithMarker(element, src); }); } }); }
javascript
{ "resource": "" }
q60184
locale_locales__getSetGlobalLocale
validation
function locale_locales__getSetGlobalLocale (key, values) { var data; if (key) { if (typeof values === 'undefined') { data = locale_locales__getLocale(key); } else { data = defineLocale(key, values); } if (data) { // moment.duration._locale = moment._locale = data; globalLocale = data; } } return globalLocale._abbr; }
javascript
{ "resource": "" }
q60185
configFromString
validation
function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; utils_hooks__hooks.createFromInputFallback(config); } }
javascript
{ "resource": "" }
q60186
duration_humanize__getSetRelativeTimeThreshold
validation
function duration_humanize__getSetRelativeTimeThreshold (threshold, limit) { if (thresholds[threshold] === undefined) { return false; } if (limit === undefined) { return thresholds[threshold]; } thresholds[threshold] = limit; return true; }
javascript
{ "resource": "" }
q60187
validation
function(element, parent, options) { options = options || {}; $mdUtil.disableScrollAround._count = Math.max(0, $mdUtil.disableScrollAround._count || 0); $mdUtil.disableScrollAround._count++; if ($mdUtil.disableScrollAround._restoreScroll) { return $mdUtil.disableScrollAround._restoreScroll; } var body = $document[0].body; var restoreBody = disableBodyScroll(); var restoreElement = disableElementScroll(parent); return $mdUtil.disableScrollAround._restoreScroll = function() { if (--$mdUtil.disableScrollAround._count <= 0) { restoreBody(); restoreElement(); delete $mdUtil.disableScrollAround._restoreScroll; } }; /** * Creates a virtual scrolling mask to prevent touchmove, keyboard, scrollbar clicking, * and wheel events */ function disableElementScroll(element) { element = angular.element(element || body); var scrollMask; if (options.disableScrollMask) { scrollMask = element; } else { scrollMask = angular.element( '<div class="md-scroll-mask">' + ' <div class="md-scroll-mask-bar"></div>' + '</div>'); element.append(scrollMask); } scrollMask.on('wheel', preventDefault); scrollMask.on('touchmove', preventDefault); return function restoreElementScroll() { scrollMask.off('wheel'); scrollMask.off('touchmove'); if (!options.disableScrollMask && scrollMask[0].parentNode ) { scrollMask[0].parentNode.removeChild(scrollMask[0]); } }; function preventDefault(e) { e.preventDefault(); } } // Converts the body to a position fixed block and translate it to the proper scroll position function disableBodyScroll() { var documentElement = $document[0].documentElement; var prevDocumentStyle = documentElement.style.cssText || ''; var prevBodyStyle = body.style.cssText || ''; var viewportTop = $mdUtil.getViewportTop(); var clientWidth = body.clientWidth; var hasVerticalScrollbar = body.scrollHeight > body.clientHeight + 1; // Scroll may be set on <html> element (for example by overflow-y: scroll) // but Chrome is reporting the scrollTop position always on <body>. // scrollElement will allow to restore the scrollTop position to proper target. var scrollElement = documentElement.scrollTop > 0 ? documentElement : body; if (hasVerticalScrollbar) { angular.element(body).css({ position: 'fixed', width: '100%', top: -viewportTop + 'px' }); } if (body.clientWidth < clientWidth) { body.style.overflow = 'hidden'; } // This should be applied after the manipulation to the body, because // adding a scrollbar can potentially resize it, causing the measurement // to change. if (hasVerticalScrollbar) { documentElement.style.overflowY = 'scroll'; } return function restoreScroll() { // Reset the inline style CSS to the previous. body.style.cssText = prevBodyStyle; documentElement.style.cssText = prevDocumentStyle; // The scroll position while being fixed scrollElement.scrollTop = viewportTop; }; } }
javascript
{ "resource": "" }
q60188
sanitizeAndConfigure
validation
function sanitizeAndConfigure(scope, options) { var selectEl = element.find('md-select-menu'); if (!options.target) { throw new Error($mdUtil.supplant(ERROR_TARGET_EXPECTED, [options.target])); } angular.extend(options, { isRemoved: false, target: angular.element(options.target), //make sure it's not a naked dom node parent: angular.element(options.parent), selectEl: selectEl, contentEl: element.find('md-content'), optionNodes: selectEl[0].getElementsByTagName('md-option') }); }
javascript
{ "resource": "" }
q60189
refreshPosition
validation
function refreshPosition(item) { // Find the top of an item by adding to the offsetHeight until we reach the // content element. var current = item.element[0]; item.top = 0; item.left = 0; item.right = 0; while (current && current !== contentEl[0]) { item.top += current.offsetTop; item.left += current.offsetLeft; if ( current.offsetParent ){ item.right += current.offsetParent.offsetWidth - current.offsetWidth - current.offsetLeft; //Compute offsetRight } current = current.offsetParent; } item.height = item.element.prop('offsetHeight'); var defaultVal = $mdUtil.floatingScrollbars() ? '0' : undefined; $mdUtil.bidi(item.clone, 'margin-left', item.left, defaultVal); $mdUtil.bidi(item.clone, 'margin-right', defaultVal, item.right); }
javascript
{ "resource": "" }
q60190
MdToastController
validation
function MdToastController($mdToast, $scope) { // For compatibility with AngularJS 1.6+, we should always use the $onInit hook in // interimElements. The $mdCompiler simulates the $onInit hook for all versions. this.$onInit = function() { var self = this; if (self.highlightAction) { $scope.highlightClasses = [ 'md-highlight', self.highlightClass ]; } $scope.$watch(function() { return activeToastContent; }, function() { self.content = activeToastContent; }); this.resolve = function() { $mdToast.hide( ACTION_RESOLVE ); }; }; }
javascript
{ "resource": "" }
q60191
positionDropdown
validation
function positionDropdown () { if (!elements) { return $mdUtil.nextTick(positionDropdown, false, $scope); } var dropdownHeight = ($scope.dropdownItems || MAX_ITEMS) * ITEM_HEIGHT; var hrect = elements.wrap.getBoundingClientRect(), vrect = elements.snap.getBoundingClientRect(), root = elements.root.getBoundingClientRect(), top = vrect.bottom - root.top, bot = root.bottom - vrect.top, left = hrect.left - root.left, width = hrect.width, offset = getVerticalOffset(), position = $scope.dropdownPosition, styles; // Automatically determine dropdown placement based on available space in viewport. if (!position) { position = (top > bot && root.height - top - MENU_PADDING < dropdownHeight) ? 'top' : 'bottom'; } // Adjust the width to account for the padding provided by `md-input-container` if ($attrs.mdFloatingLabel) { left += INPUT_PADDING; width -= INPUT_PADDING * 2; } styles = { left: left + 'px', minWidth: width + 'px', maxWidth: Math.max(hrect.right - root.left, root.right - hrect.left) - MENU_PADDING + 'px' }; if (position === 'top') { styles.top = 'auto'; styles.bottom = bot + 'px'; styles.maxHeight = Math.min(dropdownHeight, hrect.top - root.top - MENU_PADDING) + 'px'; } else { var bottomSpace = root.bottom - hrect.bottom - MENU_PADDING + $mdUtil.getViewportTop(); styles.top = (top - offset) + 'px'; styles.bottom = 'auto'; styles.maxHeight = Math.min(dropdownHeight, bottomSpace) + 'px'; } elements.$.scrollContainer.css(styles); $mdUtil.nextTick(correctHorizontalAlignment, false); /** * Calculates the vertical offset for floating label examples to account for ngMessages * @returns {number} */ function getVerticalOffset () { var offset = 0; var inputContainer = $element.find('md-input-container'); if (inputContainer.length) { var input = inputContainer.find('input'); offset = inputContainer.prop('offsetHeight'); offset -= input.prop('offsetTop'); offset -= input.prop('offsetHeight'); // add in the height left up top for the floating label text offset += inputContainer.prop('offsetTop'); } return offset; } /** * Makes sure that the menu doesn't go off of the screen on either side. */ function correctHorizontalAlignment () { var dropdown = elements.scrollContainer.getBoundingClientRect(), styles = {}; if (dropdown.right > root.right - MENU_PADDING) { styles.left = (hrect.right - dropdown.width) + 'px'; } elements.$.scrollContainer.css(styles); } }
javascript
{ "resource": "" }
q60192
correctHorizontalAlignment
validation
function correctHorizontalAlignment () { var dropdown = elements.scrollContainer.getBoundingClientRect(), styles = {}; if (dropdown.right > root.right - MENU_PADDING) { styles.left = (hrect.right - dropdown.width) + 'px'; } elements.$.scrollContainer.css(styles); }
javascript
{ "resource": "" }
q60193
gatherElements
validation
function gatherElements () { var snapWrap = gatherSnapWrap(); elements = { main: $element[0], scrollContainer: $element[0].querySelector('.md-virtual-repeat-container'), scroller: $element[0].querySelector('.md-virtual-repeat-scroller'), ul: $element.find('ul')[0], input: $element.find('input')[0], wrap: snapWrap.wrap, snap: snapWrap.snap, root: document.body }; elements.li = elements.ul.getElementsByTagName('li'); elements.$ = getAngularElements(elements); inputModelCtrl = elements.$.input.controller('ngModel'); }
javascript
{ "resource": "" }
q60194
selectedItemChange
validation
function selectedItemChange (selectedItem, previousSelectedItem) { updateModelValidators(); if (selectedItem) { getDisplayValue(selectedItem).then(function (val) { $scope.searchText = val; handleSelectedItemChange(selectedItem, previousSelectedItem); }); } else if (previousSelectedItem && $scope.searchText) { getDisplayValue(previousSelectedItem).then(function(displayValue) { // Clear the searchText, when the selectedItem is set to null. // Do not clear the searchText, when the searchText isn't matching with the previous // selected item. if (angular.isString($scope.searchText) && displayValue.toString().toLowerCase() === $scope.searchText.toLowerCase()) { $scope.searchText = ''; } }); } if (selectedItem !== previousSelectedItem) announceItemChange(); }
javascript
{ "resource": "" }
q60195
handleSearchText
validation
function handleSearchText (searchText, previousSearchText) { ctrl.index = getDefaultIndex(); // do nothing on init if (searchText === previousSearchText) return; updateModelValidators(); getDisplayValue($scope.selectedItem).then(function (val) { // clear selected item if search text no longer matches it if (searchText !== val) { $scope.selectedItem = null; // trigger change event if available if (searchText !== previousSearchText) announceTextChange(); // cancel results if search text is not long enough if (!isMinLengthMet()) { ctrl.matches = []; setLoading(false); reportMessages(false, ReportType.Count); } else { handleQuery(); } } }); }
javascript
{ "resource": "" }
q60196
keydown
validation
function keydown (event) { switch (event.keyCode) { case $mdConstant.KEY_CODE.DOWN_ARROW: if (ctrl.loading) return; event.stopPropagation(); event.preventDefault(); ctrl.index = Math.min(ctrl.index + 1, ctrl.matches.length - 1); updateScroll(); reportMessages(false, ReportType.Selected); break; case $mdConstant.KEY_CODE.UP_ARROW: if (ctrl.loading) return; event.stopPropagation(); event.preventDefault(); ctrl.index = ctrl.index < 0 ? ctrl.matches.length - 1 : Math.max(0, ctrl.index - 1); updateScroll(); reportMessages(false, ReportType.Selected); break; case $mdConstant.KEY_CODE.TAB: // If we hit tab, assume that we've left the list so it will close onListLeave(); if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return; select(ctrl.index); break; case $mdConstant.KEY_CODE.ENTER: if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return; if (hasSelection()) return; event.stopPropagation(); event.preventDefault(); select(ctrl.index); break; case $mdConstant.KEY_CODE.ESCAPE: event.preventDefault(); // Prevent browser from always clearing input if (!shouldProcessEscape()) return; event.stopPropagation(); clearSelectedItem(); if ($scope.searchText && hasEscapeOption('clear')) { clearSearchText(); } // Manually hide (needed for mdNotFound support) ctrl.hidden = true; if (hasEscapeOption('blur')) { // Force the component to blur if they hit escape doBlur(true); } break; default: } }
javascript
{ "resource": "" }
q60197
getDisplayValue
validation
function getDisplayValue (item) { return $q.when(getItemText(item) || item).then(function(itemText) { if (itemText && !angular.isString(itemText)) { $log.warn('md-autocomplete: Could not resolve display value to a string. ' + 'Please check the `md-item-text` attribute.'); } return itemText; }); /** * Getter function to invoke user-defined expression (in the directive) * to convert your object to a single string. */ function getItemText (item) { return (item && $scope.itemText) ? $scope.itemText(getItemAsNameVal(item)) : null; } }
javascript
{ "resource": "" }
q60198
updateScroll
validation
function updateScroll () { if (!elements.li[0]) return; var height = elements.li[0].offsetHeight, top = height * ctrl.index, bot = top + height, hgt = elements.scroller.clientHeight, scrollTop = elements.scroller.scrollTop; if (top < scrollTop) { scrollTo(top); } else if (bot > scrollTop + hgt) { scrollTo(bot - hgt); } }
javascript
{ "resource": "" }
q60199
MdChipsCtrl
validation
function MdChipsCtrl ($scope, $attrs, $mdConstant, $log, $element, $timeout, $mdUtil, $exceptionHandler) { /** @type {$timeout} **/ this.$timeout = $timeout; /** @type {Object} */ this.$mdConstant = $mdConstant; /** @type {angular.$scope} */ this.$scope = $scope; /** @type {angular.$scope} */ this.parent = $scope.$parent; /** @type {$mdUtil} */ this.$mdUtil = $mdUtil; /** @type {$log} */ this.$log = $log; /** @type {$exceptionHandler} */ this.$exceptionHandler = $exceptionHandler; /** @type {$element} */ this.$element = $element; /** @type {$attrs} */ this.$attrs = $attrs; /** @type {angular.NgModelController} */ this.ngModelCtrl = null; /** @type {angular.NgModelController} */ this.userInputNgModelCtrl = null; /** @type {MdAutocompleteCtrl} */ this.autocompleteCtrl = null; /** @type {Element} */ this.userInputElement = null; /** @type {Array.<Object>} */ this.items = []; /** @type {number} */ this.selectedChip = -1; /** @type {string} */ this.enableChipEdit = $mdUtil.parseAttributeBoolean($attrs.mdEnableChipEdit); /** @type {string} */ this.addOnBlur = $mdUtil.parseAttributeBoolean($attrs.mdAddOnBlur); /** * The text to be used as the aria-label for the input. * @type {string} */ this.inputAriaLabel = 'Chips input.'; /** * Hidden hint text to describe the chips container. Used to give context to screen readers when * the chips are readonly and the input cannot be selected. * * @type {string} */ this.containerHint = 'Chips container. Use arrow keys to select chips.'; /** * Hidden hint text for how to delete a chip. Used to give context to screen readers. * @type {string} */ this.deleteHint = 'Press delete to remove this chip.'; /** * Hidden label for the delete button. Used to give context to screen readers. * @type {string} */ this.deleteButtonLabel = 'Remove'; /** * Model used by the input element. * @type {string} */ this.chipBuffer = ''; /** * Whether to use the transformChip expression to transform the chip buffer * before appending it to the list. * @type {boolean} */ this.useTransformChip = false; /** * Whether to use the onAdd expression to notify of chip additions. * @type {boolean} */ this.useOnAdd = false; /** * Whether to use the onRemove expression to notify of chip removals. * @type {boolean} */ this.useOnRemove = false; /** * The ID of the chips wrapper which is used to build unique IDs for the chips and the aria-owns * attribute. * * Defaults to '_md-chips-wrapper-' plus a unique number. * * @type {string} */ this.wrapperId = ''; /** * Array of unique numbers which will be auto-generated any time the items change, and is used to * create unique IDs for the aria-owns attribute. * * @type {Array<number>} */ this.contentIds = []; /** * The index of the chip that should have it's `tabindex` property set to `0` so it is selectable * via the keyboard. * * @type {number} */ this.ariaTabIndex = null; /** * After appending a chip, the chip will be focused for this number of milliseconds before the * input is refocused. * * **Note:** This is **required** for compatibility with certain screen readers in order for * them to properly allow keyboard access. * * @type {number} */ this.chipAppendDelay = DEFAULT_CHIP_APPEND_DELAY; /** * Collection of functions to call to un-register watchers * * @type {Array} */ this.deRegister = []; this.init(); }
javascript
{ "resource": "" }