_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q23600
|
isAncestorContainer
|
train
|
function isAncestorContainer(ancestor, descendant) {
return (ancestor || descendant)
&& (ancestor == descendant || isAncestor(ancestor, descendant));
}
|
javascript
|
{
"resource": ""
}
|
q23601
|
isDescendant
|
train
|
function isDescendant(descendant, ancestor) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
}
|
javascript
|
{
"resource": ""
}
|
q23602
|
getPosition
|
train
|
function getPosition(nodeA, offsetA, nodeB, offsetB) {
// "If node A is the same as node B, return equal if offset A equals offset
// B, before if offset A is less than offset B, and after if offset A is
// greater than offset B."
if (nodeA == nodeB) {
if (offsetA == offsetB) {
return "equal";
}
if (offsetA < offsetB) {
return "before";
}
if (offsetA > offsetB) {
return "after";
}
}
// "If node A is after node B in tree order, compute the position of (node
// B, offset B) relative to (node A, offset A). If it is before, return
// after. If it is after, return before."
if (nodeB.compareDocumentPosition(nodeA) & Node.DOCUMENT_POSITION_FOLLOWING) {
var pos = getPosition(nodeB, offsetB, nodeA, offsetA);
if (pos == "before") {
return "after";
}
if (pos == "after") {
return "before";
}
}
// "If node A is an ancestor of node B:"
if (nodeB.compareDocumentPosition(nodeA) & Node.DOCUMENT_POSITION_CONTAINS) {
// "Let child equal node B."
var child = nodeB;
// "While child is not a child of node A, set child to its parent."
while (child.parentNode != nodeA) {
child = child.parentNode;
}
// "If the index of child is less than offset A, return after."
if (getNodeIndex(child) < offsetA) {
return "after";
}
}
// "Return before."
return "before";
}
|
javascript
|
{
"resource": ""
}
|
q23603
|
getContainedNodes
|
train
|
function getContainedNodes(range, condition) {
if (typeof condition == "undefined") {
condition = function() { return true };
}
var node = range.startContainer;
if (node.hasChildNodes()
&& range.startOffset < node.childNodes.length) {
// A child is contained
node = node.childNodes[range.startOffset];
} else if (range.startOffset == getNodeLength(node)) {
// No descendant can be contained
node = nextNodeDescendants(node);
} else {
// No children; this node at least can't be contained
node = nextNode(node);
}
var stop = range.endContainer;
if (stop.hasChildNodes()
&& range.endOffset < stop.childNodes.length) {
// The node after the last contained node is a child
stop = stop.childNodes[range.endOffset];
} else {
// This node and/or some of its children might be contained
stop = nextNodeDescendants(stop);
}
var nodeList = [];
while (isBefore(node, stop)) {
if (isContained(node, range)
&& condition(node)) {
nodeList.push(node);
node = nextNodeDescendants(node);
continue;
}
node = nextNode(node);
}
return nodeList;
}
|
javascript
|
{
"resource": ""
}
|
q23604
|
editCommandMethod
|
train
|
function editCommandMethod(command, range, callback) {
// Set up our global range magic, but only if we're the outermost function
if (executionStackDepth == 0 && typeof range != "undefined") {
globalRange = range;
} else if (executionStackDepth == 0) {
globalRange = null;
globalRange = getActiveRange();
}
// "If command is not supported, raise a NOT_SUPPORTED_ERR exception."
//
// We can't throw a real one, but a string will do for our purposes.
if (!(command in commands)) {
throw "NOT_SUPPORTED_ERR";
}
executionStackDepth++;
try {
var ret = callback();
} catch(e) {
executionStackDepth--;
throw e;
}
executionStackDepth--;
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q23605
|
isEditingHost
|
train
|
function isEditingHost(node) {
return node
&& isHtmlElement(node)
&& (node.contentEditable == "true"
|| (node.parentNode
&& node.parentNode.nodeType == Node.DOCUMENT_NODE
&& node.parentNode.designMode == "on"));
}
|
javascript
|
{
"resource": ""
}
|
q23606
|
isEditable
|
train
|
function isEditable(node) {
return node
&& !isEditingHost(node)
&& (node.nodeType != Node.ELEMENT_NODE || node.contentEditable != "false")
&& (isEditingHost(node.parentNode) || isEditable(node.parentNode))
&& (isHtmlElement(node)
|| (node.nodeType == Node.ELEMENT_NODE && node.namespaceURI == "http://www.w3.org/2000/svg" && node.localName == "svg")
|| (node.nodeType == Node.ELEMENT_NODE && node.namespaceURI == "http://www.w3.org/1998/Math/MathML" && node.localName == "math")
|| (node.nodeType != Node.ELEMENT_NODE && isHtmlElement(node.parentNode)));
}
|
javascript
|
{
"resource": ""
}
|
q23607
|
hasEditableDescendants
|
train
|
function hasEditableDescendants(node) {
for (var i = 0; i < node.childNodes.length; i++) {
if (isEditable(node.childNodes[i])
|| hasEditableDescendants(node.childNodes[i])) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q23608
|
getEditingHostOf
|
train
|
function getEditingHostOf(node) {
if (isEditingHost(node)) {
return node;
} else if (isEditable(node)) {
var ancestor = node.parentNode;
while (!isEditingHost(ancestor)) {
ancestor = ancestor.parentNode;
}
return ancestor;
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q23609
|
isCollapsedBlockProp
|
train
|
function isCollapsedBlockProp(node) {
if (isCollapsedLineBreak(node)
&& !isExtraneousLineBreak(node)) {
return true;
}
if (!isInlineNode(node)
|| node.nodeType != Node.ELEMENT_NODE) {
return false;
}
var hasCollapsedBlockPropChild = false;
for (var i = 0; i < node.childNodes.length; i++) {
if (!isInvisible(node.childNodes[i])
&& !isCollapsedBlockProp(node.childNodes[i])) {
return false;
}
if (isCollapsedBlockProp(node.childNodes[i])) {
hasCollapsedBlockPropChild = true;
}
}
return hasCollapsedBlockPropChild;
}
|
javascript
|
{
"resource": ""
}
|
q23610
|
isFormattableNode
|
train
|
function isFormattableNode(node) {
return isEditable(node)
&& isVisible(node)
&& (node.nodeType == Node.TEXT_NODE
|| isHtmlElement(node, ["img", "br"]));
}
|
javascript
|
{
"resource": ""
}
|
q23611
|
areEquivalentValues
|
train
|
function areEquivalentValues(command, val1, val2) {
if (val1 === null && val2 === null) {
return true;
}
if (typeof val1 == "string"
&& typeof val2 == "string"
&& val1 == val2
&& !("equivalentValues" in commands[command])) {
return true;
}
if (typeof val1 == "string"
&& typeof val2 == "string"
&& "equivalentValues" in commands[command]
&& commands[command].equivalentValues(val1, val2)) {
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q23612
|
normalizeFontSize
|
train
|
function normalizeFontSize(value) {
// "Strip leading and trailing whitespace from value."
//
// Cheap hack, not following the actual algorithm.
value = value.trim();
// "If value is not a valid floating point number, and would not be a valid
// floating point number if a single leading "+" character were stripped,
// abort these steps and do nothing."
if (!/^[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/.test(value)) {
return null;
}
var mode;
// "If the first character of value is "+", delete the character and let
// mode be "relative-plus"."
if (value[0] == "+") {
value = value.slice(1);
mode = "relative-plus";
// "Otherwise, if the first character of value is "-", delete the character
// and let mode be "relative-minus"."
} else if (value[0] == "-") {
value = value.slice(1);
mode = "relative-minus";
// "Otherwise, let mode be "absolute"."
} else {
mode = "absolute";
}
// "Apply the rules for parsing non-negative integers to value, and let
// number be the result."
//
// Another cheap hack.
var num = parseInt(value);
// "If mode is "relative-plus", add three to number."
if (mode == "relative-plus") {
num += 3;
}
// "If mode is "relative-minus", negate number, then add three to it."
if (mode == "relative-minus") {
num = 3 - num;
}
// "If number is less than one, let number equal 1."
if (num < 1) {
num = 1;
}
// "If number is greater than seven, let number equal 7."
if (num > 7) {
num = 7;
}
// "Set value to the string here corresponding to number:" [table omitted]
value = {
1: "xx-small",
2: "small",
3: "medium",
4: "large",
5: "x-large",
6: "xx-large",
7: "xxx-large"
}[num];
return value;
}
|
javascript
|
{
"resource": ""
}
|
q23613
|
train
|
function(value) {
// Action is further copy-pasted, same as foreColor
// "If value is not a valid CSS color, prepend "#" to it."
//
// "If value is still not a valid CSS color, or if it is currentColor,
// abort these steps and do nothing."
//
// Cheap hack for testing, no attempt to be comprehensive.
if (/^([0-9a-fA-F]{3}){1,2}$/.test(value)) {
value = "#" + value;
}
if (!/^(rgba?|hsla?)\(.*\)$/.test(value)
&& !parseSimpleColor(value)
&& value.toLowerCase() != "transparent") {
return;
}
// "Set the selection's value to value."
setSelectionValue("hilitecolor", value);
}
|
javascript
|
{
"resource": ""
}
|
|
q23614
|
isIndentationElement
|
train
|
function isIndentationElement(node) {
if (!isHtmlElement(node)) {
return false;
}
if (node.tagName == "BLOCKQUOTE") {
return true;
}
if (node.tagName != "DIV") {
return false;
}
for (var i = 0; i < node.style.length; i++) {
// Approximate check
if (/^(-[a-z]+-)?margin/.test(node.style[i])) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q23615
|
removePreservingDescendants
|
train
|
function removePreservingDescendants(node) {
if (node.hasChildNodes()) {
splitParent([].slice.call(node.childNodes));
} else {
node.parentNode.removeChild(node);
}
}
|
javascript
|
{
"resource": ""
}
|
q23616
|
hasClass
|
train
|
function hasClass(el, className) {
if (typeof el.classList == "object") {
return el.classList.contains(className);
} else {
var classNameSupported = (typeof el.className == "string");
var elClass = classNameSupported ? el.className : el.getAttribute("class");
return classNameContainsClass(elClass, className);
}
}
|
javascript
|
{
"resource": ""
}
|
q23617
|
train
|
function(textNodes, range, positionsToPreserve, isUndo) {
log.group("postApply " + range.toHtml());
var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1];
var merges = [], currentMerge;
var rangeStartNode = firstNode, rangeEndNode = lastNode;
var rangeStartOffset = 0, rangeEndOffset = lastNode.length;
var precedingTextNode;
// Check for every required merge and create a Merge object for each
forEach(textNodes, function(textNode) {
precedingTextNode = getPreviousMergeableTextNode(textNode, !isUndo);
log.debug("Checking for merge. text node: " + textNode.data + ", parent: " + dom.inspectNode(textNode.parentNode) + ", preceding: " + dom.inspectNode(precedingTextNode));
if (precedingTextNode) {
if (!currentMerge) {
currentMerge = new Merge(precedingTextNode);
merges.push(currentMerge);
}
currentMerge.textNodes.push(textNode);
if (textNode === firstNode) {
rangeStartNode = currentMerge.textNodes[0];
rangeStartOffset = rangeStartNode.length;
}
if (textNode === lastNode) {
rangeEndNode = currentMerge.textNodes[0];
rangeEndOffset = currentMerge.getLength();
}
} else {
currentMerge = null;
}
});
// Test whether the first node after the range needs merging
var nextTextNode = getNextMergeableTextNode(lastNode, !isUndo);
if (nextTextNode) {
if (!currentMerge) {
currentMerge = new Merge(lastNode);
merges.push(currentMerge);
}
currentMerge.textNodes.push(nextTextNode);
}
// Apply the merges
if (merges.length) {
log.info("Merging. Merges:", merges);
for (var i = 0, len = merges.length; i < len; ++i) {
merges[i].doMerge(positionsToPreserve);
}
log.info(rangeStartNode.nodeValue, rangeStartOffset, rangeEndNode.nodeValue, rangeEndOffset);
// Set the range boundaries
range.setStartAndEnd(rangeStartNode, rangeStartOffset, rangeEndNode, rangeEndOffset);
log.info("Range after merge: " + range.inspect());
}
log.groupEnd();
}
|
javascript
|
{
"resource": ""
}
|
|
q23618
|
getComputedDisplay
|
train
|
function getComputedDisplay(el, win) {
var display = getComputedStyleProperty(el, "display", win);
var tagName = el.tagName.toLowerCase();
return (display == "block" &&
tableCssDisplayBlock &&
defaultDisplayValueForTag.hasOwnProperty(tagName)) ?
defaultDisplayValueForTag[tagName] : display;
}
|
javascript
|
{
"resource": ""
}
|
q23619
|
train
|
function() {
if (!this.prepopulatedChar) {
this.prepopulateChar();
}
if (this.checkForTrailingSpace) {
var trailingSpace = this.session.getNodeWrapper(this.node.childNodes[this.offset - 1]).getTrailingSpace();
log.debug("resolveLeadingAndTrailingSpaces checking for trailing space on " + this.inspect() + ", got '" + trailingSpace + "'");
if (trailingSpace) {
this.isTrailingSpace = true;
this.character = trailingSpace;
this.characterType = COLLAPSIBLE_SPACE;
}
this.checkForTrailingSpace = false;
}
if (this.checkForLeadingSpace) {
var leadingSpace = this.session.getNodeWrapper(this.node.childNodes[this.offset]).getLeadingSpace();
log.debug("resolveLeadingAndTrailingSpaces checking for leading space on " + this.inspect() + ", got '" + leadingSpace + "'");
if (leadingSpace) {
this.isLeadingSpace = true;
this.character = leadingSpace;
this.characterType = COLLAPSIBLE_SPACE;
}
this.checkForLeadingSpace = false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q23620
|
consumeWord
|
train
|
function consumeWord(forward) {
log.debug("consumeWord called, forward is " + forward);
var pos, textChar;
var newChars = [], it = forward ? forwardIterator : backwardIterator;
var passedWordBoundary = false, insideWord = false;
while ( (pos = it.next()) ) {
textChar = pos.character;
log.debug("Testing char '" + textChar + "'");
if (allWhiteSpaceRegex.test(textChar)) {
if (insideWord) {
insideWord = false;
passedWordBoundary = true;
}
} else {
log.debug("Got non-whitespace, passedWordBoundary is " + passedWordBoundary);
if (passedWordBoundary) {
it.rewind();
break;
} else {
insideWord = true;
}
}
newChars.push(pos);
}
log.debug("consumeWord done, pos is " + (pos ? pos.inspect() : "non-existent"));
log.debug("consumeWord got new chars " + newChars.join(""));
return newChars;
}
|
javascript
|
{
"resource": ""
}
|
q23621
|
isEditingHost
|
train
|
function isEditingHost(node) {
return node &&
((node.nodeType == 9 && node.designMode == "on") ||
(isEditableElement(node) && !isEditableElement(node.parentNode)));
}
|
javascript
|
{
"resource": ""
}
|
q23622
|
isEditable
|
train
|
function isEditable(node, options) {
// This is slightly a lie, because we're excluding non-HTML elements with
// contentEditable attributes.
return !options || !options.applyToEditableOnly
|| ( (isEditableElement(node) || isEditableElement(node.parentNode)) && !isEditingHost(node) );
}
|
javascript
|
{
"resource": ""
}
|
q23623
|
isEffectivelyContained
|
train
|
function isEffectivelyContained(node, range) {
if (isContained(node, range)) {
return true;
}
var isCharData = dom.isCharacterDataNode(node);
if (node == range.startContainer && isCharData && dom.getNodeLength(node) != range.startOffset) {
return true;
}
if (node == range.endContainer && isCharData && range.endOffset != 0) {
return true;
}
var children = node.childNodes, childCount = children.length;
if (childCount != 0) {
for (var i = 0; i < childCount; ++i) {
if (!isEffectivelyContained(children[i], range)) {
return false;
}
}
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q23624
|
isInlineNode
|
train
|
function isInlineNode(node) {
return dom.isCharacterDataNode(node) ||
(node.nodeType == 1 && inlineDisplayRegex.test(getComputedStyleProperty(node, "display")));
}
|
javascript
|
{
"resource": ""
}
|
q23625
|
valuesEqual
|
train
|
function valuesEqual(command, val1, val2) {
if (val1 === null || val2 === null) {
return val1 === val2;
}
return command.valuesEqual(val1, val2);
}
|
javascript
|
{
"resource": ""
}
|
q23626
|
train
|
function(textNodes, range) {
log.group("postApply");
var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1];
var merges = [], currentMerge;
var rangeStartNode = firstNode, rangeEndNode = lastNode;
var rangeStartOffset = 0, rangeEndOffset = lastNode.length;
var textNode, precedingTextNode;
for (var i = 0, len = textNodes.length; i < len; ++i) {
textNode = textNodes[i];
precedingTextNode = getAdjacentMergeableTextNode(textNode, false);
log.debug("Checking for merge. text node: " + textNode.data + ", preceding: " + (precedingTextNode ? precedingTextNode.data : null));
if (precedingTextNode) {
if (!currentMerge) {
currentMerge = new Merge(precedingTextNode);
merges.push(currentMerge);
}
currentMerge.textNodes.push(textNode);
if (textNode === firstNode) {
rangeStartNode = currentMerge.firstTextNode;
rangeStartOffset = rangeStartNode.length;
}
if (textNode === lastNode) {
rangeEndNode = currentMerge.firstTextNode;
rangeEndOffset = currentMerge.getLength();
}
} else {
currentMerge = null;
}
}
// Test whether the first node after the range needs merging
var nextTextNode = getAdjacentMergeableTextNode(lastNode, true);
if (nextTextNode) {
if (!currentMerge) {
currentMerge = new Merge(lastNode);
merges.push(currentMerge);
}
currentMerge.textNodes.push(nextTextNode);
}
// Do the merges
if (merges.length) {
log.info("Merging. Merges:", merges);
for (i = 0, len = merges.length; i < len; ++i) {
merges[i].doMerge();
}
log.info(rangeStartNode.nodeValue, rangeStartOffset, rangeEndNode.nodeValue, rangeEndOffset);
// Set the range boundaries
range.setStart(rangeStartNode, rangeStartOffset);
range.setEnd(rangeEndNode, rangeEndOffset);
}
log.groupEnd();
}
|
javascript
|
{
"resource": ""
}
|
|
q23627
|
getScrollPosition
|
train
|
function getScrollPosition(win) {
var x = 0, y = 0;
if (typeof win.pageXOffset == NUMBER && typeof win.pageYOffset == NUMBER) {
x = win.pageXOffset;
y = win.pageYOffset;
} else {
var doc = win.document;
var docEl = doc.documentElement;
var compatMode = doc.compatMode;
var scrollEl = (typeof compatMode == "string" && compatMode.indexOf("CSS") >= 0 && docEl)
? docEl : dom.getBody(doc);
if (scrollEl && typeof scrollEl.scrollLeft == NUMBER && typeof scrollEl.scrollTop == NUMBER) {
try {
x = scrollEl.scrollLeft;
y = scrollEl.scrollTop;
} catch (ex) {}
}
}
return { x: x, y: y };
}
|
javascript
|
{
"resource": ""
}
|
q23628
|
train
|
function(el) {
var x = 0, y = 0, offsetEl = el, width = el.offsetWidth, height = el.offsetHeight;
while (offsetEl) {
x += offsetEl.offsetLeft;
y += offsetEl.offsetTop;
offsetEl = offsetEl.offsetParent;
}
return adjustClientRect(new Rect(y, x + width, y + height, x), dom.getDocument(el));
}
|
javascript
|
{
"resource": ""
}
|
|
q23629
|
templateObjectOrArray
|
train
|
function templateObjectOrArray(o, context) {
deepForEach(o, (value, key, subj, path) => {
const newPath = template(path, context, true);
let newValue;
if (value && (value.constructor !== Object && value.constructor !== Array)) {
newValue = template(value, context, true);
} else {
newValue = value;
}
debug(`path = ${path} ; value = ${JSON.stringify(value)} (${typeof value}) ; (subj type: ${subj.length ? 'list':'hash'}) ; newValue = ${JSON.stringify(newValue)} ; newPath = ${newPath}`);
// If path has changed, we need to unset the original path and
// explicitly walk down the new subtree from this path:
if (path !== newPath) {
L.unset(o, path);
newValue = template(value, context, true);
}
L.set(o, newPath, newValue);
});
}
|
javascript
|
{
"resource": ""
}
|
q23630
|
extractJSONPath
|
train
|
function extractJSONPath(doc, expr) {
// typeof null is 'object' hence the explicit check here
if (typeof doc !== 'object' || doc === null) {
return '';
}
let results;
try {
results = jsonpath.query(doc, expr);
} catch (queryErr) {
debug(queryErr);
}
if (!results) {
return '';
}
if (results.length > 1) {
return results[randomInt(0, results.length - 1)];
} else {
return results[0];
}
}
|
javascript
|
{
"resource": ""
}
|
q23631
|
divideWork
|
train
|
function divideWork(script, numWorkers) {
let newPhases = [];
for (let i = 0; i < numWorkers; i++) {
newPhases.push(L.cloneDeep(script.config.phases));
}
//
// Adjust phase definitions:
//
L.each(script.config.phases, function(phase, phaseSpecIndex) {
if (phase.arrivalRate && phase.rampTo) {
let rates = distribute(phase.arrivalRate, numWorkers);
let ramps = distribute(phase.rampTo, numWorkers);
L.each(rates, function(Lr, i) {
newPhases[i][phaseSpecIndex].arrivalRate = rates[i];
newPhases[i][phaseSpecIndex].rampTo = ramps[i];
});
return;
}
if (phase.arrivalRate && !phase.rampTo) {
let rates = distribute(phase.arrivalRate, numWorkers);
L.each(rates, function(Lr, i) {
newPhases[i][phaseSpecIndex].arrivalRate = rates[i];
});
return;
}
if (phase.arrivalCount) {
let counts = distribute(phase.arrivalCount, numWorkers);
L.each(counts, function(Lc, i) {
newPhases[i][phaseSpecIndex].arrivalCount = counts[i];
});
return;
}
if (phase.pause) {
// nothing to adjust here
return;
}
console.log('Unknown phase spec definition, skipping.\n%j\n' +
'This should not happen', phase);
});
//
// Create new scripts:
//
let newScripts = L.map(L.range(0, numWorkers), function(i) {
let newScript = L.cloneDeep(script);
newScript.config.phases = newPhases[i];
return newScript;
});
//
// Adjust pool settings for HTTP if needed:
//
// FIXME: makes multicore code tightly coupled to the engines; replace with
// something less coupled.
if (!L.isUndefined(L.get(script, 'config.http.pool'))) {
let pools = distribute(script.config.http.pool, numWorkers);
L.each(newScripts, function(s, i) {
s.config.http.pool = pools[i];
});
}
return newScripts;
}
|
javascript
|
{
"resource": ""
}
|
q23632
|
distribute
|
train
|
function distribute(m, n) {
m = Number(m);
n = Number(n);
let result = [];
if (m < n) {
for (let i = 0; i < n; i++) {
result.push(i < m ? 1 : 0);
}
} else {
let baseCount = Math.floor(m / n);
let extraItems = m % n;
for(let i = 0; i < n; i++) {
result.push(baseCount);
if (extraItems > 0) {
result[i]++;
extraItems--;
}
}
}
assert(m === sum(result), `${m} === ${sum(result)}`);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q23633
|
create
|
train
|
function create(list) {
let dist = l.reduce(list, function(acc, el, i) {
for(let j = 0; j < el.weight * 100; j++) {
acc.push(i);
}
return acc;
}, []);
return function() {
let i = dist[l.random(0, dist.length - 1)];
return [i, list[i]];
};
}
|
javascript
|
{
"resource": ""
}
|
q23634
|
createContext
|
train
|
function createContext(script) {
const INITIAL_CONTEXT = {
vars: {
target: script.config.target,
$environment: script._environment,
$processEnvironment: process.env
},
funcs: {
$randomNumber: $randomNumber,
$randomString: $randomString,
$template: input => engineUtil.template(input, { vars: result.vars })
}
};
let result = _.cloneDeep(INITIAL_CONTEXT);
// variables from payloads:
const variableValues1 = datafileVariables(script);
Object.assign(result.vars, variableValues1);
// inline variables:
const variableValues2 = inlineVariables(script);
Object.assign(result.vars, variableValues2);
result._uid = uuid.v4();
result.vars.$uuid = result._uid;
return result;
}
|
javascript
|
{
"resource": ""
}
|
q23635
|
combine
|
train
|
function combine(statsObjects) {
let result = create();
L.each(statsObjects, function(stats) {
L.each(stats._latencies, function(latency) {
result._latencies.push(latency);
});
result._generatedScenarios += stats._generatedScenarios;
L.each(stats._scenarioCounter, function(count, name) {
if(result._scenarioCounter[name]) {
result._scenarioCounter[name] += count;
} else {
result._scenarioCounter[name] = count;
}
});
result._completedScenarios += stats._completedScenarios;
result._scenariosAvoided += stats._scenariosAvoided;
L.each(stats._codes, function(count, code) {
if(result._codes[code]) {
result._codes[code] += count;
} else {
result._codes[code] = count;
}
});
L.each(stats._errors, function(count, error) {
if(result._errors[error]) {
result._errors[error] += count;
} else {
result._errors[error] = count;
}
});
L.each(stats._requestTimestamps, function(timestamp) {
result._requestTimestamps.push(timestamp);
});
result._completedRequests += stats._completedRequests;
L.each(stats._scenarioLatencies, function(latency) {
result._scenarioLatencies.push(latency);
});
result._matches += stats._matches;
L.each(stats._counters, function(value, name) {
if (!result._counters[name]) {
result._counters[name] = 0;
}
result._counters[name] += value;
});
L.each(stats._customStats, function(values, name) {
if (!result._customStats[name]) {
result._customStats[name] = [];
}
L.each(values, function(v) {
result._customStats[name].push(v);
});
});
result._concurrency += stats._concurrency || 0;
result._pendingRequests += stats._pendingRequests;
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q23636
|
ensurePropertyIsAList
|
train
|
function ensurePropertyIsAList(obj, prop) {
obj[prop] = [].concat(
typeof obj[prop] === 'undefined' ?
[] : obj[prop]);
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q23637
|
propReplace
|
train
|
function propReplace(obj, prop, value) {
var o = {};
for (var p in obj) {
if (o.hasOwnProperty.call(obj, p)) {
if (typeof obj[p] == 'object' && !Array.isArray(obj[p])) {
propReplace(obj[p], prop, value);
} else if (p == prop) {
obj[p] = value;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23638
|
pbxBuildFileObj
|
train
|
function pbxBuildFileObj(file) {
var obj = Object.create(null);
obj.isa = 'PBXBuildFile';
obj.fileRef = file.fileRef;
obj.fileRef_comment = file.basename;
if (file.settings) obj.settings = file.settings;
return obj;
}
|
javascript
|
{
"resource": ""
}
|
q23639
|
getiframeDocument
|
train
|
function getiframeDocument($iframe) {
var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframeDoc.document) {
iframeDoc = iframeDoc.document;
}
return iframeDoc;
}
|
javascript
|
{
"resource": ""
}
|
q23640
|
quadrant
|
train
|
function quadrant(point, node, fallback) {
if (point.x < node.x && point.y < node.y) return 1;
if (point.x > node.x && point.y < node.y) return 2;
if (point.x > node.x && point.y > node.y) return 3;
if (point.x < node.x && point.y > node.y) return 4;
return fallback;
}
|
javascript
|
{
"resource": ""
}
|
q23641
|
adjustQuadrant
|
train
|
function adjustQuadrant(quadrant, point, opposite) {
if ((opposite.x == point.x) || (opposite.y == point.y)) return quadrant;
var flipHorizontally = [4, 3, 2, 1]
var flipVertically = [2, 1, 4, 3]
var oppositeQuadrant = (opposite.y < point.y) ?
((opposite.x < point.x) ? 2 : 1) :
((opposite.x < point.x) ? 3 : 4);
// if an opposite relation end is in the same quadrant as a label, we need to flip the label
if (oppositeQuadrant === quadrant) {
if (config.direction === 'LR') return flipHorizontally[quadrant-1];
if (config.direction === 'TD') return flipVertically[quadrant-1];
}
return quadrant;
}
|
javascript
|
{
"resource": ""
}
|
q23642
|
_updateAllElements
|
train
|
function _updateAllElements({ updateCache } = {}) {
elements.forEach(element => {
_updateElementPosition(element);
if (updateCache) {
element.setCachedAttributes(view, scroll);
}
});
// reset ticking so more animations can be called
ticking = false;
}
|
javascript
|
{
"resource": ""
}
|
q23643
|
_setViewSize
|
train
|
function _setViewSize() {
if (hasScrollContainer) {
const width = viewEl.offsetWidth;
const height = viewEl.offsetHeight;
return view.setSize(width, height);
}
const html = document.documentElement;
const width = window.innerWidth || html.clientWidth;
const height = window.innerHeight || html.clientHeight;
return view.setSize(width, height);
}
|
javascript
|
{
"resource": ""
}
|
q23644
|
get
|
train
|
function get (target, key, receiver) {
const result = Reflect.get(target, key, receiver)
// do not register (observable.prop -> reaction) pairs for well known symbols
// these symbols are frequently retrieved in low level JavaScript under the hood
if (typeof key === 'symbol' && wellKnownSymbols.has(key)) {
return result
}
// register and save (observable.prop -> runningReaction)
registerRunningReactionForOperation({ target, key, receiver, type: 'get' })
// if we are inside a reaction and observable.prop is an object wrap it in an observable too
// this is needed to intercept property access on that object too (dynamic observable tree)
const observableResult = rawToProxy.get(result)
if (hasRunningReaction() && typeof result === 'object' && result !== null) {
if (observableResult) {
return observableResult
}
// do not violate the none-configurable none-writable prop get handler invariant
// fall back to none reactive mode in this case, instead of letting the Proxy throw a TypeError
const descriptor = Reflect.getOwnPropertyDescriptor(target, key)
if (
!descriptor ||
!(descriptor.writable === false && descriptor.configurable === false)
) {
return observable(result)
}
}
// otherwise return the observable wrapper if it is already created and cached or the raw object
return observableResult || result
}
|
javascript
|
{
"resource": ""
}
|
q23645
|
set
|
train
|
function set (target, key, value, receiver) {
// make sure to do not pollute the raw object with observables
if (typeof value === 'object' && value !== null) {
value = proxyToRaw.get(value) || value
}
// save if the object had a descriptor for this key
const hadKey = hasOwnProperty.call(target, key)
// save if the value changed because of this set operation
const oldValue = target[key]
// execute the set operation before running any reaction
const result = Reflect.set(target, key, value, receiver)
// do not queue reactions if the target of the operation is not the raw receiver
// (possible because of prototypal inheritance)
if (target !== proxyToRaw.get(receiver)) {
return result
}
// queue a reaction if it's a new property or its value changed
if (!hadKey) {
queueReactionsForOperation({ target, key, value, receiver, type: 'add' })
} else if (value !== oldValue) {
queueReactionsForOperation({
target,
key,
value,
oldValue,
receiver,
type: 'set'
})
}
return result
}
|
javascript
|
{
"resource": ""
}
|
q23646
|
splitDecimal
|
train
|
function splitDecimal(numStr) {
var allowNegative = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var hasNagation = numStr[0] === '-';
var addNegation = hasNagation && allowNegative;
numStr = numStr.replace('-', '');
var parts = numStr.split('.');
var beforeDecimal = parts[0];
var afterDecimal = parts[1] || '';
return {
beforeDecimal: beforeDecimal,
afterDecimal: afterDecimal,
hasNagation: hasNagation,
addNegation: addNegation
};
}
|
javascript
|
{
"resource": ""
}
|
q23647
|
limitToScale
|
train
|
function limitToScale(numStr, scale, fixedDecimalScale) {
var str = '';
var filler = fixedDecimalScale ? '0' : '';
for (var i = 0; i <= scale - 1; i++) {
str += numStr[i] || filler;
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q23648
|
roundToPrecision
|
train
|
function roundToPrecision(numStr, scale, fixedDecimalScale) {
//if number is empty don't do anything return empty string
if (['', '-'].indexOf(numStr) !== -1) return numStr;
var shoudHaveDecimalSeparator = numStr.indexOf('.') !== -1 && scale;
var _splitDecimal = splitDecimal(numStr),
beforeDecimal = _splitDecimal.beforeDecimal,
afterDecimal = _splitDecimal.afterDecimal,
hasNagation = _splitDecimal.hasNagation;
var roundedDecimalParts = parseFloat("0.".concat(afterDecimal || '0')).toFixed(scale).split('.');
var intPart = beforeDecimal.split('').reverse().reduce(function (roundedStr, current, idx) {
if (roundedStr.length > idx) {
return (Number(roundedStr[0]) + Number(current)).toString() + roundedStr.substring(1, roundedStr.length);
}
return current + roundedStr;
}, roundedDecimalParts[0]);
var decimalPart = limitToScale(roundedDecimalParts[1] || '', Math.min(scale, afterDecimal.length), fixedDecimalScale);
var negation = hasNagation ? '-' : '';
var decimalSeparator = shoudHaveDecimalSeparator ? '.' : '';
return "".concat(negation).concat(intPart).concat(decimalSeparator).concat(decimalPart);
}
|
javascript
|
{
"resource": ""
}
|
q23649
|
findChangedIndex
|
train
|
function findChangedIndex(prevValue, newValue) {
var i = 0,
j = 0;
var prevLength = prevValue.length;
var newLength = newValue.length;
while (prevValue[i] === newValue[i] && i < prevLength) {
i++;
} //check what has been changed from last
while (prevValue[prevLength - 1 - j] === newValue[newLength - 1 - j] && newLength - j > i && prevLength - j > i) {
j++;
}
return {
start: i,
end: prevLength - j
};
}
|
javascript
|
{
"resource": ""
}
|
q23650
|
limit
|
train
|
function limit(val, max) {
if (val.length === 1 && val[0] > max[0]) {
val = '0' + val;
}
if (val.length === 2) {
if (Number(val) === 0) {
val = '01';
//this can happen when user paste number
} else if (val > max) {
val = max;
}
}
return val;
}
|
javascript
|
{
"resource": ""
}
|
q23651
|
readSpecFile
|
train
|
function readSpecFile(file, options) {
if (options.verbose > 1) {
file ? console.error('GET ' + file) : console.error('GET <stdin>');
}
if (!file) {
// standard input
return readFileStdinAsync();
} else if (file && file.startsWith('http')) {
// remote file
return fetch(file).then(res => {
if (res.status !== 200) {
throw new Error(`Received status code ${res.status}`);
}
return res.text();
})
} else {
// local file
// TODO error handlers?
return readFileAsync(file, 'utf8');
}
}
|
javascript
|
{
"resource": ""
}
|
q23652
|
cleanPath
|
train
|
function cleanPath( txt ) {
var ch;
var j;
if ( txt.charCodeAt( 0 ) === 34 ) {
j = 1;
for ( j = 1; j < txt.length; j++ ) {
ch = txt.charCodeAt( j );
if ( ch === 34 ) {
txt = txt.slice( 1, j );
break;
}
}
}
j = txt.indexOf( '/docs/types/' );
if ( j >= 0 ) {
txt = txt.slice( 0, j );
} else {
j = txt.indexOf( '/index.d' );
if ( j >= 0 ) {
txt = txt.slice( 0, j );
}
}
return txt;
}
|
javascript
|
{
"resource": ""
}
|
q23653
|
cleanTitle
|
train
|
function cleanTitle( el ) {
var txt = cleanPath( el.innerHTML );
var idx = txt.indexOf( 'stdlib' );
if ( idx === -1 || idx === 1 ) { // e.g., '@stdlib/types/iter'
txt = 'stdlib | ' + txt;
} else if ( txt.indexOf( ' | stdlib' ) === txt.length-9 ) { // e.g., 'foo/bar | stdlib'
txt = 'stdlib | ' + txt.slice( 0, -9 );
}
el.innerHTML = txt;
}
|
javascript
|
{
"resource": ""
}
|
q23654
|
cleanLinks
|
train
|
function cleanLinks( el ) {
var i;
for ( i = 0; i < el.length; i++ ) {
el[ i ].innerHTML = cleanPath( el[ i ].innerHTML );
}
}
|
javascript
|
{
"resource": ""
}
|
q23655
|
cleanHeadings
|
train
|
function cleanHeadings( el ) {
var i;
for ( i = 0; i < el.length; i++ ) {
el[ i ].innerHTML = cleanHeading( el[ i ].innerHTML );
}
}
|
javascript
|
{
"resource": ""
}
|
q23656
|
updateDescription
|
train
|
function updateDescription( txt ) {
var ch;
if ( txt.length === 0 ) {
return txt;
}
ch = txt[ 0 ].toUpperCase();
if ( ch !== txt[ 0 ] ) {
txt = ch + txt.slice( 1 );
}
if ( txt.charCodeAt( txt.length-1 ) !== 46 ) { // .
txt += '.';
}
return txt;
}
|
javascript
|
{
"resource": ""
}
|
q23657
|
main
|
train
|
function main() {
var el;
el = document.querySelector( 'title' );
cleanTitle( el );
el = document.querySelectorAll( '.tsd-kind-external-module a' );
cleanLinks( el );
el = document.querySelectorAll( '.tsd-is-not-exported a' );
cleanLinks( el );
el = document.querySelectorAll( '.tsd-breadcrumb a' );
cleanLinks( el );
el = document.querySelectorAll( '.tsd-page-title h1' );
cleanHeadings( el );
el = document.querySelectorAll( '.tsd-description .tsd-parameters .tsd-comment p' );
updateDescriptions( el );
el = document.querySelectorAll( '.tsd-description .tsd-returns-title + p' );
updateDescriptions( el );
}
|
javascript
|
{
"resource": ""
}
|
q23658
|
transform
|
train
|
function transform( node ) {
return {
'name': node.name,
'description': node.description || '',
'access': node.access || '',
'virtual': !!node.virtual
};
}
|
javascript
|
{
"resource": ""
}
|
q23659
|
transform
|
train
|
function transform( node ) {
var type;
if ( node.type ) {
if ( node.type.length === 1 ) {
type = node.type[ 0 ];
} else {
type = node.type;
}
} else {
type = '';
}
return {
'name': node.name,
'description': node.description || '',
'type': type,
'access': node.access || '',
'virtual': !!node.virtual
};
}
|
javascript
|
{
"resource": ""
}
|
q23660
|
benchmark
|
train
|
function benchmark( b ) {
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
// TODO: synchronous task
if ( TODO/* TODO: condition */ ) {
b.fail( 'something went wrong' );
}
}
b.toc();
if ( TODO/* TODO: condition */ ) {
b.fail( 'something went wrong' );
}
b.pass( 'benchmark finished' );
b.end();
}
|
javascript
|
{
"resource": ""
}
|
q23661
|
transform
|
train
|
function transform( nodes ) {
var type;
var desc;
if ( nodes[ 0 ].type ) {
if ( nodes[ 0 ].type.names.length === 1 ) {
type = nodes[ 0 ].type.names[ 0 ];
} else {
type = nodes[ 0 ].type.names;
}
} else {
type = '';
}
desc = nodes[ 0 ].description || '';
return {
'type': type,
'description': desc
};
}
|
javascript
|
{
"resource": ""
}
|
q23662
|
getMethodReturnDoc
|
train
|
function getMethodReturnDoc(methodPath) {
const functionExpression = methodPath.get('value');
if (functionExpression.node.returnType) {
const returnType = getTypeAnnotation(functionExpression.get('returnType'));
if (returnType && t.Flow.check(returnType.node)) {
return { type: getFlowType(returnType) };
} else if (returnType) {
return { type: getTSType(returnType) };
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q23663
|
amendComposes
|
train
|
function amendComposes(documentation, path) {
const moduleName = resolveToModule(path);
if (moduleName) {
documentation.addComposes(moduleName);
}
}
|
javascript
|
{
"resource": ""
}
|
q23664
|
buildBuilder
|
train
|
function buildBuilder(mqttClient, opts) {
var connection;
connection = tls.connect(opts);
function handleTLSerrors(err) {
mqttClient.emit('error', err);
connection.end();
}
connection.on('secureConnect', function() {
if (!connection.authorized) {
connection.emit('error', new Error('TLS not authorized'));
} else {
connection.removeListener('error', handleTLSerrors);
}
});
connection.on('error', handleTLSerrors);
return connection;
}
|
javascript
|
{
"resource": ""
}
|
q23665
|
errorToString
|
train
|
function errorToString(err) {
if (isUndefined(err)) {
return undefined;
} else if (err.toString().length > maxStatusDetailLength) {
return err.toString().substring(0, maxStatusDetailLength - 3) + '...';
} else {
return err.toString();
}
}
|
javascript
|
{
"resource": ""
}
|
q23666
|
validateChecksum
|
train
|
function validateChecksum(fileName, checksum, cb) {
if (isUndefined(checksum) || isUndefined(checksum.hashAlgorithm)) {
cb();
return;
}
if (isUndefined(checksum.inline) || isUndefined(checksum.inline.value)) {
cb(new Error('Installed jobs agent only supports inline checksum value provided in job document'));
return;
}
var hash;
try {
hash = crypto.createHash(checksum.hashAlgorithm);
} catch (err) {
cb(new Error('Unsupported checksum hash algorithm: ' + checksum.hashAlgorithm));
return;
}
var stream = fs.createReadStream(fileName);
stream.on('data', function (data) {
hash.update(data, 'utf8');
}).on('end', function () {
if (hash.digest('hex') !== checksum.inline.value) {
var err = new Error('Checksum mismatch');
err.fileName = fileName;
cb(err);
} else {
cb();
}
}).on('error', function (err) {
err.fileName = fileName;
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q23667
|
validateSignature
|
train
|
function validateSignature(fileName, signature, cb) {
if (isUndefined(signature) || isUndefined(signature.codesign)) {
cb();
return;
}
if (isUndefined(codeSignCertFileName)) {
cb(new Error('No code sign certificate file specified'));
return;
}
var codeSignCert;
try {
codeSignCert = fs.readFileSync(codeSignCertFileName, 'utf8');
} catch (err) {
// unable to read codeSignCertFileName file
cb(new Error('Error encountered trying to read ' + codeSignCertFileName));
return;
}
var verify;
try {
verify = crypto.createVerify(signature.codesign.signatureAlgorithm);
} catch (err) {
console.warn('Unable to use signature algorithm: ' + signature.codesign.signatureAlgorithm + ' attempting to use default algorithm SHA256');
try {
verify = crypto.createVerify('SHA256');
} catch (err) {
cb(err);
return;
}
}
var stream = fs.createReadStream(fileName);
stream.on('data', function (data) {
verify.write(data);
}).on('end', function () {
verify.end();
try {
if (!verify.verify(codeSignCert, signature.codesign.signature, 'base64')) {
var err = new Error('Signature validation failed');
err.fileName = fileName;
cb(err);
} else {
cb();
}
} catch (err) {
cb(err);
return;
}
}).on('error', function (err) {
err.fileName = fileName;
cb(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q23668
|
backupFiles
|
train
|
function backupFiles(job, iFile, cb) {
if (isUndefined(cb)) {
cb = iFile;
iFile = 0;
}
if (iFile === job.document.files.length) {
cb();
return;
}
var file = job.document.files[iFile];
if (isUndefined(file)) {
cb(new Error('empty file specification'));
return;
}
if (isUndefined(file.fileName)) {
cb(new Error('fileName missing'));
return;
}
var filePath = path.resolve(job.document.workingDirectory || '', file.fileName);
if (!fs.existsSync(filePath)) {
backupFiles(job, iFile + 1, cb);
return;
}
job.inProgress({ operation: job.operation, step: 'backing up existing file', fileName: file.fileName }, function(err) {
showJobsError(err);
copyFile(filePath, filePath + '.old', function(copyFileError) {
if (isUndefined(copyFileError)) {
backupFiles(job, iFile + 1, cb);
} else {
cb(copyFileError);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23669
|
rollbackFiles
|
train
|
function rollbackFiles(job, iFile, cb) {
if (isUndefined(cb)) {
cb = iFile;
iFile = 0;
}
if (iFile === job.document.files.length) {
cb();
return;
}
var file = job.document.files[iFile];
var filePath = path.resolve(job.document.workingDirectory || '', file.fileName);
if (!fs.existsSync(filePath + '.old')) {
rollbackFiles(job, iFile + 1, cb);
return;
}
job.inProgress({ operation: job.operation, step: 'rolling back file', fileName: file.fileName }, function(err) {
showJobsError(err);
copyFile(filePath + '.old', filePath, function(fileErr) {
rollbackFiles(job, iFile + 1, function(rollbackError) {
cb(rollbackError || fileErr);
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23670
|
downloadFiles
|
train
|
function downloadFiles(job, iFile, cb) {
if (isUndefined(cb)) {
cb = iFile;
iFile = 0;
}
if (iFile === job.document.files.length) {
cb();
return;
}
var file = job.document.files[iFile];
var filePath = path.resolve(job.document.workingDirectory || '', file.fileName);
if (isUndefined(file.fileSource) || isUndefined(file.fileSource.url)) {
job.inProgress({ operation: job.operation, step: 'download error, rollback pending', fileName: file.fileName }, function(err) {
showJobsError(err);
cb(new Error('fileSource url missing'));
});
return;
}
job.inProgress({ step: 'downloading', fileName: file.fileName }, function(err) {
showJobsError(err);
downloadFile(file.fileSource.url, filePath, function(downloadError) {
if (isUndefined(downloadError)) {
validateChecksum(filePath, file.checksum, function(checksumError) {
if (isUndefined(checksumError)) {
validateSignature(filePath, file.signature, function(signatureError) {
if (isUndefined(signatureError)) {
downloadFiles(job, iFile + 1, cb);
} else {
cb(signatureError);
}
});
} else {
cb(checksumError);
}
});
} else {
cb(downloadError);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23671
|
updateInstalledPackage
|
train
|
function updateInstalledPackage(updatedPackage) {
var packageIndex = installedPackages.findIndex(function(element) {
return (element.packageName === updatedPackage.packageName);
});
if (packageIndex < 0) {
packageIndex = installedPackages.length;
installedPackages.push(updatedPackage);
} else {
installedPackages[packageIndex] = updatedPackage;
}
fs.writeFileSync(installedPackagesDataFileName, JSON.stringify(installedPackages));
}
|
javascript
|
{
"resource": ""
}
|
q23672
|
startPackage
|
train
|
function startPackage(package, cb) {
if (isUndefined(packageRuntimes[package.packageName])) {
packageRuntimes[package.packageName] = {};
}
var packageRuntime = packageRuntimes[package.packageName];
if (!isUndefined(packageRuntime.process)) {
cb(new Error('package already running'));
return;
}
packageRuntime.startupTimer = setTimeout(function() {
packageRuntime.startupTimer = null;
cb();
}, startupTimout * 1000);
packageRuntime.process = exec(package.launchCommand, { cwd: (!isUndefined(package.workingDirectory) ? path.resolve(package.workingDirectory) : undefined) }, function(err) {
packageRuntime.process = null;
if (!isUndefined(packageRuntime.startupTimer)) {
clearTimeout(packageRuntime.startupTimer);
packageRuntime.startupTimer = null;
cb(err);
} else if (!isUndefined(packageRuntime.killTimer)) {
clearTimeout(packageRuntime.killTimer);
packageRuntime.killTimer = null;
packageRuntime.killedCallback();
packageRuntime.killedCallback = null;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q23673
|
shutdownHandler
|
train
|
function shutdownHandler(job) {
// Change status to IN_PROGRESS
job.inProgress({ operation: job.operation, step: 'attempting' }, function(err) {
showJobsError(err);
var delay = (isUndefined(job.document.delay) ? '0' : job.document.delay.toString());
// Check for adequate permissions to perform shutdown, use -k option to do dry run
//
// User account running node.js agent must have passwordless sudo access on /sbin/shutdown
// Recommended online search for permissions setup instructions https://www.google.com/search?q=passwordless+sudo+access+instructions
exec('sudo /sbin/shutdown -k +' + delay, function (err) {
if (!isUndefined(err)) {
job.failed({ operation: job.operation, errorCode: 'ERR_SYSTEM_CALL_FAILED', errorMessage: 'unable to execute shutdown, check passwordless sudo permissions on agent',
error: errorToString(err) }, showJobsError);
} else {
job.succeeded({ operation: job.operation, step: 'initiated' }, function (err) {
showJobsError(err);
exec('sudo /sbin/shutdown +' + delay);
});
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q23674
|
rebootHandler
|
train
|
function rebootHandler(job) {
// Check if the reboot job has not yet been initiated
if (job.status.status === 'QUEUED' ||
isUndefined(job.status.statusDetails) ||
isUndefined(job.status.statusDetails.step)) {
// Change status to IN_PROGRESS
job.inProgress({ operation: job.operation, step: 'initiated' }, function(err) {
showJobsError(err);
var delay = (isUndefined(job.document.delay) ? '0' : job.document.delay.toString());
// User account running node.js agent must have passwordless sudo access on /sbin/shutdown
// Recommended online search for permissions setup instructions https://www.google.com/search?q=passwordless+sudo+access+instructions
exec('sudo /sbin/shutdown -r +' + delay, function (err) {
if (!isUndefined(err)) {
job.failed({ operation: job.operation, errorCode: 'ERR_SYSTEM_CALL_FAILED', errorMessage: 'unable to execute reboot, check passwordless sudo permissions on agent',
error: errorToString(err) }, showJobsError);
}
});
});
// Check if the reboot operation has already been successfully initiated
} else if (job.status.statusDetails.step === 'initiated') {
job.succeeded({ operation: job.operation, step: 'rebooted' }, showJobsError);
} else {
job.failed({ operation: job.operation, errorCode: 'ERR_UNEXPECTED', errorMessage: 'reboot job execution in unexpected state' }, showJobsError);
}
}
|
javascript
|
{
"resource": ""
}
|
q23675
|
systemStatusHandler
|
train
|
function systemStatusHandler(job) {
var packageNames = '[';
for (var i = 0; i < installedPackages.length; i++) {
packageNames += installedPackages[i].packageName + ((i !== installedPackages.length - 1) ? ', ' : '');
}
packageNames += ']';
job.succeeded({
operation: job.operation,
installedPackages: packageNames,
arch: process.arch,
nodeVersion: process.version,
cwd: process.cwd(),
platform: process.platform,
title: process.title,
uptime: process.uptime()
}, showJobsError);
}
|
javascript
|
{
"resource": ""
}
|
q23676
|
_markConnectionStable
|
train
|
function _markConnectionStable() {
currentReconnectTimeMs = baseReconnectTimeMs;
device.options.reconnectPeriod = currentReconnectTimeMs;
//
// Mark this timeout as expired
//
connectionTimer = null;
connectionState = 'stable';
}
|
javascript
|
{
"resource": ""
}
|
q23677
|
_trimOfflinePublishQueueIfNecessary
|
train
|
function _trimOfflinePublishQueueIfNecessary() {
var rc = true;
if ((offlineQueueMaxSize > 0) &&
(offlinePublishQueue.length >= offlineQueueMaxSize)) {
//
// The queue has reached its maximum size, trim it
// according to the defined drop behavior.
//
if (offlineQueueDropBehavior === 'oldest') {
offlinePublishQueue.shift();
} else {
rc = false;
}
}
return rc;
}
|
javascript
|
{
"resource": ""
}
|
q23678
|
_drainOperationQueue
|
train
|
function _drainOperationQueue() {
//
// Handle our active subscriptions first, using a cloned
// copy of the array. We shift them out one-by-one until
// all have been processed, leaving the official record
// of active subscriptions untouched.
//
var subscription = clonedSubscriptions.shift();
if (!isUndefined(subscription)) {
//
// If the 3rd argument (namely callback) is not present, we will
// use two-argument form to call mqtt.Client#subscribe(), which
// supports both subscribe(topics, options) and subscribe(topics, callback).
//
if (!isUndefined(subscription.callback)) {
device.subscribe(subscription.topic, subscription.options, subscription.callback);
} else {
device.subscribe(subscription.topic, subscription.options);
}
} else {
//
// If no remaining active subscriptions to process,
// then handle subscription requests queued while offline.
//
var req = offlineSubscriptionQueue.shift();
if (!isUndefined(req)) {
_updateSubscriptionCache(req.type, req.topics, req.options);
if (req.type === 'subscribe') {
if (!isUndefined(req.callback)) {
device.subscribe(req.topics, req.options, req.callback);
} else {
device.subscribe(req.topics, req.options);
}
} else if (req.type === 'unsubscribe') {
device.unsubscribe(req.topics, req.callback);
}
} else {
//
// If no active or queued subscriptions remaining to process,
// then handle queued publish operations.
//
var offlinePublishMessage = offlinePublishQueue.shift();
if (!isUndefined(offlinePublishMessage)) {
device.publish(offlinePublishMessage.topic,
offlinePublishMessage.message,
offlinePublishMessage.options,
offlinePublishMessage.callback);
}
if (offlinePublishQueue.length === 0) {
//
// The subscription and offlinePublishQueue queues are fully drained,
// cancel the draining timer.
//
clearInterval(drainingTimer);
drainingTimer = null;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q23679
|
AggregatorFactory
|
train
|
function AggregatorFactory(aggregatorFn) {
return metrics => {
if (metrics.length === 0) return;
const result = {
help: metrics[0].help,
name: metrics[0].name,
type: metrics[0].type,
values: [],
aggregator: metrics[0].aggregator
};
// Gather metrics by metricName and labels.
const byLabels = new Grouper();
metrics.forEach(metric => {
metric.values.forEach(value => {
const key = hashObject(value.labels);
byLabels.add(`${value.metricName}_${key}`, value);
});
});
// Apply aggregator function to gathered metrics.
byLabels.forEach(values => {
if (values.length === 0) return;
const valObj = {
value: aggregatorFn(values),
labels: values[0].labels
};
if (values[0].metricName) {
valObj.metricName = values[0].metricName;
}
// NB: Timestamps are omitted.
result.values.push(valObj);
});
return result;
};
}
|
javascript
|
{
"resource": ""
}
|
q23680
|
HappyForegroundThreadPool
|
train
|
function HappyForegroundThreadPool(config) {
var rpcHandler, worker;
return {
size: config.size,
start: function(compilerId, compiler, compilerOptions, done) {
var fakeCompiler = new HappyFakeCompiler({
id: 'foreground',
compilerId: compilerId,
send: function executeCompilerRPC(message) {
// TODO: DRY alert, see HappyThread.js
rpcHandler.execute(message.data.type, message.data.payload, function serveRPCResult(error, result) {
fakeCompiler._handleResponse(message.id, {
payload: {
error: error || null,
result: result || null
}
});
});
}
});
fakeCompiler.configure(compiler.options);
rpcHandler = new HappyRPCHandler();
rpcHandler.registerActiveCompiler(compilerId, compiler);
worker = new HappyWorker({
compiler: fakeCompiler,
loaders: config.loaders
});
done();
},
isRunning: function() {
return !!worker;
},
stop: function(/*compilerId*/) {
worker = null;
rpcHandler = null;
},
compile: function(loaderId, loader, params, done) {
rpcHandler.registerActiveLoader(loaderId, loader);
worker.compile(params, function(error, data) {
rpcHandler.unregisterActiveLoader(loaderId);
done(error, data);
});
},
};
}
|
javascript
|
{
"resource": ""
}
|
q23681
|
enableRerouting
|
train
|
function enableRerouting() {
if (enabled)
return;
enabled = true;
const connect = Net.Socket.prototype.connect;
Net.Socket.prototype.connect = function(options, callback) {
const hasNormalizedArgs = Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(options).length > 0;
const isNode8 = Array.isArray(options) && hasNormalizedArgs;
if (isNode8) {
const reroutedOptions = rerouteOptions(options[0]);
callback = options[1];
return connect.call(this, reroutedOptions, callback);
} else if (typeof options === 'object') {
const reroutedOptions = rerouteOptions(options);
return connect.call(this, reroutedOptions, callback);
} else
return connect.apply(this, arguments);
};
}
|
javascript
|
{
"resource": ""
}
|
q23682
|
assertMatch
|
train
|
function assertMatch(actual, expected, message) {
if (isRegExp(expected))
assert(expected.test(actual), message || `Expected "${actual}" to match "${expected}"`);
else if (typeof expected === 'function')
assert(expected(actual), message);
else
assert.deepEqual(actual, expected, message);
}
|
javascript
|
{
"resource": ""
}
|
q23683
|
ontick
|
train
|
function ontick(next) {
// No point in waiting that long
if (next >= timeoutOn) {
timeout();
return;
}
const activeWindow = eventLoop.active;
if (completionFunction && activeWindow.document.documentElement)
try {
const waitFor = Math.max(next - Date.now(), 0);
// Event processed, are we ready to complete?
const completed = completionFunction(activeWindow, waitFor);
if (completed)
done();
} catch (error) {
done(error);
}
}
|
javascript
|
{
"resource": ""
}
|
q23684
|
done
|
train
|
function done(error) {
global.clearTimeout(timer);
eventLoop.removeListener('tick', ontick);
eventLoop.removeListener('idle', done);
eventLoop.browser.removeListener('error', done);
--eventLoop.waiting;
try {
callback(error);
} catch (error) {
// If callback makes an assertion that fails, we end here.
// If we throw error synchronously, it gets swallowed.
setImmediate(function() {
throw error;
});
}
}
|
javascript
|
{
"resource": ""
}
|
q23685
|
changes
|
train
|
function changes() {
const version = require('./package.json').version;
const changelog = File.readFileSync('CHANGELOG.md', 'utf-8');
const match = changelog.match(/^## Version (.*) .*\n([\S\s]+?)\n##/m);
assert(match, 'CHANGELOG.md missing entry: ## Version ' + version);
assert.equal(match[1], version, 'CHANGELOG.md missing entry for version ' + version);
const changes = match[2].trim();
assert(changes, 'CHANGELOG.md empty entry for version ' + version);
File.writeFileSync('.changes', changes);
}
|
javascript
|
{
"resource": ""
}
|
q23686
|
decompressStream
|
train
|
function decompressStream(stream, headers) {
const transferEncoding = headers.get('Transfer-Encoding');
const contentEncoding = headers.get('Content-Encoding');
if (contentEncoding === 'deflate' || transferEncoding === 'deflate')
return stream.pipe( Zlib.createInflate() );
if (contentEncoding === 'gzip' || transferEncoding === 'gzip')
return stream.pipe( Zlib.createGunzip() );
return stream;
}
|
javascript
|
{
"resource": ""
}
|
q23687
|
click
|
train
|
function click() {
const clickEvent = input.ownerDocument.createEvent('HTMLEvents');
clickEvent.initEvent('click', true, true);
const labelElementImpl = domSymbolTree.parent(idlUtils.implForWrapper(input));
const dispatchResult = input.dispatchEvent(clickEvent);
input._click && input._click(clickEvent);
return dispatchResult;
}
|
javascript
|
{
"resource": ""
}
|
q23688
|
windowLoaded
|
train
|
function windowLoaded(event) {
document.removeEventListener('DOMContentLoaded', windowLoaded);
// JSDom > 7.1 does not allow re-dispatching the same event, so
// a copy of the event needs to be created for the new dispatch
const windowContentLoaded = document.createEvent('HTMLEvents');
windowContentLoaded.initEvent('DOMContentLoaded', false, false);
window.dispatchEvent(windowContentLoaded);
}
|
javascript
|
{
"resource": ""
}
|
q23689
|
createDocument
|
train
|
function createDocument(args) {
const { browser } = args;
const features = {
FetchExternalResources: [],
ProcessExternalResources: [],
MutationEvents: '2.0'
};
const window = new Window({
parsingMode: 'html',
contentType: 'text/html',
url: args.url,
referrer: args.referrer
});
const { document } = window;
const documentImpl = idlUtils.implForWrapper(document)
if (args.browser.hasFeature('scripts', true)) {
features.FetchExternalResources.push('script');
features.ProcessExternalResources.push('script');
window._runScripts = 'dangerously';
}
if (args.browser.hasFeature('css', false)) {
features.FetchExternalResources.push('css');
features.FetchExternalResources.push('link');
}
if (args.browser.hasFeature('img', false))
features.FetchExternalResources.push('img');
if (args.browser.hasFeature('iframe', true))
features.FetchExternalResources.push('iframe');
browserFeatures.applyDocumentFeatures(documentImpl, features);
setupWindow(window, args);
// Give event handler chance to register listeners.
args.browser.emit('loading', document);
return document;
}
|
javascript
|
{
"resource": ""
}
|
q23690
|
parseResponse
|
train
|
function parseResponse({ browser, history, document, response }) {
const window = document.defaultView;
window._request = response.request;
window._response = response;
history.updateLocation(window, response._url);
const done = window._eventQueue.waitForCompletion();
response
._consume()
.then(function(body) {
const contentType = response.headers.get('Content-Type') || '';
const html = getHTMLFromResponseBody(body, contentType);
response.body = html;
document.write(html || '<html></html>');
document.close();
browser.emit('loaded', document);
if (response.status >= 400)
throw new Error(`Server returned status code ${response.status} from ${response.url}`);
if (!document.documentElement)
throw new Error(`Could not parse document at ${response.url}`);
})
.then(function() {
// Handle meta refresh. Automatically reloads new location and counts
// as a redirect.
//
// If you need to check the page before refresh takes place, use this:
// browser.wait({
// function: function() {
// return browser.query('meta[http-equiv="refresh"]');
// }
// });
const refresh = getMetaRefresh(document);
if (refresh) {
const { refreshTimeout } = refresh;
const { refreshURL } = refresh;
window._eventQueue.setTimeout(function() {
// Allow completion function to run
window._eventQueue.enqueue(function() {
window._eventQueue.enqueue(function() {
// Count a meta-refresh in the redirects count.
history.replace(refreshURL);
// This results in a new window getting loaded
const newWindow = history.current.window;
newWindow.addEventListener('load', function() {
++newWindow._request._redirectCount;
});
});
});
}, refreshTimeout * 1000);
}
})
.catch(function(error) {
browser.emit('error', error);
})
.then(done);
}
|
javascript
|
{
"resource": ""
}
|
q23691
|
expandQNames
|
train
|
function expandQNames(xpath) {
var namespaces = constants.XmlNamespaces;
var pathParts = xpath.split('/');
for (var i=0; i < pathParts.length; i++) {
if (pathParts[i].indexOf(':') !== -1) {
var QNameParts = pathParts[i].split(':');
if (QNameParts.length !== 2) {
throw new Error('Unable to parse XPath string : ' + xpath + ' : with QName : ' + pathParts[i]);
}
var expandedPath = XPATH_PATH_TEMPLATE.replace('LOCAL_NAME', QNameParts[1]);
expandedPath = expandedPath.replace('NAMESPACE', namespaces[QNameParts[0]]);
pathParts[i] = expandedPath;
}
}
return pathParts.join('/');
}
|
javascript
|
{
"resource": ""
}
|
q23692
|
train
|
function(node) {
var doc = '';
var sibling = node.firstChild;
var serializer = new XMLSerializer();
while (sibling) {
if (this.isElementNode(sibling)) {
doc += serializer.serializeToString(sibling);
}
sibling = sibling.nextSibling;
}
return doc !== '' ? doc : null;
}
|
javascript
|
{
"resource": ""
}
|
|
q23693
|
train
|
function(node) {
var sibling = node.firstChild;
while (sibling && !sibling.data) {
sibling = sibling.nextSibling;
}
return sibling.data ? sibling.data : null;
}
|
javascript
|
{
"resource": ""
}
|
|
q23694
|
Authority
|
train
|
function Authority(authorityUrl, validateAuthority) {
this._log = null;
this._url = url.parse(authorityUrl);
this._validateAuthorityUrl();
this._validated = !validateAuthority;
this._host = null;
this._tenant = null;
this._parseAuthority();
this._authorizationEndpoint = null;
this._tokenEndpoint = null;
this._deviceCodeEndpoint = null;
this._isAdfsAuthority = (this._tenant.toLowerCase() === "adfs");
}
|
javascript
|
{
"resource": ""
}
|
q23695
|
train
|
function(options) {
if (!options) {
options = {};
}
if (options.log) {
if (!_.isFunction(options.log)) {
throw new Error('setLogOptions expects the log key in the options parameter to be a function');
}
} else {
// if no log function was passed set it to a default no op function.
options.log = function() {};
}
if (options.level) {
var level = options.level;
if (level < 0 || level > 3) {
throw new Error('setLogOptions expects the level key to be in the range 0 to 3 inclusive');
}
} else {
options.level = this.LOGGING_LEVEL.ERROR;
}
if (options.loggingWithPII != true) {
options.loggingWithPII = false;
}
this.LogOptions = options;
}
|
javascript
|
{
"resource": ""
}
|
|
q23696
|
SelfSignedJwt
|
train
|
function SelfSignedJwt(callContext, authority, clientId) {
this._log = new Logger('SelfSignedJwt', callContext._logContext);
this._callContext = callContext;
this._authority = authority;
this._tokenEndpoint = authority.tokenEndpoint;
this._clientId = clientId;
}
|
javascript
|
{
"resource": ""
}
|
q23697
|
CacheDriver
|
train
|
function CacheDriver(callContext, authority, resource, clientId, cache, refreshFunction) {
this._callContext = callContext;
this._log = new Logger('CacheDriver', callContext._logContext);
this._authority = authority;
this._resource = resource;
this._clientId = clientId;
this._cache = cache || nopCache;
this._refreshFunction = refreshFunction;
}
|
javascript
|
{
"resource": ""
}
|
q23698
|
OAuth2Client
|
train
|
function OAuth2Client(callContext, authority) {
this._tokenEndpoint = authority.tokenEndpoint;
this._deviceCodeEndpoint = authority.deviceCodeEndpoint;
this._log = new Logger('OAuth2Client', callContext._logContext);
this._callContext = callContext;
this._cancelPollingRequest = false;
}
|
javascript
|
{
"resource": ""
}
|
q23699
|
train
|
function (response, body) {
var tokenResponse;
try {
tokenResponse = self._handlePollingResponse(body);
} catch (e) {
self._log.error('Error validating get token response', e, true);
callback(null, e);
return;
}
callback(null, tokenResponse);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.