_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q35700
prepareResponse
train
function prepareResponse(response) { Safe.log('Received response: ', response); return response.text().then(function(text) { // If we get a 2xx... Safe.log('Launcher returned status '+response.status); if (response.ok) { // If not an authorized request, or not encrypted, no decryption necessary if (!this._needAuth || doNotDecrypt.indexOf(text) > -1) var body = utils.parseJson(text); // Otherwise, decrypt response else var body = utils.decrypt(text, this.Safe.getAuth('symNonce'), this.Safe.getAuth('symKey')); // Lastly, if any meta data was requested (e.g. the headers), then return an object if (this._returnMeta) { return {body: body, meta: response.headers.entries()}; } else { // No need to return 'OK' for responses that return that. return (typeof body === 'string' && body.toUpperCase() === 'OK') ? undefined : body; } } else { // If authentication was requested, then decrypt the error message received. if (this._needAuth && doNotDecrypt.indexOf(text) === -1) { var message = utils.decrypt(text, this.Safe.getAuth('symNonce'), this.Safe.getAuth('symKey')), parsed = parseSafeMessage(message, response.status); // Throw a "launcher" error type, which is an error from the launcher. throw new SafeError('launcher', parsed.message, parsed.status, response); } else { // If no message received, it's a standard http response error var parsed = parseSafeMessage(utils.parseJson(text), response.status); throw new SafeError('http', parsed.message, parsed.status, response); } } }.bind(this)); }
javascript
{ "resource": "" }
q35701
parseSafeMessage
train
function parseSafeMessage(message, status) { if (typeof message === 'object') { return {status: message.errorCode, message: message.description}; } else { return {status: status, message: message}; } }
javascript
{ "resource": "" }
q35702
train
function(next) { if (!extension[type] || typeof extension[type] !== 'function') { return next(); } // Invoke type hook implemetation. extension[type](result, function(error, newItems) { if (error) { return next(error); } utils.extend(result, newItems || {}); next(); }); }
javascript
{ "resource": "" }
q35703
CHS
train
function CHS( cylinder, head, sector ) { if( !(this instanceof CHS) ) return new CHS( cylinder, head, sector ) if( Buffer.isBuffer( cylinder ) ) return CHS.fromBuffer( cylinder ) /** @type {Number} Cylinder */ this.cylinder = cylinder & 0x03FF /** @type {Number} Head */ this.head = head & 0xFF /** @type {Number} Sector */ this.sector = sector & 0x3F }
javascript
{ "resource": "" }
q35704
train
function( target ) { target.cylinder = this.cylinder target.head = this.head target.sector = this.sector return target }
javascript
{ "resource": "" }
q35705
train
function( buffer, offset ) { if( !Buffer.isBuffer( buffer ) ) throw new TypeError( 'Value must be a buffer' ) offset = offset || 0 return this.fromNumber( buffer.readUIntLE( offset, 3 ) ) }
javascript
{ "resource": "" }
q35706
compose
train
function compose(...fns) { return function(x) { return fns.reduceRight((result, val) => val(result), x); }; }
javascript
{ "resource": "" }
q35707
tickify
train
function tickify(fn, {delay} = {}) { delay = delay || 10; return function() { return setTimeout(() => fn.apply(this, arguments), delay); }; }
javascript
{ "resource": "" }
q35708
memoify
train
function memoify(fn, {hash, cache} = {}) { hash = hash || identify; cache = cache = {}; function memoified(...args) { var key = hash(...args); return key in cache ? cache[key] : cache[key] = fn.call(this, ...args); } memoified.clear = () => cache = {}; return memoified; }
javascript
{ "resource": "" }
q35709
logify
train
function logify(fn) { return function() { console.log("entering", fn.name); var ret = fn.apply(this, arguments); console.log("leaving", fn.name); return ret; }; }
javascript
{ "resource": "" }
q35710
onceify
train
function onceify(f) { var ran, ret; return function() { return ran ? ret : (ran=true, ret=f.apply(this,arguments)); }; }
javascript
{ "resource": "" }
q35711
wrapify
train
function wrapify(fn, before = noop, after = noop) { return function(...args) { before.call(this); var ret = fn.call(this, ...args); after.call(this); return ret; }; }
javascript
{ "resource": "" }
q35712
parseBody
train
function parseBody(fn){ //get arguments to function as array of strings var body=fn.body=fn.body|| //cache result in `body` property of function fn.toString() //get string version of function .replace(/\/\/.*$|\/\*[\s\S]*?\*\//mg, '') //strip comments .replace(/^\s*$/mg, '') // kill empty lines .replace(/^.*?\)\s*\{\s*(return)?\s*/, '') // kill argument list and leading curly .replace(/\s*\}\s*$/, '') // kill trailing curly ; return body; // or fn? }
javascript
{ "resource": "" }
q35713
convertProfNode
train
function convertProfNode (node) { var res = { functionName: node.functionName, lineNumber: node.lineNumber, callUID: node.callUid, hitCount: node.selfSamplesCount, url: node.scriptName, children: [] }; for (var i = 0; i < node.childrenCount; i++) { res.children.push(convertProfNode(node.getChild(i))); } return res; }
javascript
{ "resource": "" }
q35714
writeProfile
train
function writeProfile() { var format; if (/\.cpuprofile$/.test(argv.o)) { format = 'cpuprofile'; } var prof = stopCPU('global', format); fs.writeFileSync(argv.o, prof); var fname = JSON.stringify(argv.o); console.warn('Profile written to', fname + '\nTry `kcachegrind', fname + '`'); process.removeAllListeners('exit'); process.exit(0); }
javascript
{ "resource": "" }
q35715
walkBemJson
train
function walkBemJson(bemJson, cb) { let result; if (Array.isArray(bemJson)) { result = []; bemJson.forEach((childBemJson, i) => { result[i] = walkBemJson(childBemJson, cb); }); } else if (bemJson instanceof Object) { result = {}; Object.keys(bemJson).forEach((key) => { result[key] = walkBemJson(bemJson[key], cb); }); } else if (typeof bemJson === 'string') { result = cb(bemJson); } return result; }
javascript
{ "resource": "" }
q35716
AdapterJsRTCObjectFactory
train
function AdapterJsRTCObjectFactory(logger) { Utils.checkArguments(arguments, 1); this.createIceServers = function (urls, username, password) { if (typeof(createIceServers) !== "undefined") { return createIceServers(urls, username, password); } else { logger.error("adapter.js not present or unsupported browser!"); return null; } }; this.createRTCSessionDescription = function (sessionDescriptionString) { if (typeof(RTCSessionDescription) !== "undefined") { return new RTCSessionDescription(sessionDescriptionString); } else { logger.error("adapter.js not present or unsupported browser!"); return null; } }; this.createRTCIceCandidate = function (rtcIceCandidateString) { if (typeof(RTCIceCandidate) !== "undefined") { return new RTCIceCandidate(rtcIceCandidateString); } else { logger.error("adapter.js not present or unsupported browser!"); return null; } }; this.createRTCPeerConnection = function (config) { if (typeof(RTCPeerConnection) !== "undefined") { return new RTCPeerConnection(config); } else { logger.error("adapter.js not present or unsupported browser!"); return null; } }; }
javascript
{ "resource": "" }
q35717
onlySmHere
train
function onlySmHere(jsonFileName,isIndent,outFileName){ if (fs.existsSync(jsonFileName)) { var fcount = JSON.parse(fs.readFileSync(jsonFileName)); var foooo = []; if(fs.existsSync('SUMMARY.md')){ fcount = lodash.without(fcount,...haslisted.hasListed('SUMMARY.md')); } if (fcount[0] !== undefined) { for (var i = 0; i < fcount.length; i++) { var CFpath = fcount[i]; var CFtitle = gH1.getFirstH1(fcount[i],"both"); if ( isIndent == true) { var prefix = '\ \ '; var spsign = CFpath.match(/\//g); if (spsign !== null) { var spsignCount = spsign.length; var prefixRep = prefix.repeat(spsignCount); var foo_item = prefixRep + '* [' + CFtitle + '](' + CFpath + ')'; foooo.push(foo_item); } else { var foo_item = '* [' + CFtitle + '](' + CFpath + ')'; foooo.push(foo_item); } } else { var foo_item = '* [' + CFtitle + '](' + CFpath + ')'; foooo.push(foo_item); } } var datas = foooo.join('\n'); fs.writeFile(outFileName, datas, { encoding: 'utf8', flag: 'w' }, function (err) { if (err) { throw err; } }); console.log(`${chalk.yellow('summarybuilder: ')}`+outFileName+"......ok"); } }else if(typeof(jsonFileName)=="object"){ var fcount = jsonFileName; var foooo = []; if(fs.existsSync('SUMMARY.md')){ fcount = lodash.without(fcount,...haslisted.hasListed('SUMMARY.md')); } if (fcount[0] !== undefined) { for (var i = 0; i < fcount.length; i++) { var CFpath = fcount[i]; var CFtitle = gH1.getFirstH1(fcount[i],"both"); if ( isIndent == true) { var prefix = '\ \ '; var spsign = CFpath.match(/\//g); if (spsign !== null) { var spsignCount = spsign.length; var prefixRep = prefix.repeat(spsignCount); var foo_item = prefixRep + '* [' + CFtitle + '](' + CFpath + ')'; foooo.push(foo_item); } else { var foo_item = '* [' + CFtitle + '](' + CFpath + ')'; foooo.push(foo_item); } } else { var foo_item = '* [' + CFtitle + '](' + CFpath + ')'; foooo.push(foo_item); } } var datas = foooo.join('\n'); fs.writeFile(outFileName, datas, { encoding: 'utf8', flag: 'w' }, function (err) { if (err) { throw err; } }); console.log(`${chalk.yellow('summarybuilder: ')}`+outFileName+" ....... ok"); } }else{ console.log(`${chalk.yellow('summarybuilder: ')}`+"No such a file names:"+jsonFileName+'. It is better to be created by the plugin: gulp-filelist.And sure all path of the list in '+jsonFileName+' are existent.'); console.log(`${chalk.yellow('summarybuilder: ')}`+' You can use an array type variable ,or like this: SBer_summary(["a.md","b/a.md"],true,"mySummary.md"). ') } }
javascript
{ "resource": "" }
q35718
State
train
function State(config) { this._ = require('lodash'); this._name = config.name; this._isInitial = config.isInitial; this._isTerminal = config.isTerminal; this._outgoingTransitions = config.outgoingTransitions; this.accept = config.accept; this._validateConfig(config); // Transform any value-based transition criteria to be a function this._.forEach(this._outgoingTransitions, function (transition) { var criteria = transition.criteria; // Replace the value-based criteria with a simple comparison function if (typeof criteria !== 'function') { transition.criteria = function (input) { return (input === criteria); } } }); }
javascript
{ "resource": "" }
q35719
removeDir
train
function removeDir(dirPath, cleanOnly) { var files; try { files = fs.readdirSync(dirPath); } catch(e) { return; } if (files.length > 0) { for (var i = 0; i < files.length; i++) { var filePath = path.join(dirPath, files[i]); if (fs.statSync(filePath).isFile()) fs.unlinkSync(filePath); else rmDir(filePath); } } !cleanOnly && fs.rmdirSync(dirPath); }
javascript
{ "resource": "" }
q35720
loadAndSaveShoots
train
function loadAndSaveShoots(settings, folderPath) { var promisesPool = []; var semaphore = new Semaphore({rooms: 6}); settings.pages.forEach((page) => { settings.sizes.forEach((size) => { promisesPool.push(semaphore.add(() => { return new Promise((resolve, reject) => { console.log(`Start ${page.name} for ${size.width}x${size.height}`); screenshot({ url : settings.urlBase + page.url, width : size.width, height : size.height, page: size.page === undefined ? true : size.page, cookies: settings.cookies, auth: settings.auth, delay: settings.delay, }) .then(function(img){ var fileName = getFileName(page, size); fs.writeFile(path.join(folderPath, fileName), img.data, function(err){ if (err) { console.info(`Failed to save ${fileName}`, err) } resolve(); }); }) .catch((err) => { console.info(`Failed to retrieve ${page.url}`, err) resolve(); }) }) })) }) }) var promise = Promise.all(promisesPool); // Close screenshot service promise = promise.then(() => { console.log(`Done`) screenshot.close(); }).catch(() => { console.log(`Done with errors`) screenshot.close(); }) return promise }
javascript
{ "resource": "" }
q35721
getModule
train
function getModule (filename) { const file = files(filename) const module = file.default || file if (module.commit) { throw new Error('[vssr] <%= dir.store %>/' + filename.replace('./', '') + ' should export a method which returns a Vuex instance.') } if (module.state && typeof module.state !== 'function') { throw new Error('[vssr] state should be a function in <%= dir.store %>/' + filename.replace('./', '')) } return module }
javascript
{ "resource": "" }
q35722
filenamify
train
function filenamify(url) { let res = filenamifyUrl(url); if (res.length >= 60) { res = res.substr(0, 60) + '-md5-' + crypto.createHash('md5').update(url, 'utf8').digest('hex'); } return res; }
javascript
{ "resource": "" }
q35723
hasExpired
train
function hasExpired(headers, refresh) { if (!headers) { log('response is not in cache'); return true; } if (refresh === 'force') { log('response in cache but refresh requested'); return true; } if (refresh === 'never') { log('response in cache and considered to be always valid'); return false; } let received = new Date( headers.received || headers.date || 'Jan 1, 1970, 00:00:00.000 GMT'); received = received.getTime(); if (refresh === 'once') { if (received < launchTime) { log('response in cache but one refresh requested'); return true; } else { log('response in cache and already refreshed once') return false; } } let now = Date.now(); if (Number.isInteger(refresh)) { if (received + refresh * 1000 < now) { log('response in cache is older than requested duration'); return true; } else { log('response in cache is fresh enough for requested duration'); return false; } } // Apply HTTP expiration rules otherwise if (headers.expires) { try { let expires = (new Date(headers.expires)).getTime(); if (expires < now) { log('response in cache has expired'); return true; } else { log('response in cache is still valid'); return false; } } catch (err) {} } if (headers['cache-control']) { try { let tokens = headers['cache-control'].split(',') .map(token => token.split('=')); for (token of tokens) { let param = token[0].trim(); if (param === 'no-cache') { log('response in cache but no-cache directive'); return true; } else if (param === 'max-age') { let maxAge = parseInt(token[1], 10); if (received + maxAge * 1000 < now) { log('response in cache has expired'); return true; } else { log('response in cache is still valid'); return false; } } } } catch (err) {} } // Cannot tell? Let's refresh the cache log('response in cache has expired (no explicit directive)'); return true; }
javascript
{ "resource": "" }
q35724
addPendingFetch
train
function addPendingFetch(url) { let resolve = null; let reject = null; let promise = new Promise((innerResolve, innerReject) => { resolve = innerResolve; reject = innerReject; }); pendingFetches[url] = { promise, resolve, reject }; }
javascript
{ "resource": "" }
q35725
fetchWithRetry
train
async function fetchWithRetry(url, options, remainingAttempts) { try { return await baseFetch(url, options); } catch (err) { if (remainingAttempts <= 0) throw err; log('fetch attempt failed, sleep and try again'); await sleep(2000 + Math.floor(Math.random() * 8000)); return fetchWithRetry(url, options, remainingAttempts - 1); } }
javascript
{ "resource": "" }
q35726
train
function(pModel) { // First create a "lookup" of primary keys that point back to tables console.log('--> ... creating contextual Index ==> Table lookups ...'); var tmpIndices = {}; for(var tmpTable in pModel.Tables) { for (var j = 0; j < pModel.Tables[tmpTable].Columns.length; j++) { if (pModel.Tables[tmpTable].Columns[j].DataType == "ID") { console.log(' > Adding the table '+pModel.Tables[tmpTable].TableName+' to the lookup cache with the key '+pModel.Tables[tmpTable].Columns[j].Column); tmpIndices[pModel.Tables[tmpTable].Columns[j].Column] = pModel.Tables[tmpTable].TableName; } } } console.log(' > indices built successfully.'); return tmpIndices; }
javascript
{ "resource": "" }
q35727
_delete
train
function _delete(name) { observers[name].unobserve(); delete observers[name]; delete u [name]; delete shadow [name]; }
javascript
{ "resource": "" }
q35728
add
train
function add(name) { function set(v) { var oldValue = shadow[name]; if (oldValue === v) return; o[name] = v; notifier.notify({type: 'update', object: u, name, oldValue}); shadow[name] = oldValue.change(v); } // When property on upwardable object is accessed, report it and return shadow value. function get() { accessNotifier.notify({type: 'access', object: u, name}); return shadow[name]; } function observe(changes) { // changes.forEach(change => shadow[name] = shadow[name].change(change.newValue)); // observers[name].reobserve(shadow[name]); } shadow[name] = makeUpwardable(o[name]); observers[name] = Observer(shadow[name], observe, ['upward']).observe(); defineProperty(u, name, {set: set, get: get, enumerable: true}); }
javascript
{ "resource": "" }
q35729
objectObserver
train
function objectObserver(changes) { changes.forEach(({type, name}) => { switch (type) { case 'add': o[name] = u[name]; break; case 'delete': delete o[name]; break; } }); }
javascript
{ "resource": "" }
q35730
buildMessageBuilder
train
function buildMessageBuilder(section) { const logOptions = process.env.X2_LOG || ''; const msgBuilder = new Array(); if (!/(^|,)nots(,|$)/i.test(logOptions)) msgBuilder.push(() => (new Date()).toISOString()); if (!/(^|,)nopid(,|$)/i.test(logOptions)) msgBuilder.push(() => String(process.pid)); let m; const envRE = new RegExp('(?:^|,)env:([^,]+)', 'gi'); while ((m = envRE.exec(logOptions)) !== null) { const envName = m[1]; msgBuilder.push(() => process.env[envName]); } if (section && !/(^|,)nosec(,|$)/i.test(logOptions)) msgBuilder.push(() => section); return msgBuilder; }
javascript
{ "resource": "" }
q35731
makeSheet
train
function makeSheet(scope) { var style = document.createElement('style'); document.head.appendChild(style); var sheet = style.sheet; if (scope) { style.setAttribute('scoped', "scoped"); if (!scopedSupported) { scope.dataset[scopedStyleIdsProp] = (scope.dataset[scopedStyleIdsProp] || "") + " " + (sheet.scopedStyleId = makeScopedStyleId(scopedStyleId++)); } } return sheet; }
javascript
{ "resource": "" }
q35732
Concept
train
function Concept(concept) { if (!(concept.prefLabel && concept.id && concept.type === 'Concept')) { throw new Error('Invalid concept: "' + concept.id + '"'); } this.id = concept.id; this.prefLabel = concept.prefLabel; this.altLabel = concept.altLabel; this.hiddenLabel = concept.hiddenLabel; this.definition = concept.definition; this._topConceptOf = concept.topConceptOf; this._partOfScheme = false; this._originalConcept = concept; this._broaderConcepts = []; this._narrowerConcepts = []; this._relatedConcepts = []; }
javascript
{ "resource": "" }
q35733
train
function () { // Get stored auth data. var stored = this.storage.get(); // If nothing stored, proceed with new authorization if (!stored) { this.log('No auth data stored, starting authorization from scratch...'); return this.auth.authorize(); } // Otherwise, set the auth data on the Request object so that it can be used for requests this.log('Auth data stored, checking validity...'); this._auth = utils.unserialize(stored); // Use the saved auth data to check if we're already authorized. If not, it will clear the stored // data, then proceed with new authorization. return this.auth.isAuth() .then(function(result) { if (result === false) return this.auth.authorize(); }.bind(this)); }
javascript
{ "resource": "" }
q35734
train
function () { this.log('Authorizing...'); // Generate new asymmetric key pair and nonce, e.g. public-key encryption var asymKeys = nacl.box.keyPair(), asymNonce = nacl.randomBytes(nacl.box.nonceLength); // The payload for the request var authPayload = { app: this.app, publicKey: base64.fromByteArray(asymKeys.publicKey), nonce: base64.fromByteArray(asymNonce), permissions: this.permissions }; // Proceed with request return this.Request .post('/auth') .body(authPayload) .execute() .then(function (json) { // We received the launcher's private key + encrypted symmetrical keys (i.e. private key encryption) var launcherPubKey = base64.toByteArray(json.publicKey); var messageWithSymKeys = base64.toByteArray(json.encryptedKey); // Decrypt the private key/nonce var key = nacl.box.open(messageWithSymKeys, asymNonce, launcherPubKey, asymKeys.secretKey); // Save auth data for future requests this._auth = { token: json.token, symKey: key.slice(0, nacl.secretbox.keyLength), symNonce: key.slice(nacl.secretbox.keyLength) }; // Set the auth data for future requests this.storage.set(utils.serialize(this._auth)); this.log('Authorized'); }.bind(this), function(res) { this.log('Could not authorize.'); this.storage.clear(); }.bind(this)); }
javascript
{ "resource": "" }
q35735
train
function () { this.log('Checking if authorized...'); return this.Request.get('/auth').auth().execute() // let's use our own function here, that resolve true or false, // rather than throwing an error if invalid token .then(function () { this.log('Authorized'); return true; }.bind(this), function (response) { this.log('Not authorized, or received error.', response); if (response.status === 401) { // Remove any auth from storage and Request class this.log('Not authorized, removing any stored auth data.'); clearAuthData.call(this); // Return false return false; } else { // Any other status is another error, throw the response throw response; } }.bind(this)); }
javascript
{ "resource": "" }
q35736
train
function () { this.log('Deauthorizing...'); return this.Request.delete('/auth').auth().execute() .then(function (response) { // Clear auth data from storage upon deauthorization this.storage.clear(); clearAuthData.call(this); this.log('Deauthorized and cleared from storage.'); return response; }.bind(this)); }
javascript
{ "resource": "" }
q35737
model
train
function model(M, prop) { const bmiLens = L( prop, // if we don't have <prop> property yet, then use these default values L.defaults({weight: 80, height: 180}), // add "read-only" bmi property to our BMI model that is derived from weight and height L.augment({bmi: ({weight: w, height: h}) => Math.round(w / (h * h * 0.0001))}) ) return M.lens(bmiLens) }
javascript
{ "resource": "" }
q35738
beginsWith
train
function beginsWith(haystack, needles) { let needle; for (let i = 0, u = needles.length; i < u; ++i) { needle = needles[i]; if (haystack.substr(0, needle.length) === needle) { return true; } } return false; }
javascript
{ "resource": "" }
q35739
mergeQuery
train
function mergeQuery(path, newQuery) { let parsed, properties, query, queryString; // Return the original path if the query to merge is empty. if (Object.keys(newQuery).length === 0) { return path; } // Parse the original path. parsed = url.parse(path, true); // Merge the queries to form a new query. query = parsed.query; properties = Object.keys(newQuery); for (let i = 0, u = properties.length; i < u; ++i) { let property = properties[i]; query[property] = newQuery[property]; } queryString = querystring.stringify(query); path = parsed.pathname + '?' + queryString; return path; }
javascript
{ "resource": "" }
q35740
runSync
train
function runSync(context, func, callback) { var result , requiresContext = isArrowFunction(func) ; try { if (requiresContext) { result = func.call(null, context); } else { result = func.call(context); } } catch (ex) { // pass error as error-first callback callback(ex); return; } // everything went well callback(null, result); }
javascript
{ "resource": "" }
q35741
runAsync
train
function runAsync(context, func, callback) { var result , requiresContext = isArrowFunction(func) ; if (requiresContext) { result = func.call(null, context, callback); } else { result = func.call(context, callback); } return result; }
javascript
{ "resource": "" }
q35742
async
train
function async(func) { function wrapper() { var context = this; var args = arguments; process.nextTick(function() { func.apply(context, args); }); } return wrapper; }
javascript
{ "resource": "" }
q35743
traceSources
train
function traceSources(node, original) { var i, source, sources; if (!(node instanceof EffectNode) && !(node instanceof TransformNode)) { return false; } sources = node.sources; for (i in sources) { if (sources.hasOwnProperty(i)) { source = sources[i]; if (source === original || traceSources(source, original)) { return true; } } } return false; }
javascript
{ "resource": "" }
q35744
makePolygonsArray
train
function makePolygonsArray(poly) { if (!poly || !poly.length || !Array.isArray(poly)) { return []; } if (!Array.isArray(poly[0])) { return [poly]; } if (Array.isArray(poly[0]) && !isNaN(poly[0][0])) { return [poly]; } return poly; }
javascript
{ "resource": "" }
q35745
longestCommonPathPrefix
train
function longestCommonPathPrefix(stra, strb) { const minlen = min(stra.length, strb.length); let common = 0; let lastSep = -1; for (; common < minlen; ++common) { const chr = stra[common]; if (chr !== strb[common]) { break; } if (chr === sep) { lastSep = common; } } if (common === minlen && (stra.length === minlen ? strb.length === minlen || strb[minlen] === sep : stra[minlen] === sep)) { return minlen + 1; } return lastSep + 1; }
javascript
{ "resource": "" }
q35746
relpath
train
function relpath(basePath, absPath) { let base = dedot(basePath); let abs = dedot(absPath); // Find the longest common prefix that ends with a separator. const commonPrefix = longestCommonPathPrefix(base, abs); // Remove the common path elements. base = apply(substring, base, [ commonPrefix ]); abs = apply(substring, abs, [ commonPrefix ]); // For each path element in base, output "/..". let rel = '.'; if (base) { rel = '..'; for (let i = 0; (i = apply(indexOf, base, [ sep, i ])) >= 0; ++i) { rel = `${ rel }/..`; } } // Append abs. if (abs) { rel += sep + abs; } return rel; }
javascript
{ "resource": "" }
q35747
createOptionsForServerSpec
train
function createOptionsForServerSpec(serverSpec) { var options = { forceNew: true, // Make a new connection each time reconnection: false // Don't try and reconnect automatically }; // If the server spec contains a socketResource setting we use // that otherwise leave the default ('/socket.io/') if(serverSpec.socket.socketResource) { options.resource = serverSpec.socket.socketResource; } return options; }
javascript
{ "resource": "" }
q35748
Chickadee
train
function Chickadee(options) { var self = this; options = options || {}; self.associations = options.associationManager || new associationManager(options); self.routes = { "/associations": require('./routes/associations'), "/contextat": require('./routes/contextat'), "/contextnear": require('./routes/contextnear'), "/": express.static(path.resolve(__dirname + '/../web')) }; console.log("reelyActive Chickadee instance is curious to associate metadata in an open IoT"); }
javascript
{ "resource": "" }
q35749
convertOptionsParamsToIds
train
function convertOptionsParamsToIds(req, instance, options, callback) { var err; if(options.id) { var isValidID = reelib.identifier.isValid(options.id); if(!isValidID) { err = 'Invalid id'; } options.ids = [options.id]; delete options.id; callback(err); } else if(options.directory) { instance.associations.retrieveIdsByParams(req, options.directory, null, function(ids) { options.ids = ids; delete options.directory; callback(err); }); } else if(options.tags) { instance.associations.retrieveIdsByParams(req, null, options.tags, function(ids) { options.ids = ids; delete options.tags; callback(err); }); } }
javascript
{ "resource": "" }
q35750
hex
train
function hex(n) { return crypto.randomBytes(Math.ceil(n / 2)).toString('hex').slice(0, n); }
javascript
{ "resource": "" }
q35751
exportKs
train
function exportKs (password, privateKey, salt, iv, type, option = {}) { if (!password || !privateKey || !type) { throw new Error('Missing parameter! Make sure password, privateKey and type provided') } if (!crypto.isPrivateKey(privateKey)) { throw new Error('given Private Key is not a valid Private Key string'); } salt = salt || util.bytesToHexUpperString(crypto.generateSalt()); iv = iv || util.bytesToHexUpperString(crypto.generateIv()) return crypto.marshal( crypto.deriveKey(password, salt, option), privateKey, util.strToBuffer(salt), util.strToBuffer(iv), type, option ); }
javascript
{ "resource": "" }
q35752
verifyAndDecrypt
train
function verifyAndDecrypt(derivedKey, iv, ciphertext, algo, mac) { if (typeof algo !== 'string') { throw new Error('Cipher method is invalid. Unable to proceed') } var key; if (crypto.createMac(derivedKey, ciphertext) !== mac) { throw new Error('message authentication code mismatch'); } key = derivedKey.slice(0, 16); return crypto.bs58Encode(util.bytesToHexUpperString(crypto.decrypt(ciphertext, key, iv, algo)), 3); }
javascript
{ "resource": "" }
q35753
buildJs
train
function buildJs() { // Construct a stream for the JS sources of our plugin, don't read file contents when compiling TypeScript. var sourceStream = gulp.src( config.Sources.Scripts, { cwd : config.WorkingDirectory, read : true } ); return sourceStream .pipe( jscs() ) .pipe( jscs.reporter() ) .pipe( jsValidate() ) .pipe( order() ) // Only pass through files that have changed since the last build iteration (relevant during "watch"). .pipe( cached( path.join( config.Output.Production, config.Output.DirectoryNames.Scripts ) ) ) // Generate sourcemaps .pipe( sourcemaps.init() ) .pipe( wrapper( { header : "(function() {\n\"use strict\";\n", footer : "}());" } ) ) .pipe( jsValidate() ) .pipe( jshint() ) .pipe( jshint.reporter( stylish ) ) // Put Angular dependency injection annotation where needed. .pipe( ngAnnotate() ) // Pull out files which haven't changed since our last build iteration and put them back into the stream. .pipe( remember() ) // Place the results in the development output directory. .pipe( gulp.dest( path.join( config.Output.Development, config.Output.DirectoryNames.Scripts ) ) ) // Concatenate all files into a single one. .pipe( concat( slug( application.name ) + ".concat.js", { newLine : ";" } ) ) // Put that file into the development output as well. .pipe( gulp.dest( path.join( config.Output.Development, config.Output.DirectoryNames.Scripts ) ) ) // Minify the file. .pipe( uglify() ) // Rename it to indicate minification. .pipe( rename( { extname : ".min.js" } ) ) // Write out sourcemaps .pipe( sourcemaps.write( "maps" ) ) // Write the file to the production output directory. .pipe( gulp.dest( path.join( config.Output.Production, config.Output.DirectoryNames.Scripts ) ) ); }
javascript
{ "resource": "" }
q35754
_fetchSubreddit
train
function _fetchSubreddit(subreddit) { const reducer = (prev, {data: {url}}) => prev.push(url) && prev; const jsonUri = `https://www.reddit.com/r/${subreddit}/.json`; return fetch(jsonUri) .then((res) => res.json()) .then((res) => res.data.children.reduce(reducer, [])) .then((urls) => ({subreddit, urls})); }
javascript
{ "resource": "" }
q35755
_fetchRandomSubreddit
train
function _fetchRandomSubreddit(count=1, subreddit='random', fetchOpts={}) { const _fetchSubredditUrl = (subreddit, fetchOpts) => { return fetch(`https://www.reddit.com/r/${subreddit}`, fetchOpts) .then(({url}) => { return { json: `${url}.json`, name: getSubredditName(url), url }; }); }; const promises = [...Array(count)] .map(() => _fetchSubredditUrl(subreddit, fetchOpts)); return Promise.all(promises); }
javascript
{ "resource": "" }
q35756
getSubredditName
train
function getSubredditName(url) { try { // This will throw a `TypeError: Cannot read property 'Symbol(Symbol.iterator)' of null` if the RegExp fails. const [input, name] = new RegExp('^https?://(?:www.)?reddit.com/r/(.*?)/?$').exec(url); return name; } catch (err) { return null; } }
javascript
{ "resource": "" }
q35757
relativePosition
train
function relativePosition(rect, targetRect, rel) { var x, y, w, h, targetW, targetH; x = targetRect.x; y = targetRect.y; w = rect.w; h = rect.h; targetW = targetRect.w; targetH = targetRect.h; rel = (rel || '').split(''); if (rel[0] === 'b') { y += targetH; } if (rel[1] === 'r') { x += targetW; } if (rel[0] === 'c') { y += round(targetH / 2); } if (rel[1] === 'c') { x += round(targetW / 2); } if (rel[3] === 'b') { y -= h; } if (rel[4] === 'r') { x -= w; } if (rel[3] === 'c') { y -= round(h / 2); } if (rel[4] === 'c') { x -= round(w / 2); } return create(x, y, w, h); }
javascript
{ "resource": "" }
q35758
inflate
train
function inflate(rect, w, h) { return create(rect.x - w, rect.y - h, rect.w + w * 2, rect.h + h * 2); }
javascript
{ "resource": "" }
q35759
intersect
train
function intersect(rect, cropRect) { var x1, y1, x2, y2; x1 = max(rect.x, cropRect.x); y1 = max(rect.y, cropRect.y); x2 = min(rect.x + rect.w, cropRect.x + cropRect.w); y2 = min(rect.y + rect.h, cropRect.y + cropRect.h); if (x2 - x1 < 0 || y2 - y1 < 0) { return null; } return create(x1, y1, x2 - x1, y2 - y1); }
javascript
{ "resource": "" }
q35760
clamp
train
function clamp(rect, clampRect, fixedSize) { var underflowX1, underflowY1, overflowX2, overflowY2, x1, y1, x2, y2, cx2, cy2; x1 = rect.x; y1 = rect.y; x2 = rect.x + rect.w; y2 = rect.y + rect.h; cx2 = clampRect.x + clampRect.w; cy2 = clampRect.y + clampRect.h; underflowX1 = max(0, clampRect.x - x1); underflowY1 = max(0, clampRect.y - y1); overflowX2 = max(0, x2 - cx2); overflowY2 = max(0, y2 - cy2); x1 += underflowX1; y1 += underflowY1; if (fixedSize) { x2 += underflowX1; y2 += underflowY1; x1 -= overflowX2; y1 -= overflowY2; } x2 -= overflowX2; y2 -= overflowY2; return create(x1, y1, x2 - x1, y2 - y1); }
javascript
{ "resource": "" }
q35761
fromClientRect
train
function fromClientRect(clientRect) { return create(clientRect.left, clientRect.top, clientRect.width, clientRect.height); }
javascript
{ "resource": "" }
q35762
train
function (callback, element) { if (requestAnimationFramePromise) { requestAnimationFramePromise.then(callback); return; } requestAnimationFramePromise = new Promise(function (resolve) { if (!element) { element = document.body; } requestAnimationFrame(resolve, element); }).then(callback); }
javascript
{ "resource": "" }
q35763
train
function (editor, callback, time) { var timer; timer = wrappedSetInterval(function () { if (!editor.removed) { callback(); } else { clearInterval(timer); } }, time); return timer; }
javascript
{ "resource": "" }
q35764
addEvent
train
function addEvent(target, name, callback, capture) { if (target.addEventListener) { target.addEventListener(name, callback, capture || false); } else if (target.attachEvent) { target.attachEvent('on' + name, callback); } }
javascript
{ "resource": "" }
q35765
removeEvent
train
function removeEvent(target, name, callback, capture) { if (target.removeEventListener) { target.removeEventListener(name, callback, capture || false); } else if (target.detachEvent) { target.detachEvent('on' + name, callback); } }
javascript
{ "resource": "" }
q35766
getTargetFromShadowDom
train
function getTargetFromShadowDom(event, defaultTarget) { var path, target = defaultTarget; // When target element is inside Shadow DOM we need to take first element from path // otherwise we'll get Shadow Root parent, not actual target element // Normalize target for WebComponents v0 implementation (in Chrome) path = event.path; if (path && path.length > 0) { target = path[0]; } // Normalize target for WebComponents v1 implementation (standard) if (event.deepPath) { path = event.deepPath(); if (path && path.length > 0) { target = path[0]; } } return target; }
javascript
{ "resource": "" }
q35767
fix
train
function fix(originalEvent, data) { var name, event = data || {}, undef; // Dummy function that gets replaced on the delegation state functions function returnFalse() { return false; } // Dummy function that gets replaced on the delegation state functions function returnTrue() { return true; } // Copy all properties from the original event for (name in originalEvent) { // layerX/layerY is deprecated in Chrome and produces a warning if (!deprecated[name]) { event[name] = originalEvent[name]; } } // Normalize target IE uses srcElement if (!event.target) { event.target = event.srcElement || document; } // Experimental shadow dom support if (Env.experimentalShadowDom) { event.target = getTargetFromShadowDom(originalEvent, event.target); } // Calculate pageX/Y if missing and clientX/Y available if (originalEvent && mouseEventRe.test(originalEvent.type) && originalEvent.pageX === undef && originalEvent.clientX !== undef) { var eventDoc = event.target.ownerDocument || document; var doc = eventDoc.documentElement; var body = eventDoc.body; event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add preventDefault method event.preventDefault = function () { event.isDefaultPrevented = returnTrue; // Execute preventDefault on the original event object if (originalEvent) { if (originalEvent.preventDefault) { originalEvent.preventDefault(); } else { originalEvent.returnValue = false; // IE } } }; // Add stopPropagation event.stopPropagation = function () { event.isPropagationStopped = returnTrue; // Execute stopPropagation on the original event object if (originalEvent) { if (originalEvent.stopPropagation) { originalEvent.stopPropagation(); } else { originalEvent.cancelBubble = true; // IE } } }; // Add stopImmediatePropagation event.stopImmediatePropagation = function () { event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; // Add event delegation states if (!event.isDefaultPrevented) { event.isDefaultPrevented = returnFalse; event.isPropagationStopped = returnFalse; event.isImmediatePropagationStopped = returnFalse; } // Add missing metaKey for IE 8 if (typeof event.metaKey == 'undefined') { event.metaKey = false; } return event; }
javascript
{ "resource": "" }
q35768
is
train
function is(obj, type) { if (!type) { return obj !== undefined; } if (type == 'array' && Arr.isArray(obj)) { return true; } return typeof obj == type; }
javascript
{ "resource": "" }
q35769
create
train
function create(s, p, root) { var self = this, sp, ns, cn, scn, c, de = 0; // Parse : <prefix> <class>:<super class> s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s); cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name // Create namespace for new class ns = self.createNS(s[3].replace(/\.\w+$/, ''), root); // Class already exists if (ns[cn]) { return; } // Make pure static class if (s[2] == 'static') { ns[cn] = p; if (this.onCreate) { this.onCreate(s[2], s[3], ns[cn]); } return; } // Create default constructor if (!p[cn]) { p[cn] = function () { }; de = 1; } // Add constructor and methods ns[cn] = p[cn]; self.extend(ns[cn].prototype, p); // Extend if (s[5]) { sp = self.resolve(s[5]).prototype; scn = s[5].match(/\.(\w+)$/i)[1]; // Class name // Extend constructor c = ns[cn]; if (de) { // Add passthrough constructor ns[cn] = function () { return sp[scn].apply(this, arguments); }; } else { // Add inherit constructor ns[cn] = function () { this.parent = sp[scn]; return c.apply(this, arguments); }; } ns[cn].prototype[cn] = ns[cn]; // Add super methods self.each(sp, function (f, n) { ns[cn].prototype[n] = sp[n]; }); // Add overridden methods self.each(p, function (f, n) { // Extend methods if needed if (sp[n]) { ns[cn].prototype[n] = function () { this.parent = sp[n]; return f.apply(this, arguments); }; } else { if (n != cn) { ns[cn].prototype[n] = f; } } }); } // Add static methods /*jshint sub:true*/ /*eslint dot-notation:0*/ self.each(p['static'], function (f, n) { ns[cn][n] = f; }); }
javascript
{ "resource": "" }
q35770
walk
train
function walk(o, f, n, s) { s = s || this; if (o) { if (n) { o = o[n]; } Arr.each(o, function (o, i) { if (f.call(s, o, i, n) === false) { return false; } walk(o, f, n, s); }); } }
javascript
{ "resource": "" }
q35771
createNS
train
function createNS(n, o) { var i, v; o = o || window; n = n.split('.'); for (i = 0; i < n.length; i++) { v = n[i]; if (!o[v]) { o[v] = {}; } o = o[v]; } return o; }
javascript
{ "resource": "" }
q35772
resolve
train
function resolve(n, o) { var i, l; o = o || window; n = n.split('.'); for (i = 0, l = n.length; i < l; i++) { o = o[n[i]]; if (!o) { break; } } return o; }
javascript
{ "resource": "" }
q35773
train
function (selector, context) { var self = this, match, node; if (!selector) { return self; } if (selector.nodeType) { self.context = self[0] = selector; self.length = 1; return self; } if (context && context.nodeType) { self.context = context; } else { if (context) { return DomQuery(selector).attr(context); } self.context = context = document; } if (isString(selector)) { self.selector = selector; if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { match = [null, selector, null]; } else { match = rquickExpr.exec(selector); } if (match) { if (match[1]) { node = createFragment(selector, getElementDocument(context)).firstChild; while (node) { push.call(self, node); node = node.nextSibling; } } else { node = getElementDocument(context).getElementById(match[2]); if (!node) { return self; } if (node.id !== match[2]) { return self.find(selector); } self.length = 1; self[0] = node; } } else { return DomQuery(context).find(selector); } } else { this.add(selector, false); } return self; }
javascript
{ "resource": "" }
q35774
train
function (items, sort) { var self = this, nodes, i; if (isString(items)) { return self.add(DomQuery(items)); } if (sort !== false) { nodes = DomQuery.unique(self.toArray().concat(DomQuery.makeArray(items))); self.length = nodes.length; for (i = 0; i < nodes.length; i++) { self[i] = nodes[i]; } } else { push.apply(self, DomQuery.makeArray(items)); } return self; }
javascript
{ "resource": "" }
q35775
train
function () { var self = this, node, i = this.length; while (i--) { node = self[i]; Event.clean(node); if (node.parentNode) { node.parentNode.removeChild(node); } } return this; }
javascript
{ "resource": "" }
q35776
train
function () { var self = this, node, i = this.length; while (i--) { node = self[i]; while (node.firstChild) { node.removeChild(node.firstChild); } } return this; }
javascript
{ "resource": "" }
q35777
train
function (value) { var self = this, i; if (isDefined(value)) { i = self.length; try { while (i--) { self[i].innerHTML = value; } } catch (ex) { // Workaround for "Unknown runtime error" when DIV is added to P on IE DomQuery(self[i]).empty().append(value); } return self; } return self[0] ? self[0].innerHTML : ''; }
javascript
{ "resource": "" }
q35778
train
function (value) { var self = this, i; if (isDefined(value)) { i = self.length; while (i--) { if ("innerText" in self[i]) { self[i].innerText = value; } else { self[0].textContent = value; } } return self; } return self[0] ? (self[0].innerText || self[0].textContent) : ''; }
javascript
{ "resource": "" }
q35779
train
function () { var self = this; if (self[0] && self[0].parentNode) { return domManipulate(self, arguments, function (node) { this.parentNode.insertBefore(node, this); }); } return self; }
javascript
{ "resource": "" }
q35780
train
function () { var self = this; if (self[0] && self[0].parentNode) { return domManipulate(self, arguments, function (node) { this.parentNode.insertBefore(node, this.nextSibling); }, true); } return self; }
javascript
{ "resource": "" }
q35781
train
function (className, state) { var self = this; // Functions are not supported if (typeof className != 'string') { return self; } if (className.indexOf(' ') !== -1) { each(className.split(' '), function () { self.toggleClass(this, state); }); } else { self.each(function (index, node) { var existingClassName, classState; classState = hasClass(node, className); if (classState !== state) { existingClassName = node.className; if (classState) { node.className = trim((" " + existingClassName + " ").replace(' ' + className + ' ', ' ')); } else { node.className += existingClassName ? ' ' + className : className; } } }); } return self; }
javascript
{ "resource": "" }
q35782
train
function (name) { return this.each(function () { if (typeof name == 'object') { Event.fire(this, name.type, name); } else { Event.fire(this, name); } }); }
javascript
{ "resource": "" }
q35783
train
function (selector) { var i, l, ret = []; for (i = 0, l = this.length; i < l; i++) { DomQuery.find(selector, this[i], ret); } return DomQuery(ret); }
javascript
{ "resource": "" }
q35784
train
function (selector) { if (typeof selector == 'function') { return DomQuery(grep(this.toArray(), function (item, i) { return selector(i, item); })); } return DomQuery(DomQuery.filter(selector, this.toArray())); }
javascript
{ "resource": "" }
q35785
train
function (selector) { var result = []; if (selector instanceof DomQuery) { selector = selector[0]; } this.each(function (i, node) { while (node) { if (typeof selector == 'string' && DomQuery(node).is(selector)) { result.push(node); break; } else if (node == selector) { result.push(node); break; } node = node.parentNode; } }); return DomQuery(result); }
javascript
{ "resource": "" }
q35786
train
function (node) { return Tools.toArray((node.nodeName === "iframe" ? node.contentDocument || node.contentWindow.document : node).childNodes); }
javascript
{ "resource": "" }
q35787
nativeDecode
train
function nativeDecode(text) { var elm; elm = document.createElement("div"); elm.innerHTML = text; return elm.textContent || elm.innerText || text; }
javascript
{ "resource": "" }
q35788
train
function (text, attr) { return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function (chr) { // Multi byte sequence convert it to a single entity if (chr.length > 1) { return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';'; } return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';'; }); }
javascript
{ "resource": "" }
q35789
train
function (text) { return text.replace(entityRegExp, function (all, numeric) { if (numeric) { if (numeric.charAt(0).toLowerCase() === 'x') { numeric = parseInt(numeric.substr(1), 16); } else { numeric = parseInt(numeric, 10); } // Support upper UTF if (numeric > 0xFFFF) { numeric -= 0x10000; return String.fromCharCode(0xD800 + (numeric >> 10), 0xDC00 + (numeric & 0x3FF)); } return asciiMap[numeric] || String.fromCharCode(numeric); } return reverseEntities[all] || namedEntities[all] || nativeDecode(all); }); }
javascript
{ "resource": "" }
q35790
wait
train
function wait(testCallback, waitCallback) { if (!testCallback()) { // Wait for timeout if ((new Date().getTime()) - startTime < maxLoadTime) { Delay.setTimeout(waitCallback); } else { failed(); } } }
javascript
{ "resource": "" }
q35791
waitForGeckoLinkLoaded
train
function waitForGeckoLinkLoaded() { wait(function () { try { // Accessing the cssRules will throw an exception until the CSS file is loaded var cssRules = style.sheet.cssRules; passed(); return !!cssRules; } catch (ex) { // Ignore } }, waitForGeckoLinkLoaded); }
javascript
{ "resource": "" }
q35792
DOMUtils
train
function DOMUtils(doc, settings) { var self = this, blockElementsMap; self.doc = doc; self.win = window; self.files = {}; self.counter = 0; self.stdMode = !isIE || doc.documentMode >= 8; self.boxModel = !isIE || doc.compatMode == "CSS1Compat" || self.stdMode; self.styleSheetLoader = new StyleSheetLoader(doc); self.boundEvents = []; self.settings = settings = settings || {}; self.schema = settings.schema; self.styles = new Styles({ url_converter: settings.url_converter, url_converter_scope: settings.url_converter_scope }, settings.schema); self.fixDoc(doc); self.events = settings.ownEvents ? new EventUtils(settings.proxy) : EventUtils.Event; self.attrHooks = setupAttrHooks(self, settings); blockElementsMap = settings.schema ? settings.schema.getBlockElements() : {}; self.$ = $.overrideDefaults(function () { return { context: doc, element: self.getRoot() }; }); /** * Returns true/false if the specified element is a block element or not. * * @method isBlock * @param {Node/String} node Element/Node to check. * @return {Boolean} True/False state if the node is a block element or not. */ self.isBlock = function (node) { // Fix for #5446 if (!node) { return false; } // This function is called in module pattern style since it might be executed with the wrong this scope var type = node.nodeType; // If it's a node then check the type and use the nodeName if (type) { return !!(type === 1 && blockElementsMap[node.nodeName]); } return !!blockElementsMap[node]; }; }
javascript
{ "resource": "" }
q35793
train
function (win) { var doc, rootElm; win = !win ? this.win : win; doc = win.document; rootElm = this.boxModel ? doc.documentElement : doc.body; // Returns viewport size excluding scrollbars return { x: win.pageXOffset || rootElm.scrollLeft, y: win.pageYOffset || rootElm.scrollTop, w: win.innerWidth || rootElm.clientWidth, h: win.innerHeight || rootElm.clientHeight }; }
javascript
{ "resource": "" }
q35794
train
function (elm) { var self = this, pos, size; elm = self.get(elm); pos = self.getPos(elm); size = self.getSize(elm); return { x: pos.x, y: pos.y, w: size.w, h: size.h }; }
javascript
{ "resource": "" }
q35795
train
function (elm) { var self = this, w, h; elm = self.get(elm); w = self.getStyle(elm, 'width'); h = self.getStyle(elm, 'height'); // Non pixel value, then force offset/clientWidth if (w.indexOf('px') === -1) { w = 0; } // Non pixel value, then force offset/clientWidth if (h.indexOf('px') === -1) { h = 0; } return { w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth, h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight }; }
javascript
{ "resource": "" }
q35796
train
function (node, selector, root, collect) { var self = this, selectorVal, result = []; node = self.get(node); collect = collect === undefined; // Default root on inline mode root = root || (self.getRoot().nodeName != 'BODY' ? self.getRoot().parentNode : null); // Wrap node name as func if (is(selector, 'string')) { selectorVal = selector; if (selector === '*') { selector = function (node) { return node.nodeType == 1; }; } else { selector = function (node) { return self.is(node, selectorVal); }; } } while (node) { if (node == root || !node.nodeType || node.nodeType === 9) { break; } if (!selector || selector(node)) { if (collect) { result.push(node); } else { return node; } } node = node.parentNode; } return collect ? result : null; }
javascript
{ "resource": "" }
q35797
train
function (elm) { var name; if (elm && this.doc && typeof elm == 'string') { name = elm; elm = this.doc.getElementById(elm); // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick if (elm && elm.id !== name) { return this.doc.getElementsByName(name)[1]; } } return elm; }
javascript
{ "resource": "" }
q35798
train
function (name, attrs, html) { return this.add(this.doc.createElement(name), name, attrs, html, 1); }
javascript
{ "resource": "" }
q35799
train
function (name, attrs, html) { var outHtml = '', key; outHtml += '<' + name; for (key in attrs) { if (attrs.hasOwnProperty(key) && attrs[key] !== null && typeof attrs[key] != 'undefined') { outHtml += ' ' + key + '="' + this.encode(attrs[key]) + '"'; } } // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime if (typeof html != "undefined") { return outHtml + '>' + html + '</' + name + '>'; } return outHtml + ' />'; }
javascript
{ "resource": "" }