_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q43500
train
function(ops, callback) { if(!callback) callback = function() { }; //name of the script to run for supervisord if(!ops.name) ops.name = 'undefined'; var supervisordName = this._name(ops.name); //script exists? split it apart if(ops.script) { ops.directory = ops.script.split('.').length == 1 ? ops.script :path.dirname(ops.script); try { var package = JSON.parse(fs.readFileSync(ops.directory + '/package.json')); if(!package.main && package.bin) { for(var binName in package.bin) { ops.command = ops.directory + '/' + package.bin[binName]; } } } catch(e) { } if(!ops.command) ops.command = 'node ' + ops.script +' '+ (ops.args || []).join(' '); } var envStr; if(ops.environment) { var envBuffer = []; for(var property in ops.environment) { envBuffer.push(property + '=' + ops.environment[property]); } envStr = envBuffer.join(','); } //directory to script - chdir for supervisord //if(!ops.directory) return callback('directory is not provided'); //the command to use for running supervisord if(!ops.command) return callback('command not provided'); if(!ops.name) return callback('Name not provided'); var self = this; var update = this._query({ supervisordName: supervisordName, name: ops.name, directory: ops.directory, command: ops.command, environment: envStr, stdout_logfile: this.logsDir + '/' + supervisordName + '.log', stderr_logfile: this.logsDir + '/' + supervisordName + '-err.log' }); //insert into the beet db this._collection.update({ _id: this._id(supervisordName) }, { $set: update }, { upsert: true }, function(err, result){ if(callback) callback(err, result); }); }
javascript
{ "resource": "" }
q43501
train
function(ops, callback) { var search = typeof ops == 'string' ? { name: ops } : ops, query = this._query(search), self = this; //stop the app in case... self.stop(search.name, function(err, result) { if(callback) callback(err, result); }); //remove the app self._collection.remove(query, function(err, result){ }); }
javascript
{ "resource": "" }
q43502
ForwardMochaReporter
train
function ForwardMochaReporter(mochaRunner, options) { Base.call(this, mochaRunner, options); forwardEvent(mochaRunner, runner, 'start'); forwardEvent(mochaRunner, runner, 'suite'); forwardEvent(mochaRunner, runner, 'suite end'); forwardEvent(mochaRunner, runner, 'pending'); forwardEvent(mochaRunner, runner, 'pass'); forwardEvent(mochaRunner, runner, 'fail'); // when runner output should be captured, it is done for the end event only. mochaRunner.on('end', function () { try { if (outputFile) { console.log(outputFile); captureStdout(outputFile); } var args = Array.prototype.slice.call(arguments, 0); runner.emit.apply(runner, ['end'].concat(args)); releaseStdout(); } catch (e) { releaseStdout(); } }); }
javascript
{ "resource": "" }
q43503
logtime
train
function logtime() { var d = new Date() , space = ' ' , delimiter = ':' , str = d.toString() , month = str.split(' ')[1]; return d.getDate() + space + month + space + d.getHours() + delimiter + pad(d.getMinutes()) + delimiter + pad(d.getSeconds()) + '.' + pad(d.getMilliseconds(), 3); }
javascript
{ "resource": "" }
q43504
Console
train
function Console (lc2, position, debug) { this.lc2 = lc2 this.position = position this.debug = debug || false this.name = 'Console' this.lastReadKey = 0 this.inputBuffer = 0 this.outputKey = 0 this.displayReady = 1 }
javascript
{ "resource": "" }
q43505
train
function() { FS.readFile(path, options.encoding, function(err, text) { if (err) { // Forward the error return callback(err); } // Success callback(null, text.toString()); }); }
javascript
{ "resource": "" }
q43506
pickup
train
function pickup (/*len, dict || dict */) { var str = '', pos; var len, dict; if (arguments.length === 1) { dict = arguments[0]; len = 1; } else if (arguments.length === 2) { len = arguments[0]; dict = arguments[1]; } else { return string(); } for (var i=0; i< len; i++) { pos = dice(dict.length - 1); str += dict.substring(pos, pos + 1); } return str; }
javascript
{ "resource": "" }
q43507
train
function(x, reload){ // Get the numeric ID for the module to load. var id = modules[name][1][x]; // If there's a matching module in the testability cache, return it. if (_testability_cache_[x]) return _testability_cache_[x]; // Return recursively... the module's export will be in the cache // after this. return newRequire(id ? id : x, undefined, reload); }
javascript
{ "resource": "" }
q43508
groupMembershipMiddleware
train
function groupMembershipMiddleware(groups) { if (typeof groups === 'string') { groups = [groups]; } return function hasGroupMembership(req, res, next) { if (req.locals.user) { const userGroups = req.locals.user.groups || []; for (let group of groups) { if (userGroups.indexOf(group) !== -1) { debug(`User has the '${group}' Group.`); return next(); } } } debug(`User is not a member of one of [${groups.join(',')}] Group(s).`); next(new restifyErrors.ForbiddenError('No execute permissions on endpoint')); } }
javascript
{ "resource": "" }
q43509
isLoggedInMiddleware
train
function isLoggedInMiddleware() { return function isLoggedIn(req, res, next) { const AclUser = mongoose.model("TransomAclUser"); if ((req.headers && req.headers.authorization) || (req.body && req.body.access_token) || (req.query && req.query.access_token)) { // Verify the authorization token or fail. passport.authenticate('bearer', { session: false }, function (err, user, info) { if (err) { return next(err); } if (!user || (info && info.indexOf("invalid_token") >= 0)) { // Something didn't work out. Token Expired / Denied. debug("NOT LoggedIn - Invalid"); return next(new restifyErrors.InvalidCredentialsError("Incorrect or expired credentials")); } else { // Properly authenticated! return next(); } })(req, res, next); } else { // debug("No Authorization header or query access_token. Trying Anonymous."); if (localuser.anonymous !== false) { // Attempt anonymous login, if possible; AclUser.findOne({ 'username': 'anonymous', 'active': true }, function (err, user) { if (err) { return next(err); } if (user) { req.locals = req.locals || {}; req.locals.user = user; return next(); } // Oh no, not authenticated debug("No bearer token provided or query access_token. No Anonymous user available."); return next(new restifyErrors.InvalidCredentialsError("No bearer token provided or query access_token. No Anonymous user available.")); }); } else { debug("No bearer token provided or query access_token."); return next(new restifyErrors.InvalidCredentialsError("No bearer token provided or query access_token.")); } } } }
javascript
{ "resource": "" }
q43510
prepareContext
train
function prepareContext(screenstoryRunner, options, context, file, mochaRunner) { debug('prepare context for %s', file); var wdOptions = { desiredCapabilities: options.wdCapabilities, host: options.wdHost, port: options.wdPort, user: options.wdUsername, key: options.wdKey, logLevel: options.wdLogLevel }; context.url = options.url; // @return webdriverio context.newClient = function () { // init client var client = webdriverio.remote(wdOptions) .init(); // fix resolution if (options.resolution) { client .setViewportSize(options.resolution, true); } // add extensions screenstoryRunner.extensions.forEach(function (extension) { Object.keys(extension).forEach(function (key) { debug('+ Add command "%s"', key); client.addCommand(key, extension[key]); }); }); screenstoryRunner.emitAsync('new client', client, function (err) { if (err) { debug('While executing "new client" event, following error occured'); debug(err); console.log(err); } }); return client; }; // add globals options.global.forEach(function (globalName) { addGlobal(context, globalName); }); }
javascript
{ "resource": "" }
q43511
train
function(req, requiredParams) { // Find all missing parameters var missingParams = []; _.forEach(requiredParams, function(requiredParam) { if ( Mixins.isNullOrUndefined(req.params && req.params[requiredParam]) && Mixins.isNullOrUndefined(req.query && req.query[requiredParam]) && Mixins.isNullOrUndefined(req.body && req.body[requiredParam]) ) { missingParams.push(requiredParam); } }); return missingParams; }
javascript
{ "resource": "" }
q43512
train
function(missingParams) { var errParts = []; missingParams = _.map(missingParams, function(missingParam) { return '`' + missingParam + '`'; }); errParts.push("Missing"); errParts.push(missingParams.join(', ')); errParts.push("parameter(s)."); return new MuniError(errParts.join(' '), 400); }
javascript
{ "resource": "" }
q43513
train
function() { // Used for de-duping var paths = {}; // Each controller has a `routes` object // Connect all routes defined in controllers _.forEach(router.controllers, function(controller) { _.forEach(controller.routes, function(route, method) { _.forEach(route, function(routeOptions, path) { // If path/method has already been defined, skip if (paths[path] === method) { debug.warn('Skipping duplicate route: [%s] %s', method, path); return; } // If no route action is defined, skip if (!routeOptions.action) { debug.warn('No action defined for route: [%s] %s', method, path); return; } // Setup controller scoped middleware // These apply to all routes in the controller var pre = _.invokeMap(controller.pre, 'bind', controller) || []; var before = _.invokeMap(controller.before, 'bind', controller) || []; var after = _.invokeMap(controller.after, 'bind', controller) || []; // Setup route scoped middleware // These apply only to this route var middleware = routeOptions.middleware || []; // Build the route handler (callback) var handler = router._buildHandler(controller, routeOptions); // Connect the route router[method](path, pre, middleware, before, handler, after); // Add route to set of connected routes router.routes.push({ url: router.url, method: method, path: path }); // Use for de-duping paths[path] = method; }); }); }); // Debug logging _.forEach(router.routes, function(route) { debug.info('Route [%s] %s', route.method, route.url + route.path); }); }
javascript
{ "resource": "" }
q43514
toRooms
train
function toRooms(data) { var i, rooms; rooms = []; for (i = 0; i < data.rooms.length; i++) { rooms.push(new Room(connection, data.rooms[i])); } return rooms; }
javascript
{ "resource": "" }
q43515
parseActiveChildren
train
function parseActiveChildren(values, active) { let activeChild = false; const activeValues = values.map(function (val) { const childrenTraversed = (val.children && parseActiveChildren(val.children, active)); const isActive = val.value === active || Boolean(childrenTraversed && childrenTraversed.hasActiveChild); if (isActive) { activeChild = true; } const activatedChild = Object.assign({}, val, { active: isActive }); if (val.children) { activatedChild.children = childrenTraversed.children; } return activatedChild; }); return { children: activeValues, hasActiveChild: activeChild }; }
javascript
{ "resource": "" }
q43516
queueLauncherKey
train
function queueLauncherKey(asKey, subprocess) { return function processTarget(targets) { return Object .keys(targets) .map(function (targetName) { return subprocess(targets[targetName]) .map(function (launcher) { launcher[asKey] = targetName; return launcher; }); }) .reduce(function (a, b) { // flatten return a.concat(b); }, []); }; }
javascript
{ "resource": "" }
q43517
generateSauceLabsKarmaCustomLaunchers
train
function generateSauceLabsKarmaCustomLaunchers(config) { return processPlatform(config) .reduce(function (memo, launcher) { var launcherName = [ SAUCELABS_PREFIX, shorty(launcher.platform), shorty(launcher.browserName), launcher.version ].join('_'); memo[launcherName] = launcher; return memo; }, {}); //// function shorty(str) { return str.indexOf(' ') === -1 ? // capitaliseFirstLetter str.charAt(0).toUpperCase() + str.slice(1) : // abbr str.match(/\b(\w)/g).join('').toUpperCase(); } }
javascript
{ "resource": "" }
q43518
separateMultiClassArffData
train
function separateMultiClassArffData(arffData, outputAttributes) { if (!Array.isArray(outputAttributes) || outputAttributes.length === 0) { outputAttributes = [arffData.attributes[arffData.attributes.length - 1]]; } outputAttributes.forEach((attribute) => { if (arffData.types[attribute].hasOwnProperty('oneof') && arffData.types[attribute].oneof.length > 2) { arffData.attributes.splice(arffData.attributes.indexOf(attribute), 1); outputAttributes.splice(arffData.attributes.indexOf(attribute), 1); arffData.types[attribute].oneof.forEach((oneofValue, oneofIndex) => { const newAttributeName = attribute + '__' + oneofValue; outputAttributes.push(newAttributeName); arffData.attributes.push(newAttributeName); arffData.types[newAttributeName] = {type: 'nominal', oneof: ['n', 'y']}; arffData.data.forEach((entry) => { if (entry[attribute] == oneofIndex) { entry[newAttributeName] = 1; } else { entry[newAttributeName] = 0; } }); }); } }); return outputAttributes; }
javascript
{ "resource": "" }
q43519
loadArff
train
function loadArff(fileName, callback) { ARFF.load(fileName, (error, data) => { if (error) { throw new Error(filename + error); } callback(data); }); return 'THIS IS ASYNCHRONOUS'; }
javascript
{ "resource": "" }
q43520
random
train
function random() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var range = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 36; return String.random(length, range); }
javascript
{ "resource": "" }
q43521
train
function(obj, name, callback){ if (!obj) return Belt.noop; var s = _.pick(obj, B._api_objects[name + 's']); var stream = B._gateway[name].search(function(search){ _.each(s, function(v, k){ if (_.isObject(v)) return search[k].call(search)[v.op](v.val, v.val2); return search[k].call(search).is(v); }); }) , results = [] , err; stream.on('data', function(r){ return results.push(r); }); stream.on('error', function(e){ return err = e; }); return stream.on('end', function(){ return callback(err, results); }); }
javascript
{ "resource": "" }
q43522
xcatalog
train
function xcatalog(id) { const definition = definitions.get(id); if (!definition) { throw new TypeError("No definition for: " + id); } if (!definition.fac) { definition.fac = build(definition, definition.dep.map(xcatalog)); } return definition.fac(); }
javascript
{ "resource": "" }
q43523
initBrowser
train
function initBrowser() { if (window.chrome) { Object.assign(module.exports, chromeConstants); } else { Object.assign(module.exports, braveConstants); } }
javascript
{ "resource": "" }
q43524
generateCodeDocs
train
function generateCodeDocs() { config.codeFiles.forEach(function (jsFile) { var jf = [jsFile]; documentation(jf, {}, function (err, result) { documentation.formats.md(result, {}, function (err, md) { // Write to file fs.writeFile(path.resolve(__dirname, config.docFolder + "/" + jsFile + ".md"), md); }); }); }); }
javascript
{ "resource": "" }
q43525
Stylesheet
train
function Stylesheet() { var styleElement = document.createElement('style'), head = document.getElementsByTagName('head')[0]; head.appendChild(styleElement); // Safari does not see the new stylesheet unless you append something. // However! IE will blow chunks, so ... filter it thusly: if (!window.createPopup) { styleElement.appendChild(document.createTextNode('')); } this.sheet = document.styleSheets[document.styleSheets.length - 1]; }
javascript
{ "resource": "" }
q43526
train
function (validations) { if (!validations) { return this; } if (!this.validations) { this.validations = []; } var that = this; _.isArray(validations) || (validations = [ validations ]); _.each(validations, function (validation) { that.validations.push(validation); }); return this; }
javascript
{ "resource": "" }
q43527
train
function (flagOrBuilder) { if (_.isFunction(flagOrBuilder)) { this.object(flagOrBuilder); } if (flagOrBuilder == null || flagOrBuilder) { this.isArray = true; } else { delete this.isArray; } return this; }
javascript
{ "resource": "" }
q43528
train
function (schema, process) { var that = this; if (!(schema instanceof Schema)) { throw new Error('first argument must be instance of Schema'); } if (process) { var r = process.call(this, schema); if (r != null && !r) { return this; } } _.each(schema.fields, function (fieldSchema, fieldName) { that.field(fieldName).like(fieldSchema, process); }); if (process) { return this; } _.each(schema, function (value, key) { if (/^(_.*|fields)$/.test(key)) { return; } that[key] = _.cloneDeep(value); }); return this; }
javascript
{ "resource": "" }
q43529
train
function (name, validation) { if (name == null && validation == null) { delete this.isRequired; return this; } return this.field(name).validate(validation); }
javascript
{ "resource": "" }
q43530
train
function (name, validation) { if (name == null && validation == null) { this.isRequired = false; return this; } return this.field(name).validate(validation).optional(); }
javascript
{ "resource": "" }
q43531
preciseRound
train
function preciseRound(num) { var decimals = options.round ? 0 : 1; return Math.round(num * Math.pow(10, decimals)) / Math.pow(10, decimals); }
javascript
{ "resource": "" }
q43532
remToPx
train
function remToPx(remArray) { var pxArray = remArray.map(function(v) { if (regexCalc.test(v)) { return v; } else if (regexRem.test(v)) { // this one is needed to split properties like '2rem/1.5' var restValue = ''; if (/\//.test(v)) { restValue = v.match(/\/.*/); } // replace 'rem' and anything that comes after it, we'll repair this later var unitlessValue = v.replace(/rem.*/, ''); var pxValue = preciseRound(unitlessValue * rootSize) + 'px'; var newValue = restValue ? pxValue + restValue : pxValue; remFound++; return newValue; } return v; }).join(' '); return pxArray; }
javascript
{ "resource": "" }
q43533
createBaseSize
train
function createBaseSize(value) { if (/px/.test(value)) { return value.replace(/px/, ''); } if (/em|rem/.test(value)) { return value.replace(/em|rem/, '') * 16; } if (/%/.test(value)) { return value.replace(/%/, '')/100 * 16; } }
javascript
{ "resource": "" }
q43534
findRoot
train
function findRoot(r) { r.selectors.forEach(function(s) { // look for 'html' selectors if (regexHtml.test(s)) { r.declarations.forEach(function(d) { var foundSize = false; // look for the 'font' property if (d.property === 'font' && regexFont.test(d.value)) { foundSize = d.value.match(regexFont)[1]; } // look for the 'font-size' property else if (d.property === 'font-size') { foundSize = d.value; } // update root size if new one is found if (foundSize) { rootSize = createBaseSize(foundSize); } }); } }); }
javascript
{ "resource": "" }
q43535
findRems
train
function findRems(rule) { for (var i = 0; i < rule.declarations.length; i++) { var declaration = rule.declarations[i]; // grab values that contain 'rem' if (declaration.type === 'declaration' && isSupported(declaration) && regexRem.test(declaration.value)) { var pxValues = remToPx(declaration.value.split(/\s(?![^\(\)]*\))/)); if (options.replace) { declaration.value = pxValues; } else { var fallback = clone(declaration); fallback.value = pxValues; rule.declarations.splice(i, 0, fallback); } } } }
javascript
{ "resource": "" }
q43536
propagateError
train
function propagateError(error) { flow.pendingRejections_ += 1; return flow.timer.setTimeout(function() { flow.pendingRejections_ -= 1; flow.abortFrame_(error); }, 0); }
javascript
{ "resource": "" }
q43537
then
train
function then(opt_callback, opt_errback) { // Avoid unnecessary allocations if we weren't given any callback functions. if (!opt_callback && !opt_errback) { return promise; } // The moment a listener is registered, we consider this deferred to be // handled; the callback must handle any rejection errors. handled = true; if (pendingRejectionKey) { flow.pendingRejections_ -= 1; flow.timer.clearTimeout(pendingRejectionKey); } var deferred = new webdriver.promise.Deferred(cancel, flow); var listener = { callback: opt_callback, errback: opt_errback, fulfill: deferred.fulfill, reject: deferred.reject }; if (state == webdriver.promise.Deferred.State_.PENDING || state == webdriver.promise.Deferred.State_.BLOCKED) { listeners.push(listener); } else { notify(listener); } return deferred.promise; }
javascript
{ "resource": "" }
q43538
train
function() { var highestTag = '0.0.0'; var tags = exec('git tag'); if (tags.code !== 0) return highestTag; tags = tags.output.split('\n'); tags.forEach(function(tag) { tag = semver.valid(tag); if (tag && (!highestTag || semver.gt(tag, highestTag))) { highestTag = tag; } }); return highestTag; }
javascript
{ "resource": "" }
q43539
makeChainedWaterfallCallback
train
function makeChainedWaterfallCallback(i, fns, cb) { return function() { var args = Array.prototype.slice.call(arguments); if (args[0]) { //ie. we had an error return cb(args[0]); } if (fns[i + 1]) { //remove error arg args.shift(); args.push(makeChainedWaterfallCallback(i + 1, fns, cb)); return fns[i + 1].apply(null, args); } else { return cb.apply(null, args); } }; }
javascript
{ "resource": "" }
q43540
makeChainedCallback
train
function makeChainedCallback(i, fns, results, cb) { return function(err, result) { if (err) { return cb(err); } results[i] = result; if (fns[i + 1]) { return fns[i + 1](makeChainedCallback(i + 1, fns, results, cb)); } else { return cb(null, results); } }; }
javascript
{ "resource": "" }
q43541
makeCountNCallback
train
function makeCountNCallback(n, cb) { var count = 0, results = [], error; return function(index, err, result) { results[index] = result; if (!error && err) { error = err; return cb(err); } if (!error && ++count == n) { cb(null, results); } }; }
javascript
{ "resource": "" }
q43542
logentriesRawStream
train
function logentriesRawStream(pathname, query={}) { query = Object.assign({}, query); // If query format is not defined, we set it by default to JSON. if (!query.format) { query.format = 'json'; } // Text format is default in Logentries, in this case we remove the parameter. if (query.format === 'text') { delete query.format; } // Put default start and/or end times, if not given. if (!query.start && !query.end) { query.end = Date.now(); query.start = query.end - 15*60*1000; // 15 minutes } else if (!query.start) { query.start = query.end - 15*60*1000; } else if (!query.end) { query.end = query.start + 15*60*1000; } // Return raw stream using the download API. return request.get({ url : url.format({ protocol : 'https:', host : 'pull.logentries.com', pathname : pathname, query : query }), gzip : true, timeout : 30000 // 30 seconds }); }
javascript
{ "resource": "" }
q43543
logentriesJsonStream
train
function logentriesJsonStream(pathname, query={}) { query = Object.assign({}, query); // Force query format to JSON. query.format = 'json'; // Parse each array entry from raw stream and emit JSON objects. return pump(logentriesRawStream(pathname, query), JSONStream.parse('*')); }
javascript
{ "resource": "" }
q43544
logentriesConnect
train
function logentriesConnect(options={}) { // Define path to access specific account, log set and log. let pathname = '/' + encodeURIComponent(options.account) + '/hosts/' + encodeURIComponent(options.logset) + '/' + encodeURIComponent(options.log) + '/'; // Bind path argument in query functions. let json = logentriesJsonStream.bind(null, pathname); let raw = logentriesRawStream.bind(null, pathname); return Object.assign(json, { json : json, raw : raw }); }
javascript
{ "resource": "" }
q43545
CacheModule
train
function CacheModule(settings, cacheName, serviceHandler, serviceCallName) { if (serviceCallName == null) { serviceCallName = "call"; } settings.init("cacheModules", { expiration: { "default": 1800000 } }); this.settings = settings; this.cache = { data: {}, mtime: {}, name: cacheName }; this.service = serviceHandler; this.serviceCallName = serviceCallName; }
javascript
{ "resource": "" }
q43546
addUser
train
function addUser(db, username, password, options, callback) { const Db = require('../db'); // Did the user destroy the topology if (db.serverConfig && db.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed')); // Attempt to execute auth command executeAuthCreateUserCommand(db, username, password, options, (err, r) => { // We need to perform the backward compatible insert operation if (err && err.code === -5000) { const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); // Use node md5 generator const md5 = crypto.createHash('md5'); // Generate keys used for authentication md5.update(username + ':mongo:' + password); const userPassword = md5.digest('hex'); // If we have another db set const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; // Fetch a user collection const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); // Check if we are inserting the first user count(collection, {}, finalOptions, (err, count) => { // We got an error (f.ex not authorized) if (err != null) return handleCallback(callback, err, null); // Check if the user exists and update i const findOptions = Object.assign({ projection: { dbName: 1 } }, finalOptions); collection.find({ user: username }, findOptions).toArray(err => { // We got an error (f.ex not authorized) if (err != null) return handleCallback(callback, err, null); // Add command keys finalOptions.upsert = true; // We have a user, let's update the password or upsert if not updateOne( collection, { user: username }, { $set: { user: username, pwd: userPassword } }, finalOptions, err => { if (count === 0 && err) return handleCallback(callback, null, [{ user: username, pwd: userPassword }]); if (err) return handleCallback(callback, err, null); handleCallback(callback, null, [{ user: username, pwd: userPassword }]); } ); }); }); return; } if (err) return handleCallback(callback, err); handleCallback(callback, err, r); }); }
javascript
{ "resource": "" }
q43547
morphic
train
function morphic(options) { var optionsIn = options || {}; var Matcher = optionsIn.matcherCore || defaultMatcher var matcher = new Matcher(optionsIn); var generateMatchers = optionsIn.generateMatchers || defaultGenerateMatchers; var generateNamedFieldExtractors = optionsIn.generateNamedFieldExtractors || defaultGenerateNamedFieldExtractors; var extractNamedFields = optionsIn.extractNamedFields || defaultExtractNamedFields; putRecord(matcher.useFallback.bind(matcher), [], function() { throw new Error("No methods matched input " + util.inspect(arguments)); }); var morphicFunction = function morphicFunction() { var match = matcher.getRecordFromInput(arguments); var extractedFields = extractNamedFields(match.namedFields || [], arguments); var args = [extractedFields].concat(Array.from(arguments)); var action = match.action; return action.apply(this, args); }; morphicFunction.with = function() { var generatedMatchers = generateMatchers(matchers, arguments); var namedFields = generateNamedFieldExtractors(generatedMatchers); return builder( putRecord.bind( undefined, matcher.addRecord.bind(matcher, generatedMatchers), namedFields)); }; morphicFunction.otherwise = function() { return builder( putRecord.bind( undefined, matcher.useFallback.bind(matcher), [])); }; return morphicFunction; }
javascript
{ "resource": "" }
q43548
LoopChain
train
function LoopChain(cond, fns) { if (fns instanceof Array) Chain.apply(this, fns); else Chain.apply(this, slice.call(arguments, 1)); this.cond = this.wrap(cond); this.name = '(anonymous loop chain)'; }
javascript
{ "resource": "" }
q43549
Branch
train
function Branch(cond, t, f) { this.cond = this.wrap(cond); this.if_true = this.wrap(t); this.if_false = this.wrap(f); this.name = '(Unnamed Branch)'; }
javascript
{ "resource": "" }
q43550
__chain_inner
train
function __chain_inner(result) { var args = slice.call(arguments, 1); nextTick(function() { try { if (result) { var params = that.handle_args(env, that.if_true, args); params.unshift(env, after); env._fm.$push_call(helpers.fname(that.if_true, that.if_true.fn.name)); that.if_true.fn.apply(null, params); } else { var params = that.handle_args(env, that.if_false, args); params.unshift(env, after); env._fm.$push_call(helpers.fname(that.if_false, that.if_false.fn.name)); that.if_false.fn.apply(null, params); } } catch (e) { env.$throw(e); } }); }
javascript
{ "resource": "" }
q43551
replaceWith
train
function replaceWith(input, regex, content) { // Sanity check verifyParameterIsDefined(input, 'input', 'replaceWith'); verifyParameterIsDefined(regex, 'regex', 'replaceWith'); return replaceAt(normalizeValue(input), normalizeRegExp(normalizeValue(regex)), normalizeValue(content)); }
javascript
{ "resource": "" }
q43552
afterElementOpen
train
function afterElementOpen(input, element, content) { // Sanity check verifyParameterIsDefined(input, 'input', 'afterElementOpen'); verifyParameterIsDefined(element, 'element', 'afterElementOpen'); return insertAfter(normalizeValue(input), normalizeRegExp(`<${normalizeValue(element)}[^\>]*>`), normalizeValue(content)); }
javascript
{ "resource": "" }
q43553
beforeElementClose
train
function beforeElementClose(input, element, content) { // Sanity check verifyParameterIsDefined(input, 'input', beforeElementClose.name); verifyParameterIsDefined(element, 'element', beforeElementClose.name); return insertBefore(normalizeValue(input), normalizeRegExp(`<\/${normalizeValue(element)}[^\>]*>`), normalizeValue(content)); }
javascript
{ "resource": "" }
q43554
insertComment
train
function insertComment(input, element, comment) { // Sanity check verifyParameterIsDefined(input, 'input', insertComment.name); verifyParameterIsDefined(element, 'element', insertComment.name); return insertAfter(normalizeValue(input), normalizeRegExp(`<\/${normalizeValue(element)}[^\>]*>`), `/* ${normalizeValue(comment)} */`); }
javascript
{ "resource": "" }
q43555
insertAttribute
train
function insertAttribute(input, element, attributeName, attributeValue) { // Sanity check verifyParameterIsDefined(input, 'input', insertAttribute.name); verifyParameterIsDefined(element, 'element', insertAttribute.name); verifyParameterIsDefined(attributeName, 'attributeName', insertAttribute.name); return insertAfter(normalizeValue(input), normalizeRegExp(`<${normalizeValue(element)}[^\>]*`), ` ${normalizeValue(attributeName)}="${normalizeValue(attributeValue)}"`); }
javascript
{ "resource": "" }
q43556
train
function(keyname) { const _ = Struct.PriProp(keyname); if (_.__proto__) { _.__proto__ = Struct.prototype; } else { Object.keys(Struct.prototype).forEach(function(p) { Object.defineProperty(_, p, { value : Struct.prototype[p], writable : false }); }, this); } var classFunction; Object.defineProperties(_, { requires : { value: {}, writable: false }, defaults : { value: {}, writable: false }, defaultFuncs : { value: {}, writable: false }, views: { value: {}, writable: false }, parentProps: { value: [], writable: false }, enumerableDescs: { value: {}, writable: false }, classFunction : { get: function() { return classFunction; }, set: function(v) { if (classFunction === undefined) { classFunction = v; } else if (classFunction !== v) { throw new Error('cannot change classFunction.'); } } }, Modifiers : { value : Struct.Modifiers, writable : false } }); return _; }
javascript
{ "resource": "" }
q43557
Model
train
function Model(collectionName, attributes, values) { this.collectionName = collectionName; this.idAttribute = Model.getId(attributes); this.attributes = attributeValidator.validate(attributes); this.values = { }; this.virtuals = { }; // initially add the null value from all attributes for (var key in this.attributes) { this.values[key] = undefined; } // prevents from modifying values and adding properties Object.freeze(this.attributes); // prevents from adding new properties Object.seal(this.values); // sets the initial values this.set(values); }
javascript
{ "resource": "" }
q43558
drop
train
function drop (n, array) { return (n < array.length) ? slice(n, array.length, array) : [] }
javascript
{ "resource": "" }
q43559
_getRequiredAdCountForAdUnit
train
function _getRequiredAdCountForAdUnit(adUnit) { var adContainers = page.getAdContainers(adUnit); if (!adContainers.length) { return 0; } var numberOfAdsToInsert = 0; for (var i = 0; i < adContainers.length; i++) { var adContainer = adContainers[i]; numberOfAdsToInsert += adContainer.getNumberOfAdsToInsert(); } return numberOfAdsToInsert; }
javascript
{ "resource": "" }
q43560
_buildImageFields
train
function _buildImageFields(data){ var newUnits = []; for (var i = 0, len = data.length; i < len; i++){ adUnit = data[i]; // todo: create adUnit object to encapsulate this logic if ('images' in adUnit){ if ('banner' in adUnit.images){ adUnit.campaign_banner_url = adUnit.images.banner.url; } if ('icon' in adUnit.images){ adUnit.campaign_icon_url = adUnit.images.icon.url; } if ('hq_icon' in adUnit.images){ adUnit.campaign_hq_icon_url = adUnit.images.hq_icon.url; } } newUnits.push(adUnit); } return newUnits; }
javascript
{ "resource": "" }
q43561
requestAds
train
function requestAds(adUnit, callback) { var limit = _getRequiredAdCountForAdUnit(adUnit); var token = page.getToken(); var imageType = adUnit.imageType; if (typeof imageType == 'undefined'){ imageType = "hq_icon"; } var requestQuery = { "output": "json", "placement_key": adUnit.placementKey, "limit": limit, "token": token, "auto_device": 1, "image_type": imageType }; //noinspection JSUnresolvedVariable var overrides = appSettings.overrides; if (overrides && overrides.formFactor && overrides.platform && overrides.fullDeviceName && overrides.version) { delete requestQuery.auto_device; requestQuery.os = overrides.platform; requestQuery.model = overrides.fullDeviceName; requestQuery.version = overrides.version; } ajax.get({ url: appSettings.adApiBaseUrl, query: requestQuery, success: function (data) { if (data.length !== limit) { logger.warn("Tried to fetch " + limit + " ads, but received " + data.length); } data = _buildImageFields(data); callback(data); }, error: function (e) { logger.wtf('An error occurred trying to fetch ads'); } }); }
javascript
{ "resource": "" }
q43562
clean
train
function clean(method) { for (let m of methods) { if (new RegExp(m, 'i').test(method)) { return m; } } throw new Error(`Invalid method name: ${method}`); }
javascript
{ "resource": "" }
q43563
middleware
train
function middleware(req, res, next) { req.security.csrf.exclude = true; next(); }
javascript
{ "resource": "" }
q43564
onEachExcludedRoute
train
function onEachExcludedRoute(app, route) { const normalized = normalize(route); debug(`Excluding ${(normalized.method || 'all').toUpperCase()} ${normalized.path} from CSRF check...`); const router = app.route(normalized.path); if (is.array(normalized.method) && normalized.method.length) { for (let i = 0, l = normalized.method.length; i < l; i++) { exclude(router, normalized.method[i]); } } if (is.string(normalized.method)) { exclude(router, normalized.method); return; } /* Defaults to all */ exclude(router, 'all'); }
javascript
{ "resource": "" }
q43565
block
train
function block(w, h, d){ return function(cons, nil){ for (var z=-d; z<=d; ++z) for (var y=-h; y<=h; ++y) for (var x=-w; x<=w; ++x) nil = cons(x, y, z), nil = cons(x, y, z); return nil; }; }
javascript
{ "resource": "" }
q43566
sphereVoxels
train
function sphereVoxels(cx, cy, cz, r, col){ return function(cons, nil){ sphere(cx, cy, cz, r)(function(x, y, z, res){ return cons(x, y, z, col, res); }, nil); }; }
javascript
{ "resource": "" }
q43567
dumpFiles
train
function dumpFiles(title, fn) { var matches = fn(); if (matches.length) { log.info(""); log.info((title + ":")['green']); for (var i = 0; i < matches.length; i++) { if (matches[i].src === matches[i].dst) { log.info(matches[i].dst); } else { log.info(matches[i].dst + ' (from ' + matches[i].src + ')'); } } } }
javascript
{ "resource": "" }
q43568
FileSystemLoader
train
function FileSystemLoader(dir, options) { this.dir = dir.replace(/\/$/, ''); this.options = options || (options = {}); this.posts = []; this.files = {}; this.ignore = {}; var self = this; (options.ignore || FileSystemLoader.ignore).forEach(function (file) { self.ignore[file] = true; }); process.nextTick(function () { self.loadPosts(); }); }
javascript
{ "resource": "" }
q43569
Endpoint
train
function Endpoint() { var self = this; const subscriptions = {}; const ps = new Pubsub(); this._publish = ps.publish; this._subscribe = ps.subscribe; this.active = false; this.connections = []; /** * Publishes a new connection. * @function _newConnection * @private * @param {string} sID socket ID * @returns this */ this._newConnection = sId => { self.connections.push(sId || 'unknown'); self.active = true; self._publish('change', {count: self.connections.length}); return this; }; /** * Records a lost connection. * @function _lostConnection * @private * @param {string} sID socket ID * @returns this */ this._lostConnection = sId => { const index = this.connections.indexOf(sId); this.connections.splice(index, 1); if (this.connections.length === 0) { this.active = false; } self._publish('change', {count: self.connections.length}); return this; }; /** * Subscribe an action to perform when a message is received. * @function onmessage * @param {string} type * @param {messageResponse} * @param {boolean} [historical=false] Whether or not to call the listener if this message has been received before this listener was set. * @returns {subscription} */ this.onmessage = (type, cb, historical = false) => { return self._subscribe(type, cb, historical); }; /** * Subscribe an action to perform when the connection changes. * @function onchange * @param {changeCallback} * @returns {subscription} */ this.onchange = cb => { return self._subscribe('change', cb); }; /** * Remove all subscriptions to connection events. * @function clear */ this.clear = ps.clear; }
javascript
{ "resource": "" }
q43570
find
train
function find(queue, name) { const out = queue.findIndex(e => e.name === name); if (out === -1) { throw new Error(`${name}: Could not find this function`); } return out; }
javascript
{ "resource": "" }
q43571
insert
train
function insert(queue, index, fns, mode = InsertMode.REGULAR) { fns.forEach(({ fn, name }) => { if (queue.findIndex(e => e.name === name) !== -1) { throw new Error(`${name}: A function is already queued with this name`); } else if (typeof fn !== 'function') { throw new Error(`${name}: Not a valid function`); } }); const deleteCount = mode === InsertMode.REPLACE ? 1 : 0; queue.splice(index, deleteCount, ...fns); }
javascript
{ "resource": "" }
q43572
addElement
train
function addElement( element, target, moveCurrent ) { target = target || currentNode || root; // Current element might be mangled by fix body below, // save it for restore later. var savedCurrent = currentNode; // Ignore any element that has already been added. if ( element.previous === undefined ) { if ( checkAutoParagraphing( target, element ) ) { // Create a <p> in the fragment. currentNode = target; parser.onTagOpen( fixingBlock, {} ); // The new target now is the <p>. element.returnPoint = target = currentNode; } removeTailWhitespace( element ); // Avoid adding empty inline. if ( !( isRemoveEmpty( element ) && !element.children.length ) ) target.add( element ); if ( element.name == 'pre' ) inPre = false; if ( element.name == 'textarea' ) inTextarea = false; } if ( element.returnPoint ) { currentNode = element.returnPoint; delete element.returnPoint; } else { currentNode = moveCurrent ? target : savedCurrent; } }
javascript
{ "resource": "" }
q43573
checkAutoParagraphing
train
function checkAutoParagraphing( parent, node ) { // Check for parent that can contain block. if ( ( parent == root || parent.name == 'body' ) && fixingBlock && ( !parent.name || CKEDITOR.dtd[ parent.name ][ fixingBlock ] ) ) { var name, realName; if ( node.attributes && ( realName = node.attributes[ 'data-cke-real-element-type' ] ) ) name = realName; else name = node.name; // Text node, inline elements are subjected, except for <script>/<style>. return name && name in CKEDITOR.dtd.$inline && !( name in CKEDITOR.dtd.head ) && !node.isOrphan || node.type == CKEDITOR.NODE_TEXT; } }
javascript
{ "resource": "" }
q43574
possiblySibling
train
function possiblySibling( tag1, tag2 ) { if ( tag1 in CKEDITOR.dtd.$listItem || tag1 in CKEDITOR.dtd.$tableContent ) return tag1 == tag2 || tag1 == 'dt' && tag2 == 'dd' || tag1 == 'dd' && tag2 == 'dt'; return false; }
javascript
{ "resource": "" }
q43575
train
function( filter, context ) { context = this.getFilterContext( context ); // Apply the root filter. filter.onRoot( context, this ); this.filterChildren( filter, false, context ); }
javascript
{ "resource": "" }
q43576
train
function( filter, filterRoot, context ) { // If this element's children were already filtered // by current filter, don't filter them 2nd time. // This situation may occur when filtering bottom-up // (filterChildren() called manually in element's filter), // or in unpredictable edge cases when filter // is manipulating DOM structure. if ( this.childrenFilteredBy == filter.id ) return; context = this.getFilterContext( context ); // Filtering root if enforced. if ( filterRoot && !this.parent ) filter.onRoot( context, this ); this.childrenFilteredBy = filter.id; // Don't cache anything, children array may be modified by filter rule. for ( var i = 0; i < this.children.length; i++ ) { // Stay in place if filter returned false, what means // that node has been removed. if ( this.children[ i ].filter( filter, context ) === false ) i--; } }
javascript
{ "resource": "" }
q43577
train
function( writer, filter, filterRoot ) { var context = this.getFilterContext(); // Filtering root if enforced. if ( filterRoot && !this.parent && filter ) filter.onRoot( context, this ); if ( filter ) this.filterChildren( filter, false, context ); for ( var i = 0, children = this.children, l = children.length; i < l; i++ ) children[ i ].writeHtml( writer ); }
javascript
{ "resource": "" }
q43578
mr
train
function mr(bundler) { var prevError = null var pending = null var buffer = null build() // bundler.on('update', update) return handler /** * Build the CSS and pass it to `buffer`. * * @api private */ function build() { const p = pending = new Emitter() buffer = bundler.toString() if (p !== pending) return pending.emit('ready', null, pending = false) } /** * Response middleware. Sends `buffer` to * either `next()` or `res.body()`. * * @param {Request} req * @param {Response} res * @param {Function} next * @api private */ function handler(req, res, next) { next = next || send if (pending) return pending.once('ready', function(err) { if (err) return next(err) return handler(req, res, next) }) if (prevError) return next(prevError) res.setHeader('content-type', 'text/css') return next(null, buffer) function send(err, body) { if (err) return res.emit(err) res.end(body) } } }
javascript
{ "resource": "" }
q43579
build
train
function build() { const p = pending = new Emitter() buffer = bundler.toString() if (p !== pending) return pending.emit('ready', null, pending = false) }
javascript
{ "resource": "" }
q43580
deletePropertyAt
train
function deletePropertyAt(object, prop) { if (object == null) { return object; } var value = object[prop]; delete object[prop]; return value; }
javascript
{ "resource": "" }
q43581
DotCfg
train
function DotCfg(namespace, scope, strategy) { if (instanceOf(DotCfg, this)) { if (exotic(namespace)) { strategy = scope; scope = namespace; namespace = undefined; } if (primitive(scope)) { scope = env; } if (string(namespace)) { scope[namespace] = scope[namespace] || {}; scope = scope[namespace]; } this.strategy = as(Function, strategy, dotDefault); this.scope = normalize(scope, this.strategy, false); this.extends = proxy(assign(this.strategy), this, this.scope); this.namespace = as(String, namespace, ("dot" + (guid += 1))); return this; } return new DotCfg(namespace, scope, strategy); }
javascript
{ "resource": "" }
q43582
set
train
function set(notation, value, strategy) { var this$1 = this; var fn = !undef(value) && callable(strategy) ? strategy : this.strategy; if (object(notation)) { var context; for (var key in notation) { if (ownProperty(notation, key)) { context = write(this$1.scope, key, notation[key], fn); } } return context; } write(this.scope, notation, value, fn); return this; }
javascript
{ "resource": "" }
q43583
get
train
function get(notation, defaultValue) { var value = read(this.scope, notation); return undef(value) ? defaultValue : value; }
javascript
{ "resource": "" }
q43584
makeArrayOpt
train
function makeArrayOpt(opts, name) { if( !Array.isArray(opts[name]) ) { opts[name] = [ opts[name] ]; } return opts[name]; }
javascript
{ "resource": "" }
q43585
rethrow
train
function rethrow(options) { var opts = lazy.extend({before: 3, after: 3}, options); return function (err, filename, lineno, str, expr) { if (!(err instanceof Error)) throw err; lineno = lineno >> 0; var lines = str.split('\n'); var before = Math.max(lineno - (+opts.before), 0); var after = Math.min(lines.length, lineno + (+opts.after)); // align line numbers var n = lazy.align(count(lines.length + 1)); lineno++; var pointer = errorMessage(err, opts); // Error context var context = lines.slice(before, after).map(function (line, i) { var num = i + before + 1; var msg = style(num, lineno); return msg(' > ', ' ') + n[num] + '| ' + line + ' ' + msg(expr, ''); }).join('\n'); // Alter exception message err.path = filename; err.message = (filename || 'source') + ':' + lineno + '\n' + context + '\n\n' + (pointer ? (pointer + lazy.yellow(filename)) : styleMessage(err.message, opts)) + '\n'; throw err.message; }; }
javascript
{ "resource": "" }
q43586
processRelativePath
train
function processRelativePath(cssPath, importCssPath, importCssText) { cssPath = cssPath.split('\\'); importCssPath = importCssPath.split('/'); var isSibling = importCssPath.length == 1; return importCssText.replace(reg, function(css, before, imgPath, after) { if (/^http\S/.test(imgPath) || /^\/\S/.test(imgPath) || isSibling) { //绝对路径or同级跳过 return css; } imgPath = imgPath.split('/'); imgPath = getRelativePath(cssPath, importCssPath, imgPath); return before + imgPath + after; }); }
javascript
{ "resource": "" }
q43587
getRelativePath
train
function getRelativePath(cssPath, importCssPath, imgPath) { var count1 = 0, count2 = 0, result = ''; importCssPath = getFilePath(cssPath, importCssPath); imgPath = getFilePath(importCssPath, imgPath); for (var i = 0, length = cssPath.length; i < length; i++) { if (cssPath[i] == imgPath[i]) { count1++; } else { break; } } count2 = cssPath.length - count1 - 1; for (var i = 0; i < count2; i++) { result += '../'; } result = result + imgPath.splice(count1).join('/'); return result; }
javascript
{ "resource": "" }
q43588
getFilePath
train
function getFilePath(basePath, relativePath) { var count = 0, array1, array2; for (var i = 0, length = relativePath.length; i < length; i++) { if (relativePath[i] == '..') { count++; } } array1 = basePath.slice(0, basePath.length - 1 - count); array2 = relativePath.slice(count); return array1.concat(array2); }
javascript
{ "resource": "" }
q43589
copy
train
function copy(obj, map) { if (map.has(obj)) { return map.get(obj); } else if (Array.isArray(obj)) { const result = []; map.set(obj, result); obj.forEach(item => { result.push(copy(item, map)); }); return result; } else if (typeof obj === 'object' && obj) { const result = {}; map.set(obj, result); Object.keys(obj).forEach(key => { result[key] = copy(obj[key], map); }); return result; } else { return obj; } }
javascript
{ "resource": "" }
q43590
parseSearchResults
train
function parseSearchResults(err, body) { if (err) { return tubesio.finish(err); } var result = []; jsdom.env({ html: body, scripts: [ 'http://code.jquery.com/jquery-1.5.min.js' ] }, function (err, window) { if (err) { return tubesio.finish(err); } var $ = window.jQuery; $('table.track-grid-top-100 tr').each(function (i) { if (i === 0) { return; } // Skip header row var $row = $(this); result.push({ position: parseInt($row.find('td:nth-child(1)').text()), trackName: $row.find('td:nth-child(4) > a').text(), artists: $row.find('td:nth-child(5) > a').text(), remixers: $row.find('td:nth-child(6) > a').text(), label: $row.find('td:nth-child(7) > a').text(), genre: $row.find('td:nth-child(8) > a').text(), releaseDate: Date.parse($row.find('td:nth-child(9)').text()) }); }); return tubesio.finish(result); }); }
javascript
{ "resource": "" }
q43591
inherits
train
function inherits(ctor, superCtor, staticInherit) { var v = (ctor.hasOwnProperty('super_') && ctor.super_) || getPrototypeOf(ctor); var mixinCtor = ctor.mixinCtor_; if (mixinCtor && v === mixinCtor) { ctor = mixinCtor; v = (ctor.hasOwnProperty('super_') && ctor.super_) || getPrototypeOf(ctor); } var result = false; if (!isInheritedFrom(ctor, superCtor) && !isInheritedFrom(superCtor, ctor)) { inheritsDirectly(ctor, superCtor, staticInherit); // patch the missing prototype chain if exists ctor.super. while (v != null && v !== objectSuperCtor && superCtor !== v) { ctor = superCtor; superCtor = v; inheritsDirectly(ctor, superCtor, staticInherit); v = (ctor.hasOwnProperty('super_') && ctor.super_) || getPrototypeOf(ctor); } result = true; } return result; }
javascript
{ "resource": "" }
q43592
train
function( text ) { if ( this.$.text != null ) this.$.text += text; else this.append( new CKEDITOR.dom.text( text ) ); }
javascript
{ "resource": "" }
q43593
train
function( parent ) { var range = new CKEDITOR.dom.range( this.getDocument() ); // We'll be extracting part of this element, so let's use our // range to get the correct piece. range.setStartAfter( this ); range.setEndAfter( parent ); // Extract it. var docFrag = range.extractContents(); // Move the element outside the broken element. range.insertNode( this.remove() ); // Re-insert the extracted piece after the element. docFrag.insertAfterNode( this ); }
javascript
{ "resource": "" }
q43594
train
function() { // http://help.dottoro.com/ljvmcrrn.php var rect = CKEDITOR.tools.extend( {}, this.$.getBoundingClientRect() ); !rect.width && ( rect.width = rect.right - rect.left ); !rect.height && ( rect.height = rect.bottom - rect.top ); return rect; }
javascript
{ "resource": "" }
q43595
train
function( otherElement ) { // do shallow clones, but with IDs var thisEl = this.clone( 0, 1 ), otherEl = otherElement.clone( 0, 1 ); // Remove distractions. thisEl.removeAttributes( [ '_moz_dirty', 'data-cke-expando', 'data-cke-saved-href', 'data-cke-saved-name' ] ); otherEl.removeAttributes( [ '_moz_dirty', 'data-cke-expando', 'data-cke-saved-href', 'data-cke-saved-name' ] ); // Native comparison available. if ( thisEl.$.isEqualNode ) { // Styles order matters. thisEl.$.style.cssText = CKEDITOR.tools.normalizeCssText( thisEl.$.style.cssText ); otherEl.$.style.cssText = CKEDITOR.tools.normalizeCssText( otherEl.$.style.cssText ); return thisEl.$.isEqualNode( otherEl.$ ); } else { thisEl = thisEl.getOuterHtml(); otherEl = otherEl.getOuterHtml(); // Fix tiny difference between link href in older IEs. if ( CKEDITOR.env.ie && CKEDITOR.env.version < 9 && this.is( 'a' ) ) { var parent = this.getParent(); if ( parent.type == CKEDITOR.NODE_ELEMENT ) { var el = parent.clone(); el.setHtml( thisEl ), thisEl = el.getHtml(); el.setHtml( otherEl ), otherEl = el.getHtml(); } } return thisEl == otherEl; } }
javascript
{ "resource": "" }
q43596
train
function() { // CSS unselectable. this.setStyles( CKEDITOR.tools.cssVendorPrefix( 'user-select', 'none' ) ); // For IE/Opera which doesn't support for the above CSS style, // the unselectable="on" attribute only specifies the selection // process cannot start in the element itself, and it doesn't inherit. if ( CKEDITOR.env.ie ) { this.setAttribute( 'unselectable', 'on' ); var element, elements = this.getElementsByTag( '*' ); for ( var i = 0, count = elements.count() ; i < count ; i++ ) { element = elements.getItem( i ); element.setAttribute( 'unselectable', 'on' ); } } }
javascript
{ "resource": "" }
q43597
train
function( alignToTop ) { var parent = this.getParent(); if ( !parent ) return; // Scroll the element into parent container from the inner out. do { // Check ancestors that overflows. var overflowed = parent.$.clientWidth && parent.$.clientWidth < parent.$.scrollWidth || parent.$.clientHeight && parent.$.clientHeight < parent.$.scrollHeight; // Skip body element, which will report wrong clientHeight when containing // floated content. (#9523) if ( overflowed && !parent.is( 'body' ) ) this.scrollIntoParent( parent, alignToTop, 1 ); // Walk across the frame. if ( parent.is( 'html' ) ) { var win = parent.getWindow(); // Avoid security error. try { var iframe = win.$.frameElement; iframe && ( parent = new CKEDITOR.dom.element( iframe ) ); } catch ( er ) {} } } while ( ( parent = parent.getParent() ) ); }
javascript
{ "resource": "" }
q43598
scrollBy
train
function scrollBy( x, y ) { // Webkit doesn't support "scrollTop/scrollLeft" // on documentElement/body element. if ( /body|html/.test( parent.getName() ) ) parent.getWindow().$.scrollBy( x, y ); else { parent.$.scrollLeft += x; parent.$.scrollTop += y; } }
javascript
{ "resource": "" }
q43599
screenPos
train
function screenPos( element, refWin ) { var pos = { x: 0, y: 0 }; if ( !( element.is( isQuirks ? 'body' : 'html' ) ) ) { var box = element.$.getBoundingClientRect(); pos.x = box.left, pos.y = box.top; } var win = element.getWindow(); if ( !win.equals( refWin ) ) { var outerPos = screenPos( CKEDITOR.dom.element.get( win.$.frameElement ), refWin ); pos.x += outerPos.x, pos.y += outerPos.y; } return pos; }
javascript
{ "resource": "" }