_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q300
renameClassName
train
function renameClassName(ast, oldName, newName) { let defNode = null; // Find the definition node of the class traverse(ast, { ClassDeclaration(path) { if (path.node.id && path.node.id.name === oldName) { defNode = path.node.id; } } }); if (defNode) { return identifier.renameIdentifier(ast, oldName, newName, defNode); } return []; }
javascript
{ "resource": "" }
q301
renameIdentifier
train
function renameIdentifier(ast, oldName, newName, defNode) { // Summary: // Rename identifiers with oldName in ast const changes = []; if (!defNode) { let scope; traverse(ast, { Identifier(path) { if (path.node.name === oldName) { scope = path.scope; path.stop(); } }, }); if (!scope) return changes; defNode = getDefNode(oldName, scope); } function rename(path) { if ( path.node.name === oldName && path.key !== 'imported' && // it should NOT be imported specifier getDefNode(path.node.name, path.scope) === defNode ) { path.node.name = newName; changes.push({ start: path.node.start, end: path.node.end, replacement: newName, }); } } traverse(ast, { JSXIdentifier: rename, Identifier: rename, }); return changes; }
javascript
{ "resource": "" }
q302
isLocalModule
train
function isLocalModule(modulePath) { // TODO: handle alias module path like src const alias = getModuleResolverAlias(); return /^\./.test(modulePath) || _.keys(alias).some(a => modulePath === a || _.startsWith(modulePath, a + '/')); }
javascript
{ "resource": "" }
q303
resolveModulePath
train
function resolveModulePath(relativeToFile, modulePath) { if (!isLocalModule(modulePath)) { return modulePath; } const alias = getModuleResolverAlias(); const matched = _.find(_.keys(alias), k => _.startsWith(modulePath, k)); let res = null; if (matched) { const resolveTo = alias[matched]; const relativePath = modulePath.replace(new RegExp(`^${matched}`), '').replace(/^\//, ''); res = paths.map(resolveTo, relativePath); // res = utils.joinPath(utils.getProjectRoot(), resolveTo, relativePath); } else { res = paths.join(path.dirname(relativeToFile), modulePath); } let relPath = res.replace(paths.getProjectRoot(), '').replace(/^\/?/, ''); if (vio.dirExists(relPath)) { // if import from a folder, then resolve to index.js relPath = paths.join(relPath, 'index'); } return relPath; }
javascript
{ "resource": "" }
q304
renameFunctionName
train
function renameFunctionName(ast, oldName, newName) { // Summary: // Rename the name of the function first found. Usually used by // flat function definition file. let defNode = null; // Find the definition node of the class traverse(ast, { FunctionDeclaration(path) { if (path.node.id && path.node.id.name === oldName) { defNode = path.node.id; } } }); if (defNode) { return identifier.renameIdentifier(ast, oldName, newName, defNode); } return []; }
javascript
{ "resource": "" }
q305
nearestCharAfter
train
function nearestCharAfter(char, str, index) { // Find the nearest char index before given index. skip white space strings // If not found, return -1 let i = index + 1; while (i < str.length) { if (str.charAt(i) === char) return i; if (!/\s/.test(str.charAt(i))) return -1; i += 1; } return -1; }
javascript
{ "resource": "" }
q306
addToArrayByNode
train
function addToArrayByNode(node, code) { // node: the arr expression node // code: added as the last element of the array const multilines = node.loc.start.line !== node.loc.end.line; let insertPos = node.start + 1; // insert after '[' if (node.elements.length) { const ele = _.last(node.elements); insertPos = ele.end; } let replacement; if (multilines) { const indent = _.repeat(' ', node.loc.end.column - 1); replacement = `\n${indent} ${code}`; if (node.elements.length) { replacement = `,${replacement}`; } else { replacement = `${replacement},`; } } else { replacement = code; if (node.elements.length > 0) { replacement = `, ${code}`; } } return [ { start: insertPos, end: insertPos, replacement, }, ]; }
javascript
{ "resource": "" }
q307
removeFromArrayByNode
train
function removeFromArrayByNode(node, eleNode) { const elements = node.elements; if (!elements.includes(eleNode)) { logger.warn('Failed to find element when trying to remove element from array.'); return []; } if (!node._filePath) { throw new Error('No _filePath property found on node when removing element from array'); } const content = vio.getContent(node._filePath); let startPos = nearestCharBefore(',', content, eleNode.start); let isFirstElement = false; if (startPos < 0) { // it's the first element isFirstElement = true; startPos = node.start + 1; // start from the char just after the '[' } let endPos = eleNode.end; if (elements.length === 1 || isFirstElement) { // if the element is the only element, try to remove the trailing comma if exists const nextComma = nearestCharAfter(',', content, endPos - 1); if (nextComma >= 0) endPos = nextComma + 1; } return [ { start: startPos, end: endPos, replacement: '', }, ]; }
javascript
{ "resource": "" }
q308
addToArray
train
function addToArray(ast, varName, identifierName) { let changes = []; traverse(ast, { VariableDeclarator(path) { const node = path.node; if (_.get(node, 'id.name') !== varName || _.get(node, 'init.type') !== 'ArrayExpression') return; node.init._filePath = ast._filePath; changes = addToArrayByNode(node.init, identifierName); path.stop(); }, }); return changes; }
javascript
{ "resource": "" }
q309
removeFromArray
train
function removeFromArray(ast, varName, identifierName) { let changes = []; traverse(ast, { VariableDeclarator(path) { const node = path.node; if (_.get(node, 'id.name') !== varName || _.get(node, 'init.type') !== 'ArrayExpression') return; node.init._filePath = ast._filePath; const toRemove = _.find(node.init.elements, ele => ele.name === identifierName); changes = removeFromArrayByNode(node.init, toRemove); path.stop(); }, }); return changes; }
javascript
{ "resource": "" }
q310
validateCards
train
function validateCards(cards) { if (!Array.isArray(cards)) { throw new Error('`cards` must be passed as an array'); } for (let i=0; i < cards.length; i++) { let card = cards[i]; if (card.type !== RENDER_TYPE) { throw new Error(`Card "${card.name}" must be type "${RENDER_TYPE}", was "${card.type}"`); } if (!card.render) { throw new Error(`Card "${card.name}" must define \`render\``); } } }
javascript
{ "resource": "" }
q311
parseElePath
train
function parseElePath(elePath, type = 'component') { const arr = elePath.split('/'); const feature = _.kebabCase(arr.shift()); let name = arr.pop(); if (type === 'action') name = _.camelCase(name); else if (type === 'component') name = pascalCase(name); else throw new Error('Unknown element type: ' + type + ' of ' + elePath); elePath = [feature, ...arr, name].join('/'); const ele = { name, path: elePath, feature, }; if (type === 'component') { ele.modulePath = `src/features/${elePath}.js`; ele.testPath = `tests/features/${elePath}.test.js`; ele.stylePath = `src/features/${elePath}.${config.getRekitConfig().css}`; } else if (type === 'action') { ele.modulePath = `src/features/${feature}/redux/${name}.js`; ele.testPath = `tests/features/${feature}/redux/${name}.test.js`; } return ele; }
javascript
{ "resource": "" }
q312
getTplPath
train
function getTplPath(tpl) { const tplFile = path.join(__dirname, './templates', tpl); const customTplDir = _.get(config.getRekitConfig(), 'rekitReact.templateDir') || path.join(paths.map('.rekit-react/templates')); const customTplFile = path.join(customTplDir, tpl); return fs.existsSync(customTplFile) ? customTplFile : tplFile; }
javascript
{ "resource": "" }
q313
handleMessages
train
function handleMessages(file, messages, options) { var success = true; var errorText = colors.bold(colors.red('HTML Error:')); var warningText = colors.bold(colors.yellow('HTML Warning:')); var infoText = colors.bold(colors.green('HTML Info:')); var lines = file.contents.toString().split(/\r\n|\r|\n/g); if (!Array.isArray(messages)) { fancyLog(warningText, 'Failed to run validation on', file.relative); // Not sure whether this should be true or false return true; } messages.forEach(function (message) { // allows you to intercept info, warnings or errors, using `options.verifyMessage` methed, returning false will skip the log output if(options.verifyMessage && !options.verifyMessage(message.type, message.message)) return; if (message.type === 'info' && !options.showInfo) { return; } if (message.type === 'error') { success = false; } var type = (message.type === 'error') ? errorText : ((message.type === 'info') ? infoText : warningText); var location = 'Line ' + (message.lastLine || 0) + ', Column ' + (message.lastColumn || 0) + ':'; var erroredLine = lines[message.lastLine - 1]; // If this is false, stream was changed since validation if (erroredLine) { var errorColumn = message.lastColumn; // Trim before if the error is too late in the line if (errorColumn > 60) { erroredLine = erroredLine.slice(errorColumn - 50); errorColumn = 50; } // Trim after so the line is not too long erroredLine = erroredLine.slice(0, 60); // Highlight character with error erroredLine = colors.grey(erroredLine.substring(0, errorColumn - 1)) + colors.bold(colors.red(erroredLine[ errorColumn - 1 ])) + colors.grey(erroredLine.substring(errorColumn)); } if (typeof(message.lastLine) !== 'undefined' || typeof(lastColumn) !== 'undefined') { fancyLog(type, file.relative, location, message.message); } else { fancyLog(type, file.relative, message.message); } if (erroredLine) { fancyLog(erroredLine); } }); return success; }
javascript
{ "resource": "" }
q314
getStateValues
train
function getStateValues (size, self) { var width = $(self.getDOMNode()).width(); return { profile: width > size ? 'large' : 'small' }; }
javascript
{ "resource": "" }
q315
add
train
function add(elePath, args) { if (!args || !args.urlPath) return; const ele = parseElePath(elePath, 'component'); const routePath = `src/features/${ele.feature}/route.js`; if (!vio.fileExists(routePath)) { throw new Error(`route.add failed: file not found ${routePath}`); } const { urlPath } = args; refactor.addImportFrom(routePath, './', '', ele.name); const ast1 = ast.getAst(routePath, true); const arrNode = getChildRoutesNode(ast1); if (arrNode) { const rule = `{ path: '${urlPath}', component: ${ele.name}${ args.isIndex ? ', isIndex: true' : '' } }`; const changes = refactor.addToArrayByNode(arrNode, rule); const code = refactor.updateSourceCode(vio.getContent(routePath), changes); vio.save(routePath, code); } else { throw new Error( `You are adding a route rule, but can't find childRoutes property in '${routePath}', please check.` ); } }
javascript
{ "resource": "" }
q316
train
function() { var messages = app.database.messages.find({ threadId: this.uid }, ok(this.set.bind(this, "messages"))); // update unreadMessageCount whenever the messages collection // changes messages.watch(function() { this.set("unreadMessageCount", messages.filter(function(message) { return !message.read; }).length); }.bind(this)); }
javascript
{ "resource": "" }
q317
train
function(onLoad) { // create the collection immediately so we only // apply an update to an existing collection (Users) // whenever messages changes var users = app.models.Users(); // pluck participants from the messages & update users caplet.watchProperty(this, "messages", function(messages) { var participants = []; var used = {}; messages.forEach(function(message) { if (used[message.userId]) return; used[message.userId] = 1; participants.push({ uid: message.userId }); }); users.set("data", participants); this.set("participants", users); }).trigger(); }
javascript
{ "resource": "" }
q318
AbstractError
train
function AbstractError(message, constr) { Error.apply(this, arguments); Error.captureStackTrace(this, constr || this); this.name = 'AbstractError'; this.message = message; }
javascript
{ "resource": "" }
q319
Rescuetime
train
function Rescuetime(apiKey, options) { // The api key is required if (!apiKey) { throw new RescuetimeError('Invalid API Key: ' + apiKey); } // Copy over the relavant data this.apiKey = apiKey; // Extend the defaults this.options = _.defaults(options || {}, Rescuetime.defaultOptions); // Contruct the endpoint with the correct auth from the appId and apiKey this.endpoint = this.options.endpoint; }
javascript
{ "resource": "" }
q320
train
function(user) { if (!this._shouldAllowUser(user)) { return false; } user.leaveRoom(); this.members.push(user); user.room = this; if (this.minRoomMembers !== null && this.members.length >= this.minRoomMembers) { this._hasReachedMin = true; } this._emitEvent('newMember', this, user); this._serverMessageMembers(this.isLobby ? 'lobbyMemberJoined' : 'roomMemberJoined', _.pick(user, 'id', 'name')); user._serverMessage('joinedRoom', _.pick(this, 'name')); return true; }
javascript
{ "resource": "" }
q321
getMcpSettings
train
async function getMcpSettings(accessToken) { let data = await mcpCustomizr.getSettings(accessToken); if (Object.keys(data).length === 0) { return { language: ['en'], regionalSettings: 'en', timezone: 'America/New_York', }; } return data; }
javascript
{ "resource": "" }
q322
setMcpSettings
train
async function setMcpSettings(accessToken, settings) { return await mcpCustomizr.putSettings(accessToken, { language: settings.language, regionalSettings: settings.regionalSettings, timezone: settings.timezone, }); }
javascript
{ "resource": "" }
q323
setPreferredMcpSettings
train
async function setPreferredMcpSettings(accessToken, languageCode, languageTag, timezone) { let preferredLanguage = getValidLanguageOrThrow(languageCode); let preferredRegionalSettings = getValidLanguageTagOrThrow(languageTag); let preferredTimezone = getValidTimezoneOrThrow(timezone); const mcpSettings = await getMcpSettings(accessToken); return await mcpCustomizr.putSettings(accessToken, { language: updatePreferredLanguage(preferredLanguage, mcpSettings.language), regionalSettings: preferredRegionalSettings, timezone: preferredTimezone, }); }
javascript
{ "resource": "" }
q324
getPreferredMcpLanguages
train
async function getPreferredMcpLanguages(accessToken) { const mcpSettings = await getMcpSettings(accessToken); const twoLetterArray = mcpSettings.language || []; return twoLetterArray.map((twoLetter) => { let language = countryLanguage.getLanguages().find((a) => a.iso639_1 === twoLetter); return { lang: twoLetter, iso639_1: language ? language.iso639_1 : twoLetter, iso639_2: language ? language.iso639_2 : undefined, iso639_3: language ? language.iso639_3 : undefined, }; }); }
javascript
{ "resource": "" }
q325
setPreferredMcpLanguage
train
async function setPreferredMcpLanguage(accessToken, languageCode) { let language = getValidLanguageOrThrow(languageCode); let currentLanguages = await getPreferredMcpLanguages(accessToken); return mcpCustomizr.putSettings(accessToken, { language: updatePreferredLanguage(language, currentLanguages), }); }
javascript
{ "resource": "" }
q326
getPreferredMcpRegionalSettings
train
async function getPreferredMcpRegionalSettings(accessToken) { const mcpSettings = await mcpCustomizr.getSettings(accessToken); return mcpSettings.regionalSettings; }
javascript
{ "resource": "" }
q327
setPreferredMcpRegionalSettings
train
async function setPreferredMcpRegionalSettings(accessToken, languageTag) { let regionalSettings = getValidLanguageTagOrThrow(languageTag); return mcpCustomizr.putSettings(accessToken, { regionalSettings: regionalSettings, }); }
javascript
{ "resource": "" }
q328
setPreferredMcpTimezone
train
async function setPreferredMcpTimezone(accessToken, timezone) { let tz = getValidTimezoneOrThrow(timezone); return mcpCustomizr.putSettings(accessToken, { timezone: tz, }); }
javascript
{ "resource": "" }
q329
train
function(msg) { var gameOverElement = document.getElementById('gameOver'), gameOverMsgElement = document.getElementById('gameOverMsg'), waitingForPlayerElem = document.getElementById('waitingForPlayer'); if (msg === false) { gameOverElement.style.display = 'none'; } else { gameOverMsgElement.innerText = msg; gameOverElement.style.display = 'block'; waitingForPlayerElem.style.display = 'none'; } }
javascript
{ "resource": "" }
q330
loader
train
function loader(source) { // dust files don't have side effects, so loader results are cacheable if (this.cacheable) this.cacheable(); // Set up default options & override them with other options const default_options = { root: '', dustAlias: 'dustjs-linkedin', namingFn: defaultNamingFunction, preserveWhitespace: false, wrapOutput: false, verbose: false, ignoreImages: false, excludeImageRegex: undefined }; // webpack 4 'this.options' was deprecated in webpack 3 and removed in webpack 4 // if you want to use global loader options, use dust-loader-complete < v4.0.0 // var query = this.options || this.query || {}; // var global_options = query['dust-loader-complete'] || {}; // get user supplied loader options from `this.query` const loader_options = getOptions(this) || {}; // merge user options with default options const options = Object.assign({}, default_options, loader_options); // Fix slashes & resolve root options.root = path.resolve(options.root.replace('/', path.sep)); // Get the path const template_path = path.relative(options.root, this.resourcePath); // Create the template name const name = options.namingFn(template_path, options); // Log log(options, 'Loading DustJS module from "' + template_path + '": naming template "' + name + '"'); // Find different styles of dependencies const deps = []; // Find regular dust partials, updating the source as needed for relatively-pathed partials source = findPartials(source, template_path + '/../', options, deps); // Find image dependencies if (!options.ignoreImages) { source = findImages(name, source, deps, options); } // Find require comments findRequireComments(source, template_path + '/../', options, deps); // Do not trim whitespace in case preserveWhitespace option is enabled dust.config.whitespace = options.preserveWhitespace; // Compile the template const template = dust.compile(source, name); // Build the returned string let returnedString; if (options.wrapOutput) { returnedString = "var dust = require('" + options.dustAlias + "/lib/dust'); " + deps.join(' ') + template + "var fn = " + defaultWrapperGenerator(name) + '; fn.templateName = "' + name + '"; ' + "module.exports = fn;"; } else { returnedString = "var dust = require('" + options.dustAlias + "'); " + deps.join(' ') + 'var template = ' + template + ';' + 'template.templateName = "' + name + '";' + "module.exports = template;"; } // Return the string to be used return returnedString }
javascript
{ "resource": "" }
q331
findPartials
train
function findPartials(source, source_path, options, deps) { var reg = /({>\s?")([^"{}]+)("[\s\S]*?\/})/g, // matches dust partial syntax result = null, partial, dep, name, replace; // search source & add a dependency for each match while ((result = reg.exec(source)) !== null) { partial = { prefix: result[1], name: result[2], suffix: result[3] }; // add to dependencies name = addDustDependency(partial.name, source_path, options, deps); // retrieve newest dependency dep = deps[deps.length - 1]; // log log(options, 'found partial dependency "' + partial.name + '"'); // if the partial has been renamed, update the name in the template if (name != partial.name) { log(options, 'renaming partial "' + partial.name + '" to "' + name + '"') // build replacement for partial tag replace = partial.prefix + name + partial.suffix; // replace the original partial path with the new "absolute" path (relative to root) source = source.substring(0, result.index) + replace + source.substring(result.index + result[0].length); // update regex index reg.lastIndex += (replace.length - result[0].length); } } return source; }
javascript
{ "resource": "" }
q332
determinePartialName
train
function determinePartialName(partial_path, source_path, options) { var match, rel, abs, path_reg = /(\.\.?\/)?(.+)/; // use a regex to find whether or not this is a relative path match = path_reg.exec(partial_path); if (match[1]) { // use os-appropriate separator rel = partial_path.replace('/', path.sep); // join the root, the source_path, and the relative path, then find the relative path from the root // this is the new "absolute"" path abs = path.relative(options.root, path.join(options.root, source_path, rel)); } else { // use os-appropriate separator abs = match[2].replace('/', path.sep); } // now use the naming function to get the name return options.namingFn(abs, options); }
javascript
{ "resource": "" }
q333
train
function(configArg) { config = _.extend({}, defaults); events = {}; _(configArg).forEach(function(val, key) { if (key === 'room' || key === 'lobby') { events[key] = val; } else { config[key] = val; } }); }
javascript
{ "resource": "" }
q334
findById
train
function findById(a, id) { for (var i = 0; i < a.length; i++) { if (a[i].id == id) return a[i]; } return null; }
javascript
{ "resource": "" }
q335
newRandomKey
train
function newRandomKey(coll, key, currentKey){ var randKey; do { randKey = coll[Math.floor(coll.length * Math.random())][key]; } while (randKey == currentKey); return randKey; }
javascript
{ "resource": "" }
q336
plugin
train
function plugin(options) { if (!options || typeof options !== 'object') { throw new Error('AjvMoment#plugin requires options'); } if (!options.ajv) { throw new Error(`AjvMoment#plugin options requries an 'ajv' attribute (ajv instance)`); } if (!options.moment) { throw new Error(`AjvMoment#plugin options requries a 'moment' attribute (moment.js)`); } const { ajv, moment } = options; ajv.moment = moment; const keywordSettings = { type: 'string', statements: true, errors: true, inline }; if (ajv) { ajv.addKeyword('moment', keywordSettings); } return keywordSettings; }
javascript
{ "resource": "" }
q337
getTimestamps
train
function getTimestamps() { try { var trans = db.transaction(['save'], "read"), store = trans.objectStore('save'), request = store.getAll(); request.onsuccess = function (e) { var i = 0, a = event.target.result, l = a.length; for (; i < l; i++) { timestamps[a[i].key] = a[i].timestamp; } }; } catch (e) { } }
javascript
{ "resource": "" }
q338
train
function (e) { var e = e || window.event; if (typeof callback === 'function') { callback.call(ctx, e); } }
javascript
{ "resource": "" }
q339
train
function(a, b, target){ if (target == null) target={} // Doing it in this order means we can use either a or b as the target, with no conflict // Round resulting values to integers; down for xy, up for wh // Would be slightly off if negative w, h were allowed target._h = Math.max(a._y + a._h, b._y + b._h); target._w = Math.max(a._x + a._w, b._x + b._w); target._x = ~~Math.min(a._x, b._x); target._y = ~~Math.min(a._y, b._y); target._w -= target._x; target._h -= target._y target._w = (target._w == ~~target._w) ? target._w : ~~target._w + 1 | 0; target._h = (target._h == ~~target._h) ? target._h : ~~target._h + 1 | 0; return target }
javascript
{ "resource": "" }
q340
train
function(){ var rect, obj, i; for (i=0, l=changed_objs.length; i<l; i++){ obj = changed_objs[i]; rect = obj._mbr || obj; if (obj.staleRect == null) obj.staleRect = {} obj.staleRect._x = rect._x; obj.staleRect._y = rect._y; obj.staleRect._w = rect._w; obj.staleRect._h = rect._h; obj._changed = false } changed_objs.length = 0; dirty_rects.length = 0 }
javascript
{ "resource": "" }
q341
train
function(a, b){ return (a._x < b._x + b._w && a._y < b._y + b._h && a._x + a._w > b._x && a._y + a._h > b._y) }
javascript
{ "resource": "" }
q342
IntercomError
train
function IntercomError(message, errors) { AbstractError.apply(this, arguments); this.name = 'IntercomError'; this.message = message; this.errors = errors; }
javascript
{ "resource": "" }
q343
train
function() { var valid = false; var destroy = true; var target = this; Crafty('Card').each(function() { if (this.intersect(target.x + target.w + game.config.cardBuffer, target.y, target.w, target.h) || this.intersect(target.x - target.w - game.config.cardBuffer, target.y, target.w, target.h) || this.intersect(target.x, target.y + target.h + game.config.cardBuffer, target.w, target.h) || this.intersect(target.x, target.y - target.h - game.config.cardBuffer, target.w, target.h) ) { valid = true; destroy = false; } if (this.intersect(target.x, target.y, target.w, target.h)) { destroy = false; } }); if (valid) { this.used = false; } else if (destroy) { this.destroy(); var currentTarget = this; game.targets = _.reject(game.targets, function(thisTarget) { return _.isEqual(thisTarget, currentTarget); }); } }
javascript
{ "resource": "" }
q344
Intercom
train
function Intercom(appId, apiKey, options) { // Overload the contractor // Parse out single option objects if (_.isObject(appId) && !_.isString(appId) && ((appId.apiKey && appId.appId) || appId.personalAccessToken)) { apiKey = appId.apiKey || ''; options = _.omit(appId, 'apiKey', 'appId'); appId = appId.appId || appId.personalAccessToken; } // Preform some sane validation checks and throw errors // We need the appId if (!appId) { throw new IntercomError('Invalid App ID: ' + appId); } // Copy over the relavant data this.appId = appId; this.apiKey = apiKey || ''; // Extend the defaults this.options = _.defaults(options || {}, Intercom.defaultOptions); // Contruct the endpoint with the correct auth from the appId and apiKey this.endpoint = this.options.endpoint; }
javascript
{ "resource": "" }
q345
getError
train
function getError(errno, app) { let errObj = { errno: errno, message: errors[errno].replace('$app', app) }; return errObj.message; }
javascript
{ "resource": "" }
q346
train
function (options) { EventEmitter.call(this); var self = this; self.options = _.extend({ user: '', password: '', userAgent: null, url: null, debug: false, parser: JSONBigInt }, options || {}); self._req = null; self.parser = new JSONParser(self.options.parser); self.parser.on('object', function (object) { self.emit('object', object); if (object.error) self.emit('error', new Error('Stream response error: ' + (object.error.message || '-'))); else if (object['delete']) self.emit('delete', object); else if (object.body || object.text) self.emit('tweet', object); }); self.parser.on('error', function (err) { self.emit('error', err); }); }
javascript
{ "resource": "" }
q347
benchBatch
train
function benchBatch(targets, cb, idx) { idx |= 0; if (targets.length == 0) return cb(idx); var target = targets.shift(); process.stdout.write(util.format('[%s] ', idx+1)); try { main.bench(target.name, target.func); idx++; } catch (err) { console.log('%s failed!', target.name); } //No more targets, no need to wait if (targets.length == 0) return cb(idx); //We need to wait some seconds before the next test, //or the results could vary depending on the order setTimeout(function() { benchBatch(targets, cb, idx); //Yeah, recursivity... }, 10000); }
javascript
{ "resource": "" }
q348
train
function(cssFile, config, cb) { var imgRegex = /url\s?\(['"]?(.*?)(?=['"]?\))/gi, css = null, img = null, inlineImgPath = null, imgPath = null, base = _.isUndefined(config.base) ? '' : config.base, processedImages = 0, match = [], mimetype = null; // read css file contents css = fs.readFileSync(cssFile, 'utf-8'); // find all occurences of images in the css file while (match = imgRegex.exec(css)) { imgPath = path.join(path.dirname(cssFile), match[1]); inlineImgPath = imgPath; // remove any query params from path (for cache busting etc.) if (imgPath.lastIndexOf('?') !== -1) { inlineImgPath = imgPath.substr(0, imgPath.lastIndexOf('?')); } // make sure that were only importing images if (path.extname(inlineImgPath) !== '.css') { try { // try to load the file without a given base path, // if that doesn´t work, try with try { img = fs.readFileSync(inlineImgPath, 'base64'); } catch (err) { img = fs.readFileSync(base + '/' + path.basename(inlineImgPath), 'base64'); } // replace file with bas64 data mimetype = mime.lookup(inlineImgPath); // check file size and ie8 compat mode if (img.length > 32768 && config.ie8 === true) { // i hate to write this, but can´t wrap my head around // how to do this better: DO NOTHING } else { css = css.replace(match[1], 'data:' + mimetype + ';base64,' + img); processedImages++; } } catch (err) { // Catch image file not found error grunt.verbose.error('Image file not found: ' + match[1]); } } } // check if a callback is given if (_.isFunction(cb)) { grunt.log.ok('Inlined: ' + processedImages + ' Images in file: ' + cssFile); cb(cssFile, css); } }
javascript
{ "resource": "" }
q349
train
function(htmlFile, config, cb) { var html = fs.readFileSync(htmlFile, 'utf-8'), processedImages = 0, $ = cheerio.load(html); // grab all <img/> elements from the document $('img').each(function (idx, elm) { var src = $(elm).attr('src'), imgPath = null, img = null, mimetype = null, inlineImgPath = null; // check if the image src is already a data attribute if (src.substr(0, 5) !== 'data:') { // figure out the image path and load it inlineImgPath = imgPath = path.join(path.dirname(htmlFile), src); img = fs.readFileSync(imgPath, 'base64'); mimetype = mime.lookup(inlineImgPath); // check file size and ie8 compat mode if (img.length > 32768 && config.ie8 === true) { // i hate to write this, but can´t wrap my head around // how to do this better: DO NOTHING } else { $(elm).attr('src', 'data:' + mimetype + ';base64,' + img); processedImages++; } } }); html = $.html(); // check if a callback is given if (_.isFunction(cb)) { grunt.log.ok('Inlined: ' + processedImages + ' Images in file: ' + htmlFile); cb(htmlFile, html); } }
javascript
{ "resource": "" }
q350
CliPie
train
function CliPie(r, data, options) { this.data = []; this.radius = r; this.total = 0; this.colors = {}; this.cChar = -1; this.options = Ul.deepMerge(options, { flat: true , chr: " " , no_ansi: false , circle_opts: { aRatio: 1 } , chars: "abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".split("") }); if (Array.isArray(data)) { data.forEach(this.add.bind(this)); } else if (data && data.constructor === Object) { options = data; } }
javascript
{ "resource": "" }
q351
train
function (options, limiter) { EventEmitter.call(this); this.limiter = limiter; this.active = false; this.options = _.extend({ user: '', password: '', url: '', query: '' }, options || {}); }
javascript
{ "resource": "" }
q352
swap
train
function swap(arr, i1, i2) { const tmp = arr[i1]; arr[i1] = arr[i2]; arr[i2] = tmp; }
javascript
{ "resource": "" }
q353
_bigintcmp
train
function _bigintcmp(a, b) { // The following code is a bit tricky to avoid code branching var c, abs_r, mask; var r = 0; for (c = 15; c >= 0; c--) { var x = a[c]; var y = b[c]; r = r + (x - y) * (1 - r * r); // http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs // correct for [-294967295, 294967295] mask = r >> 31; abs_r = (r + mask) ^ mask; // http://stackoverflow.com/questions/596467/how-do-i-convert-a-number-to-an-integer-in-javascript // this rounds towards zero r = ~~((r << 1) / (abs_r + 1)); } return r; }
javascript
{ "resource": "" }
q354
generateImports
train
function generateImports (context) { const { files, tree } = getPageData(context) store.state.components = tree const output = files .slice() .map(file => `import '@/${file}'`) .join('\n') fs.ensureDirSync(path.join(context, '.temp')) fs.writeFileSync(path.join(context, '.temp/html.js'), output) }
javascript
{ "resource": "" }
q355
generateFileLoaderOptions
train
function generateFileLoaderOptions (dir) { const name = `assets/${dir}/[name]${store.state.config.fileNameHash ? '.[hash:8]' : ''}.[ext]` const publicPath = process.env.NODE_ENV === 'production' ? '..' : undefined return { name, publicPath } }
javascript
{ "resource": "" }
q356
lintJS
train
function lintJS (args = []) { if (!Array.isArray(args)) { throw new TypeError('arguments has to be an array') } const command = [ `node ${resolveBin('eslint')}`, '--format codeframe', '"src/**/*.js"', ...args ].join(' ') console.log(chalk`\nCommand:\n{green ${command}}\n`) try { execSync(command, { stdio: 'inherit' }) } catch (error) { return false } return true }
javascript
{ "resource": "" }
q357
extractTypedef
train
async function extractTypedef(config) { const { source, destination, writable, } = config try { const s = createReadStream(source) const ts = createRegexTransformStream(typedefRe) const ps = new Properties() const readable = new PassThrough() const xml = new XML() await writeOnce(readable, '<types>\n') s.pipe(ts).pipe(ps).pipe(xml).pipe(readable, { end: false }) const p = whichStream({ readable, source, writable, destination, }) await new Promise((r, j) => { s.on('error', e => { LOG('Error in Read'); j(e) }) ts.on('error', e => { LOG('Error in Transform'); j(e) }) ps.on('error', e => { LOG('Error in RegexTransform'); j(e) }) xml.on('error', e => { LOG('Error in XML'); j(e) }) readable.on('error', e => { LOG('Error in Stream'); j(e) }) xml.on('end', r) }) await new Promise(r => readable.end('</types>\n', r)) await p } catch (err) { catcher(err) } }
javascript
{ "resource": "" }
q358
resolveBin
train
function resolveBin (moduleName) { // Get the directory from the module's package.json path const directory = path.dirname(require.resolve(`${moduleName}/package.json`)) // Get the relative bin path from the module's package.json bin key let bin = require(`${moduleName}/package.json`).bin // Sometimes the bin file isn't a string but an object // This extracts the first bin from that object if (typeof bin !== 'string') { bin = Object.values(bin)[0] } return path.join(directory, bin) }
javascript
{ "resource": "" }
q359
isDark
train
function isDark (r, g, b) { /** * W3C perceived brightness calculator * @see {@link https://www.w3.org/TR/AERT/#color-contrast} */ const brightness = ((r * 299) + (g * 587) + (b * 114)) / 1000 if (brightness < 140) { return true } return false }
javascript
{ "resource": "" }
q360
intercept
train
function intercept(req, res, next) { if ( !route.test(req.url) // Incorrect URL. || !req.headers.authorization // Missing authorization. || options.method !== req.method // Invalid method. ) return next(); // // Handle unauthorized requests. // if (authorization !== req.headers.authorization) { res.statusCode = 401; res.setHeader('Content-Type', 'application/json'); return res.end(JSON.stringify({ ok: false, reason: [ 'I am programmed to protect, and sacrifice if necessary.', 'Feel the power of my lazers! Pew pew!' ].join(' ') })); } var primus = this , buff = ''; if (typeof options.middleware === 'function') { options.middleware(primus, parse, req, res, next); } else { // // Receive the data from the socket. The `setEncoding` ensures that Unicode // chars are correctly buffered and parsed before the `data` event is // emitted. // req.setEncoding('utf8'); req.on('data', function data(chunk) { buff += chunk; }).once('end', function end() { parse(primus, buff, res); }); } }
javascript
{ "resource": "" }
q361
parse
train
function parse(primus, raw, res) { var called = 0 , data , err; try { data = JSON.parse(raw); } catch (e) { err = e; } if ( err // No error.. || 'object' !== typeof data // Should be an object. || Array.isArray(data) // A real object, not array. || !data.msg // The data we send should be defined. ) { res.statusCode = 500; res.setHeader('Content-Type', 'application/json'); return res.end('{ "ok": false, "reason": "invalid data structure" }'); } // // Process the incoming messages in three different modes: // // Sparks: The data.sparks is an array with spark id's which we should write // the data to. // Spark: The data.sparks is the id of one single individual spark which // should receive the data. // All: Broadcast the message to every single connected spark if no // `data.sparks` has been provided. // if (Array.isArray(data.sparks)) { data.sparks.forEach(function each(id) { var spark = primus.spark(id); if (spark) { spark.write(data.msg); called++; } }); } else if ('string' === typeof data.sparks && data.sparks) { var spark = primus.spark(data.sparks); if (spark) { spark.write(data.msg); called++; } } else { primus.forEach(function each(spark) { spark.write(data.msg); called++; }); } res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.end('{ "ok": true, "send":'+ called +' }'); }
javascript
{ "resource": "" }
q362
enhanceErrorMessages
train
function enhanceErrorMessages (method, log) { program.Command.prototype[method] = function (argument) { if (method === 'unknownOption' && this._allowUnknownOption) { return } this.outputHelp() console.log(chalk`\n{red ${log(argument)}}`) process.exit(1) } }
javascript
{ "resource": "" }
q363
generateTypedef
train
async function generateTypedef(config) { const { source, destination = source, writable, } = config try { if (!source && !writable) { console.log('Please specify a JavaScript file or a pass a stream.') process.exit(1) } const s = createReadStream(source) const readable = createJsReplaceStream() s.pipe(readable) const p = whichStream({ source, readable, destination: writable ? undefined : destination, writable, }) await new Promise((r, j) => { readable.on('error', e => { LOG('Error in Replaceable'); j(e) }) s.on('error', e => { LOG('Error in Read'); j(e) }) readable.on('end', r) }) await p if (writable) { LOG('%s written to stream', source) } else if (source == destination) { console.error('Updated %s to include types.', source) } else if (destination == '-') { console.error('Written %s to stdout.', source) } else { console.error('Saved output to %s', destination) } } catch (err) { catcher(err) } }
javascript
{ "resource": "" }
q364
run
train
async function run(options) { const { source, output = '-', reverse, justToc, h1, noCache, rootNamespace, } = options const stream = getStream(source, reverse, false) // todo: figure out why can't create a pass-through, pipe into it and pause it const { types, locations } = await getTypedefs(stream, rootNamespace) const stream3 = getStream(source, reverse, true) const doc = new Documentary({ locations, types, noCache, objectMode: true }) stream3.pipe(doc) const tocPromise = getToc(doc, h1, locations) const c = new Catchment() await whichStream({ readable: doc, writable: c, }) const toc = await tocPromise const result = (await c.promise) .replace('%%_DOCUMENTARY_TOC_CHANGE_LATER_%%', toc) .replace(/%%DTOC_(.+?)_(\d+)%%/g, '') if (justToc) { console.log(toc) process.exit() } if (output != '-') { console.log('Saved documentation to %s', output) await write(output, result) } else { console.log(result) } return [...Object.keys(locations), ...doc.assets] }
javascript
{ "resource": "" }
q365
createTree
train
function createTree (context, folder) { const tree = [] const files = [] let directoryContents = [] try { directoryContents = fs.readdirSync(path.join(context, folder)) } catch (error) { // Throw error if it’s not a permissions error if (error.code !== 'EACCESS') { throw error } } // Folders first directoryContents .filter(item => { return fs .lstatSync(path.join(context, folder, item)) .isDirectory() }) .forEach(item => { const children = createTree(context, path.join(folder, item)) // Don’t add current directory to tree if it has no children if (children.tree.length) { tree.push({ name: formatName(item), children: children.tree }) } files.push(...children.files) }) // Files second directoryContents .filter(item => item.endsWith('.njk')) .forEach(item => { const basename = path.basename(item, '.njk') const filePath = formatPath(folder, item) const configPath = path.join(context, folder, basename + '.json') let config try { config = JSON.parse(fs.readFileSync(configPath)) } catch (error) { config = {} } // Don’t add current component to tree if it’s hidden if (config.hidden) { return } tree.push({ name: formatName(basename), path: filePath.slice(0, -4), config }) files.push(filePath) }) return { files, tree } }
javascript
{ "resource": "" }
q366
isDomEventTarget
train
function isDomEventTarget (obj) { if (!(obj && obj.nodeName)) { return obj === window; } var nodeType = obj.nodeType; return ( nodeType === 1 || // Node.ELEMENT_NODE nodeType === 9 || // Node.DOCUMENT_NODE nodeType === 11 // Node.DOCUMENT_FRAGMENT_NODE ); }
javascript
{ "resource": "" }
q367
injectRegistry
train
function injectRegistry(entry) { const extraFiles = [registryFile, actBuildInfoFile, actMetaData]; // build also the registry if (typeof entry === 'string') { return extraFiles.concat(entry); } const transformed = {}; Object.keys(entry).forEach((eentry) => { transformed[eentry] = extraFiles.concat(entry[eentry]); }); return transformed; }
javascript
{ "resource": "" }
q368
fakeField
train
function fakeField(field) { const def = _.get(field, 'is.def') || field.def; if (!def) throw new Error( 'No field.def property to fake on! ' + JSON.stringify(field) ); switch (def.name) { case 'integer': case 'float': case 'double': case 'number': return faker.random.number(); case 'email': return faker.internet.email(); case 'url': return faker.internet.url(); case 'date': const date = faker.date.past(); date.setMilliseconds(0); return date; case 'image': return faker.image.avatar(); case 'link': case 'mongoid': let i = 24, s = ''; while (i--) s += faker.random.number(15).toString(16); return ObjectId(s); case 'boolean': return faker.random.boolean(); case 'array': return _.range(2).map(() => fakeField(field.of)); case 'object': const key = def.name === 'link' ? 'link.def.fields' : 'fields'; return _.reduce( _.get(field, key), (out, value, key) => { out[key] = fakeField(value); return out; }, {} ); // default to string default: return faker.name.lastName(); } }
javascript
{ "resource": "" }
q369
es5Fn
train
function es5Fn(fn) { let s = fn.toString(); //const name = fn.name; //if (s.startsWith('function (')) { //s = 'function ' + (name || '_fn' + nextFnName++) + ' (' + s.substring(10); /*} else */ if (!s.startsWith('function')) { s = 'function ' + s; } return s; }
javascript
{ "resource": "" }
q370
useBasicAuth
train
function useBasicAuth() { return new Promise((resolve, reject) => { if (!defaults.userToken || !defaults.masterToken) { reject(__generateFakeResponse__(0, '', {}, 'userToken or masterToken are missing for basic authentication')) } else { let details = { "token_type": "Basic", "expires_in": 0, "appName": defaults.appName, "username": "", "role": "", "firstName": "", "lastName": "", "fullName": "", "regId": 0, "userId": null }; let basicToken = 'Basic ' + createBasicToken(defaults.masterToken, defaults.userToken); utils.storage.set('user', { token: { Authorization: basicToken }, details: details }); resolve(__generateFakeResponse__(200, 'OK', {}, details, {})); } }); }
javascript
{ "resource": "" }
q371
useAccessAuth
train
function useAccessAuth() { return new Promise((resolve, reject) => { if (!defaults.accessToken) { reject(__generateFakeResponse__(0, '', {}, 'accessToken is missing for Access authentication')) } else { let details = { "token_type": "", "expires_in": 0, "appName": defaults.appName, "username": "", "role": "", "firstName": "", "lastName": "", "fullName": "", "regId": 0, "userId": null }; var aToken = defaults.accessToken.toLowerCase().startsWith('bearer') ? defaults.accessToken : 'Bearer ' + defaults.accessToken; utils.storage.set('user', { token: { Authorization: aToken, appName: defaults.appName }, details: details }); resolve(__generateFakeResponse__(200, 'OK', {}, details, {})); } }); }
javascript
{ "resource": "" }
q372
warn
train
function warn(msg) { console.log(TAG + ' ' + colors.bold.black.bgYellow('WARNING') + ' ' + msg); }
javascript
{ "resource": "" }
q373
getJsImports
train
function getJsImports(importType) { if (cache.jsImports[importType]) { return cache.jsImports[importType]; } var unprefixedImports = {}; if (cache.jsImports._unprefixedImports) { unprefixedImports = cache.jsImports._unprefixedImports; } else { var semanticUiReactPath = getPackagePath('semantic-ui-react'); if (!semanticUiReactPath) { error('Package semantic-ui-react could not be found. Install semantic-ui-react or set convertMemberImports ' + 'to false.'); } var srcDirPath = path.resolve(semanticUiReactPath, 'src'); var searchFolders = [ 'addons', 'behaviors', 'collections', 'elements', 'modules', 'views' ]; searchFolders.forEach(function (searchFolder) { var searchRoot = path.resolve(srcDirPath, searchFolder); dirTree(searchRoot, {extensions: /\.js$/}, function (item) { var basename = path.basename(item.path, '.js'); // skip files that do not start with an uppercase letter if (/[^A-Z]/.test(basename[0])) { return; } if (unprefixedImports[basename]) { error('duplicate react component name \'' + basename + '\' - probably the plugin needs an update'); } unprefixedImports[basename] = item.path.substring(srcDirPath.length).replace(/\\/g, '/'); }); }); cache.jsImports._unprefixedImports = unprefixedImports; } var prefix; if (importType === 'src') { prefix = '/src'; } else { prefix = '/dist/' + importType; } cache.jsImports[importType] = {}; for(var key in unprefixedImports) { if (unprefixedImports.hasOwnProperty(key)) { cache.jsImports[importType][key] = prefix + unprefixedImports[key]; } } return cache.jsImports[importType]; }
javascript
{ "resource": "" }
q374
isLodashPluginWithSemanticUiReact
train
function isLodashPluginWithSemanticUiReact(plugin) { if (Array.isArray(plugin)) { // Babel 6 plugin is a tuple as an array [id, options] return ( ["lodash", "babel-plugin-lodash"].includes(plugin[0].key) && [].concat(plugin[1].id).includes("semantic-ui-react") ); } else if (plugin != null && typeof plugin === "object") { // Babel 7 plugin is an object { key, options, ... } return ( /[/\\]node_modules([/\\].*)?[/\\]babel-plugin-lodash([/\\].*)?$/.test(plugin.key) && plugin.options && plugin.options.id && [].concat(plugin.options.id).includes("semantic-ui-react") ); } else { return false; } }
javascript
{ "resource": "" }
q375
train
function(adjustment, precision, captions, callback) { //precision should be one of: seconds, milliseconds, microseconds var precisionMultipliers = { "seconds": 1000000, //seconds to microseconds "milliseconds": 1000, //milliseconds to microseconds "microseconds": 1 //microseconds to microseconds }, newStartTime, newEndTime, adjuster = adjustment * precisionMultipliers[precision]; if (precisionMultipliers[precision] && captions[0].startTimeMicro !== undefined) { //quick check to see if it will zero out the 2nd or 3rd caption // there are cases where the first caption can be 00:00:00:000 and have no text. if ((captions[1].startTimeMicro + adjuster) <= 0 || (captions[2].startTimeMicro + adjuster) <= 0) { return callback("ERROR_ADJUSTMENT_ZEROS_CAPTIONS"); } captions.forEach(function(caption) { //calculate new start times... newStartTime = caption.startTimeMicro + adjuster; newEndTime = caption.endTimeMicro + adjuster; if (adjuster > 0) { caption.startTimeMicro = newStartTime; caption.endTimeMicro = newEndTime; } else if (newStartTime >= 0 && newEndTime >= 0) { caption.startTimeMicro = newStartTime; caption.endTimeMicro = newEndTime; } }); callback(undefined, captions); } else { callback('NO_CAPTIONS_OR_PRECISION_PASSED_TO_FUNCTION'); } }
javascript
{ "resource": "" }
q376
train
function(captions) { var VTT_BODY = ['WEBVTT\n']; //header captions.forEach(function(caption) { if (caption.text.length > 0 && validateText(caption.text)) { VTT_BODY.push(module.exports.formatTime(caption.startTimeMicro) + ' --> ' + module.exports.formatTime(caption.endTimeMicro)); VTT_BODY.push(module.exports.renderMacros(caption.text) + '\n'); } }); return VTT_BODY.join('\n'); }
javascript
{ "resource": "" }
q377
train
function(microseconds) { var milliseconds = microseconds / 1000; if (moment.utc(milliseconds).format("HH") > 0) { return moment.utc(milliseconds).format("HH:mm:ss.SSS"); } return moment.utc(milliseconds).format("mm:ss.SSS"); }
javascript
{ "resource": "" }
q378
loadingStateGetter
train
function loadingStateGetter() { if (Object.keys(this._syncers).length > 0) { return some(this._syncers, syncer => { return syncer.loading }) } return false }
javascript
{ "resource": "" }
q379
refreshSyncers
train
function refreshSyncers(keys) { if (typeof keys === 'string') { keys = [keys] } if (!keys) { keys = Object.keys(this._syncers) } return Promise.all(keys.map(key => { return this._syncers[key].refresh() })) }
javascript
{ "resource": "" }
q380
train
function(data) { var TTML_BODY = '', index = 0, splitText, captions = data; TTML_BODY += TTML.header.join('\n') + '\n'; captions.forEach(function(caption) { if (caption.text.length > 0 && validateText(caption.text)) { if ((/&/.test(caption.text)) && !(/&amp;/.test(caption.text))) { caption.text = caption.text.replace(/&/g, '&amp;'); } if ((/</.test(caption.text)) && !(/&lt;/.test(caption.text))) { caption.text = caption.text.replace(/</g, '&lt;'); } if ((/>/.test(caption.text)) && !(/&gt;/.test(caption.text))) { caption.text = caption.text.replace(/>/g, '&gt;'); } if (/\{break\}/.test(caption.text)) { splitText = caption.text.split('{break}'); //TODO this should count for number of breaks and add the appropriate pops where needed. for (index = 0; index < splitText.length; index++) { TTML_BODY += TTML.lineTemplate.replace('{region}', 'pop' + (index + 1)) .replace('{startTime}', module.exports.formatTime(caption.startTimeMicro)) .replace('{endTime}', module.exports.formatTime(caption.endTimeMicro)) .replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(splitText[index])))) + '\n'; } } else { TTML_BODY += TTML.lineTemplate.replace('{region}', 'pop1') .replace('{startTime}', module.exports.formatTime(caption.startTimeMicro)) .replace('{endTime}', module.exports.formatTime(caption.endTimeMicro)) .replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text)))) + '\n'; } } }); return TTML_BODY + TTML.footer.join('\n') + '\n'; }
javascript
{ "resource": "" }
q381
getRuleLink
train
function getRuleLink(ruleId) { let ruleLink = `http://eslint.org/docs/rules/${ruleId}`; if (_.startsWith(ruleId, 'angular')) { ruleId = ruleId.replace('angular/', ''); ruleLink = `https://github.com/Gillespie59/eslint-plugin-angular/blob/master/docs/${ruleId}.md`; } else if (_.startsWith(ruleId, 'lodash')) { ruleId = ruleId.replace('lodash/', ''); ruleLink = `https://github.com/wix/eslint-plugin-lodash/blob/master/docs/rules/${ruleId}.md`; } return ruleLink; }
javascript
{ "resource": "" }
q382
renderSummaryDetails
train
function renderSummaryDetails(rules, problemFiles, currDir) { let summaryDetails = '<div class="row">'; // errors exist if (rules['2']) { summaryDetails += summaryDetailsTemplate({ ruleType: 'error', topRules: renderRules(rules['2']) }); } // warnings exist if (rules['1']) { summaryDetails += summaryDetailsTemplate({ ruleType: 'warning', topRules: renderRules(rules['1']) }); } summaryDetails += '</div>'; // files with problems exist if (!_.isEmpty(problemFiles)) { summaryDetails += mostProblemsTemplate({ files: renderProblemFiles(problemFiles, currDir) }); } return summaryDetails; }
javascript
{ "resource": "" }
q383
renderIssue
train
function renderIssue(message) { return issueTemplate({ severity: severityString(message.severity), severityName: message.severity === 1 ? 'Warning' : 'Error', lineNumber: message.line, column: message.column, message: message.message, ruleId: message.ruleId, ruleLink: getRuleLink(message.ruleId) }); }
javascript
{ "resource": "" }
q384
renderSourceCode
train
function renderSourceCode(sourceCode, messages, parentIndex) { return codeWrapperTemplate({ parentIndex, sourceCode: _.map(sourceCode.split('\n'), function(code, lineNumber) { const lineMessages = _.filter(messages, {line: lineNumber + 1}), severity = _.get(lineMessages[0], 'severity') || 0; let template = ''; // checks if there is a problem on the current line and renders it if (!_.isEmpty(lineMessages)) { template += _.map(lineMessages, renderIssue).join(''); } // adds a line of code to the template (with line number and severity color if appropriate template += codeTemplate({ lineNumber: lineNumber + 1, code, severity: severityString(severity) }); return template; }).join('\n') }); }
javascript
{ "resource": "" }
q385
renderResultDetails
train
function renderResultDetails(sourceCode, messages, parentIndex) { const topIssues = messages.length < 10 ? '' : _.groupBy(messages, 'severity'); return resultDetailsTemplate({ parentIndex, sourceCode: renderSourceCode(sourceCode, messages, parentIndex), detailSummary: resultSummaryTemplate({ topIssues: renderSummaryDetails(topIssues), issues: _.map(messages, renderIssue).join('') }) }); }
javascript
{ "resource": "" }
q386
renderProblemFiles
train
function renderProblemFiles(files, currDir) { return _.map(files, function(fileDetails) { return filesTemplate({ fileId: _.camelCase(fileDetails.filePath), filePath: fileDetails.filePath.replace(currDir, ''), errorCount: fileDetails.errorCount, warningCount: fileDetails.warningCount }); }).join('\n'); }
javascript
{ "resource": "" }
q387
writeFile
train
function writeFile(filePath, fileContent, regex) { fs.writeFileSync(filePath, fileContent.replace(regex, '')); }
javascript
{ "resource": "" }
q388
getOutputDir
train
function getOutputDir() { const outputOptionIdx = process.argv.indexOf('-o') !== -1 ? process.argv.indexOf('-o') : process.argv.indexOf('--output-file'), argsLength = process.argv.length, outputDirOption = '--outputDirectory='; if (process.argv[1].includes('grunt')) { for (var i = 2; i < argsLength; i++) { if (process.argv[i].includes(outputDirOption)) { return `/${process.argv[i].replace(outputDirOption, '')}`; } } return '/reports/'; // defaults to a reports folder if nothing else is found } else if (outputOptionIdx !== -1) { return `/${process.argv[outputOptionIdx + 1].split('/')[0]}/`; } return ''; }
javascript
{ "resource": "" }
q389
buildScriptsAndStyleFiles
train
function buildScriptsAndStyleFiles(outputPath) { const stylesRegex = /<style>|<\/style>/gi, scriptsRegex = /<script type="text\/javascript">|<\/script>/gi; // creates the report directory if it doesn't exist if (!fs.existsSync(outputPath)) { fs.mkdirSync(outputPath); } // create the styles.css and main.js files writeFile(`${outputPath}styles.css`, styles(), stylesRegex); writeFile(`${outputPath}main.js`, scripts(), scriptsRegex); }
javascript
{ "resource": "" }
q390
train
function(text) { var openItalic = false, cText = [], italicStart = new RegExp(/\{italic\}/), commandBreak = new RegExp(/\{break\}/), italicEnd = new RegExp(/\{end-italic\}/), finalText = "", textArray = text.split(''), idx = 0; for (idx = 0; idx <= textArray.length; idx++) { cText.push(textArray[idx]); if (italicStart.test(cText.join('')) && openItalic === false) { // found an italic start, push to array, reset. finalText += cText.join(''); cText = []; openItalic = true; } else if (commandBreak.test(cText.join('')) && openItalic === false) { finalText += cText.join(''); cText = []; openItalic = false; } else if (commandBreak.test(cText.join('')) && openItalic === true) { finalText += cText.join('').replace(commandBreak, '{end-italic}{break}'); cText = []; openItalic = false; } else if (italicStart.test(cText.join('')) && openItalic === true) { // found an italic start within another italic...prepend an end finalText += cText.join('').replace(italicStart, ''); cText = []; openItalic = true; } else if (italicEnd.test(cText.join('')) && openItalic === true) { finalText += cText.join(''); cText = []; openItalic = false; } else if (italicEnd.test(cText.join('')) && openItalic === false) { //drop useless end italics that are out of place. finalText += cText.join('').replace(italicEnd, ''); cText = []; openItalic = false; } if (idx === text.length) { if (openItalic) { finalText += cText.join('') + '{end-italic}'; } else { finalText += cText.join(''); } cText = []; } } return finalText; }
javascript
{ "resource": "" }
q391
train
function(file, options, callback) { var lines; fs.readFile(file, options, function(err, data) { if (err) { //err return callback(err); } if (/\r\n/.test(data.toString())) { lines = data.toString().split('\r\n'); } else { lines = data.toString().split('\n'); } if (module.exports.verify(lines[0])) { callback(undefined, lines); } else { callback("INVALID_SCC_FORMAT"); } }); }
javascript
{ "resource": "" }
q392
train
function(lines) { var idx = 0; jsonCaptions = []; for (idx = 0; idx < lines.length; idx++) { if (!module.exports.verify(lines[idx])) { module.exports.translateLine(lines[idx].toLowerCase()); } } if (paintBuffer.length > 0) { rollUp(true); } if (jsonCaptions[jsonCaptions.length - 1].endTimeMicro === undefined) { jsonCaptions[jsonCaptions.length - 1].endTimeMicro = jsonCaptions[jsonCaptions.length - 1].startTimeMicro; } return jsonCaptions; }
javascript
{ "resource": "" }
q393
train
function(timeStamp) { var secondsPerStamp = 1.001, timesplit = timeStamp.split(':'), timestampSeconds = (parseInt(timesplit[0], 10) * 3600 + parseInt(timesplit[1], 10) * 60 + parseInt(timesplit[2], 10) + parseInt(timesplit[3], 10) / 30), seconds = timestampSeconds * secondsPerStamp, microSeconds = seconds * 1000 * 1000; return (microSeconds > 0) ? microSeconds : 0; }
javascript
{ "resource": "" }
q394
train
function(captions) { var SMPTE_TT_BODY = ''; // SMPTE_TT_BODY += SMPTE_TT.header.join('\n') + '\n'; captions.forEach(function(caption) { if (caption.text.length > 0 && validateText(caption.text)) { if ((/&/.test(caption.text)) && (!(/&amp;/.test(caption.text)) || !(/&gt;/.test(caption.text)) || !(/&lt;/.test(caption.text)))) { caption.text = caption.text.replace(/&/g, '&amp;'); } if ((/</.test(caption.text)) && !(/&lt;/.test(caption.text))) { caption.text = caption.text.replace(/</g, '&lt;'); } if ((/>/.test(caption.text)) && !(/&gt;/.test(caption.text))) { caption.text = caption.text.replace(/>/g, '&gt;'); } SMPTE_TT_BODY += SMPTE_TT.lineTemplate.replace('{startTime}', module.exports.formatTime(caption.startTimeMicro)) .replace('{endTime}', module.exports.formatTime(caption.endTimeMicro)) .replace('{text}', module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text)))) + '\n'; } }); return SMPTE_TT_BODY + SMPTE_TT.footer.join('\n') + '\n'; }
javascript
{ "resource": "" }
q395
extract
train
function extract(npmignore) { if (npmignore == null) { throw new Error('npmignore expects a string.'); } var lines = split(npmignore); var len = lines.length; var npmignored = false; var git = []; var npm = []; var i = 0; while (i < len) { var line = lines[i++]; if (re.test(line)) { npmignored = true; } if (npmignored) { npm.push(line); } else { git.push(line); } } return npm; }
javascript
{ "resource": "" }
q396
diff
train
function diff(arr, remove) { if (arr == null) { return []; } if (remove == null) { return arr; } var res = []; var len = arr.length; var i = 0; while (i < len) { var ele = arr[i++]; if (remove.indexOf(ele) === -1) { res.push(ele); } } return res; }
javascript
{ "resource": "" }
q397
train
function(data) { var SAMI_BODY = '', captions = data; SAMI_BODY += SAMI.header.join('\n') + '\n'; captions.forEach(function(caption) { if (caption.text === '') { caption.text = '&nbsp;'; } SAMI_BODY += SAMI.lineTemplate.replace('{startTime}', Math.floor(caption.startTimeMicro / 1000)) .replace('{text}', module.exports.renderMacros(caption.text)) + '\n'; }); return SAMI_BODY + SAMI.footer.join('\n') + '\n'; }
javascript
{ "resource": "" }
q398
train
function(captions) { var SRT_BODY = [], counter = 1; captions.forEach(function(caption) { if (caption.text.length > 0 && validateText(caption.text)) { SRT_BODY.push(counter); SRT_BODY.push(module.exports.formatTime(caption.startTimeMicro) + ' --> ' + module.exports.formatTime(caption.endTimeMicro)); SRT_BODY.push(module.exports.renderMacros(macros.fixItalics(macros.cleanMacros(caption.text))) + '\n'); counter++; } }); return SRT_BODY.join('\n'); }
javascript
{ "resource": "" }
q399
train
function(file, options, callback) { fs.readFile(file, options, function(err, data) { if (err) { return callback(err); } module.exports.parse(data.toString(), function(parseErr, lines) { if (parseErr) { return callback(parseErr); } callback(undefined, lines); }); }); }
javascript
{ "resource": "" }