_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q15500
privateBrowsing
train
function privateBrowsing(controller) { this._controller = controller; this._handler = null; /** * Menu item in the main menu to enter/leave Private Browsing mode * @private */ this._pbMenuItem = new elementslib.Elem(this._controller.menus['tools-menu'].privateBrowsingItem); this._pbTransitionItem = ...
javascript
{ "resource": "" }
q15501
privateBrowsing_start
train
function privateBrowsing_start(useShortcut) { var dialog = null; if (this.enabled) return; if (this.showPrompt) { dialog = new modalDialog.modalDialog(this._controller.window); dialog.start(this._handler); } if (useShortcut) { var cmdKey = utils.getEntity(this.getDtds(), "...
javascript
{ "resource": "" }
q15502
privateBrowsing_stop
train
function privateBrowsing_stop(useShortcut) { if (!this.enabled) return; if (useShortcut) { var privateBrowsingCmdKey = utils.getEntity(this.getDtds(), "privateBrowsingCmd.commandkey"); this._controller.keypress(null, privateBrowsingCmdKey, {accelKey: true, shiftKey: true}); } else { ...
javascript
{ "resource": "" }
q15503
privateBrowsing_waitForTransitionComplete
train
function privateBrowsing_waitForTransitionComplete(state) { // We have to wait until the transition has been finished this._controller.waitForEval("subject.hasAttribute('disabled') == false", gTimeout, 100, this._pbTransitionItem.getNode()); this._controller.waitForEval("sub...
javascript
{ "resource": "" }
q15504
create
train
function create(controller, boxes) { var doc = controller.window.document; var maxWidth = doc.documentElement.boxObject.width; var maxHeight = doc.documentElement.boxObject.height; var rect = []; for (var i = 0, j = boxes.length; i < j; ++i) { rect = boxes[i]; if (rect[0] + rect[2] > maxWidth) maxWidt...
javascript
{ "resource": "" }
q15505
_saveCanvas
train
function _saveCanvas(canvas) { // Use the path given on the command line and saved under // persisted.screenshotPath, if available. If not, use the path to the // temporary folder as a fallback. var file = null; if ("screenshotPath" in persisted) { file = Cc["@mozilla.org/file/local;1"].createInstance(Ci....
javascript
{ "resource": "" }
q15506
train
function(requestedId) { var requestedDeps = this.getNotYetLoadedTransitiveDepIds_(requestedId); return goog.array.some(failedIds, function(id) { return goog.array.contains(requestedDeps, id); }); }
javascript
{ "resource": "" }
q15507
train
function(element, options) { return Element.findChildren( element, options.only, options.tree ? true : false, options.tag); }
javascript
{ "resource": "" }
q15508
positiveSize
train
function positiveSize(e) { var rect = bot.dom.getClientRect(e); if (rect.height > 0 && rect.width > 0) { return true; } // A vertical or horizontal SVG Path element will report zero width or // height but is "shown" if it has a positive stroke-width. if (bot.dom.isElement(e, 'PATH') && (re...
javascript
{ "resource": "" }
q15509
hiddenByOverflow
train
function hiddenByOverflow(e) { return bot.dom.getOverflowState(e) == bot.dom.OverflowState.HIDDEN && goog.array.every(e.childNodes, function(n) { return !bot.dom.isElement(n) || hiddenByOverflow(n) || !positiveSize(n); }); }
javascript
{ "resource": "" }
q15510
getOverflowParent
train
function getOverflowParent(e) { var position = bot.dom.getEffectiveStyle(e, 'position'); if (position == 'fixed') { treatAsFixedPosition = true; // Fixed-position element may only overflow the viewport. return e == htmlElem ? null : htmlElem; } else { var parent = bot.dom.getParentEl...
javascript
{ "resource": "" }
q15511
getOverflowStyles
train
function getOverflowStyles(e) { // When the <html> element has an overflow style of 'visible', it assumes // the overflow style of the body, and the body is really overflow:visible. var overflowElem = e; if (htmlOverflowStyle == 'visible') { // Note: bodyElem will be null/undefined in SVG document...
javascript
{ "resource": "" }
q15512
getScroll
train
function getScroll(e) { if (e == htmlElem) { return new goog.dom.DomHelper(ownerDoc).getDocumentScroll(); } else { return new goog.math.Coordinate(e.scrollLeft, e.scrollTop); } }
javascript
{ "resource": "" }
q15513
train
function() { var obj = {}; for (var type in this.prefs_) { if (this.prefs_.hasOwnProperty(type)) { obj[type] = this.prefs_[type].name; } } return obj; }
javascript
{ "resource": "" }
q15514
unwrapNode
train
function unwrapNode(aNode) { var node = aNode; if (node) { // unwrap is not available on older branches (3.5 and 3.6) - Bug 533596 if ("unwrap" in XPCNativeWrapper) { node = XPCNativeWrapper.unwrap(node); } else if ("wrappedJSObject" in node) { node = node.wrappedJSObject; } } ...
javascript
{ "resource": "" }
q15515
DOMWalker_walk
train
function DOMWalker_walk(ids, root, waitFunction) { if (typeof waitFunction == 'function') this._controller.waitFor(waitFunction()); if (!root) root = this._controller.window.document.documentElement; var resultsArray = this._walk(root); if (typeof this._callbackResults == 'function') ...
javascript
{ "resource": "" }
q15516
DOMWalker_getNode
train
function DOMWalker_getNode(idSet) { var doc = this._controller.window.document; // QuerySelector seems to be unusuale for id's in this case: // https://developer.mozilla.org/En/Code_snippets/QuerySelector switch (idSet.getBy) { case DOMWalker.GET_BY_ID: return doc.getElementById(idSet[idS...
javascript
{ "resource": "" }
q15517
DOMWalker_prepareTargetWindows
train
function DOMWalker_prepareTargetWindows(ids) { var doc = this._controller.window.document; // Go through all the provided ids for (var i = 0; i < ids.length; i++) { var node = this._getNode(ids[i]); // Go further only, if the needed element exists if (node) { var idSet = ids[i]; ...
javascript
{ "resource": "" }
q15518
DOMWalker__walk
train
function DOMWalker__walk(root) { if (!root.childNodes) throw new Error("root.childNodes does not exist"); var collectedResults = []; for (var i = 0; i < root.childNodes.length; i++) { var nodeStatus = this._callbackFilter(root.childNodes[i]); var nodeTestResults = []; switch (nod...
javascript
{ "resource": "" }
q15519
DOMWalker_modalWindowHelper
train
function DOMWalker_modalWindowHelper(controller) { let domWalker = new DOMWalker(controller, persisted.modalInfos.callbackFilter, persisted.modalInfos.callbackNodeTest, persisted.modalInfos.callbackResults); do...
javascript
{ "resource": "" }
q15520
nodeCollector_filter
train
function nodeCollector_filter(aCallback, aThisObject) { if (!aCallback) throw new Error(arguments.callee.name + ": No callback specified"); this.nodes = Array.filter(this.nodes, aCallback, aThisObject); return this; }
javascript
{ "resource": "" }
q15521
nodeCollector_filterByDOMProperty
train
function nodeCollector_filterByDOMProperty(aProperty, aValue) { return this.filter(function(node) { if (aProperty && aValue) return node.getAttribute(aProperty) == aValue; else if (aProperty) return node.hasAttribute(aProperty); else return true; }); }
javascript
{ "resource": "" }
q15522
nodeCollector_filterByJSProperty
train
function nodeCollector_filterByJSProperty(aProperty, aValue) { return this.filter(function(node) { if (aProperty && aValue) return node.aProperty == aValue; else if (aProperty) return node.aProperty !== undefined; else return true; }); }
javascript
{ "resource": "" }
q15523
nodeCollector_queryAnonymousNodes
train
function nodeCollector_queryAnonymousNodes(aAttribute, aValue) { var node = this._document.getAnonymousElementByAttribute(this._root, aAttribute, aValue); this.nodes = node ? [node] : [ ]; ...
javascript
{ "resource": "" }
q15524
stopWithHelp
train
function stopWithHelp(...msgs) { utils.header() utils.error(...msgs) commands.help.forCommand(commands.build) utils.die() }
javascript
{ "resource": "" }
q15525
buildToStdout
train
function buildToStdout(compileOptions) { return compile(compileOptions).then(result => process.stdout.write(result.css)) }
javascript
{ "resource": "" }
q15526
buildToFile
train
function buildToFile(compileOptions, startTime) { utils.header() utils.log() utils.log(emoji.go, 'Building...', chalk.bold.cyan(compileOptions.inputFile)) return compile(compileOptions).then(result => { utils.writeFile(compileOptions.outputFile, result.css) const prettyTime = prettyHrtime(process.hrti...
javascript
{ "resource": "" }
q15527
computeControlPoint
train
function computeControlPoint(source, target, direction, offset) { const midPoint = [(source[0] + target[0]) / 2, (source[1] + target[1]) / 2]; const dx = target[0] - source[0]; const dy = target[1] - source[1]; const normal = [dy, -dx]; const length = Math.sqrt(Math.pow(normal[0], 2.0) + Math.pow(normal[1], 2...
javascript
{ "resource": "" }
q15528
layoutGraph
train
function layoutGraph(graph) { // create a map for referencing node position by node id. const nodePositionMap = graph.nodes.reduce((res, node) => { res[node.id] = node.position; return res; }, {}); // bucket edges between the same source/target node pairs. const nodePairs = graph.edges.reduce((res, ed...
javascript
{ "resource": "" }
q15529
createCanvas
train
function createCanvas(props) { let {container = document.body} = props; if (typeof container === 'string') { container = document.getElementById(container); } if (!container) { throw Error('Deck: container not found'); } // Add DOM elements const containerStyle = window.getComputedStyle(contain...
javascript
{ "resource": "" }
q15530
getGPUAggregationParams
train
function getGPUAggregationParams({boundingBox, cellSize, worldOrigin}) { const {yMin, yMax, xMin, xMax} = boundingBox; // NOTE: this alignment will match grid cell boundaries with existing CPU implementation // this gurantees identical aggregation results when switching between CPU and GPU aggregation. // Also...
javascript
{ "resource": "" }
q15531
resizeImage
train
function resizeImage(ctx, imageData, width, height) { const {naturalWidth, naturalHeight} = imageData; if (width === naturalWidth && height === naturalHeight) { return imageData; } ctx.canvas.height = height; ctx.canvas.width = width; ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); // ima...
javascript
{ "resource": "" }
q15532
buildRowMapping
train
function buildRowMapping(mapping, columns, yOffset) { for (let i = 0; i < columns.length; i++) { const {icon, xOffset} = columns[i]; const id = getIconId(icon); mapping[id] = Object.assign({}, icon, { x: xOffset, y: yOffset }); } }
javascript
{ "resource": "" }
q15533
resizeTexture
train
function resizeTexture(texture, width, height) { const oldWidth = texture.width; const oldHeight = texture.height; const oldPixels = readPixelsToBuffer(texture, {}); texture.resize({width, height}); texture.setSubImageData({ data: oldPixels, x: 0, y: height - oldHeight, width: oldWidth, ...
javascript
{ "resource": "" }
q15534
_pointsToGridHashing
train
function _pointsToGridHashing(points = [], cellSize, getPosition) { // find the geometric center of sample points let latMin = Infinity; let latMax = -Infinity; let pLat; for (const pt of points) { pLat = getPosition(pt)[1]; if (Number.isFinite(pLat)) { latMin = pLat < latMin ? pLat : latMin; ...
javascript
{ "resource": "" }
q15535
diffDataProps
train
function diffDataProps(props, oldProps) { if (oldProps === null) { return 'oldProps is null, initial diff'; } // Support optional app defined comparison of data const {dataComparator} = props; if (dataComparator) { if (!dataComparator(props.data, oldProps.data)) { return 'Data comparator detect...
javascript
{ "resource": "" }
q15536
diffUpdateTriggers
train
function diffUpdateTriggers(props, oldProps) { if (oldProps === null) { return 'oldProps is null, initial diff'; } // If the 'all' updateTrigger fires, ignore testing others if ('all' in props.updateTriggers) { const diffReason = diffUpdateTrigger(props, oldProps, 'all'); if (diffReason) { re...
javascript
{ "resource": "" }
q15537
getPropsPrototypeAndTypes
train
function getPropsPrototypeAndTypes(componentClass) { const props = getOwnProperty(componentClass, '_mergedDefaultProps'); if (props) { return { defaultProps: props, propTypes: getOwnProperty(componentClass, '_propTypes'), deprecatedProps: getOwnProperty(componentClass, '_deprecatedProps') ...
javascript
{ "resource": "" }
q15538
createPropsPrototypeAndTypes
train
function createPropsPrototypeAndTypes(componentClass) { const parent = componentClass.prototype; if (!parent) { return { defaultProps: {} }; } const parentClass = Object.getPrototypeOf(componentClass); const parentPropDefs = (parent && getPropsPrototypeAndTypes(parentClass)) || null; // Pars...
javascript
{ "resource": "" }
q15539
createPropsPrototype
train
function createPropsPrototype(props, parentProps, propTypes, componentClass) { const defaultProps = Object.create(null); Object.assign(defaultProps, parentProps, props); // Avoid freezing `id` prop const id = getComponentName(componentClass); delete props.id; // Add getters/setters for async prop propert...
javascript
{ "resource": "" }
q15540
addAsyncPropsToPropPrototype
train
function addAsyncPropsToPropPrototype(defaultProps, propTypes) { const defaultValues = {}; const descriptors = { // Default "resolved" values for async props, returned if value not yet resolved/set. _asyncPropDefaultValues: { enumerable: false, value: defaultValues }, // Shadowed object...
javascript
{ "resource": "" }
q15541
wrapInView
train
function wrapInView(node) { if (!node) { return node; } if (typeof node === 'function') { // React.Children does not traverse functions. // All render callbacks must be protected under a <View> return createElement(View, {}, node); } if (Array.isArray(node)) { return node.map(wrapInView); ...
javascript
{ "resource": "" }
q15542
setTextStyle
train
function setTextStyle(ctx, fontSize) { ctx.font = `${fontSize}px Helvetica,Arial,sans-serif`; ctx.fillStyle = '#000'; ctx.textBaseline = 'top'; ctx.textAlign = 'center'; }
javascript
{ "resource": "" }
q15543
time
train
function time(priority, label) { assert(Number.isFinite(priority), 'log priority must be a number'); if (priority <= log.priority) { // In case the platform doesn't have console.time if (console.time) { console.time(label); } else { console.info(label); } } }
javascript
{ "resource": "" }
q15544
checkForAssertionErrors
train
function checkForAssertionErrors(args) { const isAssertion = args && args.length > 0 && typeof args[0] === 'object' && args[0] !== null && args[0].name === 'AssertionError'; if (isAssertion) { args = Array.prototype.slice.call(args); args.unshift(`assert(${args[0].message})`); } ret...
javascript
{ "resource": "" }
q15545
isNestedRingClosed
train
function isNestedRingClosed(simplePolygon) { // check if first and last vertex are the same const p0 = simplePolygon[0]; const p1 = simplePolygon[simplePolygon.length - 1]; return p0[0] === p1[0] && p0[1] === p1[1] && p0[2] === p1[2]; }
javascript
{ "resource": "" }
q15546
isFlatRingClosed
train
function isFlatRingClosed(positions, size, startIndex, endIndex) { for (let i = 0; i < size; i++) { if (positions[startIndex + i] !== positions[endIndex - size + i]) { return false; } } return true; }
javascript
{ "resource": "" }
q15547
copyNestedRing
train
function copyNestedRing(target, targetStartIndex, simplePolygon, size) { let targetIndex = targetStartIndex; const len = simplePolygon.length; for (let i = 0; i < len; i++) { for (let j = 0; j < size; j++) { target[targetIndex++] = simplePolygon[i][j] || 0; } } if (!isNestedRingClosed(simplePol...
javascript
{ "resource": "" }
q15548
copyFlatRing
train
function copyFlatRing(target, targetStartIndex, positions, size, srcStartIndex = 0, srcEndIndex) { srcEndIndex = srcEndIndex || positions.length; const srcLength = srcEndIndex - srcStartIndex; if (srcLength <= 0) { return targetStartIndex; } let targetIndex = targetStartIndex; for (let i = 0; i < srcLe...
javascript
{ "resource": "" }
q15549
getFlatVertexCount
train
function getFlatVertexCount(positions, size, startIndex = 0, endIndex) { endIndex = endIndex || positions.length; if (startIndex >= endIndex) { return 0; } return ( (isFlatRingClosed(positions, size, startIndex, endIndex) ? 0 : 1) + (endIndex - startIndex) / size ); }
javascript
{ "resource": "" }
q15550
activateWidgetExtension
train
function activateWidgetExtension(app, registry) { registry.registerWidget({ name: MODULE_NAME, version: MODULE_VERSION, exports: { DeckGLModel, DeckGLView } }); }
javascript
{ "resource": "" }
q15551
getNewChars
train
function getNewChars(key, characterSet) { const cachedFontAtlas = cache.get(key); if (!cachedFontAtlas) { return characterSet; } const newChars = []; const cachedMapping = cachedFontAtlas.mapping; let cachedCharSet = Object.keys(cachedMapping); cachedCharSet = new Set(cachedCharSet); let charSet =...
javascript
{ "resource": "" }
q15552
handleMouseEvent
train
function handleMouseEvent(deck, type, event) { let callback; switch (type) { case 'click': // Hack: because we do not listen to pointer down, perform picking now deck._lastPointerDownInfo = deck.pickObject({ x: event.pixel.x, y: event.pixel.y }); callback = deck._onEvent;...
javascript
{ "resource": "" }
q15553
getLevelFromToken
train
function getLevelFromToken(token) { // leaf level token size is 16. Each 2 bit add a level const lastHex = token.substr(token.length - 1); // a) token = trailing-zero trimmed hex id // b) 64 bit hex id - 3 face bit + 60 bits for 30 levels + 1 bit lsb marker const level = 2 * (token.length - 1) - ((lastHex & 1...
javascript
{ "resource": "" }
q15554
flattenArray
train
function flattenArray(array, filter, map, result) { let index = -1; while (++index < array.length) { const value = array[index]; if (Array.isArray(value)) { flattenArray(value, filter, map, result); } else if (filter(value)) { result.push(map(value)); } } return result; }
javascript
{ "resource": "" }
q15555
sayHello
train
function sayHello(call, callback) { var reply = new messages.HelloReply(); reply.setMessage('Hello ' + call.request.getName()); callback(null, reply); }
javascript
{ "resource": "" }
q15556
NetProfiler
train
function NetProfiler (options = {}) { if (!(this instanceof NetProfiler)) return new NetProfiler(options) if (!options.net) { options.net = require('net') } this.net = options.net this.proxies = {} this.activeConnections = [] this.startTs = new Date() / 1000 this.tickMs = options.tickMs || 1000 ...
javascript
{ "resource": "" }
q15557
formErrorText
train
function formErrorText (info, msg) { const hr = '----------' return addPlatformInformation(info) .then((obj) => { const formatted = [] function add (msg) { formatted.push( stripIndents(msg) ) } add(` ${obj.description} ${obj.solution} `) if (msg) { ...
javascript
{ "resource": "" }
q15558
unknownOption
train
function unknownOption (flag, type = 'option') { if (this._allowUnknownOption) return logger.error() logger.error(` error: unknown ${type}:`, flag) logger.error() this.outputHelp() util.exit(1) }
javascript
{ "resource": "" }
q15559
applyResource
train
function applyResource(resource, isMethod) { let root; let parent; let currentPath; const path = resource.path.replace(/^\//, '').replace(/\/$/, ''); const pathParts = path.split('/'); function applyNodeResource(node, parts, index) { const n = node; if (index === par...
javascript
{ "resource": "" }
q15560
isValidProject
train
function isValidProject(project) { const isValid = VALID_TRACKING_PROJECTS.indexOf(project) !== -1; if (!isValid) { console.log(chalk.red('Tracking Error:')); console.log(`"${project}" is invalid project. Must be one of`, VALID_TRACKING_PROJECTS); } return isValid; }
javascript
{ "resource": "" }
q15561
isValidObject
train
function isValidObject(key) { const isValid = VALID_TRACKING_OBJECTS.indexOf(key) !== -1; if (!isValid) { console.log(chalk.red('Tracking Error:')); console.log(`"${key}" is invalid tracking object. Must be one of`, VALID_TRACKING_OBJECTS); } return isValid; }
javascript
{ "resource": "" }
q15562
getPathDirectory
train
function getPathDirectory(length, parts) { if (!parts) { return ''; } return parts .slice(length) .filter(part => part !== '') .join(path.sep); }
javascript
{ "resource": "" }
q15563
parseRepoURL
train
function parseRepoURL(inputUrl) { if (!inputUrl) { throw new ServerlessError('URL is required'); } const url = URL.parse(inputUrl.replace(/\/$/, '')); // check if url parameter is a valid url if (!url.host) { throw new ServerlessError('The URL you passed is not a valid URL'); } switch (url.host...
javascript
{ "resource": "" }
q15564
set
train
function set(key, value) { let config = getGlobalConfig(); if (key && typeof key === 'string' && typeof value !== 'undefined') { config = _.set(config, key, value); } else if (_.isObject(key)) { config = _.merge(config, key); } else if (typeof value !== 'undefined') { config = _.merge(config, value)...
javascript
{ "resource": "" }
q15565
findReferences
train
function findReferences(root, value) { const visitedObjects = []; const resourcePaths = []; const stack = [{ propValue: root, path: '' }]; while (!_.isEmpty(stack)) { const property = stack.pop(); _.forOwn(property.propValue, (propValue, key) => { let propKey; if (_.isArray(property.propVa...
javascript
{ "resource": "" }
q15566
param
train
function param(err) { if (err) { return done(err); } if (i >= keys.length ) { return done(); } paramIndex = 0; key = keys[i++]; name = key.name; paramVal = req.params[name]; paramCallbacks = params[name]; paramCalled = called[name]; if (paramVal === undefined |...
javascript
{ "resource": "" }
q15567
appendMethods
train
function appendMethods(list, addition) { for (var i = 0; i < addition.length; i++) { var method = addition[i]; if (list.indexOf(method) === -1) { list.push(method); } } }
javascript
{ "resource": "" }
q15568
getProtohost
train
function getProtohost(url) { if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { return undefined } var searchIndex = url.indexOf('?') var pathLength = searchIndex !== -1 ? searchIndex : url.length var fqdnIndex = url.substr(0, pathLength).indexOf('://') return fqdnIndex !== -...
javascript
{ "resource": "" }
q15569
gettype
train
function gettype(obj) { var type = typeof obj; if (type !== 'object') { return type; } // inspect [[Class]] for objects return toString.call(obj) .replace(objectRegExp, '$1'); }
javascript
{ "resource": "" }
q15570
sendOptionsResponse
train
function sendOptionsResponse(res, options, next) { try { var body = options.join(','); res.set('Allow', body); res.send(body); } catch (err) { next(err); } }
javascript
{ "resource": "" }
q15571
wrap
train
function wrap(old, fn) { return function proxy() { var args = new Array(arguments.length + 1); args[0] = old; for (var i = 0, len = arguments.length; i < len; i++) { args[i + 1] = arguments[i]; } fn.apply(this, args); }; }
javascript
{ "resource": "" }
q15572
tryRender
train
function tryRender(view, options, callback) { try { view.render(options, callback); } catch (err) { callback(err); } }
javascript
{ "resource": "" }
q15573
authenticate
train
function authenticate(name, pass, fn) { if (!module.parent) console.log('authenticating %s:%s', name, pass); var user = users[name]; // query the db for the given username if (!user) return fn(new Error('cannot find user')); // apply the same algorithm to the POSTed password, applying // the hash against th...
javascript
{ "resource": "" }
q15574
sendfile
train
function sendfile(res, file, options, callback) { var done = false; var streaming; // request aborted function onaborted() { if (done) return; done = true; var err = new Error('Request aborted'); err.code = 'ECONNABORTED'; callback(err); } // directory function ondirectory() { i...
javascript
{ "resource": "" }
q15575
stringify
train
function stringify (value, replacer, spaces, escape) { // v8 checks arguments.length for optimizing simple call // https://bugs.chromium.org/p/v8/issues/detail?id=4730 var json = replacer || spaces ? JSON.stringify(value, replacer, spaces) : JSON.stringify(value); if (escape) { json = json.replace(...
javascript
{ "resource": "" }
q15576
createError
train
function createError(status, message) { var err = new Error(message); err.status = status; return err; }
javascript
{ "resource": "" }
q15577
View
train
function View(name, options) { var opts = options || {}; this.defaultEngine = opts.defaultEngine; this.ext = extname(name); this.name = name; this.root = opts.root; if (!this.ext && !this.defaultEngine) { throw new Error('No default engine was specified and no extension was provided.'); } var fil...
javascript
{ "resource": "" }
q15578
GithubView
train
function GithubView(name, options){ this.name = name; options = options || {}; this.engine = options.engines[extname(name)]; // "root" is the app.set('views') setting, however // in your own implementation you could ignore this this.path = '/' + options.root + '/master/' + name; }
javascript
{ "resource": "" }
q15579
count
train
function count(req, res, next) { User.count(function(err, count){ if (err) return next(err); req.count = count; next(); }) }
javascript
{ "resource": "" }
q15580
count2
train
function count2(req, res, next) { User.count(function(err, count){ if (err) return next(err); res.locals.count = count; next(); }) }
javascript
{ "resource": "" }
q15581
createETagGenerator
train
function createETagGenerator (options) { return function generateETag (body, encoding) { var buf = !Buffer.isBuffer(body) ? Buffer.from(body, encoding) : body return etag(buf, options) } }
javascript
{ "resource": "" }
q15582
train
async function () { // while the array of all exchanges is not empty while (exchanges.length > 0) { // pop one exchange from the array const exchange = exchanges.pop () // check if it has the necessary method implemented if (exchange.has['fetchTickers']...
javascript
{ "resource": "" }
q15583
filterFiles
train
function filterFiles (filters) { return (files, metalsmith, done) => { filter(files, filters, metalsmith.metadata(), done) } }
javascript
{ "resource": "" }
q15584
logMessage
train
function logMessage (message, data) { if (!message) return render(message, data, (err, res) => { if (err) { console.error('\n Error when rendering template complete message: ' + err.message.trim()) } else { console.log('\n' + res.split(/\r?\n/g).map(line => ' ' + line).join('\n')) } ...
javascript
{ "resource": "" }
q15585
cleanArgs
train
function cleanArgs (cmd) { const args = {} cmd.options.forEach(o => { const key = camelize(o.long.replace(/^--/, '')) // if an option is not present and Command has a method with the same name // it should not be copied if (typeof cmd[key] !== 'function' && typeof cmd[key] !== 'undefined') { a...
javascript
{ "resource": "" }
q15586
mayProxy
train
function mayProxy (pathname) { const maybePublicPath = path.resolve(appPublicFolder, pathname.slice(1)) return !fs.existsSync(maybePublicPath) }
javascript
{ "resource": "" }
q15587
autoOpenLastProject
train
async function autoOpenLastProject () { const context = getContext() const id = context.db.get('config.lastOpenProject').value() if (id) { try { await open(id, context) } catch (e) { log(`Project can't be auto-opened`, id) } } }
javascript
{ "resource": "" }
q15588
getDefaultValue
train
function getDefaultValue (rule, data) { const { category: ruleCategory } = rule.meta.docs const currentCategory = getEslintConfigName(data.eslint) if (!currentCategory || ruleCategory === undefined) return RULE_SETTING_OFF return CATEGORIES.indexOf(ruleCategory) <= CATEGORIES.indexOf(currentCategory.split('/'...
javascript
{ "resource": "" }
q15589
getModulePath
train
function getModulePath (mod, useAbsolutePath) { const modPath = mod === 'regenerator-runtime' ? 'regenerator-runtime/runtime' : `core-js/modules/${mod}` return useAbsolutePath ? require.resolve(modPath) : modPath }
javascript
{ "resource": "" }
q15590
convertRules
train
function convertRules (config) { const result = {} const eslintRules = new CLIEngine({ useEslintrc: false, baseConfig: { extends: [require.resolve(`@vue/eslint-config-${config}`)] } }).getConfigForFile().rules const getRuleOptions = (ruleName, defaultOptions = []) => { const ruleConfig =...
javascript
{ "resource": "" }
q15591
train
function( block, linesToHighlight ) { linesToHighlight = linesToHighlight || block.getAttribute( 'data-line-numbers' ); if( typeof linesToHighlight === 'string' && linesToHighlight !== '' ) { linesToHighlight.split( ',' ).forEach( function( lineNumbers ) { // Avoid failures becase of whitespace ...
javascript
{ "resource": "" }
q15592
post
train
function post() { var slideElement = Reveal.getCurrentSlide(), notesElement = slideElement.querySelector( 'aside.notes' ); var messageData = { notes: '', markdown: false, socketId: socketId, state: Reveal.getState() }; // Look for notes defined in a slide attribute if( slideElement.hasAttrib...
javascript
{ "resource": "" }
q15593
train
function() { var me = this; var tickFont; if (me.isHorizontal()) { return Math.ceil(me.width / 40); } tickFont = helpers.options._parseFont(me.options.ticks); return Math.ceil(me.height / tickFont.lineHeight); }
javascript
{ "resource": "" }
q15594
train
function(last) { var me = this; var chart = me.chart; var scale = me._getIndexScale(); var stacked = scale.options.stacked; var ilen = last === undefined ? chart.data.datasets.length : last + 1; var stacks = []; var i, meta; for (i = 0; i < ilen; ++i) { meta = chart.getDatasetMeta(i); if (meta.ba...
javascript
{ "resource": "" }
q15595
train
function(datasetIndex, name) { var stacks = this._getStacks(datasetIndex); var index = (name !== undefined) ? stacks.indexOf(name) : -1; // indexOf returns -1 if element is not present return (index === -1) ? stacks.length - 1 : index; }
javascript
{ "resource": "" }
q15596
toFontString
train
function toFontString(font) { if (!font || helpers.isNullOrUndef(font.size) || helpers.isNullOrUndef(font.family)) { return null; } return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family; }
javascript
{ "resource": "" }
q15597
train
function(elements, eventPosition) { var x = eventPosition.x; var y = eventPosition.y; var minDistance = Number.POSITIVE_INFINITY; var i, len, nearestElement; for (i = 0, len = elements.length; i < len; ++i) { var el = elements[i]; if (el && el.hasValue()) { var center = el.getCenterPoint(); var...
javascript
{ "resource": "" }
q15598
pushOrConcat
train
function pushOrConcat(base, toPush) { if (toPush) { if (helpers.isArray(toPush)) { // base = base.concat(toPush); Array.prototype.push.apply(base, toPush); } else { base.push(toPush); } } return base; }
javascript
{ "resource": "" }
q15599
splitNewlines
train
function splitNewlines(str) { if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) { return str.split('\n'); } return str; }
javascript
{ "resource": "" }