_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q38700
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); if(args.length > 1) { throw new CommandArgLength(cmd); } }
javascript
{ "resource": "" }
q38701
execute
train
function execute(req, res) { if(req.args.length) return res.send(null, req.args[0]); res.send(null, Constants.PONG); }
javascript
{ "resource": "" }
q38702
defaultMigrationLoader
train
function defaultMigrationLoader(dir) { let list = new List; return new Promise((resolve, reject) => { fs.readdir(dir, function(err, files) { if (err) return reject(err); const migrationFiles = files.filter((file) => file.match(/^\d+.*\.js$/)).sort(); migrationFiles.forEach((file) => { let mod; try { mod = require(path.join(dir, file)); } catch (err) { return reject(err); } list = list.addMigration(file, mod.up, mod.down); }); resolve(list); }); }); }
javascript
{ "resource": "" }
q38703
checkHostmask
train
function checkHostmask (hostmask, admin) { return names.every(function (name) { const result = admin[name].test(hostmask[name]); client.debug("PluginAdmin", format("%s: %s, %s (%s)", name, hostmask[name], admin[name], result)); return result; }); }
javascript
{ "resource": "" }
q38704
train
function (hostmask, opts) { return Promise.try(function () { if (opts && opts.allowAll === true) { return true; } const customAdmins = opts && opts.customAdmins; const memoizationKey = opts && opts.memoizeOver; const hostmask_passed = (customAdmins || admins).filter(function (admin) { return checkHostmask(hostmask, admin); }); if (hostmask_passed.some(notHasIdentifiedasProperty)) { client.debug("PluginAdmin", "Admin object w/o identifiedas property (true)"); return true; } client.debug("PluginAdmin", "Admin object w/o identifiedas property (false)"); return (function recur () { if (hostmask_passed.length === 0) { client.debug("PluginAdmin", "User passes an identifiedas check (false)"); return false; } return Promise.try(function () { const hostmask = hostmask_passed.pop(); return hostmask.identifiedas; }) .then(function (accountname) { return isIdentifiedAs(hostmask.nickname, accountname, {memoizeOver: memoizationKey}); }) .then(function (isIdentifiedAs) { if (isIdentifiedAs) { client.debug("PluginAdmin", "User passes an identifiedas check (true)"); return true; } else { return recur(); } }); }()); }); }
javascript
{ "resource": "" }
q38705
ObsessedError
train
function ObsessedError(message, errors) { Error.captureStackTrace(this, ObsessedError); this.message = this.combine(message, errors); }
javascript
{ "resource": "" }
q38706
preparePlatforms
train
function preparePlatforms (platformList, projectRoot, options) { return Q.all(platformList.map(function(platform) { // TODO: this need to be replaced by real projectInfo // instance for current project. var project = { root: projectRoot, projectConfig: new ConfigParser(cordova_util.projectConfig(projectRoot)), locations: { plugins: path.join(projectRoot, 'plugins'), www: cordova_util.projectWww(projectRoot) } }; // CB-9987 We need to reinstall the plugins for the platform it they were added by cordova@<5.4.0 return restoreMissingPluginsForPlatform(platform, projectRoot, options) .then(function () { // platformApi prepare takes care of all functionality // which previously had been executed by cordova.prepare: // - reset config.xml and then merge changes from project's one, // - update www directory from project's one and merge assets from platform_www, // - reapply config changes, made by plugins, // - update platform's project // Please note that plugins' changes, such as installed js files, assets and // config changes is not being reinstalled on each prepare. var platformApi = platforms.getPlatformApi(platform); return platformApi.prepare(project, _.clone(options)) .then(function () { if (platform === 'windows' && !(platformApi instanceof PlatformApiPoly)) { // Windows Api doesn't fire 'pre_package' hook, so we fire it here return new HooksRunner(projectRoot).fire('pre_package', { wwwPath: platformApi.getPlatformInfo().locations.www, platforms: ['windows'], nohooks: options.nohooks }); } }) .then(function () { if (options.browserify) { var browserify = require('../plugman/browserify'); return browserify(project, platformApi); } }) .then(function () { // Handle edit-config in config.xml var platformRoot = path.join(projectRoot, 'platforms', platform); var platformJson = PlatformJson.load(platformRoot, platform); var munger = new PlatformMunger(platform, platformRoot, platformJson); munger.add_config_changes(project.projectConfig, /*should_increment=*/true).save_all(); }); }); })); }
javascript
{ "resource": "" }
q38707
defaultOpts
train
function defaultOpts (opts) { opts = opts || {}; opts.title = opts.title || 'Test Suite'; opts.ui = (opts.ui && opts.ui.toLowerCase() === 'tdd' ? 'tdd' : 'bdd'); opts.path = path.resolve(opts.path || '.'); opts.host = opts.host || 'localhost'; opts.port = opts.port || 3000; return opts; }
javascript
{ "resource": "" }
q38708
cleanup
train
function cleanup(key) { callbackQueue[key] = null; if (++nulls > nullThreshold) { callbackQueue = omit(callbackQueue, function removeNulls(datum) { return datum === null; }); } }
javascript
{ "resource": "" }
q38709
iterateOverCallbacks
train
function iterateOverCallbacks(bucket, args) { bucket.forEach(function iterator(callback) { nextTick(function queuedCallback() { callback.apply(null, args); }); }); }
javascript
{ "resource": "" }
q38710
touchstartHandler
train
function touchstartHandler(event) { if (Object.keys(gestures).length === 0) { docEl.addEventListener('touchmove', touchmoveHandler, false) docEl.addEventListener('touchend', touchendHandler, false) docEl.addEventListener('touchcancel', touchcancelHandler, false) } // record every touch for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i] var touchRecord = {} for (var p in touch) { touchRecord[p] = touch[p] } var gesture = { startTouch: touchRecord, startTime: Date.now(), status: 'tapping', element: event.srcElement || event.target, pressingHandler: setTimeout(function (element, touch) { return function () { if (gesture.status === 'tapping') { gesture.status = 'pressing' fireEvent(element, 'longpress', { // add touch data for jud touch: touch, touches: event.touches, changedTouches: event.changedTouches, touchEvent: event }) } clearTimeout(gesture.pressingHandler) gesture.pressingHandler = null } }(event.srcElement || event.target, event.changedTouches[i]), 500) } gestures[touch.identifier] = gesture } if (Object.keys(gestures).length == 2) { var elements = [] for (var p in gestures) { elements.push(gestures[p].element) } fireEvent(getCommonAncestor(elements[0], elements[1]), 'dualtouchstart', { touches: slice.call(event.touches), touchEvent: event }) } }
javascript
{ "resource": "" }
q38711
touchendHandler
train
function touchendHandler(event) { if (Object.keys(gestures).length == 2) { var elements = [] for (var p in gestures) { elements.push(gestures[p].element) } fireEvent(getCommonAncestor(elements[0], elements[1]), 'dualtouchend', { touches: slice.call(event.touches), touchEvent: event }) } for (var i = 0; i < event.changedTouches.length; i++) { var touch = event.changedTouches[i] var id = touch.identifier var gesture = gestures[id] if (!gesture) { continue } if (gesture.pressingHandler) { clearTimeout(gesture.pressingHandler) gesture.pressingHandler = null } if (gesture.status === 'tapping') { gesture.timestamp = Date.now() fireEvent(gesture.element, 'tap', { touch: touch, touchEvent: event }) if (lastTap && gesture.timestamp - lastTap.timestamp < 300) { fireEvent(gesture.element, 'doubletap', { touch: touch, touchEvent: event }) } lastTap = gesture } if (gesture.status === 'panning') { var now = Date.now() var duration = now - gesture.startTime var displacementX = touch.clientX - gesture.startTouch.clientX var displacementY = touch.clientY - gesture.startTouch.clientY var velocity = Math.sqrt(gesture.velocityY * gesture.velocityY + gesture.velocityX * gesture.velocityX) var isSwipe = velocity > 0.5 && (now - gesture.lastTime) < 100 var extra = { duration: duration, isSwipe: isSwipe, velocityX: gesture.velocityX, velocityY: gesture.velocityY, displacementX: displacementX, displacementY: displacementY, touch: touch, touches: event.touches, changedTouches: event.changedTouches, touchEvent: event, isVertical: gesture.isVertical, direction: gesture.direction } fireEvent(gesture.element, 'panend', extra) if (isSwipe) { fireEvent(gesture.element, 'swipe', extra) } } if (gesture.status === 'pressing') { fireEvent(gesture.element, 'pressend', { touch: touch, touchEvent: event }) } delete gestures[id] } if (Object.keys(gestures).length === 0) { docEl.removeEventListener('touchmove', touchmoveHandler, false) docEl.removeEventListener('touchend', touchendHandler, false) docEl.removeEventListener('touchcancel', touchcancelHandler, false) } }
javascript
{ "resource": "" }
q38712
replWriter
train
function replWriter(output) { if (output){ if (output.constructor && output.constructor.name !== "String"){ return util.inspect(output, {colors:true}) + '\n'; } } return output + '\n'; }
javascript
{ "resource": "" }
q38713
train
function (msg, line, column) { this._info(line || this.line, column || this.column, msg, true, true); }
javascript
{ "resource": "" }
q38714
xToValue
train
function xToValue(x) { const rect = this.$.getBoundingClientRect(), percent = x / rect.width, range = this.max - this.min, value = Math.floor(percent * range + 0.5); return this.min + this.step * Math.floor(value / this.step); }
javascript
{ "resource": "" }
q38715
valueToX
train
function valueToX(value) { const rect = this.$.getBoundingClientRect(), percent = (value - this.min) / (this.max - this.min); return rect.width * percent; }
javascript
{ "resource": "" }
q38716
onDrag
train
function onDrag(evt) { const rect = this._rect, x = valueToX.call(this, this._value), min = -x, max = rect.width - x, tx = clamp(evt.x - evt.x0, min, max), value = xToValue.call(this, x + tx); Dom.css(this.$elements.button, { transform: `translateX(${tx}px)` }); this.displayedValue = valueToDisplayedValue.call(this, value); if (this.smooth) { this._dragging = true; this.value = value; } }
javascript
{ "resource": "" }
q38717
onDragEnd
train
function onDragEnd(evt) { this._dragging = false; const rect = this._rect, x = valueToX.call(this, this._value), min = -x, max = rect.width - x, tx = clamp(evt.x - evt.x0, min, max); Dom.css(this.$elements.button, { transform: `translateX(0px)` }); this.value = xToValue.call(this, x + tx); }
javascript
{ "resource": "" }
q38718
moveToValue
train
function moveToValue(value) { const left = 100 * (value - this.min) / (this.max - this.min); Dom.css(this.$elements.button, { left: `${left}%` }); }
javascript
{ "resource": "" }
q38719
categoryPathPlain
train
function categoryPathPlain(patternObject) { 'use strict'; // check for subcategory if (patternObject.subcategory) { return path.join(patternObject.category, patternObject.subcategory); } else { return patternObject.category; } }
javascript
{ "resource": "" }
q38720
categoryPathConverted
train
function categoryPathConverted(categoryObject, patternObject) { 'use strict'; // convert our category path using the categoryObject var categoryPath = utility.categoryNameConverter(categoryObject.categories, patternObject.category); // check for subcategory if (patternObject.subcategory) { var subcategoryPath = utility.categoryNameConverter(categoryObject.subcategories[categoryPath], patternObject.subcategory); return path.join(categoryPath, subcategoryPath); } else { return categoryPath; } }
javascript
{ "resource": "" }
q38721
getHandoffFromUpdate
train
async function getHandoffFromUpdate (update) { if (!has(update, 'message.text')) { return } // having to do own request as watson-developer-cloud package is broken for // Tone analyzer const toneAnalyzerUrl = 'https://gateway.watsonplatform.net/tone-analyzer/api' const params = { // Get the text from the JSON file. text: update.message.text, tones: 'emotion', version: '2016-05-19' } const requestOptions = { url: `${toneAnalyzerUrl}/v3/tone`, method: 'GET', qs: params, auth: { username: TONE_ANALYSIS_USERNAME, password: TONE_ANALYSIS_PASSWORD }, json: true } const tone = await request(requestOptions) if (has(tone, 'document_tone.tone_categories[0].tones')) { const sentiments = tone.document_tone.tone_categories[0].tones // return sentiment before const badSentimentThreshold = 0.7 for (const sentiment of sentiments) { // not too sure about the ones other than anger for now tbh if (['Anger', 'Disgust', 'Fear', 'Sadness'].indexOf(sentiment.tone_name) > -1 && sentiment.score > badSentimentThreshold) { return 'lowSentiment' } } } }
javascript
{ "resource": "" }
q38722
train
function(path, obj) { if(path == '#') return obj; path = path.substr(1); var parts = path.split('/'); parts.shift(); // Locate object for(var i = 0; i < parts.length; i++) { obj = obj[parts[i]]; } return obj; }
javascript
{ "resource": "" }
q38723
train
function(reference, callback) { var url = reference.url; var uri = reference.uri; var schema = reference.schema; // Execute the request request(url, function(error, response, body) { // We have an error if(error) return callback(error); // Got the body, parse it var obj = JSON.parse(body); // Resolve the object explode(obj, function(err, obj) { if(err) return callback(err); // Split the url out to locate the right place var path = url.substr(url.indexOf('#')); // Locate the actual document we want var pathObj = resolve(path, obj); // Replace the node delete schema['$ref']; for(var name in pathObj) { schema[name] = pathObj[name]; } // Return the result callback(); }) }); }
javascript
{ "resource": "" }
q38724
train
function(schema, field, reference, seenObjects, path, options) { // Don't resolve recursive relation if(reference == '#') return {$ref: '#'} // Get the path var path = reference.substr(1).split('/').slice(1); path = path.map(function(x) { x = x.replace(/~1/g, '/').replace(/~0/g, '~'); return decodeURI(x); }) // Get a pointer to the schema var pointer = schema; // Traverse the schema for(var i = 0; i < path.length; i++) { pointer = pointer[path[i]]; } // Check if we have seen the object var objects = seenObjects.filter(function(x) { return x.obj === pointer; }); if(objects.length == 1) { seenObjects[0].count = objects[0].count + 1; } else { seenObjects.push({obj: pointer, count: 1}); } // Do we have a reference if(pointer['$ref']) { return deref(schema, field, pointer['$ref'], seenObjects, path, options); } else { extractReferences(schema, pointer, seenObjects, path, options); } return pointer; }
javascript
{ "resource": "" }
q38725
pathToId
train
function pathToId(file, base, rel) { var id = rel ? path.resolve(rel, '..', file) : file; id = path.relative(base, id); // replace \ with / in windows' path and remove extname in path id = id.replace(BACKLASH_RE, '/').replace(JS_EXT_RE, ''); return id; }
javascript
{ "resource": "" }
q38726
idToPath
train
function idToPath(id, config) { var alias = config.alias || {}; return alias.hasOwnProperty(id) ? path.resolve(alias[id]) : path.resolve(config.base, id) + '.js'; }
javascript
{ "resource": "" }
q38727
replaceAdjacentAt
train
function replaceAdjacentAt(index, newValues, array) { error_if_not_array_1.errorIfNotArray(newValues); // The other parameters, index and array, are type-checked here: array_replace_adjacent_items_1._replaceAdjacentItems(index, newValues.length, newValues, array); }
javascript
{ "resource": "" }
q38728
append
train
function append (value, string) { if ( value === null || value === undefined || value === '' || string === null || string === undefined ) { return value } return value + string }
javascript
{ "resource": "" }
q38729
TokenParser
train
function TokenParser(tokens, filters, autoescape, line, filename) { this.out = []; this.state = []; this.filterApplyIdx = []; this._parsers = {}; this.line = line; this.filename = filename; this.filters = filters; this.escape = autoescape; this.parse = function () { var self = this; if (self._parsers.start) { self._parsers.start.call(self); } utils.each(tokens, function (token, i) { var prevToken = tokens[i - 1]; self.isLast = (i === tokens.length - 1); if (prevToken) { while (prevToken.type === _t.WHITESPACE) { i -= 1; prevToken = tokens[i - 1]; } } self.prevToken = prevToken; self.parseToken(token); }); if (self._parsers.end) { self._parsers.end.call(self); } if (self.escape) { self.filterApplyIdx = [0]; if (typeof self.escape === 'string') { self.parseToken({ type: _t.FILTER, match: 'e' }); self.parseToken({ type: _t.COMMA, match: ',' }); self.parseToken({ type: _t.STRING, match: String(autoescape) }); self.parseToken({ type: _t.PARENCLOSE, match: ')'}); } else { self.parseToken({ type: _t.FILTEREMPTY, match: 'e' }); } } return self.out; }; }
javascript
{ "resource": "" }
q38730
train
function (token, match, lastState) { var self = this; match = match.split('.'); if (_reserved.indexOf(match[0]) !== -1) { utils.throwError('Reserved keyword "' + match[0] + '" attempted to be used as a variable', self.line, self.filename); } self.filterApplyIdx.push(self.out.length); if (lastState === _t.CURLYOPEN) { if (match.length > 1) { utils.throwError('Unexpected dot', self.line, self.filename); } self.out.push(match[0]); return; } self.out.push(self.checkMatch(match)); }
javascript
{ "resource": "" }
q38731
train
function (match) { var temp = match[0], result; function checkDot(ctx) { var c = ctx + temp, m = match, build = ''; build = '(typeof ' + c + ' !== "undefined" && ' + c + ' !== null'; utils.each(m, function (v, i) { if (i === 0) { return; } build += ' && ' + c + '.' + v + ' !== undefined && ' + c + '.' + v + ' !== null'; c += '.' + v; }); build += ')'; return build; } function buildDot(ctx) { return '(' + checkDot(ctx) + ' ? ' + ctx + match.join('.') + ' : "")'; } result = '(' + checkDot('_ctx.') + ' ? ' + buildDot('_ctx.') + ' : ' + buildDot('') + ')'; return '(' + result + ' !== null ? ' + result + ' : ' + '"" )'; }
javascript
{ "resource": "" }
q38732
parseVariable
train
function parseVariable(str, line) { var tokens = lexer.read(utils.strip(str)), parser, out; parser = new TokenParser(tokens, filters, escape, line, opts.filename); out = parser.parse().join(''); if (parser.state.length) { utils.throwError('Unable to parse "' + str + '"', line, opts.filename); } /** * A parsed variable token. * @typedef {object} VarToken * @property {function} compile Method for compiling this token. */ return { compile: function () { return '_output += ' + out + ';\n'; } }; }
javascript
{ "resource": "" }
q38733
parseTag
train
function parseTag(str, line) { var tokens, parser, chunks, tagName, tag, args, last; if (utils.startsWith(str, 'end')) { last = stack[stack.length - 1]; if (last && last.name === str.split(/\s+/)[0].replace(/^end/, '') && last.ends) { switch (last.name) { case 'autoescape': escape = opts.autoescape; break; case 'raw': inRaw = false; break; } stack.pop(); return; } if (!inRaw) { utils.throwError('Unexpected end of tag "' + str.replace(/^end/, '') + '"', line, opts.filename); } } if (inRaw) { return; } chunks = str.split(/\s+(.+)?/); tagName = chunks.shift(); if (!tags.hasOwnProperty(tagName)) { utils.throwError('Unexpected tag "' + str + '"', line, opts.filename); } tokens = lexer.read(utils.strip(chunks.join(' '))); parser = new TokenParser(tokens, filters, false, line, opts.filename); tag = tags[tagName]; /** * Define custom parsing methods for your tag. * @callback parse * * @example * exports.parse = function (str, line, parser, types, options, swig) { * parser.on('start', function () { * // ... * }); * parser.on(types.STRING, function (token) { * // ... * }); * }; * * @param {string} str The full token string of the tag. * @param {number} line The line number that this tag appears on. * @param {TokenParser} parser A TokenParser instance. * @param {TYPES} types Lexer token type enum. * @param {TagToken[]} stack The current stack of open tags. * @param {SwigOpts} options Swig Options Object. * @param {object} swig The Swig instance (gives acces to loaders, parsers, etc) */ if (!tag.parse(chunks[1], line, parser, _t, stack, opts, swig)) { utils.throwError('Unexpected tag "' + tagName + '"', line, opts.filename); } parser.parse(); args = parser.out; switch (tagName) { case 'autoescape': escape = (args[0] !== 'false') ? args[0] : false; break; case 'raw': inRaw = true; break; } /** * A parsed tag token. * @typedef {Object} TagToken * @property {compile} [compile] Method for compiling this token. * @property {array} [args] Array of arguments for the tag. * @property {Token[]} [content=[]] An array of tokens that are children of this Token. * @property {boolean} [ends] Whether or not this tag requires an end tag. * @property {string} name The name of this tag. */ return { block: !!tags[tagName].block, compile: tag.compile, args: args, content: [], ends: tag.ends, name: tagName }; }
javascript
{ "resource": "" }
q38734
getBuildArgs
train
function getBuildArgs(options) { // if no options passed, empty object will be returned if (!options) return []; var downstreamArgs = []; var argNames =[ 'debug', 'release', 'device', 'emulator', 'nobuild', 'list' ]; argNames.forEach(function(flag) { if (options[flag]) { downstreamArgs.push('--' + flag); } }); if (options.buildConfig) { downstreamArgs.push('--buildConfig=' + options.buildConfig); } if (options.target) { downstreamArgs.push('--target=' + options.target); } if (options.archs) { downstreamArgs.push('--archs=' + options.archs); } var unparsedArgs = options.argv || []; return downstreamArgs.concat(unparsedArgs); }
javascript
{ "resource": "" }
q38735
getPlatformVersion
train
function getPlatformVersion (platformRoot) { var versionFile = path.join(platformRoot, 'cordova/version'); if (!fs.existsSync(versionFile)) { return null; } var version = shell.cat(versionFile).match(/VERSION\s=\s["'](.*)["'];/m); return version && version[1]; }
javascript
{ "resource": "" }
q38736
functs
train
function functs(...f) { /** * execute all included functions * @param {...*} [args] - arguments passed to all included functions * @returns {*[]} */ function functs(...args) { return functs.run(this, args); } if(Array.isArray(f[0])) { f = f[0]; } functs._f = f.filter((f) => { return typeof f === 'function'; }); functs.add = add.bind(functs); functs.remove = remove.bind(functs); functs.run = run.bind(functs); return functs; }
javascript
{ "resource": "" }
q38737
add
train
function add(...f) { if(Array.isArray(f[0])) { f = f[0]; } f = f.filter((f) => { return typeof f === 'function'; }); this._f.push.apply(this._f, f); return f; }
javascript
{ "resource": "" }
q38738
remove
train
function remove(...key) { const self = this; if(Array.isArray(key[0])) { key = key[0]; } key.forEach(k => { self._f = self._f.filter(f => { return f !== k; }); }); }
javascript
{ "resource": "" }
q38739
run
train
function run(thisArg, args) { var end = -1; const r = this._f.map((f, i) => { if(end === -1) { return f.apply(thisArg, args.concat(abort)); } function abort() { end = i; } }); if(end === -1) { return r; } return r.slice(0, end); }
javascript
{ "resource": "" }
q38740
parse
train
function parse(script, options, macros) { var name = script.attr('id'); var text = script.text(); var atts = assistant.directives(script); return compile(name, text, options, macros, atts); }
javascript
{ "resource": "" }
q38741
compile
train
function compile(name, edbml, options, macros, directives) { var result = compiler.compile(edbml, options, macros, directives); return assistant.declare(name, result); }
javascript
{ "resource": "" }
q38742
addParams
train
function addParams(name,command,key,tag,emphasis) { var thisCssNo = buttons.length+1; return buttons.push({name:name, cls:thisCssNo, command:command, key:key, tag:tag, emphasis:emphasis}); }
javascript
{ "resource": "" }
q38743
selectionGet
train
function selectionGet() { // for webkit, mozilla, opera if (window.getSelection) return window.getSelection(); // for ie else if (document.selection && document.selection.createRange && document.selection.type != "None") return document.selection.createRange(); }
javascript
{ "resource": "" }
q38744
selectionSet
train
function selectionSet(addCommand,thirdParam) { var range, sel = selectionGet(); // for webkit, mozilla, opera if (window.getSelection) { if (sel.anchorNode && sel.getRangeAt) range = sel.getRangeAt(0); if(range) { sel.removeAllRanges(); sel.addRange(range); } if(!thisBrowser.match(/msie/)) document.execCommand('StyleWithCSS', false, false); document.execCommand(addCommand, false, thirdParam); } // for ie else if (document.selection && document.selection.createRange && document.selection.type != "None") { range = document.selection.createRange(); range.execCommand(addCommand, false, thirdParam); } // change styles to around tags affectStyleAround(false,false); }
javascript
{ "resource": "" }
q38745
replaceSelection
train
function replaceSelection(tTag,tAttr,tVal) { // first, prevent to conflict of different jqte editors if(editor.not(":focus")) editor.focus(); // for webkit, mozilla, opera if (window.getSelection) { var selObj = selectionGet(), selRange, newElement, documentFragment; if (selObj.anchorNode && selObj.getRangeAt) { selRange = selObj.getRangeAt(0); // create to new element newElement = document.createElement(tTag); // add the attribute to the new element $(newElement).attr(tAttr,tVal); // extract to the selected text documentFragment = selRange.extractContents(); // add the contents to the new element newElement.appendChild(documentFragment); selRange.insertNode(newElement); selObj.removeAllRanges(); // if the attribute is "style", change styles to around tags if(tAttr=="style") affectStyleAround($(newElement),tVal); // for other attributes else affectStyleAround($(newElement),false); } } // for ie else if (document.selection && document.selection.createRange && document.selection.type != "None") { var range = document.selection.createRange(); var selectedText = range.htmlText; var newText = '<'+tTag+' '+tAttr+'="'+tVal+'">'+selectedText+'</'+tTag+'>'; document.selection.createRange().pasteHTML(newText); } }
javascript
{ "resource": "" }
q38746
train
function() { var node,selection; if(window.getSelection) { selection = getSelection(); node = selection.anchorNode; } if(!node && document.selection && document.selection.createRange && document.selection.type != "None") { selection = document.selection; var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange(); node = range.commonAncestorContainer ? range.commonAncestorContainer : range.parentElement ? range.parentElement() : range.item(0); } if(node) { return (node.nodeName == "#text" ? $(node.parentNode) : $(node)); } else return false; }
javascript
{ "resource": "" }
q38747
selectText
train
function selectText(element) { if(element) { var element = element[0]; if (document.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); if(element != "undefined" && element != null) { range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); if($(element).is(":empty")) { $(element).append("&nbsp;"); selectText($(element)); } } } } }
javascript
{ "resource": "" }
q38748
selected2link
train
function selected2link() { if(!toolbar.data("sourceOpened")) { var selectedTag = getSelectedNode(); // the selected node var thisHrefLink = "http://"; // default the input value of the link-form-field // display the link-form-field linkAreaSwitch(true); if(selectedTag) { var thisTagName = selectedTag.prop('tagName').toLowerCase(); // if tag name of the selected node is "a" and the selected node have "href" attribute if(thisTagName == "a" && selectedTag.is('[href]')) { thisHrefLink = selectedTag.attr('href'); selectedTag.attr(setdatalink,""); } // if it don't have "a" tag name else replaceSelection("a",setdatalink,""); } else linkinput.val(thisHrefLink).focus(); // the method of displaying-hiding to link-types linktypeselect.click(function(e) { if($(e.target).hasClass(vars.css+"_linktypetext") || $(e.target).hasClass(vars.css+"_linktypearrow")) linktypeSwitch(true); }); // the method of selecting to link-types linktypes.find("a").click(function() { var thisLinkType = $(this).attr(vars.css+"-linktype"); linktypes.data("linktype",thisLinkType) linktypeview.find("."+vars.css+"_linktypetext").html(linktypes.find('a:eq('+linktypes.data("linktype")+')').text()); linkInputSet(thisHrefLink); linktypeSwitch(); }); linkInputSet(thisHrefLink); // the method of link-input linkinput // auto focus .focus() // update to value .val(thisHrefLink) // the event of key to enter in link-input .bind("keypress keyup",function(e) { if(e.keyCode==13) { linkRecord(jQTE.find("["+setdatalink+"]")); return false; } }); // the event of click link-button linkbutton.click(function() { linkRecord(jQTE.find("["+setdatalink+"]")); }); } else // hide the link-form-field linkAreaSwitch(false); }
javascript
{ "resource": "" }
q38749
linkAreaSwitch
train
function linkAreaSwitch(status) { // remove all pre-link attribute (mark as "link will be added") clearSetElement("["+setdatalink+"]:not([href])"); jQTE.find("["+setdatalink+"][href]").removeAttr(setdatalink); if(status) { toolbar.data("linkOpened",true); linkform.show(); } else { toolbar.data("linkOpened",false); linkform.hide(); } linktypeSwitch(); }
javascript
{ "resource": "" }
q38750
linkInputSet
train
function linkInputSet(thisHrefLink) { var currentType = linktypes.data("linktype"); // if selected type of e-mail if(currentType=="1" && (linkinput.val()=="http://" || linkinput.is("[value^=http://]") || !linkinput.is("[value^=mailto]"))) linkinput.val("mailto:"); else if(currentType!="1" && !linkinput.is("[value^=http://]")) linkinput.val("http://"); else linkinput.val(thisHrefLink); }
javascript
{ "resource": "" }
q38751
refuseStyle
train
function refuseStyle(refStyle) { var selectedTag = getSelectedNode(); // the selected node // if the selected node have attribute of "style" and it have unwanted style if(selectedTag && selectedTag.is("[style]") && selectedTag.css(refStyle)!="") { var refValue = selectedTag.css(refStyle); // first get key of unwanted style selectedTag.css(refStyle,""); // clear unwanted style var cleanStyle = selectedTag.attr("style"); // cleaned style selectedTag.css(refStyle,refValue); // add unwanted style to the selected node again return cleanStyle; // print cleaned style } else return ""; }
javascript
{ "resource": "" }
q38752
formatLabelView
train
function formatLabelView(str) { var formatLabel = formatbar.closest("."+vars.css+"_tool").find("."+vars.css+"_tool_label").find("."+vars.css+"_tool_text"); if(str.length > 10) str = str.substr(0,7) + "..."; // change format label of button formatLabel.html(str); }
javascript
{ "resource": "" }
q38753
extractToText
train
function extractToText(strings) { var $htmlContent, $htmlPattern, $htmlReplace; // first remove to unnecessary gaps $htmlContent = strings.replace(/\n/gim,'').replace(/\r/gim,'').replace(/\t/gim,'').replace(/&nbsp;/gim,' '); $htmlPattern = [ /\<span(|\s+.*?)><span(|\s+.*?)>(.*?)<\/span><\/span>/gim, // trim nested spans /<(\w*[^p])\s*[^\/>]*>\s*<\/\1>/gim, // remove empty or white-spaces tags (ignore paragraphs (<p>) and breaks (<br>)) /\<div(|\s+.*?)>(.*?)\<\/div>/gim, // convert div to p /\<strong(|\s+.*?)>(.*?)\<\/strong>/gim, // convert strong to b /\<em(|\s+.*?)>(.*?)\<\/em>/gim // convert em to i ]; $htmlReplace = [ '<span$2>$3</span>', '', '<p$1>$2</p>', '<b$1>$2</b>', '<i$1>$2</i>' ]; // repeat the cleaning process 5 times for(c=0; c<5; c++) { // create loop as the number of pattern for(var i = 0; i < $htmlPattern.length; i++) { $htmlContent = $htmlContent.replace($htmlPattern[i], $htmlReplace[i]); } } // if paragraph is false (<p>), convert <p> to <br> if(!vars.p) $htmlContent = $htmlContent.replace(/\<p(|\s+.*?)>(.*?)\<\/p>/ig, '<br/>$2'); // if break is false (<br>), convert <br> to <p> if(!vars.br) { $htmlPattern = [ /\<br>(.*?)/ig, /\<br\/>(.*?)/ig ]; $htmlReplace = [ '<p>$1</p>', '<p>$1</p>' ]; // create loop as the number of pattern (for breaks) for (var i = 0; i < $htmlPattern.length; i++) { $htmlContent = $htmlContent.replace($htmlPattern[i], $htmlReplace[i]); } } // if paragraph and break is false (<p> && <br>), convert <p> to <div> if(!vars.p && !vars.br) $htmlContent = $htmlContent.replace(/\<p>(.*?)\<\/p>/ig, '<div>$1</div>'); return $htmlContent; }
javascript
{ "resource": "" }
q38754
buttonEmphasize
train
function buttonEmphasize(e) { for(var n = 0; n < buttons.length; n++) { if(vars[buttons[n].name] && buttons[n].emphasis && buttons[n].tag!='') detectElement(buttons[n].tag) ? toolbar.find('.'+vars.css+'_tool_'+buttons[n].cls).addClass(emphasize) : $('.'+vars.css+'_tool_'+buttons[n].cls).removeClass(emphasize); } // showing text format if(vars.format && $.isArray(vars.formats)) { var isFoundFormat = false; for(var f = 0; f < vars.formats.length; f++) { var thisFormat = []; thisFormat[0] = vars.formats[f][0]; if(vars.formats[f][0].length>0 && detectElement(thisFormat)) { formatLabelView(vars.formats[f][1]); isFoundFormat = true; break; } } if(!isFoundFormat) formatLabelView(vars.formats[0][1]); } // hide all style-fields styleFieldSwitch("",false); formatFieldSwitch(false); }
javascript
{ "resource": "" }
q38755
update
train
function update (opt) { // remove old shaders disposeShaders() var quiet = opt.quiet var attributeBindings = opt.attributes var vertSrc = opt.vertex || defaultVertex var fragSrc = opt.fragment || defaultFragment // re-compile source vertexShader = compileShader(gl, gl.VERTEX_SHADER, vertSrc, quiet, name) fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fragSrc, quiet, name) // re-link var shaders = [ vertexShader, fragmentShader ] linkShaders(gl, program, shaders, attributeBindings, quiet, name) // extract uniforms and attributes types = extract(gl, program) // allow user to inject some dummy uniforms if (opt.uniforms) { var inactiveUniforms = [] opt.uniforms.forEach(function (uniform) { if (indexOfName(types.uniforms, uniform.name) === -1) { inactiveUniforms.push(uniform) types.uniforms.push({ name: uniform.name, type: uniform.type }) } }) // provide UX for inactive uniforms...? TBD if (!quiet && inactiveUniforms.length > 0) { var shaderName = name ? (' (' + name + ')') : '' console.warn('Inactive uniforms in shader' + shaderName + ': ' + inactiveUniforms .map(function (x) { return x.name }) .join(', ')) } } // normalize sort order by name across Chrome / FF types.uniforms.sort(compareString) types.attributes.sort(compareString) // provide optimized getters/setters uniforms = reflect(types.uniforms, function (uniform, index) { return makeUniformProp(uniform, index) }) // provide attribute locations and type // (GLSL ES does not support array/struct attributes) attributes = types.attributes.reduce(function (struct, attrib) { var name = attrib.name struct[name] = { size: dimension(attrib.type), type: attrib.type, location: gl.getAttribLocation(program, name) } return struct }, {}) }
javascript
{ "resource": "" }
q38756
runCommand
train
function runCommand(cmd, args, options) { return new Promise((resolve, reject) => { const spwan = spawn( cmd, args, Object.assign( { cwd: process.cwd(), stdio: 'inherit', shell: true, }, options ) ) spwan.on('exit', () => { resolve() }) }) }
javascript
{ "resource": "" }
q38757
existsFile
train
function existsFile(file, permission) { return Promise.resolve(fsPromise.accessAsync(file, permission)) .then(() => true) .catch(() => false); }
javascript
{ "resource": "" }
q38758
generateReturnableError
train
function generateReturnableError(error) { if (_.isError(error)) { return { body: {error: error.message}, options: {code: httpCodes.INTERNAL_SERVER_ERROR} }; } if (_.isString(error)) { return { body: {error}, options: {code: httpCodes.INTERNAL_SERVER_ERROR} }; } if (_.isObject(error) && !_.isFunction(error)) { if (_.isArray(error)) { return { body: {error}, options: {code: httpCodes.INTERNAL_SERVER_ERROR} }; } let code = error.code || httpCodes.INTERNAL_SERVER_ERROR; delete error.code; return { body: error, options: {code} }; } if (_.isFunction(error)) { return { body: {error: 'Incorrect error type "function"'}, options: {code: httpCodes.INTERNAL_SERVER_ERROR} }; } return { body: {error: 'Unexpected error format'}, options: {code: httpCodes.INTERNAL_SERVER_ERROR} }; }
javascript
{ "resource": "" }
q38759
build
train
async function build() { const clientConfig = await webpackConfig({target: 'web', env: 'prod'}); const serverConfig = await webpackConfig({target: 'node', env: 'prod'}); return new Promise((resolve, reject) => { console.log('Compiling client...'); // eslint-disable-next-line consistent-return webpack(clientConfig, (clientError, clientStats) => { if (clientError) { return reject(clientError); } const clientMessages = formatWebpackMessages(clientStats.toJson({}, true)); if (clientMessages.errors.length) { return reject(new Error(clientMessages.errors.join('\n\n'))); } if ( process.env.CI && (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') && clientMessages.warnings.length ) { console.log( chalk.yellow( '\nTreating warnings as errors because process.env.CI = true.\n' + 'Most CI servers set it automatically.\n' ) ); return reject(new Error(clientMessages.warnings.join('\n\n'))); } console.log(chalk.green('Compiled client successfully.'), '\n'); console.log('Compiling server...'); webpack(serverConfig, (serverError, serverStats) => { if (serverError) { return reject(serverError); } const serverMessages = formatWebpackMessages(serverStats.toJson({}, true)); if (serverMessages.errors.length) { return reject(new Error(serverMessages.errors.join('\n\n'))); } if ( process.env.CI && (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') && serverMessages.warnings.length ) { console.log( chalk.yellow( '\nTreating warnings as errors because process.env.CI = true.\n' + 'Most CI servers set it automatically.\n' ) ); return reject(new Error(serverMessages.warnings.join('\n\n'))); } console.log(chalk.green('Compiled server successfully.'), '\n'); return resolve({ stats: clientStats, warnings: Object.assign({}, clientMessages.warnings, serverMessages.warnings), }); }); }); }); }
javascript
{ "resource": "" }
q38760
Link
train
function Link(href, rel, type) { if (typeof href == 'object') { var options = href; this.href = options.href; this.template = options.template; this.rel = options.rel; this.type = options.type; } else { this.href = href; this.rel = rel; this.type = type; } this.titles = new MultiHash(); this.properties = new MultiHash(); }
javascript
{ "resource": "" }
q38761
on
train
function on(evt, handler) { var _this = this; var thisArg = arguments[2] === undefined ? null : arguments[2]; // if multiple events are passed, call our utility method `eachEvt` to deal with this. // if it returns `true`, we should exit, because we're actually being called recursively. // If it returns `false`, we're not being called with multiple parameters (this time, anyway), // and so can continue processing. if (eachEvt(evt, handler, thisArg, function () { for (var _len2 = arguments.length, _ = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { _[_key2] = arguments[_key2]; } return _this.on.apply(_this, _); })) { return this; } // simplify typing; eH = eventHandlers var eH = this[_eventHandlers]; if (!eH.has(evt)) { // if we don't have an event category already in the map, create it as a new map // this map will be of the form bindingObject:methods. eH.set(evt, new core.Map()); } // simplify typing; objMap == objectMap (bindingObject:methods) var objMap = eH.get(evt); if (!objMap.has(thisArg)) { // if we don't have `thisArg` in the map, make a set for it. The set is the set of functions // and we use a set so as to prevent duplicates automatically. objMap.set(thisArg, new core.Set()); } var handlerSet = objMap.get(thisArg); if (typeof handler === "function") { // add the handler handlerSet.add(handler); } else { // a little error checking! throw new TypeError("Event handler must be a function."); } return this; }
javascript
{ "resource": "" }
q38762
off
train
function off(evt, handler) { var _this2 = this; var thisArg = arguments[2] === undefined ? null : arguments[2]; // handle multiple events appropriately. if (eachEvt(evt, handler, thisArg, function () { for (var _len3 = arguments.length, _ = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { _[_key3] = arguments[_key3]; } return _this2.off.apply(_this2, _); })) { return this; }if (evt === undefined && handler === undefined && thisArg === null) { // remove all event handlers. Easiest way to do this is just create a new event map this[_eventHandlers] = new core.Map(); return this; } var eH = this[_eventHandlers]; if (handler === undefined && thisArg === null) { // remove all handlers for a specific event. Easiest way to do this is just create a new object map eH.set(evt, new core.Map()); return this; } var objMap = eH.get(evt); if (objMap !== undefined) { // the following cases apply only if we have an object map for the event -- otherwise we do nothing. if (typeof handler === "object") { // remove all handlers in a given event category for a specific object objMap["delete"](handler); return this; } // only remove if we have the event map in the first place var handlerSet = objMap.get(thisArg); if (handlerSet !== undefined) { handlerSet["delete"](handler); if (handlerSet.size === 0) { eH["delete"](objMap); } } } return this; }
javascript
{ "resource": "" }
q38763
once
train
function once(evt, handler) { var thisArg = arguments[2] === undefined ? null : arguments[2]; var wrapper = undefined, self = this; // add a wrapper around the handler and listen to the requested event this.on(evt, wrapper = function () { for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } try { handler.apply.apply(handler, [thisArg].concat(args)); } catch (err) { console.error("ONCE handler received an error: " + err.message + ", " + JSON.stringify(err)); } finally { // remove the wrapper so that the event doesn't call us again self.off(evt, wrapper, thisArg); } }, thisArg); }
javascript
{ "resource": "" }
q38764
emitSyncFlag
train
function emitSyncFlag(evt, args) { var _this3 = this; var async = arguments[2] === undefined ? true : arguments[2]; var sender = this, eH = this[_eventHandlers]; // emit locally first to onEvent handlers try { (function () { var onEvent = "on:" + evt, sanitizedEvent = evt.replace(/\:/g, "_"), onSanitizedEvent = "on" + sanitizedEvent, ProperEventCase = sanitizedEvent[0].toUpperCase() + sanitizedEvent.substr(1), onProperEventCase = "on" + ProperEventCase, localHandler = undefined; if (_this3[onEvent]) { localHandler = _this3[onEvent]; } else if (_this3[onSanitizedEvent]) { localHandler = _this3[onSanitizedEvent]; } else if (_this3[onProperEventCase]) { localHandler = _this3[onProperEventCase]; } if (localHandler) { if (async) { setImmediate(function () { tryWrapper.apply(undefined, [localHandler.bind(sender), sender, evt].concat(_toConsumableArray(args))); }); } else { tryWrapper.apply(undefined, [localHandler.bind(sender), sender, evt].concat(_toConsumableArray(args))); } } })(); } catch (err) { console.log("EMITTER WARNING: Something broke while trying to call local methods.", err); } core.Array.from(eH) // for all the registered event categories, filter out the events that we really care about .filter(function (_ref3) { var _ref32 = _slicedToArray(_ref3, 1); var potentialEvent = _ref32[0]; if (potentialEvent[0] !== "/") { // the event isn't a regexp -- do a direct string compare return potentialEvent === evt; } else { // the event IS a regexp. Split on /, which returns an array of [ don't-care, expression, flags ] var _potentialEvent$split = potentialEvent.split("/"); var _potentialEvent$split2 = _slicedToArray(_potentialEvent$split, 3); var exp = _potentialEvent$split2[1]; var flags = _potentialEvent$split2[2]; // Return the result of the new regular expression. // TODO: I suppose we should think about caching the regular expression objects for performance. return new RegExp(exp, flags).test(evt); } }) // and now we want to call each handler .forEach(function (_ref4) { var _ref42 = _slicedToArray(_ref4, 2); var objMap = _ref42[1]; objMap.forEach(function (handlerSet, thisArg) { if (handlerSet !== undefined) { handlerSet.forEach(function (handler) { if (async) { setImmediate(function () { tryWrapper.apply(undefined, [handler.bind(thisArg), sender, evt].concat(_toConsumableArray(args))); }); } else { tryWrapper.apply(undefined, [handler.bind(thisArg), sender, evt].concat(_toConsumableArray(args))); } }); } }); }); }
javascript
{ "resource": "" }
q38765
allOffFor
train
function allOffFor(o) { var eH = this[_eventHandlers]; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = eH[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _step$value = _slicedToArray(_step.value, 2); var evt = _step$value[0]; var objMap = _step$value[1]; if (objMap !== undefined) { objMap["delete"](o); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator["return"]) { _iterator["return"](); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return this; }
javascript
{ "resource": "" }
q38766
builder
train
function builder(fromUID, node) { debug('builder fromUID:%s',fromUID); // Create a node (or use the provided one) var node = node || new DepNode((packageId++).toString(), options); // Get the entry point module object var fromModule = findModule(fromUID); // Add entry point to the module node.addModule(fromModule); debug(' fromModule.req.length:%s', fromModule.req.length); // For each module dependency, add module to // the node _.each(fromModule.req, function(link) { var module = findModule(link.uid); // Duplicate : pass if(node.hasModule(module.uid)) return; if(link.async) { debug(' Add async module (%s) to node %s', link.uid, node.id); // Async : Create a child node node.appendChild(builder(link.uid)); } else { debug(' Add sync module (%s) to node %s', link.uid, node.id); // Sync : add module node.addModule(module); builder(link.uid, node); } }); return node; }
javascript
{ "resource": "" }
q38767
extract
train
function extract(token) { var obj = {}; Object.keys(token).map(function(k) { if ( !ignore.has(k) ) { obj[k] = token[k]; } }); return obj; }
javascript
{ "resource": "" }
q38768
mergeListeners
train
function mergeListeners(emitter) { var events = emitter._events; _.each(events, function (fns, type) { if (Array.isArray(fns)) { _.each(fns, function (fn) { if (_.isFunction(fn)) { self.on(type, fn); } }); } else if (_.isFunction(fns)) { self.on(type, fns); } }); }
javascript
{ "resource": "" }
q38769
mergeMethods
train
function mergeMethods(builder) { var methods = builder.methods(); _.each(methods, function (fn, methodName) { // e.g.: users.getUserInfo self._methods[util.format('%s.%s', name, methodName)] = fn; }); }
javascript
{ "resource": "" }
q38770
Surround
train
function Surround(obj, pattern) { var self = this; var regEX = new RegExp(pattern); for(var fn in obj) { var orig = obj[fn]; if (typeof(orig) != "function" || !regEX.test(fn)) continue; // Already surrouneded. if (obj[fn].__stacks) { this.stacks = obj[fn].__stacks; return this; } this.stacks = this.defaults(); // The replace of the original function. obj[fn] = function() { self.stacks.before .concat([orig], self.stacks.after) .forEach(function(fn) { fn.apply(obj, arguments); }); }; // Resets the stack and returns the basic func back. obj[fn].reset = function() { obj[fn] = orig; self.stacks = self.defaults(); }; // The stacks are cached in the func itself. obj[fn].__stacks = this.stacks; } }
javascript
{ "resource": "" }
q38771
createTemporaryStorageFolder
train
function createTemporaryStorageFolder() { fs.mkdir(imageDir, '0775', function(err) { if (err && err.code !== 'EEXIST') { console.log(err); throw new Error(err); } }); }
javascript
{ "resource": "" }
q38772
writeStreamToFile
train
function writeStreamToFile(fileMeta, stream) { var deferred = q.defer(); stream.on('end', function() { deferred.resolve(fileMeta); }); stream.on('error', function(error) { deferred.reject(error); }); var filename = imageDir + '/' + fileMeta.uid; stream.pipe(fs.createWriteStream(filename)); return deferred.promise; }
javascript
{ "resource": "" }
q38773
parseBase64Stream
train
function parseBase64Stream(req) { var passthrough = false; var accumulation = ''; var stream = req.pipe(through(function(chunk, enc, callback) { if (!passthrough) { accumulation += chunk; var test = ';base64,'; var index = accumulation.indexOf(test); if (index > -1) { passthrough = true; chunk = accumulation.substr(index + test.length); } } if (passthrough) { this.push(chunk); } callback(); })) .pipe(base64.decode()); return stream; }
javascript
{ "resource": "" }
q38774
train
function (thisProperty, callbackArgs) { return function (callback) { function notifyListener() { if (Model.asyncEvents) { setTimeout(function () { callback.apply(thisProperty, callbackArgs); }, 0); } else { callback.apply(thisProperty, callbackArgs); } } if (Model.TRANSACTION_OPTIONS.flattenCallbacks || Model.TRANSACTION_OPTIONS.flattenCallbacksByHash) { var callbackExecuted = false; if (Model.TRANSACTION_OPTIONS.flattenCallbacks) { if (executedCallbacks.indexOf(callback) === -1) { // Only call callback once executedCallbacks.push(callback); notifyListener(); callbackExecuted = true; } } if (Model.TRANSACTION_OPTIONS.flattenCallbacksByHash) { if (!callback.hash || callbackHashs.indexOf(callback.hash) === -1) { // Only call hash identified callback once if (callback.hash) { callbackHashs.push(callback.hash); } if (!callbackExecuted) { notifyListener(); callbackExecuted = true; } } } } else { notifyListener(); } }; }
javascript
{ "resource": "" }
q38775
Property
train
function Property (name, value, parent, metadata) { var myName = "/" + name; if (parent) { myName = parent.getName() + myName; } Object.defineProperty(this, "_name", { value: myName, enumerable: false }); Object.defineProperty(this, "_parent", { value: parent, enumerable: false, writable: false, configurable: true //set to configurable so we can delete it in destroy }); Object.defineProperty(this, "_metadata", { value: metadata || {}, enumerable: false }); Object.defineProperty(this, "_eventListeners", { value: { //map of eventName to listener array. The following are modeljs Events propertyChange: [], modelChange: [], change: [], childCreated: [], childDestroyed: [], destroy: [], all: [] }, enumerable: false, writable: false, configurable: false }); var myValue = value; if (isFunction(myValue)) { myValue = myValue.bind(parent); } //make sure value is valid if (!this.validateValue(myValue)) { myValue = undefined; } Object.defineProperty(this, "_myValue", { value: myValue, enumerable: false, writable: true }); }
javascript
{ "resource": "" }
q38776
Model
train
function Model(json, metadata, parent) { var jsonModel = json || {}, modelMetadata = metadata || {}, modelName = modelMetadata.name !== undefined? modelMetadata.name : "root", modelParent = parent || null; if (modelMetadata.name) { // name is not part of the metadata. delete modelMetadata.name; } //A Model is in itself a Property so lets call our supers constructor Property.call(this, modelName, jsonModel, modelParent, modelMetadata); if (this.validateValue(jsonModel)) { for (var name in jsonModel) { if (name.match(Model.PROPERTY_METADATA_SERIALIZED_NAME_REGEX)) { // skip special meta data properties continue; } var value = jsonModel[name]; var propertyMetadata = jsonModel[name + Model.PROPERTY_METADATA_SERIALIZED_NAME_SUFFIX]; if (!modelMetadata.thin) { this.createProperty(name, value, propertyMetadata); } } } }
javascript
{ "resource": "" }
q38777
propergateEvent
train
function propergateEvent (isAtoB, property /*, ... other event callback arguments */) { var eventName = arguments[arguments.length-1]; //Since this is registered on the all event the last argument is the orginal Event name. if (eventName === Model.Event.CHILD_DESTROYED) { //we listen to he destroy action so no need to listen to CHILD_DESTROYED too return; } if(options && (options.eventBlackList || options.eventWhiteList)) { if (options.eventBlackList && options.eventBlackList.indexOf(eventName) !== -1) { return; } if (options.eventWhiteList && options.eventWhiteList.indexOf(eventName) === -1) { return; } } var linkedProperty = this; var newPropDisconnect; var reversePropergationFunction = isAtoB? propergateDestToSrc: propergateSrcToDest; // deregister our reverse propergation function and put it back later, so we don't have infinite loop. if (reversePropergationFunction) { // this will not exist if the connection direction was "one-way" linkedProperty.off(Model.Event.ALL, reversePropergationFunction); } if (eventName === Model.Event.PROPERTY_CHANGE) { linkedProperty.setValue(property.getValue()); } else if (eventName === Model.Event.CHILD_CREATED) { var newProperty = arguments[2]; if (Model.isArray(linkedProperty)) { // newProperty.getShortName() == linkedProperty.length; <- do push when this is true linkedProperty.push(newProperty.getValue()); newPropDisconnect = connect(newProperty, linkedProperty[newProperty.getShortName()]); } else { linkedProperty.createProperty(newProperty.getShortName(), newProperty.getValue(), newProperty.getMetadata()); newPropDisconnect = connect(newProperty, linkedProperty[newProperty.getShortName()]); } } else if (eventName === Model.Event.DESTROY) { if (Model.isArray(linkedProperty._parent) && parseInt(linkedProperty.getShortName(), 10) === linkedProperty._parent.length - 1) { linkedProperty._parent.pop(); } else { linkedProperty.destroy(); } } else { //custom event // remove the first argument, 'isAtoB' which is bound to this function via bind // also remove the second which is the property event triggered on // extract the middle // remove the last argument which is the event name since this method is registared to the Model.Event.ALL event. var args = [eventName].concat(Array.prototype.slice.call(arguments, 2, arguments.length-1)); Property.prototype.trigger.apply(linkedProperty, args ); } // only restore the connection if property is not destroyed if (eventName !== Model.Event.DESTROY && reversePropergationFunction) { linkedProperty.on(Model.Event.ALL, reversePropergationFunction); } return newPropDisconnect; // how do we disconnect this. }
javascript
{ "resource": "" }
q38778
writeNewAsync
train
function writeNewAsync(filepath, data){ return new Promise((resolve, reject)=>{ fs.writeFile(filepath, data ,{ flag: "wx" }, function(err){ if (!err) resolve(true) else reject(err) }) }) }
javascript
{ "resource": "" }
q38779
readdirAsync
train
function readdirAsync(filepath){ return new Promise((resolve, reject)=>{ fs.readdir(filepath, (err, items)=>{ if (err) reject(err) else resolve(items) }) }) }
javascript
{ "resource": "" }
q38780
raise
train
function raise(err, parameters, cause) { if(!(err instanceof Error)) { err = wrap(err, parameters, cause); } throw err; }
javascript
{ "resource": "" }
q38781
_runIfLocked
train
function _runIfLocked() { var self = this; self._clusterUtils._setLock(self.lockKey, function(err, lock) { if (err) { throw err; } else if (!lock) { return; } process.nextTick(self._func); }); }
javascript
{ "resource": "" }
q38782
registerCookieJar
train
function registerCookieJar(server) { var deferred = Q.defer(); server.register({ register: require('yar'), options: { cache: { expiresIn: cookieConfig.ttl }, cookieOptions: { clearInvalid: true, password: cookieConfig.password, domain: cookieConfig.domain, isSecure: cookieConfig.isSecure } } }, function (err) { err ? deferred.reject(err) : deferred.resolve(err); }); return deferred.promise; }
javascript
{ "resource": "" }
q38783
registerJwtCookie
train
function registerJwtCookie(server) { server.state('jwt', { ttl: cookieConfig.ttl, domain: cookieConfig.domain, isSecure: cookieConfig.isSecure, path: '/' }); }
javascript
{ "resource": "" }
q38784
getJwtFromCookie
train
function getJwtFromCookie(req, reply) { var jwt = req.state && req.state.jwt; if (jwt) { req.headers = req.headers || {}; req.headers.authorization = jwt; } reply.continue(); }
javascript
{ "resource": "" }
q38785
init
train
function init(ctx) { var server = ctx.server; return registerCookieJar(server) .then(function () { registerJwtCookie(server); server.ext('onPreAuth', getJwtFromCookie); return new Q(ctx); }); }
javascript
{ "resource": "" }
q38786
startsWithAny
train
function startsWithAny(string, vector) { return _.any(vector.map(function (e) { return _str.startsWith(string, e); })); }
javascript
{ "resource": "" }
q38787
endsWithAny
train
function endsWithAny(string, vector) { return _.any(vector.map(function (e) { return _str.endsWith(string, e); })); }
javascript
{ "resource": "" }
q38788
createReduce
train
function createReduce(dir) { // Optimized iterator function as using arguments.length // in the main function will deoptimize the, see #1991. function iterator(obj, iteratee, memo, keys, index, length) { for (; index >= 0 && index < length; index += dir) { var currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; } return function (obj, iteratee, memo, context) { iteratee = optimizeCb(iteratee, context, 4); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, index = dir > 0 ? 0 : length - 1; // Determine the initial value if none is provided. // Determine the initial value if none is provided. if (arguments.length < 3) { memo = obj[keys ? keys[index] : index]; index += dir; } return iterator(obj, iteratee, memo, keys, index, length); }; }
javascript
{ "resource": "" }
q38789
onResponse
train
function onResponse(packet) { if (typeof that.callbacks[packet.respond_to] === 'function') { try { if (packet.data) { packet.data = JSON.undry(packet.data); } } catch (err) { console.log('ERROR UNDRYING PACKET:', err); return; } if (packet.noData) { that.callbacks[packet.respond_to](packet.err, packet.stream); } else if (packet.stream) { that.callbacks[packet.respond_to](packet.err, packet.data, packet.stream); } else { that.callbacks[packet.respond_to](packet.err, packet.data); } } delete that.callbacks[packet.respond_to]; }
javascript
{ "resource": "" }
q38790
onPacket
train
function onPacket(packet) { var respond; try { if (packet.data && typeof packet.data == 'object') { packet.data = JSON.undry(packet.data); } } catch (err) { console.log('ERROR UNDRYING PACKET:', err, packet); return; } if (packet.respond) { respond = function respond(err, data) { var responsePacket = {}; responsePacket.err = err; responsePacket.respond_to = packet.id; responsePacket.data = data; server.emit('response', responsePacket); }; } // See if this is for a specific linkup if (packet.link) { if (that.linkups[packet.link]) { if (packet.stream) { that.linkups[packet.link].emit(packet.type, packet.data, packet.stream, respond, null); } else { that.linkups[packet.link].emit(packet.type, packet.data, respond, null); } } return; } if (packet.stream) { that.emit(packet.type, packet.data, packet.stream, respond, null); } else { that.emit(packet.type, packet.data, respond, null); } }
javascript
{ "resource": "" }
q38791
train
function(inheritedTime) { this._inheritedTime = inheritedTime; this._updateTimeMarkers(); // The polyfill uses a sampling model whereby time values are propagated // down the tree at each sample. However, for the media item, we need to use // play() and pause(). // Handle the case of being outside our effect interval. if (this._iterationTime === null) { this._ensureIsAtUnscaledTime(0); this._ensurePaused(); return; } if (this._iterationTime >= this._intrinsicDuration()) { // Our iteration time exceeds the media element's duration, so just make // sure the media element is at the end. It will stop automatically, but // that could take some time if the seek below is significant, so force // it. this._ensureIsAtUnscaledTime(this._intrinsicDuration()); this._ensurePaused(); return; } var finalIteration = this._floorWithOpenClosedRange( this.timing.iterationStart + this.timing._iterations(), 1.0); var endTimeFraction = this._modulusWithOpenClosedRange( this.timing.iterationStart + this.timing._iterations(), 1.0); if (this.currentIteration === finalIteration && this._timeFraction === endTimeFraction && this._intrinsicDuration() >= this.duration) { // We have reached the end of our final iteration, but the media element // is not done. this._ensureIsAtUnscaledTime(this.duration * endTimeFraction); this._ensurePaused(); return; } // Set the appropriate playback rate. var playbackRate = this._media.defaultPlaybackRate * this._netEffectivePlaybackRate(); if (this._media.playbackRate !== playbackRate) { this._media.playbackRate = playbackRate; } // Set the appropriate play/pause state. Note that we may not be able to // seek to the desired time. In this case, the media element's seek // algorithm repositions the seek to the nearest seekable time. This is OK, // but in this case, we don't want to play the media element, as it prevents // us from synchronising properly. if (this.player.paused || !this._isSeekableUnscaledTime(this._iterationTime)) { this._ensurePaused(); } else { this._ensurePlaying(); } // Seek if required. This could be due to our AnimationPlayer being seeked, // or video slippage. We need to handle the fact that the video may not play // at exactly the right speed. There's also a variable delay when the video // is first played. // TODO: What's the right value for this delta? var delta = isDefinedAndNotNull(this._delta) ? this._delta : 0.2 * Math.abs(this._media.playbackRate); if (Math.abs(this._iterationTime - this._unscaledMediaCurrentTime()) > delta) { this._ensureIsAtUnscaledTime(this._iterationTime); } }
javascript
{ "resource": "" }
q38792
train
function(offset, composite, easing) { ASSERT_ENABLED && assert( typeof offset === 'number' || offset === null, 'Invalid offset value'); ASSERT_ENABLED && assert( composite === 'add' || composite === 'replace' || composite === null, 'Invalid composite value'); this.offset = offset; this.composite = composite; this.easing = easing; this.cssValues = {}; }
javascript
{ "resource": "" }
q38793
train
function(property, value, svgMode) { if (value === 'inherit') { return value; } return getType(property).toCssValue(value, svgMode); }
javascript
{ "resource": "" }
q38794
PixelateFilter
train
function PixelateFilter() { core.AbstractFilter.call(this, // vertex shader null, // fragment shader fs.readFileSync(__dirname + '/pixelate.frag', 'utf8'), // custom uniforms { dimensions: { type: '4fv', value: new Float32Array([0, 0, 0, 0]) }, pixelSize: { type: 'v2', value: { x: 10, y: 10 } } } ); }
javascript
{ "resource": "" }
q38795
getUrl
train
function getUrl (url) { var opt = { url: url , timeout: 10000 // 10 seconds } ; return new Promise(function(resolve, reject){ request(opt, function(err, res, body){ if (err) { return reject(err); } resolve(body) }); }); }
javascript
{ "resource": "" }
q38796
readCss
train
function readCss () { return new Promise(function(resolve, reject){ readFile(SRC, {encoding: 'utf8'}, function(err, str){ if (err) { return reject(err); } resolve(str) }); }); }
javascript
{ "resource": "" }
q38797
getCss
train
function getCss () { return checkTime().then(function(isOld){ if (isOld){ return writeCss().then(function(str){ if (!str) return readCss() return str }) } return readCss() }) }
javascript
{ "resource": "" }
q38798
archiveResource
train
function archiveResource(resource, primary, archive) { if (!resource.archive) { return true; } var name = resource.name; primary.bind(name); archive.bind(name); // get the archive criteria var criteria = resource.archive(); log.info('Getting archive docs for ' + name); // find all the documents that match the archive criteria return getDocsToArchive(criteria, primary[name]) .then(function (docs) { log.info('Found ' + docs.length + ' ' + name + ' docs to archive'); // insert all of the documents into the archive database var deferred = Q.defer(); archive[name].insert(docs, function (err, results) { err ? deferred.reject(err) : deferred.resolve(results); }); return deferred.promise; }) .then(function () { log.info('Docs inserted into archive DB for ' + name + '. Now deleting docs in main db'); // delete the data from the primary database var deferred = Q.defer(); primary[name].remove(criteria, function (err, results) { log.info('Deleting docs complete for ' + name); err ? deferred.reject(err) : deferred.resolve(results); }); return deferred.promise; }); }
javascript
{ "resource": "" }
q38799
getDocsToArchive
train
function getDocsToArchive(criteria, primaryCollection) { var deferred = Q.defer(); primaryCollection.find(criteria).toArray(function (err, items) { err ? deferred.reject(err) : deferred.resolve(items); }); return deferred.promise; }
javascript
{ "resource": "" }