_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q43800
requestHypemKey
train
function requestHypemKey(hypemId, callback) { var options = { method: "GET", url: HYPEM_TRACK_URL + hypemId, headers: {"Cookie": COOKIE}, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (!error && response.statusCode === 200) { var bodyLines = response.body.split('\n'); _.forIn(bodyLines, function (bodyLine) { if (bodyLine.indexOf('key') !== -1) { // first hit should be the correct one // fix if hypem changes that try { var key = JSON.parse(bodyLine.replace('</script>', '')).tracks[0].key; callback(null, key); } catch (error) { // if an error happen here do nothing and parse // the rest of the document } } }); } else { callback(new Error("Nothing found: " + options.url), null); } }); }
javascript
{ "resource": "" }
q43801
requestMp3Url
train
function requestMp3Url(hypemId, hypemKey, callback) { var options = { method: "GET", url: HYPEM_SERVE_URL + hypemId + "/" + hypemKey, headers: {"Cookie": COOKIE}, timeout: FIVE_SECONDS_IN_MILLIS }; request(options, function (error, response) { if (!error && response.statusCode === 200) { try { // the request got a json from hypem // where the link to the mp3 file is saved var jsonBody = JSON.parse(response.body); var mp3Url = jsonBody.url; callback(null, mp3Url); } catch (error) { callback(error, null); } } else { callback(new Error("Nothing found: " + options.url), null); } }); }
javascript
{ "resource": "" }
q43802
getNormalizedSoundcloudUrl
train
function getNormalizedSoundcloudUrl(soundcloudUrl) { var parsedUrl = url.parse(soundcloudUrl); var protocol = parsedUrl.protocol; var host = parsedUrl.host; var pathname = parsedUrl.pathname; var splitHostname = pathname.split('/'); var normalizedUrl = protocol + "//" + host + "/" + splitHostname[1] + "/" + splitHostname[2]; return normalizedUrl; }
javascript
{ "resource": "" }
q43803
train
function(options) { this.DelOptions = $.extend({}, defaults, this.DelOptions, options); this.dName = this.DelOptions.dName || this._name; this.selector = this.selector || '.' + this.dName; this.namespace = this.DelOptions.namespace || this.dName; this.initEl(); }
javascript
{ "resource": "" }
q43804
train
function(el) { return (el instanceof $ ? el : $(el)).find(this.makeSelector.apply(this, [].slice.call(arguments, 1))); }
javascript
{ "resource": "" }
q43805
parse
train
function parse (code) { Object.keys(syntax).forEach((s) => { code = code.replace(syntax[s], (_, m) => { // ensure if the regex only matches part of the string that we keep the leftover let leftOver = _.replace(m, '') // encode the string and class let parsed = `{#${s}#${encode(m)}#}` if (s === 'function' && leftOver) { // we want to parse sub commands and the easiest way to do that is to // run over the leftOver portion of the function call with the same regex let startingParenthesis = leftOver.indexOf('(') let endingParenthesis = leftOver.lastIndexOf(')') let endingComma = leftOver.lastIndexOf(';') // since we don't want to create a new string for every operation // we can simply walk the string and replace the character that needs it let subFunction = leftOver.replace(/./g, (c, i) => { // we can define a waterfall case that only replaces the three positions with nothing // leaving the other characters in their place switch (i) { case startingParenthesis: case endingParenthesis: case endingComma: return '' default: return c } }) leftOver = `(${parse(subFunction)})${endingComma > -1 ? ';' : ''}` } return parsed + leftOver }) }) return code }
javascript
{ "resource": "" }
q43806
encode
train
function encode (str) { return str.split('').map((s) => { if (s.charCodeAt(0) > 127) return s return String.fromCharCode(s.charCodeAt(0) + 0x2800) }).join(' ') }
javascript
{ "resource": "" }
q43807
decode
train
function decode (str) { return str.trim().split(' ').map((s) => { if (s.charCodeAt(0) - 0x2800 > 127) return s return String.fromCharCode(s.charCodeAt(0) - 0x2800) }).join('') }
javascript
{ "resource": "" }
q43808
runBrowsersBail
train
function runBrowsersBail(location, remote, platforms, options) { var throttle = options.throttle || function (fn) { return fn(); }; var results = []; results.passedBrowsers = []; results.failedBrowsers = []; return new Promise(function (resolve) { function next(i) { if (i >= platforms.length) { return resolve(results); } var platform = platforms[i]; if (options.onQueue) options.onQueue(platform); throttle(function () { if (options.onStart) options.onStart(platform); return runSingleBrowser(location, remote, platform, { name: options.name, capabilities: options.capabilities, debug: options.debug, httpDebug: options.httpDebug, jobInfo: options.jobInfo, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, timeout: options.timeout }); }).done(function (result) { Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); results.push(result); if (options.onResult) options.onResult(result); if (result.passed) { results.passedBrowsers.push(result); next(i + 1); } else { results.failedBrowsers = [result]; resolve(results); } }, function (err) { var result = {passed: false, duration: err.duration, err: err}; Object.keys(platform).forEach(function (key) { result[key] = platform[key]; }); results.push(result); if (options.onResult) options.onResult(result); results.failedBrowsers = [result]; resolve(results); }); } next(0); }); }
javascript
{ "resource": "" }
q43809
train
function() { var bear = this; // don't bind until we're ready var srv = bear.ready.then( function() { var dfd = _.Deferred(); // only make once if ( !bear.githInstance ) { bear.githInstance = bear.gith({ repo: bear.settings.repo, }).on( 'all', bear._processPayload.bind( bear ) ); } dfd.resolve( bear.githInstance ); return dfd.promise(); }); return srv; }
javascript
{ "resource": "" }
q43810
train
function( payload ) { var bear = this; var dfd = _.Deferred(); var action = dfd.promise(); // ok to launch live? if ( payload.branch === bear.settings.liveBranch ) { // can we just upload master without worrying about tags? if ( !bear.settings.deployOnTag ) { action = action.then( function() { return bear.live( bear.settings.liveBranch); }); } else if ( payload.tag ) { // since we tagged and that's required, only launch at that sha action = action.then( function() { return bear.live( bear.settings.liveBranch, payload.sha ); }); } } // either way, setup the staging version action = action.then( function() { return bear.stage( payload.branch ); }); // if we assigned a callback, fire it when these are done if ( bear.settings.githCallback ) { action.done( function() { bear.settings.githCallback.call( bear, payload ); }); } // start us off dfd.resolve(); }
javascript
{ "resource": "" }
q43811
train
function() { return dexec( 'cd ' + this.settings.git + '; npm install' ).done(function( stdout, stderr ) { log( 'npm install successful' ); log.extra( stdout, stderr ); }); }
javascript
{ "resource": "" }
q43812
textStream
train
function textStream() { var start = randomInt(0, config.size - bufferSize) return fs.createReadStream(dictPath, { encoding: config.encoding, start: start, end: start + bufferSize }) }
javascript
{ "resource": "" }
q43813
SocketioHandler
train
function SocketioHandler(io, options) { /** * Emit 'data' to all sockets for the provided User or array of Users. * * @param {*} channelName * @param {*} users * @param {*} data */ function emitToUsers(users, channelName, data) { const usersArray = Array.isArray(users) ? users : [users]; usersArray.map(function (user) { Object.keys(io.sockets.sockets).filter(function (key) { return io.sockets.sockets[key].transomUser._id.toString() === user._id.toString(); }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }); } /** * Emit 'data' to all sockets for the authenticated Users. * * @param {*} channelName * @param {*} data */ function emitToEveryone(channelName, data) { Object.keys(io.sockets.sockets).filter(function (key) { return !!io.sockets.sockets[key].transomUser; }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); } return { emitToUsers, emitToEveryone, // simple getter that allows access to io, while dis-allowing updates. get io() { return io; } }; }
javascript
{ "resource": "" }
q43814
emitToUsers
train
function emitToUsers(users, channelName, data) { const usersArray = Array.isArray(users) ? users : [users]; usersArray.map(function (user) { Object.keys(io.sockets.sockets).filter(function (key) { return io.sockets.sockets[key].transomUser._id.toString() === user._id.toString(); }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }); }
javascript
{ "resource": "" }
q43815
emitToEveryone
train
function emitToEveryone(channelName, data) { Object.keys(io.sockets.sockets).filter(function (key) { return !!io.sockets.sockets[key].transomUser; }).map(function (socketKey) { io.sockets.sockets[socketKey].emit(channelName, data); }); }
javascript
{ "resource": "" }
q43816
updatePos
train
function updatePos( pos, prop, val ) { floatSpace.setStyle( prop, pixelate( val ) ); floatSpace.setStyle( 'position', pos ); }
javascript
{ "resource": "" }
q43817
changeMode
train
function changeMode( newMode ) { var editorPos = editable.getDocumentPosition(); switch ( newMode ) { case 'top': updatePos( 'absolute', 'top', editorPos.y - spaceHeight - dockedOffsetY ); break; case 'pin': updatePos( 'fixed', 'top', pinnedOffsetY ); break; case 'bottom': updatePos( 'absolute', 'top', editorPos.y + ( editorRect.height || editorRect.bottom - editorRect.top ) + dockedOffsetY ); break; } mode = newMode; }
javascript
{ "resource": "" }
q43818
train
function(e) { e = e || window.event; e.preventDefault ? e.preventDefault() : (e.returnValue = false); var eTarget = e.target || e.srcElement; // find root element of slide var clickedListItem = closest(eTarget, function(el) { //console.log(el.getAttribute('ui-gallery-item')); return el.getAttribute('ui-gallery-item') != null; }); if (!clickedListItem) { return; } var parentNode = closest(eTarget, function(el) { return el.getAttribute('ui-gallery') != null; }); if (!parentNode) { return; } var childNodes = parentNode.querySelectorAll('[ui-gallery-item]'); // find index of clicked item by looping through all child nodes // alternatively, you may define index via data- attribute var clickedGallery = parentNode, numChildNodes = childNodes.length, nodeIndex = 0, index; for (var i = 0; i < numChildNodes; i++) { if (childNodes[i].nodeType !== 1) { continue; } if (childNodes[i] === clickedListItem) { index = nodeIndex; break; } nodeIndex++; } if (index >= 0) { // open PhotoSwipe if valid index found openPhotoSwipe(index, clickedGallery); } return false; }
javascript
{ "resource": "" }
q43819
handleUncaughtExceptions
train
function handleUncaughtExceptions(error) { if (!error || !error.stack) { console.log('Uncaught exception:', error); process.exit(); } var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); if (match) { var cache = {}; var position = mapSourcePosition(cache, { source: match[1], line: match[2], column: match[3] }); if (fs.existsSync(position.source)) { var contents = fs.readFileSync(position.source, 'utf8'); var line = contents.split(/(?:\r\n|\r|\n)/)[position.line - 1]; if (line) { console.log('\n' + position.source + ':' + position.line); console.log(line); console.log(new Array(+position.column).join(' ') + '^'); } } } console.log(error.stack); process.exit(); }
javascript
{ "resource": "" }
q43820
broadcastMonitors
train
function broadcastMonitors(records, moduleId, msg) { msg = protocol.composeRequest(null, moduleId, msg); if (records instanceof Array) { for (let i = 0, l = records.length; i < l; i++) { const socket = records[i].socket; doSend(socket, 'monitor', msg); } } else { for (const id in records) { if (records.hasOwnProperty(id)) { const socket = records[id].socket; doSend(socket, 'monitor', msg); } } } }
javascript
{ "resource": "" }
q43821
getChar
train
function getChar (bits) { var index = parseInt(bits,2); if (isNaN(index) || index < 0 || index > 63) throw new Error('baseURL#getChar: Need valid bitString'); return ALPHABET[index]; }
javascript
{ "resource": "" }
q43822
indexOfBits
train
function indexOfBits (char) { var index = ALPHABET.indexOf(char); if (index < 0) throw new Error('baseURL#indexOfBits: Need valid baseURL char'); return bitString.pad(index.toString(2), 6) ; }
javascript
{ "resource": "" }
q43823
encode
train
function encode (bits) { if (!bitString.isValid(bits)) throw new Error('baseURL#encode: bits not valid bitstring'); if (bits.length % 6 !== 0) throw new Error('baseURL#encode: bits must be a multiple of 6'); var result = ''; for (var i = 0; i < bits.length; i = i + 6) { result += getChar(bits.slice(i, i + 6 )); } return result; }
javascript
{ "resource": "" }
q43824
decode
train
function decode (str) { if (!isValid(str)) throw new Error('baseURL#decode: str not valid baseURL string'); var bits = ''; // Decode for (var i = 0; i < str.length; i++) { bits += indexOfBits(str[i]); } return bits; }
javascript
{ "resource": "" }
q43825
simpleComponent
train
function simpleComponent(elementName, elementClass, elementClassToExtend) { elementClass = elementClass || {} elementClassToExtend = elementClassToExtend || HTMLElement elementClass.prototype = Object.create(elementClassToExtend.prototype) assign(elementClass.prototype, elementClass) elementClass.__template = template(elementName) if (elementClass.prototype.createdCallback) { elementClass.prototype.__originalCreatedCallback = elementClass.prototype.createdCallback } elementClass.prototype.createdCallback = function() { fill(this, elementClass.__template) if (elementClass.prototype.__originalCreatedCallback) { elementClass.prototype.__originalCreatedCallback.call(this) } } document.registerElement(elementName, elementClass) }
javascript
{ "resource": "" }
q43826
fill
train
function fill(toElement, templateElement) { var templateContentClone = templateElement.content.cloneNode(true) var slot var i if (toElement.childNodes.length) { slot = templateContentClone.querySelector('slot') if (slot) { while (toElement.childNodes.length) { slot.appendChild(toElement.firstChild) } } } toElement.appendChild(templateContentClone) }
javascript
{ "resource": "" }
q43827
makeRequire
train
function makeRequire(m, self) { function _require(_path) { return m.require(_path); } _require.resolve = function(request) { return _module._resolveFilename(request, self); }; _require.cache = _module._cache; _require.extensions = _module._extensions; return _require; }
javascript
{ "resource": "" }
q43828
_connectionFailureHandler
train
function _connectionFailureHandler(self) { return function() { if (this._connectionFailHandled) return; this._connectionFailHandled = true; // Destroy the connection this.destroy(); // Count down the number of reconnects self.retriesLeft = self.retriesLeft - 1; // How many retries are left if (self.retriesLeft <= 0) { // Destroy the instance self.destroy(); // Emit close event self.emit( 'reconnectFailed', new MongoNetworkError( f( 'failed to reconnect after %s attempts with interval %s ms', self.options.reconnectTries, self.options.reconnectInterval ) ) ); } else { self.reconnectId = setTimeout(attemptReconnect(self), self.options.reconnectInterval); } }; }
javascript
{ "resource": "" }
q43829
_connectHandler
train
function _connectHandler(self) { return function() { // Assign var connection = this; // Pool destroyed stop the connection if (self.state === DESTROYED || self.state === DESTROYING) { return connection.destroy(); } // Clear out all handlers handlers.forEach(function(event) { connection.removeAllListeners(event); }); // Reset reconnect id self.reconnectId = null; // Apply pool connection handlers connection.on('error', connectionFailureHandler(self, 'error')); connection.on('close', connectionFailureHandler(self, 'close')); connection.on('timeout', connectionFailureHandler(self, 'timeout')); connection.on('parseError', connectionFailureHandler(self, 'parseError')); // Apply any auth to the connection reauthenticate(self, this, function() { // Reset retries self.retriesLeft = self.options.reconnectTries; // Push to available connections self.availableConnections.push(connection); // Set the reconnectConnection to null self.reconnectConnection = null; // Emit reconnect event self.emit('reconnect', self); // Trigger execute to start everything up again _execute(self)(); }); }; }
javascript
{ "resource": "" }
q43830
authenticateStragglers
train
function authenticateStragglers(self, connection, callback) { // Get any non authenticated connections var connections = self.nonAuthenticatedConnections.slice(0); var nonAuthenticatedConnections = self.nonAuthenticatedConnections; self.nonAuthenticatedConnections = []; // Establish if the connection need to be authenticated // Add to authentication list if // 1. we were in an authentication process when the operation was executed // 2. our current authentication timestamp is from the workItem one, meaning an auth has happened if ( connection.workItems.length === 1 && (connection.workItems[0].authenticating === true || (typeof connection.workItems[0].authenticatingTimestamp === 'number' && connection.workItems[0].authenticatingTimestamp !== self.authenticatingTimestamp)) ) { // Add connection to the list connections.push(connection); } // No connections need to be re-authenticated if (connections.length === 0) { // Release the connection back to the pool moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); // Finish return callback(); } // Apply re-authentication to all connections before releasing back to pool var connectionCount = connections.length; // Authenticate all connections for (var i = 0; i < connectionCount; i++) { reauthenticate(self, connections[i], function() { connectionCount = connectionCount - 1; if (connectionCount === 0) { // Put non authenticated connections in available connections self.availableConnections = self.availableConnections.concat( nonAuthenticatedConnections ); // Release the connection back to the pool moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); // Return callback(); } }); } }
javascript
{ "resource": "" }
q43831
authenticateLiveConnections
train
function authenticateLiveConnections(self, args, cb) { // Get the current viable connections var connections = self.allConnections(); // Allow nothing else to use the connections while we authenticate them self.availableConnections = []; self.inUseConnections = []; self.connectingConnections = []; var connectionsCount = connections.length; var error = null; // No connections available, return if (connectionsCount === 0) { self.authenticating = false; return callback(null); } // Authenticate the connections for (var i = 0; i < connections.length; i++) { authenticate(self, args, connections[i], function(err, result) { connectionsCount = connectionsCount - 1; // Store the error if (err) error = err; // Processed all connections if (connectionsCount === 0) { // Auth finished self.authenticating = false; // Add the connections back to available connections self.availableConnections = self.availableConnections.concat(connections); // We had an error, return it if (error) { // Log the error if (self.logger.isError()) { self.logger.error( f( '[%s] failed to authenticate against server %s:%s', self.id, self.options.host, self.options.port ) ); } return cb(error, result); } cb(null, result); } }); } }
javascript
{ "resource": "" }
q43832
waitForLogout
train
function waitForLogout(self, cb) { if (!self.loggingout) return cb(); setTimeout(function() { waitForLogout(self, cb); }, 1); }
javascript
{ "resource": "" }
q43833
train
function(_connection) { return function() { // Destroyed state return if (self.state === DESTROYED || self.state === DESTROYING) { // Remove the connection from the list removeConnection(self, _connection); return _connection.destroy(); } // Destroy all event emitters handlers.forEach(function(e) { _connection.removeAllListeners(e); }); // Add the final handlers _connection.once('close', connectionFailureHandler(self, 'close')); _connection.once('error', connectionFailureHandler(self, 'error')); _connection.once('timeout', connectionFailureHandler(self, 'timeout')); _connection.once('parseError', connectionFailureHandler(self, 'parseError')); // Signal reauthenticate(self, _connection, function(err) { if (self.state === DESTROYED || self.state === DESTROYING) { return _connection.destroy(); } // Remove the connection from the connectingConnections list removeConnection(self, _connection); // Handle error if (err) { return _connection.destroy(); } // If we are c at the moment // Do not automatially put in available connections // As we need to apply the credentials first if (self.authenticating) { self.nonAuthenticatedConnections.push(_connection); } else { // Push to available self.availableConnections.push(_connection); // Execute any work waiting _execute(self)(); } }); }; }
javascript
{ "resource": "" }
q43834
Miscue
train
function Miscue(code, data) { if (!(this instanceof Miscue)) return new Miscue(code, data); return this.initialize(code, data); }
javascript
{ "resource": "" }
q43835
createLint
train
function createLint(inPath, opts = {}) { if (!inPath) { throw new Error('Input path argument is required'); } return function lint() { return gulp.src(inPath) .pipe(eslint(opts)) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }; }
javascript
{ "resource": "" }
q43836
getStartEndRowsFromBoardSize
train
function getStartEndRowsFromBoardSize(boardSize) { const endRow = boardSize.y - 1; return { white: getStartEndRow(endRow, false), black: getStartEndRow(endRow, true) }; }
javascript
{ "resource": "" }
q43837
getJumpPosition
train
function getJumpPosition(from, toJump, board) { const jumpXY = getJumpXY(from, toJump); if (!hasPosition(board, jumpXY)) return; const jumpPosition = getPositionFromBoard(board, jumpXY); if (Position.hasPiece(jumpPosition)) return; return jumpPosition; }
javascript
{ "resource": "" }
q43838
isValid
train
function isValid (path, entry) { var isValid = valid(path) if (isValid) { log.verbose('extracted file from tarball', path) extractCount++ } else { // invalid log.silly('ignoring from tarball', path) } return isValid }
javascript
{ "resource": "" }
q43839
get
train
function get(path) { var conf = this; if (typeof path !== 'string') { throw new Error('path should be a string!'); } else if (path.length === 0) { throw new Error('path cannot be empty!'); } var result = baseGet(conf, getPathArray(path)); if (result === undefined) { throw new Error('the value is undefined!'); } else { bindGetMethod(result); // eslint-disable-line } return result; }
javascript
{ "resource": "" }
q43840
addProperty
train
function addProperty(sourceData, propertiesGroups, filePath) { var group = propertiesUtils.getGroup(sourceData[2], propertiesGroups), propertyName, data, propertyDefinitionWithoutObjectName; if (!group) { grunt.log.error('Object ' + sourceData[2] + ' without init file'); return; } grunt.verbose.ok(sourceData[2]); // generate property data propertyDefinitionWithoutObjectName = sourceData[2].replace(group.pattern, '').replace(/^\./, ''); propertyName = propertyDefinitionWithoutObjectName.replace(/^prototype\./i, ''); data = { name: propertyName, source: sourceData[3].replace(/(^[\r\n\s]+|[\r\n\s;]+$)/g, ''), comment: sourceData[1] || '', type: propertiesUtils.isFunction(sourceData[3]) ? 'function' : 'object', isPublic: propertiesUtils.isPublic(propertyName), isFromPrototype: propertiesUtils.isFromPrototype(propertyDefinitionWithoutObjectName), filePath: filePath }; // add property data to prototype or inline array group[(data.isFromPrototype ? 'prototypeProperties' : 'inlineProperties')].push(data); }
javascript
{ "resource": "" }
q43841
addJSONProperties
train
function addJSONProperties(jsonData, propertiesGroups, filePath, currentNamesPath) { var i, group, propertyDefinition, propertyDefinitionWithoutObjectName, propertyName, data; if (currentNamesPath === undefined) { currentNamesPath = ''; } // get all values for (i in jsonData) { // add to group if is a simply object if (jsonData[i] instanceof Array || jsonData[i] == null || typeof jsonData[i] !== 'object' || grunt.util._.isEmpty(jsonData[i])) { // find group propertyDefinition = (currentNamesPath ? currentNamesPath + '.' + i : i) .replace(/^[^.]+\./, ''); group = propertiesUtils.getGroup(propertyDefinition, propertiesGroups); if (!group) { grunt.log.error('Object ' + propertyDefinition + ' without init file'); return; } grunt.verbose.ok(propertyDefinition); // generate property data propertyDefinitionWithoutObjectName = propertyDefinition .replace(group.pattern, '') .replace(/^\./, ''); propertyName = propertyDefinitionWithoutObjectName .replace(/^prototype\./i, ''); data = { name: propertyName, comment: '', type: 'object', isPublic: propertiesUtils.isPublic(propertyName), isFromPrototype: propertiesUtils.isFromPrototype(propertyDefinitionWithoutObjectName), filePath: filePath }; // string -> "string" // true -> true switch (typeof jsonData[i]) { case 'object': if (jsonData[i] != null) { data.source = JSON.stringify(jsonData[i]); } break; case 'string': data.source = '"' + jsonData[i].split('"').join('\\"') + '"'; break; } if (data.source === undefined) { data.source = '' + jsonData[i]; } // add property data to prototype or inline array group[(data.isFromPrototype ? 'prototypeProperties' : 'inlineProperties')].push(data); } else { // is object // add attributeName to path and try to add addJSONProperties(jsonData[i], propertiesGroups, filePath, currentNamesPath ? currentNamesPath + '.' + i : i); } } }
javascript
{ "resource": "" }
q43842
onChunk
train
function onChunk(count) { // If chunk read has no bytes than there is nothing left, so end a // collection. if (count === 0) return next(end) // Move a offset `position` with `count` towards the end unless // position was a `null` in which case we just keep it (`null` means // from a current position). position = position === null ? position : position + count // Read chunk is forwarded to a consumer that will return // a promise which is delivered once write is complete. // In a future we may switch to an approach similar to new // streams in node, where buffering watermarks are specified // via options and reads can buffer up up to that point in // parallel to write. when(next(buffer.slice(0, count), state), onDrain, onError) }
javascript
{ "resource": "" }
q43843
onDrain
train
function onDrain(value) { state = value // If value is marked as `reduced` no further reads should take place, // as consumer has finished consumption. if (isReduced(value)) return next(end) // If current `position` has reached or passed `finish` mark end a // collection. else if (position >= finish) return next(end, state) // Otherwise read another chunk from the current position & execute // `onChunk` handler or `onError` if fails. Note that `readChunk` // reads chunk and returns either number of bytes read or a promise // for that or an error if failed. Errors will invoke onError handler // causing collection error and end. `onChunk` will propagate data // further likely to the writer on the other end. when(readChunk(fd, buffer, position, size), onChunk, onError) }
javascript
{ "resource": "" }
q43844
train
function(objects) { if (!_.isArray(objects)) { objects = [objects]; } var change = new Parse.Op.Relation(objects, []); this.parent.set(this.key, change); this.targetClassName = change._targetClassName; }
javascript
{ "resource": "" }
q43845
train
function() { var targetClass; var query; if (!this.targetClassName) { targetClass = Parse.Object._getSubclass(this.parent.className); query = new Parse.Query(targetClass); query._extraOptions.redirectClassNameForKey = this.key; } else { targetClass = Parse.Object._getSubclass(this.targetClassName); query = new Parse.Query(targetClass); } query._addCondition("$relatedTo", "object", this.parent._toPointer()); query._addCondition("$relatedTo", "key", this.key); return query; }
javascript
{ "resource": "" }
q43846
train
function(s_line, s_close_delim, z_merge_delim) { // open block add( s_line || '', z_merge_delim, true ); // set close delim s_close = ('string' === typeof s_close_delim)? s_close_delim: a_closers.slice(-1)[0]; a_closers.push(s_close); // increase indentation add.tabs += 1; }
javascript
{ "resource": "" }
q43847
trimHtml
train
function trimHtml(html) { function trimSpaces(all, s1, s2) { // WebKit &nbsp; meant to preserve multiple spaces but instead inserted around all inline tags, // including the spans with inline styles created on paste if (!s1 && !s2) { return ' '; } return '\u00a0'; } html = filter(html, [ /^[\s\S]*<body[^>]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig, // Remove anything but the contents within the BODY element /<!--StartFragment-->|<!--EndFragment-->/g, // Inner fragments (tables from excel on mac) [/( ?)<span class="Apple-converted-space">\u00a0<\/span>( ?)/g, trimSpaces], /<br class="Apple-interchange-newline">/g, /<br>$/i // Trailing BR elements ]); return html; }
javascript
{ "resource": "" }
q43848
getDataTransferItems
train
function getDataTransferItems(dataTransfer) { var items = {}; if (dataTransfer) { // Use old WebKit/IE API if (dataTransfer.getData) { var legacyText = dataTransfer.getData('Text'); if (legacyText && legacyText.length > 0) { if (legacyText.indexOf(mceInternalUrlPrefix) == -1) { items['text/plain'] = legacyText; } } } if (dataTransfer.types) { for (var i = 0; i < dataTransfer.types.length; i++) { var contentType = dataTransfer.types[i]; try { // IE11 throws exception when contentType is Files (type is present but data cannot be retrieved via getData()) items[contentType] = dataTransfer.getData(contentType); } catch (ex) { items[contentType] = ""; // useless in general, but for consistency across browsers } } } } return items; }
javascript
{ "resource": "" }
q43849
train
function (originalIt) { return function it(desc, cb) { if (cb.length === 0) { originalIt(desc, cb); } else { originalIt(desc, wrapInTryCatch(cb)); } }; }
javascript
{ "resource": "" }
q43850
mount
train
function mount(mountLocation, tagname, props) { // return riot.mount(mountLocation, tagname, props)[0]; const id = makeUID(`riotjs_mount_${tagname}`); const fauxTag = `<${tagname} data-elmoed-editor="${tagname}" id="${id}"> </${tagname}>`; // Loop through all sub-mounted editors that might already exist in the // mount location and properly unmount them for clean up const selector = '[data-elmoed-editor]'; const subEditors = mountLocation.querySelectorAll(selector); for (const submountedEditor of subEditors) { // _tag learned from: https://github.com/riot/riot/issues/934 // Might not be maintained, hence the check for its existence if (!submountedEditor._tag) { console.error('Unsuccessful unmount tag: Bad Riot.js version?'); continue; } submountedEditor._tag.unmount(); } /* eslint-disable no-param-reassign */ // Clear any initial HTML mountLocation.innerHTML = ''; // Add in the HTML in the right location for riot to find mountLocation.innerHTML = fauxTag; // Finally, mount the element where it belongs const tagInstance = riot.mount(`#${id}`, props)[0]; tagInstance.on('before-unmount', () => { props.clearAll(); // ensure everything gets cleared }); return tagInstance; }
javascript
{ "resource": "" }
q43851
train
function( editor, name, isIndent ) { this.name = name; this.editor = editor; /** * An object of jobs handled by the command. Each job consists * of two functions: `refresh` and `exec` as well as the execution priority. * * * The `refresh` function determines whether a job is doable for * a particular context. These functions are executed in the * order of priorities, one by one, for all plugins that registered * jobs. As jobs are related to generic commands, refreshing * occurs when the global command is firing the `refresh` event. * * **Note**: This function must return either {@link CKEDITOR#TRISTATE_DISABLED} * or {@link CKEDITOR#TRISTATE_OFF}. * * * The `exec` function modifies the DOM if possible. Just like * `refresh`, `exec` functions are executed in the order of priorities * while the generic command is executed. This function is not executed * if `refresh` for this job returned {@link CKEDITOR#TRISTATE_DISABLED}. * * **Note**: This function must return a Boolean value, indicating whether it * was successful. If a job was successful, then no other jobs are being executed. * * Sample definition: * * command.jobs = { * // Priority = 20. * '20': { * refresh( editor, path ) { * if ( condition ) * return CKEDITOR.TRISTATE_OFF; * else * return CKEDITOR.TRISTATE_DISABLED; * }, * exec( editor ) { * // DOM modified! This was OK. * return true; * } * }, * // Priority = 60. This job is done later. * '60': { * // Another job. * } * }; * * For additional information, please check comments for * the `setupGenericListeners` function. * * @readonly * @property {Object} [={}] */ this.jobs = {}; /** * Determines whether the editor that the command belongs to has * {@link CKEDITOR.config#enterMode config.enterMode} set to {@link CKEDITOR#ENTER_BR}. * * @readonly * @see CKEDITOR.config#enterMode * @property {Boolean} [=false] */ this.enterBr = editor.config.enterMode == CKEDITOR.ENTER_BR; /** * Determines whether the command belongs to the indentation family. * Otherwise it is assumed to be an outdenting command. * * @readonly * @property {Boolean} [=false] */ this.isIndent = !!isIndent; /** * The name of the global command related to this one. * * @readonly */ this.relatedGlobal = isIndent ? 'indent' : 'outdent'; /** * A keystroke associated with this command (*Tab* or *Shift+Tab*). * * @readonly */ this.indentKey = isIndent ? 9 : CKEDITOR.SHIFT + 9; /** * Stores created markers for the command so they can eventually be * purged after the `exec` function is run. */ this.database = {}; }
javascript
{ "resource": "" }
q43852
train
function( editor, commands ) { editor.on( 'pluginsLoaded', function() { for ( var name in commands ) { ( function( editor, command ) { var relatedGlobal = editor.getCommand( command.relatedGlobal ); for ( var priority in command.jobs ) { // Observe generic exec event and execute command when necessary. // If the command was successfully handled by the command and // DOM has been modified, stop event propagation so no other plugin // will bother. Job is done. relatedGlobal.on( 'exec', function( evt ) { if ( evt.data.done ) return; // Make sure that anything this command will do is invisible // for undoManager. What undoManager only can see and // remember is the execution of the global command (relatedGlobal). editor.fire( 'lockSnapshot' ); if ( command.execJob( editor, priority ) ) evt.data.done = true; editor.fire( 'unlockSnapshot' ); // Clean up the markers. CKEDITOR.dom.element.clearAllMarkers( command.database ); }, this, null, priority ); // Observe generic refresh event and force command refresh. // Once refreshed, save command state in event data // so generic command plugin can update its own state and UI. relatedGlobal.on( 'refresh', function( evt ) { if ( !evt.data.states ) evt.data.states = {}; evt.data.states[ command.name + '@' + priority ] = command.refreshJob( editor, priority, evt.data.path ); }, this, null, priority ); } // Since specific indent commands have no UI elements, // they need to be manually registered as a editor feature. editor.addFeature( command ); } )( this, commands[ name ] ); } } ); }
javascript
{ "resource": "" }
q43853
train
function( editor, priority ) { var job = this.jobs[ priority ]; if ( job.state != TRISTATE_DISABLED ) return job.exec.call( this, editor ); }
javascript
{ "resource": "" }
q43854
setupGenericListeners
train
function setupGenericListeners( editor, command ) { var selection, bookmarks; // Set the command state according to content-specific // command states. command.on( 'refresh', function( evt ) { // If no state comes with event data, disable command. var states = [ TRISTATE_DISABLED ]; for ( var s in evt.data.states ) states.push( evt.data.states[ s ] ); this.setState( CKEDITOR.tools.search( states, TRISTATE_OFF ) ? TRISTATE_OFF : TRISTATE_DISABLED ); }, command, null, 100 ); // Initialization. Save bookmarks and mark event as not handled // by any plugin (command) yet. command.on( 'exec', function( evt ) { selection = editor.getSelection(); bookmarks = selection.createBookmarks( 1 ); // Mark execution as not handled yet. if ( !evt.data ) evt.data = {}; evt.data.done = false; }, command, null, 0 ); // Housekeeping. Make sure selectionChange will be called. // Also re-select previously saved bookmarks. command.on( 'exec', function( evt ) { editor.forceNextSelectionCheck(); selection.selectBookmarks( bookmarks ); }, command, null, 100 ); }
javascript
{ "resource": "" }
q43855
train
function (event, fn, context) { this._events = this._events || {}; var e = this._events[event] || (this._events[event] = []); e.push([fn, context]); }
javascript
{ "resource": "" }
q43856
train
function (obj, event, fn, context) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = eventIndex++); listeningTo[id] = obj; if (!fn && typeof event === 'object') { fn = this; } if (!context) { context = this; } obj.on(event, fn, context); }
javascript
{ "resource": "" }
q43857
train
function (event, fn) { this._events = this._events || {}; var e = this._events[event]; if (e) { for (var i = 0, l = e.length; i < l; i++) { if (e[i][0] === fn) { e.splice(i, 1); i--; l--; } } } }
javascript
{ "resource": "" }
q43858
train
function (obj, event, fn) { var listeningTo = this._listeningTo; if (!listeningTo) { return; } var remove = !event && !fn; if (!fn && typeof event === 'object') { fn = this; } if (obj) { (listeningTo = {})[obj._listenId] = obj; } for (var id in listeningTo) { obj = listeningTo[id]; obj.off(event, fn, this); if (remove) { delete this._listeningTo[id]; } } }
javascript
{ "resource": "" }
q43859
train
function (event/*, args... */) { this._events = this._events || {}; var e = this._events[event]; if (e) { for (var i = 0, l = e.length; i < l; i++){ e[i][0].apply(e[i][1] || this, slice(arguments, 1)); } } }
javascript
{ "resource": "" }
q43860
Property
train
function Property (initValue) { if (arguments.length) { this.set(initValue); } else { this.set(this.defaultValue); } ok.Data.apply(this, arguments); }
javascript
{ "resource": "" }
q43861
train
function (newValue) { var oldValue = this._value; if (oldValue !== newValue) { this._value = newValue; this.trigger(EVENT_CHANGE, this, newValue, oldValue); } }
javascript
{ "resource": "" }
q43862
deleteUser
train
function deleteUser(id, callback) { orionAccount.findByUsername(id, function(err, user) { if(err) { callback(err); } const userPath = path.join(this.options.workspaceDir, id.substring(0,2)); fs.access(userPath, (err) => { if(err) { callback(err); } //TODO should a delete failure prevent the user delete? return rimraf(userPath, (err) => { if(err) { callback(err); } orionAccount.remove({username: id}, callback); }); }); }.bind(this)); }
javascript
{ "resource": "" }
q43863
isDirective
train
function isDirective(node) { return node.type === "ExpressionStatement" && node.expression.type === "Literal" && typeof node.expression.value === "string"; }
javascript
{ "resource": "" }
q43864
TaskList
train
function TaskList(options) { var parent = lib.node(options.parent); if (!parent) { throw messages['no parent']; } if (!options.serviceRegistry) {throw messages["no service registry"]; } this._parent = parent; this._registry = options.serviceRegistry; this._description = options.description; this._tasks = options.tasks; this._title = options.title || messages["Tasks"]; this._collapsed = options.collapsed; this._id = options.id || this._parent.id + "taskList"; //$NON-NLS-0$ this._contentId = this._parent.id + "taskContent"; //$NON-NLS-0$ this._item = options.item; this._handler = options.handler; this._commandService = options.commandService; this._descriptionProperty = options.descriptionProperty; this.renderTasks(); }
javascript
{ "resource": "" }
q43865
train
function() { /** All events from last tick */ var pendingEvents = this._annotationChangedContext.events; var pendingLocations = this._annotationChangedContext.locations; var pendingModels = this._annotationChangedContext.textModels; /** All unique events from last tick */ var handlingEvents = []; var handlingLocations = []; var handlingModels = []; // Cleanup this._annotationChangedContext.timeout = undefined; this._annotationChangedContext.events = []; this._annotationChangedContext.locations = []; // Remove duplicate events for (var i = 0; i < pendingEvents.length; i++) { var duplicate = false; for (var j = 0; j < i; j++) { if (pendingEvents[i].textModelChangedEvent === pendingEvents[j].textModelChangedEvent) { duplicate = true; } break; } if (!duplicate) { handlingEvents.push(pendingEvents[i]); handlingLocations.push(pendingLocations[i]); handlingModels.push(pendingModels[i]); } } // Handle for (i = 0; i < handlingEvents.length; i++) { var e = handlingEvents[i]; for (j = 0; j < e.changed.length; j++) { var annotation = e.changed[j]; var location = handlingLocations[i]; var oldLine; var newLine = handlingModels[i].getLineAtOffset(annotation.start); if (annotation._oldStart > e.textModelChangedEvent.start) { oldLine = newLine - e.textModelChangedEvent.addedLineCount + e.textModelChangedEvent.removedLineCount; } else { oldLine = handlingModels[i].getLineAtOffset(annotation._oldStart); } var before = null; var after = null; if (annotation.type === AT.ANNOTATION_BOOKMARK) { before = new mBreakpoint.LineBookmark(location, oldLine, annotation.title); after = new mBreakpoint.LineBookmark(location, newLine, annotation.title); } else if (annotation.type === AT.ANNOTATION_BREAKPOINT) { before = new mBreakpoint.LineBreakpoint(location, oldLine, annotation.title, true); after = new mBreakpoint.LineBreakpoint(location, newLine, annotation.title, true); } else if (annotation.type === AT.ANNOTATION_CONDITIONAL_BREAKPOINT) { before = new mBreakpoint.LineConditionalBreakpoint(location, oldLine, annotation.title, annotation.title, true); after = new mBreakpoint.LineConditionalBreakpoint(location, newLine, annotation.title, annotation.title, true); } if (before && after) { this.debugService.updateBreakpoint(before, after, true); } } } }
javascript
{ "resource": "" }
q43866
train
function(serviceRegistry, setup) { this._setup = setup; this._projectClient = serviceRegistry.getService("orion.project.client"); serviceRegistry.registerService("orion.edit.hover", this, { name: 'Hover Evaluation', contentType: ["application/javascript", "text/x-c++src", "text/x-python"] // TODO: get by sub-services }); }
javascript
{ "resource": "" }
q43867
train
function(editorContext, ctxt) { var promise = new Deferred(); var launchConf = this._setup.runBar.getSelectedLaunchConfiguration(); if (launchConf) { this._projectClient.getProjectDeployService(launchConf.ServiceId, launchConf.Type).then(function(service){ if (service && service.computeHoverInfo) { service.computeHoverInfo(launchConf, editorContext, ctxt).then(function(value) { promise.resolve(value); }, function() { promise.resolve(null); }); } else { console.error('Failed to evaluate hover.'); promise.resolve(null); } }); } else { promise.resolve(null); } return promise; }
javascript
{ "resource": "" }
q43868
StringField
train
function StringField(type, options) { Field.call(this, type, options); this.arg = new Argument(); this.element = util.createElement(this.document, 'input'); this.element.type = 'text'; this.element.classList.add('gcli-field'); this.onInputChange = this.onInputChange.bind(this); this.element.addEventListener('keyup', this.onInputChange, false); this.onFieldChange = util.createEvent('StringField.onFieldChange'); }
javascript
{ "resource": "" }
q43869
BooleanField
train
function BooleanField(type, options) { Field.call(this, type, options); this.name = options.name; this.named = options.named; this.element = util.createElement(this.document, 'input'); this.element.type = 'checkbox'; this.element.id = 'gcliForm' + this.name; this.onInputChange = this.onInputChange.bind(this); this.element.addEventListener('change', this.onInputChange, false); this.onFieldChange = util.createEvent('BooleanField.onFieldChange'); }
javascript
{ "resource": "" }
q43870
DelegateField
train
function DelegateField(type, options) { Field.call(this, type, options); this.options = options; this.requisition.onAssignmentChange.add(this.update, this); this.element = util.createElement(this.document, 'div'); this.update(); this.onFieldChange = util.createEvent('DelegateField.onFieldChange'); }
javascript
{ "resource": "" }
q43871
train
function() { this._createSettingsCommand(); this._createGotoLineCommnand(); this._createFindCommnand(); this._createBlameCommand(); this._createDiffCommand(); this._createShowTooltipCommand(); this._createUndoStackCommands(); this._createClipboardCommands(); this._createDelimiterCommands(); this._createEncodingCommand(); this._createFormatterCommand(); this._createSaveCommand(); this._createOpenFolderCommand(); this._createOpenRecentCommand(); this._createSwitchWorkspaceCommand(); this._createReferencesCommand(); this._createOpenDeclCommand(); return this._createEditCommands(); }
javascript
{ "resource": "" }
q43872
ASTManager
train
function ASTManager(serviceRegistry, jsProject) { this.cache = new LRU(10); this.orionAcorn = new OrionAcorn(); this.jsProject = jsProject; registry = serviceRegistry; }
javascript
{ "resource": "" }
q43873
CommandRegistry
train
function CommandRegistry(options) { this._commandList = {}; this._contributionsByScopeId = {}; this._activeBindings = {}; this._urlBindings = {}; this._pendingBindings = {}; // bindings for as-yet-unknown commands this._parameterCollector = null; this._init(options || {}); }
javascript
{ "resource": "" }
q43874
train
function(url) { for (var id in this._urlBindings) { if (this._urlBindings[id] && this._urlBindings[id].urlBinding && this._urlBindings[id].command) { var match = this._urlBindings[id].urlBinding.match(url); if (match) { var urlBinding = this._urlBindings[id]; var command = urlBinding.command; var invocation = urlBinding.invocation; // If the command has not rendered (visibleWhen=false, etc.) we don't have an invocation. if (invocation && invocation.parameters && command.callback) { invocation.parameters.setValue(match.parameterName, match.parameterValue); var self = this; window.setTimeout(function() { self._invoke(invocation); }, 0); return; } } } } }
javascript
{ "resource": "" }
q43875
train
function(commandId, item, handler, parameters, userData, parent) { var self = this; if (item) { var command = this._commandList[commandId]; var enabled = command && (command.visibleWhen ? command.visibleWhen(item) : true); if (enabled && command.callback) { var commandInvocation = new Commands.CommandInvocation(handler, item, userData, command, self); commandInvocation.domParent = parent; return self._invoke(commandInvocation, parameters); } } else { //TODO should we be keeping invocation context for commands without bindings? var binding = this._urlBindings[commandId]; if (binding && binding.command) { if (binding.command.callback) { return self._invoke(binding.invocation, parameters); } } } }
javascript
{ "resource": "" }
q43876
train
function(node, fillFunction, onClose, name) { if (this._parameterCollector) { this._parameterCollector.close(); this._parameterCollector.open(node, fillFunction, onClose, name); } }
javascript
{ "resource": "" }
q43877
train
function(node, message, yesString, noString, modal, onConfirm) { this._popupDialog(modal,"CONFIRM", node, message, [{label:yesString,callback:onConfirm,type:"ok"},{label:noString,callback:null,type:"cancel"}]); }
javascript
{ "resource": "" }
q43878
train
function(node, message, yesString, onConfirm) { this._popupDialog(false, "ALERT", node, message, [{label:yesString,callback:onConfirm,type:"ok"}]); }
javascript
{ "resource": "" }
q43879
train
function(node, message, yesString, noString, defaultInput, modal, onConfirm, positionString) { var position = null; if(positionString === "below"){position = ["below", "right", "above", "left"];} else if(positionString === "right"){position = ["right", "above", "below", "left"];} this._popupDialog(modal,"PROMPT", node, message, [{label:yesString,callback:onConfirm,type:"ok"},{label:noString,callback:null,type:"cancel"}], defaultInput, position); }
javascript
{ "resource": "" }
q43880
train
function(keyAssist) { var scopes = {}; var binding; // see commands.js _processKey function execute(activeBinding) { return function() { Commands.executeBinding(activeBinding); }; } var bindings = []; for (var aBinding in this._activeBindings) { binding = this._activeBindings[aBinding]; if (binding && binding.keyBinding && binding.command && (binding.command.name || binding.command.tooltip)) { bindings.push(binding); } } bindings.sort(function (a, b) { var ta = a.command.name || a.command.tooltip; var tb = b.command.name || b.command.tooltip; return ta.localeCompare(tb); }); for (var i=0; i<bindings.length; i++) { binding = bindings[i]; // skip scopes and process at end if (binding.keyBinding.scopeName) { if (!scopes[binding.keyBinding.scopeName]) { scopes[binding.keyBinding.scopeName] = []; } scopes[binding.keyBinding.scopeName].push(binding); } else { keyAssist.createItem(binding.keyBinding, binding.command.name || binding.command.tooltip, binding.command.id, execute(binding)); } } for (var scopedBinding in scopes) { if (scopes[scopedBinding].length && scopes[scopedBinding].length > 0) { keyAssist.createHeader(scopedBinding, lib.validId(scopedBinding) + "Scope"); //$NON-NLS-0$ scopes[scopedBinding].forEach(function(binding) { keyAssist.createItem(binding.keyBinding, binding.command.name || binding.command.tooltip, binding.command.id, execute(binding)); }); } } }
javascript
{ "resource": "" }
q43881
train
function(command) { this._commandList[command.id] = command; // Resolve any pending key/url bindings against this command var pending = this._pendingBindings[command.id]; if (pending) { var _self = this; pending.forEach(function(binding) { _self._addBinding(command, binding.type, binding.binding, binding.bindingOnly); }); delete this._pendingBindings[command.id]; } }
javascript
{ "resource": "" }
q43882
train
function(scopeId, groupId, position, title, parentPath, emptyGroupMessage, imageClass, tooltip, selectionClass, defaultActionId, extraClasses) { if (!this._contributionsByScopeId[scopeId]) { this._contributionsByScopeId[scopeId] = {}; } var parentTable = this._contributionsByScopeId[scopeId]; if (parentPath) { parentTable = this._createEntryForPath(parentTable, parentPath); } if (parentTable[groupId]) { // update existing group definition if info has been supplied if (title) { parentTable[groupId].title = title; } if (position) { parentTable[groupId].position = position; } if (imageClass) { parentTable[groupId].imageClass = imageClass; } if (tooltip) { parentTable[groupId].tooltip = tooltip; } if (selectionClass) { parentTable[groupId].selectionClass = selectionClass; } if (extraClasses) { parentTable[groupId].extraClass = extraClasses; } if(defaultActionId === true){ parentTable[groupId].pretendDefaultActionId = true; } else { parentTable[groupId].defaultActionId = defaultActionId; } parentTable[groupId].emptyGroupMessage = emptyGroupMessage; } else { // create new group definition parentTable[groupId] = {title: title, position: position, emptyGroupMessage: emptyGroupMessage, imageClass: imageClass, tooltip: tooltip, selectionClass: selectionClass, defaultActionId: defaultActionId === true ? null : defaultActionId, pretendDefaultActionId: defaultActionId === true, children: {}, extraClasses: extraClasses}; parentTable.sortedContributions = null; } }
javascript
{ "resource": "" }
q43883
train
function(scopeId, selectionService) { if (!this._contributionsByScopeId[scopeId]) { this._contributionsByScopeId[scopeId] = {}; } this._contributionsByScopeId[scopeId].localSelectionService = selectionService; }
javascript
{ "resource": "" }
q43884
train
function(scopeId, commandId, position, parentPath, bindingOnly, keyBinding, urlBinding, handler) { if (!this._contributionsByScopeId[scopeId]) { this._contributionsByScopeId[scopeId] = {}; } var parentTable = this._contributionsByScopeId[scopeId]; if (parentPath) { parentTable = this._createEntryForPath(parentTable, parentPath); } // store the contribution parentTable[commandId] = {position: position, handler: handler}; var command; if (this._bindingOverrides) { var bindingOverride = this.getBindingOverride(commandId, keyBinding); if (bindingOverride) { keyBinding = bindingOverride; } } // add to the bindings table now if (keyBinding) { command = this._commandList[commandId]; if (command) { this._addBinding(command, "key", keyBinding, bindingOnly); //$NON-NLS-0$ } else { this._addPendingBinding(commandId, "key", keyBinding, bindingOnly); //$NON-NLS-0$ } } // add to the url key table if (urlBinding) { command = this._commandList[commandId]; if (command) { this._addBinding(command, "url", urlBinding, bindingOnly); //$NON-NLS-0$ } else { this._addPendingBinding(commandId, "url", urlBinding, bindingOnly); //$NON-NLS-0$ } } // get rid of sort cache because we have a new contribution parentTable.sortedContributions = null; }
javascript
{ "resource": "" }
q43885
train
function(commandId, type, binding, bindingOnly) { this._pendingBindings[commandId] = this._pendingBindings[commandId] || []; this._pendingBindings[commandId].push({ type: type, binding: binding, bindingOnly: bindingOnly }); }
javascript
{ "resource": "" }
q43886
train
function(scopeId, parent, items, handler, renderType, userData, domNodeWrapperList) { if (typeof(scopeId) !== "string") { //$NON-NLS-0$ throw "a scope id for rendering must be specified"; //$NON-NLS-0$ } parent = lib.node(parent); if (!parent) { throw "no parent"; //$NON-NLS-0$ } var contributions = this._contributionsByScopeId[scopeId]; if (!items && contributions) { var selectionService = contributions.localSelectionService || this._selectionService; var self = this; if (selectionService) { selectionService.getSelections(function(selections) { self.renderCommands(scopeId, parent, selections, handler, renderType, userData); }); } return; } if (contributions) { this._render(scopeId, contributions, parent, items, handler, renderType || "button", userData, domNodeWrapperList); //$NON-NLS-0$ // If the last thing we rendered was a group, it's possible there is an unnecessary trailing separator. this._checkForTrailingSeparator(parent, renderType, true); } }
javascript
{ "resource": "" }
q43887
train
function(parent) { parent = lib.node(parent); if (!parent) { throw "no parent"; //$NON-NLS-0$ } while (parent.hasChildNodes()) { var node = parent.firstChild; if (node.commandTooltip) { node.commandTooltip.destroy(); } if (node.emptyGroupTooltip) { node.emptyGroupTooltip.destroy(); } this.destroy(node); parent.removeChild(node); } }
javascript
{ "resource": "" }
q43888
train
function (url) { //ensure this is only the hash portion var params = PageUtil.matchResourceParameters(url); if (typeof params[this.token] !== "undefined") { //$NON-NLS-0$ this.parameterValue = params[this.token]; return this; } return null; }
javascript
{ "resource": "" }
q43889
CommandParameter
train
function CommandParameter (name, type, label, value, lines, eventListeners, validator) { this.name = name; this.type = type; this.label = label; this.value = value; this.lines = lines || 1; this.validator = validator; this.eventListeners = (Array.isArray(eventListeners)) ? eventListeners : (eventListeners ? [eventListeners] : []); }
javascript
{ "resource": "" }
q43890
ParametersDescription
train
function ParametersDescription (parameters, options, getParameters) { this._storeParameters(parameters); this._hasOptionalParameters = options && options.hasOptionalParameters; this._options = options; // saved for making a copy this.optionsRequested = false; this.getParameters = getParameters; this.clientCollect = options && options.clientCollect; this.getParameterElement = options && options.getParameterElement; this.getSubmitName = options && options.getSubmitName; this.getCancelName = options && options.getCancelName; this.message = options && options.message; }
javascript
{ "resource": "" }
q43891
train
function(func) { for (var key in this.parameterTable) { if (this.parameterTable[key].type && this.parameterTable[key].name) { func(this.parameterTable[key]); } } }
javascript
{ "resource": "" }
q43892
train
function() { var parameters = []; this.forEach(function(parm) { var newParm = new CommandParameter(parm.name, parm.type, parm.label, parm.value, parm.lines, parm.eventListeners, parm.validator); parameters.push(newParm); }); var copy = new ParametersDescription(parameters, this._options, this.getParameters); // this value may have changed since the options copy.clientCollect = this.clientCollect; copy.message = this.message; return copy; }
javascript
{ "resource": "" }
q43893
xhrJson
train
function xhrJson(method, url, options) { if (options && typeof options.data !== 'undefined') { options.data = JSON.stringify(options.data); } return xhr.apply(null, Array.prototype.slice.call(arguments)).then(function(result) { return JSON.parse(result.response || null); }); }
javascript
{ "resource": "" }
q43894
flashNode
train
function flashNode(node, match) { if (!node.__gcliHighlighting) { node.__gcliHighlighting = true; var original = node.style.background; node.style.background = match ? 'green' : 'red'; setTimeout(function() { node.style.background = original; delete node.__gcliHighlighting; }, 500); } }
javascript
{ "resource": "" }
q43895
removeWorkspaceAccess
train
function removeWorkspaceAccess(userAccessRights, workspaceId) { var newAccessRights = []; if(Array.isArray(userAccessRights)) { userAccessRights.forEach(function(accessRight) { if(!new RegExp("/" + workspaceId + "(\/|$)").test(accessRight.Uri)) { newAccessRights.push(accessRight); } }); } return newAccessRights; }
javascript
{ "resource": "" }
q43896
hasAccess
train
function hasAccess(access, res, err, next, uri){ if (err) { api.writeError(404, res, err); } if(access) { next(); } else { api.writeError(403, res, "You are not authorized to access: " + uri); } }
javascript
{ "resource": "" }
q43897
wildCardMatch
train
function wildCardMatch(text, pattern){ var cards = pattern.split("*"); if (!pattern.startsWith("*") && !text.startsWith(cards[0])) { //$NON-NLS-1$ return false; } if (!pattern.endsWith("*") && !text.endsWith(cards[cards.length - 1])) { //$NON-NLS-1$ return false; } return !cards.some(function(card){ var idx = text.indexOf(card); if (idx === -1){ return true; } text = text.substring(idx + card.length); }); }
javascript
{ "resource": "" }
q43898
getAuthorizationData
train
function getAuthorizationData(metadata, store){ var properties; var workspaceIDs; var isPropertyString; if (typeof metadata.properties === "string") { isPropertyString = true; properties = JSON.parse(metadata.properties); // metadata.properties need to be parse when using MongoDB workspaceIDs = metadata.workspaces.map(function(workspace){ return workspace.id; }); } else { isPropertyString = false; properties = metadata.properties; // metadata.properties don't need to be parse when using FS workspaceIDs = metadata.WorkspaceIds; // This is only needed for Java server's metadata migration from old Java code } var version = properties["UserRightsVersion"] || 1; //assume version 1 if not specified var userRightArray = []; if (version === 1 || version === 2) { // This only for Java server's metadata migration workspaceIDs.forEach(function(workspaceId){ userRightArray = userRightArray.concat(createUserAccess(metadata["UniqueId"]).concat(createWorkspaceAccess(workspaceId))); }); properties["UserRights"] = userRightArray; properties["UserRightsVersion"] = CURRENT_VERSION; if (isPropertyString) { metadata.properties = JSON.stringify(properties, null, 2); } store.updateUser(metadata["UniqueId"], metadata, function(){}); } else { userRightArray = properties.UserRights; } return userRightArray; }
javascript
{ "resource": "" }
q43899
train
function() { if (this.capabilities && this.capabilities.textDocumentSync) { var kind = this.capabilities.textDocumentSync; if (this.capabilities.textDocumentSync.change) { kind = this.capabilities.textDocumentSync.change; } switch (kind) { case this.ipc.TEXT_DOCUMENT_SYNC_KIND.None: case this.ipc.TEXT_DOCUMENT_SYNC_KIND.Incremental: case this.ipc.TEXT_DOCUMENT_SYNC_KIND.Full: return kind; } } return this.ipc.TEXT_DOCUMENT_SYNC_KIND.None; }
javascript
{ "resource": "" }