_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q15900
train
function (str) { var strlen = str.length; if (this.html.substr(this.currentChar, strlen).toLowerCase() === str.toLowerCase()) { this.currentChar += strlen; return true; } return false; }
javascript
{ "resource": "" }
q15901
train
function (str) { var index = this.html.indexOf(str, this.currentChar) + str.length; if (index === -1) this.currentChar = this.html.length; this.currentChar = index; }
javascript
{ "resource": "" }
q15902
train
function () { var c = this.nextChar(); if (c === undefined) return null; // Read any text as Text node if (c !== "<") { --this.currentChar; var textNode = new Text(); var n = this.html.indexOf("<", this.currentChar); if (n === -1) { textNode.innerHTML = this.html.substring(this.currentChar, this.html.length); this.currentChar = this.html.length; } else { textNode.innerHTML = this.html.substring(this.currentChar, n); this.currentChar = n; } return textNode; } c = this.peekNext(); // Read Comment node. Normally, Comment nodes know their inner // textContent, but we don't really care about Comment nodes (we throw // them away in readChildren()). So just returning an empty Comment node // here is sufficient. if (c === "!" || c === "?") { // We're still before the ! or ? that is starting this comment: this.currentChar++; return this.discardNextComment(); } // If we're reading a closing tag, return null. This means we've reached // the end of this set of child nodes. if (c === "/") { --this.currentChar; return null; } // Otherwise, we're looking at an Element node var result = this.makeElementNode(this.retPair); if (!result) return null; var node = this.retPair[0]; var closed = this.retPair[1]; var localName = node.localName; // If this isn't a void Element, read its child nodes if (!closed) { this.readChildren(node); var closingTag = "</" + localName + ">"; if (!this.match(closingTag)) { this.error("expected '" + closingTag + "' and got " + this.html.substr(this.currentChar, closingTag.length)); return null; } } // Only use the first title, because SVG might have other // title elements which we don't care about (medium.com // does this, at least). if (localName === "title" && !this.doc.title) { this.doc.title = node.textContent.trim(); } else if (localName === "head") { this.doc.head = node; } else if (localName === "body") { this.doc.body = node; } else if (localName === "html") { this.doc.documentElement = node; } return node; }
javascript
{ "resource": "" }
q15903
train
function (html, url) { this.html = html; var doc = this.doc = new Document(url); this.readChildren(doc); // If this is an HTML document, remove root-level children except for the // <html> node if (doc.documentElement) { for (var i = doc.childNodes.length; --i >= 0;) { var child = doc.childNodes[i]; if (child !== doc.documentElement) { doc.removeChild(child); } } } return doc; }
javascript
{ "resource": "" }
q15904
envFromArgs
train
function envFromArgs(args) { if (!args) return 'prod'; const envIndex = args.indexOf('--env'); const devIndex = args.indexOf('dev'); if (envIndex === devIndex - 1) return 'dev'; return 'prod'; }
javascript
{ "resource": "" }
q15905
profileFromArgs
train
function profileFromArgs(args) { if (!args) return null; const profileIndex = args.indexOf('--profile'); if (profileIndex <= 0 || profileIndex >= args.length - 1) return null; const profileValue = args[profileIndex + 1]; return profileValue ? profileValue : null; }
javascript
{ "resource": "" }
q15906
train
function(lines) { let output = []; let newlineCount = 0; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (!line.trim()) { newlineCount++; } else { newlineCount = 0; } if (newlineCount >= 2) continue; output.push(line); } return output; }
javascript
{ "resource": "" }
q15907
handleItemDelete
train
function handleItemDelete(state, action) { let newState = Object.assign({}, state); const map = { 'FOLDER_DELETE': ['folders', 'selectedFolderId'], 'NOTE_DELETE': ['notes', 'selectedNoteIds'], 'TAG_DELETE': ['tags', 'selectedTagId'], 'SEARCH_DELETE': ['searches', 'selectedSearchId'], }; const listKey = map[action.type][0]; const selectedItemKey = map[action.type][1]; let previousIndex = 0; let newItems = []; const items = state[listKey]; for (let i = 0; i < items.length; i++) { let item = items[i]; if (item.id == action.id) { previousIndex = i; continue; } newItems.push(item); } newState = Object.assign({}, state); newState[listKey] = newItems; if (previousIndex >= newItems.length) { previousIndex = newItems.length - 1; } const newId = previousIndex >= 0 ? newItems[previousIndex].id : null; newState[selectedItemKey] = action.type === 'NOTE_DELETE' ? [newId] : newId; if (!newId && newState.notesParentType !== 'Folder') { newState.notesParentType = 'Folder'; } return newState; }
javascript
{ "resource": "" }
q15908
train
function(nodeList, filterFn) { for (var i = nodeList.length - 1; i >= 0; i--) { var node = nodeList[i]; var parentNode = node.parentNode; if (parentNode) { if (!filterFn || filterFn.call(this, node, i, nodeList)) { parentNode.removeChild(node); } } } }
javascript
{ "resource": "" }
q15909
train
function(nodeList, newTagName) { for (var i = nodeList.length - 1; i >= 0; i--) { var node = nodeList[i]; this._setNodeTag(node, newTagName); } }
javascript
{ "resource": "" }
q15910
train
function() { var slice = Array.prototype.slice; var args = slice.call(arguments); var nodeLists = args.map(function(list) { return slice.call(list); }); return Array.prototype.concat.apply([], nodeLists); }
javascript
{ "resource": "" }
q15911
train
function(node) { var classesToPreserve = this._classesToPreserve; var className = (node.getAttribute("class") || "") .split(/\s+/) .filter(function(cls) { return classesToPreserve.indexOf(cls) != -1; }) .join(" "); if (className) { node.setAttribute("class", className); } else { node.removeAttribute("class"); } for (node = node.firstElementChild; node; node = node.nextElementSibling) { this._cleanClasses(node); } }
javascript
{ "resource": "" }
q15912
train
function() { var doc = this._doc; // Remove all style tags in head this._removeNodes(doc.getElementsByTagName("style")); if (doc.body) { this._replaceBrs(doc.body); } this._replaceNodeTags(doc.getElementsByTagName("font"), "SPAN"); }
javascript
{ "resource": "" }
q15913
train
function (node) { var next = node; while (next && (next.nodeType != this.ELEMENT_NODE) && this.REGEXPS.whitespace.test(next.textContent)) { next = next.nextSibling; } return next; }
javascript
{ "resource": "" }
q15914
train
function(byline) { if (typeof byline == 'string' || byline instanceof String) { byline = byline.trim(); return (byline.length > 0) && (byline.length < 100); } return false; }
javascript
{ "resource": "" }
q15915
train
function() { var metadata = {}; var values = {}; var metaElements = this._doc.getElementsByTagName("meta"); // Match "description", or Twitter's "twitter:description" (Cards) // in name attribute. var namePattern = /^\s*((twitter)\s*:\s*)?(description|title)\s*$/gi; // Match Facebook's Open Graph title & description properties. var propertyPattern = /^\s*og\s*:\s*(description|title)\s*$/gi; // Find description tags. this._forEachNode(metaElements, function(element) { var elementName = element.getAttribute("name"); var elementProperty = element.getAttribute("property"); if ([elementName, elementProperty].indexOf("author") !== -1) { metadata.byline = element.getAttribute("content"); return; } var name = null; if (namePattern.test(elementName)) { name = elementName; } else if (propertyPattern.test(elementProperty)) { name = elementProperty; } if (name) { var content = element.getAttribute("content"); if (content) { // Convert to lowercase and remove any whitespace // so we can match below. name = name.toLowerCase().replace(/\s/g, ''); values[name] = content.trim(); } } }); if ("description" in values) { metadata.excerpt = values["description"]; } else if ("og:description" in values) { // Use facebook open graph description. metadata.excerpt = values["og:description"]; } else if ("twitter:description" in values) { // Use twitter cards description. metadata.excerpt = values["twitter:description"]; } metadata.title = this._getArticleTitle(); if (!metadata.title) { if ("og:title" in values) { // Use facebook open graph title. metadata.title = values["og:title"]; } else if ("twitter:title" in values) { // Use twitter cards title. metadata.title = values["twitter:title"]; } } return metadata; }
javascript
{ "resource": "" }
q15916
train
function(doc) { this._removeNodes(doc.getElementsByTagName('script'), function(scriptNode) { scriptNode.nodeValue = ""; scriptNode.removeAttribute('src'); return true; }); this._removeNodes(doc.getElementsByTagName('noscript')); }
javascript
{ "resource": "" }
q15917
train
function(element) { // There should be exactly 1 element child which is a P: if (element.children.length != 1 || element.children[0].tagName !== "P") { return false; } // And there should be no text nodes with real content return !this._someNode(element.childNodes, function(node) { return node.nodeType === this.TEXT_NODE && this.REGEXPS.hasContent.test(node.textContent); }); }
javascript
{ "resource": "" }
q15918
train
function (element) { return this._someNode(element.childNodes, function(node) { return this.DIV_TO_P_ELEMS.indexOf(node.tagName) !== -1 || this._hasChildBlockElement(node); }); }
javascript
{ "resource": "" }
q15919
train
function(e, normalizeSpaces) { normalizeSpaces = (typeof normalizeSpaces === 'undefined') ? true : normalizeSpaces; var textContent = e.textContent.trim(); if (normalizeSpaces) { return textContent.replace(this.REGEXPS.normalize, " "); } return textContent; }
javascript
{ "resource": "" }
q15920
train
function(node, tagName, maxDepth, filterFn) { maxDepth = maxDepth || 3; tagName = tagName.toUpperCase(); var depth = 0; while (node.parentNode) { if (maxDepth > 0 && depth > maxDepth) return false; if (node.parentNode.tagName === tagName && (!filterFn || filterFn(node.parentNode))) return true; node = node.parentNode; depth++; } return false; }
javascript
{ "resource": "" }
q15921
train
function(table) { var rows = 0; var columns = 0; var trs = table.getElementsByTagName("tr"); for (var i = 0; i < trs.length; i++) { var rowspan = trs[i].getAttribute("rowspan") || 0; if (rowspan) { rowspan = parseInt(rowspan, 10); } rows += (rowspan || 1); // Now look for column-related info var columnsInThisRow = 0; var cells = trs[i].getElementsByTagName("td"); for (var j = 0; j < cells.length; j++) { var colspan = cells[j].getAttribute("colspan") || 0; if (colspan) { colspan = parseInt(colspan, 10); } columnsInThisRow += (colspan || 1); } columns = Math.max(columns, columnsInThisRow); } return {rows: rows, columns: columns}; }
javascript
{ "resource": "" }
q15922
train
function(helperIsVisible) { var nodes = this._getAllNodesWithTag(this._doc, ["p", "pre"]); // Get <div> nodes which have <br> node(s) and append them into the `nodes` variable. // Some articles' DOM structures might look like // <div> // Sentences<br> // <br> // Sentences<br> // </div> var brNodes = this._getAllNodesWithTag(this._doc, ["div > br"]); if (brNodes.length) { var set = new Set(); [].forEach.call(brNodes, function(node) { set.add(node.parentNode); }); nodes = [].concat.apply(Array.from(set), nodes); } // FIXME we should have a fallback for helperIsVisible, but this is // problematic because of jsdom's elem.style handling - see // https://github.com/mozilla/readability/pull/186 for context. var score = 0; // This is a little cheeky, we use the accumulator 'score' to decide what to return from // this callback: return this._someNode(nodes, function(node) { if (helperIsVisible && !helperIsVisible(node)) return false; var matchString = node.className + " " + node.id; if (this.REGEXPS.unlikelyCandidates.test(matchString) && !this.REGEXPS.okMaybeItsACandidate.test(matchString)) { return false; } if (node.matches && node.matches("li p")) { return false; } var textContentLength = node.textContent.trim().length; if (textContentLength < 140) { return false; } score += Math.sqrt(textContentLength - 140); if (score > 20) { return true; } return false; }); }
javascript
{ "resource": "" }
q15923
train
function () { // Avoid parsing too large documents, as per configuration option if (this._maxElemsToParse > 0) { var numTags = this._doc.getElementsByTagName("*").length; if (numTags > this._maxElemsToParse) { throw new Error("Aborting parsing document; " + numTags + " elements found"); } } if (typeof this._doc.documentElement.firstElementChild === "undefined") { this._getNextNode = this._getNextNodeNoElementProperties; } // Remove script tags from the document. this._removeScripts(this._doc); this._prepDocument(); var metadata = this._getArticleMetadata(); this._articleTitle = metadata.title; var articleContent = this._grabArticle(); if (!articleContent) return null; this.log("Grabbed: " + articleContent.innerHTML); this._postProcessContent(articleContent); // If we haven't found an excerpt in the article's metadata, use the article's // first paragraph as the excerpt. This is used for displaying a preview of // the article's content. if (!metadata.excerpt) { var paragraphs = articleContent.getElementsByTagName("p"); if (paragraphs.length > 0) { metadata.excerpt = paragraphs[0].textContent.trim(); } } var textContent = articleContent.textContent; return { title: this._articleTitle, byline: metadata.byline || this._articleByline, dir: this._articleDir, content: articleContent.innerHTML, textContent: textContent, length: textContent.length, excerpt: metadata.excerpt, }; }
javascript
{ "resource": "" }
q15924
basicDelta
train
async function basicDelta(path, getDirStatFn, options) { const outputLimit = 50; const itemIds = await options.allItemIdsHandler(); if (!Array.isArray(itemIds)) throw new Error('Delta API not supported - local IDs must be provided'); const context = basicDeltaContextFromOptions_(options); let newContext = { timestamp: context.timestamp, filesAtTimestamp: context.filesAtTimestamp.slice(), statsCache: context.statsCache, statIdsCache: context.statIdsCache, deletedItemsProcessed: context.deletedItemsProcessed, }; // Stats are cached until all items have been processed (until hasMore is false) if (newContext.statsCache === null) { newContext.statsCache = await getDirStatFn(path); newContext.statsCache.sort(function(a, b) { return a.updated_time - b.updated_time; }); newContext.statIdsCache = newContext.statsCache .filter(item => BaseItem.isSystemPath(item.path)) .map(item => BaseItem.pathToId(item.path)); newContext.statIdsCache.sort(); // Items must be sorted to use binary search below } let output = []; // Find out which files have been changed since the last time. Note that we keep // both the timestamp of the most recent change, *and* the items that exactly match // this timestamp. This to handle cases where an item is modified while this delta // function is running. For example: // t0: Item 1 is changed // t0: Sync items - run delta function // t0: While delta() is running, modify Item 2 // Since item 2 was modified within the same millisecond, it would be skipped in the // next sync if we relied exclusively on a timestamp. for (let i = 0; i < newContext.statsCache.length; i++) { const stat = newContext.statsCache[i]; if (stat.isDir) continue; if (stat.updated_time < context.timestamp) continue; // Special case for items that exactly match the timestamp if (stat.updated_time === context.timestamp) { if (context.filesAtTimestamp.indexOf(stat.path) >= 0) continue; } if (stat.updated_time > newContext.timestamp) { newContext.timestamp = stat.updated_time; newContext.filesAtTimestamp = []; } newContext.filesAtTimestamp.push(stat.path); output.push(stat); if (output.length >= outputLimit) break; } if (!newContext.deletedItemsProcessed) { // Find out which items have been deleted on the sync target by comparing the items // we have to the items on the target. // Note that when deleted items are processed it might result in the output having // more items than outputLimit. This is acceptable since delete operations are cheap. let deletedItems = []; for (let i = 0; i < itemIds.length; i++) { const itemId = itemIds[i]; if (ArrayUtils.binarySearch(newContext.statIdsCache, itemId) < 0) { deletedItems.push({ path: BaseItem.systemPath(itemId), isDeleted: true, }); } } output = output.concat(deletedItems); } newContext.deletedItemsProcessed = true; const hasMore = output.length >= outputLimit; if (!hasMore) { // Clear temporary info from context. It's especially important to remove deletedItemsProcessed // so that they are processed again on the next sync. newContext.statsCache = null; newContext.statIdsCache = null; delete newContext.deletedItemsProcessed; } return { hasMore: hasMore, context: newContext, items: output, }; }
javascript
{ "resource": "" }
q15925
train
function(target) { var setFn = function(value, key) { target[key] = value; }; for (var i = 1, ilen = arguments.length; i < ilen; ++i) { helpers.each(arguments[i], setFn); } return target; }
javascript
{ "resource": "" }
q15926
train
function(point, area) { var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error. return point.x > area.left - epsilon && point.x < area.right + epsilon && point.y > area.top - epsilon && point.y < area.bottom + epsilon; }
javascript
{ "resource": "" }
q15927
train
function(options) { var globalDefaults = core_defaults.global; var size = valueOrDefault(options.fontSize, globalDefaults.defaultFontSize); var font = { family: valueOrDefault(options.fontFamily, globalDefaults.defaultFontFamily), lineHeight: helpers_core.options.toLineHeight(valueOrDefault(options.lineHeight, globalDefaults.defaultLineHeight), size), size: size, style: valueOrDefault(options.fontStyle, globalDefaults.defaultFontStyle), weight: null, string: '' }; font.string = toFontString(font); return font; }
javascript
{ "resource": "" }
q15928
train
function(inputs, context, index) { var i, ilen, value; for (i = 0, ilen = inputs.length; i < ilen; ++i) { value = inputs[i]; if (value === undefined) { continue; } if (context !== undefined && typeof value === 'function') { value = value(context); } if (index !== undefined && helpers_core.isArray(value)) { value = value[index]; } if (value !== undefined) { return value; } } }
javascript
{ "resource": "" }
q15929
getRelativePosition
train
function getRelativePosition(e, chart) { if (e.native) { return { x: e.x, y: e.y }; } return helpers$1.getRelativePosition(e, chart); }
javascript
{ "resource": "" }
q15930
fitBox
train
function fitBox(box) { var minBoxSize = helpers$1.findNextWhere(minBoxSizes, function(minBox) { return minBox.box === box; }); if (minBoxSize) { if (minBoxSize.horizontal) { var scaleMargin = { left: Math.max(outerBoxSizes.left, maxPadding.left), right: Math.max(outerBoxSizes.right, maxPadding.right), top: 0, bottom: 0 }; // Don't use min size here because of label rotation. When the labels are rotated, their rotation highly depends // on the margin. Sometimes they need to increase in size slightly box.update(box.fullWidth ? chartWidth : maxChartAreaWidth, chartHeight / 2, scaleMargin); } else { box.update(minBoxSize.width, maxChartAreaHeight); } } }
javascript
{ "resource": "" }
q15931
mergeConfig
train
function mergeConfig(/* config objects ... */) { return helpers$1.merge({}, [].slice.call(arguments), { merger: function(key, target, source, options) { var tval = target[key] || {}; var sval = source[key]; if (key === 'scales') { // scale config merging is complex. Add our own function here for that target[key] = mergeScaleConfig(tval, sval); } else if (key === 'scale') { // used in polar area & radar charts since there is only one scale target[key] = helpers$1.merge(tval, [core_scaleService.getScaleDefaults(sval.type), sval]); } else { helpers$1._merger(key, target, source, options); } } }); }
javascript
{ "resource": "" }
q15932
train
function() { var me = this; helpers$1.each(me.data.datasets, function(dataset, datasetIndex) { me.getDatasetMeta(datasetIndex).controller.reset(); }, me); }
javascript
{ "resource": "" }
q15933
train
function(easingValue) { var me = this; var tooltip = me.tooltip; var args = { tooltip: tooltip, easingValue: easingValue }; if (core_plugins.notify(me, 'beforeTooltipDraw', [args]) === false) { return; } tooltip.draw(); core_plugins.notify(me, 'afterTooltipDraw', [args]); }
javascript
{ "resource": "" }
q15934
getConstraintDimension
train
function getConstraintDimension(domNode, maxStyle, percentageProperty) { var view = document.defaultView; var parentNode = helpers$1._getParentNode(domNode); var constrainedNode = view.getComputedStyle(domNode)[maxStyle]; var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle]; var hasCNode = isConstrainedValue(constrainedNode); var hasCContainer = isConstrainedValue(constrainedContainer); var infinity = Number.POSITIVE_INFINITY; if (hasCNode || hasCContainer) { return Math.min( hasCNode ? parseMaxStyle(constrainedNode, domNode, percentageProperty) : infinity, hasCContainer ? parseMaxStyle(constrainedContainer, parentNode, percentageProperty) : infinity); } return 'none'; }
javascript
{ "resource": "" }
q15935
generateTicks
train
function generateTicks(generationOptions, dataRange) { var ticks = []; // To get a "nice" value for the tick spacing, we will use the appropriately named // "nice number" algorithm. See https://stackoverflow.com/questions/8506881/nice-label-algorithm-for-charts-with-minimum-ticks // for details. var MIN_SPACING = 1e-14; var stepSize = generationOptions.stepSize; var unit = stepSize || 1; var maxNumSpaces = generationOptions.maxTicks - 1; var min = generationOptions.min; var max = generationOptions.max; var precision = generationOptions.precision; var rmin = dataRange.min; var rmax = dataRange.max; var spacing = helpers$1.niceNum((rmax - rmin) / maxNumSpaces / unit) * unit; var factor, niceMin, niceMax, numSpaces; // Beyond MIN_SPACING floating point numbers being to lose precision // such that we can't do the math necessary to generate ticks if (spacing < MIN_SPACING && isNullOrUndef(min) && isNullOrUndef(max)) { return [rmin, rmax]; } numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing); if (numSpaces > maxNumSpaces) { // If the calculated num of spaces exceeds maxNumSpaces, recalculate it spacing = helpers$1.niceNum(numSpaces * spacing / maxNumSpaces / unit) * unit; } if (stepSize || isNullOrUndef(precision)) { // If a precision is not specified, calculate factor based on spacing factor = Math.pow(10, helpers$1._decimalPlaces(spacing)); } else { // If the user specified a precision, round to that number of decimal places factor = Math.pow(10, precision); spacing = Math.ceil(spacing * factor) / factor; } niceMin = Math.floor(rmin / spacing) * spacing; niceMax = Math.ceil(rmax / spacing) * spacing; // If min, max and stepSize is set and they make an evenly spaced scale use it. if (stepSize) { // If very close to our whole number, use it. if (!isNullOrUndef(min) && helpers$1.almostWhole(min / spacing, spacing / 1000)) { niceMin = min; } if (!isNullOrUndef(max) && helpers$1.almostWhole(max / spacing, spacing / 1000)) { niceMax = max; } } numSpaces = (niceMax - niceMin) / spacing; // If very close to our rounded value, use it. if (helpers$1.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { numSpaces = Math.round(numSpaces); } else { numSpaces = Math.ceil(numSpaces); } niceMin = Math.round(niceMin * factor) / factor; niceMax = Math.round(niceMax * factor) / factor; ticks.push(isNullOrUndef(min) ? niceMin : min); for (var j = 1; j < numSpaces; ++j) { ticks.push(Math.round((niceMin + j * spacing) * factor) / factor); } ticks.push(isNullOrUndef(max) ? niceMax : max); return ticks; }
javascript
{ "resource": "" }
q15936
train
function(value) { var exp = Math.floor(helpers$1.log10(value)); var significand = Math.floor(value / Math.pow(10, exp)); return significand * Math.pow(10, exp); }
javascript
{ "resource": "" }
q15937
bindInternal4
train
function bindInternal4(func, thisContext) { return function (a, b, c, d) { return func.call(thisContext, a, b, c, d); }; }
javascript
{ "resource": "" }
q15938
mangleScope
train
function mangleScope(scope) { let newNames = new Set(); // Sort bindings so that more frequently referenced bindings get shorter names. let sortedBindings = Object.keys(scope.bindings).sort( (a, b) => scope.bindings[b].referencePaths.length - scope.bindings[a].referencePaths.length ); for (let oldName of sortedBindings) { let i = 0; let newName = ''; do { newName = getIdentifier(i++); } while ( newNames.has(newName) || !canRename(scope, scope.bindings[oldName], newName) ); rename(scope, oldName, newName); newNames.add(newName); } }
javascript
{ "resource": "" }
q15939
mergeBlocks
train
function mergeBlocks(blocks) { let finalBlock; for (const block of blocks) { if (!finalBlock) finalBlock = block; else { block.nodes.forEach(node => finalBlock.push(node)); } } return finalBlock; }
javascript
{ "resource": "" }
q15940
morph
train
function morph(object, newProperties) { for (let key in object) { delete object[key]; } for (let key in newProperties) { object[key] = newProperties[key]; } }
javascript
{ "resource": "" }
q15941
getFlowConfig
train
function getFlowConfig(asset) { if (/^(\/{2}|\/\*+) *@flow/.test(asset.contents.substring(0, 20))) { return { internal: true, babelVersion: 7, config: { plugins: [[require('@babel/plugin-transform-flow-strip-types')]] } }; } return null; }
javascript
{ "resource": "" }
q15942
syncPromise
train
function syncPromise(promise) { let isDone = false; let res, err; promise.then( value => { res = value; isDone = true; }, error => { err = error; isDone = true; } ); deasync.loopWhile(() => !isDone); if (err) { throw err; } return res; }
javascript
{ "resource": "" }
q15943
treeShake
train
function treeShake(scope) { // Keep passing over all bindings in the scope until we don't remove any. // This handles cases where we remove one binding which had a reference to // another one. That one will get removed in the next pass if it is now unreferenced. let removed; do { removed = false; // Recrawl to get all bindings. scope.crawl(); Object.keys(scope.bindings).forEach(name => { let binding = getUnusedBinding(scope.path, name); // If it is not safe to remove the binding don't touch it. if (!binding) { return; } // Remove the binding and all references to it. binding.path.remove(); binding.referencePaths.concat(binding.constantViolations).forEach(remove); scope.removeBinding(name); removed = true; }); } while (removed); }
javascript
{ "resource": "" }
q15944
getUnusedBinding
train
function getUnusedBinding(path, name) { let binding = path.scope.getBinding(name); if (!binding) { return null; } let pure = isPure(binding); if (!binding.referenced && pure) { return binding; } // Is there any references which aren't simple assignments? let bailout = binding.referencePaths.some( path => !isExportAssignment(path) && !isUnusedWildcard(path) ); if (!bailout && pure) { return binding; } return null; }
javascript
{ "resource": "" }
q15945
pad
train
function pad(text, length, align = 'left') { let pad = ' '.repeat(length - stringWidth(text)); if (align === 'right') { return pad + text; } return text + pad; }
javascript
{ "resource": "" }
q15946
normalizeError
train
function normalizeError(err) { let message = 'Unknown error'; if (err) { if (err instanceof Error) { return err; } message = err.stack || err.message || err; } return new Error(message); }
javascript
{ "resource": "" }
q15947
getJSXConfig
train
async function getJSXConfig(asset, isSourceModule) { // Don't enable JSX in node_modules if (!isSourceModule) { return null; } let pkg = await asset.getPackage(); // Find a dependency that we can map to a JSX pragma let pragma = null; for (let dep in JSX_PRAGMA) { if ( pkg && ((pkg.dependencies && pkg.dependencies[dep]) || (pkg.devDependencies && pkg.devDependencies[dep])) ) { pragma = JSX_PRAGMA[dep]; break; } } if (!pragma) { pragma = maybeCreateFallbackPragma(asset); } if (pragma || JSX_EXTENSIONS[path.extname(asset.name)]) { return { internal: true, babelVersion: 7, config: { plugins: [ [ require('@babel/plugin-transform-react-jsx'), { pragma, pragmaFrag: 'React.Fragment' } ] ] } }; } }
javascript
{ "resource": "" }
q15948
train
function() { this.scrollToCurrent(); window.addEventListener('hashchange', this.scrollToCurrent.bind(this)); document.body.addEventListener('click', this.delegateAnchors.bind(this)); }
javascript
{ "resource": "" }
q15949
train
function() { let search_box = document.getElementById("search-input") search_box.onclick = function() { document.getElementById("search-image").style.display = "none"; search_box.style.outline = "none"; search_box.placeholder = "Search"; search_box.style.paddingLeft = "2px"; } }
javascript
{ "resource": "" }
q15950
train
function(nodes) { var map = {}, imports = []; // Compute a map from name to node. nodes.forEach(function(d) { map[d.name] = d; }); // For each import, construct a link from the source to target node. nodes.forEach(function(d) { if (d.imports) d.imports.forEach(function(i) { imports.push({source: map[d.name], target: map[i]}); }); }); return imports; }
javascript
{ "resource": "" }
q15951
BlocksToMoveVisitor
train
function BlocksToMoveVisitor() { this.visit = function(element) { if (isBlock(element)) { blocksToMove.push(findBlock(element.id)); return false; } return true; } }
javascript
{ "resource": "" }
q15952
getStyle
train
function getStyle(node, styleProp) { // if not an element if( node.nodeType != 1) return; var value; if (node.currentStyle) { // ie case styleProp = replaceDashWithCamelNotation(styleProp); value = node.currentStyle[styleProp]; } else if (window.getComputedStyle) { // mozilla case value = document.defaultView.getComputedStyle(node, null).getPropertyValue(styleProp); } return value; }
javascript
{ "resource": "" }
q15953
resizeCanvas
train
function resizeCanvas() { var divElement = document.getElementById("mainCanvas"); var screenHeight = window.innerHeight || document.body.offsetHeight; divElement.style.height = (screenHeight - 16) + "px"; }
javascript
{ "resource": "" }
q15954
setMenu
train
function setMenu() { var url = document.location.href; // strip extension url = stripExtension(url); var ulElement = document.getElementById("menu"); var links = ulElement.getElementsByTagName("A"); var i; for(i = 0; i < links.length; i++) { if(url.indexOf(stripExtension(links[i].href)) == 0) { links[i].className = "active_menu"; return; } } }
javascript
{ "resource": "" }
q15955
stripExtension
train
function stripExtension(url) { var lastDotPos = url.lastIndexOf('.'); return (lastDotPos <= 0)? url: url.substring (0, lastDotPos - 1); }
javascript
{ "resource": "" }
q15956
getElementCoords
train
function getElementCoords (element, coords) { coords = coords || element.node().getBBox() const ctm = element.node().getCTM() const xn = ctm.e + coords.x * ctm.a const yn = ctm.f + coords.y * ctm.d return { left: xn, top: yn, width: coords.width, height: coords.height } }
javascript
{ "resource": "" }
q15957
buildDocsEntry
train
function buildDocsEntry() { const output = join('docs/src/docs-entry.js'); const getName = fullPath => fullPath.replace(/\/(en|zh)/, '.$1').split('/').pop().replace('.md', ''); const docs = glob .sync([ join('docs/**/*.md'), join('packages/**/*.md'), '!**/node_modules/**' ]) .map(fullPath => { const name = getName(fullPath); return `'${name}': () => import('${path.relative(join('docs/src'), fullPath).replace(/\\/g, '/')}')`; }); const content = `${tips} export default { ${docs.join(',\n ')} }; `; fs.writeFileSync(output, content); }
javascript
{ "resource": "" }
q15958
analyzeDependencies
train
function analyzeDependencies(component) { const checkList = ['base']; search( dependencyTree({ directory: dir, filename: path.join(dir, component, 'index.js'), filter: path => !~path.indexOf('node_modules') }), component, checkList ); if (!whiteList.includes(component)) { checkList.push(component); } return checkList.filter(item => checkComponentHasStyle(item)); }
javascript
{ "resource": "" }
q15959
compile
train
async function compile() { let codes; const paths = await glob(['./es/**/*.less', './lib/**/*.less'], { absolute: true }); codes = await Promise.all(paths.map(path => fs.readFile(path, 'utf-8'))); codes = await compileLess(codes, paths); codes = await compilePostcss(codes, paths); codes = await compileCsso(codes); await dest(codes, paths); }
javascript
{ "resource": "" }
q15960
invertCurve
train
function invertCurve(curve){ var out = new Array(curve.length); for (var j = 0; j < curve.length; j++){ out[j] = 1 - curve[j]; } return out; }
javascript
{ "resource": "" }
q15961
_wrapScheduleMethods
train
function _wrapScheduleMethods(method){ return function(value, time){ time = this.toSeconds(time); method.apply(this, arguments); var event = this._events.get(time); var previousEvent = this._events.previousEvent(event); var ticksUntilTime = this._getTicksUntilEvent(previousEvent, time); event.ticks = Math.max(ticksUntilTime, 0); return this; }; }
javascript
{ "resource": "" }
q15962
computeSplitMapLayers
train
function computeSplitMapLayers(layers) { const mapLayers = layers.reduce( (newLayers, currentLayer) => ({ ...newLayers, [currentLayer.id]: generateLayerMetaForSplitViews(currentLayer) }), {} ); return [ { layers: mapLayers }, { layers: mapLayers } ]; }
javascript
{ "resource": "" }
q15963
removeLayerFromSplitMaps
train
function removeLayerFromSplitMaps(state, layer) { return state.splitMaps.map(settings => { const {layers} = settings; /* eslint-disable no-unused-vars */ const {[layer.id]: _, ...newLayers} = layers; /* eslint-enable no-unused-vars */ return { ...settings, layers: newLayers }; }); }
javascript
{ "resource": "" }
q15964
addNewLayersToSplitMap
train
function addNewLayersToSplitMap(splitMaps, layers) { const newLayers = Array.isArray(layers) ? layers : [layers]; if (!splitMaps || !splitMaps.length || !newLayers.length) { return splitMaps; } // add new layer to both maps, // don't override, if layer.id is already in splitMaps.settings.layers return splitMaps.map(settings => ({ ...settings, layers: { ...settings.layers, ...newLayers.reduce( (accu, newLayer) => newLayer.config.isVisible ? { ...accu, [newLayer.id]: settings.layers[newLayer.id] ? settings.layers[newLayer.id] : generateLayerMetaForSplitViews(newLayer) } : accu, {} ) } })); }
javascript
{ "resource": "" }
q15965
toggleLayerFromSplitMaps
train
function toggleLayerFromSplitMaps(state, layer) { return state.splitMaps.map(settings => { const {layers} = settings; const newLayers = { ...layers, [layer.id]: generateLayerMetaForSplitViews(layer) }; return { ...settings, layers: newLayers }; }); }
javascript
{ "resource": "" }
q15966
authLink
train
function authLink(path = 'auth') { return dropbox.getAuthenticationUrl( `${window.location.origin}/${path}`, btoa(JSON.stringify({handler: 'dropbox', origin: window.location.origin})) ) }
javascript
{ "resource": "" }
q15967
shareFile
train
function shareFile(metadata) { return dropbox.sharingCreateSharedLinkWithSettings({ path: metadata.path_display || metadata.path_lower }).then( // Update URL to avoid CORS issue // Unfortunately this is not the ideal scenario but it will make sure people // can share dropbox urls with users without the dropbox account (publish on twitter, facebook) result => ({ ...result, folder_link: KEPLER_DROPBOX_FOLDER_LINK, url: overrideUrl(result.url) }) ); }
javascript
{ "resource": "" }
q15968
getAccessToken
train
function getAccessToken() { let token = dropbox.getAccessToken(); if (!token && window.localStorage) { const jsonString = window.localStorage.getItem('dropbox'); token = jsonString && JSON.parse(jsonString).token; if (token) { dropbox.setAccessToken(token); } } return (token || '') !== '' ? token : null; }
javascript
{ "resource": "" }
q15969
_appendActionToUpdaters
train
function _appendActionToUpdaters(node, actionMap) { if (node.members && node.members.static.length) { node.members.static = node.members.static.map(nd => _appendActionToUpdaters(nd, actionMap)); } const updater = node.name; const action = Object.values(actionMap) .find(action => action.updaters.find(up => up.name === updater)); if (!action) { return node; } const actionName = action.name; const mdContent = ` * __Action__: [${BT}${actionName}${BT}](../actions/actions.md#${actionName.toLowerCase()}) `; return _appendListToDescription(node, mdContent); }
javascript
{ "resource": "" }
q15970
_cleanUpTOCChildren
train
function _cleanUpTOCChildren(node) { if (!Array.isArray(node.children)) { return node; } if (_isExampleOrParameterLink(node)) { return null; } const filteredChildren = node.children.reduce((accu, nd) => { accu.push(_cleanUpTOCChildren(nd)); return accu; }, []).filter(n => n); if (!filteredChildren.length) { return null; } return { ...node, children: filteredChildren }; }
javascript
{ "resource": "" }
q15971
geojsonSizeFieldV0ToV1
train
function geojsonSizeFieldV0ToV1(config) { const defaultRaiuds = 10; const defaultRadiusRange = [0, 50]; // if extruded, sizeField is most likely used for height if (config.visConfig.extruded) { return 'heightField'; } // if show stroke enabled, sizeField is most likely used for stroke if (config.visConfig.stroked) { return 'sizeField'; } // if radius changed, or radius Range Changed, sizeField is most likely used for radius // this is the most unreliable guess, that's why we put it in the end if ( config.visConfig.radius !== defaultRaiuds || config.visConfig.radiusRange.some((d, i) => d !== defaultRadiusRange[i]) ) { return 'radiusField'; } return 'sizeField'; }
javascript
{ "resource": "" }
q15972
mergeActions
train
function mergeActions(actions, userActions) { const overrides = {}; for (const key in userActions) { if (userActions.hasOwnProperty(key) && actions.hasOwnProperty(key)) { overrides[key] = userActions[key]; } } return {...actions, ...overrides}; }
javascript
{ "resource": "" }
q15973
loadRemoteRawData
train
function loadRemoteRawData(url) { if (!url) { // TODO: we should return reject with an appropriate error return Promise.resolve(null) } return new Promise((resolve, reject) => { request(url, (error, result) => { if (error) { reject(error); } const responseError = detectResponseError(result); if (responseError) { reject(responseError); return; } resolve(result.response) }) }); }
javascript
{ "resource": "" }
q15974
loadRemoteSampleMap
train
function loadRemoteSampleMap(options) { return (dispatch) => { // Load configuration first const {configUrl, dataUrl} = options; Promise .all([loadRemoteConfig(configUrl), loadRemoteData(dataUrl)]) .then( ([config, data]) => { // TODO: these two actions can be merged dispatch(loadRemoteResourceSuccess(data, config, options)); dispatch(toggleModal(null)); }, error => { if (error) { const {target = {}} = error; const {status, responseText} = target; dispatch(loadRemoteResourceError({status, message: `${responseText} - ${LOADING_SAMPLE_ERROR_MESSAGE} ${options.id} (${configUrl})`}, configUrl)); } } ); } }
javascript
{ "resource": "" }
q15975
addActionHandler
train
function addActionHandler(path, actionMap, filePath) { const {init} = path.node; if (init && Array.isArray(init.properties)) { init.properties.forEach(property => { const {key, value} = property; if (key && value && key.property && value.property) { const actionType = key.property.name; const updater = value.name; actionMap[actionType] = actionMap[actionType] || createActionNode(actionType); actionMap[actionType].updaters.push({ updater: value.object.name, name: value.property.name, path: filePath }); } }) } }
javascript
{ "resource": "" }
q15976
addActionCreator
train
function addActionCreator(path, actionMap, filePath) { const {node, parentPath} = path; if (node.arguments.length && parentPath.node && parentPath.node.id) { const action = parentPath.node.id.name; const firstArg = node.arguments[0]; const actionType = firstArg.property ? firstArg.property.name : firstArg.name; const {loc} = parentPath.node actionMap[actionType] = actionMap[actionType] || createActionNode(actionType); actionMap[actionType].action = {name: action, path: `${filePath}#L${loc.start.line}-L${loc.end.line}`}; } }
javascript
{ "resource": "" }
q15977
getHistogram
train
function getHistogram(domain, mappedValue) { const histogram = histogramConstruct(domain, mappedValue, histogramBins); const enlargedHistogram = histogramConstruct( domain, mappedValue, enlargedHistogramBins ); return {histogram, enlargedHistogram}; }
javascript
{ "resource": "" }
q15978
classifyRings
train
function classifyRings(rings) { const len = rings.length; if (len <= 1) return [rings]; const polygons = []; let polygon; let ccw; for (let i = 0; i < len; i++) { const area = signedArea(rings[i]); if (area === 0) { continue; } if (ccw === undefined) { ccw = area < 0; } if (ccw === area < 0) { if (polygon) { polygons.push(polygon); } polygon = [rings[i]]; } else { polygon.push(rings[i]); } } if (polygon) { polygons.push(polygon); } return polygons; }
javascript
{ "resource": "" }
q15979
CustomSidebarFactory
train
function CustomSidebarFactory(CloseButton) { const SideBar = SidebarFactory(CloseButton); const CustomSidebar = (props) => ( <StyledSideBarContainer> <SideBar {...props}/> </StyledSideBarContainer> ); return CustomSidebar; }
javascript
{ "resource": "" }
q15980
cleanUpFalsyCsvValue
train
function cleanUpFalsyCsvValue(rows) { for (let i = 0; i < rows.length; i++) { for (let j = 0; j < rows[i].length; j++) { // analyzer will set any fields to 'string' if there are empty values // which will be parsed as '' by d3.csv // here we parse empty data as null // TODO: create warning when deltect `CSV_NULLS` in the data if (!rows[i][j] || CSV_NULLS.includes(rows[i][j])) { rows[i][j] = null; } } } }
javascript
{ "resource": "" }
q15981
hasProblematicOverloading
train
function hasProblematicOverloading(instances) { // Check if there are same lengthed argument sets const knownLengths = []; return instances.map(({ args }) => args.length).reduce((carry, item) => { if (carry || knownLengths.some((l) => l === item)) { return true; } knownLengths.push(item); return false; }, false); }
javascript
{ "resource": "" }
q15982
isEmpty
train
function isEmpty(obj) { if (Array.isArray(obj)) { return obj.length === 0; } else if (typeof obj === 'object') { for (var i in obj) { return false; } return true; } else { return !obj; } }
javascript
{ "resource": "" }
q15983
getAppPath
train
function getAppPath(appPathArray) { if (appPathArray.length === 0) { // directory already exists, --overwrite is not set // exit here return null; } if (appPathArray.length > 1) { log.warn( 'Warning: This should not be happening, packaged app path contains more than one element:', appPathArray, ); } return appPathArray[0]; }
javascript
{ "resource": "" }
q15984
maybeNoIconOption
train
function maybeNoIconOption(options) { const packageOptions = JSON.parse(JSON.stringify(options)); if (options.platform === 'win32' && !isWindows()) { if (!hasBinary.sync('wine')) { log.warn( 'Wine is required to set the icon for a Windows app when packaging on non-windows platforms', ); packageOptions.icon = null; } } return packageOptions; }
javascript
{ "resource": "" }
q15985
removeInvalidOptions
train
function removeInvalidOptions(options, param) { const packageOptions = JSON.parse(JSON.stringify(options)); if (options.platform === 'win32' && !isWindows()) { if (!hasBinary.sync('wine')) { log.warn( `Wine is required to use "${param}" option for a Windows app when packaging on non-windows platforms`, ); packageOptions[param] = null; } } return packageOptions; }
javascript
{ "resource": "" }
q15986
findSync
train
function findSync(pattern, basePath, findDir) { const matches = []; (function findSyncRecurse(base) { let children; try { children = fs.readdirSync(base); } catch (exception) { if (exception.code === 'ENOENT') { return; } throw exception; } children.forEach((child) => { const childPath = path.join(base, child); const childIsDirectory = fs.lstatSync(childPath).isDirectory(); const patternMatches = pattern.test(childPath); if (!patternMatches) { if (!childIsDirectory) { return; } findSyncRecurse(childPath); return; } if (!findDir) { matches.push(childPath); return; } if (childIsDirectory) { matches.push(childPath); } }); })(basePath); return matches; }
javascript
{ "resource": "" }
q15987
wrap
train
function wrap(fieldName, promise, args) { return promise(args).then((result) => ({ [fieldName]: result, })); }
javascript
{ "resource": "" }
q15988
getMatchingIcons
train
function getMatchingIcons(iconsWithScores, maxScore) { return iconsWithScores .filter((item) => item.score === maxScore) .map((item) => Object.assign({}, item, { ext: path.extname(item.url) })); }
javascript
{ "resource": "" }
q15989
selectAppArgs
train
function selectAppArgs(options) { return { name: options.name, targetUrl: options.targetUrl, counter: options.counter, bounce: options.bounce, width: options.width, height: options.height, minWidth: options.minWidth, minHeight: options.minHeight, maxWidth: options.maxWidth, maxHeight: options.maxHeight, x: options.x, y: options.y, showMenuBar: options.showMenuBar, fastQuit: options.fastQuit, userAgent: options.userAgent, nativefierVersion: options.nativefierVersion, ignoreCertificate: options.ignoreCertificate, disableGpu: options.disableGpu, ignoreGpuBlacklist: options.ignoreGpuBlacklist, enableEs3Apis: options.enableEs3Apis, insecure: options.insecure, flashPluginDir: options.flashPluginDir, diskCacheSize: options.diskCacheSize, fullScreen: options.fullScreen, hideWindowFrame: options.hideWindowFrame, maximize: options.maximize, disableContextMenu: options.disableContextMenu, disableDevTools: options.disableDevTools, zoom: options.zoom, internalUrls: options.internalUrls, crashReporter: options.crashReporter, singleInstance: options.singleInstance, clearCache: options.clearCache, appCopyright: options.appCopyright, appVersion: options.appVersion, buildVersion: options.buildVersion, win32metadata: options.win32metadata, versionString: options.versionString, processEnvs: options.processEnvs, fileDownloadOptions: options.fileDownloadOptions, tray: options.tray, basicAuthUsername: options.basicAuthUsername, basicAuthPassword: options.basicAuthPassword, alwaysOnTop: options.alwaysOnTop, titleBarStyle: options.titleBarStyle, globalShortcuts: options.globalShortcuts, }; }
javascript
{ "resource": "" }
q15990
convertToIcnsTmp
train
function convertToIcnsTmp(pngSrc, callback) { const tempIconDirObj = tmp.dirSync({ unsafeCleanup: true }); const tempIconDirPath = tempIconDirObj.name; convertToIcns(pngSrc, `${tempIconDirPath}/icon.icns`, callback); }
javascript
{ "resource": "" }
q15991
debugLog
train
function debugLog(browserWindow, message) { // need the timeout as it takes time for the preload javascript to be loaded in the window setTimeout(() => { browserWindow.webContents.send('debug', message); }, 3000); log.info(message); }
javascript
{ "resource": "" }
q15992
patchDisplay
train
function patchDisplay(cm, updateNumbersFrom, dims) { let display = cm.display, lineNumbers = cm.options.lineNumbers let container = display.lineDiv, cur = container.firstChild function rm(node) { let next = node.nextSibling // Works around a throw-scroll bug in OS X Webkit if (webkit && mac && cm.display.currentWheelTarget == node) node.style.display = "none" else node.parentNode.removeChild(node) return next } let view = display.view, lineN = display.viewFrom // Loop over the elements in the view, syncing cur (the DOM nodes // in display.lineDiv) with the view as we go. for (let i = 0; i < view.length; i++) { let lineView = view[i] if (lineView.hidden) { } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet let node = buildLineElement(cm, lineView, lineN, dims) container.insertBefore(node, cur) } else { // Already drawn while (cur != lineView.node) cur = rm(cur) let updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber if (lineView.changes) { if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false updateLineForChanges(cm, lineView, lineN, dims) } if (updateNumber) { removeChildren(lineView.lineNumber) lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))) } cur = lineView.node.nextSibling } lineN += lineView.size } while (cur) cur = rm(cur) }
javascript
{ "resource": "" }
q15993
skipAtomicInSelection
train
function skipAtomicInSelection(doc, sel, bias, mayClear) { let out for (let i = 0; i < sel.ranges.length; i++) { let range = sel.ranges[i] let old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i] let newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear) let newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear) if (out || newAnchor != range.anchor || newHead != range.head) { if (!out) out = sel.ranges.slice(0, i) out[i] = new Range(newAnchor, newHead) } } return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel }
javascript
{ "resource": "" }
q15994
lastChangeEvent
train
function lastChangeEvent(hist, force) { if (force) { clearSelectionEvents(hist.done) return lst(hist.done) } else if (hist.done.length && !lst(hist.done).ranges) { return lst(hist.done) } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { hist.done.pop() return lst(hist.done) } }
javascript
{ "resource": "" }
q15995
getOldSpans
train
function getOldSpans(doc, change) { let found = change["spans_" + doc.id] if (!found) return null let nw = [] for (let i = 0; i < change.text.length; ++i) nw.push(removeClearedSpans(found[i])) return nw }
javascript
{ "resource": "" }
q15996
handleKeyBinding
train
function handleKeyBinding(cm, e) { let name = keyName(e, true) if (!name) return false if (e.shiftKey && !cm.state.keySeq) { // First try to resolve full name (including 'Shift-'). Failing // that, see if there is a cursor-motion command (starting with // 'go') bound to the keyname without 'Shift-'. return dispatchKey(cm, "Shift-" + name, e, b => doHandleBinding(cm, b, true)) || dispatchKey(cm, name, e, b => { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) return doHandleBinding(cm, b) }) } else { return dispatchKey(cm, name, e, b => doHandleBinding(cm, b)) } }
javascript
{ "resource": "" }
q15997
handleCharBinding
train
function handleCharBinding(cm, e, ch) { return dispatchKey(cm, "'" + ch + "'", e, b => doHandleBinding(cm, b, true)) }
javascript
{ "resource": "" }
q15998
boxIsAfter
train
function boxIsAfter(box, x, y, left) { return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x }
javascript
{ "resource": "" }
q15999
runMode
train
function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { let flattenSpans = mode.flattenSpans if (flattenSpans == null) flattenSpans = cm.options.flattenSpans let curStart = 0, curStyle = null let stream = new StringStream(text, cm.options.tabSize, context), style let inner = cm.options.addModeClass && [null] if (text == "") extractLineClasses(callBlankLine(mode, context.state), lineClasses) while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false if (forceToEnd) processLine(cm, text, context, stream.pos) stream.pos = text.length style = null } else { style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses) } if (inner) { let mName = inner[0].name if (mName) style = "m-" + (style ? mName + " " + style : mName) } if (!flattenSpans || curStyle != style) { while (curStart < stream.start) { curStart = Math.min(stream.start, curStart + 5000) f(curStart, curStyle) } curStyle = style } stream.start = stream.pos } while (curStart < stream.pos) { // Webkit seems to refuse to render text nodes longer than 57444 // characters, and returns inaccurate measurements in nodes // starting around 5000 chars. let pos = Math.min(stream.pos, curStart + 5000) f(pos, curStyle) curStart = pos } }
javascript
{ "resource": "" }