id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
|
|---|---|---|---|---|---|---|---|---|---|---|---|
8,600
|
babel/minify
|
packages/babel-plugin-minify-simplify/src/if-statement.js
|
conditionalReturnToGuards
|
function conditionalReturnToGuards(path) {
const { node } = path;
if (
!path.inList ||
!path.get("consequent").isBlockStatement() ||
node.alternate
) {
return;
}
let ret;
let test;
const exprs = [];
const statements = node.consequent.body;
for (let i = 0, statement; (statement = statements[i]); i++) {
if (t.isExpressionStatement(statement)) {
exprs.push(statement.expression);
} else if (t.isIfStatement(statement)) {
if (i < statements.length - 1) {
// This isn't the last statement. Bail.
return;
}
if (statement.alternate) {
return;
}
if (!t.isReturnStatement(statement.consequent)) {
return;
}
ret = statement.consequent;
test = statement.test;
} else {
return;
}
}
if (!test || !ret) {
return;
}
exprs.push(test);
const expr = exprs.length === 1 ? exprs[0] : t.sequenceExpression(exprs);
const replacement = t.logicalExpression("&&", node.test, expr);
path.replaceWith(t.ifStatement(replacement, ret, null));
}
|
javascript
|
function conditionalReturnToGuards(path) {
const { node } = path;
if (
!path.inList ||
!path.get("consequent").isBlockStatement() ||
node.alternate
) {
return;
}
let ret;
let test;
const exprs = [];
const statements = node.consequent.body;
for (let i = 0, statement; (statement = statements[i]); i++) {
if (t.isExpressionStatement(statement)) {
exprs.push(statement.expression);
} else if (t.isIfStatement(statement)) {
if (i < statements.length - 1) {
// This isn't the last statement. Bail.
return;
}
if (statement.alternate) {
return;
}
if (!t.isReturnStatement(statement.consequent)) {
return;
}
ret = statement.consequent;
test = statement.test;
} else {
return;
}
}
if (!test || !ret) {
return;
}
exprs.push(test);
const expr = exprs.length === 1 ? exprs[0] : t.sequenceExpression(exprs);
const replacement = t.logicalExpression("&&", node.test, expr);
path.replaceWith(t.ifStatement(replacement, ret, null));
}
|
[
"function",
"conditionalReturnToGuards",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"if",
"(",
"!",
"path",
".",
"inList",
"||",
"!",
"path",
".",
"get",
"(",
"\"consequent\"",
")",
".",
"isBlockStatement",
"(",
")",
"||",
"node",
".",
"alternate",
")",
"{",
"return",
";",
"}",
"let",
"ret",
";",
"let",
"test",
";",
"const",
"exprs",
"=",
"[",
"]",
";",
"const",
"statements",
"=",
"node",
".",
"consequent",
".",
"body",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"statement",
";",
"(",
"statement",
"=",
"statements",
"[",
"i",
"]",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"t",
".",
"isExpressionStatement",
"(",
"statement",
")",
")",
"{",
"exprs",
".",
"push",
"(",
"statement",
".",
"expression",
")",
";",
"}",
"else",
"if",
"(",
"t",
".",
"isIfStatement",
"(",
"statement",
")",
")",
"{",
"if",
"(",
"i",
"<",
"statements",
".",
"length",
"-",
"1",
")",
"{",
"// This isn't the last statement. Bail.",
"return",
";",
"}",
"if",
"(",
"statement",
".",
"alternate",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"t",
".",
"isReturnStatement",
"(",
"statement",
".",
"consequent",
")",
")",
"{",
"return",
";",
"}",
"ret",
"=",
"statement",
".",
"consequent",
";",
"test",
"=",
"statement",
".",
"test",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"if",
"(",
"!",
"test",
"||",
"!",
"ret",
")",
"{",
"return",
";",
"}",
"exprs",
".",
"push",
"(",
"test",
")",
";",
"const",
"expr",
"=",
"exprs",
".",
"length",
"===",
"1",
"?",
"exprs",
"[",
"0",
"]",
":",
"t",
".",
"sequenceExpression",
"(",
"exprs",
")",
";",
"const",
"replacement",
"=",
"t",
".",
"logicalExpression",
"(",
"\"&&\"",
",",
"node",
".",
"test",
",",
"expr",
")",
";",
"path",
".",
"replaceWith",
"(",
"t",
".",
"ifStatement",
"(",
"replacement",
",",
"ret",
",",
"null",
")",
")",
";",
"}"
] |
Make if statements with conditional returns in the body into an if statement that guards the rest of the block.
|
[
"Make",
"if",
"statements",
"with",
"conditional",
"returns",
"in",
"the",
"body",
"into",
"an",
"if",
"statement",
"that",
"guards",
"the",
"rest",
"of",
"the",
"block",
"."
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/if-statement.js#L346-L394
|
8,601
|
babel/minify
|
utils/unpad/src/unpad.js
|
unpad
|
function unpad(str) {
const lines = str.split("\n");
const m = lines[1] && lines[1].match(/^\s+/);
if (!m) {
return str;
}
const spaces = m[0].length;
return lines
.map(line => line.slice(spaces))
.join("\n")
.trim();
}
|
javascript
|
function unpad(str) {
const lines = str.split("\n");
const m = lines[1] && lines[1].match(/^\s+/);
if (!m) {
return str;
}
const spaces = m[0].length;
return lines
.map(line => line.slice(spaces))
.join("\n")
.trim();
}
|
[
"function",
"unpad",
"(",
"str",
")",
"{",
"const",
"lines",
"=",
"str",
".",
"split",
"(",
"\"\\n\"",
")",
";",
"const",
"m",
"=",
"lines",
"[",
"1",
"]",
"&&",
"lines",
"[",
"1",
"]",
".",
"match",
"(",
"/",
"^\\s+",
"/",
")",
";",
"if",
"(",
"!",
"m",
")",
"{",
"return",
"str",
";",
"}",
"const",
"spaces",
"=",
"m",
"[",
"0",
"]",
".",
"length",
";",
"return",
"lines",
".",
"map",
"(",
"line",
"=>",
"line",
".",
"slice",
"(",
"spaces",
")",
")",
".",
"join",
"(",
"\"\\n\"",
")",
".",
"trim",
"(",
")",
";",
"}"
] |
Remove padding from a string.
|
[
"Remove",
"padding",
"from",
"a",
"string",
"."
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/utils/unpad/src/unpad.js#L2-L13
|
8,602
|
babel/minify
|
packages/babel-plugin-transform-simplify-comparison-operators/src/index.js
|
baseTypeStrictlyMatches
|
function baseTypeStrictlyMatches(left, right) {
let leftTypes, rightTypes;
if (t.isIdentifier(left)) {
leftTypes = customTypeAnnotation(left);
} else if (t.isIdentifier(right)) {
rightTypes = customTypeAnnotation(right);
}
// Early exit
if (t.isAnyTypeAnnotation(leftTypes) || t.isAnyTypeAnnotation(rightTypes)) {
return false;
}
leftTypes = [].concat(leftTypes, left.getTypeAnnotation());
rightTypes = [].concat(rightTypes, right.getTypeAnnotation());
leftTypes = t.createUnionTypeAnnotation(leftTypes);
rightTypes = t.createUnionTypeAnnotation(rightTypes);
if (
!t.isAnyTypeAnnotation(leftTypes) &&
t.isFlowBaseAnnotation(leftTypes)
) {
return leftTypes.type === rightTypes.type;
}
}
|
javascript
|
function baseTypeStrictlyMatches(left, right) {
let leftTypes, rightTypes;
if (t.isIdentifier(left)) {
leftTypes = customTypeAnnotation(left);
} else if (t.isIdentifier(right)) {
rightTypes = customTypeAnnotation(right);
}
// Early exit
if (t.isAnyTypeAnnotation(leftTypes) || t.isAnyTypeAnnotation(rightTypes)) {
return false;
}
leftTypes = [].concat(leftTypes, left.getTypeAnnotation());
rightTypes = [].concat(rightTypes, right.getTypeAnnotation());
leftTypes = t.createUnionTypeAnnotation(leftTypes);
rightTypes = t.createUnionTypeAnnotation(rightTypes);
if (
!t.isAnyTypeAnnotation(leftTypes) &&
t.isFlowBaseAnnotation(leftTypes)
) {
return leftTypes.type === rightTypes.type;
}
}
|
[
"function",
"baseTypeStrictlyMatches",
"(",
"left",
",",
"right",
")",
"{",
"let",
"leftTypes",
",",
"rightTypes",
";",
"if",
"(",
"t",
".",
"isIdentifier",
"(",
"left",
")",
")",
"{",
"leftTypes",
"=",
"customTypeAnnotation",
"(",
"left",
")",
";",
"}",
"else",
"if",
"(",
"t",
".",
"isIdentifier",
"(",
"right",
")",
")",
"{",
"rightTypes",
"=",
"customTypeAnnotation",
"(",
"right",
")",
";",
"}",
"// Early exit",
"if",
"(",
"t",
".",
"isAnyTypeAnnotation",
"(",
"leftTypes",
")",
"||",
"t",
".",
"isAnyTypeAnnotation",
"(",
"rightTypes",
")",
")",
"{",
"return",
"false",
";",
"}",
"leftTypes",
"=",
"[",
"]",
".",
"concat",
"(",
"leftTypes",
",",
"left",
".",
"getTypeAnnotation",
"(",
")",
")",
";",
"rightTypes",
"=",
"[",
"]",
".",
"concat",
"(",
"rightTypes",
",",
"right",
".",
"getTypeAnnotation",
"(",
")",
")",
";",
"leftTypes",
"=",
"t",
".",
"createUnionTypeAnnotation",
"(",
"leftTypes",
")",
";",
"rightTypes",
"=",
"t",
".",
"createUnionTypeAnnotation",
"(",
"rightTypes",
")",
";",
"if",
"(",
"!",
"t",
".",
"isAnyTypeAnnotation",
"(",
"leftTypes",
")",
"&&",
"t",
".",
"isFlowBaseAnnotation",
"(",
"leftTypes",
")",
")",
"{",
"return",
"leftTypes",
".",
"type",
"===",
"rightTypes",
".",
"type",
";",
"}",
"}"
] |
Based on the type inference in Babel
|
[
"Based",
"on",
"the",
"type",
"inference",
"in",
"Babel"
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-transform-simplify-comparison-operators/src/index.js#L37-L63
|
8,603
|
babel/minify
|
packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js
|
removeUseStrict
|
function removeUseStrict(block) {
if (!block.isBlockStatement()) {
throw new Error(
`Received ${block.type}. Expected BlockStatement. ` +
`Please report at ${newIssueUrl}`
);
}
const useStricts = getUseStrictDirectives(block);
// early exit
if (useStricts.length < 1) return;
// only keep the first use strict
if (useStricts.length > 1) {
for (let i = 1; i < useStricts.length; i++) {
useStricts[i].remove();
}
}
// check if parent has an use strict
if (hasStrictParent(block)) {
useStricts[0].remove();
}
}
|
javascript
|
function removeUseStrict(block) {
if (!block.isBlockStatement()) {
throw new Error(
`Received ${block.type}. Expected BlockStatement. ` +
`Please report at ${newIssueUrl}`
);
}
const useStricts = getUseStrictDirectives(block);
// early exit
if (useStricts.length < 1) return;
// only keep the first use strict
if (useStricts.length > 1) {
for (let i = 1; i < useStricts.length; i++) {
useStricts[i].remove();
}
}
// check if parent has an use strict
if (hasStrictParent(block)) {
useStricts[0].remove();
}
}
|
[
"function",
"removeUseStrict",
"(",
"block",
")",
"{",
"if",
"(",
"!",
"block",
".",
"isBlockStatement",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"block",
".",
"type",
"}",
"`",
"+",
"`",
"${",
"newIssueUrl",
"}",
"`",
")",
";",
"}",
"const",
"useStricts",
"=",
"getUseStrictDirectives",
"(",
"block",
")",
";",
"// early exit",
"if",
"(",
"useStricts",
".",
"length",
"<",
"1",
")",
"return",
";",
"// only keep the first use strict",
"if",
"(",
"useStricts",
".",
"length",
">",
"1",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<",
"useStricts",
".",
"length",
";",
"i",
"++",
")",
"{",
"useStricts",
"[",
"i",
"]",
".",
"remove",
"(",
")",
";",
"}",
"}",
"// check if parent has an use strict",
"if",
"(",
"hasStrictParent",
"(",
"block",
")",
")",
"{",
"useStricts",
"[",
"0",
"]",
".",
"remove",
"(",
")",
";",
"}",
"}"
] |
Remove redundant use strict
If the parent has a "use strict" directive, it is not required in
the children
@param {NodePath} block BlockStatement
|
[
"Remove",
"redundant",
"use",
"strict",
"If",
"the",
"parent",
"has",
"a",
"use",
"strict",
"directive",
"it",
"is",
"not",
"required",
"in",
"the",
"children"
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-dead-code-elimination/src/remove-use-strict.js#L16-L40
|
8,604
|
babel/minify
|
scripts/plugin-contribution.js
|
tableStyle
|
function tableStyle() {
return {
chars: {
top: "",
"top-mid": "",
"top-left": "",
"top-right": "",
bottom: "",
"bottom-mid": "",
"bottom-left": "",
"bottom-right": "",
left: "",
"left-mid": "",
mid: "",
"mid-mid": "",
right: "",
"right-mid": "",
middle: " "
},
style: {
"padding-left": 0,
"padding-right": 0,
head: ["bold"]
}
};
}
|
javascript
|
function tableStyle() {
return {
chars: {
top: "",
"top-mid": "",
"top-left": "",
"top-right": "",
bottom: "",
"bottom-mid": "",
"bottom-left": "",
"bottom-right": "",
left: "",
"left-mid": "",
mid: "",
"mid-mid": "",
right: "",
"right-mid": "",
middle: " "
},
style: {
"padding-left": 0,
"padding-right": 0,
head: ["bold"]
}
};
}
|
[
"function",
"tableStyle",
"(",
")",
"{",
"return",
"{",
"chars",
":",
"{",
"top",
":",
"\"\"",
",",
"\"top-mid\"",
":",
"\"\"",
",",
"\"top-left\"",
":",
"\"\"",
",",
"\"top-right\"",
":",
"\"\"",
",",
"bottom",
":",
"\"\"",
",",
"\"bottom-mid\"",
":",
"\"\"",
",",
"\"bottom-left\"",
":",
"\"\"",
",",
"\"bottom-right\"",
":",
"\"\"",
",",
"left",
":",
"\"\"",
",",
"\"left-mid\"",
":",
"\"\"",
",",
"mid",
":",
"\"\"",
",",
"\"mid-mid\"",
":",
"\"\"",
",",
"right",
":",
"\"\"",
",",
"\"right-mid\"",
":",
"\"\"",
",",
"middle",
":",
"\" \"",
"}",
",",
"style",
":",
"{",
"\"padding-left\"",
":",
"0",
",",
"\"padding-right\"",
":",
"0",
",",
"head",
":",
"[",
"\"bold\"",
"]",
"}",
"}",
";",
"}"
] |
just to keep it at the bottom
|
[
"just",
"to",
"keep",
"it",
"at",
"the",
"bottom"
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/scripts/plugin-contribution.js#L143-L168
|
8,605
|
babel/minify
|
packages/babel-minify/src/fs.js
|
readStdin
|
async function readStdin() {
let code = "";
const stdin = process.stdin;
return new Promise(resolve => {
stdin.setEncoding("utf8");
stdin.on("readable", () => {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
stdin.on("end", () => {
resolve(code);
});
});
}
|
javascript
|
async function readStdin() {
let code = "";
const stdin = process.stdin;
return new Promise(resolve => {
stdin.setEncoding("utf8");
stdin.on("readable", () => {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
stdin.on("end", () => {
resolve(code);
});
});
}
|
[
"async",
"function",
"readStdin",
"(",
")",
"{",
"let",
"code",
"=",
"\"\"",
";",
"const",
"stdin",
"=",
"process",
".",
"stdin",
";",
"return",
"new",
"Promise",
"(",
"resolve",
"=>",
"{",
"stdin",
".",
"setEncoding",
"(",
"\"utf8\"",
")",
";",
"stdin",
".",
"on",
"(",
"\"readable\"",
",",
"(",
")",
"=>",
"{",
"const",
"chunk",
"=",
"process",
".",
"stdin",
".",
"read",
"(",
")",
";",
"if",
"(",
"chunk",
"!==",
"null",
")",
"code",
"+=",
"chunk",
";",
"}",
")",
";",
"stdin",
".",
"on",
"(",
"\"end\"",
",",
"(",
")",
"=>",
"{",
"resolve",
"(",
"code",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
the async keyword simply exists to denote we are returning a promise even though we don't use await inside it
|
[
"the",
"async",
"keyword",
"simply",
"exists",
"to",
"denote",
"we",
"are",
"returning",
"a",
"promise",
"even",
"though",
"we",
"don",
"t",
"use",
"await",
"inside",
"it"
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-minify/src/fs.js#L48-L61
|
8,606
|
babel/minify
|
packages/babel-helper-evaluate-path/src/index.js
|
shouldDeoptBasedOnScope
|
function shouldDeoptBasedOnScope(binding, refPath) {
if (binding.scope.path.isProgram() && refPath.scope !== binding.scope) {
return true;
}
return false;
}
|
javascript
|
function shouldDeoptBasedOnScope(binding, refPath) {
if (binding.scope.path.isProgram() && refPath.scope !== binding.scope) {
return true;
}
return false;
}
|
[
"function",
"shouldDeoptBasedOnScope",
"(",
"binding",
",",
"refPath",
")",
"{",
"if",
"(",
"binding",
".",
"scope",
".",
"path",
".",
"isProgram",
"(",
")",
"&&",
"refPath",
".",
"scope",
"!==",
"binding",
".",
"scope",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
check if referenced in a different fn scope we can't determine if this function is called sync or async if the binding is in program scope all it's references inside a different function should be deopted
|
[
"check",
"if",
"referenced",
"in",
"a",
"different",
"fn",
"scope",
"we",
"can",
"t",
"determine",
"if",
"this",
"function",
"is",
"called",
"sync",
"or",
"async",
"if",
"the",
"binding",
"is",
"in",
"program",
"scope",
"all",
"it",
"s",
"references",
"inside",
"a",
"different",
"function",
"should",
"be",
"deopted"
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-helper-evaluate-path/src/index.js#L111-L116
|
8,607
|
babel/minify
|
packages/babel-plugin-minify-builtins/src/index.js
|
getSegmentedSubPaths
|
function getSegmentedSubPaths(paths) {
let segments = new Map();
// Get earliest Path in tree where paths intersect
paths[0].getDeepestCommonAncestorFrom(
paths,
(lastCommon, index, ancestries) => {
// found the LCA
if (!lastCommon.isProgram()) {
let fnParent;
if (
lastCommon.isFunction() &&
t.isBlockStatement(lastCommon.node.body)
) {
segments.set(lastCommon, paths);
return;
} else if (
!(fnParent = getFunctionParent(lastCommon)).isProgram() &&
t.isBlockStatement(fnParent.node.body)
) {
segments.set(fnParent, paths);
return;
}
}
// Deopt and construct segments otherwise
for (const ancestor of ancestries) {
const fnPath = getChildFuncion(ancestor);
if (fnPath === void 0) {
continue;
}
const validDescendants = paths.filter(p => {
return p.isDescendant(fnPath);
});
segments.set(fnPath, validDescendants);
}
}
);
return segments;
}
|
javascript
|
function getSegmentedSubPaths(paths) {
let segments = new Map();
// Get earliest Path in tree where paths intersect
paths[0].getDeepestCommonAncestorFrom(
paths,
(lastCommon, index, ancestries) => {
// found the LCA
if (!lastCommon.isProgram()) {
let fnParent;
if (
lastCommon.isFunction() &&
t.isBlockStatement(lastCommon.node.body)
) {
segments.set(lastCommon, paths);
return;
} else if (
!(fnParent = getFunctionParent(lastCommon)).isProgram() &&
t.isBlockStatement(fnParent.node.body)
) {
segments.set(fnParent, paths);
return;
}
}
// Deopt and construct segments otherwise
for (const ancestor of ancestries) {
const fnPath = getChildFuncion(ancestor);
if (fnPath === void 0) {
continue;
}
const validDescendants = paths.filter(p => {
return p.isDescendant(fnPath);
});
segments.set(fnPath, validDescendants);
}
}
);
return segments;
}
|
[
"function",
"getSegmentedSubPaths",
"(",
"paths",
")",
"{",
"let",
"segments",
"=",
"new",
"Map",
"(",
")",
";",
"// Get earliest Path in tree where paths intersect",
"paths",
"[",
"0",
"]",
".",
"getDeepestCommonAncestorFrom",
"(",
"paths",
",",
"(",
"lastCommon",
",",
"index",
",",
"ancestries",
")",
"=>",
"{",
"// found the LCA",
"if",
"(",
"!",
"lastCommon",
".",
"isProgram",
"(",
")",
")",
"{",
"let",
"fnParent",
";",
"if",
"(",
"lastCommon",
".",
"isFunction",
"(",
")",
"&&",
"t",
".",
"isBlockStatement",
"(",
"lastCommon",
".",
"node",
".",
"body",
")",
")",
"{",
"segments",
".",
"set",
"(",
"lastCommon",
",",
"paths",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"!",
"(",
"fnParent",
"=",
"getFunctionParent",
"(",
"lastCommon",
")",
")",
".",
"isProgram",
"(",
")",
"&&",
"t",
".",
"isBlockStatement",
"(",
"fnParent",
".",
"node",
".",
"body",
")",
")",
"{",
"segments",
".",
"set",
"(",
"fnParent",
",",
"paths",
")",
";",
"return",
";",
"}",
"}",
"// Deopt and construct segments otherwise",
"for",
"(",
"const",
"ancestor",
"of",
"ancestries",
")",
"{",
"const",
"fnPath",
"=",
"getChildFuncion",
"(",
"ancestor",
")",
";",
"if",
"(",
"fnPath",
"===",
"void",
"0",
")",
"{",
"continue",
";",
"}",
"const",
"validDescendants",
"=",
"paths",
".",
"filter",
"(",
"p",
"=>",
"{",
"return",
"p",
".",
"isDescendant",
"(",
"fnPath",
")",
";",
"}",
")",
";",
"segments",
".",
"set",
"(",
"fnPath",
",",
"validDescendants",
")",
";",
"}",
"}",
")",
";",
"return",
"segments",
";",
"}"
] |
Creates a segmented map that contains the earliest common Ancestor as the key and array of subpaths that are descendats of the LCA as value
|
[
"Creates",
"a",
"segmented",
"map",
"that",
"contains",
"the",
"earliest",
"common",
"Ancestor",
"as",
"the",
"key",
"and",
"array",
"of",
"subpaths",
"that",
"are",
"descendats",
"of",
"the",
"LCA",
"as",
"value"
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-builtins/src/index.js#L190-L228
|
8,608
|
babel/minify
|
packages/babel-plugin-minify-mangle-names/src/index.js
|
toObject
|
function toObject(value) {
if (!Array.isArray(value)) {
return value;
}
const map = {};
for (let i = 0; i < value.length; i++) {
map[value[i]] = true;
}
return map;
}
|
javascript
|
function toObject(value) {
if (!Array.isArray(value)) {
return value;
}
const map = {};
for (let i = 0; i < value.length; i++) {
map[value[i]] = true;
}
return map;
}
|
[
"function",
"toObject",
"(",
"value",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"value",
")",
")",
"{",
"return",
"value",
";",
"}",
"const",
"map",
"=",
"{",
"}",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"value",
".",
"length",
";",
"i",
"++",
")",
"{",
"map",
"[",
"value",
"[",
"i",
"]",
"]",
"=",
"true",
";",
"}",
"return",
"map",
";",
"}"
] |
convert value to object
|
[
"convert",
"value",
"to",
"object"
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-mangle-names/src/index.js#L553-L563
|
8,609
|
babel/minify
|
packages/babel-plugin-transform-merge-sibling-variables/src/index.js
|
function(path) {
if (!path.inList) {
return;
}
const { node } = path;
let sibling = path.getSibling(path.key + 1);
let declarations = [];
while (sibling.isVariableDeclaration({ kind: node.kind })) {
declarations = declarations.concat(sibling.node.declarations);
sibling.remove();
sibling = path.getSibling(path.key + 1);
}
if (declarations.length > 0) {
path.replaceWith(
t.variableDeclaration(node.kind, [
...node.declarations,
...declarations
])
);
}
}
|
javascript
|
function(path) {
if (!path.inList) {
return;
}
const { node } = path;
let sibling = path.getSibling(path.key + 1);
let declarations = [];
while (sibling.isVariableDeclaration({ kind: node.kind })) {
declarations = declarations.concat(sibling.node.declarations);
sibling.remove();
sibling = path.getSibling(path.key + 1);
}
if (declarations.length > 0) {
path.replaceWith(
t.variableDeclaration(node.kind, [
...node.declarations,
...declarations
])
);
}
}
|
[
"function",
"(",
"path",
")",
"{",
"if",
"(",
"!",
"path",
".",
"inList",
")",
"{",
"return",
";",
"}",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"let",
"sibling",
"=",
"path",
".",
"getSibling",
"(",
"path",
".",
"key",
"+",
"1",
")",
";",
"let",
"declarations",
"=",
"[",
"]",
";",
"while",
"(",
"sibling",
".",
"isVariableDeclaration",
"(",
"{",
"kind",
":",
"node",
".",
"kind",
"}",
")",
")",
"{",
"declarations",
"=",
"declarations",
".",
"concat",
"(",
"sibling",
".",
"node",
".",
"declarations",
")",
";",
"sibling",
".",
"remove",
"(",
")",
";",
"sibling",
"=",
"path",
".",
"getSibling",
"(",
"path",
".",
"key",
"+",
"1",
")",
";",
"}",
"if",
"(",
"declarations",
".",
"length",
">",
"0",
")",
"{",
"path",
".",
"replaceWith",
"(",
"t",
".",
"variableDeclaration",
"(",
"node",
".",
"kind",
",",
"[",
"...",
"node",
".",
"declarations",
",",
"...",
"declarations",
"]",
")",
")",
";",
"}",
"}"
] |
concat variables of the same kind with their siblings
|
[
"concat",
"variables",
"of",
"the",
"same",
"kind",
"with",
"their",
"siblings"
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-transform-merge-sibling-variables/src/index.js#L51-L78
|
|
8,610
|
babel/minify
|
packages/babel-plugin-transform-merge-sibling-variables/src/index.js
|
function(path) {
if (!path.inList) {
return;
}
const { node } = path;
if (node.kind !== "var") {
return;
}
const next = path.getSibling(path.key + 1);
if (!next.isForStatement()) {
return;
}
const init = next.get("init");
if (!init.isVariableDeclaration({ kind: node.kind })) {
return;
}
const declarations = node.declarations.concat(
init.node.declarations
);
// temporary workaround to forces babel recalculate scope,
// references and binding until babel/babel#4818 resolved
path.remove();
init.replaceWith(t.variableDeclaration("var", declarations));
}
|
javascript
|
function(path) {
if (!path.inList) {
return;
}
const { node } = path;
if (node.kind !== "var") {
return;
}
const next = path.getSibling(path.key + 1);
if (!next.isForStatement()) {
return;
}
const init = next.get("init");
if (!init.isVariableDeclaration({ kind: node.kind })) {
return;
}
const declarations = node.declarations.concat(
init.node.declarations
);
// temporary workaround to forces babel recalculate scope,
// references and binding until babel/babel#4818 resolved
path.remove();
init.replaceWith(t.variableDeclaration("var", declarations));
}
|
[
"function",
"(",
"path",
")",
"{",
"if",
"(",
"!",
"path",
".",
"inList",
")",
"{",
"return",
";",
"}",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"if",
"(",
"node",
".",
"kind",
"!==",
"\"var\"",
")",
"{",
"return",
";",
"}",
"const",
"next",
"=",
"path",
".",
"getSibling",
"(",
"path",
".",
"key",
"+",
"1",
")",
";",
"if",
"(",
"!",
"next",
".",
"isForStatement",
"(",
")",
")",
"{",
"return",
";",
"}",
"const",
"init",
"=",
"next",
".",
"get",
"(",
"\"init\"",
")",
";",
"if",
"(",
"!",
"init",
".",
"isVariableDeclaration",
"(",
"{",
"kind",
":",
"node",
".",
"kind",
"}",
")",
")",
"{",
"return",
";",
"}",
"const",
"declarations",
"=",
"node",
".",
"declarations",
".",
"concat",
"(",
"init",
".",
"node",
".",
"declarations",
")",
";",
"// temporary workaround to forces babel recalculate scope,",
"// references and binding until babel/babel#4818 resolved",
"path",
".",
"remove",
"(",
")",
";",
"init",
".",
"replaceWith",
"(",
"t",
".",
"variableDeclaration",
"(",
"\"var\"",
",",
"declarations",
")",
")",
";",
"}"
] |
concat `var` declarations next to for loops with it's initialisers. block-scoped `let` and `const` are not moved because the for loop is a different block scope.
|
[
"concat",
"var",
"declarations",
"next",
"to",
"for",
"loops",
"with",
"it",
"s",
"initialisers",
".",
"block",
"-",
"scoped",
"let",
"and",
"const",
"are",
"not",
"moved",
"because",
"the",
"for",
"loop",
"is",
"a",
"different",
"block",
"scope",
"."
] |
6b8bab6bf5905ebc3a5a9130662a5fef34886de4
|
https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-transform-merge-sibling-variables/src/index.js#L83-L111
|
|
8,611
|
KhaosT/homebridge-camera-ffmpeg
|
drive.js
|
authorize
|
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
|
javascript
|
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
|
[
"function",
"authorize",
"(",
"credentials",
",",
"callback",
")",
"{",
"var",
"clientSecret",
"=",
"credentials",
".",
"installed",
".",
"client_secret",
";",
"var",
"clientId",
"=",
"credentials",
".",
"installed",
".",
"client_id",
";",
"var",
"redirectUrl",
"=",
"credentials",
".",
"installed",
".",
"redirect_uris",
"[",
"0",
"]",
";",
"var",
"auth",
"=",
"new",
"googleAuth",
"(",
")",
";",
"var",
"oauth2Client",
"=",
"new",
"auth",
".",
"OAuth2",
"(",
"clientId",
",",
"clientSecret",
",",
"redirectUrl",
")",
";",
"// Check if we have previously stored a token.",
"fs",
".",
"readFile",
"(",
"TOKEN_PATH",
",",
"function",
"(",
"err",
",",
"token",
")",
"{",
"if",
"(",
"err",
")",
"{",
"getNewToken",
"(",
"oauth2Client",
",",
"callback",
")",
";",
"}",
"else",
"{",
"oauth2Client",
".",
"credentials",
"=",
"JSON",
".",
"parse",
"(",
"token",
")",
";",
"callback",
"(",
"oauth2Client",
")",
";",
"}",
"}",
")",
";",
"}"
] |
This is all from the Google Drive Quickstart
Create an OAuth2 client with the given credentials, and then execute the
given callback function.
@param {Object} credentials The authorization client credentials.
@param {function} callback The callback to call with the authorized client.
|
[
"This",
"is",
"all",
"from",
"the",
"Google",
"Drive",
"Quickstart",
"Create",
"an",
"OAuth2",
"client",
"with",
"the",
"given",
"credentials",
"and",
"then",
"execute",
"the",
"given",
"callback",
"function",
"."
] |
cd284406d1a67b88b6488fb455128a0b7a220e12
|
https://github.com/KhaosT/homebridge-camera-ffmpeg/blob/cd284406d1a67b88b6488fb455128a0b7a220e12/drive.js#L136-L152
|
8,612
|
Serhioromano/bootstrap-calendar
|
components/jstimezonedetect/jstz.js
|
function () {
var ambiguity_list = AMBIGUITIES[timezone_name],
length = ambiguity_list.length,
i = 0,
tz = ambiguity_list[0];
for (; i < length; i += 1) {
tz = ambiguity_list[i];
if (jstz.date_is_dst(jstz.dst_start_for(tz))) {
timezone_name = tz;
return;
}
}
}
|
javascript
|
function () {
var ambiguity_list = AMBIGUITIES[timezone_name],
length = ambiguity_list.length,
i = 0,
tz = ambiguity_list[0];
for (; i < length; i += 1) {
tz = ambiguity_list[i];
if (jstz.date_is_dst(jstz.dst_start_for(tz))) {
timezone_name = tz;
return;
}
}
}
|
[
"function",
"(",
")",
"{",
"var",
"ambiguity_list",
"=",
"AMBIGUITIES",
"[",
"timezone_name",
"]",
",",
"length",
"=",
"ambiguity_list",
".",
"length",
",",
"i",
"=",
"0",
",",
"tz",
"=",
"ambiguity_list",
"[",
"0",
"]",
";",
"for",
"(",
";",
"i",
"<",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"tz",
"=",
"ambiguity_list",
"[",
"i",
"]",
";",
"if",
"(",
"jstz",
".",
"date_is_dst",
"(",
"jstz",
".",
"dst_start_for",
"(",
"tz",
")",
")",
")",
"{",
"timezone_name",
"=",
"tz",
";",
"return",
";",
"}",
"}",
"}"
] |
The keys in this object are timezones that we know may be ambiguous after
a preliminary scan through the olson_tz object.
The array of timezones to compare must be in the order that daylight savings
starts for the regions.
|
[
"The",
"keys",
"in",
"this",
"object",
"are",
"timezones",
"that",
"we",
"know",
"may",
"be",
"ambiguous",
"after",
"a",
"preliminary",
"scan",
"through",
"the",
"olson_tz",
"object",
"."
] |
fd5e6fdb69d7e8afdc655b54ffe7a50b8edfffd1
|
https://github.com/Serhioromano/bootstrap-calendar/blob/fd5e6fdb69d7e8afdc655b54ffe7a50b8edfffd1/components/jstimezonedetect/jstz.js#L229-L243
|
|
8,613
|
OptimalBits/redbird
|
lib/proxy.js
|
redirectToHttps
|
function redirectToHttps(req, res, target, ssl, log) {
req.url = req._url || req.url; // Get the original url since we are going to redirect.
var targetPort = ssl.redirectPort || ssl.port;
var hostname = req.headers.host.split(':')[0] + ( targetPort ? ':' + targetPort : '' );
var url = 'https://' + path.join(hostname, req.url);
log && log.info('Redirecting %s to %s', path.join(req.headers.host, req.url), url);
//
// We can use 301 for permanent redirect, but its bad for debugging, we may have it as
// a configurable option.
//
res.writeHead(302, { Location: url });
res.end();
}
|
javascript
|
function redirectToHttps(req, res, target, ssl, log) {
req.url = req._url || req.url; // Get the original url since we are going to redirect.
var targetPort = ssl.redirectPort || ssl.port;
var hostname = req.headers.host.split(':')[0] + ( targetPort ? ':' + targetPort : '' );
var url = 'https://' + path.join(hostname, req.url);
log && log.info('Redirecting %s to %s', path.join(req.headers.host, req.url), url);
//
// We can use 301 for permanent redirect, but its bad for debugging, we may have it as
// a configurable option.
//
res.writeHead(302, { Location: url });
res.end();
}
|
[
"function",
"redirectToHttps",
"(",
"req",
",",
"res",
",",
"target",
",",
"ssl",
",",
"log",
")",
"{",
"req",
".",
"url",
"=",
"req",
".",
"_url",
"||",
"req",
".",
"url",
";",
"// Get the original url since we are going to redirect.",
"var",
"targetPort",
"=",
"ssl",
".",
"redirectPort",
"||",
"ssl",
".",
"port",
";",
"var",
"hostname",
"=",
"req",
".",
"headers",
".",
"host",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"+",
"(",
"targetPort",
"?",
"':'",
"+",
"targetPort",
":",
"''",
")",
";",
"var",
"url",
"=",
"'https://'",
"+",
"path",
".",
"join",
"(",
"hostname",
",",
"req",
".",
"url",
")",
";",
"log",
"&&",
"log",
".",
"info",
"(",
"'Redirecting %s to %s'",
",",
"path",
".",
"join",
"(",
"req",
".",
"headers",
".",
"host",
",",
"req",
".",
"url",
")",
",",
"url",
")",
";",
"//",
"// We can use 301 for permanent redirect, but its bad for debugging, we may have it as",
"// a configurable option.",
"//",
"res",
".",
"writeHead",
"(",
"302",
",",
"{",
"Location",
":",
"url",
"}",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}"
] |
Redirect to the HTTPS proxy
|
[
"Redirect",
"to",
"the",
"HTTPS",
"proxy"
] |
a8779cccde681f27f78c80b9ee6ca373254c73e5
|
https://github.com/OptimalBits/redbird/blob/a8779cccde681f27f78c80b9ee6ca373254c73e5/lib/proxy.js#L702-L715
|
8,614
|
timdown/rangy
|
src/modules/inactive/rangy-commands_new.js
|
getFurthestAncestor
|
function getFurthestAncestor(node) {
var root = node;
while (root.parentNode != null) {
root = root.parentNode;
}
return root;
}
|
javascript
|
function getFurthestAncestor(node) {
var root = node;
while (root.parentNode != null) {
root = root.parentNode;
}
return root;
}
|
[
"function",
"getFurthestAncestor",
"(",
"node",
")",
"{",
"var",
"root",
"=",
"node",
";",
"while",
"(",
"root",
".",
"parentNode",
"!=",
"null",
")",
"{",
"root",
"=",
"root",
".",
"parentNode",
";",
"}",
"return",
"root",
";",
"}"
] |
Returns the furthest ancestor of a Node as defined by DOM Range.
|
[
"Returns",
"the",
"furthest",
"ancestor",
"of",
"a",
"Node",
"as",
"defined",
"by",
"DOM",
"Range",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-commands_new.js#L79-L85
|
8,615
|
timdown/rangy
|
src/modules/inactive/rangy-commands_new.js
|
isCollapsedLineBreak
|
function isCollapsedLineBreak(br) {
if (!isHtmlElement(br, "br")) {
return false;
}
// Add a zwsp after it and see if that changes the height of the nearest
// non-inline parent. Note: this is not actually reliable, because the
// parent might have a fixed height or something.
var ref = br.parentNode;
while (getComputedStyleProperty(ref, "display") == "inline") {
ref = ref.parentNode;
}
var refStyle = ref.hasAttribute("style") ? ref.getAttribute("style") : null;
ref.style.height = "auto";
ref.style.maxHeight = "none";
ref.style.minHeight = "0";
var space = document.createTextNode("\u200b");
var origHeight = ref.offsetHeight;
if (origHeight == 0) {
throw "isCollapsedLineBreak: original height is zero, bug?";
}
br.parentNode.insertBefore(space, br.nextSibling);
var finalHeight = ref.offsetHeight;
space.parentNode.removeChild(space);
if (refStyle === null) {
// Without the setAttribute() line, removeAttribute() doesn't work in
// Chrome 14 dev. I have no idea why.
ref.setAttribute("style", "");
ref.removeAttribute("style");
} else {
ref.setAttribute("style", refStyle);
}
// Allow some leeway in case the zwsp didn't create a whole new line, but
// only made an existing line slightly higher. Firefox 6.0a2 shows this
// behavior when the first line is bold.
return origHeight < finalHeight - 5;
}
|
javascript
|
function isCollapsedLineBreak(br) {
if (!isHtmlElement(br, "br")) {
return false;
}
// Add a zwsp after it and see if that changes the height of the nearest
// non-inline parent. Note: this is not actually reliable, because the
// parent might have a fixed height or something.
var ref = br.parentNode;
while (getComputedStyleProperty(ref, "display") == "inline") {
ref = ref.parentNode;
}
var refStyle = ref.hasAttribute("style") ? ref.getAttribute("style") : null;
ref.style.height = "auto";
ref.style.maxHeight = "none";
ref.style.minHeight = "0";
var space = document.createTextNode("\u200b");
var origHeight = ref.offsetHeight;
if (origHeight == 0) {
throw "isCollapsedLineBreak: original height is zero, bug?";
}
br.parentNode.insertBefore(space, br.nextSibling);
var finalHeight = ref.offsetHeight;
space.parentNode.removeChild(space);
if (refStyle === null) {
// Without the setAttribute() line, removeAttribute() doesn't work in
// Chrome 14 dev. I have no idea why.
ref.setAttribute("style", "");
ref.removeAttribute("style");
} else {
ref.setAttribute("style", refStyle);
}
// Allow some leeway in case the zwsp didn't create a whole new line, but
// only made an existing line slightly higher. Firefox 6.0a2 shows this
// behavior when the first line is bold.
return origHeight < finalHeight - 5;
}
|
[
"function",
"isCollapsedLineBreak",
"(",
"br",
")",
"{",
"if",
"(",
"!",
"isHtmlElement",
"(",
"br",
",",
"\"br\"",
")",
")",
"{",
"return",
"false",
";",
"}",
"// Add a zwsp after it and see if that changes the height of the nearest",
"// non-inline parent. Note: this is not actually reliable, because the",
"// parent might have a fixed height or something.",
"var",
"ref",
"=",
"br",
".",
"parentNode",
";",
"while",
"(",
"getComputedStyleProperty",
"(",
"ref",
",",
"\"display\"",
")",
"==",
"\"inline\"",
")",
"{",
"ref",
"=",
"ref",
".",
"parentNode",
";",
"}",
"var",
"refStyle",
"=",
"ref",
".",
"hasAttribute",
"(",
"\"style\"",
")",
"?",
"ref",
".",
"getAttribute",
"(",
"\"style\"",
")",
":",
"null",
";",
"ref",
".",
"style",
".",
"height",
"=",
"\"auto\"",
";",
"ref",
".",
"style",
".",
"maxHeight",
"=",
"\"none\"",
";",
"ref",
".",
"style",
".",
"minHeight",
"=",
"\"0\"",
";",
"var",
"space",
"=",
"document",
".",
"createTextNode",
"(",
"\"\\u200b\"",
")",
";",
"var",
"origHeight",
"=",
"ref",
".",
"offsetHeight",
";",
"if",
"(",
"origHeight",
"==",
"0",
")",
"{",
"throw",
"\"isCollapsedLineBreak: original height is zero, bug?\"",
";",
"}",
"br",
".",
"parentNode",
".",
"insertBefore",
"(",
"space",
",",
"br",
".",
"nextSibling",
")",
";",
"var",
"finalHeight",
"=",
"ref",
".",
"offsetHeight",
";",
"space",
".",
"parentNode",
".",
"removeChild",
"(",
"space",
")",
";",
"if",
"(",
"refStyle",
"===",
"null",
")",
"{",
"// Without the setAttribute() line, removeAttribute() doesn't work in",
"// Chrome 14 dev. I have no idea why.",
"ref",
".",
"setAttribute",
"(",
"\"style\"",
",",
"\"\"",
")",
";",
"ref",
".",
"removeAttribute",
"(",
"\"style\"",
")",
";",
"}",
"else",
"{",
"ref",
".",
"setAttribute",
"(",
"\"style\"",
",",
"refStyle",
")",
";",
"}",
"// Allow some leeway in case the zwsp didn't create a whole new line, but",
"// only made an existing line slightly higher. Firefox 6.0a2 shows this",
"// behavior when the first line is bold.",
"return",
"origHeight",
"<",
"finalHeight",
"-",
"5",
";",
"}"
] |
"A collapsed line break is a br that begins a line box which has nothing else in it, and therefore has zero height."
|
[
"A",
"collapsed",
"line",
"break",
"is",
"a",
"br",
"that",
"begins",
"a",
"line",
"box",
"which",
"has",
"nothing",
"else",
"in",
"it",
"and",
"therefore",
"has",
"zero",
"height",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-commands_new.js#L299-L336
|
8,616
|
timdown/rangy
|
src/modules/inactive/rangy-commands_new.js
|
getEffectiveCommandValue
|
function getEffectiveCommandValue(node, context) {
var isElement = (node.nodeType == 1);
// "If neither node nor its parent is an Element, return null."
if (!isElement && (!node.parentNode || node.parentNode.nodeType != 1)) {
return null;
}
// "If node is not an Element, return the effective command value of its parent for command."
if (!isElement) {
return getEffectiveCommandValue(node.parentNode, context);
}
return context.command.getEffectiveValue(node, context);
}
|
javascript
|
function getEffectiveCommandValue(node, context) {
var isElement = (node.nodeType == 1);
// "If neither node nor its parent is an Element, return null."
if (!isElement && (!node.parentNode || node.parentNode.nodeType != 1)) {
return null;
}
// "If node is not an Element, return the effective command value of its parent for command."
if (!isElement) {
return getEffectiveCommandValue(node.parentNode, context);
}
return context.command.getEffectiveValue(node, context);
}
|
[
"function",
"getEffectiveCommandValue",
"(",
"node",
",",
"context",
")",
"{",
"var",
"isElement",
"=",
"(",
"node",
".",
"nodeType",
"==",
"1",
")",
";",
"// \"If neither node nor its parent is an Element, return null.\"",
"if",
"(",
"!",
"isElement",
"&&",
"(",
"!",
"node",
".",
"parentNode",
"||",
"node",
".",
"parentNode",
".",
"nodeType",
"!=",
"1",
")",
")",
"{",
"return",
"null",
";",
"}",
"// \"If node is not an Element, return the effective command value of its parent for command.\"",
"if",
"(",
"!",
"isElement",
")",
"{",
"return",
"getEffectiveCommandValue",
"(",
"node",
".",
"parentNode",
",",
"context",
")",
";",
"}",
"return",
"context",
".",
"command",
".",
"getEffectiveValue",
"(",
"node",
",",
"context",
")",
";",
"}"
] |
"effective value" per edit command spec
|
[
"effective",
"value",
"per",
"edit",
"command",
"spec"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-commands_new.js#L834-L848
|
8,617
|
timdown/rangy
|
builder/build.js
|
doSubstituteBuildVars
|
function doSubstituteBuildVars(file, buildVars) {
var contents = fs.readFileSync(file, FILE_ENCODING);
contents = contents.replace(/%%build:([^%]+)%%/g, function(matched, buildVarName) {
return buildVars[buildVarName];
});
// Now do replacements specified by build directives
contents = contents.replace(/\/\*\s?build:replaceWith\((.*?)\)\s?\*\/.*?\*\s?build:replaceEnd\s?\*\//g, "$1");
fs.writeFileSync(file, contents, FILE_ENCODING);
}
|
javascript
|
function doSubstituteBuildVars(file, buildVars) {
var contents = fs.readFileSync(file, FILE_ENCODING);
contents = contents.replace(/%%build:([^%]+)%%/g, function(matched, buildVarName) {
return buildVars[buildVarName];
});
// Now do replacements specified by build directives
contents = contents.replace(/\/\*\s?build:replaceWith\((.*?)\)\s?\*\/.*?\*\s?build:replaceEnd\s?\*\//g, "$1");
fs.writeFileSync(file, contents, FILE_ENCODING);
}
|
[
"function",
"doSubstituteBuildVars",
"(",
"file",
",",
"buildVars",
")",
"{",
"var",
"contents",
"=",
"fs",
".",
"readFileSync",
"(",
"file",
",",
"FILE_ENCODING",
")",
";",
"contents",
"=",
"contents",
".",
"replace",
"(",
"/",
"%%build:([^%]+)%%",
"/",
"g",
",",
"function",
"(",
"matched",
",",
"buildVarName",
")",
"{",
"return",
"buildVars",
"[",
"buildVarName",
"]",
";",
"}",
")",
";",
"// Now do replacements specified by build directives\r",
"contents",
"=",
"contents",
".",
"replace",
"(",
"/",
"\\/\\*\\s?build:replaceWith\\((.*?)\\)\\s?\\*\\/.*?\\*\\s?build:replaceEnd\\s?\\*\\/",
"/",
"g",
",",
"\"$1\"",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"file",
",",
"contents",
",",
"FILE_ENCODING",
")",
";",
"}"
] |
Substitute build vars in scripts
|
[
"Substitute",
"build",
"vars",
"in",
"scripts"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/builder/build.js#L223-L233
|
8,618
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
isAncestor
|
function isAncestor(ancestor, descendant) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
}
|
javascript
|
function isAncestor(ancestor, descendant) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
}
|
[
"function",
"isAncestor",
"(",
"ancestor",
",",
"descendant",
")",
"{",
"return",
"ancestor",
"&&",
"descendant",
"&&",
"Boolean",
"(",
"ancestor",
".",
"compareDocumentPosition",
"(",
"descendant",
")",
"&",
"Node",
".",
"DOCUMENT_POSITION_CONTAINED_BY",
")",
";",
"}"
] |
Returns true if ancestor is an ancestor of descendant, false otherwise.
|
[
"Returns",
"true",
"if",
"ancestor",
"is",
"an",
"ancestor",
"of",
"descendant",
"false",
"otherwise",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L55-L59
|
8,619
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
isAncestorContainer
|
function isAncestorContainer(ancestor, descendant) {
return (ancestor || descendant)
&& (ancestor == descendant || isAncestor(ancestor, descendant));
}
|
javascript
|
function isAncestorContainer(ancestor, descendant) {
return (ancestor || descendant)
&& (ancestor == descendant || isAncestor(ancestor, descendant));
}
|
[
"function",
"isAncestorContainer",
"(",
"ancestor",
",",
"descendant",
")",
"{",
"return",
"(",
"ancestor",
"||",
"descendant",
")",
"&&",
"(",
"ancestor",
"==",
"descendant",
"||",
"isAncestor",
"(",
"ancestor",
",",
"descendant",
")",
")",
";",
"}"
] |
Returns true if ancestor is an ancestor of or equal to descendant, false
otherwise.
|
[
"Returns",
"true",
"if",
"ancestor",
"is",
"an",
"ancestor",
"of",
"or",
"equal",
"to",
"descendant",
"false",
"otherwise",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L65-L68
|
8,620
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
isDescendant
|
function isDescendant(descendant, ancestor) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
}
|
javascript
|
function isDescendant(descendant, ancestor) {
return ancestor
&& descendant
&& Boolean(ancestor.compareDocumentPosition(descendant) & Node.DOCUMENT_POSITION_CONTAINED_BY);
}
|
[
"function",
"isDescendant",
"(",
"descendant",
",",
"ancestor",
")",
"{",
"return",
"ancestor",
"&&",
"descendant",
"&&",
"Boolean",
"(",
"ancestor",
".",
"compareDocumentPosition",
"(",
"descendant",
")",
"&",
"Node",
".",
"DOCUMENT_POSITION_CONTAINED_BY",
")",
";",
"}"
] |
Returns true if descendant is a descendant of ancestor, false otherwise.
|
[
"Returns",
"true",
"if",
"descendant",
"is",
"a",
"descendant",
"of",
"ancestor",
"false",
"otherwise",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L73-L77
|
8,621
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
getPosition
|
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
|
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";
}
|
[
"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\"",
";",
"}"
] |
The position of two boundary points relative to one another, as defined by
DOM Range.
|
[
"The",
"position",
"of",
"two",
"boundary",
"points",
"relative",
"to",
"one",
"another",
"as",
"defined",
"by",
"DOM",
"Range",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L254-L301
|
8,622
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
getContainedNodes
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Return all nodes contained in range that the provided function returns true
for, omitting any with an ancestor already being returned.
|
[
"Return",
"all",
"nodes",
"contained",
"in",
"range",
"that",
"the",
"provided",
"function",
"returns",
"true",
"for",
"omitting",
"any",
"with",
"an",
"ancestor",
"already",
"being",
"returned",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L332-L370
|
8,623
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
editCommandMethod
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Helper function for common behavior.
|
[
"Helper",
"function",
"for",
"common",
"behavior",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L497-L522
|
8,624
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
isEditingHost
|
function isEditingHost(node) {
return node
&& isHtmlElement(node)
&& (node.contentEditable == "true"
|| (node.parentNode
&& node.parentNode.nodeType == Node.DOCUMENT_NODE
&& node.parentNode.designMode == "on"));
}
|
javascript
|
function isEditingHost(node) {
return node
&& isHtmlElement(node)
&& (node.contentEditable == "true"
|| (node.parentNode
&& node.parentNode.nodeType == Node.DOCUMENT_NODE
&& node.parentNode.designMode == "on"));
}
|
[
"function",
"isEditingHost",
"(",
"node",
")",
"{",
"return",
"node",
"&&",
"isHtmlElement",
"(",
"node",
")",
"&&",
"(",
"node",
".",
"contentEditable",
"==",
"\"true\"",
"||",
"(",
"node",
".",
"parentNode",
"&&",
"node",
".",
"parentNode",
".",
"nodeType",
"==",
"Node",
".",
"DOCUMENT_NODE",
"&&",
"node",
".",
"parentNode",
".",
"designMode",
"==",
"\"on\"",
")",
")",
";",
"}"
] |
"An editing host is a node that is either an HTML element with a contenteditable attribute set to the true state, or the HTML element child of a Document whose designMode is enabled."
|
[
"An",
"editing",
"host",
"is",
"a",
"node",
"that",
"is",
"either",
"an",
"HTML",
"element",
"with",
"a",
"contenteditable",
"attribute",
"set",
"to",
"the",
"true",
"state",
"or",
"the",
"HTML",
"element",
"child",
"of",
"a",
"Document",
"whose",
"designMode",
"is",
"enabled",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L729-L736
|
8,625
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
isEditable
|
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
|
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)));
}
|
[
"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",
")",
")",
")",
";",
"}"
] |
"Something is editable if it is a node; it is not an editing host; it does not have a contenteditable attribute set to the false state; its parent is an editing host or editable; and either it is an HTML element, or it is an svg or math element, or it is not an Element and its parent is an HTML element."
|
[
"Something",
"is",
"editable",
"if",
"it",
"is",
"a",
"node",
";",
"it",
"is",
"not",
"an",
"editing",
"host",
";",
"it",
"does",
"not",
"have",
"a",
"contenteditable",
"attribute",
"set",
"to",
"the",
"false",
"state",
";",
"its",
"parent",
"is",
"an",
"editing",
"host",
"or",
"editable",
";",
"and",
"either",
"it",
"is",
"an",
"HTML",
"element",
"or",
"it",
"is",
"an",
"svg",
"or",
"math",
"element",
"or",
"it",
"is",
"not",
"an",
"Element",
"and",
"its",
"parent",
"is",
"an",
"HTML",
"element",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L743-L752
|
8,626
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
hasEditableDescendants
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Helper function, not defined in the spec
|
[
"Helper",
"function",
"not",
"defined",
"in",
"the",
"spec"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L755-L763
|
8,627
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
getEditingHostOf
|
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
|
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;
}
}
|
[
"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",
";",
"}",
"}"
] |
"The editing host of node is null if node is neither editable nor an editing host; node itself, if node is an editing host; or the nearest ancestor of node that is an editing host, if node is editable."
|
[
"The",
"editing",
"host",
"of",
"node",
"is",
"null",
"if",
"node",
"is",
"neither",
"editable",
"nor",
"an",
"editing",
"host",
";",
"node",
"itself",
"if",
"node",
"is",
"an",
"editing",
"host",
";",
"or",
"the",
"nearest",
"ancestor",
"of",
"node",
"that",
"is",
"an",
"editing",
"host",
"if",
"node",
"is",
"editable",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L768-L780
|
8,628
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
isCollapsedBlockProp
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
"A collapsed block prop is either a collapsed line break that is not an extraneous line break, or an Element that is an inline node and whose children are all either invisible or collapsed block props and that has at least one child that is a collapsed block prop."
|
[
"A",
"collapsed",
"block",
"prop",
"is",
"either",
"a",
"collapsed",
"line",
"break",
"that",
"is",
"not",
"an",
"extraneous",
"line",
"break",
"or",
"an",
"Element",
"that",
"is",
"an",
"inline",
"node",
"and",
"whose",
"children",
"are",
"all",
"either",
"invisible",
"or",
"collapsed",
"block",
"props",
"and",
"that",
"has",
"at",
"least",
"one",
"child",
"that",
"is",
"a",
"collapsed",
"block",
"prop",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L1034-L1057
|
8,629
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
isFormattableNode
|
function isFormattableNode(node) {
return isEditable(node)
&& isVisible(node)
&& (node.nodeType == Node.TEXT_NODE
|| isHtmlElement(node, ["img", "br"]));
}
|
javascript
|
function isFormattableNode(node) {
return isEditable(node)
&& isVisible(node)
&& (node.nodeType == Node.TEXT_NODE
|| isHtmlElement(node, ["img", "br"]));
}
|
[
"function",
"isFormattableNode",
"(",
"node",
")",
"{",
"return",
"isEditable",
"(",
"node",
")",
"&&",
"isVisible",
"(",
"node",
")",
"&&",
"(",
"node",
".",
"nodeType",
"==",
"Node",
".",
"TEXT_NODE",
"||",
"isHtmlElement",
"(",
"node",
",",
"[",
"\"img\"",
",",
"\"br\"",
"]",
")",
")",
";",
"}"
] |
"A formattable node is an editable visible node that is either a Text node, an img, or a br."
|
[
"A",
"formattable",
"node",
"is",
"an",
"editable",
"visible",
"node",
"that",
"is",
"either",
"a",
"Text",
"node",
"an",
"img",
"or",
"a",
"br",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L1988-L1993
|
8,630
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
areEquivalentValues
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
"Two quantities are equivalent values for a command if either both are null, or both are strings and they're equal and the command does not define any equivalent values, or both are strings and the command defines equivalent values and they match the definition."
|
[
"Two",
"quantities",
"are",
"equivalent",
"values",
"for",
"a",
"command",
"if",
"either",
"both",
"are",
"null",
"or",
"both",
"are",
"strings",
"and",
"they",
"re",
"equal",
"and",
"the",
"command",
"does",
"not",
"define",
"any",
"equivalent",
"values",
"or",
"both",
"are",
"strings",
"and",
"the",
"command",
"defines",
"equivalent",
"values",
"and",
"they",
"match",
"the",
"definition",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L1999-L2019
|
8,631
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
normalizeFontSize
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Helper function for fontSize's action plus queryOutputHelper. It's just the middle of fontSize's action, ripped out into its own function. Returns null if the size is invalid.
|
[
"Helper",
"function",
"for",
"fontSize",
"s",
"action",
"plus",
"queryOutputHelper",
".",
"It",
"s",
"just",
"the",
"middle",
"of",
"fontSize",
"s",
"action",
"ripped",
"out",
"into",
"its",
"own",
"function",
".",
"Returns",
"null",
"if",
"the",
"size",
"is",
"invalid",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L3177-L3245
|
8,632
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
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
|
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);
}
|
[
"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",
")",
";",
"}"
] |
Copy-pasted, same as backColor
|
[
"Copy",
"-",
"pasted",
"same",
"as",
"backColor"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L3394-L3414
|
|
8,633
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
isIndentationElement
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
"An indentation element is either a blockquote, or a div that has a style attribute that sets "margin" or some subproperty of it."
|
[
"An",
"indentation",
"element",
"is",
"either",
"a",
"blockquote",
"or",
"a",
"div",
"that",
"has",
"a",
"style",
"attribute",
"that",
"sets",
"margin",
"or",
"some",
"subproperty",
"of",
"it",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L3702-L3723
|
8,634
|
timdown/rangy
|
src/modules/inactive/commands/aryeh_implementation.js
|
removePreservingDescendants
|
function removePreservingDescendants(node) {
if (node.hasChildNodes()) {
splitParent([].slice.call(node.childNodes));
} else {
node.parentNode.removeChild(node);
}
}
|
javascript
|
function removePreservingDescendants(node) {
if (node.hasChildNodes()) {
splitParent([].slice.call(node.childNodes));
} else {
node.parentNode.removeChild(node);
}
}
|
[
"function",
"removePreservingDescendants",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"hasChildNodes",
"(",
")",
")",
"{",
"splitParent",
"(",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"node",
".",
"childNodes",
")",
")",
";",
"}",
"else",
"{",
"node",
".",
"parentNode",
".",
"removeChild",
"(",
"node",
")",
";",
"}",
"}"
] |
"To remove a node node while preserving its descendants, split the parent of node's children if it has any. If it has no children, instead remove it from its parent."
|
[
"To",
"remove",
"a",
"node",
"node",
"while",
"preserving",
"its",
"descendants",
"split",
"the",
"parent",
"of",
"node",
"s",
"children",
"if",
"it",
"has",
"any",
".",
"If",
"it",
"has",
"no",
"children",
"instead",
"remove",
"it",
"from",
"its",
"parent",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/commands/aryeh_implementation.js#L5146-L5152
|
8,635
|
timdown/rangy
|
src/modules/rangy-classapplier.js
|
hasClass
|
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
|
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);
}
}
|
[
"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",
")",
";",
"}",
"}"
] |
Inefficient, inelegant nonsense for IE's svg element, which has no classList and non-HTML className implementation
|
[
"Inefficient",
"inelegant",
"nonsense",
"for",
"IE",
"s",
"svg",
"element",
"which",
"has",
"no",
"classList",
"and",
"non",
"-",
"HTML",
"className",
"implementation"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/rangy-classapplier.js#L48-L56
|
8,636
|
timdown/rangy
|
src/modules/rangy-classapplier.js
|
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
|
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();
}
|
[
"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",
"(",
")",
";",
"}"
] |
Normalizes nodes after applying a class to a Range.
|
[
"Normalizes",
"nodes",
"after",
"applying",
"a",
"class",
"to",
"a",
"Range",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/rangy-classapplier.js#L696-L751
|
|
8,637
|
timdown/rangy
|
src/modules/rangy-textrange.js
|
getComputedDisplay
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Corrects IE's "block" value for table-related elements
|
[
"Corrects",
"IE",
"s",
"block",
"value",
"for",
"table",
"-",
"related",
"elements"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/rangy-textrange.js#L300-L307
|
8,638
|
timdown/rangy
|
src/modules/rangy-textrange.js
|
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
|
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;
}
}
|
[
"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",
";",
"}",
"}"
] |
Resolve leading and trailing spaces, which may involve prepopulating other positions
|
[
"Resolve",
"leading",
"and",
"trailing",
"spaces",
"which",
"may",
"involve",
"prepopulating",
"other",
"positions"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/rangy-textrange.js#L791-L815
|
|
8,639
|
timdown/rangy
|
src/modules/rangy-textrange.js
|
consumeWord
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Consumes a word and the whitespace beyond it
|
[
"Consumes",
"a",
"word",
"and",
"the",
"whitespace",
"beyond",
"it"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/rangy-textrange.js#L1306-L1339
|
8,640
|
timdown/rangy
|
src/modules/inactive/rangy-commands.js
|
isEditingHost
|
function isEditingHost(node) {
return node &&
((node.nodeType == 9 && node.designMode == "on") ||
(isEditableElement(node) && !isEditableElement(node.parentNode)));
}
|
javascript
|
function isEditingHost(node) {
return node &&
((node.nodeType == 9 && node.designMode == "on") ||
(isEditableElement(node) && !isEditableElement(node.parentNode)));
}
|
[
"function",
"isEditingHost",
"(",
"node",
")",
"{",
"return",
"node",
"&&",
"(",
"(",
"node",
".",
"nodeType",
"==",
"9",
"&&",
"node",
".",
"designMode",
"==",
"\"on\"",
")",
"||",
"(",
"isEditableElement",
"(",
"node",
")",
"&&",
"!",
"isEditableElement",
"(",
"node",
".",
"parentNode",
")",
")",
")",
";",
"}"
] |
"An editing host is a node that is either an Element whose isContentEditable property returns true but whose parent node is not an element or whose isContentEditable property returns false, or a Document whose designMode is enabled."
|
[
"An",
"editing",
"host",
"is",
"a",
"node",
"that",
"is",
"either",
"an",
"Element",
"whose",
"isContentEditable",
"property",
"returns",
"true",
"but",
"whose",
"parent",
"node",
"is",
"not",
"an",
"element",
"or",
"whose",
"isContentEditable",
"property",
"returns",
"false",
"or",
"a",
"Document",
"whose",
"designMode",
"is",
"enabled",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-commands.js#L85-L89
|
8,641
|
timdown/rangy
|
src/modules/inactive/rangy-commands.js
|
isEditable
|
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
|
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) );
}
|
[
"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",
")",
")",
";",
"}"
] |
"A node is editable if it is not an editing host and is or is the child of an Element whose isContentEditable property returns true."
|
[
"A",
"node",
"is",
"editable",
"if",
"it",
"is",
"not",
"an",
"editing",
"host",
"and",
"is",
"or",
"is",
"the",
"child",
"of",
"an",
"Element",
"whose",
"isContentEditable",
"property",
"returns",
"true",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-commands.js#L100-L105
|
8,642
|
timdown/rangy
|
src/modules/inactive/rangy-commands.js
|
isEffectivelyContained
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
"A Node is effectively contained in a Range if either it is contained in the
Range; or it is the Range's start node, it is a Text node, and its length is
different from the Range's start offset; or it is the Range's end node, it
is a Text node, and the Range's end offset is not 0; or it has at least one
child, and all its children are effectively contained in the Range."
|
[
"A",
"Node",
"is",
"effectively",
"contained",
"in",
"a",
"Range",
"if",
"either",
"it",
"is",
"contained",
"in",
"the",
"Range",
";",
"or",
"it",
"is",
"the",
"Range",
"s",
"start",
"node",
"it",
"is",
"a",
"Text",
"node",
"and",
"its",
"length",
"is",
"different",
"from",
"the",
"Range",
"s",
"start",
"offset",
";",
"or",
"it",
"is",
"the",
"Range",
"s",
"end",
"node",
"it",
"is",
"a",
"Text",
"node",
"and",
"the",
"Range",
"s",
"end",
"offset",
"is",
"not",
"0",
";",
"or",
"it",
"has",
"at",
"least",
"one",
"child",
"and",
"all",
"its",
"children",
"are",
"effectively",
"contained",
"in",
"the",
"Range",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-commands.js#L128-L149
|
8,643
|
timdown/rangy
|
src/modules/inactive/rangy-commands.js
|
isInlineNode
|
function isInlineNode(node) {
return dom.isCharacterDataNode(node) ||
(node.nodeType == 1 && inlineDisplayRegex.test(getComputedStyleProperty(node, "display")));
}
|
javascript
|
function isInlineNode(node) {
return dom.isCharacterDataNode(node) ||
(node.nodeType == 1 && inlineDisplayRegex.test(getComputedStyleProperty(node, "display")));
}
|
[
"function",
"isInlineNode",
"(",
"node",
")",
"{",
"return",
"dom",
".",
"isCharacterDataNode",
"(",
"node",
")",
"||",
"(",
"node",
".",
"nodeType",
"==",
"1",
"&&",
"inlineDisplayRegex",
".",
"test",
"(",
"getComputedStyleProperty",
"(",
"node",
",",
"\"display\"",
")",
")",
")",
";",
"}"
] |
"An inline node is either a Text node, or an Element whose 'display'
property computes to 'inline', 'inline-block', or 'inline-table'."
|
[
"An",
"inline",
"node",
"is",
"either",
"a",
"Text",
"node",
"or",
"an",
"Element",
"whose",
"display",
"property",
"computes",
"to",
"inline",
"inline",
"-",
"block",
"or",
"inline",
"-",
"table",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-commands.js#L165-L168
|
8,644
|
timdown/rangy
|
src/modules/inactive/rangy-commands.js
|
valuesEqual
|
function valuesEqual(command, val1, val2) {
if (val1 === null || val2 === null) {
return val1 === val2;
}
return command.valuesEqual(val1, val2);
}
|
javascript
|
function valuesEqual(command, val1, val2) {
if (val1 === null || val2 === null) {
return val1 === val2;
}
return command.valuesEqual(val1, val2);
}
|
[
"function",
"valuesEqual",
"(",
"command",
",",
"val1",
",",
"val2",
")",
"{",
"if",
"(",
"val1",
"===",
"null",
"||",
"val2",
"===",
"null",
")",
"{",
"return",
"val1",
"===",
"val2",
";",
"}",
"return",
"command",
".",
"valuesEqual",
"(",
"val1",
",",
"val2",
")",
";",
"}"
] |
This entire function is a massive hack to work around browser incompatibility. It wouldn't work in real life, but it's good enough for a test implementation. It's not clear how all this should actually be specced in practice, since CSS defines no notion of equality, does it?
|
[
"This",
"entire",
"function",
"is",
"a",
"massive",
"hack",
"to",
"work",
"around",
"browser",
"incompatibility",
".",
"It",
"wouldn",
"t",
"work",
"in",
"real",
"life",
"but",
"it",
"s",
"good",
"enough",
"for",
"a",
"test",
"implementation",
".",
"It",
"s",
"not",
"clear",
"how",
"all",
"this",
"should",
"actually",
"be",
"specced",
"in",
"practice",
"since",
"CSS",
"defines",
"no",
"notion",
"of",
"equality",
"does",
"it?"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-commands.js#L701-L707
|
8,645
|
timdown/rangy
|
src/modules/inactive/rangy-textcommands.js
|
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
|
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();
}
|
[
"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",
"(",
")",
";",
"}"
] |
Normalizes nodes after applying a CSS class to a Range.
|
[
"Normalizes",
"nodes",
"after",
"applying",
"a",
"CSS",
"class",
"to",
"a",
"Range",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-textcommands.js#L238-L296
|
|
8,646
|
timdown/rangy
|
src/modules/inactive/rangy-position.js
|
getScrollPosition
|
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
|
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 };
}
|
[
"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",
"}",
";",
"}"
] |
Since Rangy can deal with multiple documents which could be in different modes, we have to do the checks every time, unless we cache a getScrollPosition function in each document. This would necessarily pollute the document's global namespace, which I'm choosing to view as a greater evil than a slight performance hit.
|
[
"Since",
"Rangy",
"can",
"deal",
"with",
"multiple",
"documents",
"which",
"could",
"be",
"in",
"different",
"modes",
"we",
"have",
"to",
"do",
"the",
"checks",
"every",
"time",
"unless",
"we",
"cache",
"a",
"getScrollPosition",
"function",
"in",
"each",
"document",
".",
"This",
"would",
"necessarily",
"pollute",
"the",
"document",
"s",
"global",
"namespace",
"which",
"I",
"m",
"choosing",
"to",
"view",
"as",
"a",
"greater",
"evil",
"than",
"a",
"slight",
"performance",
"hit",
"."
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-position.js#L30-L50
|
8,647
|
timdown/rangy
|
src/modules/inactive/rangy-position.js
|
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
|
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));
}
|
[
"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",
")",
")",
";",
"}"
] |
This implementation is very naive. There are many browser quirks that make it extremely difficult to get accurate element coordinates in all situations
|
[
"This",
"implementation",
"is",
"very",
"naive",
".",
"There",
"are",
"many",
"browser",
"quirks",
"that",
"make",
"it",
"extremely",
"difficult",
"to",
"get",
"accurate",
"element",
"coordinates",
"in",
"all",
"situations"
] |
1e55169d2e4d1d9458c2a87119addf47a8265276
|
https://github.com/timdown/rangy/blob/1e55169d2e4d1d9458c2a87119addf47a8265276/src/modules/inactive/rangy-position.js#L400-L409
|
|
8,648
|
artilleryio/artillery
|
core/lib/engine_util.js
|
templateObjectOrArray
|
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
|
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);
});
}
|
[
"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",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"value",
")",
"}",
"${",
"typeof",
"value",
"}",
"${",
"subj",
".",
"length",
"?",
"'list'",
":",
"'hash'",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"newValue",
")",
"}",
"${",
"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",
")",
";",
"}",
")",
";",
"}"
] |
Mutates the object in place
|
[
"Mutates",
"the",
"object",
"in",
"place"
] |
e8023099e7b05a712dba6d627ce5ea221f75d142
|
https://github.com/artilleryio/artillery/blob/e8023099e7b05a712dba6d627ce5ea221f75d142/core/lib/engine_util.js#L240-L262
|
8,649
|
artilleryio/artillery
|
core/lib/engine_util.js
|
extractJSONPath
|
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
|
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];
}
}
|
[
"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",
"]",
";",
"}",
"}"
] |
doc is a JSON object
|
[
"doc",
"is",
"a",
"JSON",
"object"
] |
e8023099e7b05a712dba6d627ce5ea221f75d142
|
https://github.com/artilleryio/artillery/blob/e8023099e7b05a712dba6d627ce5ea221f75d142/core/lib/engine_util.js#L499-L522
|
8,650
|
artilleryio/artillery
|
lib/dist.js
|
divideWork
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Create a number of scripts for workers from the script given to use by user.
|
[
"Create",
"a",
"number",
"of",
"scripts",
"for",
"workers",
"from",
"the",
"script",
"given",
"to",
"use",
"by",
"user",
"."
] |
e8023099e7b05a712dba6d627ce5ea221f75d142
|
https://github.com/artilleryio/artillery/blob/e8023099e7b05a712dba6d627ce5ea221f75d142/lib/dist.js#L15-L82
|
8,651
|
artilleryio/artillery
|
lib/dist.js
|
distribute
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Given M "things", distribute them between N peers as equally as possible
|
[
"Given",
"M",
"things",
"distribute",
"them",
"between",
"N",
"peers",
"as",
"equally",
"as",
"possible"
] |
e8023099e7b05a712dba6d627ce5ea221f75d142
|
https://github.com/artilleryio/artillery/blob/e8023099e7b05a712dba6d627ce5ea221f75d142/lib/dist.js#L88-L111
|
8,652
|
artilleryio/artillery
|
core/lib/weighted-pick.js
|
create
|
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
|
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]];
};
}
|
[
"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",
"]",
"]",
";",
"}",
";",
"}"
] |
naive implementation of selection with replacement
|
[
"naive",
"implementation",
"of",
"selection",
"with",
"replacement"
] |
e8023099e7b05a712dba6d627ce5ea221f75d142
|
https://github.com/artilleryio/artillery/blob/e8023099e7b05a712dba6d627ce5ea221f75d142/core/lib/weighted-pick.js#L12-L24
|
8,653
|
artilleryio/artillery
|
core/lib/runner.js
|
createContext
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Create initial context for a scenario.
|
[
"Create",
"initial",
"context",
"for",
"a",
"scenario",
"."
] |
e8023099e7b05a712dba6d627ce5ea221f75d142
|
https://github.com/artilleryio/artillery/blob/e8023099e7b05a712dba6d627ce5ea221f75d142/core/lib/runner.js#L450-L476
|
8,654
|
artilleryio/artillery
|
core/lib/stats2.js
|
combine
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Combine several stats objects from different workers into one
|
[
"Combine",
"several",
"stats",
"objects",
"from",
"different",
"workers",
"into",
"one"
] |
e8023099e7b05a712dba6d627ce5ea221f75d142
|
https://github.com/artilleryio/artillery/blob/e8023099e7b05a712dba6d627ce5ea221f75d142/core/lib/stats2.js#L26-L86
|
8,655
|
artilleryio/artillery
|
core/lib/engine_http.js
|
ensurePropertyIsAList
|
function ensurePropertyIsAList(obj, prop) {
obj[prop] = [].concat(
typeof obj[prop] === 'undefined' ?
[] : obj[prop]);
return obj;
}
|
javascript
|
function ensurePropertyIsAList(obj, prop) {
obj[prop] = [].concat(
typeof obj[prop] === 'undefined' ?
[] : obj[prop]);
return obj;
}
|
[
"function",
"ensurePropertyIsAList",
"(",
"obj",
",",
"prop",
")",
"{",
"obj",
"[",
"prop",
"]",
"=",
"[",
"]",
".",
"concat",
"(",
"typeof",
"obj",
"[",
"prop",
"]",
"===",
"'undefined'",
"?",
"[",
"]",
":",
"obj",
"[",
"prop",
"]",
")",
";",
"return",
"obj",
";",
"}"
] |
Helper function to wrap an object's property in a list if it's defined, or set it to an empty list if not.
|
[
"Helper",
"function",
"to",
"wrap",
"an",
"object",
"s",
"property",
"in",
"a",
"list",
"if",
"it",
"s",
"defined",
"or",
"set",
"it",
"to",
"an",
"empty",
"list",
"if",
"not",
"."
] |
e8023099e7b05a712dba6d627ce5ea221f75d142
|
https://github.com/artilleryio/artillery/blob/e8023099e7b05a712dba6d627ce5ea221f75d142/core/lib/engine_http.js#L57-L62
|
8,656
|
apache/cordova-node-xcode
|
lib/pbxProject.js
|
propReplace
|
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
|
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;
}
}
}
}
|
[
"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",
";",
"}",
"}",
"}",
"}"
] |
helper recursive prop search+replace
|
[
"helper",
"recursive",
"prop",
"search",
"+",
"replace"
] |
a65e1943ed8c71d93e4c673d0a7aabf4ebca7623
|
https://github.com/apache/cordova-node-xcode/blob/a65e1943ed8c71d93e4c673d0a7aabf4ebca7623/lib/pbxProject.js#L1495-L1506
|
8,657
|
apache/cordova-node-xcode
|
lib/pbxProject.js
|
pbxBuildFileObj
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
helper object creation functions
|
[
"helper",
"object",
"creation",
"functions"
] |
a65e1943ed8c71d93e4c673d0a7aabf4ebca7623
|
https://github.com/apache/cordova-node-xcode/blob/a65e1943ed8c71d93e4c673d0a7aabf4ebca7623/lib/pbxProject.js#L1509-L1518
|
8,658
|
johnculviner/jquery.fileDownload
|
src/Scripts/jquery.fileDownload.js
|
getiframeDocument
|
function getiframeDocument($iframe) {
var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframeDoc.document) {
iframeDoc = iframeDoc.document;
}
return iframeDoc;
}
|
javascript
|
function getiframeDocument($iframe) {
var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframeDoc.document) {
iframeDoc = iframeDoc.document;
}
return iframeDoc;
}
|
[
"function",
"getiframeDocument",
"(",
"$iframe",
")",
"{",
"var",
"iframeDoc",
"=",
"$iframe",
"[",
"0",
"]",
".",
"contentWindow",
"||",
"$iframe",
"[",
"0",
"]",
".",
"contentDocument",
";",
"if",
"(",
"iframeDoc",
".",
"document",
")",
"{",
"iframeDoc",
"=",
"iframeDoc",
".",
"document",
";",
"}",
"return",
"iframeDoc",
";",
"}"
] |
gets an iframes document in a cross browser compatible manner
|
[
"gets",
"an",
"iframes",
"document",
"in",
"a",
"cross",
"browser",
"compatible",
"manner"
] |
67859ca512d8ab35a44b2ff26473e18350172fac
|
https://github.com/johnculviner/jquery.fileDownload/blob/67859ca512d8ab35a44b2ff26473e18350172fac/src/Scripts/jquery.fileDownload.js#L437-L443
|
8,659
|
skanaar/nomnoml
|
src/renderer.js
|
quadrant
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
find basic quadrant using relative position of endpoint and block rectangle
|
[
"find",
"basic",
"quadrant",
"using",
"relative",
"position",
"of",
"endpoint",
"and",
"block",
"rectangle"
] |
188b359e9cd3cc56b9a7b3d4e897bf1191b9910c
|
https://github.com/skanaar/nomnoml/blob/188b359e9cd3cc56b9a7b3d4e897bf1191b9910c/src/renderer.js#L108-L114
|
8,660
|
skanaar/nomnoml
|
src/renderer.js
|
adjustQuadrant
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Flip basic label quadrant if needed, to avoid crossing a bent relationship line
|
[
"Flip",
"basic",
"label",
"quadrant",
"if",
"needed",
"to",
"avoid",
"crossing",
"a",
"bent",
"relationship",
"line"
] |
188b359e9cd3cc56b9a7b3d4e897bf1191b9910c
|
https://github.com/skanaar/nomnoml/blob/188b359e9cd3cc56b9a7b3d4e897bf1191b9910c/src/renderer.js#L117-L130
|
8,661
|
jscottsmith/react-scroll-parallax
|
src/classes/ParallaxController.js
|
_updateAllElements
|
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
|
function _updateAllElements({ updateCache } = {}) {
elements.forEach(element => {
_updateElementPosition(element);
if (updateCache) {
element.setCachedAttributes(view, scroll);
}
});
// reset ticking so more animations can be called
ticking = false;
}
|
[
"function",
"_updateAllElements",
"(",
"{",
"updateCache",
"}",
"=",
"{",
"}",
")",
"{",
"elements",
".",
"forEach",
"(",
"element",
"=>",
"{",
"_updateElementPosition",
"(",
"element",
")",
";",
"if",
"(",
"updateCache",
")",
"{",
"element",
".",
"setCachedAttributes",
"(",
"view",
",",
"scroll",
")",
";",
"}",
"}",
")",
";",
"// reset ticking so more animations can be called",
"ticking",
"=",
"false",
";",
"}"
] |
Update element positions.
Determines if the element is in view based on the cached
attributes, if so set the elements parallax styles.
|
[
"Update",
"element",
"positions",
".",
"Determines",
"if",
"the",
"element",
"is",
"in",
"view",
"based",
"on",
"the",
"cached",
"attributes",
"if",
"so",
"set",
"the",
"elements",
"parallax",
"styles",
"."
] |
6404cf1cef94734bf1bc179e951d7d1dafc4d309
|
https://github.com/jscottsmith/react-scroll-parallax/blob/6404cf1cef94734bf1bc179e951d7d1dafc4d309/src/classes/ParallaxController.js#L93-L102
|
8,662
|
jscottsmith/react-scroll-parallax
|
src/classes/ParallaxController.js
|
_setViewSize
|
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
|
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);
}
|
[
"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",
")",
";",
"}"
] |
Cache the window height.
|
[
"Cache",
"the",
"window",
"height",
"."
] |
6404cf1cef94734bf1bc179e951d7d1dafc4d309
|
https://github.com/jscottsmith/react-scroll-parallax/blob/6404cf1cef94734bf1bc179e951d7d1dafc4d309/src/classes/ParallaxController.js#L117-L129
|
8,663
|
nx-js/observer-util
|
src/handlers.js
|
get
|
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
|
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
}
|
[
"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",
"}"
] |
intercept get operations on observables to know which reaction uses their properties
|
[
"intercept",
"get",
"operations",
"on",
"observables",
"to",
"know",
"which",
"reaction",
"uses",
"their",
"properties"
] |
62aebe1bb8c92572a1dbbd236600f20cba0f6ae9
|
https://github.com/nx-js/observer-util/blob/62aebe1bb8c92572a1dbbd236600f20cba0f6ae9/src/handlers.js#L17-L45
|
8,664
|
nx-js/observer-util
|
src/handlers.js
|
set
|
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
|
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
}
|
[
"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",
"}"
] |
intercept set operations on observables to know when to trigger reactions
|
[
"intercept",
"set",
"operations",
"on",
"observables",
"to",
"know",
"when",
"to",
"trigger",
"reactions"
] |
62aebe1bb8c92572a1dbbd236600f20cba0f6ae9
|
https://github.com/nx-js/observer-util/blob/62aebe1bb8c92572a1dbbd236600f20cba0f6ae9/src/handlers.js#L60-L90
|
8,665
|
s-yadav/react-number-format
|
lib/utils.js
|
splitDecimal
|
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
|
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
};
}
|
[
"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",
"}",
";",
"}"
] |
spilt a float number into different parts beforeDecimal, afterDecimal, and negation
|
[
"spilt",
"a",
"float",
"number",
"into",
"different",
"parts",
"beforeDecimal",
"afterDecimal",
"and",
"negation"
] |
6a1113ff90ba69e479ec2b9902799f1ab2e69082
|
https://github.com/s-yadav/react-number-format/blob/6a1113ff90ba69e479ec2b9902799f1ab2e69082/lib/utils.js#L58-L72
|
8,666
|
s-yadav/react-number-format
|
lib/utils.js
|
limitToScale
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
limit decimal numbers to given scale
Not used .fixedTo because that will break with big numbers
|
[
"limit",
"decimal",
"numbers",
"to",
"given",
"scale",
"Not",
"used",
".",
"fixedTo",
"because",
"that",
"will",
"break",
"with",
"big",
"numbers"
] |
6a1113ff90ba69e479ec2b9902799f1ab2e69082
|
https://github.com/s-yadav/react-number-format/blob/6a1113ff90ba69e479ec2b9902799f1ab2e69082/lib/utils.js#L89-L98
|
8,667
|
s-yadav/react-number-format
|
lib/utils.js
|
roundToPrecision
|
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
|
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);
}
|
[
"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",
")",
";",
"}"
] |
This method is required to round prop value to given scale.
Not used .round or .fixedTo because that will break with big numbers
|
[
"This",
"method",
"is",
"required",
"to",
"round",
"prop",
"value",
"to",
"given",
"scale",
".",
"Not",
"used",
".",
"round",
"or",
".",
"fixedTo",
"because",
"that",
"will",
"break",
"with",
"big",
"numbers"
] |
6a1113ff90ba69e479ec2b9902799f1ab2e69082
|
https://github.com/s-yadav/react-number-format/blob/6a1113ff90ba69e479ec2b9902799f1ab2e69082/lib/utils.js#L105-L127
|
8,668
|
s-yadav/react-number-format
|
lib/utils.js
|
findChangedIndex
|
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
|
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
};
}
|
[
"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",
"}",
";",
"}"
] |
Given previous value and newValue it returns the index
start - end to which values have changed.
This function makes assumption about only consecutive
characters are changed which is correct assumption for caret input.
|
[
"Given",
"previous",
"value",
"and",
"newValue",
"it",
"returns",
"the",
"index",
"start",
"-",
"end",
"to",
"which",
"values",
"have",
"changed",
".",
"This",
"function",
"makes",
"assumption",
"about",
"only",
"consecutive",
"characters",
"are",
"changed",
"which",
"is",
"correct",
"assumption",
"for",
"caret",
"input",
"."
] |
6a1113ff90ba69e479ec2b9902799f1ab2e69082
|
https://github.com/s-yadav/react-number-format/blob/6a1113ff90ba69e479ec2b9902799f1ab2e69082/lib/utils.js#L172-L191
|
8,669
|
s-yadav/react-number-format
|
custom_formatters/card_expiry.js
|
limit
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
This method limit val between 1 to max
val and max both are passed as string
|
[
"This",
"method",
"limit",
"val",
"between",
"1",
"to",
"max",
"val",
"and",
"max",
"both",
"are",
"passed",
"as",
"string"
] |
6a1113ff90ba69e479ec2b9902799f1ab2e69082
|
https://github.com/s-yadav/react-number-format/blob/6a1113ff90ba69e479ec2b9902799f1ab2e69082/custom_formatters/card_expiry.js#L5-L21
|
8,670
|
wework/speccy
|
lib/loader.js
|
readSpecFile
|
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
|
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');
}
}
|
[
"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",
"(",
"`",
"${",
"res",
".",
"status",
"}",
"`",
")",
";",
"}",
"return",
"res",
".",
"text",
"(",
")",
";",
"}",
")",
"}",
"else",
"{",
"// local file",
"// TODO error handlers?",
"return",
"readFileAsync",
"(",
"file",
",",
"'utf8'",
")",
";",
"}",
"}"
] |
file can be null, meaning stdin
|
[
"file",
"can",
"be",
"null",
"meaning",
"stdin"
] |
740d19d88935db7735250c16abc2ad09256b5854
|
https://github.com/wework/speccy/blob/740d19d88935db7735250c16abc2ad09256b5854/lib/loader.js#L65-L85
|
8,671
|
stdlib-js/stdlib
|
etc/typedoc/theme/assets/js/theme.js
|
cleanPath
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
eslint-disable-line func-names, no-restricted-syntax
Removes extraneous information from a path.
@private
@param {string} txt - text 1
@returns {string} cleaned text
|
[
"eslint",
"-",
"disable",
"-",
"line",
"func",
"-",
"names",
"no",
"-",
"restricted",
"-",
"syntax",
"Removes",
"extraneous",
"information",
"from",
"a",
"path",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/etc/typedoc/theme/assets/js/theme.js#L29-L52
|
8,672
|
stdlib-js/stdlib
|
etc/typedoc/theme/assets/js/theme.js
|
cleanTitle
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Cleans up the document title.
@private
@param {DOMElement} el - title element
|
[
"Cleans",
"up",
"the",
"document",
"title",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/etc/typedoc/theme/assets/js/theme.js#L60-L69
|
8,673
|
stdlib-js/stdlib
|
etc/typedoc/theme/assets/js/theme.js
|
cleanLinks
|
function cleanLinks( el ) {
var i;
for ( i = 0; i < el.length; i++ ) {
el[ i ].innerHTML = cleanPath( el[ i ].innerHTML );
}
}
|
javascript
|
function cleanLinks( el ) {
var i;
for ( i = 0; i < el.length; i++ ) {
el[ i ].innerHTML = cleanPath( el[ i ].innerHTML );
}
}
|
[
"function",
"cleanLinks",
"(",
"el",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"el",
".",
"length",
";",
"i",
"++",
")",
"{",
"el",
"[",
"i",
"]",
".",
"innerHTML",
"=",
"cleanPath",
"(",
"el",
"[",
"i",
"]",
".",
"innerHTML",
")",
";",
"}",
"}"
] |
Cleans up link text.
@private
@param {Array<DOMElement>} el - list of anchor elements to clean
|
[
"Cleans",
"up",
"link",
"text",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/etc/typedoc/theme/assets/js/theme.js#L77-L82
|
8,674
|
stdlib-js/stdlib
|
etc/typedoc/theme/assets/js/theme.js
|
cleanHeadings
|
function cleanHeadings( el ) {
var i;
for ( i = 0; i < el.length; i++ ) {
el[ i ].innerHTML = cleanHeading( el[ i ].innerHTML );
}
}
|
javascript
|
function cleanHeadings( el ) {
var i;
for ( i = 0; i < el.length; i++ ) {
el[ i ].innerHTML = cleanHeading( el[ i ].innerHTML );
}
}
|
[
"function",
"cleanHeadings",
"(",
"el",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"el",
".",
"length",
";",
"i",
"++",
")",
"{",
"el",
"[",
"i",
"]",
".",
"innerHTML",
"=",
"cleanHeading",
"(",
"el",
"[",
"i",
"]",
".",
"innerHTML",
")",
";",
"}",
"}"
] |
Cleans up heading text.
@private
@param {Array<DOMElement>} el - list of heading elements to clean
|
[
"Cleans",
"up",
"heading",
"text",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/etc/typedoc/theme/assets/js/theme.js#L104-L109
|
8,675
|
stdlib-js/stdlib
|
etc/typedoc/theme/assets/js/theme.js
|
updateDescription
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Updates a description.
@private
@param {string} txt - description
@returns {string} updated description
|
[
"Updates",
"a",
"description",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/etc/typedoc/theme/assets/js/theme.js#L118-L131
|
8,676
|
stdlib-js/stdlib
|
etc/typedoc/theme/assets/js/theme.js
|
main
|
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
|
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 );
}
|
[
"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",
")",
";",
"}"
] |
Main execution sequence.
@private
|
[
"Main",
"execution",
"sequence",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/etc/typedoc/theme/assets/js/theme.js#L151-L174
|
8,677
|
stdlib-js/stdlib
|
tools/docs/jsdoc/templates/json/transforms/mixin/index.js
|
transform
|
function transform( node ) {
return {
'name': node.name,
'description': node.description || '',
'access': node.access || '',
'virtual': !!node.virtual
};
}
|
javascript
|
function transform( node ) {
return {
'name': node.name,
'description': node.description || '',
'access': node.access || '',
'virtual': !!node.virtual
};
}
|
[
"function",
"transform",
"(",
"node",
")",
"{",
"return",
"{",
"'name'",
":",
"node",
".",
"name",
",",
"'description'",
":",
"node",
".",
"description",
"||",
"''",
",",
"'access'",
":",
"node",
".",
"access",
"||",
"''",
",",
"'virtual'",
":",
"!",
"!",
"node",
".",
"virtual",
"}",
";",
"}"
] |
Transforms a `mixin` doclet element.
@param {Object} node - doclet element
@returns {Object} filtered object
|
[
"Transforms",
"a",
"mixin",
"doclet",
"element",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/tools/docs/jsdoc/templates/json/transforms/mixin/index.js#L9-L16
|
8,678
|
stdlib-js/stdlib
|
tools/docs/jsdoc/templates/json/transforms/member/index.js
|
transform
|
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
|
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
};
}
|
[
"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",
"}",
";",
"}"
] |
Transforms a `member` doclet element.
@param {Object} node - doclet element
@returns {Object} filtered object
|
[
"Transforms",
"a",
"member",
"doclet",
"element",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/tools/docs/jsdoc/templates/json/transforms/member/index.js#L9-L27
|
8,679
|
stdlib-js/stdlib
|
tools/snippets/benchmark/benchmark.length.js
|
benchmark
|
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
|
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();
}
|
[
"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",
"(",
")",
";",
"}"
] |
Benchmark function.
@private
@param {Benchmark} b - benchmark instance
|
[
"Benchmark",
"function",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/tools/snippets/benchmark/benchmark.length.js#L54-L70
|
8,680
|
stdlib-js/stdlib
|
tools/docs/jsdoc/templates/json/transforms/function/returns.js
|
transform
|
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
|
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
};
}
|
[
"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",
"}",
";",
"}"
] |
Transforms `returns` doclet elements.
@param {Object[]} nodes - doclet elements
@returns {Object} filtered object
|
[
"Transforms",
"returns",
"doclet",
"elements",
"."
] |
1026b15f47f0b4d2c0db8617f22a35873c514919
|
https://github.com/stdlib-js/stdlib/blob/1026b15f47f0b4d2c0db8617f22a35873c514919/tools/docs/jsdoc/templates/json/transforms/function/returns.js#L9-L26
|
8,681
|
reactjs/react-docgen
|
src/utils/getMethodDocumentation.js
|
getMethodReturnDoc
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Extract flow return type.
|
[
"Extract",
"flow",
"return",
"type",
"."
] |
f78450432c6b1cad788327a2f97f782091958b7a
|
https://github.com/reactjs/react-docgen/blob/f78450432c6b1cad788327a2f97f782091958b7a/src/utils/getMethodDocumentation.js#L72-L85
|
8,682
|
reactjs/react-docgen
|
src/handlers/propTypeCompositionHandler.js
|
amendComposes
|
function amendComposes(documentation, path) {
const moduleName = resolveToModule(path);
if (moduleName) {
documentation.addComposes(moduleName);
}
}
|
javascript
|
function amendComposes(documentation, path) {
const moduleName = resolveToModule(path);
if (moduleName) {
documentation.addComposes(moduleName);
}
}
|
[
"function",
"amendComposes",
"(",
"documentation",
",",
"path",
")",
"{",
"const",
"moduleName",
"=",
"resolveToModule",
"(",
"path",
")",
";",
"if",
"(",
"moduleName",
")",
"{",
"documentation",
".",
"addComposes",
"(",
"moduleName",
")",
";",
"}",
"}"
] |
It resolves the path to its module name and adds it to the "composes" entry
in the documentation.
|
[
"It",
"resolves",
"the",
"path",
"to",
"its",
"module",
"name",
"and",
"adds",
"it",
"to",
"the",
"composes",
"entry",
"in",
"the",
"documentation",
"."
] |
f78450432c6b1cad788327a2f97f782091958b7a
|
https://github.com/reactjs/react-docgen/blob/f78450432c6b1cad788327a2f97f782091958b7a/src/handlers/propTypeCompositionHandler.js#L22-L27
|
8,683
|
aws/aws-iot-device-sdk-js
|
device/lib/tls.js
|
buildBuilder
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
npm deps app deps
|
[
"npm",
"deps",
"app",
"deps"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/device/lib/tls.js#L23-L43
|
8,684
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
errorToString
|
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
|
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();
}
}
|
[
"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",
"(",
")",
";",
"}",
"}"
] |
Private function to safely convert errors to strings
|
[
"Private",
"function",
"to",
"safely",
"convert",
"errors",
"to",
"strings"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L102-L110
|
8,685
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
validateChecksum
|
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
|
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);
});
}
|
[
"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",
")",
";",
"}",
")",
";",
"}"
] |
Private function to validate checksum
|
[
"Private",
"function",
"to",
"validate",
"checksum"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L115-L150
|
8,686
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
validateSignature
|
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
|
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);
});
}
|
[
"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",
")",
";",
"}",
")",
";",
"}"
] |
Private function to validate signature
|
[
"Private",
"function",
"to",
"validate",
"signature"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L156-L213
|
8,687
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
backupFiles
|
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
|
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);
}
});
});
}
|
[
"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",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Private function to backup existing files before downloading
|
[
"Private",
"function",
"to",
"backup",
"existing",
"files",
"before",
"downloading"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L219-L257
|
8,688
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
rollbackFiles
|
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
|
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);
});
});
});
}
|
[
"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",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Private function to rollback files after a failed install operation
|
[
"Private",
"function",
"to",
"rollback",
"files",
"after",
"a",
"failed",
"install",
"operation"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L263-L289
|
8,689
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
downloadFiles
|
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
|
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);
}
});
});
}
|
[
"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",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Private function to download specified files in sequence to temporary locations
|
[
"Private",
"function",
"to",
"download",
"specified",
"files",
"in",
"sequence",
"to",
"temporary",
"locations"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L295-L339
|
8,690
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
updateInstalledPackage
|
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
|
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));
}
|
[
"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",
")",
")",
";",
"}"
] |
Private function to update installed package
|
[
"Private",
"function",
"to",
"update",
"installed",
"package"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L345-L358
|
8,691
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
startPackage
|
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
|
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;
}
});
}
|
[
"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",
";",
"}",
"}",
")",
";",
"}"
] |
Private function to start installed package
|
[
"Private",
"function",
"to",
"start",
"installed",
"package"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L414-L444
|
8,692
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
shutdownHandler
|
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
|
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);
});
}
});
});
}
|
[
"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",
")",
";",
"}",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Private function to handle gracefull shutdown operation
|
[
"Private",
"function",
"to",
"handle",
"gracefull",
"shutdown",
"operation"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L580-L603
|
8,693
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
rebootHandler
|
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
|
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);
}
}
|
[
"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",
")",
";",
"}",
"}"
] |
Private function to handle reboot operation
|
[
"Private",
"function",
"to",
"handle",
"reboot",
"operation"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L609-L637
|
8,694
|
aws/aws-iot-device-sdk-js
|
examples/jobs-agent.js
|
systemStatusHandler
|
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
|
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);
}
|
[
"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",
")",
";",
"}"
] |
Private function to handle systemStatus operation
|
[
"Private",
"function",
"to",
"handle",
"systemStatus",
"operation"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/examples/jobs-agent.js#L643-L661
|
8,695
|
aws/aws-iot-device-sdk-js
|
device/index.js
|
_markConnectionStable
|
function _markConnectionStable() {
currentReconnectTimeMs = baseReconnectTimeMs;
device.options.reconnectPeriod = currentReconnectTimeMs;
//
// Mark this timeout as expired
//
connectionTimer = null;
connectionState = 'stable';
}
|
javascript
|
function _markConnectionStable() {
currentReconnectTimeMs = baseReconnectTimeMs;
device.options.reconnectPeriod = currentReconnectTimeMs;
//
// Mark this timeout as expired
//
connectionTimer = null;
connectionState = 'stable';
}
|
[
"function",
"_markConnectionStable",
"(",
")",
"{",
"currentReconnectTimeMs",
"=",
"baseReconnectTimeMs",
";",
"device",
".",
"options",
".",
"reconnectPeriod",
"=",
"currentReconnectTimeMs",
";",
"//",
"// Mark this timeout as expired",
"//",
"connectionTimer",
"=",
"null",
";",
"connectionState",
"=",
"'stable'",
";",
"}"
] |
Timeout expiry function for the connection timer; once a connection is stable, reset the current reconnection time to the base value.
|
[
"Timeout",
"expiry",
"function",
"for",
"the",
"connection",
"timer",
";",
"once",
"a",
"connection",
"is",
"stable",
"reset",
"the",
"current",
"reconnection",
"time",
"to",
"the",
"base",
"value",
"."
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/device/index.js#L647-L655
|
8,696
|
aws/aws-iot-device-sdk-js
|
device/index.js
|
_trimOfflinePublishQueueIfNecessary
|
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
|
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;
}
|
[
"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",
";",
"}"
] |
Trim the offline queue if required; returns true if another element can be placed in the queue
|
[
"Trim",
"the",
"offline",
"queue",
"if",
"required",
";",
"returns",
"true",
"if",
"another",
"element",
"can",
"be",
"placed",
"in",
"the",
"queue"
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/device/index.js#L660-L676
|
8,697
|
aws/aws-iot-device-sdk-js
|
device/index.js
|
_drainOperationQueue
|
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
|
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;
}
}
}
}
|
[
"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",
";",
"}",
"}",
"}",
"}"
] |
Timeout expiry function for the drain timer; once a connection has been established, begin draining cached transactions.
|
[
"Timeout",
"expiry",
"function",
"for",
"the",
"drain",
"timer",
";",
"once",
"a",
"connection",
"has",
"been",
"established",
"begin",
"draining",
"cached",
"transactions",
"."
] |
481445639ff6bb92586c63d3c9ee85dd37728453
|
https://github.com/aws/aws-iot-device-sdk-js/blob/481445639ff6bb92586c63d3c9ee85dd37728453/device/index.js#L682-L744
|
8,698
|
siimon/prom-client
|
lib/metricAggregators.js
|
AggregatorFactory
|
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
|
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;
};
}
|
[
"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",
";",
"}",
";",
"}"
] |
Returns a new function that applies the `aggregatorFn` to the values.
@param {Function} aggregatorFn function to apply to values.
@return {Function} aggregator function
|
[
"Returns",
"a",
"new",
"function",
"that",
"applies",
"the",
"aggregatorFn",
"to",
"the",
"values",
"."
] |
b66755a6f79c7483dc899360eaf9759f330cd420
|
https://github.com/siimon/prom-client/blob/b66755a6f79c7483dc899360eaf9759f330cd420/lib/metricAggregators.js#L10-L43
|
8,699
|
amireh/happypack
|
lib/HappyForegroundThreadPool.js
|
HappyForegroundThreadPool
|
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
|
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);
});
},
};
}
|
[
"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",
")",
";",
"}",
")",
";",
"}",
",",
"}",
";",
"}"
] |
Create a thread pool that can be shared between multiple plugin instances.
@param {Object} config
@param {Array.<String>} config.loaders
The loaders to configure the (foreground) worker with.
|
[
"Create",
"a",
"thread",
"pool",
"that",
"can",
"be",
"shared",
"between",
"multiple",
"plugin",
"instances",
"."
] |
e45926e9754f42098d882ff129269b15907ef00e
|
https://github.com/amireh/happypack/blob/e45926e9754f42098d882ff129269b15907ef00e/lib/HappyForegroundThreadPool.js#L13-L68
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.