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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,800 | decaffeinate/bulk-decaffeinate | src/config/resolveConfig.js | resolveBinary | async function resolveBinary(binaryName) {
let nodeModulesPath = `./node_modules/.bin/${binaryName}`;
if (await exists(nodeModulesPath)) {
return nodeModulesPath;
} else {
try {
await exec(`which ${binaryName}`);
return binaryName;
} catch (e) {
console.log(`${binaryName} binary not found on the PATH or in node_modules.`);
let rl = readline.createInterface(process.stdin, process.stdout);
let answer = await rl.question(`Run "npm install -g ${binaryName}"? [Y/n] `);
rl.close();
if (answer.toLowerCase().startsWith('n')) {
throw new CLIError(`${binaryName} must be installed.`);
}
console.log(`Installing ${binaryName} globally...`);
await execLive(`npm install -g ${binaryName}`);
console.log(`Successfully installed ${binaryName}\n`);
return binaryName;
}
}
} | javascript | async function resolveBinary(binaryName) {
let nodeModulesPath = `./node_modules/.bin/${binaryName}`;
if (await exists(nodeModulesPath)) {
return nodeModulesPath;
} else {
try {
await exec(`which ${binaryName}`);
return binaryName;
} catch (e) {
console.log(`${binaryName} binary not found on the PATH or in node_modules.`);
let rl = readline.createInterface(process.stdin, process.stdout);
let answer = await rl.question(`Run "npm install -g ${binaryName}"? [Y/n] `);
rl.close();
if (answer.toLowerCase().startsWith('n')) {
throw new CLIError(`${binaryName} must be installed.`);
}
console.log(`Installing ${binaryName} globally...`);
await execLive(`npm install -g ${binaryName}`);
console.log(`Successfully installed ${binaryName}\n`);
return binaryName;
}
}
} | [
"async",
"function",
"resolveBinary",
"(",
"binaryName",
")",
"{",
"let",
"nodeModulesPath",
"=",
"`",
"${",
"binaryName",
"}",
"`",
";",
"if",
"(",
"await",
"exists",
"(",
"nodeModulesPath",
")",
")",
"{",
"return",
"nodeModulesPath",
";",
"}",
"else",
"{",
"try",
"{",
"await",
"exec",
"(",
"`",
"${",
"binaryName",
"}",
"`",
")",
";",
"return",
"binaryName",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"`",
"${",
"binaryName",
"}",
"`",
")",
";",
"let",
"rl",
"=",
"readline",
".",
"createInterface",
"(",
"process",
".",
"stdin",
",",
"process",
".",
"stdout",
")",
";",
"let",
"answer",
"=",
"await",
"rl",
".",
"question",
"(",
"`",
"${",
"binaryName",
"}",
"`",
")",
";",
"rl",
".",
"close",
"(",
")",
";",
"if",
"(",
"answer",
".",
"toLowerCase",
"(",
")",
".",
"startsWith",
"(",
"'n'",
")",
")",
"{",
"throw",
"new",
"CLIError",
"(",
"`",
"${",
"binaryName",
"}",
"`",
")",
";",
"}",
"console",
".",
"log",
"(",
"`",
"${",
"binaryName",
"}",
"`",
")",
";",
"await",
"execLive",
"(",
"`",
"${",
"binaryName",
"}",
"`",
")",
";",
"console",
".",
"log",
"(",
"`",
"${",
"binaryName",
"}",
"\\n",
"`",
")",
";",
"return",
"binaryName",
";",
"}",
"}",
"}"
] | Determine the shell command that can be used to run the given binary,
prompting to globally install it if necessary. | [
"Determine",
"the",
"shell",
"command",
"that",
"can",
"be",
"used",
"to",
"run",
"the",
"given",
"binary",
"prompting",
"to",
"globally",
"install",
"it",
"if",
"necessary",
"."
] | 78a75de4eb3d7a3bd5a4d8e882a6b5d4ca8cd7f1 | https://github.com/decaffeinate/bulk-decaffeinate/blob/78a75de4eb3d7a3bd5a4d8e882a6b5d4ca8cd7f1/src/config/resolveConfig.js#L184-L206 |
22,801 | image-js/mrz-detection | src/svm.js | getDescriptors | function getDescriptors(images) {
const result = [];
for (let image of images) {
result.push(extractHOG(image));
}
const heights = images.map((img) => img.height);
const maxHeight = Math.max.apply(null, heights);
const minHeight = Math.min.apply(null, heights);
for (let i = 0; i < images.length; i++) {
const img = images[i];
let bonusFeature = 1;
if (minHeight !== maxHeight) {
bonusFeature = (img.height - minHeight) / (maxHeight - minHeight);
}
result[i].push(bonusFeature);
}
return result;
} | javascript | function getDescriptors(images) {
const result = [];
for (let image of images) {
result.push(extractHOG(image));
}
const heights = images.map((img) => img.height);
const maxHeight = Math.max.apply(null, heights);
const minHeight = Math.min.apply(null, heights);
for (let i = 0; i < images.length; i++) {
const img = images[i];
let bonusFeature = 1;
if (minHeight !== maxHeight) {
bonusFeature = (img.height - minHeight) / (maxHeight - minHeight);
}
result[i].push(bonusFeature);
}
return result;
} | [
"function",
"getDescriptors",
"(",
"images",
")",
"{",
"const",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"image",
"of",
"images",
")",
"{",
"result",
".",
"push",
"(",
"extractHOG",
"(",
"image",
")",
")",
";",
"}",
"const",
"heights",
"=",
"images",
".",
"map",
"(",
"(",
"img",
")",
"=>",
"img",
".",
"height",
")",
";",
"const",
"maxHeight",
"=",
"Math",
".",
"max",
".",
"apply",
"(",
"null",
",",
"heights",
")",
";",
"const",
"minHeight",
"=",
"Math",
".",
"min",
".",
"apply",
"(",
"null",
",",
"heights",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"images",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"img",
"=",
"images",
"[",
"i",
"]",
";",
"let",
"bonusFeature",
"=",
"1",
";",
"if",
"(",
"minHeight",
"!==",
"maxHeight",
")",
"{",
"bonusFeature",
"=",
"(",
"img",
".",
"height",
"-",
"minHeight",
")",
"/",
"(",
"maxHeight",
"-",
"minHeight",
")",
";",
"}",
"result",
"[",
"i",
"]",
".",
"push",
"(",
"bonusFeature",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Get descriptors for images from 1 identity card | [
"Get",
"descriptors",
"for",
"images",
"from",
"1",
"identity",
"card"
] | 8d5f96f1f0a0897960fe29400e5ae3cd2a536ecd | https://github.com/image-js/mrz-detection/blob/8d5f96f1f0a0897960fe29400e5ae3cd2a536ecd/src/svm.js#L60-L78 |
22,802 | bibig/node-shorthash | examples/sandbox.js | randomEnglishWord | function randomEnglishWord (length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
i, word='',
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[randomNumber(consonants.length-1)],
randVowel = vowels[randomNumber(vowels.length-1)];
//word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += (i===0) ? randConsonant : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
} | javascript | function randomEnglishWord (length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
i, word='',
consonants = consonants.split(''),
vowels = vowels.split('');
for (i=0;i<length/2;i++) {
var randConsonant = consonants[randomNumber(consonants.length-1)],
randVowel = vowels[randomNumber(vowels.length-1)];
//word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += (i===0) ? randConsonant : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
} | [
"function",
"randomEnglishWord",
"(",
"length",
")",
"{",
"var",
"consonants",
"=",
"'bcdfghjklmnpqrstvwxyz'",
",",
"vowels",
"=",
"'aeiou'",
",",
"i",
",",
"word",
"=",
"''",
",",
"consonants",
"=",
"consonants",
".",
"split",
"(",
"''",
")",
",",
"vowels",
"=",
"vowels",
".",
"split",
"(",
"''",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"length",
"/",
"2",
";",
"i",
"++",
")",
"{",
"var",
"randConsonant",
"=",
"consonants",
"[",
"randomNumber",
"(",
"consonants",
".",
"length",
"-",
"1",
")",
"]",
",",
"randVowel",
"=",
"vowels",
"[",
"randomNumber",
"(",
"vowels",
".",
"length",
"-",
"1",
")",
"]",
";",
"//word += (i===0) ? randConsonant.toUpperCase() : randConsonant;",
"word",
"+=",
"(",
"i",
"===",
"0",
")",
"?",
"randConsonant",
":",
"randConsonant",
";",
"word",
"+=",
"i",
"*",
"2",
"<",
"length",
"-",
"1",
"?",
"randVowel",
":",
"''",
";",
"}",
"return",
"word",
";",
"}"
] | people name, term | [
"people",
"name",
"term"
] | 7afa157422d04240d40df65b6d609a956f5ebbff | https://github.com/bibig/node-shorthash/blob/7afa157422d04240d40df65b6d609a956f5ebbff/examples/sandbox.js#L35-L49 |
22,803 | yahoo/pngjs-image | lib/conversion.js | function (idx, funcName) {
var colors = 0,
colorCounter = 0,
fn,
width = this._image.width,
height = this._image.height,
dim = width * height,
spaceOnRight,
spaceOnLeft,
spaceOnTop,
spaceOnBottom;
funcName = funcName || "getLuminosityAtIndex";
fn = function (idx) {
colors += this[funcName](idx);
colorCounter++;
}.bind(this);
spaceOnRight = (idx % width < width - 1);
spaceOnLeft = (idx % width > 0);
spaceOnTop = (idx >= width);
spaceOnBottom = (idx <= dim - width);
if (spaceOnTop) {
if (spaceOnLeft) {
fn(idx - this._image.width - 1);
}
fn(idx - this._image.width);
if (spaceOnRight) {
fn(idx - this._image.width + 1);
}
}
if (spaceOnLeft) {
fn(idx - 1);
}
fn(idx);
if (spaceOnRight) {
fn(idx + 1);
}
if (spaceOnBottom) {
if (spaceOnLeft) {
fn(idx + this._image.width - 1);
}
fn(idx + this._image.width);
if (spaceOnRight) {
fn(idx + this._image.width + 1);
}
}
return Math.floor(colors / colorCounter);
} | javascript | function (idx, funcName) {
var colors = 0,
colorCounter = 0,
fn,
width = this._image.width,
height = this._image.height,
dim = width * height,
spaceOnRight,
spaceOnLeft,
spaceOnTop,
spaceOnBottom;
funcName = funcName || "getLuminosityAtIndex";
fn = function (idx) {
colors += this[funcName](idx);
colorCounter++;
}.bind(this);
spaceOnRight = (idx % width < width - 1);
spaceOnLeft = (idx % width > 0);
spaceOnTop = (idx >= width);
spaceOnBottom = (idx <= dim - width);
if (spaceOnTop) {
if (spaceOnLeft) {
fn(idx - this._image.width - 1);
}
fn(idx - this._image.width);
if (spaceOnRight) {
fn(idx - this._image.width + 1);
}
}
if (spaceOnLeft) {
fn(idx - 1);
}
fn(idx);
if (spaceOnRight) {
fn(idx + 1);
}
if (spaceOnBottom) {
if (spaceOnLeft) {
fn(idx + this._image.width - 1);
}
fn(idx + this._image.width);
if (spaceOnRight) {
fn(idx + this._image.width + 1);
}
}
return Math.floor(colors / colorCounter);
} | [
"function",
"(",
"idx",
",",
"funcName",
")",
"{",
"var",
"colors",
"=",
"0",
",",
"colorCounter",
"=",
"0",
",",
"fn",
",",
"width",
"=",
"this",
".",
"_image",
".",
"width",
",",
"height",
"=",
"this",
".",
"_image",
".",
"height",
",",
"dim",
"=",
"width",
"*",
"height",
",",
"spaceOnRight",
",",
"spaceOnLeft",
",",
"spaceOnTop",
",",
"spaceOnBottom",
";",
"funcName",
"=",
"funcName",
"||",
"\"getLuminosityAtIndex\"",
";",
"fn",
"=",
"function",
"(",
"idx",
")",
"{",
"colors",
"+=",
"this",
"[",
"funcName",
"]",
"(",
"idx",
")",
";",
"colorCounter",
"++",
";",
"}",
".",
"bind",
"(",
"this",
")",
";",
"spaceOnRight",
"=",
"(",
"idx",
"%",
"width",
"<",
"width",
"-",
"1",
")",
";",
"spaceOnLeft",
"=",
"(",
"idx",
"%",
"width",
">",
"0",
")",
";",
"spaceOnTop",
"=",
"(",
"idx",
">=",
"width",
")",
";",
"spaceOnBottom",
"=",
"(",
"idx",
"<=",
"dim",
"-",
"width",
")",
";",
"if",
"(",
"spaceOnTop",
")",
"{",
"if",
"(",
"spaceOnLeft",
")",
"{",
"fn",
"(",
"idx",
"-",
"this",
".",
"_image",
".",
"width",
"-",
"1",
")",
";",
"}",
"fn",
"(",
"idx",
"-",
"this",
".",
"_image",
".",
"width",
")",
";",
"if",
"(",
"spaceOnRight",
")",
"{",
"fn",
"(",
"idx",
"-",
"this",
".",
"_image",
".",
"width",
"+",
"1",
")",
";",
"}",
"}",
"if",
"(",
"spaceOnLeft",
")",
"{",
"fn",
"(",
"idx",
"-",
"1",
")",
";",
"}",
"fn",
"(",
"idx",
")",
";",
"if",
"(",
"spaceOnRight",
")",
"{",
"fn",
"(",
"idx",
"+",
"1",
")",
";",
"}",
"if",
"(",
"spaceOnBottom",
")",
"{",
"if",
"(",
"spaceOnLeft",
")",
"{",
"fn",
"(",
"idx",
"+",
"this",
".",
"_image",
".",
"width",
"-",
"1",
")",
";",
"}",
"fn",
"(",
"idx",
"+",
"this",
".",
"_image",
".",
"width",
")",
";",
"if",
"(",
"spaceOnRight",
")",
"{",
"fn",
"(",
"idx",
"+",
"this",
".",
"_image",
".",
"width",
"+",
"1",
")",
";",
"}",
"}",
"return",
"Math",
".",
"floor",
"(",
"colors",
"/",
"colorCounter",
")",
";",
"}"
] | Gets the blurred value of a pixel with a gray-scale function
@method getBlurPixelAtIndex
@param {int} idx Index
@param {string} [funcName] Gray-scale function
@return {int} | [
"Gets",
"the",
"blurred",
"value",
"of",
"a",
"pixel",
"with",
"a",
"gray",
"-",
"scale",
"function"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/lib/conversion.js#L21-L75 | |
22,804 | yahoo/pngjs-image | lib/conversion.js | function (x, y, funcName) {
var idx = this.getIndex(x, y);
return this.getBlurPixelAtIndex(idx, funcName);
} | javascript | function (x, y, funcName) {
var idx = this.getIndex(x, y);
return this.getBlurPixelAtIndex(idx, funcName);
} | [
"function",
"(",
"x",
",",
"y",
",",
"funcName",
")",
"{",
"var",
"idx",
"=",
"this",
".",
"getIndex",
"(",
"x",
",",
"y",
")",
";",
"return",
"this",
".",
"getBlurPixelAtIndex",
"(",
"idx",
",",
"funcName",
")",
";",
"}"
] | Gets the blur-value of a pixel at a specific coordinate
@method getBlurPixel
@param {int} x X-coordinate of pixel
@param {int} y Y-coordinate of pixel
@param {string} [funcName] Gray-scale function
@return {int} blur-value | [
"Gets",
"the",
"blur",
"-",
"value",
"of",
"a",
"pixel",
"at",
"a",
"specific",
"coordinate"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/lib/conversion.js#L86-L89 | |
22,805 | yahoo/pngjs-image | lib/conversion.js | function (idx) {
var r = this.getRed(idx),
g = this.getGreen(idx),
b = this.getBlue(idx),
y,
i,
q;
y = this.getLumaAtIndex(idx);
i = Math.floor((0.595716 * r) - (0.274453 * g) - (0.321263 * b));
q = Math.floor((0.211456 * r) - (0.522591 * g) + (0.311135 * b));
y = y < 0 ? 0 : (y > 255 ? 255 : y);
i = i < 0 ? 0 : (i > 255 ? 255 : i);
q = q < 0 ? 0 : (q > 255 ? 255 : q);
return {y: y, i: i, q: q};
} | javascript | function (idx) {
var r = this.getRed(idx),
g = this.getGreen(idx),
b = this.getBlue(idx),
y,
i,
q;
y = this.getLumaAtIndex(idx);
i = Math.floor((0.595716 * r) - (0.274453 * g) - (0.321263 * b));
q = Math.floor((0.211456 * r) - (0.522591 * g) + (0.311135 * b));
y = y < 0 ? 0 : (y > 255 ? 255 : y);
i = i < 0 ? 0 : (i > 255 ? 255 : i);
q = q < 0 ? 0 : (q > 255 ? 255 : q);
return {y: y, i: i, q: q};
} | [
"function",
"(",
"idx",
")",
"{",
"var",
"r",
"=",
"this",
".",
"getRed",
"(",
"idx",
")",
",",
"g",
"=",
"this",
".",
"getGreen",
"(",
"idx",
")",
",",
"b",
"=",
"this",
".",
"getBlue",
"(",
"idx",
")",
",",
"y",
",",
"i",
",",
"q",
";",
"y",
"=",
"this",
".",
"getLumaAtIndex",
"(",
"idx",
")",
";",
"i",
"=",
"Math",
".",
"floor",
"(",
"(",
"0.595716",
"*",
"r",
")",
"-",
"(",
"0.274453",
"*",
"g",
")",
"-",
"(",
"0.321263",
"*",
"b",
")",
")",
";",
"q",
"=",
"Math",
".",
"floor",
"(",
"(",
"0.211456",
"*",
"r",
")",
"-",
"(",
"0.522591",
"*",
"g",
")",
"+",
"(",
"0.311135",
"*",
"b",
")",
")",
";",
"y",
"=",
"y",
"<",
"0",
"?",
"0",
":",
"(",
"y",
">",
"255",
"?",
"255",
":",
"y",
")",
";",
"i",
"=",
"i",
"<",
"0",
"?",
"0",
":",
"(",
"i",
">",
"255",
"?",
"255",
":",
"i",
")",
";",
"q",
"=",
"q",
"<",
"0",
"?",
"0",
":",
"(",
"q",
">",
"255",
"?",
"255",
":",
"q",
")",
";",
"return",
"{",
"y",
":",
"y",
",",
"i",
":",
"i",
",",
"q",
":",
"q",
"}",
";",
"}"
] | Gets the YIQ-value of a pixel at a specific index
The values for RGB correspond afterwards to YIQ respectively.
@method getYIQAtIndex
@param {int} idx Index of pixel
@return {object} YIQ-value | [
"Gets",
"the",
"YIQ",
"-",
"value",
"of",
"a",
"pixel",
"at",
"a",
"specific",
"index",
"The",
"values",
"for",
"RGB",
"correspond",
"afterwards",
"to",
"YIQ",
"respectively",
"."
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/lib/conversion.js#L100-L118 | |
22,806 | yahoo/pngjs-image | lib/conversion.js | function (idx) {
var r = this.getRed(idx),
g = this.getGreen(idx),
b = this.getBlue(idx);
r = Math.floor((0.393 * r) + (0.769 * g) + (0.189 * b));
g = Math.floor((0.349 * r) + (0.686 * g) + (0.168 * b));
b = Math.floor((0.272 * r) + (0.534 * g) + (0.131 * b));
r = r < 0 ? 0 : (r > 255 ? 255 : r);
g = g < 0 ? 0 : (g > 255 ? 255 : g);
b = b < 0 ? 0 : (b > 255 ? 255 : b);
return {red: r, green: g, blue: b};
} | javascript | function (idx) {
var r = this.getRed(idx),
g = this.getGreen(idx),
b = this.getBlue(idx);
r = Math.floor((0.393 * r) + (0.769 * g) + (0.189 * b));
g = Math.floor((0.349 * r) + (0.686 * g) + (0.168 * b));
b = Math.floor((0.272 * r) + (0.534 * g) + (0.131 * b));
r = r < 0 ? 0 : (r > 255 ? 255 : r);
g = g < 0 ? 0 : (g > 255 ? 255 : g);
b = b < 0 ? 0 : (b > 255 ? 255 : b);
return {red: r, green: g, blue: b};
} | [
"function",
"(",
"idx",
")",
"{",
"var",
"r",
"=",
"this",
".",
"getRed",
"(",
"idx",
")",
",",
"g",
"=",
"this",
".",
"getGreen",
"(",
"idx",
")",
",",
"b",
"=",
"this",
".",
"getBlue",
"(",
"idx",
")",
";",
"r",
"=",
"Math",
".",
"floor",
"(",
"(",
"0.393",
"*",
"r",
")",
"+",
"(",
"0.769",
"*",
"g",
")",
"+",
"(",
"0.189",
"*",
"b",
")",
")",
";",
"g",
"=",
"Math",
".",
"floor",
"(",
"(",
"0.349",
"*",
"r",
")",
"+",
"(",
"0.686",
"*",
"g",
")",
"+",
"(",
"0.168",
"*",
"b",
")",
")",
";",
"b",
"=",
"Math",
".",
"floor",
"(",
"(",
"0.272",
"*",
"r",
")",
"+",
"(",
"0.534",
"*",
"g",
")",
"+",
"(",
"0.131",
"*",
"b",
")",
")",
";",
"r",
"=",
"r",
"<",
"0",
"?",
"0",
":",
"(",
"r",
">",
"255",
"?",
"255",
":",
"r",
")",
";",
"g",
"=",
"g",
"<",
"0",
"?",
"0",
":",
"(",
"g",
">",
"255",
"?",
"255",
":",
"g",
")",
";",
"b",
"=",
"b",
"<",
"0",
"?",
"0",
":",
"(",
"b",
">",
"255",
"?",
"255",
":",
"b",
")",
";",
"return",
"{",
"red",
":",
"r",
",",
"green",
":",
"g",
",",
"blue",
":",
"b",
"}",
";",
"}"
] | Gets the sepia of a pixel at a specific index
@method getSepiaAtIndex
@param {int} idx Index of pixel
@return {object} Color | [
"Gets",
"the",
"sepia",
"of",
"a",
"pixel",
"at",
"a",
"specific",
"index"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/lib/conversion.js#L166-L180 | |
22,807 | yahoo/pngjs-image | lib/conversion.js | function (idx) {
var r = this.getRed(idx),
g = this.getGreen(idx),
b = this.getBlue(idx);
return Math.floor((Math.max(r, g, b) + Math.min(r, g, b)) / 2);
} | javascript | function (idx) {
var r = this.getRed(idx),
g = this.getGreen(idx),
b = this.getBlue(idx);
return Math.floor((Math.max(r, g, b) + Math.min(r, g, b)) / 2);
} | [
"function",
"(",
"idx",
")",
"{",
"var",
"r",
"=",
"this",
".",
"getRed",
"(",
"idx",
")",
",",
"g",
"=",
"this",
".",
"getGreen",
"(",
"idx",
")",
",",
"b",
"=",
"this",
".",
"getBlue",
"(",
"idx",
")",
";",
"return",
"Math",
".",
"floor",
"(",
"(",
"Math",
".",
"max",
"(",
"r",
",",
"g",
",",
"b",
")",
"+",
"Math",
".",
"min",
"(",
"r",
",",
"g",
",",
"b",
")",
")",
"/",
"2",
")",
";",
"}"
] | Gets the lightness of a pixel at a specific index
@method getLightnessAtIndex
@param {int} idx Index of pixel
@return {int} Lightness | [
"Gets",
"the",
"lightness",
"of",
"a",
"pixel",
"at",
"a",
"specific",
"index"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/lib/conversion.js#L227-L233 | |
22,808 | yahoo/pngjs-image | lib/modify.js | function () {
var Class = this.constructor,
x, y,
width = this.getWidth(),
height = this.getHeight(),
image = Class.createImage(height, width);
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
image.setPixel(y, width - x - 1, this.getPixel(x, y));
}
}
return image;
} | javascript | function () {
var Class = this.constructor,
x, y,
width = this.getWidth(),
height = this.getHeight(),
image = Class.createImage(height, width);
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
image.setPixel(y, width - x - 1, this.getPixel(x, y));
}
}
return image;
} | [
"function",
"(",
")",
"{",
"var",
"Class",
"=",
"this",
".",
"constructor",
",",
"x",
",",
"y",
",",
"width",
"=",
"this",
".",
"getWidth",
"(",
")",
",",
"height",
"=",
"this",
".",
"getHeight",
"(",
")",
",",
"image",
"=",
"Class",
".",
"createImage",
"(",
"height",
",",
"width",
")",
";",
"for",
"(",
"x",
"=",
"0",
";",
"x",
"<",
"width",
";",
"x",
"++",
")",
"{",
"for",
"(",
"y",
"=",
"0",
";",
"y",
"<",
"height",
";",
"y",
"++",
")",
"{",
"image",
".",
"setPixel",
"(",
"y",
",",
"width",
"-",
"x",
"-",
"1",
",",
"this",
".",
"getPixel",
"(",
"x",
",",
"y",
")",
")",
";",
"}",
"}",
"return",
"image",
";",
"}"
] | Rotates the current image 90 degree counter-clockwise
@method rotateCCW
@return {PNGImage} Rotated image | [
"Rotates",
"the",
"current",
"image",
"90",
"degree",
"counter",
"-",
"clockwise"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/lib/modify.js#L19-L33 | |
22,809 | yahoo/pngjs-image | index.js | PNGImage | function PNGImage (image) {
image.on('error', function (err) {
PNGImage.log(err.message);
});
this._image = image;
} | javascript | function PNGImage (image) {
image.on('error', function (err) {
PNGImage.log(err.message);
});
this._image = image;
} | [
"function",
"PNGImage",
"(",
"image",
")",
"{",
"image",
".",
"on",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"PNGImage",
".",
"log",
"(",
"err",
".",
"message",
")",
";",
"}",
")",
";",
"this",
".",
"_image",
"=",
"image",
";",
"}"
] | PNGjs-image class
@class PNGImage
@submodule Core
@param {PNG} image png-js object
@constructor | [
"PNGjs",
"-",
"image",
"class"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/index.js#L26-L31 |
22,810 | yahoo/pngjs-image | index.js | function (x, y, width, height) {
var image;
width = Math.min(width, this.getWidth() - x);
height = Math.min(height, this.getHeight() - y);
if ((width < 0) || (height < 0)) {
throw new Error('Width and height cannot be negative.');
}
image = new PNG({
width: width, height: height
});
this._image.bitblt(image, x, y, width, height, 0, 0);
this._image = image;
} | javascript | function (x, y, width, height) {
var image;
width = Math.min(width, this.getWidth() - x);
height = Math.min(height, this.getHeight() - y);
if ((width < 0) || (height < 0)) {
throw new Error('Width and height cannot be negative.');
}
image = new PNG({
width: width, height: height
});
this._image.bitblt(image, x, y, width, height, 0, 0);
this._image = image;
} | [
"function",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
")",
"{",
"var",
"image",
";",
"width",
"=",
"Math",
".",
"min",
"(",
"width",
",",
"this",
".",
"getWidth",
"(",
")",
"-",
"x",
")",
";",
"height",
"=",
"Math",
".",
"min",
"(",
"height",
",",
"this",
".",
"getHeight",
"(",
")",
"-",
"y",
")",
";",
"if",
"(",
"(",
"width",
"<",
"0",
")",
"||",
"(",
"height",
"<",
"0",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Width and height cannot be negative.'",
")",
";",
"}",
"image",
"=",
"new",
"PNG",
"(",
"{",
"width",
":",
"width",
",",
"height",
":",
"height",
"}",
")",
";",
"this",
".",
"_image",
".",
"bitblt",
"(",
"image",
",",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"0",
",",
"0",
")",
";",
"this",
".",
"_image",
"=",
"image",
";",
"}"
] | Clips the current image by modifying it in-place
@method clip
@param {int} x Starting x-coordinate
@param {int} y Starting y-coordinate
@param {int} width Width of area relative to starting coordinate
@param {int} height Height of area relative to starting coordinate | [
"Clips",
"the",
"current",
"image",
"by",
"modifying",
"it",
"in",
"-",
"place"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/index.js#L299-L316 | |
22,811 | yahoo/pngjs-image | index.js | function (x, y, width, height, color) {
var i,
iLen = x + width,
j,
jLen = y + height,
index;
for (i = x; i < iLen; i++) {
for (j = y; j < jLen; j++) {
index = this.getIndex(i, j);
this.setAtIndex(index, color);
}
}
} | javascript | function (x, y, width, height, color) {
var i,
iLen = x + width,
j,
jLen = y + height,
index;
for (i = x; i < iLen; i++) {
for (j = y; j < jLen; j++) {
index = this.getIndex(i, j);
this.setAtIndex(index, color);
}
}
} | [
"function",
"(",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"color",
")",
"{",
"var",
"i",
",",
"iLen",
"=",
"x",
"+",
"width",
",",
"j",
",",
"jLen",
"=",
"y",
"+",
"height",
",",
"index",
";",
"for",
"(",
"i",
"=",
"x",
";",
"i",
"<",
"iLen",
";",
"i",
"++",
")",
"{",
"for",
"(",
"j",
"=",
"y",
";",
"j",
"<",
"jLen",
";",
"j",
"++",
")",
"{",
"index",
"=",
"this",
".",
"getIndex",
"(",
"i",
",",
"j",
")",
";",
"this",
".",
"setAtIndex",
"(",
"index",
",",
"color",
")",
";",
"}",
"}",
"}"
] | Fills an area with the specified color
@method fillRect
@param {int} x Starting x-coordinate
@param {int} y Starting y-coordinate
@param {int} width Width of area relative to starting coordinate
@param {int} height Height of area relative to starting coordinate
@param {object} color
@param {int} [color.red] Red channel of color to set
@param {int} [color.green] Green channel of color to set
@param {int} [color.blue] Blue channel of color to set
@param {int} [color.alpha] Alpha channel for color to set
@param {float} [color.opacity] Opacity of color | [
"Fills",
"an",
"area",
"with",
"the",
"specified",
"color"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/index.js#L333-L347 | |
22,812 | yahoo/pngjs-image | index.js | function (filters, returnResult) {
var image,
newFilters;
// Convert to array
if (_.isString(filters)) {
filters = [filters];
} else if (!_.isArray(filters) && _.isObject(filters)) {
filters = [filters];
}
// Format array as needed by the function
newFilters = [];
(filters || []).forEach(function (filter) {
if (_.isString(filter)) {
newFilters.push({key: filter, options: {}});
} else if (_.isObject(filter)) {
newFilters.push(filter);
}
});
filters = newFilters;
// Process filters
image = this;
(filters || []).forEach(function (filter) {
var currentFilter = PNGImage.filters[filter.key];
if (!currentFilter) {
throw new Error('Unknown filter ' + filter.key);
}
filter.options = filter.options || {};
filter.options.needsCopy = !!returnResult;
image = currentFilter(this, filter.options);
}.bind(this));
// Overwrite current image, or just returning it
if (!returnResult) {
this._image = image.getImage();
}
return image;
} | javascript | function (filters, returnResult) {
var image,
newFilters;
// Convert to array
if (_.isString(filters)) {
filters = [filters];
} else if (!_.isArray(filters) && _.isObject(filters)) {
filters = [filters];
}
// Format array as needed by the function
newFilters = [];
(filters || []).forEach(function (filter) {
if (_.isString(filter)) {
newFilters.push({key: filter, options: {}});
} else if (_.isObject(filter)) {
newFilters.push(filter);
}
});
filters = newFilters;
// Process filters
image = this;
(filters || []).forEach(function (filter) {
var currentFilter = PNGImage.filters[filter.key];
if (!currentFilter) {
throw new Error('Unknown filter ' + filter.key);
}
filter.options = filter.options || {};
filter.options.needsCopy = !!returnResult;
image = currentFilter(this, filter.options);
}.bind(this));
// Overwrite current image, or just returning it
if (!returnResult) {
this._image = image.getImage();
}
return image;
} | [
"function",
"(",
"filters",
",",
"returnResult",
")",
"{",
"var",
"image",
",",
"newFilters",
";",
"// Convert to array",
"if",
"(",
"_",
".",
"isString",
"(",
"filters",
")",
")",
"{",
"filters",
"=",
"[",
"filters",
"]",
";",
"}",
"else",
"if",
"(",
"!",
"_",
".",
"isArray",
"(",
"filters",
")",
"&&",
"_",
".",
"isObject",
"(",
"filters",
")",
")",
"{",
"filters",
"=",
"[",
"filters",
"]",
";",
"}",
"// Format array as needed by the function",
"newFilters",
"=",
"[",
"]",
";",
"(",
"filters",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"filter",
")",
"{",
"if",
"(",
"_",
".",
"isString",
"(",
"filter",
")",
")",
"{",
"newFilters",
".",
"push",
"(",
"{",
"key",
":",
"filter",
",",
"options",
":",
"{",
"}",
"}",
")",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isObject",
"(",
"filter",
")",
")",
"{",
"newFilters",
".",
"push",
"(",
"filter",
")",
";",
"}",
"}",
")",
";",
"filters",
"=",
"newFilters",
";",
"// Process filters",
"image",
"=",
"this",
";",
"(",
"filters",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"filter",
")",
"{",
"var",
"currentFilter",
"=",
"PNGImage",
".",
"filters",
"[",
"filter",
".",
"key",
"]",
";",
"if",
"(",
"!",
"currentFilter",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Unknown filter '",
"+",
"filter",
".",
"key",
")",
";",
"}",
"filter",
".",
"options",
"=",
"filter",
".",
"options",
"||",
"{",
"}",
";",
"filter",
".",
"options",
".",
"needsCopy",
"=",
"!",
"!",
"returnResult",
";",
"image",
"=",
"currentFilter",
"(",
"this",
",",
"filter",
".",
"options",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"// Overwrite current image, or just returning it",
"if",
"(",
"!",
"returnResult",
")",
"{",
"this",
".",
"_image",
"=",
"image",
".",
"getImage",
"(",
")",
";",
"}",
"return",
"image",
";",
"}"
] | Applies a list of filters to the image
@method applyFilters
@param {string|object|object[]} filters Names of filters in sequence `{key:<string>, options:<object>}`
@param {boolean} [returnResult=false]
@return {PNGImage} | [
"Applies",
"a",
"list",
"of",
"filters",
"to",
"the",
"image"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/index.js#L358-L406 | |
22,813 | yahoo/pngjs-image | index.js | function (filename, fn) {
fn = fn || function () {};
this._image.pack().pipe(fs.createWriteStream(filename)).once('close', function () {
this._image.removeListener('error', fn);
fn(undefined, this);
}.bind(this)).once('error', function (err) {
this._image.removeListener('close', fn);
fn(err, this);
}.bind(this));
} | javascript | function (filename, fn) {
fn = fn || function () {};
this._image.pack().pipe(fs.createWriteStream(filename)).once('close', function () {
this._image.removeListener('error', fn);
fn(undefined, this);
}.bind(this)).once('error', function (err) {
this._image.removeListener('close', fn);
fn(err, this);
}.bind(this));
} | [
"function",
"(",
"filename",
",",
"fn",
")",
"{",
"fn",
"=",
"fn",
"||",
"function",
"(",
")",
"{",
"}",
";",
"this",
".",
"_image",
".",
"pack",
"(",
")",
".",
"pipe",
"(",
"fs",
".",
"createWriteStream",
"(",
"filename",
")",
")",
".",
"once",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"this",
".",
"_image",
".",
"removeListener",
"(",
"'error'",
",",
"fn",
")",
";",
"fn",
"(",
"undefined",
",",
"this",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
".",
"once",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"this",
".",
"_image",
".",
"removeListener",
"(",
"'close'",
",",
"fn",
")",
";",
"fn",
"(",
"err",
",",
"this",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Writes the image to the filesystem
@method writeImage
@param {string} filename Path to file
@param {function} fn Callback | [
"Writes",
"the",
"image",
"to",
"the",
"filesystem"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/index.js#L429-L440 | |
22,814 | yahoo/pngjs-image | index.js | function (fn) {
var writeBuffer = new streamBuffers.WritableStreamBuffer({
initialSize: (100 * 1024), incrementAmount: (10 * 1024)
});
fn = fn || function () {};
this._image.pack().pipe(writeBuffer).once('close', function () {
this._image.removeListener('error', fn);
fn(undefined, writeBuffer.getContents());
}.bind(this)).once('error', function (err) {
this._image.removeListener('close', fn);
fn(err);
}.bind(this));
} | javascript | function (fn) {
var writeBuffer = new streamBuffers.WritableStreamBuffer({
initialSize: (100 * 1024), incrementAmount: (10 * 1024)
});
fn = fn || function () {};
this._image.pack().pipe(writeBuffer).once('close', function () {
this._image.removeListener('error', fn);
fn(undefined, writeBuffer.getContents());
}.bind(this)).once('error', function (err) {
this._image.removeListener('close', fn);
fn(err);
}.bind(this));
} | [
"function",
"(",
"fn",
")",
"{",
"var",
"writeBuffer",
"=",
"new",
"streamBuffers",
".",
"WritableStreamBuffer",
"(",
"{",
"initialSize",
":",
"(",
"100",
"*",
"1024",
")",
",",
"incrementAmount",
":",
"(",
"10",
"*",
"1024",
")",
"}",
")",
";",
"fn",
"=",
"fn",
"||",
"function",
"(",
")",
"{",
"}",
";",
"this",
".",
"_image",
".",
"pack",
"(",
")",
".",
"pipe",
"(",
"writeBuffer",
")",
".",
"once",
"(",
"'close'",
",",
"function",
"(",
")",
"{",
"this",
".",
"_image",
".",
"removeListener",
"(",
"'error'",
",",
"fn",
")",
";",
"fn",
"(",
"undefined",
",",
"writeBuffer",
".",
"getContents",
"(",
")",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
".",
"once",
"(",
"'error'",
",",
"function",
"(",
"err",
")",
"{",
"this",
".",
"_image",
".",
"removeListener",
"(",
"'close'",
",",
"fn",
")",
";",
"fn",
"(",
"err",
")",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Writes the image to a buffer
@method toBlob
@param {function} fn Callback | [
"Writes",
"the",
"image",
"to",
"a",
"buffer"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/index.js#L457-L472 | |
22,815 | yahoo/pngjs-image | lib/filters.js | generateFilter | function generateFilter (fn) {
/**
* Creates a destination image
*
* @method
* @param {PNGImage} image
* @param {object} options
* @param {object} [options.needsCopy=false]
* @return {PNGImage}
*/
return function (image, options) {
if (options.needsCopy) {
var newImage = image.constructor.createImage(image.getWidth(), image.getHeight());
fn(image, newImage, options);
return newImage;
} else {
fn(image, image, options);
return image;
}
};
} | javascript | function generateFilter (fn) {
/**
* Creates a destination image
*
* @method
* @param {PNGImage} image
* @param {object} options
* @param {object} [options.needsCopy=false]
* @return {PNGImage}
*/
return function (image, options) {
if (options.needsCopy) {
var newImage = image.constructor.createImage(image.getWidth(), image.getHeight());
fn(image, newImage, options);
return newImage;
} else {
fn(image, image, options);
return image;
}
};
} | [
"function",
"generateFilter",
"(",
"fn",
")",
"{",
"/**\n\t * Creates a destination image\n\t *\n\t * @method\n\t * @param {PNGImage} image\n\t * @param {object} options\n\t * @param {object} [options.needsCopy=false]\n\t * @return {PNGImage}\n\t */",
"return",
"function",
"(",
"image",
",",
"options",
")",
"{",
"if",
"(",
"options",
".",
"needsCopy",
")",
"{",
"var",
"newImage",
"=",
"image",
".",
"constructor",
".",
"createImage",
"(",
"image",
".",
"getWidth",
"(",
")",
",",
"image",
".",
"getHeight",
"(",
")",
")",
";",
"fn",
"(",
"image",
",",
"newImage",
",",
"options",
")",
";",
"return",
"newImage",
";",
"}",
"else",
"{",
"fn",
"(",
"image",
",",
"image",
",",
"options",
")",
";",
"return",
"image",
";",
"}",
"}",
";",
"}"
] | Generates a filter function by doing common tasks to abstract this away from the actual filter functions
@method generateFilter
@param {function} fn
@return {Function}
@private | [
"Generates",
"a",
"filter",
"function",
"by",
"doing",
"common",
"tasks",
"to",
"abstract",
"this",
"away",
"from",
"the",
"actual",
"filter",
"functions"
] | 63f11c69d87da204d7aebb4160c2d21bbfee3d4a | https://github.com/yahoo/pngjs-image/blob/63f11c69d87da204d7aebb4160c2d21bbfee3d4a/lib/filters.js#L20-L43 |
22,816 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (index, appId, userId, deviceId) {
'use strict';
this.index = index;
this.appId = appId;
this.userId = userId;
this.deviceId = deviceId || 'amzn1.ask.device.VOID';
} | javascript | function (index, appId, userId, deviceId) {
'use strict';
this.index = index;
this.appId = appId;
this.userId = userId;
this.deviceId = deviceId || 'amzn1.ask.device.VOID';
} | [
"function",
"(",
"index",
",",
"appId",
",",
"userId",
",",
"deviceId",
")",
"{",
"'use strict'",
";",
"this",
".",
"index",
"=",
"index",
";",
"this",
".",
"appId",
"=",
"appId",
";",
"this",
".",
"userId",
"=",
"userId",
";",
"this",
".",
"deviceId",
"=",
"deviceId",
"||",
"'amzn1.ask.device.VOID'",
";",
"}"
] | Initializes necessary values before using the test framework.
@param {object} index The object containing your skill's 'handler' method.
@param {string} appId The Skill's app ID. Looks like "amzn1.ask.skill.00000000-0000-0000-0000-000000000000".
@param {string} userId The Amazon User ID to test with. Looks like "amzn1.ask.account.LONG_STRING"
@param {string} deviceId Optional The Amazon Device ID to test with. Looks like "amzn1.ask.device.LONG_STRING" | [
"Initializes",
"necessary",
"values",
"before",
"using",
"the",
"test",
"framework",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L102-L108 | |
22,817 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (resources) {
'use strict';
this.i18n = require('i18next');
var sprintf = require('i18next-sprintf-postprocessor');
this.i18n.use(sprintf).init({
overloadTranslationOptionHandler: sprintf.overloadTranslationOptionHandler,
returnObjects: true,
lng: this.locale,
resources: resources
});
} | javascript | function (resources) {
'use strict';
this.i18n = require('i18next');
var sprintf = require('i18next-sprintf-postprocessor');
this.i18n.use(sprintf).init({
overloadTranslationOptionHandler: sprintf.overloadTranslationOptionHandler,
returnObjects: true,
lng: this.locale,
resources: resources
});
} | [
"function",
"(",
"resources",
")",
"{",
"'use strict'",
";",
"this",
".",
"i18n",
"=",
"require",
"(",
"'i18next'",
")",
";",
"var",
"sprintf",
"=",
"require",
"(",
"'i18next-sprintf-postprocessor'",
")",
";",
"this",
".",
"i18n",
".",
"use",
"(",
"sprintf",
")",
".",
"init",
"(",
"{",
"overloadTranslationOptionHandler",
":",
"sprintf",
".",
"overloadTranslationOptionHandler",
",",
"returnObjects",
":",
"true",
",",
"lng",
":",
"this",
".",
"locale",
",",
"resources",
":",
"resources",
"}",
")",
";",
"}"
] | Initializes i18n.
@param {object} resources The 'resources' object to give to i18n. | [
"Initializes",
"i18n",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L114-L124 | |
22,818 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (tableName, partitionKeyName, attributesName) {
'use strict';
if (!tableName) {
throw "'tableName' argument must be provided.";
}
this.dynamoDBTable = tableName;
this.partitionKeyName = partitionKeyName || 'userId';
this.attributesName = attributesName || 'mapAttr';
let self = this;
AWSMOCK.mock('DynamoDB.DocumentClient', 'get', (params, callback) => {
// Do not inline; resolution has to take place on call
self.dynamoDBGetMock(params, callback);
});
AWSMOCK.mock('DynamoDB.DocumentClient', 'put', (params, callback) => {
// Do not inline; resolution has to take place on call
self.dynamoDBPutMock(params, callback);
});
} | javascript | function (tableName, partitionKeyName, attributesName) {
'use strict';
if (!tableName) {
throw "'tableName' argument must be provided.";
}
this.dynamoDBTable = tableName;
this.partitionKeyName = partitionKeyName || 'userId';
this.attributesName = attributesName || 'mapAttr';
let self = this;
AWSMOCK.mock('DynamoDB.DocumentClient', 'get', (params, callback) => {
// Do not inline; resolution has to take place on call
self.dynamoDBGetMock(params, callback);
});
AWSMOCK.mock('DynamoDB.DocumentClient', 'put', (params, callback) => {
// Do not inline; resolution has to take place on call
self.dynamoDBPutMock(params, callback);
});
} | [
"function",
"(",
"tableName",
",",
"partitionKeyName",
",",
"attributesName",
")",
"{",
"'use strict'",
";",
"if",
"(",
"!",
"tableName",
")",
"{",
"throw",
"\"'tableName' argument must be provided.\"",
";",
"}",
"this",
".",
"dynamoDBTable",
"=",
"tableName",
";",
"this",
".",
"partitionKeyName",
"=",
"partitionKeyName",
"||",
"'userId'",
";",
"this",
".",
"attributesName",
"=",
"attributesName",
"||",
"'mapAttr'",
";",
"let",
"self",
"=",
"this",
";",
"AWSMOCK",
".",
"mock",
"(",
"'DynamoDB.DocumentClient'",
",",
"'get'",
",",
"(",
"params",
",",
"callback",
")",
"=>",
"{",
"// Do not inline; resolution has to take place on call",
"self",
".",
"dynamoDBGetMock",
"(",
"params",
",",
"callback",
")",
";",
"}",
")",
";",
"AWSMOCK",
".",
"mock",
"(",
"'DynamoDB.DocumentClient'",
",",
"'put'",
",",
"(",
"params",
",",
"callback",
")",
"=>",
"{",
"// Do not inline; resolution has to take place on call",
"self",
".",
"dynamoDBPutMock",
"(",
"params",
",",
"callback",
")",
";",
"}",
")",
";",
"}"
] | Activates mocking of DynamoDB backed attributes
@param {string} tableName name of the DynamoDB Table
@param {string} partitionKeyName the key to be used as id (default: userId)
@param {string} attributesName the key to be used for the attributes (default: mapAttr) | [
"Activates",
"mocking",
"of",
"DynamoDB",
"backed",
"attributes"
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L159-L177 | |
22,819 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (intentName, slots, locale) {
'use strict';
var requestSlots;
if (!slots) {
requestSlots = {};
}
else {
requestSlots = JSON.parse(JSON.stringify(slots));
for (var key in requestSlots) {
requestSlots[key] = {name: key, value: requestSlots[key]};
}
}
return {
"version": this.version,
"session": this._getSessionData(),
"context": this._getContextData(),
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId." + uuid.v4(),
"timestamp": new Date().toISOString(),
"locale": locale || this.locale,
"intent": {"name": intentName, "slots": requestSlots}
},
};
} | javascript | function (intentName, slots, locale) {
'use strict';
var requestSlots;
if (!slots) {
requestSlots = {};
}
else {
requestSlots = JSON.parse(JSON.stringify(slots));
for (var key in requestSlots) {
requestSlots[key] = {name: key, value: requestSlots[key]};
}
}
return {
"version": this.version,
"session": this._getSessionData(),
"context": this._getContextData(),
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId." + uuid.v4(),
"timestamp": new Date().toISOString(),
"locale": locale || this.locale,
"intent": {"name": intentName, "slots": requestSlots}
},
};
} | [
"function",
"(",
"intentName",
",",
"slots",
",",
"locale",
")",
"{",
"'use strict'",
";",
"var",
"requestSlots",
";",
"if",
"(",
"!",
"slots",
")",
"{",
"requestSlots",
"=",
"{",
"}",
";",
"}",
"else",
"{",
"requestSlots",
"=",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"slots",
")",
")",
";",
"for",
"(",
"var",
"key",
"in",
"requestSlots",
")",
"{",
"requestSlots",
"[",
"key",
"]",
"=",
"{",
"name",
":",
"key",
",",
"value",
":",
"requestSlots",
"[",
"key",
"]",
"}",
";",
"}",
"}",
"return",
"{",
"\"version\"",
":",
"this",
".",
"version",
",",
"\"session\"",
":",
"this",
".",
"_getSessionData",
"(",
")",
",",
"\"context\"",
":",
"this",
".",
"_getContextData",
"(",
")",
",",
"\"request\"",
":",
"{",
"\"type\"",
":",
"\"IntentRequest\"",
",",
"\"requestId\"",
":",
"\"EdwRequestId.\"",
"+",
"uuid",
".",
"v4",
"(",
")",
",",
"\"timestamp\"",
":",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
",",
"\"locale\"",
":",
"locale",
"||",
"this",
".",
"locale",
",",
"\"intent\"",
":",
"{",
"\"name\"",
":",
"intentName",
",",
"\"slots\"",
":",
"requestSlots",
"}",
"}",
",",
"}",
";",
"}"
] | Generates an intent request object.
@param {string} intentName The name of the intent to call.
@param {object} slots Slot data to call the intent with.
@param {string} locale Optional locale to use. If not specified, uses the locale specified by `setLocale`. | [
"Generates",
"an",
"intent",
"request",
"object",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L225-L249 | |
22,820 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (reason, locale) {
'use strict';
return {
"version": this.version,
"session": this._getSessionData(),
"context": this._getContextData(),
"request": {
"type": "SessionEndedRequest",
"requestId": "EdwRequestId." + uuid.v4(),
"timestamp": new Date().toISOString(),
"locale": locale || this.locale,
"reason": reason
//TODO: support error
}
};
} | javascript | function (reason, locale) {
'use strict';
return {
"version": this.version,
"session": this._getSessionData(),
"context": this._getContextData(),
"request": {
"type": "SessionEndedRequest",
"requestId": "EdwRequestId." + uuid.v4(),
"timestamp": new Date().toISOString(),
"locale": locale || this.locale,
"reason": reason
//TODO: support error
}
};
} | [
"function",
"(",
"reason",
",",
"locale",
")",
"{",
"'use strict'",
";",
"return",
"{",
"\"version\"",
":",
"this",
".",
"version",
",",
"\"session\"",
":",
"this",
".",
"_getSessionData",
"(",
")",
",",
"\"context\"",
":",
"this",
".",
"_getContextData",
"(",
")",
",",
"\"request\"",
":",
"{",
"\"type\"",
":",
"\"SessionEndedRequest\"",
",",
"\"requestId\"",
":",
"\"EdwRequestId.\"",
"+",
"uuid",
".",
"v4",
"(",
")",
",",
"\"timestamp\"",
":",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
",",
"\"locale\"",
":",
"locale",
"||",
"this",
".",
"locale",
",",
"\"reason\"",
":",
"reason",
"//TODO: support error",
"}",
"}",
";",
"}"
] | Generates a sesson ended request object.
@param {string} reason The reason the session was ended.
@param {string} locale Optional locale to use. If not specified, uses the locale specified by `setLocale`.
@see https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/custom-standard-request-types-reference#sessionendedrequest | [
"Generates",
"a",
"sesson",
"ended",
"request",
"object",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L257-L272 | |
22,821 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (request, token, offset, activity) {
'use strict';
if (!request) {
throw 'request must be specified to add entity resolution';
}
if (token) {
request.context.AudioPlayer.token = token;
}
if (offset) {
request.context.AudioPlayer.offsetInMilliseconds = offset;
}
if (activity) {
request.context.AudioPlayer.playerActivity = activity;
}
return request;
} | javascript | function (request, token, offset, activity) {
'use strict';
if (!request) {
throw 'request must be specified to add entity resolution';
}
if (token) {
request.context.AudioPlayer.token = token;
}
if (offset) {
request.context.AudioPlayer.offsetInMilliseconds = offset;
}
if (activity) {
request.context.AudioPlayer.playerActivity = activity;
}
return request;
} | [
"function",
"(",
"request",
",",
"token",
",",
"offset",
",",
"activity",
")",
"{",
"'use strict'",
";",
"if",
"(",
"!",
"request",
")",
"{",
"throw",
"'request must be specified to add entity resolution'",
";",
"}",
"if",
"(",
"token",
")",
"{",
"request",
".",
"context",
".",
"AudioPlayer",
".",
"token",
"=",
"token",
";",
"}",
"if",
"(",
"offset",
")",
"{",
"request",
".",
"context",
".",
"AudioPlayer",
".",
"offsetInMilliseconds",
"=",
"offset",
";",
"}",
"if",
"(",
"activity",
")",
"{",
"request",
".",
"context",
".",
"AudioPlayer",
".",
"playerActivity",
"=",
"activity",
";",
"}",
"return",
"request",
";",
"}"
] | Adds an AudioPlayer context to the given request.
@param {object} request The intent request to modify.
@param {string} token An opaque token that represents the audio stream described by this AudioPlayer object. You provide this token when sending the Play directive.
@param {string} offset Identifies a track’s offset in milliseconds at the time the request was sent. This is 0 if the track is at the beginning.
@param {string} activity Indicates the last known state of audio playback.
@return {object} the given intent request to allow chaining. | [
"Adds",
"an",
"AudioPlayer",
"context",
"to",
"the",
"given",
"request",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L282-L298 | |
22,822 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (request, slotName, slotType, value, id) {
'use strict';
if (!request) {
throw 'request must be specified to add entity resolution';
}
if (!slotName) {
throw 'slotName must be specified to add entity resolution';
}
if (!value) {
throw 'value must be specified to add entity resolution';
}
if (!request.request.intent.slots[slotName]) {
request.request.intent.slots[slotName] = {name: slotName, value: value};
}
const authority = "amzn1.er-authority.echo-sdk." + this.appId + "." + slotType;
var valueAdded = false;
if (request.request.intent.slots[slotName].resolutions) {
request.request.intent.slots[slotName].resolutions.resolutionsPerAuthority.forEach(rpa => {
if (!valueAdded && (rpa.authority === authority)) {
rpa.values.push({
"value": {
"name": value,
"id": id
}
});
valueAdded = true;
}
});
} else {
request.request.intent.slots[slotName].resolutions = {
"resolutionsPerAuthority": []
};
}
if (!valueAdded) {
request.request.intent.slots[slotName].resolutions.resolutionsPerAuthority.push({
"authority": authority,
"status": {
"code": "ER_SUCCESS_MATCH"
},
"values": [
{
"value": {
"name": value,
"id": id
}
}
]
});
}
return request;
} | javascript | function (request, slotName, slotType, value, id) {
'use strict';
if (!request) {
throw 'request must be specified to add entity resolution';
}
if (!slotName) {
throw 'slotName must be specified to add entity resolution';
}
if (!value) {
throw 'value must be specified to add entity resolution';
}
if (!request.request.intent.slots[slotName]) {
request.request.intent.slots[slotName] = {name: slotName, value: value};
}
const authority = "amzn1.er-authority.echo-sdk." + this.appId + "." + slotType;
var valueAdded = false;
if (request.request.intent.slots[slotName].resolutions) {
request.request.intent.slots[slotName].resolutions.resolutionsPerAuthority.forEach(rpa => {
if (!valueAdded && (rpa.authority === authority)) {
rpa.values.push({
"value": {
"name": value,
"id": id
}
});
valueAdded = true;
}
});
} else {
request.request.intent.slots[slotName].resolutions = {
"resolutionsPerAuthority": []
};
}
if (!valueAdded) {
request.request.intent.slots[slotName].resolutions.resolutionsPerAuthority.push({
"authority": authority,
"status": {
"code": "ER_SUCCESS_MATCH"
},
"values": [
{
"value": {
"name": value,
"id": id
}
}
]
});
}
return request;
} | [
"function",
"(",
"request",
",",
"slotName",
",",
"slotType",
",",
"value",
",",
"id",
")",
"{",
"'use strict'",
";",
"if",
"(",
"!",
"request",
")",
"{",
"throw",
"'request must be specified to add entity resolution'",
";",
"}",
"if",
"(",
"!",
"slotName",
")",
"{",
"throw",
"'slotName must be specified to add entity resolution'",
";",
"}",
"if",
"(",
"!",
"value",
")",
"{",
"throw",
"'value must be specified to add entity resolution'",
";",
"}",
"if",
"(",
"!",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
")",
"{",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
"=",
"{",
"name",
":",
"slotName",
",",
"value",
":",
"value",
"}",
";",
"}",
"const",
"authority",
"=",
"\"amzn1.er-authority.echo-sdk.\"",
"+",
"this",
".",
"appId",
"+",
"\".\"",
"+",
"slotType",
";",
"var",
"valueAdded",
"=",
"false",
";",
"if",
"(",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
".",
"resolutions",
")",
"{",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
".",
"resolutions",
".",
"resolutionsPerAuthority",
".",
"forEach",
"(",
"rpa",
"=>",
"{",
"if",
"(",
"!",
"valueAdded",
"&&",
"(",
"rpa",
".",
"authority",
"===",
"authority",
")",
")",
"{",
"rpa",
".",
"values",
".",
"push",
"(",
"{",
"\"value\"",
":",
"{",
"\"name\"",
":",
"value",
",",
"\"id\"",
":",
"id",
"}",
"}",
")",
";",
"valueAdded",
"=",
"true",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
".",
"resolutions",
"=",
"{",
"\"resolutionsPerAuthority\"",
":",
"[",
"]",
"}",
";",
"}",
"if",
"(",
"!",
"valueAdded",
")",
"{",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
".",
"resolutions",
".",
"resolutionsPerAuthority",
".",
"push",
"(",
"{",
"\"authority\"",
":",
"authority",
",",
"\"status\"",
":",
"{",
"\"code\"",
":",
"\"ER_SUCCESS_MATCH\"",
"}",
",",
"\"values\"",
":",
"[",
"{",
"\"value\"",
":",
"{",
"\"name\"",
":",
"value",
",",
"\"id\"",
":",
"id",
"}",
"}",
"]",
"}",
")",
";",
"}",
"return",
"request",
";",
"}"
] | Adds an entity resolution to the given request.
@param {object} request The intent request to modify.
@param {string} slotName The name of the slot to add the resolution to. If the slot does not exist it is added.
@param {string} slotType The type of the slot.
@param {string} value The value of the slot.
@param {string} id The id of the resolved entity.
@return {object} the given intent request to allow chaining. | [
"Adds",
"an",
"entity",
"resolution",
"to",
"the",
"given",
"request",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L309-L362 | |
22,823 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (request, resolutions) {
'use strict';
let alexaTest = this;
resolutions.forEach(resolution => {
alexaTest.addEntityResolutionToRequest(request, resolution.slotName, resolution.slotType, resolution.value, resolution.id);
});
return request;
} | javascript | function (request, resolutions) {
'use strict';
let alexaTest = this;
resolutions.forEach(resolution => {
alexaTest.addEntityResolutionToRequest(request, resolution.slotName, resolution.slotType, resolution.value, resolution.id);
});
return request;
} | [
"function",
"(",
"request",
",",
"resolutions",
")",
"{",
"'use strict'",
";",
"let",
"alexaTest",
"=",
"this",
";",
"resolutions",
".",
"forEach",
"(",
"resolution",
"=>",
"{",
"alexaTest",
".",
"addEntityResolutionToRequest",
"(",
"request",
",",
"resolution",
".",
"slotName",
",",
"resolution",
".",
"slotType",
",",
"resolution",
".",
"value",
",",
"resolution",
".",
"id",
")",
";",
"}",
")",
";",
"return",
"request",
";",
"}"
] | Adds multiple entity resolutions to the given request.
@param {object} request The intent request to modify.
@param {array} resolutions The array containing the resolutions to add
@return {object} the given intent request to allow chaining. | [
"Adds",
"multiple",
"entity",
"resolutions",
"to",
"the",
"given",
"request",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L370-L377 | |
22,824 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (request, slotName, slotType, value) {
'use strict';
if (!request) {
throw 'request must be specified to add entity resolution';
}
if (!slotName) {
throw 'slotName must be specified to add entity resolution';
}
if (!value) {
throw 'value must be specified to add entity resolution';
}
if (!request.request.intent.slots[slotName]) {
request.request.intent.slots[slotName] = {name: slotName, value: value};
}
if (!request.request.intent.slots[slotName].resolutions) {
request.request.intent.slots[slotName].resolutions = {
"resolutionsPerAuthority": []
};
}
request.request.intent.slots[slotName].resolutions.resolutionsPerAuthority.push({
"authority": "amzn1.er-authority.echo-sdk." + this.appId + "." + slotType,
"status": {
"code": "ER_SUCCESS_NO_MATCH"
}
});
return request;
} | javascript | function (request, slotName, slotType, value) {
'use strict';
if (!request) {
throw 'request must be specified to add entity resolution';
}
if (!slotName) {
throw 'slotName must be specified to add entity resolution';
}
if (!value) {
throw 'value must be specified to add entity resolution';
}
if (!request.request.intent.slots[slotName]) {
request.request.intent.slots[slotName] = {name: slotName, value: value};
}
if (!request.request.intent.slots[slotName].resolutions) {
request.request.intent.slots[slotName].resolutions = {
"resolutionsPerAuthority": []
};
}
request.request.intent.slots[slotName].resolutions.resolutionsPerAuthority.push({
"authority": "amzn1.er-authority.echo-sdk." + this.appId + "." + slotType,
"status": {
"code": "ER_SUCCESS_NO_MATCH"
}
});
return request;
} | [
"function",
"(",
"request",
",",
"slotName",
",",
"slotType",
",",
"value",
")",
"{",
"'use strict'",
";",
"if",
"(",
"!",
"request",
")",
"{",
"throw",
"'request must be specified to add entity resolution'",
";",
"}",
"if",
"(",
"!",
"slotName",
")",
"{",
"throw",
"'slotName must be specified to add entity resolution'",
";",
"}",
"if",
"(",
"!",
"value",
")",
"{",
"throw",
"'value must be specified to add entity resolution'",
";",
"}",
"if",
"(",
"!",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
")",
"{",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
"=",
"{",
"name",
":",
"slotName",
",",
"value",
":",
"value",
"}",
";",
"}",
"if",
"(",
"!",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
".",
"resolutions",
")",
"{",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
".",
"resolutions",
"=",
"{",
"\"resolutionsPerAuthority\"",
":",
"[",
"]",
"}",
";",
"}",
"request",
".",
"request",
".",
"intent",
".",
"slots",
"[",
"slotName",
"]",
".",
"resolutions",
".",
"resolutionsPerAuthority",
".",
"push",
"(",
"{",
"\"authority\"",
":",
"\"amzn1.er-authority.echo-sdk.\"",
"+",
"this",
".",
"appId",
"+",
"\".\"",
"+",
"slotType",
",",
"\"status\"",
":",
"{",
"\"code\"",
":",
"\"ER_SUCCESS_NO_MATCH\"",
"}",
"}",
")",
";",
"return",
"request",
";",
"}"
] | Adds an entity resolution with code ER_SUCCESS_NO_MATCH to the given request.
@param {object} request The intent request to modify.
@param {string} slotName The name of the slot to add the resolution to. If the slot does not exist it is added.
@param {string} slotType The type of the slot.
@param {string} value The value of the slot.
@return {object} the given intent request to allow chaining. | [
"Adds",
"an",
"entity",
"resolution",
"with",
"code",
"ER_SUCCESS_NO_MATCH",
"to",
"the",
"given",
"request",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L387-L416 | |
22,825 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (context, name, actual, expected) {
'use strict';
if (expected !== actual) {
context.assert(
{
message: "the response did not return the correct " + name + " value",
expected: expected, actual: actual ? actual : String(actual),
operator: "==", showDiff: true
});
}
} | javascript | function (context, name, actual, expected) {
'use strict';
if (expected !== actual) {
context.assert(
{
message: "the response did not return the correct " + name + " value",
expected: expected, actual: actual ? actual : String(actual),
operator: "==", showDiff: true
});
}
} | [
"function",
"(",
"context",
",",
"name",
",",
"actual",
",",
"expected",
")",
"{",
"'use strict'",
";",
"if",
"(",
"expected",
"!==",
"actual",
")",
"{",
"context",
".",
"assert",
"(",
"{",
"message",
":",
"\"the response did not return the correct \"",
"+",
"name",
"+",
"\" value\"",
",",
"expected",
":",
"expected",
",",
"actual",
":",
"actual",
"?",
"actual",
":",
"String",
"(",
"actual",
")",
",",
"operator",
":",
"\"==\"",
",",
"showDiff",
":",
"true",
"}",
")",
";",
"}",
"}"
] | Internal method. Asserts if the strings are not equal. | [
"Internal",
"method",
".",
"Asserts",
"if",
"the",
"strings",
"are",
"not",
"equal",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L752-L762 | |
22,826 | BrianMacIntosh/alexa-skill-test-framework | index.js | function (context, name, actual, expectedArray) {
'use strict';
for (let i = 0; i < expectedArray.length; i++) {
if (actual === expectedArray[i]) {
return;
}
}
context.assert(
{
message: "the response did not contain a valid speechOutput",
expected: "one of [" + expectedArray.map(text => `"${text}"`).join(', ') + "]",
actual: actual,
operator: "==", showDiff: true
});
} | javascript | function (context, name, actual, expectedArray) {
'use strict';
for (let i = 0; i < expectedArray.length; i++) {
if (actual === expectedArray[i]) {
return;
}
}
context.assert(
{
message: "the response did not contain a valid speechOutput",
expected: "one of [" + expectedArray.map(text => `"${text}"`).join(', ') + "]",
actual: actual,
operator: "==", showDiff: true
});
} | [
"function",
"(",
"context",
",",
"name",
",",
"actual",
",",
"expectedArray",
")",
"{",
"'use strict'",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"expectedArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"actual",
"===",
"expectedArray",
"[",
"i",
"]",
")",
"{",
"return",
";",
"}",
"}",
"context",
".",
"assert",
"(",
"{",
"message",
":",
"\"the response did not contain a valid speechOutput\"",
",",
"expected",
":",
"\"one of [\"",
"+",
"expectedArray",
".",
"map",
"(",
"text",
"=>",
"`",
"${",
"text",
"}",
"`",
")",
".",
"join",
"(",
"', '",
")",
"+",
"\"]\"",
",",
"actual",
":",
"actual",
",",
"operator",
":",
"\"==\"",
",",
"showDiff",
":",
"true",
"}",
")",
";",
"}"
] | Internal method. Asserts if the string is not part of the array. | [
"Internal",
"method",
".",
"Asserts",
"if",
"the",
"string",
"is",
"not",
"part",
"of",
"the",
"array",
"."
] | 6476443369e85e45800dd88f05ccc42a23ce6c48 | https://github.com/BrianMacIntosh/alexa-skill-test-framework/blob/6476443369e85e45800dd88f05ccc42a23ce6c48/index.js#L767-L781 | |
22,827 | owncloud/davclient.js | lib/client.js | function(url, properties, depth, headers) {
if(typeof depth === "undefined") {
depth = '0';
}
// depth header must be a string, in case a number was passed in
depth = '' + depth;
headers = headers || {};
headers['Depth'] = depth;
headers['Content-Type'] = 'application/xml; charset=utf-8';
var body =
'<?xml version="1.0"?>\n' +
'<d:propfind ';
var namespace;
for (namespace in this.xmlNamespaces) {
body += ' xmlns:' + this.xmlNamespaces[namespace] + '="' + namespace + '"';
}
body += '>\n' +
' <d:prop>\n';
for(var ii in properties) {
if (!properties.hasOwnProperty(ii)) {
continue;
}
var property = this.parseClarkNotation(properties[ii]);
if (this.xmlNamespaces[property.namespace]) {
body+=' <' + this.xmlNamespaces[property.namespace] + ':' + property.name + ' />\n';
} else {
body+=' <x:' + property.name + ' xmlns:x="' + property.namespace + '" />\n';
}
}
body+=' </d:prop>\n';
body+='</d:propfind>';
return this.request('PROPFIND', url, headers, body).then(
function(result) {
if (depth === '0') {
return {
status: result.status,
body: result.body[0],
xhr: result.xhr
};
} else {
return {
status: result.status,
body: result.body,
xhr: result.xhr
};
}
}.bind(this)
);
} | javascript | function(url, properties, depth, headers) {
if(typeof depth === "undefined") {
depth = '0';
}
// depth header must be a string, in case a number was passed in
depth = '' + depth;
headers = headers || {};
headers['Depth'] = depth;
headers['Content-Type'] = 'application/xml; charset=utf-8';
var body =
'<?xml version="1.0"?>\n' +
'<d:propfind ';
var namespace;
for (namespace in this.xmlNamespaces) {
body += ' xmlns:' + this.xmlNamespaces[namespace] + '="' + namespace + '"';
}
body += '>\n' +
' <d:prop>\n';
for(var ii in properties) {
if (!properties.hasOwnProperty(ii)) {
continue;
}
var property = this.parseClarkNotation(properties[ii]);
if (this.xmlNamespaces[property.namespace]) {
body+=' <' + this.xmlNamespaces[property.namespace] + ':' + property.name + ' />\n';
} else {
body+=' <x:' + property.name + ' xmlns:x="' + property.namespace + '" />\n';
}
}
body+=' </d:prop>\n';
body+='</d:propfind>';
return this.request('PROPFIND', url, headers, body).then(
function(result) {
if (depth === '0') {
return {
status: result.status,
body: result.body[0],
xhr: result.xhr
};
} else {
return {
status: result.status,
body: result.body,
xhr: result.xhr
};
}
}.bind(this)
);
} | [
"function",
"(",
"url",
",",
"properties",
",",
"depth",
",",
"headers",
")",
"{",
"if",
"(",
"typeof",
"depth",
"===",
"\"undefined\"",
")",
"{",
"depth",
"=",
"'0'",
";",
"}",
"// depth header must be a string, in case a number was passed in",
"depth",
"=",
"''",
"+",
"depth",
";",
"headers",
"=",
"headers",
"||",
"{",
"}",
";",
"headers",
"[",
"'Depth'",
"]",
"=",
"depth",
";",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/xml; charset=utf-8'",
";",
"var",
"body",
"=",
"'<?xml version=\"1.0\"?>\\n'",
"+",
"'<d:propfind '",
";",
"var",
"namespace",
";",
"for",
"(",
"namespace",
"in",
"this",
".",
"xmlNamespaces",
")",
"{",
"body",
"+=",
"' xmlns:'",
"+",
"this",
".",
"xmlNamespaces",
"[",
"namespace",
"]",
"+",
"'=\"'",
"+",
"namespace",
"+",
"'\"'",
";",
"}",
"body",
"+=",
"'>\\n'",
"+",
"' <d:prop>\\n'",
";",
"for",
"(",
"var",
"ii",
"in",
"properties",
")",
"{",
"if",
"(",
"!",
"properties",
".",
"hasOwnProperty",
"(",
"ii",
")",
")",
"{",
"continue",
";",
"}",
"var",
"property",
"=",
"this",
".",
"parseClarkNotation",
"(",
"properties",
"[",
"ii",
"]",
")",
";",
"if",
"(",
"this",
".",
"xmlNamespaces",
"[",
"property",
".",
"namespace",
"]",
")",
"{",
"body",
"+=",
"' <'",
"+",
"this",
".",
"xmlNamespaces",
"[",
"property",
".",
"namespace",
"]",
"+",
"':'",
"+",
"property",
".",
"name",
"+",
"' />\\n'",
";",
"}",
"else",
"{",
"body",
"+=",
"' <x:'",
"+",
"property",
".",
"name",
"+",
"' xmlns:x=\"'",
"+",
"property",
".",
"namespace",
"+",
"'\" />\\n'",
";",
"}",
"}",
"body",
"+=",
"' </d:prop>\\n'",
";",
"body",
"+=",
"'</d:propfind>'",
";",
"return",
"this",
".",
"request",
"(",
"'PROPFIND'",
",",
"url",
",",
"headers",
",",
"body",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"if",
"(",
"depth",
"===",
"'0'",
")",
"{",
"return",
"{",
"status",
":",
"result",
".",
"status",
",",
"body",
":",
"result",
".",
"body",
"[",
"0",
"]",
",",
"xhr",
":",
"result",
".",
"xhr",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"status",
":",
"result",
".",
"status",
",",
"body",
":",
"result",
".",
"body",
",",
"xhr",
":",
"result",
".",
"xhr",
"}",
";",
"}",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Generates a propFind request.
@param {string} url Url to do the propfind request on
@param {Array} properties List of properties to retrieve.
@param {string} depth "0", "1" or "infinity"
@param {Object} [headers] headers
@return {Promise} | [
"Generates",
"a",
"propFind",
"request",
"."
] | 07237a4bb813eb19e19e322e2457ce216721d529 | https://github.com/owncloud/davclient.js/blob/07237a4bb813eb19e19e322e2457ce216721d529/lib/client.js#L52-L112 | |
22,828 | owncloud/davclient.js | lib/client.js | function(url, properties, headers) {
headers = headers || {};
headers['Content-Type'] = 'application/xml; charset=utf-8';
var body =
'<?xml version="1.0"?>\n' +
'<d:propertyupdate ';
var namespace;
for (namespace in this.xmlNamespaces) {
body += ' xmlns:' + this.xmlNamespaces[namespace] + '="' + namespace + '"';
}
body += '>\n' + this._renderPropSet(properties);
body += '</d:propertyupdate>';
return this.request('PROPPATCH', url, headers, body).then(
function(result) {
return {
status: result.status,
body: result.body,
xhr: result.xhr
};
}.bind(this)
);
} | javascript | function(url, properties, headers) {
headers = headers || {};
headers['Content-Type'] = 'application/xml; charset=utf-8';
var body =
'<?xml version="1.0"?>\n' +
'<d:propertyupdate ';
var namespace;
for (namespace in this.xmlNamespaces) {
body += ' xmlns:' + this.xmlNamespaces[namespace] + '="' + namespace + '"';
}
body += '>\n' + this._renderPropSet(properties);
body += '</d:propertyupdate>';
return this.request('PROPPATCH', url, headers, body).then(
function(result) {
return {
status: result.status,
body: result.body,
xhr: result.xhr
};
}.bind(this)
);
} | [
"function",
"(",
"url",
",",
"properties",
",",
"headers",
")",
"{",
"headers",
"=",
"headers",
"||",
"{",
"}",
";",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/xml; charset=utf-8'",
";",
"var",
"body",
"=",
"'<?xml version=\"1.0\"?>\\n'",
"+",
"'<d:propertyupdate '",
";",
"var",
"namespace",
";",
"for",
"(",
"namespace",
"in",
"this",
".",
"xmlNamespaces",
")",
"{",
"body",
"+=",
"' xmlns:'",
"+",
"this",
".",
"xmlNamespaces",
"[",
"namespace",
"]",
"+",
"'=\"'",
"+",
"namespace",
"+",
"'\"'",
";",
"}",
"body",
"+=",
"'>\\n'",
"+",
"this",
".",
"_renderPropSet",
"(",
"properties",
")",
";",
"body",
"+=",
"'</d:propertyupdate>'",
";",
"return",
"this",
".",
"request",
"(",
"'PROPPATCH'",
",",
"url",
",",
"headers",
",",
"body",
")",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"{",
"status",
":",
"result",
".",
"status",
",",
"body",
":",
"result",
".",
"body",
",",
"xhr",
":",
"result",
".",
"xhr",
"}",
";",
"}",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] | Generates a propPatch request.
@param {string} url Url to do the proppatch request on
@param {Object.<String,String>} properties List of properties to store.
@param {Object} [headers] headers
@return {Promise} | [
"Generates",
"a",
"propPatch",
"request",
"."
] | 07237a4bb813eb19e19e322e2457ce216721d529 | https://github.com/owncloud/davclient.js/blob/07237a4bb813eb19e19e322e2457ce216721d529/lib/client.js#L158-L183 | |
22,829 | owncloud/davclient.js | lib/client.js | function(method, url, headers, body, responseType) {
var self = this;
var xhr = this.xhrProvider();
headers = headers || {};
responseType = responseType || "";
if (this.userName) {
headers['Authorization'] = 'Basic ' + btoa(this.userName + ':' + this.password);
// xhr.open(method, this.resolveUrl(url), true, this.userName, this.password);
}
xhr.open(method, this.resolveUrl(url), true);
var ii;
for(ii in headers) {
xhr.setRequestHeader(ii, headers[ii]);
}
xhr.responseType = responseType;
// Work around for edge
if (body === undefined) {
xhr.send();
} else {
xhr.send(body);
}
return new Promise(function(fulfill, reject) {
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
var resultBody = xhr.response;
if (xhr.status === 207) {
resultBody = self.parseMultiStatus(xhr.response);
}
fulfill({
body: resultBody,
status: xhr.status,
xhr: xhr
});
};
xhr.ontimeout = function() {
reject(new Error('Timeout exceeded'));
};
});
} | javascript | function(method, url, headers, body, responseType) {
var self = this;
var xhr = this.xhrProvider();
headers = headers || {};
responseType = responseType || "";
if (this.userName) {
headers['Authorization'] = 'Basic ' + btoa(this.userName + ':' + this.password);
// xhr.open(method, this.resolveUrl(url), true, this.userName, this.password);
}
xhr.open(method, this.resolveUrl(url), true);
var ii;
for(ii in headers) {
xhr.setRequestHeader(ii, headers[ii]);
}
xhr.responseType = responseType;
// Work around for edge
if (body === undefined) {
xhr.send();
} else {
xhr.send(body);
}
return new Promise(function(fulfill, reject) {
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
var resultBody = xhr.response;
if (xhr.status === 207) {
resultBody = self.parseMultiStatus(xhr.response);
}
fulfill({
body: resultBody,
status: xhr.status,
xhr: xhr
});
};
xhr.ontimeout = function() {
reject(new Error('Timeout exceeded'));
};
});
} | [
"function",
"(",
"method",
",",
"url",
",",
"headers",
",",
"body",
",",
"responseType",
")",
"{",
"var",
"self",
"=",
"this",
";",
"var",
"xhr",
"=",
"this",
".",
"xhrProvider",
"(",
")",
";",
"headers",
"=",
"headers",
"||",
"{",
"}",
";",
"responseType",
"=",
"responseType",
"||",
"\"\"",
";",
"if",
"(",
"this",
".",
"userName",
")",
"{",
"headers",
"[",
"'Authorization'",
"]",
"=",
"'Basic '",
"+",
"btoa",
"(",
"this",
".",
"userName",
"+",
"':'",
"+",
"this",
".",
"password",
")",
";",
"// xhr.open(method, this.resolveUrl(url), true, this.userName, this.password);",
"}",
"xhr",
".",
"open",
"(",
"method",
",",
"this",
".",
"resolveUrl",
"(",
"url",
")",
",",
"true",
")",
";",
"var",
"ii",
";",
"for",
"(",
"ii",
"in",
"headers",
")",
"{",
"xhr",
".",
"setRequestHeader",
"(",
"ii",
",",
"headers",
"[",
"ii",
"]",
")",
";",
"}",
"xhr",
".",
"responseType",
"=",
"responseType",
";",
"// Work around for edge",
"if",
"(",
"body",
"===",
"undefined",
")",
"{",
"xhr",
".",
"send",
"(",
")",
";",
"}",
"else",
"{",
"xhr",
".",
"send",
"(",
"body",
")",
";",
"}",
"return",
"new",
"Promise",
"(",
"function",
"(",
"fulfill",
",",
"reject",
")",
"{",
"xhr",
".",
"onreadystatechange",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"xhr",
".",
"readyState",
"!==",
"4",
")",
"{",
"return",
";",
"}",
"var",
"resultBody",
"=",
"xhr",
".",
"response",
";",
"if",
"(",
"xhr",
".",
"status",
"===",
"207",
")",
"{",
"resultBody",
"=",
"self",
".",
"parseMultiStatus",
"(",
"xhr",
".",
"response",
")",
";",
"}",
"fulfill",
"(",
"{",
"body",
":",
"resultBody",
",",
"status",
":",
"xhr",
".",
"status",
",",
"xhr",
":",
"xhr",
"}",
")",
";",
"}",
";",
"xhr",
".",
"ontimeout",
"=",
"function",
"(",
")",
"{",
"reject",
"(",
"new",
"Error",
"(",
"'Timeout exceeded'",
")",
")",
";",
"}",
";",
"}",
")",
";",
"}"
] | Performs a HTTP request, and returns a Promise
@param {string} method HTTP method
@param {string} url Relative or absolute url
@param {Object} headers HTTP headers as an object.
@param {string} body HTTP request body.
@param {string} responseType HTTP request response type.
@return {Promise} | [
"Performs",
"a",
"HTTP",
"request",
"and",
"returns",
"a",
"Promise"
] | 07237a4bb813eb19e19e322e2457ce216721d529 | https://github.com/owncloud/davclient.js/blob/07237a4bb813eb19e19e322e2457ce216721d529/lib/client.js#L233-L287 | |
22,830 | owncloud/davclient.js | lib/client.js | function(propNode) {
var content = null;
if (propNode.childNodes && propNode.childNodes.length > 0) {
var subNodes = [];
// filter out text nodes
for (var j = 0; j < propNode.childNodes.length; j++) {
var node = propNode.childNodes[j];
if (node.nodeType === 1) {
subNodes.push(node);
}
}
if (subNodes.length) {
content = subNodes;
}
}
return content || propNode.textContent || propNode.text || '';
} | javascript | function(propNode) {
var content = null;
if (propNode.childNodes && propNode.childNodes.length > 0) {
var subNodes = [];
// filter out text nodes
for (var j = 0; j < propNode.childNodes.length; j++) {
var node = propNode.childNodes[j];
if (node.nodeType === 1) {
subNodes.push(node);
}
}
if (subNodes.length) {
content = subNodes;
}
}
return content || propNode.textContent || propNode.text || '';
} | [
"function",
"(",
"propNode",
")",
"{",
"var",
"content",
"=",
"null",
";",
"if",
"(",
"propNode",
".",
"childNodes",
"&&",
"propNode",
".",
"childNodes",
".",
"length",
">",
"0",
")",
"{",
"var",
"subNodes",
"=",
"[",
"]",
";",
"// filter out text nodes",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"propNode",
".",
"childNodes",
".",
"length",
";",
"j",
"++",
")",
"{",
"var",
"node",
"=",
"propNode",
".",
"childNodes",
"[",
"j",
"]",
";",
"if",
"(",
"node",
".",
"nodeType",
"===",
"1",
")",
"{",
"subNodes",
".",
"push",
"(",
"node",
")",
";",
"}",
"}",
"if",
"(",
"subNodes",
".",
"length",
")",
"{",
"content",
"=",
"subNodes",
";",
"}",
"}",
"return",
"content",
"||",
"propNode",
".",
"textContent",
"||",
"propNode",
".",
"text",
"||",
"''",
";",
"}"
] | Parses a property node.
Either returns a string if the node only contains text, or returns an
array of non-text subnodes.
@param {Object} propNode node to parse
@return {string|Array} text content as string or array of subnodes, excluding text nodes | [
"Parses",
"a",
"property",
"node",
"."
] | 07237a4bb813eb19e19e322e2457ce216721d529 | https://github.com/owncloud/davclient.js/blob/07237a4bb813eb19e19e322e2457ce216721d529/lib/client.js#L311-L328 | |
22,831 | owncloud/davclient.js | lib/client.js | function(xmlBody) {
var parser = new DOMParser();
var doc = parser.parseFromString(xmlBody, "application/xml");
var resolver = function(foo) {
var ii;
for(ii in this.xmlNamespaces) {
if (this.xmlNamespaces[ii] === foo) {
return ii;
}
}
}.bind(this);
var responseIterator = doc.evaluate('/d:multistatus/d:response', doc, resolver, XPathResult.ANY_TYPE, null);
var result = [];
var responseNode = responseIterator.iterateNext();
while(responseNode) {
var response = {
href : null,
propStat : []
};
response.href = doc.evaluate('string(d:href)', responseNode, resolver, XPathResult.ANY_TYPE, null).stringValue;
var propStatIterator = doc.evaluate('d:propstat', responseNode, resolver, XPathResult.ANY_TYPE, null);
var propStatNode = propStatIterator.iterateNext();
while(propStatNode) {
var propStat = {
status : doc.evaluate('string(d:status)', propStatNode, resolver, XPathResult.ANY_TYPE, null).stringValue,
properties : {},
};
var propIterator = doc.evaluate('d:prop/*', propStatNode, resolver, XPathResult.ANY_TYPE, null);
var propNode = propIterator.iterateNext();
while(propNode) {
var content = this._parsePropNode(propNode);
propStat.properties['{' + propNode.namespaceURI + '}' + propNode.localName] = content;
propNode = propIterator.iterateNext();
}
response.propStat.push(propStat);
propStatNode = propStatIterator.iterateNext();
}
result.push(response);
responseNode = responseIterator.iterateNext();
}
return result;
} | javascript | function(xmlBody) {
var parser = new DOMParser();
var doc = parser.parseFromString(xmlBody, "application/xml");
var resolver = function(foo) {
var ii;
for(ii in this.xmlNamespaces) {
if (this.xmlNamespaces[ii] === foo) {
return ii;
}
}
}.bind(this);
var responseIterator = doc.evaluate('/d:multistatus/d:response', doc, resolver, XPathResult.ANY_TYPE, null);
var result = [];
var responseNode = responseIterator.iterateNext();
while(responseNode) {
var response = {
href : null,
propStat : []
};
response.href = doc.evaluate('string(d:href)', responseNode, resolver, XPathResult.ANY_TYPE, null).stringValue;
var propStatIterator = doc.evaluate('d:propstat', responseNode, resolver, XPathResult.ANY_TYPE, null);
var propStatNode = propStatIterator.iterateNext();
while(propStatNode) {
var propStat = {
status : doc.evaluate('string(d:status)', propStatNode, resolver, XPathResult.ANY_TYPE, null).stringValue,
properties : {},
};
var propIterator = doc.evaluate('d:prop/*', propStatNode, resolver, XPathResult.ANY_TYPE, null);
var propNode = propIterator.iterateNext();
while(propNode) {
var content = this._parsePropNode(propNode);
propStat.properties['{' + propNode.namespaceURI + '}' + propNode.localName] = content;
propNode = propIterator.iterateNext();
}
response.propStat.push(propStat);
propStatNode = propStatIterator.iterateNext();
}
result.push(response);
responseNode = responseIterator.iterateNext();
}
return result;
} | [
"function",
"(",
"xmlBody",
")",
"{",
"var",
"parser",
"=",
"new",
"DOMParser",
"(",
")",
";",
"var",
"doc",
"=",
"parser",
".",
"parseFromString",
"(",
"xmlBody",
",",
"\"application/xml\"",
")",
";",
"var",
"resolver",
"=",
"function",
"(",
"foo",
")",
"{",
"var",
"ii",
";",
"for",
"(",
"ii",
"in",
"this",
".",
"xmlNamespaces",
")",
"{",
"if",
"(",
"this",
".",
"xmlNamespaces",
"[",
"ii",
"]",
"===",
"foo",
")",
"{",
"return",
"ii",
";",
"}",
"}",
"}",
".",
"bind",
"(",
"this",
")",
";",
"var",
"responseIterator",
"=",
"doc",
".",
"evaluate",
"(",
"'/d:multistatus/d:response'",
",",
"doc",
",",
"resolver",
",",
"XPathResult",
".",
"ANY_TYPE",
",",
"null",
")",
";",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"responseNode",
"=",
"responseIterator",
".",
"iterateNext",
"(",
")",
";",
"while",
"(",
"responseNode",
")",
"{",
"var",
"response",
"=",
"{",
"href",
":",
"null",
",",
"propStat",
":",
"[",
"]",
"}",
";",
"response",
".",
"href",
"=",
"doc",
".",
"evaluate",
"(",
"'string(d:href)'",
",",
"responseNode",
",",
"resolver",
",",
"XPathResult",
".",
"ANY_TYPE",
",",
"null",
")",
".",
"stringValue",
";",
"var",
"propStatIterator",
"=",
"doc",
".",
"evaluate",
"(",
"'d:propstat'",
",",
"responseNode",
",",
"resolver",
",",
"XPathResult",
".",
"ANY_TYPE",
",",
"null",
")",
";",
"var",
"propStatNode",
"=",
"propStatIterator",
".",
"iterateNext",
"(",
")",
";",
"while",
"(",
"propStatNode",
")",
"{",
"var",
"propStat",
"=",
"{",
"status",
":",
"doc",
".",
"evaluate",
"(",
"'string(d:status)'",
",",
"propStatNode",
",",
"resolver",
",",
"XPathResult",
".",
"ANY_TYPE",
",",
"null",
")",
".",
"stringValue",
",",
"properties",
":",
"{",
"}",
",",
"}",
";",
"var",
"propIterator",
"=",
"doc",
".",
"evaluate",
"(",
"'d:prop/*'",
",",
"propStatNode",
",",
"resolver",
",",
"XPathResult",
".",
"ANY_TYPE",
",",
"null",
")",
";",
"var",
"propNode",
"=",
"propIterator",
".",
"iterateNext",
"(",
")",
";",
"while",
"(",
"propNode",
")",
"{",
"var",
"content",
"=",
"this",
".",
"_parsePropNode",
"(",
"propNode",
")",
";",
"propStat",
".",
"properties",
"[",
"'{'",
"+",
"propNode",
".",
"namespaceURI",
"+",
"'}'",
"+",
"propNode",
".",
"localName",
"]",
"=",
"content",
";",
"propNode",
"=",
"propIterator",
".",
"iterateNext",
"(",
")",
";",
"}",
"response",
".",
"propStat",
".",
"push",
"(",
"propStat",
")",
";",
"propStatNode",
"=",
"propStatIterator",
".",
"iterateNext",
"(",
")",
";",
"}",
"result",
".",
"push",
"(",
"response",
")",
";",
"responseNode",
"=",
"responseIterator",
".",
"iterateNext",
"(",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Parses a multi-status response body.
@param {string} xmlBody
@param {Array} | [
"Parses",
"a",
"multi",
"-",
"status",
"response",
"body",
"."
] | 07237a4bb813eb19e19e322e2457ce216721d529 | https://github.com/owncloud/davclient.js/blob/07237a4bb813eb19e19e322e2457ce216721d529/lib/client.js#L336-L395 | |
22,832 | owncloud/davclient.js | lib/client.js | function(url) {
// Note: this is rudamentary.. not sure yet if it handles every case.
if (/^https?:\/\//i.test(url)) {
// absolute
return url;
}
var baseParts = this.parseUrl(this.baseUrl);
if (url.charAt('/')) {
// Url starts with a slash
return baseParts.root + url;
}
// Url does not start with a slash, we need grab the base url right up until the last slash.
var newUrl = baseParts.root + '/';
if (baseParts.path.lastIndexOf('/')!==-1) {
newUrl = newUrl = baseParts.path.subString(0, baseParts.path.lastIndexOf('/')) + '/';
}
newUrl+=url;
return url;
} | javascript | function(url) {
// Note: this is rudamentary.. not sure yet if it handles every case.
if (/^https?:\/\//i.test(url)) {
// absolute
return url;
}
var baseParts = this.parseUrl(this.baseUrl);
if (url.charAt('/')) {
// Url starts with a slash
return baseParts.root + url;
}
// Url does not start with a slash, we need grab the base url right up until the last slash.
var newUrl = baseParts.root + '/';
if (baseParts.path.lastIndexOf('/')!==-1) {
newUrl = newUrl = baseParts.path.subString(0, baseParts.path.lastIndexOf('/')) + '/';
}
newUrl+=url;
return url;
} | [
"function",
"(",
"url",
")",
"{",
"// Note: this is rudamentary.. not sure yet if it handles every case.",
"if",
"(",
"/",
"^https?:\\/\\/",
"/",
"i",
".",
"test",
"(",
"url",
")",
")",
"{",
"// absolute",
"return",
"url",
";",
"}",
"var",
"baseParts",
"=",
"this",
".",
"parseUrl",
"(",
"this",
".",
"baseUrl",
")",
";",
"if",
"(",
"url",
".",
"charAt",
"(",
"'/'",
")",
")",
"{",
"// Url starts with a slash",
"return",
"baseParts",
".",
"root",
"+",
"url",
";",
"}",
"// Url does not start with a slash, we need grab the base url right up until the last slash.",
"var",
"newUrl",
"=",
"baseParts",
".",
"root",
"+",
"'/'",
";",
"if",
"(",
"baseParts",
".",
"path",
".",
"lastIndexOf",
"(",
"'/'",
")",
"!==",
"-",
"1",
")",
"{",
"newUrl",
"=",
"newUrl",
"=",
"baseParts",
".",
"path",
".",
"subString",
"(",
"0",
",",
"baseParts",
".",
"path",
".",
"lastIndexOf",
"(",
"'/'",
")",
")",
"+",
"'/'",
";",
"}",
"newUrl",
"+=",
"url",
";",
"return",
"url",
";",
"}"
] | Takes a relative url, and maps it to an absolute url, using the baseUrl
@param {string} url
@return {string} | [
"Takes",
"a",
"relative",
"url",
"and",
"maps",
"it",
"to",
"an",
"absolute",
"url",
"using",
"the",
"baseUrl"
] | 07237a4bb813eb19e19e322e2457ce216721d529 | https://github.com/owncloud/davclient.js/blob/07237a4bb813eb19e19e322e2457ce216721d529/lib/client.js#L403-L425 | |
22,833 | owncloud/davclient.js | lib/client.js | function(url) {
var parts = url.match(/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/);
var result = {
url : parts[0],
scheme : parts[1],
host : parts[3],
port : parts[4],
path : parts[5],
query : parts[6],
fragment : parts[7],
};
result.root =
result.scheme + '://' +
result.host +
(result.port ? ':' + result.port : '');
return result;
} | javascript | function(url) {
var parts = url.match(/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/);
var result = {
url : parts[0],
scheme : parts[1],
host : parts[3],
port : parts[4],
path : parts[5],
query : parts[6],
fragment : parts[7],
};
result.root =
result.scheme + '://' +
result.host +
(result.port ? ':' + result.port : '');
return result;
} | [
"function",
"(",
"url",
")",
"{",
"var",
"parts",
"=",
"url",
".",
"match",
"(",
"/",
"^(?:([A-Za-z]+):)?(\\/{0,3})([0-9.\\-A-Za-z]+)(?::(\\d+))?(?:\\/([^?#]*))?(?:\\?([^#]*))?(?:#(.*))?$",
"/",
")",
";",
"var",
"result",
"=",
"{",
"url",
":",
"parts",
"[",
"0",
"]",
",",
"scheme",
":",
"parts",
"[",
"1",
"]",
",",
"host",
":",
"parts",
"[",
"3",
"]",
",",
"port",
":",
"parts",
"[",
"4",
"]",
",",
"path",
":",
"parts",
"[",
"5",
"]",
",",
"query",
":",
"parts",
"[",
"6",
"]",
",",
"fragment",
":",
"parts",
"[",
"7",
"]",
",",
"}",
";",
"result",
".",
"root",
"=",
"result",
".",
"scheme",
"+",
"'://'",
"+",
"result",
".",
"host",
"+",
"(",
"result",
".",
"port",
"?",
"':'",
"+",
"result",
".",
"port",
":",
"''",
")",
";",
"return",
"result",
";",
"}"
] | Parses a url and returns its individual components.
@param {String} url
@return {Object} | [
"Parses",
"a",
"url",
"and",
"returns",
"its",
"individual",
"components",
"."
] | 07237a4bb813eb19e19e322e2457ce216721d529 | https://github.com/owncloud/davclient.js/blob/07237a4bb813eb19e19e322e2457ce216721d529/lib/client.js#L433-L452 | |
22,834 | naholyr/github-todos | index.js | checkUpdate | function checkUpdate () {
var pkg = require("./package.json");
require("update-notifier")({
packageName: pkg.name,
packageVersion: pkg.version
}).notify();
} | javascript | function checkUpdate () {
var pkg = require("./package.json");
require("update-notifier")({
packageName: pkg.name,
packageVersion: pkg.version
}).notify();
} | [
"function",
"checkUpdate",
"(",
")",
"{",
"var",
"pkg",
"=",
"require",
"(",
"\"./package.json\"",
")",
";",
"require",
"(",
"\"update-notifier\"",
")",
"(",
"{",
"packageName",
":",
"pkg",
".",
"name",
",",
"packageVersion",
":",
"pkg",
".",
"version",
"}",
")",
".",
"notify",
"(",
")",
";",
"}"
] | Check for package update | [
"Check",
"for",
"package",
"update"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/index.js#L35-L41 |
22,835 | naholyr/github-todos | index.js | main | function main (processArgv, conf) {
// CLI input
var opts = getOpts(processArgv);
var argv = opts.argv;
// Update notifier
if (!argv["no-notifier"]) {
checkUpdate();
}
// Convert options "--help" and "-h" into command "help"
if (argv.help) {
processArgv = transformHelpArgs(processArgv);
// Regenerate opts from newly forged process.argv
opts = getOpts(processArgv);
argv = opts.argv;
}
// "--version"
if (argv.version) {
showVersion();
}
var commandName = argv._[0];
// Demand command name
if (!commandName) {
console.error("No command specified");
opts.showHelp();
process.exit(127);
}
// Load command module
var command = commands.load(commandName);
// Demand valid command
if (!command) {
console.error("Unknown command: " + commandName);
opts.showHelp();
process.exit(127);
}
process.on("exit", function () {
ttys.stdin.end();
});
// Configure opts and run command (inside a domain to catch any error)
commands.run(command, opts, conf).then(ok, fail);
function ok () {
process.exit(0);
}
function fail (e) {
if (e.code === "EINTERRUPT") {
process.exit(127);
} else {
console.error("%s", e);
if (process.env.DEBUG) {
throw e;
}
process.exit(1);
}
}
} | javascript | function main (processArgv, conf) {
// CLI input
var opts = getOpts(processArgv);
var argv = opts.argv;
// Update notifier
if (!argv["no-notifier"]) {
checkUpdate();
}
// Convert options "--help" and "-h" into command "help"
if (argv.help) {
processArgv = transformHelpArgs(processArgv);
// Regenerate opts from newly forged process.argv
opts = getOpts(processArgv);
argv = opts.argv;
}
// "--version"
if (argv.version) {
showVersion();
}
var commandName = argv._[0];
// Demand command name
if (!commandName) {
console.error("No command specified");
opts.showHelp();
process.exit(127);
}
// Load command module
var command = commands.load(commandName);
// Demand valid command
if (!command) {
console.error("Unknown command: " + commandName);
opts.showHelp();
process.exit(127);
}
process.on("exit", function () {
ttys.stdin.end();
});
// Configure opts and run command (inside a domain to catch any error)
commands.run(command, opts, conf).then(ok, fail);
function ok () {
process.exit(0);
}
function fail (e) {
if (e.code === "EINTERRUPT") {
process.exit(127);
} else {
console.error("%s", e);
if (process.env.DEBUG) {
throw e;
}
process.exit(1);
}
}
} | [
"function",
"main",
"(",
"processArgv",
",",
"conf",
")",
"{",
"// CLI input",
"var",
"opts",
"=",
"getOpts",
"(",
"processArgv",
")",
";",
"var",
"argv",
"=",
"opts",
".",
"argv",
";",
"// Update notifier",
"if",
"(",
"!",
"argv",
"[",
"\"no-notifier\"",
"]",
")",
"{",
"checkUpdate",
"(",
")",
";",
"}",
"// Convert options \"--help\" and \"-h\" into command \"help\"",
"if",
"(",
"argv",
".",
"help",
")",
"{",
"processArgv",
"=",
"transformHelpArgs",
"(",
"processArgv",
")",
";",
"// Regenerate opts from newly forged process.argv",
"opts",
"=",
"getOpts",
"(",
"processArgv",
")",
";",
"argv",
"=",
"opts",
".",
"argv",
";",
"}",
"// \"--version\"",
"if",
"(",
"argv",
".",
"version",
")",
"{",
"showVersion",
"(",
")",
";",
"}",
"var",
"commandName",
"=",
"argv",
".",
"_",
"[",
"0",
"]",
";",
"// Demand command name",
"if",
"(",
"!",
"commandName",
")",
"{",
"console",
".",
"error",
"(",
"\"No command specified\"",
")",
";",
"opts",
".",
"showHelp",
"(",
")",
";",
"process",
".",
"exit",
"(",
"127",
")",
";",
"}",
"// Load command module",
"var",
"command",
"=",
"commands",
".",
"load",
"(",
"commandName",
")",
";",
"// Demand valid command",
"if",
"(",
"!",
"command",
")",
"{",
"console",
".",
"error",
"(",
"\"Unknown command: \"",
"+",
"commandName",
")",
";",
"opts",
".",
"showHelp",
"(",
")",
";",
"process",
".",
"exit",
"(",
"127",
")",
";",
"}",
"process",
".",
"on",
"(",
"\"exit\"",
",",
"function",
"(",
")",
"{",
"ttys",
".",
"stdin",
".",
"end",
"(",
")",
";",
"}",
")",
";",
"// Configure opts and run command (inside a domain to catch any error)",
"commands",
".",
"run",
"(",
"command",
",",
"opts",
",",
"conf",
")",
".",
"then",
"(",
"ok",
",",
"fail",
")",
";",
"function",
"ok",
"(",
")",
"{",
"process",
".",
"exit",
"(",
"0",
")",
";",
"}",
"function",
"fail",
"(",
"e",
")",
"{",
"if",
"(",
"e",
".",
"code",
"===",
"\"EINTERRUPT\"",
")",
"{",
"process",
".",
"exit",
"(",
"127",
")",
";",
"}",
"else",
"{",
"console",
".",
"error",
"(",
"\"%s\"",
",",
"e",
")",
";",
"if",
"(",
"process",
".",
"env",
".",
"DEBUG",
")",
"{",
"throw",
"e",
";",
"}",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}",
"}"
] | Main execution, after env has been checked | [
"Main",
"execution",
"after",
"env",
"has",
"been",
"checked"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/index.js#L71-L136 |
22,836 | naholyr/github-todos | lib/todos.js | rememberSkip | function rememberSkip (title) {
return readIgnoreFile().spread(function (ignores, skipFile) {
if (!_.contains(ignores, title)) {
return fs.writeFile(skipFile, ignores.concat([title]).join("\n"));
}
});
} | javascript | function rememberSkip (title) {
return readIgnoreFile().spread(function (ignores, skipFile) {
if (!_.contains(ignores, title)) {
return fs.writeFile(skipFile, ignores.concat([title]).join("\n"));
}
});
} | [
"function",
"rememberSkip",
"(",
"title",
")",
"{",
"return",
"readIgnoreFile",
"(",
")",
".",
"spread",
"(",
"function",
"(",
"ignores",
",",
"skipFile",
")",
"{",
"if",
"(",
"!",
"_",
".",
"contains",
"(",
"ignores",
",",
"title",
")",
")",
"{",
"return",
"fs",
".",
"writeFile",
"(",
"skipFile",
",",
"ignores",
".",
"concat",
"(",
"[",
"title",
"]",
")",
".",
"join",
"(",
"\"\\n\"",
")",
")",
";",
"}",
"}",
")",
";",
"}"
] | Add line to github-todos-ignore | [
"Add",
"line",
"to",
"github",
"-",
"todos",
"-",
"ignore"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/lib/todos.js#L92-L98 |
22,837 | naholyr/github-todos | doc/issue-service/sample.js | convertIssue | function convertIssue (issue) {
if (!issue) {
return null;
}
return {
"type": "issue",
"number": issue.number,
"url": issue.url,
"title": issue.title,
"labels": issue.labels
};
} | javascript | function convertIssue (issue) {
if (!issue) {
return null;
}
return {
"type": "issue",
"number": issue.number,
"url": issue.url,
"title": issue.title,
"labels": issue.labels
};
} | [
"function",
"convertIssue",
"(",
"issue",
")",
"{",
"if",
"(",
"!",
"issue",
")",
"{",
"return",
"null",
";",
"}",
"return",
"{",
"\"type\"",
":",
"\"issue\"",
",",
"\"number\"",
":",
"issue",
".",
"number",
",",
"\"url\"",
":",
"issue",
".",
"url",
",",
"\"title\"",
":",
"issue",
".",
"title",
",",
"\"labels\"",
":",
"issue",
".",
"labels",
"}",
";",
"}"
] | Convert issue to Github-Todos format | [
"Convert",
"issue",
"to",
"Github",
"-",
"Todos",
"format"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/doc/issue-service/sample.js#L41-L53 |
22,838 | naholyr/github-todos | doc/issue-service/sample.js | allIssues | function allIssues (client, repo) {
return client.getIssues(repo).then(function (issues) {
return issues.map(convertIssue);
});
} | javascript | function allIssues (client, repo) {
return client.getIssues(repo).then(function (issues) {
return issues.map(convertIssue);
});
} | [
"function",
"allIssues",
"(",
"client",
",",
"repo",
")",
"{",
"return",
"client",
".",
"getIssues",
"(",
"repo",
")",
".",
"then",
"(",
"function",
"(",
"issues",
")",
"{",
"return",
"issues",
".",
"map",
"(",
"convertIssue",
")",
";",
"}",
")",
";",
"}"
] | Assuming client.getIssues returns promise of issues | [
"Assuming",
"client",
".",
"getIssues",
"returns",
"promise",
"of",
"issues"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/doc/issue-service/sample.js#L77-L81 |
22,839 | naholyr/github-todos | doc/issue-service/sample.js | createIssue | function createIssue (client, repo, title, body, labels) {
return client.createIssue(repo, title, body, labels).then(convertIssue);
} | javascript | function createIssue (client, repo, title, body, labels) {
return client.createIssue(repo, title, body, labels).then(convertIssue);
} | [
"function",
"createIssue",
"(",
"client",
",",
"repo",
",",
"title",
",",
"body",
",",
"labels",
")",
"{",
"return",
"client",
".",
"createIssue",
"(",
"repo",
",",
"title",
",",
"body",
",",
"labels",
")",
".",
"then",
"(",
"convertIssue",
")",
";",
"}"
] | Assuming client.createIssue returns a promise of issue | [
"Assuming",
"client",
".",
"createIssue",
"returns",
"a",
"promise",
"of",
"issue"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/doc/issue-service/sample.js#L84-L86 |
22,840 | naholyr/github-todos | doc/issue-service/sample.js | commentIssue | function commentIssue (client, repo, number, comment) {
return client.createComment(repo, number, comment).then(convertComment);
} | javascript | function commentIssue (client, repo, number, comment) {
return client.createComment(repo, number, comment).then(convertComment);
} | [
"function",
"commentIssue",
"(",
"client",
",",
"repo",
",",
"number",
",",
"comment",
")",
"{",
"return",
"client",
".",
"createComment",
"(",
"repo",
",",
"number",
",",
"comment",
")",
".",
"then",
"(",
"convertComment",
")",
";",
"}"
] | Assuming client.createComment returns a promise of comment | [
"Assuming",
"client",
".",
"createComment",
"returns",
"a",
"promise",
"of",
"comment"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/doc/issue-service/sample.js#L89-L91 |
22,841 | naholyr/github-todos | doc/issue-service/sample.js | tagIssue | function tagIssue (client, repo, number, label) {
return client.addLabel(repo, number, label).then(convertIssue);
} | javascript | function tagIssue (client, repo, number, label) {
return client.addLabel(repo, number, label).then(convertIssue);
} | [
"function",
"tagIssue",
"(",
"client",
",",
"repo",
",",
"number",
",",
"label",
")",
"{",
"return",
"client",
".",
"addLabel",
"(",
"repo",
",",
"number",
",",
"label",
")",
".",
"then",
"(",
"convertIssue",
")",
";",
"}"
] | Assuming client.addLabel returns a promise of issue | [
"Assuming",
"client",
".",
"addLabel",
"returns",
"a",
"promise",
"of",
"issue"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/doc/issue-service/sample.js#L94-L96 |
22,842 | naholyr/github-todos | doc/issue-service/sample.js | connect | function connect (conf) {
// Instantiating API client, this is the one that will be passed to other methods
var client = new Client();
if (conf["my-host.token"]) {
// Authorize client
client.setToken(conf["my-host.token"]);
// Check token…
return checkToken(client)
.then(null, function () {
// …and create a new one if it failed
console.error("Existing token is invalid");
return createToken(client);
});
} else {
// No token found: create new one
return createToken(client);
}
} | javascript | function connect (conf) {
// Instantiating API client, this is the one that will be passed to other methods
var client = new Client();
if (conf["my-host.token"]) {
// Authorize client
client.setToken(conf["my-host.token"]);
// Check token…
return checkToken(client)
.then(null, function () {
// …and create a new one if it failed
console.error("Existing token is invalid");
return createToken(client);
});
} else {
// No token found: create new one
return createToken(client);
}
} | [
"function",
"connect",
"(",
"conf",
")",
"{",
"// Instantiating API client, this is the one that will be passed to other methods",
"var",
"client",
"=",
"new",
"Client",
"(",
")",
";",
"if",
"(",
"conf",
"[",
"\"my-host.token\"",
"]",
")",
"{",
"// Authorize client",
"client",
".",
"setToken",
"(",
"conf",
"[",
"\"my-host.token\"",
"]",
")",
";",
"// Check token…",
"return",
"checkToken",
"(",
"client",
")",
".",
"then",
"(",
"null",
",",
"function",
"(",
")",
"{",
"// …and create a new one if it failed",
"console",
".",
"error",
"(",
"\"Existing token is invalid\"",
")",
";",
"return",
"createToken",
"(",
"client",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// No token found: create new one",
"return",
"createToken",
"(",
"client",
")",
";",
"}",
"}"
] | Assuming client.setToken sets authorization token for next calls | [
"Assuming",
"client",
".",
"setToken",
"sets",
"authorization",
"token",
"for",
"next",
"calls"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/doc/issue-service/sample.js#L111-L129 |
22,843 | naholyr/github-todos | doc/issue-service/sample.js | createToken | function createToken (client) {
return ask([
{"type": "input", "message": "Username", "name": "user"},
{"type": "password", "message": "Password", "name": "password"}
]).then(function (answers) {
return client.createToken(answers.username, answers.password)
.then(saveToken)
.then(function (token) {
// Authorize client…
client.setToken(token);
// …and send it back to connect()
return client;
});
});
} | javascript | function createToken (client) {
return ask([
{"type": "input", "message": "Username", "name": "user"},
{"type": "password", "message": "Password", "name": "password"}
]).then(function (answers) {
return client.createToken(answers.username, answers.password)
.then(saveToken)
.then(function (token) {
// Authorize client…
client.setToken(token);
// …and send it back to connect()
return client;
});
});
} | [
"function",
"createToken",
"(",
"client",
")",
"{",
"return",
"ask",
"(",
"[",
"{",
"\"type\"",
":",
"\"input\"",
",",
"\"message\"",
":",
"\"Username\"",
",",
"\"name\"",
":",
"\"user\"",
"}",
",",
"{",
"\"type\"",
":",
"\"password\"",
",",
"\"message\"",
":",
"\"Password\"",
",",
"\"name\"",
":",
"\"password\"",
"}",
"]",
")",
".",
"then",
"(",
"function",
"(",
"answers",
")",
"{",
"return",
"client",
".",
"createToken",
"(",
"answers",
".",
"username",
",",
"answers",
".",
"password",
")",
".",
"then",
"(",
"saveToken",
")",
".",
"then",
"(",
"function",
"(",
"token",
")",
"{",
"// Authorize client…",
"client",
".",
"setToken",
"(",
"token",
")",
";",
"// …and send it back to connect()",
"return",
"client",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Assuming client.createToken returns a promise of string | [
"Assuming",
"client",
".",
"createToken",
"returns",
"a",
"promise",
"of",
"string"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/doc/issue-service/sample.js#L141-L155 |
22,844 | naholyr/github-todos | lib/issue-service/bitbucket.js | getFileUrl | function getFileUrl (repo, path, sha, line) {
return HOST + "/" + repo + "/src/" + sha + "/" + path + "#cl-" + line;
} | javascript | function getFileUrl (repo, path, sha, line) {
return HOST + "/" + repo + "/src/" + sha + "/" + path + "#cl-" + line;
} | [
"function",
"getFileUrl",
"(",
"repo",
",",
"path",
",",
"sha",
",",
"line",
")",
"{",
"return",
"HOST",
"+",
"\"/\"",
"+",
"repo",
"+",
"\"/src/\"",
"+",
"sha",
"+",
"\"/\"",
"+",
"path",
"+",
"\"#cl-\"",
"+",
"line",
";",
"}"
] | Synchronously generate direct link to file | [
"Synchronously",
"generate",
"direct",
"link",
"to",
"file"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/lib/issue-service/bitbucket.js#L130-L132 |
22,845 | naholyr/github-todos | lib/commands.js | load | function load (commandName) {
var command;
try {
command = require("./cli/" + commandName);
} catch (e) {
debug("Error loading command", commandName, e);
command = null;
}
return command;
} | javascript | function load (commandName) {
var command;
try {
command = require("./cli/" + commandName);
} catch (e) {
debug("Error loading command", commandName, e);
command = null;
}
return command;
} | [
"function",
"load",
"(",
"commandName",
")",
"{",
"var",
"command",
";",
"try",
"{",
"command",
"=",
"require",
"(",
"\"./cli/\"",
"+",
"commandName",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"debug",
"(",
"\"Error loading command\"",
",",
"commandName",
",",
"e",
")",
";",
"command",
"=",
"null",
";",
"}",
"return",
"command",
";",
"}"
] | Safe-require command module | [
"Safe",
"-",
"require",
"command",
"module"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/lib/commands.js#L14-L25 |
22,846 | naholyr/github-todos | lib/commands.js | run | function run (command, opts, conf) {
// Use "new Promise" to isolate process and catch any error
return new Promise(function (resolve, reject) {
if (command.config) {
opts = command.config(opts, conf);
}
Promise.cast(command.run(opts.argv, opts, conf)).then(resolve, reject);
});
} | javascript | function run (command, opts, conf) {
// Use "new Promise" to isolate process and catch any error
return new Promise(function (resolve, reject) {
if (command.config) {
opts = command.config(opts, conf);
}
Promise.cast(command.run(opts.argv, opts, conf)).then(resolve, reject);
});
} | [
"function",
"run",
"(",
"command",
",",
"opts",
",",
"conf",
")",
"{",
"// Use \"new Promise\" to isolate process and catch any error",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"if",
"(",
"command",
".",
"config",
")",
"{",
"opts",
"=",
"command",
".",
"config",
"(",
"opts",
",",
"conf",
")",
";",
"}",
"Promise",
".",
"cast",
"(",
"command",
".",
"run",
"(",
"opts",
".",
"argv",
",",
"opts",
",",
"conf",
")",
")",
".",
"then",
"(",
"resolve",
",",
"reject",
")",
";",
"}",
")",
";",
"}"
] | Safe-fun command | [
"Safe",
"-",
"fun",
"command"
] | 4f9b0ce4be718d911b82e414a0b7135c9bdfcade | https://github.com/naholyr/github-todos/blob/4f9b0ce4be718d911b82e414a0b7135c9bdfcade/lib/commands.js#L28-L37 |
22,847 | robophil/Product-Tour | js/product-tour.js | getActiveStepCount | function getActiveStepCount() {
var tourWrapper = jQuery('.cd-tour-wrapper'), //get the wrapper element
tourSteps = tourWrapper.children('li'); //get all its children with tag 'li'
var current_index = 0;
tourSteps.each(function (index, li) {
if (jQuery(li).hasClass('is-selected'))
current_index = index;
});
return current_index;
} | javascript | function getActiveStepCount() {
var tourWrapper = jQuery('.cd-tour-wrapper'), //get the wrapper element
tourSteps = tourWrapper.children('li'); //get all its children with tag 'li'
var current_index = 0;
tourSteps.each(function (index, li) {
if (jQuery(li).hasClass('is-selected'))
current_index = index;
});
return current_index;
} | [
"function",
"getActiveStepCount",
"(",
")",
"{",
"var",
"tourWrapper",
"=",
"jQuery",
"(",
"'.cd-tour-wrapper'",
")",
",",
"//get the wrapper element",
"tourSteps",
"=",
"tourWrapper",
".",
"children",
"(",
"'li'",
")",
";",
"//get all its children with tag 'li'",
"var",
"current_index",
"=",
"0",
";",
"tourSteps",
".",
"each",
"(",
"function",
"(",
"index",
",",
"li",
")",
"{",
"if",
"(",
"jQuery",
"(",
"li",
")",
".",
"hasClass",
"(",
"'is-selected'",
")",
")",
"current_index",
"=",
"index",
";",
"}",
")",
";",
"return",
"current_index",
";",
"}"
] | this returns the active step number
@return {number} | [
"this",
"returns",
"the",
"active",
"step",
"number"
] | 5613a945e01144cd553ecbe1be73fc1e81f85500 | https://github.com/robophil/Product-Tour/blob/5613a945e01144cd553ecbe1be73fc1e81f85500/js/product-tour.js#L296-L307 |
22,848 | dunn/libgen.js | lib/check.js | function(text, callback){
const md5 = (text.md5) ? text.md5.toLowerCase() : text.toLowerCase();
const mirrors = require('../available_mirrors.js');
let downloadMirrors = [];
let n = mirrors.length;
// create an array of mirrors that allow direct downloads
while (n--)
if (mirrors[n].canDownloadDirect)
downloadMirrors = downloadMirrors.concat(mirrors[n].baseUrl);
n = downloadMirrors.length;
let liveLink = false;
async.whilst(
function() { return n-- && !liveLink; },
function(callback) {
const options = {};
options.method = 'HEAD';
options.url = `${downloadMirrors[n]}/get.php?md5=`;
options.url += md5;
request(options, (err, response, body) => {
// don't stop because one mirror has problems
// if (err) return callback(err);
if (response.statusCode === 200)
liveLink = options.url;
return callback();
});
},
function(err) {
if (err)
return callback(err);
else if (liveLink)
return callback(null, liveLink);
else
return callback(new Error(`No working direct download links for ${md5}`));
});
} | javascript | function(text, callback){
const md5 = (text.md5) ? text.md5.toLowerCase() : text.toLowerCase();
const mirrors = require('../available_mirrors.js');
let downloadMirrors = [];
let n = mirrors.length;
// create an array of mirrors that allow direct downloads
while (n--)
if (mirrors[n].canDownloadDirect)
downloadMirrors = downloadMirrors.concat(mirrors[n].baseUrl);
n = downloadMirrors.length;
let liveLink = false;
async.whilst(
function() { return n-- && !liveLink; },
function(callback) {
const options = {};
options.method = 'HEAD';
options.url = `${downloadMirrors[n]}/get.php?md5=`;
options.url += md5;
request(options, (err, response, body) => {
// don't stop because one mirror has problems
// if (err) return callback(err);
if (response.statusCode === 200)
liveLink = options.url;
return callback();
});
},
function(err) {
if (err)
return callback(err);
else if (liveLink)
return callback(null, liveLink);
else
return callback(new Error(`No working direct download links for ${md5}`));
});
} | [
"function",
"(",
"text",
",",
"callback",
")",
"{",
"const",
"md5",
"=",
"(",
"text",
".",
"md5",
")",
"?",
"text",
".",
"md5",
".",
"toLowerCase",
"(",
")",
":",
"text",
".",
"toLowerCase",
"(",
")",
";",
"const",
"mirrors",
"=",
"require",
"(",
"'../available_mirrors.js'",
")",
";",
"let",
"downloadMirrors",
"=",
"[",
"]",
";",
"let",
"n",
"=",
"mirrors",
".",
"length",
";",
"// create an array of mirrors that allow direct downloads",
"while",
"(",
"n",
"--",
")",
"if",
"(",
"mirrors",
"[",
"n",
"]",
".",
"canDownloadDirect",
")",
"downloadMirrors",
"=",
"downloadMirrors",
".",
"concat",
"(",
"mirrors",
"[",
"n",
"]",
".",
"baseUrl",
")",
";",
"n",
"=",
"downloadMirrors",
".",
"length",
";",
"let",
"liveLink",
"=",
"false",
";",
"async",
".",
"whilst",
"(",
"function",
"(",
")",
"{",
"return",
"n",
"--",
"&&",
"!",
"liveLink",
";",
"}",
",",
"function",
"(",
"callback",
")",
"{",
"const",
"options",
"=",
"{",
"}",
";",
"options",
".",
"method",
"=",
"'HEAD'",
";",
"options",
".",
"url",
"=",
"`",
"${",
"downloadMirrors",
"[",
"n",
"]",
"}",
"`",
";",
"options",
".",
"url",
"+=",
"md5",
";",
"request",
"(",
"options",
",",
"(",
"err",
",",
"response",
",",
"body",
")",
"=>",
"{",
"// don't stop because one mirror has problems",
"// if (err) return callback(err);",
"if",
"(",
"response",
".",
"statusCode",
"===",
"200",
")",
"liveLink",
"=",
"options",
".",
"url",
";",
"return",
"callback",
"(",
")",
";",
"}",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"return",
"callback",
"(",
"err",
")",
";",
"else",
"if",
"(",
"liveLink",
")",
"return",
"callback",
"(",
"null",
",",
"liveLink",
")",
";",
"else",
"return",
"callback",
"(",
"new",
"Error",
"(",
"`",
"${",
"md5",
"}",
"`",
")",
")",
";",
"}",
")",
";",
"}"
] | text can be a json object or an MD5 string | [
"text",
"can",
"be",
"a",
"json",
"object",
"or",
"an",
"MD5",
"string"
] | 12bf14e7deef9e8a704c8500a9951b609e2168df | https://github.com/dunn/libgen.js/blob/12bf14e7deef9e8a704c8500a9951b609e2168df/lib/check.js#L17-L54 | |
22,849 | dunn/libgen.js | lib/clean.js | function(json, fields) {
if (((typeof json) === 'object') && !Array.isArray(json))
return hasFields(json,fields);
else if (Array.isArray(json)) {
var spliced = [];
var n = json.length;
while (n--)
if (hasFields(json[n],fields))
spliced.push(json[n]);
if (spliced.length)
return spliced;
else
return false;
}
else
return console.error(new Error('Bad data passed to clean.forFields()'));
} | javascript | function(json, fields) {
if (((typeof json) === 'object') && !Array.isArray(json))
return hasFields(json,fields);
else if (Array.isArray(json)) {
var spliced = [];
var n = json.length;
while (n--)
if (hasFields(json[n],fields))
spliced.push(json[n]);
if (spliced.length)
return spliced;
else
return false;
}
else
return console.error(new Error('Bad data passed to clean.forFields()'));
} | [
"function",
"(",
"json",
",",
"fields",
")",
"{",
"if",
"(",
"(",
"(",
"typeof",
"json",
")",
"===",
"'object'",
")",
"&&",
"!",
"Array",
".",
"isArray",
"(",
"json",
")",
")",
"return",
"hasFields",
"(",
"json",
",",
"fields",
")",
";",
"else",
"if",
"(",
"Array",
".",
"isArray",
"(",
"json",
")",
")",
"{",
"var",
"spliced",
"=",
"[",
"]",
";",
"var",
"n",
"=",
"json",
".",
"length",
";",
"while",
"(",
"n",
"--",
")",
"if",
"(",
"hasFields",
"(",
"json",
"[",
"n",
"]",
",",
"fields",
")",
")",
"spliced",
".",
"push",
"(",
"json",
"[",
"n",
"]",
")",
";",
"if",
"(",
"spliced",
".",
"length",
")",
"return",
"spliced",
";",
"else",
"return",
"false",
";",
"}",
"else",
"return",
"console",
".",
"error",
"(",
"new",
"Error",
"(",
"'Bad data passed to clean.forFields()'",
")",
")",
";",
"}"
] | removes texts that don't have the specified fields | [
"removes",
"texts",
"that",
"don",
"t",
"have",
"the",
"specified",
"fields"
] | 12bf14e7deef9e8a704c8500a9951b609e2168df | https://github.com/dunn/libgen.js/blob/12bf14e7deef9e8a704c8500a9951b609e2168df/lib/clean.js#L32-L49 | |
22,850 | dunn/libgen.js | lib/clean.js | function(array) {
let sorted = array.sort((a, b) => {
return a.id - b.id;
});
let i = sorted.length - 1;
while (i--)
if (sorted[i + 1].id === sorted[i].id)
sorted.splice(i,1);
return sorted;
} | javascript | function(array) {
let sorted = array.sort((a, b) => {
return a.id - b.id;
});
let i = sorted.length - 1;
while (i--)
if (sorted[i + 1].id === sorted[i].id)
sorted.splice(i,1);
return sorted;
} | [
"function",
"(",
"array",
")",
"{",
"let",
"sorted",
"=",
"array",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"return",
"a",
".",
"id",
"-",
"b",
".",
"id",
";",
"}",
")",
";",
"let",
"i",
"=",
"sorted",
".",
"length",
"-",
"1",
";",
"while",
"(",
"i",
"--",
")",
"if",
"(",
"sorted",
"[",
"i",
"+",
"1",
"]",
".",
"id",
"===",
"sorted",
"[",
"i",
"]",
".",
"id",
")",
"sorted",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"return",
"sorted",
";",
"}"
] | removes duplicate texts from an array of libgen json objects | [
"removes",
"duplicate",
"texts",
"from",
"an",
"array",
"of",
"libgen",
"json",
"objects"
] | 12bf14e7deef9e8a704c8500a9951b609e2168df | https://github.com/dunn/libgen.js/blob/12bf14e7deef9e8a704c8500a9951b609e2168df/lib/clean.js#L51-L61 | |
22,851 | anvaka/oflow | demo/pingpong/src/game.js | Game | function Game(scene) {
var isOver = false,
overCallbacks = [],
cachedPos = new Geometry.Point(),
ball = new Ball(scene),
gameOver = function (side) {
var i;
isOver = true;
for (i = 0; i < overCallbacks.length; ++i) {
overCallbacks[i](side);
}
};
this.leftHandle = new Handle(true, scene);
this.rightHandle = new Handle(false, scene);
this.ball = ball;
this.step = function () {
if (isOver) {
return;
}
ball.move();
var outSide = ball.isOut();
if (this.leftHandle.hit(ball)) {
cachedPos.x = settings.handleWidth;
cachedPos.y = ball.y;
ball.setPosition(cachedPos);
ball.vx = -ball.vx;
} else if (this.rightHandle.hit(ball)) {
cachedPos.x = this.rightHandle.x;
cachedPos.y = ball.y;
ball.setPosition(cachedPos);
ball.vx = -ball.vx;
} else if (outSide) {
gameOver(outSide);
}
scene.render(this.leftHandle, this.rightHandle, ball);
};
this.isOver = function () {
return isOver;
};
this.onOver = function (callback) {
if (typeof callback === 'function') {
overCallbacks.push(callback);
}
};
} | javascript | function Game(scene) {
var isOver = false,
overCallbacks = [],
cachedPos = new Geometry.Point(),
ball = new Ball(scene),
gameOver = function (side) {
var i;
isOver = true;
for (i = 0; i < overCallbacks.length; ++i) {
overCallbacks[i](side);
}
};
this.leftHandle = new Handle(true, scene);
this.rightHandle = new Handle(false, scene);
this.ball = ball;
this.step = function () {
if (isOver) {
return;
}
ball.move();
var outSide = ball.isOut();
if (this.leftHandle.hit(ball)) {
cachedPos.x = settings.handleWidth;
cachedPos.y = ball.y;
ball.setPosition(cachedPos);
ball.vx = -ball.vx;
} else if (this.rightHandle.hit(ball)) {
cachedPos.x = this.rightHandle.x;
cachedPos.y = ball.y;
ball.setPosition(cachedPos);
ball.vx = -ball.vx;
} else if (outSide) {
gameOver(outSide);
}
scene.render(this.leftHandle, this.rightHandle, ball);
};
this.isOver = function () {
return isOver;
};
this.onOver = function (callback) {
if (typeof callback === 'function') {
overCallbacks.push(callback);
}
};
} | [
"function",
"Game",
"(",
"scene",
")",
"{",
"var",
"isOver",
"=",
"false",
",",
"overCallbacks",
"=",
"[",
"]",
",",
"cachedPos",
"=",
"new",
"Geometry",
".",
"Point",
"(",
")",
",",
"ball",
"=",
"new",
"Ball",
"(",
"scene",
")",
",",
"gameOver",
"=",
"function",
"(",
"side",
")",
"{",
"var",
"i",
";",
"isOver",
"=",
"true",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"overCallbacks",
".",
"length",
";",
"++",
"i",
")",
"{",
"overCallbacks",
"[",
"i",
"]",
"(",
"side",
")",
";",
"}",
"}",
";",
"this",
".",
"leftHandle",
"=",
"new",
"Handle",
"(",
"true",
",",
"scene",
")",
";",
"this",
".",
"rightHandle",
"=",
"new",
"Handle",
"(",
"false",
",",
"scene",
")",
";",
"this",
".",
"ball",
"=",
"ball",
";",
"this",
".",
"step",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"isOver",
")",
"{",
"return",
";",
"}",
"ball",
".",
"move",
"(",
")",
";",
"var",
"outSide",
"=",
"ball",
".",
"isOut",
"(",
")",
";",
"if",
"(",
"this",
".",
"leftHandle",
".",
"hit",
"(",
"ball",
")",
")",
"{",
"cachedPos",
".",
"x",
"=",
"settings",
".",
"handleWidth",
";",
"cachedPos",
".",
"y",
"=",
"ball",
".",
"y",
";",
"ball",
".",
"setPosition",
"(",
"cachedPos",
")",
";",
"ball",
".",
"vx",
"=",
"-",
"ball",
".",
"vx",
";",
"}",
"else",
"if",
"(",
"this",
".",
"rightHandle",
".",
"hit",
"(",
"ball",
")",
")",
"{",
"cachedPos",
".",
"x",
"=",
"this",
".",
"rightHandle",
".",
"x",
";",
"cachedPos",
".",
"y",
"=",
"ball",
".",
"y",
";",
"ball",
".",
"setPosition",
"(",
"cachedPos",
")",
";",
"ball",
".",
"vx",
"=",
"-",
"ball",
".",
"vx",
";",
"}",
"else",
"if",
"(",
"outSide",
")",
"{",
"gameOver",
"(",
"outSide",
")",
";",
"}",
"scene",
".",
"render",
"(",
"this",
".",
"leftHandle",
",",
"this",
".",
"rightHandle",
",",
"ball",
")",
";",
"}",
";",
"this",
".",
"isOver",
"=",
"function",
"(",
")",
"{",
"return",
"isOver",
";",
"}",
";",
"this",
".",
"onOver",
"=",
"function",
"(",
"callback",
")",
"{",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"overCallbacks",
".",
"push",
"(",
"callback",
")",
";",
"}",
"}",
";",
"}"
] | Ping Pong game model | [
"Ping",
"Pong",
"game",
"model"
] | 6e81b16756eb55c6544261a26395c32a6d07374d | https://github.com/anvaka/oflow/blob/6e81b16756eb55c6544261a26395c32a6d07374d/demo/pingpong/src/game.js#L13-L61 |
22,852 | anvaka/oflow | demo/pingpong/src/scene.js | Scene | function Scene(container) {
var ctx = container.getContext('2d'),
cachedHeight = container.height,
cachedWidth = container.width,
getWidth = function () {
return cachedWidth;
},
getHeight = function () {
return cachedHeight;
},
renderHandle = function (color, handle) {
ctx.fillStyle = color;
ctx.fillRect(handle.x, handle.y, handle.width, handle.height);
},
clearBackground = function (color) {
ctx.fillStyle = color;
ctx.fillRect(0, 0, getWidth(), getHeight());
},
renderBall = function (color, ball) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(ball.x, ball.y, settings.ballradius, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke();
};
return {
width: function () {
return getWidth();
},
height: function () {
return getHeight();
},
render: function (leftHandle, rightHandle, ball) {
clearBackground('#000000');
renderHandle('#ccaa00', leftHandle);
renderHandle('#00aa00', rightHandle);
renderBall('#ffffff', ball);
}
};
} | javascript | function Scene(container) {
var ctx = container.getContext('2d'),
cachedHeight = container.height,
cachedWidth = container.width,
getWidth = function () {
return cachedWidth;
},
getHeight = function () {
return cachedHeight;
},
renderHandle = function (color, handle) {
ctx.fillStyle = color;
ctx.fillRect(handle.x, handle.y, handle.width, handle.height);
},
clearBackground = function (color) {
ctx.fillStyle = color;
ctx.fillRect(0, 0, getWidth(), getHeight());
},
renderBall = function (color, ball) {
ctx.beginPath();
ctx.fillStyle = color;
ctx.arc(ball.x, ball.y, settings.ballradius, 0, 2 * Math.PI, false);
ctx.fill();
ctx.stroke();
};
return {
width: function () {
return getWidth();
},
height: function () {
return getHeight();
},
render: function (leftHandle, rightHandle, ball) {
clearBackground('#000000');
renderHandle('#ccaa00', leftHandle);
renderHandle('#00aa00', rightHandle);
renderBall('#ffffff', ball);
}
};
} | [
"function",
"Scene",
"(",
"container",
")",
"{",
"var",
"ctx",
"=",
"container",
".",
"getContext",
"(",
"'2d'",
")",
",",
"cachedHeight",
"=",
"container",
".",
"height",
",",
"cachedWidth",
"=",
"container",
".",
"width",
",",
"getWidth",
"=",
"function",
"(",
")",
"{",
"return",
"cachedWidth",
";",
"}",
",",
"getHeight",
"=",
"function",
"(",
")",
"{",
"return",
"cachedHeight",
";",
"}",
",",
"renderHandle",
"=",
"function",
"(",
"color",
",",
"handle",
")",
"{",
"ctx",
".",
"fillStyle",
"=",
"color",
";",
"ctx",
".",
"fillRect",
"(",
"handle",
".",
"x",
",",
"handle",
".",
"y",
",",
"handle",
".",
"width",
",",
"handle",
".",
"height",
")",
";",
"}",
",",
"clearBackground",
"=",
"function",
"(",
"color",
")",
"{",
"ctx",
".",
"fillStyle",
"=",
"color",
";",
"ctx",
".",
"fillRect",
"(",
"0",
",",
"0",
",",
"getWidth",
"(",
")",
",",
"getHeight",
"(",
")",
")",
";",
"}",
",",
"renderBall",
"=",
"function",
"(",
"color",
",",
"ball",
")",
"{",
"ctx",
".",
"beginPath",
"(",
")",
";",
"ctx",
".",
"fillStyle",
"=",
"color",
";",
"ctx",
".",
"arc",
"(",
"ball",
".",
"x",
",",
"ball",
".",
"y",
",",
"settings",
".",
"ballradius",
",",
"0",
",",
"2",
"*",
"Math",
".",
"PI",
",",
"false",
")",
";",
"ctx",
".",
"fill",
"(",
")",
";",
"ctx",
".",
"stroke",
"(",
")",
";",
"}",
";",
"return",
"{",
"width",
":",
"function",
"(",
")",
"{",
"return",
"getWidth",
"(",
")",
";",
"}",
",",
"height",
":",
"function",
"(",
")",
"{",
"return",
"getHeight",
"(",
")",
";",
"}",
",",
"render",
":",
"function",
"(",
"leftHandle",
",",
"rightHandle",
",",
"ball",
")",
"{",
"clearBackground",
"(",
"'#000000'",
")",
";",
"renderHandle",
"(",
"'#ccaa00'",
",",
"leftHandle",
")",
";",
"renderHandle",
"(",
"'#00aa00'",
",",
"rightHandle",
")",
";",
"renderBall",
"(",
"'#ffffff'",
",",
"ball",
")",
";",
"}",
"}",
";",
"}"
] | Renders game to the canvas. | [
"Renders",
"game",
"to",
"the",
"canvas",
"."
] | 6e81b16756eb55c6544261a26395c32a6d07374d | https://github.com/anvaka/oflow/blob/6e81b16756eb55c6544261a26395c32a6d07374d/demo/pingpong/src/scene.js#L10-L50 |
22,853 | anvaka/oflow | demo/pingpong/src/eventLoop.js | EventLoop | function EventLoop() {
var renderCallbacks = [],
intervalId,
startInternal = function () {
intervalId = requestAnimationFrame(startInternal);
for (var i = 0, n = renderCallbacks.length; i < n; ++i) {
renderCallbacks[i]();
}
};
this.onRender = function (callback) {
if (typeof callback === 'function') {
renderCallbacks.push(callback);
}
};
this.start = function () {
startInternal();
};
this.stop = function () {
if (intervalId) {
cancelAnimationFrame(intervalId);
intervalId = null;
}
};
} | javascript | function EventLoop() {
var renderCallbacks = [],
intervalId,
startInternal = function () {
intervalId = requestAnimationFrame(startInternal);
for (var i = 0, n = renderCallbacks.length; i < n; ++i) {
renderCallbacks[i]();
}
};
this.onRender = function (callback) {
if (typeof callback === 'function') {
renderCallbacks.push(callback);
}
};
this.start = function () {
startInternal();
};
this.stop = function () {
if (intervalId) {
cancelAnimationFrame(intervalId);
intervalId = null;
}
};
} | [
"function",
"EventLoop",
"(",
")",
"{",
"var",
"renderCallbacks",
"=",
"[",
"]",
",",
"intervalId",
",",
"startInternal",
"=",
"function",
"(",
")",
"{",
"intervalId",
"=",
"requestAnimationFrame",
"(",
"startInternal",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"n",
"=",
"renderCallbacks",
".",
"length",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"renderCallbacks",
"[",
"i",
"]",
"(",
")",
";",
"}",
"}",
";",
"this",
".",
"onRender",
"=",
"function",
"(",
"callback",
")",
"{",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"renderCallbacks",
".",
"push",
"(",
"callback",
")",
";",
"}",
"}",
";",
"this",
".",
"start",
"=",
"function",
"(",
")",
"{",
"startInternal",
"(",
")",
";",
"}",
";",
"this",
".",
"stop",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"intervalId",
")",
"{",
"cancelAnimationFrame",
"(",
"intervalId",
")",
";",
"intervalId",
"=",
"null",
";",
"}",
"}",
";",
"}"
] | A simple event loop class, which fires onRender events on each animation frame | [
"A",
"simple",
"event",
"loop",
"class",
"which",
"fires",
"onRender",
"events",
"on",
"each",
"animation",
"frame"
] | 6e81b16756eb55c6544261a26395c32a6d07374d | https://github.com/anvaka/oflow/blob/6e81b16756eb55c6544261a26395c32a6d07374d/demo/pingpong/src/eventLoop.js#L8-L32 |
22,854 | anvaka/oflow | demo/pingpong/src/utils.js | whenReady | function whenReady() {
var pendingObjects = [].slice.call(arguments),
wait = pendingObjects.length,
resolvedCallback,
promise = {
run : function (callback) {
resolvedCallback = callback;
}
},
resolved = function () {
wait -= 1;
if (wait <= 0 && resolvedCallback) {
resolvedCallback();
}
},
i;
for (i = 0; i < pendingObjects.length; i++) {
if (typeof pendingObjects[i].onReady === 'function') {
pendingObjects[i].onReady(resolved);
} else {
window.setTimeout(resolved, 0);
}
}
if (pendingObjects.length === 0) {
window.setTimeout(resolved, 0);
}
return promise; // to Domenic, this is not a promise, I know :).
} | javascript | function whenReady() {
var pendingObjects = [].slice.call(arguments),
wait = pendingObjects.length,
resolvedCallback,
promise = {
run : function (callback) {
resolvedCallback = callback;
}
},
resolved = function () {
wait -= 1;
if (wait <= 0 && resolvedCallback) {
resolvedCallback();
}
},
i;
for (i = 0; i < pendingObjects.length; i++) {
if (typeof pendingObjects[i].onReady === 'function') {
pendingObjects[i].onReady(resolved);
} else {
window.setTimeout(resolved, 0);
}
}
if (pendingObjects.length === 0) {
window.setTimeout(resolved, 0);
}
return promise; // to Domenic, this is not a promise, I know :).
} | [
"function",
"whenReady",
"(",
")",
"{",
"var",
"pendingObjects",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
",",
"wait",
"=",
"pendingObjects",
".",
"length",
",",
"resolvedCallback",
",",
"promise",
"=",
"{",
"run",
":",
"function",
"(",
"callback",
")",
"{",
"resolvedCallback",
"=",
"callback",
";",
"}",
"}",
",",
"resolved",
"=",
"function",
"(",
")",
"{",
"wait",
"-=",
"1",
";",
"if",
"(",
"wait",
"<=",
"0",
"&&",
"resolvedCallback",
")",
"{",
"resolvedCallback",
"(",
")",
";",
"}",
"}",
",",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"pendingObjects",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"typeof",
"pendingObjects",
"[",
"i",
"]",
".",
"onReady",
"===",
"'function'",
")",
"{",
"pendingObjects",
"[",
"i",
"]",
".",
"onReady",
"(",
"resolved",
")",
";",
"}",
"else",
"{",
"window",
".",
"setTimeout",
"(",
"resolved",
",",
"0",
")",
";",
"}",
"}",
"if",
"(",
"pendingObjects",
".",
"length",
"===",
"0",
")",
"{",
"window",
".",
"setTimeout",
"(",
"resolved",
",",
"0",
")",
";",
"}",
"return",
"promise",
";",
"// to Domenic, this is not a promise, I know :).",
"}"
] | just a little helper method to wait for multiple objects
and fire event when all of them indicated they are ready | [
"just",
"a",
"little",
"helper",
"method",
"to",
"wait",
"for",
"multiple",
"objects",
"and",
"fire",
"event",
"when",
"all",
"of",
"them",
"indicated",
"they",
"are",
"ready"
] | 6e81b16756eb55c6544261a26395c32a6d07374d | https://github.com/anvaka/oflow/blob/6e81b16756eb55c6544261a26395c32a6d07374d/demo/pingpong/src/utils.js#L10-L39 |
22,855 | anvaka/oflow | demo/pingpong/src/handle.js | Handle | function Handle(isLeft, scene) {
this.height = settings.handleHeight;
this.width = settings.handleWidth;
this.x = isLeft ? 0 : scene.width() - this.width;
this.y = (scene.height() - this.height) / 2;
var offset = isLeft ? this.width : 0,
intersect = new Geometry.Intersect();
this.hit = function ballHitsHandle(ball) {
return intersect.run(this.x + offset, this.y, this.x + offset, this.y + this.height,
ball.x, ball.y, ball.x + ball.vx, ball.y + ball.vy);
};
this.move = function moveHandle(direction) {
var y = this.y - direction;
if (0 <= y && y <= scene.height() - this.height) {
this.y = y;
} else {
this.y = y < 0 ? 0 : scene.height() - this.height;
}
};
} | javascript | function Handle(isLeft, scene) {
this.height = settings.handleHeight;
this.width = settings.handleWidth;
this.x = isLeft ? 0 : scene.width() - this.width;
this.y = (scene.height() - this.height) / 2;
var offset = isLeft ? this.width : 0,
intersect = new Geometry.Intersect();
this.hit = function ballHitsHandle(ball) {
return intersect.run(this.x + offset, this.y, this.x + offset, this.y + this.height,
ball.x, ball.y, ball.x + ball.vx, ball.y + ball.vy);
};
this.move = function moveHandle(direction) {
var y = this.y - direction;
if (0 <= y && y <= scene.height() - this.height) {
this.y = y;
} else {
this.y = y < 0 ? 0 : scene.height() - this.height;
}
};
} | [
"function",
"Handle",
"(",
"isLeft",
",",
"scene",
")",
"{",
"this",
".",
"height",
"=",
"settings",
".",
"handleHeight",
";",
"this",
".",
"width",
"=",
"settings",
".",
"handleWidth",
";",
"this",
".",
"x",
"=",
"isLeft",
"?",
"0",
":",
"scene",
".",
"width",
"(",
")",
"-",
"this",
".",
"width",
";",
"this",
".",
"y",
"=",
"(",
"scene",
".",
"height",
"(",
")",
"-",
"this",
".",
"height",
")",
"/",
"2",
";",
"var",
"offset",
"=",
"isLeft",
"?",
"this",
".",
"width",
":",
"0",
",",
"intersect",
"=",
"new",
"Geometry",
".",
"Intersect",
"(",
")",
";",
"this",
".",
"hit",
"=",
"function",
"ballHitsHandle",
"(",
"ball",
")",
"{",
"return",
"intersect",
".",
"run",
"(",
"this",
".",
"x",
"+",
"offset",
",",
"this",
".",
"y",
",",
"this",
".",
"x",
"+",
"offset",
",",
"this",
".",
"y",
"+",
"this",
".",
"height",
",",
"ball",
".",
"x",
",",
"ball",
".",
"y",
",",
"ball",
".",
"x",
"+",
"ball",
".",
"vx",
",",
"ball",
".",
"y",
"+",
"ball",
".",
"vy",
")",
";",
"}",
";",
"this",
".",
"move",
"=",
"function",
"moveHandle",
"(",
"direction",
")",
"{",
"var",
"y",
"=",
"this",
".",
"y",
"-",
"direction",
";",
"if",
"(",
"0",
"<=",
"y",
"&&",
"y",
"<=",
"scene",
".",
"height",
"(",
")",
"-",
"this",
".",
"height",
")",
"{",
"this",
".",
"y",
"=",
"y",
";",
"}",
"else",
"{",
"this",
".",
"y",
"=",
"y",
"<",
"0",
"?",
"0",
":",
"scene",
".",
"height",
"(",
")",
"-",
"this",
".",
"height",
";",
"}",
"}",
";",
"}"
] | Represents a single ping pong handle either left or right | [
"Represents",
"a",
"single",
"ping",
"pong",
"handle",
"either",
"left",
"or",
"right"
] | 6e81b16756eb55c6544261a26395c32a6d07374d | https://github.com/anvaka/oflow/blob/6e81b16756eb55c6544261a26395c32a6d07374d/demo/pingpong/src/handle.js#L11-L33 |
22,856 | anvaka/oflow | demo/pingpong/src/ball.js | Ball | function Ball(scene) {
this.x = scene.width() / 2;
this.y = scene.height() / 2;
this.vx = 1;// + Math.random()* 2;
this.vy = 1;// + Math.random() * 2;
this.move = function () {
this.x += this.vx;
this.y += this.vy;
if (this.y < 0) {
this.y = 0;
this.vy = -this.vy;
} else if (this.y > scene.height()) {
this.y = scene.height();
this.vy = -this.vy;
}
};
this.setPosition = function (pos) {
this.x = pos.x;
this.y = pos.y;
};
this.isOut = function () {
if (this.x < 0) {
return 'left';
}
if (this.x > scene.width()) {
return 'right';
}
return false;
};
} | javascript | function Ball(scene) {
this.x = scene.width() / 2;
this.y = scene.height() / 2;
this.vx = 1;// + Math.random()* 2;
this.vy = 1;// + Math.random() * 2;
this.move = function () {
this.x += this.vx;
this.y += this.vy;
if (this.y < 0) {
this.y = 0;
this.vy = -this.vy;
} else if (this.y > scene.height()) {
this.y = scene.height();
this.vy = -this.vy;
}
};
this.setPosition = function (pos) {
this.x = pos.x;
this.y = pos.y;
};
this.isOut = function () {
if (this.x < 0) {
return 'left';
}
if (this.x > scene.width()) {
return 'right';
}
return false;
};
} | [
"function",
"Ball",
"(",
"scene",
")",
"{",
"this",
".",
"x",
"=",
"scene",
".",
"width",
"(",
")",
"/",
"2",
";",
"this",
".",
"y",
"=",
"scene",
".",
"height",
"(",
")",
"/",
"2",
";",
"this",
".",
"vx",
"=",
"1",
";",
"// + Math.random()* 2;",
"this",
".",
"vy",
"=",
"1",
";",
"// + Math.random() * 2;",
"this",
".",
"move",
"=",
"function",
"(",
")",
"{",
"this",
".",
"x",
"+=",
"this",
".",
"vx",
";",
"this",
".",
"y",
"+=",
"this",
".",
"vy",
";",
"if",
"(",
"this",
".",
"y",
"<",
"0",
")",
"{",
"this",
".",
"y",
"=",
"0",
";",
"this",
".",
"vy",
"=",
"-",
"this",
".",
"vy",
";",
"}",
"else",
"if",
"(",
"this",
".",
"y",
">",
"scene",
".",
"height",
"(",
")",
")",
"{",
"this",
".",
"y",
"=",
"scene",
".",
"height",
"(",
")",
";",
"this",
".",
"vy",
"=",
"-",
"this",
".",
"vy",
";",
"}",
"}",
";",
"this",
".",
"setPosition",
"=",
"function",
"(",
"pos",
")",
"{",
"this",
".",
"x",
"=",
"pos",
".",
"x",
";",
"this",
".",
"y",
"=",
"pos",
".",
"y",
";",
"}",
";",
"this",
".",
"isOut",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"x",
"<",
"0",
")",
"{",
"return",
"'left'",
";",
"}",
"if",
"(",
"this",
".",
"x",
">",
"scene",
".",
"width",
"(",
")",
")",
"{",
"return",
"'right'",
";",
"}",
"return",
"false",
";",
"}",
";",
"}"
] | Represents a ball object on the scene | [
"Represents",
"a",
"ball",
"object",
"on",
"the",
"scene"
] | 6e81b16756eb55c6544261a26395c32a6d07374d | https://github.com/anvaka/oflow/blob/6e81b16756eb55c6544261a26395c32a6d07374d/demo/pingpong/src/ball.js#L8-L38 |
22,857 | anvaka/oflow | demo/pingpong/src/controllers/webcamController.js | WebCamController | function WebCamController() {
var flow = new oflow.WebCamFlow(),
readyCallback,
waitReady = true;
return {
mount: function (handle) {
flow.onCalculated(function (direction) {
if (waitReady) {
readyCallback();
waitReady = false;
}
handle.move(-direction.v * 10);
});
flow.startCapture();
},
dismount: function () {
flow.stopCapture();
},
onReady: function (callback) {
readyCallback = callback;
},
step: function () {
}
};
} | javascript | function WebCamController() {
var flow = new oflow.WebCamFlow(),
readyCallback,
waitReady = true;
return {
mount: function (handle) {
flow.onCalculated(function (direction) {
if (waitReady) {
readyCallback();
waitReady = false;
}
handle.move(-direction.v * 10);
});
flow.startCapture();
},
dismount: function () {
flow.stopCapture();
},
onReady: function (callback) {
readyCallback = callback;
},
step: function () {
}
};
} | [
"function",
"WebCamController",
"(",
")",
"{",
"var",
"flow",
"=",
"new",
"oflow",
".",
"WebCamFlow",
"(",
")",
",",
"readyCallback",
",",
"waitReady",
"=",
"true",
";",
"return",
"{",
"mount",
":",
"function",
"(",
"handle",
")",
"{",
"flow",
".",
"onCalculated",
"(",
"function",
"(",
"direction",
")",
"{",
"if",
"(",
"waitReady",
")",
"{",
"readyCallback",
"(",
")",
";",
"waitReady",
"=",
"false",
";",
"}",
"handle",
".",
"move",
"(",
"-",
"direction",
".",
"v",
"*",
"10",
")",
";",
"}",
")",
";",
"flow",
".",
"startCapture",
"(",
")",
";",
"}",
",",
"dismount",
":",
"function",
"(",
")",
"{",
"flow",
".",
"stopCapture",
"(",
")",
";",
"}",
",",
"onReady",
":",
"function",
"(",
"callback",
")",
"{",
"readyCallback",
"=",
"callback",
";",
"}",
",",
"step",
":",
"function",
"(",
")",
"{",
"}",
"}",
";",
"}"
] | Controls a handle via optical flow detection from the webcam. | [
"Controls",
"a",
"handle",
"via",
"optical",
"flow",
"detection",
"from",
"the",
"webcam",
"."
] | 6e81b16756eb55c6544261a26395c32a6d07374d | https://github.com/anvaka/oflow/blob/6e81b16756eb55c6544261a26395c32a6d07374d/demo/pingpong/src/controllers/webcamController.js#L9-L34 |
22,858 | mikolalysenko/static-kdtree | bench/ubilabs.js | loadTree | function loadTree (data) {
// Just need to restore the `parent` parameter
self.root = data;
function restoreParent (root) {
if (root.left) {
root.left.parent = root;
restoreParent(root.left);
}
if (root.right) {
root.right.parent = root;
restoreParent(root.right);
}
}
restoreParent(self.root);
} | javascript | function loadTree (data) {
// Just need to restore the `parent` parameter
self.root = data;
function restoreParent (root) {
if (root.left) {
root.left.parent = root;
restoreParent(root.left);
}
if (root.right) {
root.right.parent = root;
restoreParent(root.right);
}
}
restoreParent(self.root);
} | [
"function",
"loadTree",
"(",
"data",
")",
"{",
"// Just need to restore the `parent` parameter",
"self",
".",
"root",
"=",
"data",
";",
"function",
"restoreParent",
"(",
"root",
")",
"{",
"if",
"(",
"root",
".",
"left",
")",
"{",
"root",
".",
"left",
".",
"parent",
"=",
"root",
";",
"restoreParent",
"(",
"root",
".",
"left",
")",
";",
"}",
"if",
"(",
"root",
".",
"right",
")",
"{",
"root",
".",
"right",
".",
"parent",
"=",
"root",
";",
"restoreParent",
"(",
"root",
".",
"right",
")",
";",
"}",
"}",
"restoreParent",
"(",
"self",
".",
"root",
")",
";",
"}"
] | Reloads a serialied tree | [
"Reloads",
"a",
"serialied",
"tree"
] | 9bbc8397ca81c5bf2233776310206ed779a83c2e | https://github.com/mikolalysenko/static-kdtree/blob/9bbc8397ca81c5bf2233776310206ed779a83c2e/bench/ubilabs.js#L51-L68 |
22,859 | dwmkerr/wait-port | lib/wait-port.js | tryConnect | function tryConnect(options, timeout) {
return new Promise((resolve, reject) => {
try {
const socket = createConnectionWithTimeout(options, timeout, (err) => {
if (err) {
if (err.code === 'ECONNREFUSED') {
// We successfully *tried* to connect, so resolve with false so
// that we try again.
debug('Socket not open: ECONNREFUSED');
socket.destroy();
return resolve(false);
} else if (err.code === 'ECONNTIMEOUT') {
// We've successfully *tried* to connect, but we're timing out
// establishing the connection. This is not ideal (either
// the port is open or it ain't).
debug('Socket not open: ECONNTIMEOUT');
socket.destroy();
return resolve(false);
} else if (err.code === 'ECONNRESET') {
// This can happen if the target server kills its connection before
// we can read from it, we can normally just try again.
debug('Socket not open: ECONNRESET');
socket.destroy();
return resolve(false);
}
// Trying to open the socket has resulted in an error we don't
// understand. Better give up.
debug(`Unexpected error trying to open socket: ${err}`);
socket.destroy();
return reject(err);
}
// Boom, we connected!
debug('Socket connected!');
// If we are not dealing with http, we're done.
if (options.protocol !== 'http') {
// Disconnect, stop the timer and resolve.
socket.destroy();
return resolve(true);
}
// TODO: we should only use the portion of the timeout for this interval which is still left to us.
// Now we've got to wait for a HTTP response.
checkHttp(socket, options, timeout, (err) => {
if (err) {
if (err.code === 'EREQTIMEOUT') {
debug('HTTP error: EREQTIMEOUT');
socket.destroy();
return resolve(false);
} else if (err.code === 'ERESPONSE') {
debug('HTTP error: ERESPONSE');
socket.destroy();
return resolve(false);
}
debug(`Unexpected error checking http response: ${err}`);
socket.destroy();
return reject(err);
}
socket.destroy();
return resolve(true);
});
});
} catch (err) {
// Trying to open the socket has resulted in an exception we don't
// understand. Better give up.
debug(`Unexpected exception trying to open socket: ${err}`);
return reject(err);
}
});
} | javascript | function tryConnect(options, timeout) {
return new Promise((resolve, reject) => {
try {
const socket = createConnectionWithTimeout(options, timeout, (err) => {
if (err) {
if (err.code === 'ECONNREFUSED') {
// We successfully *tried* to connect, so resolve with false so
// that we try again.
debug('Socket not open: ECONNREFUSED');
socket.destroy();
return resolve(false);
} else if (err.code === 'ECONNTIMEOUT') {
// We've successfully *tried* to connect, but we're timing out
// establishing the connection. This is not ideal (either
// the port is open or it ain't).
debug('Socket not open: ECONNTIMEOUT');
socket.destroy();
return resolve(false);
} else if (err.code === 'ECONNRESET') {
// This can happen if the target server kills its connection before
// we can read from it, we can normally just try again.
debug('Socket not open: ECONNRESET');
socket.destroy();
return resolve(false);
}
// Trying to open the socket has resulted in an error we don't
// understand. Better give up.
debug(`Unexpected error trying to open socket: ${err}`);
socket.destroy();
return reject(err);
}
// Boom, we connected!
debug('Socket connected!');
// If we are not dealing with http, we're done.
if (options.protocol !== 'http') {
// Disconnect, stop the timer and resolve.
socket.destroy();
return resolve(true);
}
// TODO: we should only use the portion of the timeout for this interval which is still left to us.
// Now we've got to wait for a HTTP response.
checkHttp(socket, options, timeout, (err) => {
if (err) {
if (err.code === 'EREQTIMEOUT') {
debug('HTTP error: EREQTIMEOUT');
socket.destroy();
return resolve(false);
} else if (err.code === 'ERESPONSE') {
debug('HTTP error: ERESPONSE');
socket.destroy();
return resolve(false);
}
debug(`Unexpected error checking http response: ${err}`);
socket.destroy();
return reject(err);
}
socket.destroy();
return resolve(true);
});
});
} catch (err) {
// Trying to open the socket has resulted in an exception we don't
// understand. Better give up.
debug(`Unexpected exception trying to open socket: ${err}`);
return reject(err);
}
});
} | [
"function",
"tryConnect",
"(",
"options",
",",
"timeout",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"try",
"{",
"const",
"socket",
"=",
"createConnectionWithTimeout",
"(",
"options",
",",
"timeout",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ECONNREFUSED'",
")",
"{",
"// We successfully *tried* to connect, so resolve with false so",
"// that we try again.",
"debug",
"(",
"'Socket not open: ECONNREFUSED'",
")",
";",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"resolve",
"(",
"false",
")",
";",
"}",
"else",
"if",
"(",
"err",
".",
"code",
"===",
"'ECONNTIMEOUT'",
")",
"{",
"// We've successfully *tried* to connect, but we're timing out",
"// establishing the connection. This is not ideal (either",
"// the port is open or it ain't).",
"debug",
"(",
"'Socket not open: ECONNTIMEOUT'",
")",
";",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"resolve",
"(",
"false",
")",
";",
"}",
"else",
"if",
"(",
"err",
".",
"code",
"===",
"'ECONNRESET'",
")",
"{",
"// This can happen if the target server kills its connection before",
"// we can read from it, we can normally just try again.",
"debug",
"(",
"'Socket not open: ECONNRESET'",
")",
";",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"resolve",
"(",
"false",
")",
";",
"}",
"// Trying to open the socket has resulted in an error we don't",
"// understand. Better give up.",
"debug",
"(",
"`",
"${",
"err",
"}",
"`",
")",
";",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"// Boom, we connected!",
"debug",
"(",
"'Socket connected!'",
")",
";",
"// If we are not dealing with http, we're done.",
"if",
"(",
"options",
".",
"protocol",
"!==",
"'http'",
")",
"{",
"// Disconnect, stop the timer and resolve.",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"resolve",
"(",
"true",
")",
";",
"}",
"// TODO: we should only use the portion of the timeout for this interval which is still left to us.",
"// Now we've got to wait for a HTTP response.",
"checkHttp",
"(",
"socket",
",",
"options",
",",
"timeout",
",",
"(",
"err",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'EREQTIMEOUT'",
")",
"{",
"debug",
"(",
"'HTTP error: EREQTIMEOUT'",
")",
";",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"resolve",
"(",
"false",
")",
";",
"}",
"else",
"if",
"(",
"err",
".",
"code",
"===",
"'ERESPONSE'",
")",
"{",
"debug",
"(",
"'HTTP error: ERESPONSE'",
")",
";",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"resolve",
"(",
"false",
")",
";",
"}",
"debug",
"(",
"`",
"${",
"err",
"}",
"`",
")",
";",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"socket",
".",
"destroy",
"(",
")",
";",
"return",
"resolve",
"(",
"true",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"// Trying to open the socket has resulted in an exception we don't",
"// understand. Better give up.",
"debug",
"(",
"`",
"${",
"err",
"}",
"`",
")",
";",
"return",
"reject",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"}"
] | This function attempts to open a connection, given a limited time window. This is the function which we will run repeatedly until we connect. | [
"This",
"function",
"attempts",
"to",
"open",
"a",
"connection",
"given",
"a",
"limited",
"time",
"window",
".",
"This",
"is",
"the",
"function",
"which",
"we",
"will",
"run",
"repeatedly",
"until",
"we",
"connect",
"."
] | e68862259ff1c0f095b057cd50dbab6911e49103 | https://github.com/dwmkerr/wait-port/blob/e68862259ff1c0f095b057cd50dbab6911e49103/lib/wait-port.js#L83-L156 |
22,860 | jacoborus/estilo | src/load-project.js | loadNterm | function loadNterm (project) {
const templatePath = path.resolve(project.path, 'estilo/addons/nvim-term.yml')
if (!fs.existsSync(templatePath)) {
project.nterm = false
} else {
project.nterm = yaml.safeLoad(fs.readFileSync(templatePath))
}
return project
} | javascript | function loadNterm (project) {
const templatePath = path.resolve(project.path, 'estilo/addons/nvim-term.yml')
if (!fs.existsSync(templatePath)) {
project.nterm = false
} else {
project.nterm = yaml.safeLoad(fs.readFileSync(templatePath))
}
return project
} | [
"function",
"loadNterm",
"(",
"project",
")",
"{",
"const",
"templatePath",
"=",
"path",
".",
"resolve",
"(",
"project",
".",
"path",
",",
"'estilo/addons/nvim-term.yml'",
")",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"templatePath",
")",
")",
"{",
"project",
".",
"nterm",
"=",
"false",
"}",
"else",
"{",
"project",
".",
"nterm",
"=",
"yaml",
".",
"safeLoad",
"(",
"fs",
".",
"readFileSync",
"(",
"templatePath",
")",
")",
"}",
"return",
"project",
"}"
] | load nvim term template | [
"load",
"nvim",
"term",
"template"
] | 8feea237b27826b9c84a8f0d862ae278dc9c312e | https://github.com/jacoborus/estilo/blob/8feea237b27826b9c84a8f0d862ae278dc9c312e/src/load-project.js#L131-L139 |
22,861 | mysticatea/eslint-plugin-es | lib/rules/no-unicode-codepoint-escapes.js | findAndReport | function findAndReport(text, node) {
for (const match of codePointEscapeSearchGenerator(text)) {
const start = match.index
const end = start + match[0].length
const range = [start + node.start, end + node.start]
context.report({
node,
loc: {
start: sourceCode.getLocFromIndex(range[0]),
end: sourceCode.getLocFromIndex(range[1]),
},
messageId: "forbidden",
fix(fixer) {
const codePointStr = text.slice(start + 3, end - 1)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
let codePoint = Number(`0x${codePointStr}`)
let replacement = null
if (codePoint <= 0xffff) {
// BMP code point
replacement = toHex(codePoint)
} else {
// Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000
const highSurrogate = (codePoint >> 10) + 0xd800
const lowSurrogate = (codePoint % 0x400) + 0xdc00
replacement = `${toHex(highSurrogate)}\\u${toHex(
lowSurrogate
)}`
}
return fixer.replaceTextRange(
[range[0] + 2, range[1]],
replacement
)
},
})
}
} | javascript | function findAndReport(text, node) {
for (const match of codePointEscapeSearchGenerator(text)) {
const start = match.index
const end = start + match[0].length
const range = [start + node.start, end + node.start]
context.report({
node,
loc: {
start: sourceCode.getLocFromIndex(range[0]),
end: sourceCode.getLocFromIndex(range[1]),
},
messageId: "forbidden",
fix(fixer) {
const codePointStr = text.slice(start + 3, end - 1)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
let codePoint = Number(`0x${codePointStr}`)
let replacement = null
if (codePoint <= 0xffff) {
// BMP code point
replacement = toHex(codePoint)
} else {
// Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000
const highSurrogate = (codePoint >> 10) + 0xd800
const lowSurrogate = (codePoint % 0x400) + 0xdc00
replacement = `${toHex(highSurrogate)}\\u${toHex(
lowSurrogate
)}`
}
return fixer.replaceTextRange(
[range[0] + 2, range[1]],
replacement
)
},
})
}
} | [
"function",
"findAndReport",
"(",
"text",
",",
"node",
")",
"{",
"for",
"(",
"const",
"match",
"of",
"codePointEscapeSearchGenerator",
"(",
"text",
")",
")",
"{",
"const",
"start",
"=",
"match",
".",
"index",
"const",
"end",
"=",
"start",
"+",
"match",
"[",
"0",
"]",
".",
"length",
"const",
"range",
"=",
"[",
"start",
"+",
"node",
".",
"start",
",",
"end",
"+",
"node",
".",
"start",
"]",
"context",
".",
"report",
"(",
"{",
"node",
",",
"loc",
":",
"{",
"start",
":",
"sourceCode",
".",
"getLocFromIndex",
"(",
"range",
"[",
"0",
"]",
")",
",",
"end",
":",
"sourceCode",
".",
"getLocFromIndex",
"(",
"range",
"[",
"1",
"]",
")",
",",
"}",
",",
"messageId",
":",
"\"forbidden\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"const",
"codePointStr",
"=",
"text",
".",
"slice",
"(",
"start",
"+",
"3",
",",
"end",
"-",
"1",
")",
"// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint",
"let",
"codePoint",
"=",
"Number",
"(",
"`",
"${",
"codePointStr",
"}",
"`",
")",
"let",
"replacement",
"=",
"null",
"if",
"(",
"codePoint",
"<=",
"0xffff",
")",
"{",
"// BMP code point",
"replacement",
"=",
"toHex",
"(",
"codePoint",
")",
"}",
"else",
"{",
"// Astral code point; split in surrogate halves",
"// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae",
"codePoint",
"-=",
"0x10000",
"const",
"highSurrogate",
"=",
"(",
"codePoint",
">>",
"10",
")",
"+",
"0xd800",
"const",
"lowSurrogate",
"=",
"(",
"codePoint",
"%",
"0x400",
")",
"+",
"0xdc00",
"replacement",
"=",
"`",
"${",
"toHex",
"(",
"highSurrogate",
")",
"}",
"\\\\",
"${",
"toHex",
"(",
"lowSurrogate",
")",
"}",
"`",
"}",
"return",
"fixer",
".",
"replaceTextRange",
"(",
"[",
"range",
"[",
"0",
"]",
"+",
"2",
",",
"range",
"[",
"1",
"]",
"]",
",",
"replacement",
")",
"}",
",",
"}",
")",
"}",
"}"
] | find code point escape, and report
@param {string} text text
@param {Node} node node
@returns {void} | [
"find",
"code",
"point",
"escape",
"and",
"report"
] | 5203ab2902f4ebd68b7089465a8785e122cebf87 | https://github.com/mysticatea/eslint-plugin-es/blob/5203ab2902f4ebd68b7089465a8785e122cebf87/lib/rules/no-unicode-codepoint-escapes.js#L46-L83 |
22,862 | uqee/sticky-cluster | example/index.js | function (callback) {
async.parallel(
[
// fake db 1
function (callback) { setTimeout(callback, 2000); },
// fake db 2
function (callback) { setTimeout(callback, 1000); }
],
callback
);
} | javascript | function (callback) {
async.parallel(
[
// fake db 1
function (callback) { setTimeout(callback, 2000); },
// fake db 2
function (callback) { setTimeout(callback, 1000); }
],
callback
);
} | [
"function",
"(",
"callback",
")",
"{",
"async",
".",
"parallel",
"(",
"[",
"// fake db 1",
"function",
"(",
"callback",
")",
"{",
"setTimeout",
"(",
"callback",
",",
"2000",
")",
";",
"}",
",",
"// fake db 2",
"function",
"(",
"callback",
")",
"{",
"setTimeout",
"(",
"callback",
",",
"1000",
")",
";",
"}",
"]",
",",
"callback",
")",
";",
"}"
] | connect to remote services | [
"connect",
"to",
"remote",
"services"
] | 4cc3a9066b2d666b0cc175d3b97f7e1eab2154e6 | https://github.com/uqee/sticky-cluster/blob/4cc3a9066b2d666b0cc175d3b97f7e1eab2154e6/example/index.js#L11-L22 | |
22,863 | uqee/sticky-cluster | example/index.js | function (services, callback) {
var http = require('http');
var app = require('express')();
var server = http.createServer(app);
// get remote services
//var fakedb1 = services[0];
//var fakedb2 = services[1];
// all express-related stuff goes here, e.g.
app.use(function (req, res) { res.end('Handled by PID = ' + process.pid); });
// all socket.io stuff goes here
//var io = require('socket.io')(server);
// don't do server.listen(...)!
// just pass the server instance to the final async's callback
callback(null, server);
} | javascript | function (services, callback) {
var http = require('http');
var app = require('express')();
var server = http.createServer(app);
// get remote services
//var fakedb1 = services[0];
//var fakedb2 = services[1];
// all express-related stuff goes here, e.g.
app.use(function (req, res) { res.end('Handled by PID = ' + process.pid); });
// all socket.io stuff goes here
//var io = require('socket.io')(server);
// don't do server.listen(...)!
// just pass the server instance to the final async's callback
callback(null, server);
} | [
"function",
"(",
"services",
",",
"callback",
")",
"{",
"var",
"http",
"=",
"require",
"(",
"'http'",
")",
";",
"var",
"app",
"=",
"require",
"(",
"'express'",
")",
"(",
")",
";",
"var",
"server",
"=",
"http",
".",
"createServer",
"(",
"app",
")",
";",
"// get remote services",
"//var fakedb1 = services[0];",
"//var fakedb2 = services[1];",
"// all express-related stuff goes here, e.g.",
"app",
".",
"use",
"(",
"function",
"(",
"req",
",",
"res",
")",
"{",
"res",
".",
"end",
"(",
"'Handled by PID = '",
"+",
"process",
".",
"pid",
")",
";",
"}",
")",
";",
"// all socket.io stuff goes here",
"//var io = require('socket.io')(server);",
"// don't do server.listen(...)!",
"// just pass the server instance to the final async's callback",
"callback",
"(",
"null",
",",
"server",
")",
";",
"}"
] | configure the worker | [
"configure",
"the",
"worker"
] | 4cc3a9066b2d666b0cc175d3b97f7e1eab2154e6 | https://github.com/uqee/sticky-cluster/blob/4cc3a9066b2d666b0cc175d3b97f7e1eab2154e6/example/index.js#L26-L44 | |
22,864 | mysticatea/eslint-plugin-es | lib/rules/no-template-literals.js | isStringLiteralCode | function isStringLiteralCode(s) {
return (
(s.startsWith("'") && s.endsWith("'")) ||
(s.startsWith('"') && s.endsWith('"'))
)
} | javascript | function isStringLiteralCode(s) {
return (
(s.startsWith("'") && s.endsWith("'")) ||
(s.startsWith('"') && s.endsWith('"'))
)
} | [
"function",
"isStringLiteralCode",
"(",
"s",
")",
"{",
"return",
"(",
"(",
"s",
".",
"startsWith",
"(",
"\"'\"",
")",
"&&",
"s",
".",
"endsWith",
"(",
"\"'\"",
")",
")",
"||",
"(",
"s",
".",
"startsWith",
"(",
"'\"'",
")",
"&&",
"s",
".",
"endsWith",
"(",
"'\"'",
")",
")",
")",
"}"
] | Checks whether it is string literal
@param {string} s string source code
@returns {boolean} true: is string literal source code | [
"Checks",
"whether",
"it",
"is",
"string",
"literal"
] | 5203ab2902f4ebd68b7089465a8785e122cebf87 | https://github.com/mysticatea/eslint-plugin-es/blob/5203ab2902f4ebd68b7089465a8785e122cebf87/lib/rules/no-template-literals.js#L12-L17 |
22,865 | mysticatea/eslint-plugin-es | lib/rules/no-template-literals.js | templateLiteralToStringConcat | function templateLiteralToStringConcat(node, sourceCode) {
const ss = []
node.quasis.forEach((q, i) => {
const value = q.value.cooked
if (value) {
ss.push(JSON.stringify(value))
}
if (i < node.expressions.length) {
const e = node.expressions[i]
const text = sourceCode.getText(e)
ss.push(text)
}
})
if (!ss.length || !isStringLiteralCode(ss[0])) {
ss.unshift(`""`)
}
return ss.join("+")
} | javascript | function templateLiteralToStringConcat(node, sourceCode) {
const ss = []
node.quasis.forEach((q, i) => {
const value = q.value.cooked
if (value) {
ss.push(JSON.stringify(value))
}
if (i < node.expressions.length) {
const e = node.expressions[i]
const text = sourceCode.getText(e)
ss.push(text)
}
})
if (!ss.length || !isStringLiteralCode(ss[0])) {
ss.unshift(`""`)
}
return ss.join("+")
} | [
"function",
"templateLiteralToStringConcat",
"(",
"node",
",",
"sourceCode",
")",
"{",
"const",
"ss",
"=",
"[",
"]",
"node",
".",
"quasis",
".",
"forEach",
"(",
"(",
"q",
",",
"i",
")",
"=>",
"{",
"const",
"value",
"=",
"q",
".",
"value",
".",
"cooked",
"if",
"(",
"value",
")",
"{",
"ss",
".",
"push",
"(",
"JSON",
".",
"stringify",
"(",
"value",
")",
")",
"}",
"if",
"(",
"i",
"<",
"node",
".",
"expressions",
".",
"length",
")",
"{",
"const",
"e",
"=",
"node",
".",
"expressions",
"[",
"i",
"]",
"const",
"text",
"=",
"sourceCode",
".",
"getText",
"(",
"e",
")",
"ss",
".",
"push",
"(",
"text",
")",
"}",
"}",
")",
"if",
"(",
"!",
"ss",
".",
"length",
"||",
"!",
"isStringLiteralCode",
"(",
"ss",
"[",
"0",
"]",
")",
")",
"{",
"ss",
".",
"unshift",
"(",
"`",
"`",
")",
"}",
"return",
"ss",
".",
"join",
"(",
"\"+\"",
")",
"}"
] | Transform template literal to string concatenation.
@param {ASTNode} node TemplateLiteral node.(not within TaggedTemplateExpression)
@param {SourceCode} sourceCode SourceCode
@returns {string} After transformation | [
"Transform",
"template",
"literal",
"to",
"string",
"concatenation",
"."
] | 5203ab2902f4ebd68b7089465a8785e122cebf87 | https://github.com/mysticatea/eslint-plugin-es/blob/5203ab2902f4ebd68b7089465a8785e122cebf87/lib/rules/no-template-literals.js#L25-L43 |
22,866 | mysticatea/eslint-plugin-es | lib/rules/no-arrow-functions.js | toFunctionExpression | function toFunctionExpression(node) {
const params = node.params
const paramText = params.length
? sourceCode.text.slice(
params[0].range[0],
params[params.length - 1].range[1]
)
: ""
const arrowToken = sourceCode.getTokenBefore(
node.body,
isArrowToken
)
const preText = sourceCode.text.slice(
arrowToken.range[1],
node.body.range[0]
)
const bodyText = sourceCode.text.slice(
arrowToken.range[1],
node.range[1]
)
if (node.body.type === "BlockStatement") {
return `function(${paramText})${bodyText}`
}
if (preText.includes("\n")) {
return `function(${paramText}){return(${bodyText})}`
}
return `function(${paramText}){return ${bodyText}}`
} | javascript | function toFunctionExpression(node) {
const params = node.params
const paramText = params.length
? sourceCode.text.slice(
params[0].range[0],
params[params.length - 1].range[1]
)
: ""
const arrowToken = sourceCode.getTokenBefore(
node.body,
isArrowToken
)
const preText = sourceCode.text.slice(
arrowToken.range[1],
node.body.range[0]
)
const bodyText = sourceCode.text.slice(
arrowToken.range[1],
node.range[1]
)
if (node.body.type === "BlockStatement") {
return `function(${paramText})${bodyText}`
}
if (preText.includes("\n")) {
return `function(${paramText}){return(${bodyText})}`
}
return `function(${paramText}){return ${bodyText}}`
} | [
"function",
"toFunctionExpression",
"(",
"node",
")",
"{",
"const",
"params",
"=",
"node",
".",
"params",
"const",
"paramText",
"=",
"params",
".",
"length",
"?",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"params",
"[",
"0",
"]",
".",
"range",
"[",
"0",
"]",
",",
"params",
"[",
"params",
".",
"length",
"-",
"1",
"]",
".",
"range",
"[",
"1",
"]",
")",
":",
"\"\"",
"const",
"arrowToken",
"=",
"sourceCode",
".",
"getTokenBefore",
"(",
"node",
".",
"body",
",",
"isArrowToken",
")",
"const",
"preText",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"arrowToken",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"body",
".",
"range",
"[",
"0",
"]",
")",
"const",
"bodyText",
"=",
"sourceCode",
".",
"text",
".",
"slice",
"(",
"arrowToken",
".",
"range",
"[",
"1",
"]",
",",
"node",
".",
"range",
"[",
"1",
"]",
")",
"if",
"(",
"node",
".",
"body",
".",
"type",
"===",
"\"BlockStatement\"",
")",
"{",
"return",
"`",
"${",
"paramText",
"}",
"${",
"bodyText",
"}",
"`",
"}",
"if",
"(",
"preText",
".",
"includes",
"(",
"\"\\n\"",
")",
")",
"{",
"return",
"`",
"${",
"paramText",
"}",
"${",
"bodyText",
"}",
"`",
"}",
"return",
"`",
"${",
"paramText",
"}",
"${",
"bodyText",
"}",
"`",
"}"
] | ArrowFunctionExpression to FunctionExpression
@param {Node} node ArrowFunctionExpression Node
@returns {string} function expression text | [
"ArrowFunctionExpression",
"to",
"FunctionExpression"
] | 5203ab2902f4ebd68b7089465a8785e122cebf87 | https://github.com/mysticatea/eslint-plugin-es/blob/5203ab2902f4ebd68b7089465a8785e122cebf87/lib/rules/no-arrow-functions.js#L32-L61 |
22,867 | mysticatea/eslint-plugin-es | lib/rules/no-arrow-functions.js | report | function report(node, hasThis, hasSuper) {
context.report({
node,
messageId: "forbidden",
fix(fixer) {
if (hasSuper) {
return undefined
}
const functionText = toFunctionExpression(node)
return fixer.replaceText(
node,
hasThis ? `${functionText}.bind(this)` : functionText
)
},
})
} | javascript | function report(node, hasThis, hasSuper) {
context.report({
node,
messageId: "forbidden",
fix(fixer) {
if (hasSuper) {
return undefined
}
const functionText = toFunctionExpression(node)
return fixer.replaceText(
node,
hasThis ? `${functionText}.bind(this)` : functionText
)
},
})
} | [
"function",
"report",
"(",
"node",
",",
"hasThis",
",",
"hasSuper",
")",
"{",
"context",
".",
"report",
"(",
"{",
"node",
",",
"messageId",
":",
"\"forbidden\"",
",",
"fix",
"(",
"fixer",
")",
"{",
"if",
"(",
"hasSuper",
")",
"{",
"return",
"undefined",
"}",
"const",
"functionText",
"=",
"toFunctionExpression",
"(",
"node",
")",
"return",
"fixer",
".",
"replaceText",
"(",
"node",
",",
"hasThis",
"?",
"`",
"${",
"functionText",
"}",
"`",
":",
"functionText",
")",
"}",
",",
"}",
")",
"}"
] | Report that ArrowFunctionExpression is being used
@param {Node} node ArrowFunctionExpression Node
@param {boolean} hasThis Whether `this` is referenced in` function` scope
@param {boolean} hasSuper Whether `super` is referenced in` function` scope
@returns {void} | [
"Report",
"that",
"ArrowFunctionExpression",
"is",
"being",
"used"
] | 5203ab2902f4ebd68b7089465a8785e122cebf87 | https://github.com/mysticatea/eslint-plugin-es/blob/5203ab2902f4ebd68b7089465a8785e122cebf87/lib/rules/no-arrow-functions.js#L70-L85 |
22,868 | words/dice-coefficient | index.js | diceCoefficient | function diceCoefficient(value, alternative) {
var val = String(value).toLowerCase()
var alt = String(alternative).toLowerCase()
var left = val.length === 1 ? [val] : bigrams(val)
var right = alt.length === 1 ? [alt] : bigrams(alt)
var leftLength = left.length
var rightLength = right.length
var index = -1
var intersections = 0
var leftPair
var rightPair
var offset
while (++index < leftLength) {
leftPair = left[index]
offset = -1
while (++offset < rightLength) {
rightPair = right[offset]
if (leftPair === rightPair) {
intersections++
/* Make sure this pair never matches again */
right[offset] = ''
break
}
}
}
return (2 * intersections) / (leftLength + rightLength)
} | javascript | function diceCoefficient(value, alternative) {
var val = String(value).toLowerCase()
var alt = String(alternative).toLowerCase()
var left = val.length === 1 ? [val] : bigrams(val)
var right = alt.length === 1 ? [alt] : bigrams(alt)
var leftLength = left.length
var rightLength = right.length
var index = -1
var intersections = 0
var leftPair
var rightPair
var offset
while (++index < leftLength) {
leftPair = left[index]
offset = -1
while (++offset < rightLength) {
rightPair = right[offset]
if (leftPair === rightPair) {
intersections++
/* Make sure this pair never matches again */
right[offset] = ''
break
}
}
}
return (2 * intersections) / (leftLength + rightLength)
} | [
"function",
"diceCoefficient",
"(",
"value",
",",
"alternative",
")",
"{",
"var",
"val",
"=",
"String",
"(",
"value",
")",
".",
"toLowerCase",
"(",
")",
"var",
"alt",
"=",
"String",
"(",
"alternative",
")",
".",
"toLowerCase",
"(",
")",
"var",
"left",
"=",
"val",
".",
"length",
"===",
"1",
"?",
"[",
"val",
"]",
":",
"bigrams",
"(",
"val",
")",
"var",
"right",
"=",
"alt",
".",
"length",
"===",
"1",
"?",
"[",
"alt",
"]",
":",
"bigrams",
"(",
"alt",
")",
"var",
"leftLength",
"=",
"left",
".",
"length",
"var",
"rightLength",
"=",
"right",
".",
"length",
"var",
"index",
"=",
"-",
"1",
"var",
"intersections",
"=",
"0",
"var",
"leftPair",
"var",
"rightPair",
"var",
"offset",
"while",
"(",
"++",
"index",
"<",
"leftLength",
")",
"{",
"leftPair",
"=",
"left",
"[",
"index",
"]",
"offset",
"=",
"-",
"1",
"while",
"(",
"++",
"offset",
"<",
"rightLength",
")",
"{",
"rightPair",
"=",
"right",
"[",
"offset",
"]",
"if",
"(",
"leftPair",
"===",
"rightPair",
")",
"{",
"intersections",
"++",
"/* Make sure this pair never matches again */",
"right",
"[",
"offset",
"]",
"=",
"''",
"break",
"}",
"}",
"}",
"return",
"(",
"2",
"*",
"intersections",
")",
"/",
"(",
"leftLength",
"+",
"rightLength",
")",
"}"
] | Get the edit-distance according to Dice between two values. | [
"Get",
"the",
"edit",
"-",
"distance",
"according",
"to",
"Dice",
"between",
"two",
"values",
"."
] | 8eac06e9af5715e7ae2b07fdc9a5833bfb08485e | https://github.com/words/dice-coefficient/blob/8eac06e9af5715e7ae2b07fdc9a5833bfb08485e/index.js#L8-L39 |
22,869 | smoketurner/serverless-vpc-plugin | src/vpc.js | buildVpc | function buildVpc(cidrBlock = '10.0.0.0/16', { name = 'VPC' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::VPC',
Properties: {
CidrBlock: cidrBlock,
EnableDnsSupport: true,
EnableDnsHostnames: true,
InstanceTenancy: 'default',
Tags: [
{
Key: 'Name',
Value: {
Ref: 'AWS::StackName',
},
},
],
},
},
};
} | javascript | function buildVpc(cidrBlock = '10.0.0.0/16', { name = 'VPC' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::VPC',
Properties: {
CidrBlock: cidrBlock,
EnableDnsSupport: true,
EnableDnsHostnames: true,
InstanceTenancy: 'default',
Tags: [
{
Key: 'Name',
Value: {
Ref: 'AWS::StackName',
},
},
],
},
},
};
} | [
"function",
"buildVpc",
"(",
"cidrBlock",
"=",
"'10.0.0.0/16'",
",",
"{",
"name",
"=",
"'VPC'",
"}",
"=",
"{",
"}",
")",
"{",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::VPC'",
",",
"Properties",
":",
"{",
"CidrBlock",
":",
"cidrBlock",
",",
"EnableDnsSupport",
":",
"true",
",",
"EnableDnsHostnames",
":",
"true",
",",
"InstanceTenancy",
":",
"'default'",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a VPC
@param {String} cidrBlock
@param {Object} params
@return {Object} | [
"Build",
"a",
"VPC"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/vpc.js#L8-L28 |
22,870 | smoketurner/serverless-vpc-plugin | src/vpc.js | buildSubnet | function buildSubnet(name, position, zone, cidrBlock) {
const cfName = `${name}Subnet${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::Subnet',
Properties: {
AvailabilityZone: zone,
CidrBlock: cidrBlock,
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
name.toLowerCase(),
zone,
],
],
},
},
],
VpcId: {
Ref: 'VPC',
},
},
},
};
} | javascript | function buildSubnet(name, position, zone, cidrBlock) {
const cfName = `${name}Subnet${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::Subnet',
Properties: {
AvailabilityZone: zone,
CidrBlock: cidrBlock,
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
name.toLowerCase(),
zone,
],
],
},
},
],
VpcId: {
Ref: 'VPC',
},
},
},
};
} | [
"function",
"buildSubnet",
"(",
"name",
",",
"position",
",",
"zone",
",",
"cidrBlock",
")",
"{",
"const",
"cfName",
"=",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
";",
"return",
"{",
"[",
"cfName",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::Subnet'",
",",
"Properties",
":",
"{",
"AvailabilityZone",
":",
"zone",
",",
"CidrBlock",
":",
"cidrBlock",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"'-'",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"name",
".",
"toLowerCase",
"(",
")",
",",
"zone",
",",
"]",
",",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"VpcId",
":",
"{",
"Ref",
":",
"'VPC'",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Create a subnet
@param {String} name Name of subnet
@param {Number} position Subnet position
@param {String} zone Availability zone
@param {String} cidrBlock Subnet CIDR block
@return {Object} | [
"Create",
"a",
"subnet"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/vpc.js#L85-L116 |
22,871 | smoketurner/serverless-vpc-plugin | src/vpc.js | buildRouteTable | function buildRouteTable(name, position, zone) {
const cfName = `${name}RouteTable${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::RouteTable',
Properties: {
VpcId: {
Ref: 'VPC',
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
name.toLowerCase(),
zone,
],
],
},
},
],
},
},
};
} | javascript | function buildRouteTable(name, position, zone) {
const cfName = `${name}RouteTable${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::RouteTable',
Properties: {
VpcId: {
Ref: 'VPC',
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
name.toLowerCase(),
zone,
],
],
},
},
],
},
},
};
} | [
"function",
"buildRouteTable",
"(",
"name",
",",
"position",
",",
"zone",
")",
"{",
"const",
"cfName",
"=",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
";",
"return",
"{",
"[",
"cfName",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::RouteTable'",
",",
"Properties",
":",
"{",
"VpcId",
":",
"{",
"Ref",
":",
"'VPC'",
",",
"}",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"'-'",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"name",
".",
"toLowerCase",
"(",
")",
",",
"zone",
",",
"]",
",",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a RouteTable in a given AZ
@param {String} name
@param {Number} position
@param {String} zone
@return {Object} | [
"Build",
"a",
"RouteTable",
"in",
"a",
"given",
"AZ"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/vpc.js#L126-L155 |
22,872 | smoketurner/serverless-vpc-plugin | src/vpc.js | buildRouteTableAssociation | function buildRouteTableAssociation(name, position) {
const cfName = `${name}RouteTableAssociation${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::SubnetRouteTableAssociation',
Properties: {
RouteTableId: {
Ref: `${name}RouteTable${position}`,
},
SubnetId: {
Ref: `${name}Subnet${position}`,
},
},
},
};
} | javascript | function buildRouteTableAssociation(name, position) {
const cfName = `${name}RouteTableAssociation${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::SubnetRouteTableAssociation',
Properties: {
RouteTableId: {
Ref: `${name}RouteTable${position}`,
},
SubnetId: {
Ref: `${name}Subnet${position}`,
},
},
},
};
} | [
"function",
"buildRouteTableAssociation",
"(",
"name",
",",
"position",
")",
"{",
"const",
"cfName",
"=",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
";",
"return",
"{",
"[",
"cfName",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::SubnetRouteTableAssociation'",
",",
"Properties",
":",
"{",
"RouteTableId",
":",
"{",
"Ref",
":",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
",",
"}",
",",
"SubnetId",
":",
"{",
"Ref",
":",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a RouteTableAssociation
@param {String} name
@param {Number} position
@return {Object} | [
"Build",
"a",
"RouteTableAssociation"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/vpc.js#L164-L179 |
22,873 | smoketurner/serverless-vpc-plugin | src/vpc.js | buildRoute | function buildRoute(
name,
position,
{ NatGatewayId = null, GatewayId = null, InstanceId = null } = {},
) {
const route = {
Type: 'AWS::EC2::Route',
Properties: {
DestinationCidrBlock: '0.0.0.0/0',
RouteTableId: {
Ref: `${name}RouteTable${position}`,
},
},
};
if (NatGatewayId) {
route.Properties.NatGatewayId = {
Ref: NatGatewayId,
};
} else if (GatewayId) {
route.Properties.GatewayId = {
Ref: GatewayId,
};
} else if (InstanceId) {
route.Properties.InstanceId = {
Ref: InstanceId,
};
} else {
throw new Error(
'Unable to create route: either NatGatewayId, GatewayId or InstanceId must be provided',
);
}
const cfName = `${name}Route${position}`;
return {
[cfName]: route,
};
} | javascript | function buildRoute(
name,
position,
{ NatGatewayId = null, GatewayId = null, InstanceId = null } = {},
) {
const route = {
Type: 'AWS::EC2::Route',
Properties: {
DestinationCidrBlock: '0.0.0.0/0',
RouteTableId: {
Ref: `${name}RouteTable${position}`,
},
},
};
if (NatGatewayId) {
route.Properties.NatGatewayId = {
Ref: NatGatewayId,
};
} else if (GatewayId) {
route.Properties.GatewayId = {
Ref: GatewayId,
};
} else if (InstanceId) {
route.Properties.InstanceId = {
Ref: InstanceId,
};
} else {
throw new Error(
'Unable to create route: either NatGatewayId, GatewayId or InstanceId must be provided',
);
}
const cfName = `${name}Route${position}`;
return {
[cfName]: route,
};
} | [
"function",
"buildRoute",
"(",
"name",
",",
"position",
",",
"{",
"NatGatewayId",
"=",
"null",
",",
"GatewayId",
"=",
"null",
",",
"InstanceId",
"=",
"null",
"}",
"=",
"{",
"}",
",",
")",
"{",
"const",
"route",
"=",
"{",
"Type",
":",
"'AWS::EC2::Route'",
",",
"Properties",
":",
"{",
"DestinationCidrBlock",
":",
"'0.0.0.0/0'",
",",
"RouteTableId",
":",
"{",
"Ref",
":",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
",",
"}",
",",
"}",
",",
"}",
";",
"if",
"(",
"NatGatewayId",
")",
"{",
"route",
".",
"Properties",
".",
"NatGatewayId",
"=",
"{",
"Ref",
":",
"NatGatewayId",
",",
"}",
";",
"}",
"else",
"if",
"(",
"GatewayId",
")",
"{",
"route",
".",
"Properties",
".",
"GatewayId",
"=",
"{",
"Ref",
":",
"GatewayId",
",",
"}",
";",
"}",
"else",
"if",
"(",
"InstanceId",
")",
"{",
"route",
".",
"Properties",
".",
"InstanceId",
"=",
"{",
"Ref",
":",
"InstanceId",
",",
"}",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"'Unable to create route: either NatGatewayId, GatewayId or InstanceId must be provided'",
",",
")",
";",
"}",
"const",
"cfName",
"=",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
";",
"return",
"{",
"[",
"cfName",
"]",
":",
"route",
",",
"}",
";",
"}"
] | Build a Route for a NatGateway or InternetGateway
@param {String} name
@param {Number} position
@param {Object} params
@return {Object} | [
"Build",
"a",
"Route",
"for",
"a",
"NatGateway",
"or",
"InternetGateway"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/vpc.js#L189-L226 |
22,874 | smoketurner/serverless-vpc-plugin | src/vpc.js | buildLambdaSecurityGroup | function buildLambdaSecurityGroup({ name = 'LambdaExecutionSecurityGroup' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::SecurityGroup',
Properties: {
GroupDescription: 'Lambda Execution Group',
VpcId: {
Ref: 'VPC',
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'lambda-exec',
],
],
},
},
],
},
},
};
} | javascript | function buildLambdaSecurityGroup({ name = 'LambdaExecutionSecurityGroup' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::SecurityGroup',
Properties: {
GroupDescription: 'Lambda Execution Group',
VpcId: {
Ref: 'VPC',
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'lambda-exec',
],
],
},
},
],
},
},
};
} | [
"function",
"buildLambdaSecurityGroup",
"(",
"{",
"name",
"=",
"'LambdaExecutionSecurityGroup'",
"}",
"=",
"{",
"}",
")",
"{",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::SecurityGroup'",
",",
"Properties",
":",
"{",
"GroupDescription",
":",
"'Lambda Execution Group'",
",",
"VpcId",
":",
"{",
"Ref",
":",
"'VPC'",
",",
"}",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"'-'",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"'lambda-exec'",
",",
"]",
",",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a SecurityGroup to be used by Lambda's when they execute.
@param {Object} params
@return {Object} | [
"Build",
"a",
"SecurityGroup",
"to",
"be",
"used",
"by",
"Lambda",
"s",
"when",
"they",
"execute",
"."
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/vpc.js#L234-L262 |
22,875 | smoketurner/serverless-vpc-plugin | src/bastion.js | getPublicIp | function getPublicIp() {
return new Promise((resolve, reject) => {
const options = {
host: 'api.ipify.org',
port: 80,
path: '/',
};
http
.get(options, res => {
res.setEncoding('utf8');
let body = '';
res.on('data', chunk => {
body += chunk;
});
res.on('end', () => {
resolve(body);
});
})
.on('error', err => {
reject(err);
});
});
} | javascript | function getPublicIp() {
return new Promise((resolve, reject) => {
const options = {
host: 'api.ipify.org',
port: 80,
path: '/',
};
http
.get(options, res => {
res.setEncoding('utf8');
let body = '';
res.on('data', chunk => {
body += chunk;
});
res.on('end', () => {
resolve(body);
});
})
.on('error', err => {
reject(err);
});
});
} | [
"function",
"getPublicIp",
"(",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"options",
"=",
"{",
"host",
":",
"'api.ipify.org'",
",",
"port",
":",
"80",
",",
"path",
":",
"'/'",
",",
"}",
";",
"http",
".",
"get",
"(",
"options",
",",
"res",
"=>",
"{",
"res",
".",
"setEncoding",
"(",
"'utf8'",
")",
";",
"let",
"body",
"=",
"''",
";",
"res",
".",
"on",
"(",
"'data'",
",",
"chunk",
"=>",
"{",
"body",
"+=",
"chunk",
";",
"}",
")",
";",
"res",
".",
"on",
"(",
"'end'",
",",
"(",
")",
"=>",
"{",
"resolve",
"(",
"body",
")",
";",
"}",
")",
";",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"err",
"=>",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Return the public IP
@return {Promise} | [
"Return",
"the",
"public",
"IP"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/bastion.js#L10-L34 |
22,876 | smoketurner/serverless-vpc-plugin | src/bastion.js | buildBastionIamRole | function buildBastionIamRole({ name = 'BastionIamRole' } = {}) {
return {
[name]: {
Type: 'AWS::IAM::Role',
Properties: {
AssumeRolePolicyDocument: {
Statement: [
{
Effect: 'Allow',
Principal: {
Service: 'ec2.amazonaws.com',
},
Action: 'sts:AssumeRole',
},
],
},
Policies: [
{
PolicyName: 'AllowEIPAssociation',
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: 'ec2:AssociateAddress',
Resource: '*',
Effect: 'Allow',
},
],
},
},
],
ManagedPolicyArns: ['arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'],
},
},
};
} | javascript | function buildBastionIamRole({ name = 'BastionIamRole' } = {}) {
return {
[name]: {
Type: 'AWS::IAM::Role',
Properties: {
AssumeRolePolicyDocument: {
Statement: [
{
Effect: 'Allow',
Principal: {
Service: 'ec2.amazonaws.com',
},
Action: 'sts:AssumeRole',
},
],
},
Policies: [
{
PolicyName: 'AllowEIPAssociation',
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: 'ec2:AssociateAddress',
Resource: '*',
Effect: 'Allow',
},
],
},
},
],
ManagedPolicyArns: ['arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'],
},
},
};
} | [
"function",
"buildBastionIamRole",
"(",
"{",
"name",
"=",
"'BastionIamRole'",
"}",
"=",
"{",
"}",
")",
"{",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::IAM::Role'",
",",
"Properties",
":",
"{",
"AssumeRolePolicyDocument",
":",
"{",
"Statement",
":",
"[",
"{",
"Effect",
":",
"'Allow'",
",",
"Principal",
":",
"{",
"Service",
":",
"'ec2.amazonaws.com'",
",",
"}",
",",
"Action",
":",
"'sts:AssumeRole'",
",",
"}",
",",
"]",
",",
"}",
",",
"Policies",
":",
"[",
"{",
"PolicyName",
":",
"'AllowEIPAssociation'",
",",
"PolicyDocument",
":",
"{",
"Version",
":",
"'2012-10-17'",
",",
"Statement",
":",
"[",
"{",
"Action",
":",
"'ec2:AssociateAddress'",
",",
"Resource",
":",
"'*'",
",",
"Effect",
":",
"'Allow'",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"ManagedPolicyArns",
":",
"[",
"'arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build an IAM role for the bastion host
@param {Object} params
@return {Object} | [
"Build",
"an",
"IAM",
"role",
"for",
"the",
"bastion",
"host"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/bastion.js#L58-L93 |
22,877 | smoketurner/serverless-vpc-plugin | src/bastion.js | buildBastionLaunchConfiguration | function buildBastionLaunchConfiguration(
keyPairName,
{ name = 'BastionLaunchConfiguration' } = {},
) {
return {
[name]: {
Type: 'AWS::AutoScaling::LaunchConfiguration',
Properties: {
AssociatePublicIpAddress: true,
BlockDeviceMappings: [
{
DeviceName: '/dev/xvda',
Ebs: {
VolumeSize: 10,
VolumeType: 'gp2',
DeleteOnTermination: true,
},
},
],
KeyName: keyPairName,
ImageId: {
Ref: 'LatestAmiId',
},
InstanceMonitoring: false,
IamInstanceProfile: {
Ref: 'BastionInstanceProfile',
},
InstanceType: 't2.micro',
SecurityGroups: [
{
Ref: 'BastionSecurityGroup',
},
],
SpotPrice: '0.0116', // On-Demand price of t2.micro in us-east-1
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-helper-scripts-reference.html
UserData: {
'Fn::Base64': {
'Fn::Join': [
'',
[
'#!/bin/bash -xe\n',
'/usr/bin/yum update -y\n',
'/usr/bin/yum install -y aws-cfn-bootstrap\n',
'EIP_ALLOCATION_ID=',
{ 'Fn::GetAtt': ['BastionEIP', 'AllocationId'] },
'\n',
'INSTANCE_ID=`/usr/bin/curl -sq http://169.254.169.254/latest/meta-data/instance-id`\n',
// eslint-disable-next-line no-template-curly-in-string
'/usr/bin/aws ec2 associate-address --instance-id ${INSTANCE_ID} --allocation-id ${EIP_ALLOCATION_ID} --region ',
{ Ref: 'AWS::Region' },
'\n',
'/opt/aws/bin/cfn-signal --exit-code 0 --stack ',
{ Ref: 'AWS::StackName' },
' --resource BastionAutoScalingGroup ',
' --region ',
{ Ref: 'AWS::Region' },
'\n',
],
],
},
},
},
},
};
} | javascript | function buildBastionLaunchConfiguration(
keyPairName,
{ name = 'BastionLaunchConfiguration' } = {},
) {
return {
[name]: {
Type: 'AWS::AutoScaling::LaunchConfiguration',
Properties: {
AssociatePublicIpAddress: true,
BlockDeviceMappings: [
{
DeviceName: '/dev/xvda',
Ebs: {
VolumeSize: 10,
VolumeType: 'gp2',
DeleteOnTermination: true,
},
},
],
KeyName: keyPairName,
ImageId: {
Ref: 'LatestAmiId',
},
InstanceMonitoring: false,
IamInstanceProfile: {
Ref: 'BastionInstanceProfile',
},
InstanceType: 't2.micro',
SecurityGroups: [
{
Ref: 'BastionSecurityGroup',
},
],
SpotPrice: '0.0116', // On-Demand price of t2.micro in us-east-1
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-helper-scripts-reference.html
UserData: {
'Fn::Base64': {
'Fn::Join': [
'',
[
'#!/bin/bash -xe\n',
'/usr/bin/yum update -y\n',
'/usr/bin/yum install -y aws-cfn-bootstrap\n',
'EIP_ALLOCATION_ID=',
{ 'Fn::GetAtt': ['BastionEIP', 'AllocationId'] },
'\n',
'INSTANCE_ID=`/usr/bin/curl -sq http://169.254.169.254/latest/meta-data/instance-id`\n',
// eslint-disable-next-line no-template-curly-in-string
'/usr/bin/aws ec2 associate-address --instance-id ${INSTANCE_ID} --allocation-id ${EIP_ALLOCATION_ID} --region ',
{ Ref: 'AWS::Region' },
'\n',
'/opt/aws/bin/cfn-signal --exit-code 0 --stack ',
{ Ref: 'AWS::StackName' },
' --resource BastionAutoScalingGroup ',
' --region ',
{ Ref: 'AWS::Region' },
'\n',
],
],
},
},
},
},
};
} | [
"function",
"buildBastionLaunchConfiguration",
"(",
"keyPairName",
",",
"{",
"name",
"=",
"'BastionLaunchConfiguration'",
"}",
"=",
"{",
"}",
",",
")",
"{",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::AutoScaling::LaunchConfiguration'",
",",
"Properties",
":",
"{",
"AssociatePublicIpAddress",
":",
"true",
",",
"BlockDeviceMappings",
":",
"[",
"{",
"DeviceName",
":",
"'/dev/xvda'",
",",
"Ebs",
":",
"{",
"VolumeSize",
":",
"10",
",",
"VolumeType",
":",
"'gp2'",
",",
"DeleteOnTermination",
":",
"true",
",",
"}",
",",
"}",
",",
"]",
",",
"KeyName",
":",
"keyPairName",
",",
"ImageId",
":",
"{",
"Ref",
":",
"'LatestAmiId'",
",",
"}",
",",
"InstanceMonitoring",
":",
"false",
",",
"IamInstanceProfile",
":",
"{",
"Ref",
":",
"'BastionInstanceProfile'",
",",
"}",
",",
"InstanceType",
":",
"'t2.micro'",
",",
"SecurityGroups",
":",
"[",
"{",
"Ref",
":",
"'BastionSecurityGroup'",
",",
"}",
",",
"]",
",",
"SpotPrice",
":",
"'0.0116'",
",",
"// On-Demand price of t2.micro in us-east-1",
"// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-helper-scripts-reference.html",
"UserData",
":",
"{",
"'Fn::Base64'",
":",
"{",
"'Fn::Join'",
":",
"[",
"''",
",",
"[",
"'#!/bin/bash -xe\\n'",
",",
"'/usr/bin/yum update -y\\n'",
",",
"'/usr/bin/yum install -y aws-cfn-bootstrap\\n'",
",",
"'EIP_ALLOCATION_ID='",
",",
"{",
"'Fn::GetAtt'",
":",
"[",
"'BastionEIP'",
",",
"'AllocationId'",
"]",
"}",
",",
"'\\n'",
",",
"'INSTANCE_ID=`/usr/bin/curl -sq http://169.254.169.254/latest/meta-data/instance-id`\\n'",
",",
"// eslint-disable-next-line no-template-curly-in-string",
"'/usr/bin/aws ec2 associate-address --instance-id ${INSTANCE_ID} --allocation-id ${EIP_ALLOCATION_ID} --region '",
",",
"{",
"Ref",
":",
"'AWS::Region'",
"}",
",",
"'\\n'",
",",
"'/opt/aws/bin/cfn-signal --exit-code 0 --stack '",
",",
"{",
"Ref",
":",
"'AWS::StackName'",
"}",
",",
"' --resource BastionAutoScalingGroup '",
",",
"' --region '",
",",
"{",
"Ref",
":",
"'AWS::Region'",
"}",
",",
"'\\n'",
",",
"]",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build the auto-scaling group launch configuration for the bastion host
@param {String} keyPairName Existing key pair name
@param {Object} params
@return {Object} | [
"Build",
"the",
"auto",
"-",
"scaling",
"group",
"launch",
"configuration",
"for",
"the",
"bastion",
"host"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/bastion.js#L123-L187 |
22,878 | smoketurner/serverless-vpc-plugin | src/bastion.js | buildBastionAutoScalingGroup | function buildBastionAutoScalingGroup(numZones = 0, { name = 'BastionAutoScalingGroup' } = {}) {
if (numZones < 1) {
return {};
}
const zones = [];
for (let i = 1; i <= numZones; i += 1) {
zones.push({ Ref: `${PUBLIC_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::AutoScaling::AutoScalingGroup',
CreationPolicy: {
ResourceSignal: {
Count: 1,
Timeout: 'PT10M',
},
},
Properties: {
LaunchConfigurationName: {
Ref: 'BastionLaunchConfiguration',
},
VPCZoneIdentifier: zones,
MinSize: 1,
MaxSize: 1,
Cooldown: '300',
DesiredCapacity: 1,
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'bastion',
],
],
},
PropagateAtLaunch: true,
},
],
},
},
};
} | javascript | function buildBastionAutoScalingGroup(numZones = 0, { name = 'BastionAutoScalingGroup' } = {}) {
if (numZones < 1) {
return {};
}
const zones = [];
for (let i = 1; i <= numZones; i += 1) {
zones.push({ Ref: `${PUBLIC_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::AutoScaling::AutoScalingGroup',
CreationPolicy: {
ResourceSignal: {
Count: 1,
Timeout: 'PT10M',
},
},
Properties: {
LaunchConfigurationName: {
Ref: 'BastionLaunchConfiguration',
},
VPCZoneIdentifier: zones,
MinSize: 1,
MaxSize: 1,
Cooldown: '300',
DesiredCapacity: 1,
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'bastion',
],
],
},
PropagateAtLaunch: true,
},
],
},
},
};
} | [
"function",
"buildBastionAutoScalingGroup",
"(",
"numZones",
"=",
"0",
",",
"{",
"name",
"=",
"'BastionAutoScalingGroup'",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"zones",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"numZones",
";",
"i",
"+=",
"1",
")",
"{",
"zones",
".",
"push",
"(",
"{",
"Ref",
":",
"`",
"${",
"PUBLIC_SUBNET",
"}",
"${",
"i",
"}",
"`",
"}",
")",
";",
"}",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::AutoScaling::AutoScalingGroup'",
",",
"CreationPolicy",
":",
"{",
"ResourceSignal",
":",
"{",
"Count",
":",
"1",
",",
"Timeout",
":",
"'PT10M'",
",",
"}",
",",
"}",
",",
"Properties",
":",
"{",
"LaunchConfigurationName",
":",
"{",
"Ref",
":",
"'BastionLaunchConfiguration'",
",",
"}",
",",
"VPCZoneIdentifier",
":",
"zones",
",",
"MinSize",
":",
"1",
",",
"MaxSize",
":",
"1",
",",
"Cooldown",
":",
"'300'",
",",
"DesiredCapacity",
":",
"1",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"'-'",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"'bastion'",
",",
"]",
",",
"]",
",",
"}",
",",
"PropagateAtLaunch",
":",
"true",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build the bastion host auto-scaling group
@param {Number} numZones Number of availability zones
@param {Object} params
@return {Object} | [
"Build",
"the",
"bastion",
"host",
"auto",
"-",
"scaling",
"group"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/bastion.js#L196-L244 |
22,879 | smoketurner/serverless-vpc-plugin | src/bastion.js | buildBastionSecurityGroup | function buildBastionSecurityGroup(sourceIp = '0.0.0.0/0', { name = 'BastionSecurityGroup' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::SecurityGroup',
Properties: {
GroupDescription: 'Bastion Host',
VpcId: {
Ref: 'VPC',
},
SecurityGroupIngress: [
{
Description: 'Allow inbound SSH access to the bastion host',
IpProtocol: 'tcp',
FromPort: 22,
ToPort: 22,
CidrIp: sourceIp,
},
{
Description: 'Allow inbound ICMP to the bastion host',
IpProtocol: 'icmp',
FromPort: -1,
ToPort: -1,
CidrIp: sourceIp,
},
],
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'bastion',
],
],
},
},
],
},
},
};
} | javascript | function buildBastionSecurityGroup(sourceIp = '0.0.0.0/0', { name = 'BastionSecurityGroup' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::SecurityGroup',
Properties: {
GroupDescription: 'Bastion Host',
VpcId: {
Ref: 'VPC',
},
SecurityGroupIngress: [
{
Description: 'Allow inbound SSH access to the bastion host',
IpProtocol: 'tcp',
FromPort: 22,
ToPort: 22,
CidrIp: sourceIp,
},
{
Description: 'Allow inbound ICMP to the bastion host',
IpProtocol: 'icmp',
FromPort: -1,
ToPort: -1,
CidrIp: sourceIp,
},
],
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'bastion',
],
],
},
},
],
},
},
};
} | [
"function",
"buildBastionSecurityGroup",
"(",
"sourceIp",
"=",
"'0.0.0.0/0'",
",",
"{",
"name",
"=",
"'BastionSecurityGroup'",
"}",
"=",
"{",
"}",
")",
"{",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::SecurityGroup'",
",",
"Properties",
":",
"{",
"GroupDescription",
":",
"'Bastion Host'",
",",
"VpcId",
":",
"{",
"Ref",
":",
"'VPC'",
",",
"}",
",",
"SecurityGroupIngress",
":",
"[",
"{",
"Description",
":",
"'Allow inbound SSH access to the bastion host'",
",",
"IpProtocol",
":",
"'tcp'",
",",
"FromPort",
":",
"22",
",",
"ToPort",
":",
"22",
",",
"CidrIp",
":",
"sourceIp",
",",
"}",
",",
"{",
"Description",
":",
"'Allow inbound ICMP to the bastion host'",
",",
"IpProtocol",
":",
"'icmp'",
",",
"FromPort",
":",
"-",
"1",
",",
"ToPort",
":",
"-",
"1",
",",
"CidrIp",
":",
"sourceIp",
",",
"}",
",",
"]",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"'-'",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"'bastion'",
",",
"]",
",",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a SecurityGroup to be used by the bastion host
@param {String} sourceIp source IP address
@param {Object} params
@return {Object} | [
"Build",
"a",
"SecurityGroup",
"to",
"be",
"used",
"by",
"the",
"bastion",
"host"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/bastion.js#L253-L297 |
22,880 | smoketurner/serverless-vpc-plugin | src/bastion.js | buildBastion | async function buildBastion(keyPairName, numZones = 0) {
if (numZones < 1) {
return {};
}
let publicIp = '0.0.0.0/0';
try {
publicIp = await getPublicIp();
publicIp = `${publicIp}/32`;
} catch (err) {
console.error('Unable to discover public IP address:', err);
}
return Object.assign(
{},
buildBastionEIP(),
buildBastionIamRole(),
buildBastionInstanceProfile(),
buildBastionSecurityGroup(publicIp),
buildBastionLaunchConfiguration(keyPairName),
buildBastionAutoScalingGroup(numZones),
);
} | javascript | async function buildBastion(keyPairName, numZones = 0) {
if (numZones < 1) {
return {};
}
let publicIp = '0.0.0.0/0';
try {
publicIp = await getPublicIp();
publicIp = `${publicIp}/32`;
} catch (err) {
console.error('Unable to discover public IP address:', err);
}
return Object.assign(
{},
buildBastionEIP(),
buildBastionIamRole(),
buildBastionInstanceProfile(),
buildBastionSecurityGroup(publicIp),
buildBastionLaunchConfiguration(keyPairName),
buildBastionAutoScalingGroup(numZones),
);
} | [
"async",
"function",
"buildBastion",
"(",
"keyPairName",
",",
"numZones",
"=",
"0",
")",
"{",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"let",
"publicIp",
"=",
"'0.0.0.0/0'",
";",
"try",
"{",
"publicIp",
"=",
"await",
"getPublicIp",
"(",
")",
";",
"publicIp",
"=",
"`",
"${",
"publicIp",
"}",
"`",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"'Unable to discover public IP address:'",
",",
"err",
")",
";",
"}",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"buildBastionEIP",
"(",
")",
",",
"buildBastionIamRole",
"(",
")",
",",
"buildBastionInstanceProfile",
"(",
")",
",",
"buildBastionSecurityGroup",
"(",
"publicIp",
")",
",",
"buildBastionLaunchConfiguration",
"(",
"keyPairName",
")",
",",
"buildBastionAutoScalingGroup",
"(",
"numZones",
")",
",",
")",
";",
"}"
] | Build the bastion host
@param {String} keyPairName Existing key pair name
@param {Number} numZones Number of availability zones
@return {Promise} | [
"Build",
"the",
"bastion",
"host"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/bastion.js#L306-L327 |
22,881 | smoketurner/serverless-vpc-plugin | src/subnet_groups.js | buildRDSSubnetGroup | function buildRDSSubnetGroup(numZones = 0, { name = 'RDSSubnetGroup' } = {}) {
if (numZones < 1) {
return {};
}
const subnetIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::RDS::DBSubnetGroup',
Properties: {
DBSubnetGroupName: {
Ref: 'AWS::StackName',
},
DBSubnetGroupDescription: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
} | javascript | function buildRDSSubnetGroup(numZones = 0, { name = 'RDSSubnetGroup' } = {}) {
if (numZones < 1) {
return {};
}
const subnetIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::RDS::DBSubnetGroup',
Properties: {
DBSubnetGroupName: {
Ref: 'AWS::StackName',
},
DBSubnetGroupDescription: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
} | [
"function",
"buildRDSSubnetGroup",
"(",
"numZones",
"=",
"0",
",",
"{",
"name",
"=",
"'RDSSubnetGroup'",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"subnetIds",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"numZones",
";",
"i",
"+=",
"1",
")",
"{",
"subnetIds",
".",
"push",
"(",
"{",
"Ref",
":",
"`",
"${",
"DB_SUBNET",
"}",
"${",
"i",
"}",
"`",
"}",
")",
";",
"}",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::RDS::DBSubnetGroup'",
",",
"Properties",
":",
"{",
"DBSubnetGroupName",
":",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"DBSubnetGroupDescription",
":",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"SubnetIds",
":",
"subnetIds",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build an RDSubnetGroup for a given number of zones
@param {Number} numZones Number of availability zones
@param {Objects} params
@return {Object} | [
"Build",
"an",
"RDSubnetGroup",
"for",
"a",
"given",
"number",
"of",
"zones"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/subnet_groups.js#L10-L34 |
22,882 | smoketurner/serverless-vpc-plugin | src/subnet_groups.js | buildElastiCacheSubnetGroup | function buildElastiCacheSubnetGroup(numZones = 0, { name = 'ElastiCacheSubnetGroup' } = {}) {
if (numZones < 1) {
return {};
}
const subnetIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::ElastiCache::SubnetGroup',
Properties: {
CacheSubnetGroupName: {
Ref: 'AWS::StackName',
},
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
} | javascript | function buildElastiCacheSubnetGroup(numZones = 0, { name = 'ElastiCacheSubnetGroup' } = {}) {
if (numZones < 1) {
return {};
}
const subnetIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::ElastiCache::SubnetGroup',
Properties: {
CacheSubnetGroupName: {
Ref: 'AWS::StackName',
},
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
} | [
"function",
"buildElastiCacheSubnetGroup",
"(",
"numZones",
"=",
"0",
",",
"{",
"name",
"=",
"'ElastiCacheSubnetGroup'",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"subnetIds",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"numZones",
";",
"i",
"+=",
"1",
")",
"{",
"subnetIds",
".",
"push",
"(",
"{",
"Ref",
":",
"`",
"${",
"DB_SUBNET",
"}",
"${",
"i",
"}",
"`",
"}",
")",
";",
"}",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::ElastiCache::SubnetGroup'",
",",
"Properties",
":",
"{",
"CacheSubnetGroupName",
":",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"Description",
":",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"SubnetIds",
":",
"subnetIds",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build an ElastiCacheSubnetGroup for a given number of zones
@param {Number} numZones Number of availability zones
@param {Object} params
@return {Object} | [
"Build",
"an",
"ElastiCacheSubnetGroup",
"for",
"a",
"given",
"number",
"of",
"zones"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/subnet_groups.js#L43-L67 |
22,883 | smoketurner/serverless-vpc-plugin | src/subnet_groups.js | buildRedshiftSubnetGroup | function buildRedshiftSubnetGroup(numZones = 0, { name = 'RedshiftSubnetGroup' } = {}) {
if (numZones < 1) {
return {};
}
const subnetIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::Redshift::ClusterSubnetGroup',
Properties: {
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
} | javascript | function buildRedshiftSubnetGroup(numZones = 0, { name = 'RedshiftSubnetGroup' } = {}) {
if (numZones < 1) {
return {};
}
const subnetIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::Redshift::ClusterSubnetGroup',
Properties: {
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
} | [
"function",
"buildRedshiftSubnetGroup",
"(",
"numZones",
"=",
"0",
",",
"{",
"name",
"=",
"'RedshiftSubnetGroup'",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"subnetIds",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"numZones",
";",
"i",
"+=",
"1",
")",
"{",
"subnetIds",
".",
"push",
"(",
"{",
"Ref",
":",
"`",
"${",
"DB_SUBNET",
"}",
"${",
"i",
"}",
"`",
"}",
")",
";",
"}",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::Redshift::ClusterSubnetGroup'",
",",
"Properties",
":",
"{",
"Description",
":",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"SubnetIds",
":",
"subnetIds",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build an RedshiftSubnetGroup for a given number of zones
@param {Number} numZones Number of availability zones
@param {Object} params
@return {Object} | [
"Build",
"an",
"RedshiftSubnetGroup",
"for",
"a",
"given",
"number",
"of",
"zones"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/subnet_groups.js#L76-L97 |
22,884 | smoketurner/serverless-vpc-plugin | src/subnet_groups.js | buildDAXSubnetGroup | function buildDAXSubnetGroup(numZones = 0, { name = 'DAXSubnetGroup' } = {}) {
if (numZones < 1) {
return {};
}
const subnetIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::DAX::SubnetGroup',
Properties: {
SubnetGroupName: {
Ref: 'AWS::StackName',
},
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
} | javascript | function buildDAXSubnetGroup(numZones = 0, { name = 'DAXSubnetGroup' } = {}) {
if (numZones < 1) {
return {};
}
const subnetIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${DB_SUBNET}Subnet${i}` });
}
return {
[name]: {
Type: 'AWS::DAX::SubnetGroup',
Properties: {
SubnetGroupName: {
Ref: 'AWS::StackName',
},
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
} | [
"function",
"buildDAXSubnetGroup",
"(",
"numZones",
"=",
"0",
",",
"{",
"name",
"=",
"'DAXSubnetGroup'",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"subnetIds",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"numZones",
";",
"i",
"+=",
"1",
")",
"{",
"subnetIds",
".",
"push",
"(",
"{",
"Ref",
":",
"`",
"${",
"DB_SUBNET",
"}",
"${",
"i",
"}",
"`",
"}",
")",
";",
"}",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::DAX::SubnetGroup'",
",",
"Properties",
":",
"{",
"SubnetGroupName",
":",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"Description",
":",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"SubnetIds",
":",
"subnetIds",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build an DAXSubnetGroup for a given number of zones
@param {Number} numZones Number of availability zones
@param {Object} params
@return {Object} | [
"Build",
"an",
"DAXSubnetGroup",
"for",
"a",
"given",
"number",
"of",
"zones"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/subnet_groups.js#L106-L130 |
22,885 | smoketurner/serverless-vpc-plugin | src/subnet_groups.js | buildSubnetGroups | function buildSubnetGroups(numZones = 0) {
if (numZones < 2) {
return {};
}
return Object.assign(
{},
buildRDSSubnetGroup(numZones),
buildRedshiftSubnetGroup(numZones),
buildElastiCacheSubnetGroup(numZones),
buildDAXSubnetGroup(numZones),
);
} | javascript | function buildSubnetGroups(numZones = 0) {
if (numZones < 2) {
return {};
}
return Object.assign(
{},
buildRDSSubnetGroup(numZones),
buildRedshiftSubnetGroup(numZones),
buildElastiCacheSubnetGroup(numZones),
buildDAXSubnetGroup(numZones),
);
} | [
"function",
"buildSubnetGroups",
"(",
"numZones",
"=",
"0",
")",
"{",
"if",
"(",
"numZones",
"<",
"2",
")",
"{",
"return",
"{",
"}",
";",
"}",
"return",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"buildRDSSubnetGroup",
"(",
"numZones",
")",
",",
"buildRedshiftSubnetGroup",
"(",
"numZones",
")",
",",
"buildElastiCacheSubnetGroup",
"(",
"numZones",
")",
",",
"buildDAXSubnetGroup",
"(",
"numZones",
")",
",",
")",
";",
"}"
] | Build the database subnet groups
@param {Number} numZones Number of availability zones
@return {Object} | [
"Build",
"the",
"database",
"subnet",
"groups"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/subnet_groups.js#L138-L149 |
22,886 | smoketurner/serverless-vpc-plugin | src/nat_instance.js | buildNatSecurityGroup | function buildNatSecurityGroup(subnets = [], { name = 'NatSecurityGroup' } = {}) {
const SecurityGroupIngress = [];
if (Array.isArray(subnets) && subnets.length > 0) {
subnets.forEach((subnet, index) => {
const position = index + 1;
const http = {
Description: `Allow inbound HTTP traffic from ${APP_SUBNET}Subnet${position}`,
IpProtocol: 'tcp',
FromPort: 80,
ToPort: 80,
CidrIp: subnet,
};
const https = {
Description: `Allow inbound HTTPS traffic from ${APP_SUBNET}Subnet${position}`,
IpProtocol: 'tcp',
FromPort: 443,
ToPort: 443,
CidrIp: subnet,
};
SecurityGroupIngress.push(http, https);
});
}
return {
[name]: {
Type: 'AWS::EC2::SecurityGroup',
Properties: {
GroupDescription: 'NAT Instance',
VpcId: {
Ref: 'VPC',
},
SecurityGroupEgress: [
{
Description: 'Allow outbound HTTP access to the Internet',
IpProtocol: 'tcp',
FromPort: 80,
ToPort: 80,
CidrIp: '0.0.0.0/0',
},
{
Description: 'Allow outbound HTTPS access to the Internet',
IpProtocol: 'tcp',
FromPort: 443,
ToPort: 443,
CidrIp: '0.0.0.0/0',
},
],
SecurityGroupIngress,
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'nat',
],
],
},
},
],
},
},
};
} | javascript | function buildNatSecurityGroup(subnets = [], { name = 'NatSecurityGroup' } = {}) {
const SecurityGroupIngress = [];
if (Array.isArray(subnets) && subnets.length > 0) {
subnets.forEach((subnet, index) => {
const position = index + 1;
const http = {
Description: `Allow inbound HTTP traffic from ${APP_SUBNET}Subnet${position}`,
IpProtocol: 'tcp',
FromPort: 80,
ToPort: 80,
CidrIp: subnet,
};
const https = {
Description: `Allow inbound HTTPS traffic from ${APP_SUBNET}Subnet${position}`,
IpProtocol: 'tcp',
FromPort: 443,
ToPort: 443,
CidrIp: subnet,
};
SecurityGroupIngress.push(http, https);
});
}
return {
[name]: {
Type: 'AWS::EC2::SecurityGroup',
Properties: {
GroupDescription: 'NAT Instance',
VpcId: {
Ref: 'VPC',
},
SecurityGroupEgress: [
{
Description: 'Allow outbound HTTP access to the Internet',
IpProtocol: 'tcp',
FromPort: 80,
ToPort: 80,
CidrIp: '0.0.0.0/0',
},
{
Description: 'Allow outbound HTTPS access to the Internet',
IpProtocol: 'tcp',
FromPort: 443,
ToPort: 443,
CidrIp: '0.0.0.0/0',
},
],
SecurityGroupIngress,
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'nat',
],
],
},
},
],
},
},
};
} | [
"function",
"buildNatSecurityGroup",
"(",
"subnets",
"=",
"[",
"]",
",",
"{",
"name",
"=",
"'NatSecurityGroup'",
"}",
"=",
"{",
"}",
")",
"{",
"const",
"SecurityGroupIngress",
"=",
"[",
"]",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"subnets",
")",
"&&",
"subnets",
".",
"length",
">",
"0",
")",
"{",
"subnets",
".",
"forEach",
"(",
"(",
"subnet",
",",
"index",
")",
"=>",
"{",
"const",
"position",
"=",
"index",
"+",
"1",
";",
"const",
"http",
"=",
"{",
"Description",
":",
"`",
"${",
"APP_SUBNET",
"}",
"${",
"position",
"}",
"`",
",",
"IpProtocol",
":",
"'tcp'",
",",
"FromPort",
":",
"80",
",",
"ToPort",
":",
"80",
",",
"CidrIp",
":",
"subnet",
",",
"}",
";",
"const",
"https",
"=",
"{",
"Description",
":",
"`",
"${",
"APP_SUBNET",
"}",
"${",
"position",
"}",
"`",
",",
"IpProtocol",
":",
"'tcp'",
",",
"FromPort",
":",
"443",
",",
"ToPort",
":",
"443",
",",
"CidrIp",
":",
"subnet",
",",
"}",
";",
"SecurityGroupIngress",
".",
"push",
"(",
"http",
",",
"https",
")",
";",
"}",
")",
";",
"}",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::SecurityGroup'",
",",
"Properties",
":",
"{",
"GroupDescription",
":",
"'NAT Instance'",
",",
"VpcId",
":",
"{",
"Ref",
":",
"'VPC'",
",",
"}",
",",
"SecurityGroupEgress",
":",
"[",
"{",
"Description",
":",
"'Allow outbound HTTP access to the Internet'",
",",
"IpProtocol",
":",
"'tcp'",
",",
"FromPort",
":",
"80",
",",
"ToPort",
":",
"80",
",",
"CidrIp",
":",
"'0.0.0.0/0'",
",",
"}",
",",
"{",
"Description",
":",
"'Allow outbound HTTPS access to the Internet'",
",",
"IpProtocol",
":",
"'tcp'",
",",
"FromPort",
":",
"443",
",",
"ToPort",
":",
"443",
",",
"CidrIp",
":",
"'0.0.0.0/0'",
",",
"}",
",",
"]",
",",
"SecurityGroupIngress",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"'-'",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"'nat'",
",",
"]",
",",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a SecurityGroup to be used by the NAT instance
@param {Array} subnets Array of subnets
@param {Object} params
@return {Object} | [
"Build",
"a",
"SecurityGroup",
"to",
"be",
"used",
"by",
"the",
"NAT",
"instance"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/nat_instance.js#L10-L79 |
22,887 | smoketurner/serverless-vpc-plugin | src/nat_instance.js | buildNatInstance | function buildNatInstance(imageId, zones = [], { name = 'NatInstance' } = {}) {
if (!imageId) {
return {};
}
if (!Array.isArray(zones) || zones.length < 1) {
return {};
}
return {
[name]: {
Type: 'AWS::EC2::Instance',
DependsOn: 'InternetGatewayAttachment',
Properties: {
AvailabilityZone: {
'Fn::Select': ['0', zones],
},
BlockDeviceMappings: [
{
DeviceName: '/dev/xvda',
Ebs: {
VolumeSize: 10,
VolumeType: 'gp2',
DeleteOnTermination: true,
},
},
],
ImageId: imageId, // amzn-ami-vpc-nat-hvm-2018.03.0.20181116-x86_64-ebs
InstanceType: 't2.micro',
Monitoring: false,
NetworkInterfaces: [
{
AssociatePublicIpAddress: true,
DeleteOnTermination: true,
Description: 'eth0',
DeviceIndex: '0',
GroupSet: [
{
Ref: 'NatSecurityGroup',
},
],
SubnetId: {
Ref: `${PUBLIC_SUBNET}Subnet1`,
},
},
],
SourceDestCheck: false, // required for a NAT instance
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'nat',
],
],
},
},
],
},
},
};
} | javascript | function buildNatInstance(imageId, zones = [], { name = 'NatInstance' } = {}) {
if (!imageId) {
return {};
}
if (!Array.isArray(zones) || zones.length < 1) {
return {};
}
return {
[name]: {
Type: 'AWS::EC2::Instance',
DependsOn: 'InternetGatewayAttachment',
Properties: {
AvailabilityZone: {
'Fn::Select': ['0', zones],
},
BlockDeviceMappings: [
{
DeviceName: '/dev/xvda',
Ebs: {
VolumeSize: 10,
VolumeType: 'gp2',
DeleteOnTermination: true,
},
},
],
ImageId: imageId, // amzn-ami-vpc-nat-hvm-2018.03.0.20181116-x86_64-ebs
InstanceType: 't2.micro',
Monitoring: false,
NetworkInterfaces: [
{
AssociatePublicIpAddress: true,
DeleteOnTermination: true,
Description: 'eth0',
DeviceIndex: '0',
GroupSet: [
{
Ref: 'NatSecurityGroup',
},
],
SubnetId: {
Ref: `${PUBLIC_SUBNET}Subnet1`,
},
},
],
SourceDestCheck: false, // required for a NAT instance
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'nat',
],
],
},
},
],
},
},
};
} | [
"function",
"buildNatInstance",
"(",
"imageId",
",",
"zones",
"=",
"[",
"]",
",",
"{",
"name",
"=",
"'NatInstance'",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"imageId",
")",
"{",
"return",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"zones",
")",
"||",
"zones",
".",
"length",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::Instance'",
",",
"DependsOn",
":",
"'InternetGatewayAttachment'",
",",
"Properties",
":",
"{",
"AvailabilityZone",
":",
"{",
"'Fn::Select'",
":",
"[",
"'0'",
",",
"zones",
"]",
",",
"}",
",",
"BlockDeviceMappings",
":",
"[",
"{",
"DeviceName",
":",
"'/dev/xvda'",
",",
"Ebs",
":",
"{",
"VolumeSize",
":",
"10",
",",
"VolumeType",
":",
"'gp2'",
",",
"DeleteOnTermination",
":",
"true",
",",
"}",
",",
"}",
",",
"]",
",",
"ImageId",
":",
"imageId",
",",
"// amzn-ami-vpc-nat-hvm-2018.03.0.20181116-x86_64-ebs",
"InstanceType",
":",
"'t2.micro'",
",",
"Monitoring",
":",
"false",
",",
"NetworkInterfaces",
":",
"[",
"{",
"AssociatePublicIpAddress",
":",
"true",
",",
"DeleteOnTermination",
":",
"true",
",",
"Description",
":",
"'eth0'",
",",
"DeviceIndex",
":",
"'0'",
",",
"GroupSet",
":",
"[",
"{",
"Ref",
":",
"'NatSecurityGroup'",
",",
"}",
",",
"]",
",",
"SubnetId",
":",
"{",
"Ref",
":",
"`",
"${",
"PUBLIC_SUBNET",
"}",
"`",
",",
"}",
",",
"}",
",",
"]",
",",
"SourceDestCheck",
":",
"false",
",",
"// required for a NAT instance",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"'-'",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"'nat'",
",",
"]",
",",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build the NAT instance
@param {Object} imageId AMI image ID
@param {Array} zones Array of availability zones
@param {Object} params
@return {Object} | [
"Build",
"the",
"NAT",
"instance"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/nat_instance.js#L89-L154 |
22,888 | smoketurner/serverless-vpc-plugin | src/az.js | buildAvailabilityZones | function buildAvailabilityZones(
subnets,
zones = [],
{ numNatGateway = 0, createDbSubnet = true, createNatInstance = false } = {},
) {
if (!(subnets instanceof Map) || subnets.size < 1) {
return {};
}
if (!Array.isArray(zones) || zones.length < 1) {
return {};
}
const resources = {};
if (numNatGateway > 0) {
for (let index = 0; index < numNatGateway; index += 1) {
Object.assign(resources, buildEIP(index + 1), buildNatGateway(index + 1, zones[index]));
}
}
zones.forEach((zone, index) => {
const position = index + 1;
Object.assign(
resources,
// App Subnet
buildSubnet(APP_SUBNET, position, zone, subnets.get(zone).get(APP_SUBNET)),
buildRouteTable(APP_SUBNET, position, zone),
buildRouteTableAssociation(APP_SUBNET, position),
// no default route on Application subnet
// Public Subnet
buildSubnet(PUBLIC_SUBNET, position, zone, subnets.get(zone).get(PUBLIC_SUBNET)),
buildRouteTable(PUBLIC_SUBNET, position, zone),
buildRouteTableAssociation(PUBLIC_SUBNET, position),
buildRoute(PUBLIC_SUBNET, position, {
GatewayId: 'InternetGateway',
}),
);
const params = {};
if (numNatGateway > 0) {
params.NatGatewayId = `NatGateway${(index % numNatGateway) + 1}`;
} else if (createNatInstance) {
params.InstanceId = 'NatInstance';
}
// only set default route on Application subnet to a NAT Gateway or NAT Instance
if (Object.keys(params).length > 0) {
Object.assign(resources, buildRoute(APP_SUBNET, position, params));
}
if (createDbSubnet) {
// DB Subnet
Object.assign(
resources,
buildSubnet(DB_SUBNET, position, zone, subnets.get(zone).get(DB_SUBNET)),
buildRouteTable(DB_SUBNET, position, zone),
buildRouteTableAssociation(DB_SUBNET, position),
// no default route on DB subnet
);
}
});
return resources;
} | javascript | function buildAvailabilityZones(
subnets,
zones = [],
{ numNatGateway = 0, createDbSubnet = true, createNatInstance = false } = {},
) {
if (!(subnets instanceof Map) || subnets.size < 1) {
return {};
}
if (!Array.isArray(zones) || zones.length < 1) {
return {};
}
const resources = {};
if (numNatGateway > 0) {
for (let index = 0; index < numNatGateway; index += 1) {
Object.assign(resources, buildEIP(index + 1), buildNatGateway(index + 1, zones[index]));
}
}
zones.forEach((zone, index) => {
const position = index + 1;
Object.assign(
resources,
// App Subnet
buildSubnet(APP_SUBNET, position, zone, subnets.get(zone).get(APP_SUBNET)),
buildRouteTable(APP_SUBNET, position, zone),
buildRouteTableAssociation(APP_SUBNET, position),
// no default route on Application subnet
// Public Subnet
buildSubnet(PUBLIC_SUBNET, position, zone, subnets.get(zone).get(PUBLIC_SUBNET)),
buildRouteTable(PUBLIC_SUBNET, position, zone),
buildRouteTableAssociation(PUBLIC_SUBNET, position),
buildRoute(PUBLIC_SUBNET, position, {
GatewayId: 'InternetGateway',
}),
);
const params = {};
if (numNatGateway > 0) {
params.NatGatewayId = `NatGateway${(index % numNatGateway) + 1}`;
} else if (createNatInstance) {
params.InstanceId = 'NatInstance';
}
// only set default route on Application subnet to a NAT Gateway or NAT Instance
if (Object.keys(params).length > 0) {
Object.assign(resources, buildRoute(APP_SUBNET, position, params));
}
if (createDbSubnet) {
// DB Subnet
Object.assign(
resources,
buildSubnet(DB_SUBNET, position, zone, subnets.get(zone).get(DB_SUBNET)),
buildRouteTable(DB_SUBNET, position, zone),
buildRouteTableAssociation(DB_SUBNET, position),
// no default route on DB subnet
);
}
});
return resources;
} | [
"function",
"buildAvailabilityZones",
"(",
"subnets",
",",
"zones",
"=",
"[",
"]",
",",
"{",
"numNatGateway",
"=",
"0",
",",
"createDbSubnet",
"=",
"true",
",",
"createNatInstance",
"=",
"false",
"}",
"=",
"{",
"}",
",",
")",
"{",
"if",
"(",
"!",
"(",
"subnets",
"instanceof",
"Map",
")",
"||",
"subnets",
".",
"size",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"zones",
")",
"||",
"zones",
".",
"length",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"resources",
"=",
"{",
"}",
";",
"if",
"(",
"numNatGateway",
">",
"0",
")",
"{",
"for",
"(",
"let",
"index",
"=",
"0",
";",
"index",
"<",
"numNatGateway",
";",
"index",
"+=",
"1",
")",
"{",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildEIP",
"(",
"index",
"+",
"1",
")",
",",
"buildNatGateway",
"(",
"index",
"+",
"1",
",",
"zones",
"[",
"index",
"]",
")",
")",
";",
"}",
"}",
"zones",
".",
"forEach",
"(",
"(",
"zone",
",",
"index",
")",
"=>",
"{",
"const",
"position",
"=",
"index",
"+",
"1",
";",
"Object",
".",
"assign",
"(",
"resources",
",",
"// App Subnet",
"buildSubnet",
"(",
"APP_SUBNET",
",",
"position",
",",
"zone",
",",
"subnets",
".",
"get",
"(",
"zone",
")",
".",
"get",
"(",
"APP_SUBNET",
")",
")",
",",
"buildRouteTable",
"(",
"APP_SUBNET",
",",
"position",
",",
"zone",
")",
",",
"buildRouteTableAssociation",
"(",
"APP_SUBNET",
",",
"position",
")",
",",
"// no default route on Application subnet",
"// Public Subnet",
"buildSubnet",
"(",
"PUBLIC_SUBNET",
",",
"position",
",",
"zone",
",",
"subnets",
".",
"get",
"(",
"zone",
")",
".",
"get",
"(",
"PUBLIC_SUBNET",
")",
")",
",",
"buildRouteTable",
"(",
"PUBLIC_SUBNET",
",",
"position",
",",
"zone",
")",
",",
"buildRouteTableAssociation",
"(",
"PUBLIC_SUBNET",
",",
"position",
")",
",",
"buildRoute",
"(",
"PUBLIC_SUBNET",
",",
"position",
",",
"{",
"GatewayId",
":",
"'InternetGateway'",
",",
"}",
")",
",",
")",
";",
"const",
"params",
"=",
"{",
"}",
";",
"if",
"(",
"numNatGateway",
">",
"0",
")",
"{",
"params",
".",
"NatGatewayId",
"=",
"`",
"${",
"(",
"index",
"%",
"numNatGateway",
")",
"+",
"1",
"}",
"`",
";",
"}",
"else",
"if",
"(",
"createNatInstance",
")",
"{",
"params",
".",
"InstanceId",
"=",
"'NatInstance'",
";",
"}",
"// only set default route on Application subnet to a NAT Gateway or NAT Instance",
"if",
"(",
"Object",
".",
"keys",
"(",
"params",
")",
".",
"length",
">",
"0",
")",
"{",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildRoute",
"(",
"APP_SUBNET",
",",
"position",
",",
"params",
")",
")",
";",
"}",
"if",
"(",
"createDbSubnet",
")",
"{",
"// DB Subnet",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildSubnet",
"(",
"DB_SUBNET",
",",
"position",
",",
"zone",
",",
"subnets",
".",
"get",
"(",
"zone",
")",
".",
"get",
"(",
"DB_SUBNET",
")",
")",
",",
"buildRouteTable",
"(",
"DB_SUBNET",
",",
"position",
",",
"zone",
")",
",",
"buildRouteTableAssociation",
"(",
"DB_SUBNET",
",",
"position",
")",
",",
"// no default route on DB subnet",
")",
";",
"}",
"}",
")",
";",
"return",
"resources",
";",
"}"
] | Builds the Availability Zones for the region.
1.) Splits the VPC CIDR Block into /20 subnets, one per AZ.
2.) Split each AZ /20 CIDR Block into two /21 subnets
3.) Use the first /21 subnet for Applications
4.) Split the second /21 subnet into two /22 subnets: one Public subnet (for load balancers),
and one for databases (RDS, ElastiCache, and Redshift)
@param {Map} subnets Map of subnets
@param {Array} zones Array of availability zones
@param {Number} numNatGateway Number of NAT gateways (and EIPs) to provision
@param {Boolean} createDbSubnet Whether to create the DBSubnet or not
@param {Boolean} createNatInstance Whether to create a NAT instance or not
@return {Object} | [
"Builds",
"the",
"Availability",
"Zones",
"for",
"the",
"region",
"."
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/az.js#L21-L87 |
22,889 | smoketurner/serverless-vpc-plugin | src/natgw.js | buildNatGateway | function buildNatGateway(position, zone) {
const cfName = `NatGateway${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::NatGateway',
Properties: {
AllocationId: {
'Fn::GetAtt': [`EIP${position}`, 'AllocationId'],
},
SubnetId: {
Ref: `${PUBLIC_SUBNET}Subnet${position}`,
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
zone,
],
],
},
},
],
},
},
};
} | javascript | function buildNatGateway(position, zone) {
const cfName = `NatGateway${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::NatGateway',
Properties: {
AllocationId: {
'Fn::GetAtt': [`EIP${position}`, 'AllocationId'],
},
SubnetId: {
Ref: `${PUBLIC_SUBNET}Subnet${position}`,
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
zone,
],
],
},
},
],
},
},
};
} | [
"function",
"buildNatGateway",
"(",
"position",
",",
"zone",
")",
"{",
"const",
"cfName",
"=",
"`",
"${",
"position",
"}",
"`",
";",
"return",
"{",
"[",
"cfName",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::NatGateway'",
",",
"Properties",
":",
"{",
"AllocationId",
":",
"{",
"'Fn::GetAtt'",
":",
"[",
"`",
"${",
"position",
"}",
"`",
",",
"'AllocationId'",
"]",
",",
"}",
",",
"SubnetId",
":",
"{",
"Ref",
":",
"`",
"${",
"PUBLIC_SUBNET",
"}",
"${",
"position",
"}",
"`",
",",
"}",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"'-'",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
",",
"}",
",",
"zone",
",",
"]",
",",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a NatGateway in a given AZ
@param {Number} position
@param {String} zone
@return {Object} | [
"Build",
"a",
"NatGateway",
"in",
"a",
"given",
"AZ"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/natgw.js#L28-L59 |
22,890 | smoketurner/serverless-vpc-plugin | src/flow_logs.js | buildLogBucket | function buildLogBucket() {
return {
LogBucket: {
Type: 'AWS::S3::Bucket',
DeletionPolicy: 'Retain',
Properties: {
AccessControl: 'LogDeliveryWrite',
BucketEncryption: {
ServerSideEncryptionConfiguration: [
{
ServerSideEncryptionByDefault: {
SSEAlgorithm: 'AES256',
},
},
],
},
PublicAccessBlockConfiguration: {
BlockPublicAcls: true,
BlockPublicPolicy: true,
IgnorePublicAcls: true,
RestrictPublicBuckets: true,
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [' ', [{ Ref: 'AWS::StackName' }, 'Logs']],
},
},
],
},
},
};
} | javascript | function buildLogBucket() {
return {
LogBucket: {
Type: 'AWS::S3::Bucket',
DeletionPolicy: 'Retain',
Properties: {
AccessControl: 'LogDeliveryWrite',
BucketEncryption: {
ServerSideEncryptionConfiguration: [
{
ServerSideEncryptionByDefault: {
SSEAlgorithm: 'AES256',
},
},
],
},
PublicAccessBlockConfiguration: {
BlockPublicAcls: true,
BlockPublicPolicy: true,
IgnorePublicAcls: true,
RestrictPublicBuckets: true,
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [' ', [{ Ref: 'AWS::StackName' }, 'Logs']],
},
},
],
},
},
};
} | [
"function",
"buildLogBucket",
"(",
")",
"{",
"return",
"{",
"LogBucket",
":",
"{",
"Type",
":",
"'AWS::S3::Bucket'",
",",
"DeletionPolicy",
":",
"'Retain'",
",",
"Properties",
":",
"{",
"AccessControl",
":",
"'LogDeliveryWrite'",
",",
"BucketEncryption",
":",
"{",
"ServerSideEncryptionConfiguration",
":",
"[",
"{",
"ServerSideEncryptionByDefault",
":",
"{",
"SSEAlgorithm",
":",
"'AES256'",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"PublicAccessBlockConfiguration",
":",
"{",
"BlockPublicAcls",
":",
"true",
",",
"BlockPublicPolicy",
":",
"true",
",",
"IgnorePublicAcls",
":",
"true",
",",
"RestrictPublicBuckets",
":",
"true",
",",
"}",
",",
"Tags",
":",
"[",
"{",
"Key",
":",
"'Name'",
",",
"Value",
":",
"{",
"'Fn::Join'",
":",
"[",
"' '",
",",
"[",
"{",
"Ref",
":",
"'AWS::StackName'",
"}",
",",
"'Logs'",
"]",
"]",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build an S3 bucket for logging
@return {Object} | [
"Build",
"an",
"S3",
"bucket",
"for",
"logging"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/flow_logs.js#L6-L39 |
22,891 | smoketurner/serverless-vpc-plugin | src/flow_logs.js | buildLogBucketPolicy | function buildLogBucketPolicy() {
return {
LogBucketPolicy: {
Type: 'AWS::S3::BucketPolicy',
Properties: {
Bucket: {
Ref: 'LogBucket',
},
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Sid: 'AWSLogDeliveryAclCheck',
Effect: 'Allow',
Principal: {
Service: 'delivery.logs.amazonaws.com',
},
Action: 's3:GetBucketAcl',
Resource: {
'Fn::GetAtt': ['LogBucket', 'Arn'],
},
},
{
Sid: 'AWSLogDeliveryWrite',
Effect: 'Allow',
Principal: {
Service: 'delivery.logs.amazonaws.com',
},
Action: 's3:PutObject',
Resource: {
'Fn::Join': [
'',
[
'arn:aws:s3:::',
{ Ref: 'LogBucket' },
'/AWSLogs/',
{ Ref: 'AWS::AccountId' },
'/*',
],
],
},
Condition: {
StringEquals: {
's3:x-amz-acl': 'bucket-owner-full-control',
},
},
},
],
},
},
},
};
} | javascript | function buildLogBucketPolicy() {
return {
LogBucketPolicy: {
Type: 'AWS::S3::BucketPolicy',
Properties: {
Bucket: {
Ref: 'LogBucket',
},
PolicyDocument: {
Version: '2012-10-17',
Statement: [
{
Sid: 'AWSLogDeliveryAclCheck',
Effect: 'Allow',
Principal: {
Service: 'delivery.logs.amazonaws.com',
},
Action: 's3:GetBucketAcl',
Resource: {
'Fn::GetAtt': ['LogBucket', 'Arn'],
},
},
{
Sid: 'AWSLogDeliveryWrite',
Effect: 'Allow',
Principal: {
Service: 'delivery.logs.amazonaws.com',
},
Action: 's3:PutObject',
Resource: {
'Fn::Join': [
'',
[
'arn:aws:s3:::',
{ Ref: 'LogBucket' },
'/AWSLogs/',
{ Ref: 'AWS::AccountId' },
'/*',
],
],
},
Condition: {
StringEquals: {
's3:x-amz-acl': 'bucket-owner-full-control',
},
},
},
],
},
},
},
};
} | [
"function",
"buildLogBucketPolicy",
"(",
")",
"{",
"return",
"{",
"LogBucketPolicy",
":",
"{",
"Type",
":",
"'AWS::S3::BucketPolicy'",
",",
"Properties",
":",
"{",
"Bucket",
":",
"{",
"Ref",
":",
"'LogBucket'",
",",
"}",
",",
"PolicyDocument",
":",
"{",
"Version",
":",
"'2012-10-17'",
",",
"Statement",
":",
"[",
"{",
"Sid",
":",
"'AWSLogDeliveryAclCheck'",
",",
"Effect",
":",
"'Allow'",
",",
"Principal",
":",
"{",
"Service",
":",
"'delivery.logs.amazonaws.com'",
",",
"}",
",",
"Action",
":",
"'s3:GetBucketAcl'",
",",
"Resource",
":",
"{",
"'Fn::GetAtt'",
":",
"[",
"'LogBucket'",
",",
"'Arn'",
"]",
",",
"}",
",",
"}",
",",
"{",
"Sid",
":",
"'AWSLogDeliveryWrite'",
",",
"Effect",
":",
"'Allow'",
",",
"Principal",
":",
"{",
"Service",
":",
"'delivery.logs.amazonaws.com'",
",",
"}",
",",
"Action",
":",
"'s3:PutObject'",
",",
"Resource",
":",
"{",
"'Fn::Join'",
":",
"[",
"''",
",",
"[",
"'arn:aws:s3:::'",
",",
"{",
"Ref",
":",
"'LogBucket'",
"}",
",",
"'/AWSLogs/'",
",",
"{",
"Ref",
":",
"'AWS::AccountId'",
"}",
",",
"'/*'",
",",
"]",
",",
"]",
",",
"}",
",",
"Condition",
":",
"{",
"StringEquals",
":",
"{",
"'s3:x-amz-acl'",
":",
"'bucket-owner-full-control'",
",",
"}",
",",
"}",
",",
"}",
",",
"]",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build an S3 Bucket Policy for the logging bucket
@return {Object}
@see https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs-s3.html#flow-logs-s3-permissions | [
"Build",
"an",
"S3",
"Bucket",
"Policy",
"for",
"the",
"logging",
"bucket"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/flow_logs.js#L47-L99 |
22,892 | smoketurner/serverless-vpc-plugin | src/flow_logs.js | buildVpcFlowLogs | function buildVpcFlowLogs({ name = 'S3FlowLog' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::FlowLog',
DependsOn: 'LogBucketPolicy',
Properties: {
LogDestinationType: 's3',
LogDestination: {
'Fn::GetAtt': ['LogBucket', 'Arn'],
},
ResourceId: {
Ref: 'VPC',
},
ResourceType: 'VPC',
TrafficType: 'ALL',
},
},
};
} | javascript | function buildVpcFlowLogs({ name = 'S3FlowLog' } = {}) {
return {
[name]: {
Type: 'AWS::EC2::FlowLog',
DependsOn: 'LogBucketPolicy',
Properties: {
LogDestinationType: 's3',
LogDestination: {
'Fn::GetAtt': ['LogBucket', 'Arn'],
},
ResourceId: {
Ref: 'VPC',
},
ResourceType: 'VPC',
TrafficType: 'ALL',
},
},
};
} | [
"function",
"buildVpcFlowLogs",
"(",
"{",
"name",
"=",
"'S3FlowLog'",
"}",
"=",
"{",
"}",
")",
"{",
"return",
"{",
"[",
"name",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::FlowLog'",
",",
"DependsOn",
":",
"'LogBucketPolicy'",
",",
"Properties",
":",
"{",
"LogDestinationType",
":",
"'s3'",
",",
"LogDestination",
":",
"{",
"'Fn::GetAtt'",
":",
"[",
"'LogBucket'",
",",
"'Arn'",
"]",
",",
"}",
",",
"ResourceId",
":",
"{",
"Ref",
":",
"'VPC'",
",",
"}",
",",
"ResourceType",
":",
"'VPC'",
",",
"TrafficType",
":",
"'ALL'",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a VPC FlowLog definition that logs to an S3 bucket
@param {Object} params
@return {Object} | [
"Build",
"a",
"VPC",
"FlowLog",
"definition",
"that",
"logs",
"to",
"an",
"S3",
"bucket"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/flow_logs.js#L107-L125 |
22,893 | smoketurner/serverless-vpc-plugin | src/nacl.js | buildNetworkAclEntry | function buildNetworkAclEntry(
name,
CidrBlock,
{ Egress = false, Protocol = -1, RuleAction = 'allow', RuleNumber = 100 } = {},
) {
const direction = Egress ? 'Egress' : 'Ingress';
const cfName = `${name}${direction}${RuleNumber}`;
return {
[cfName]: {
Type: 'AWS::EC2::NetworkAclEntry',
Properties: {
CidrBlock,
NetworkAclId: {
Ref: name,
},
Egress,
Protocol,
RuleAction,
RuleNumber,
},
},
};
} | javascript | function buildNetworkAclEntry(
name,
CidrBlock,
{ Egress = false, Protocol = -1, RuleAction = 'allow', RuleNumber = 100 } = {},
) {
const direction = Egress ? 'Egress' : 'Ingress';
const cfName = `${name}${direction}${RuleNumber}`;
return {
[cfName]: {
Type: 'AWS::EC2::NetworkAclEntry',
Properties: {
CidrBlock,
NetworkAclId: {
Ref: name,
},
Egress,
Protocol,
RuleAction,
RuleNumber,
},
},
};
} | [
"function",
"buildNetworkAclEntry",
"(",
"name",
",",
"CidrBlock",
",",
"{",
"Egress",
"=",
"false",
",",
"Protocol",
"=",
"-",
"1",
",",
"RuleAction",
"=",
"'allow'",
",",
"RuleNumber",
"=",
"100",
"}",
"=",
"{",
"}",
",",
")",
"{",
"const",
"direction",
"=",
"Egress",
"?",
"'Egress'",
":",
"'Ingress'",
";",
"const",
"cfName",
"=",
"`",
"${",
"name",
"}",
"${",
"direction",
"}",
"${",
"RuleNumber",
"}",
"`",
";",
"return",
"{",
"[",
"cfName",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::NetworkAclEntry'",
",",
"Properties",
":",
"{",
"CidrBlock",
",",
"NetworkAclId",
":",
"{",
"Ref",
":",
"name",
",",
"}",
",",
"Egress",
",",
"Protocol",
",",
"RuleAction",
",",
"RuleNumber",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a Network ACL entry
@param {String} name
@param {String} CidrBlock
@param {Object} params
@return {Object} | [
"Build",
"a",
"Network",
"ACL",
"entry"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/nacl.js#L48-L70 |
22,894 | smoketurner/serverless-vpc-plugin | src/nacl.js | buildNetworkAclAssociation | function buildNetworkAclAssociation(name, position) {
const cfName = `${name}SubnetNetworkAclAssociation${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::SubnetNetworkAclAssociation',
Properties: {
SubnetId: {
Ref: `${name}Subnet${position}`,
},
NetworkAclId: {
Ref: `${name}NetworkAcl`,
},
},
},
};
} | javascript | function buildNetworkAclAssociation(name, position) {
const cfName = `${name}SubnetNetworkAclAssociation${position}`;
return {
[cfName]: {
Type: 'AWS::EC2::SubnetNetworkAclAssociation',
Properties: {
SubnetId: {
Ref: `${name}Subnet${position}`,
},
NetworkAclId: {
Ref: `${name}NetworkAcl`,
},
},
},
};
} | [
"function",
"buildNetworkAclAssociation",
"(",
"name",
",",
"position",
")",
"{",
"const",
"cfName",
"=",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
";",
"return",
"{",
"[",
"cfName",
"]",
":",
"{",
"Type",
":",
"'AWS::EC2::SubnetNetworkAclAssociation'",
",",
"Properties",
":",
"{",
"SubnetId",
":",
"{",
"Ref",
":",
"`",
"${",
"name",
"}",
"${",
"position",
"}",
"`",
",",
"}",
",",
"NetworkAclId",
":",
"{",
"Ref",
":",
"`",
"${",
"name",
"}",
"`",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
";",
"}"
] | Build a Subnet Network ACL Association
@param {String} name
@param {Number} position | [
"Build",
"a",
"Subnet",
"Network",
"ACL",
"Association"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/nacl.js#L78-L93 |
22,895 | smoketurner/serverless-vpc-plugin | src/nacl.js | buildPublicNetworkAcl | function buildPublicNetworkAcl(numZones = 0) {
if (numZones < 1) {
return {};
}
const resources = {};
Object.assign(
resources,
buildNetworkAcl(PUBLIC_SUBNET),
buildNetworkAclEntry(`${PUBLIC_SUBNET}NetworkAcl`, '0.0.0.0/0'),
buildNetworkAclEntry(`${PUBLIC_SUBNET}NetworkAcl`, '0.0.0.0/0', {
Egress: true,
}),
);
for (let i = 1; i <= numZones; i += 1) {
Object.assign(resources, buildNetworkAclAssociation(PUBLIC_SUBNET, i));
}
return resources;
} | javascript | function buildPublicNetworkAcl(numZones = 0) {
if (numZones < 1) {
return {};
}
const resources = {};
Object.assign(
resources,
buildNetworkAcl(PUBLIC_SUBNET),
buildNetworkAclEntry(`${PUBLIC_SUBNET}NetworkAcl`, '0.0.0.0/0'),
buildNetworkAclEntry(`${PUBLIC_SUBNET}NetworkAcl`, '0.0.0.0/0', {
Egress: true,
}),
);
for (let i = 1; i <= numZones; i += 1) {
Object.assign(resources, buildNetworkAclAssociation(PUBLIC_SUBNET, i));
}
return resources;
} | [
"function",
"buildPublicNetworkAcl",
"(",
"numZones",
"=",
"0",
")",
"{",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"resources",
"=",
"{",
"}",
";",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildNetworkAcl",
"(",
"PUBLIC_SUBNET",
")",
",",
"buildNetworkAclEntry",
"(",
"`",
"${",
"PUBLIC_SUBNET",
"}",
"`",
",",
"'0.0.0.0/0'",
")",
",",
"buildNetworkAclEntry",
"(",
"`",
"${",
"PUBLIC_SUBNET",
"}",
"`",
",",
"'0.0.0.0/0'",
",",
"{",
"Egress",
":",
"true",
",",
"}",
")",
",",
")",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"numZones",
";",
"i",
"+=",
"1",
")",
"{",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildNetworkAclAssociation",
"(",
"PUBLIC_SUBNET",
",",
"i",
")",
")",
";",
"}",
"return",
"resources",
";",
"}"
] | Build the Public Network ACL
@param {Number} numZones Number of availability zones | [
"Build",
"the",
"Public",
"Network",
"ACL"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/nacl.js#L100-L121 |
22,896 | smoketurner/serverless-vpc-plugin | src/nacl.js | buildAppNetworkAcl | function buildAppNetworkAcl(numZones = 0) {
if (numZones < 1) {
return {};
}
const resources = {};
Object.assign(
resources,
buildNetworkAcl(APP_SUBNET),
buildNetworkAclEntry(`${APP_SUBNET}NetworkAcl`, '0.0.0.0/0'),
buildNetworkAclEntry(`${APP_SUBNET}NetworkAcl`, '0.0.0.0/0', {
Egress: true,
}),
);
for (let i = 1; i <= numZones; i += 1) {
Object.assign(resources, buildNetworkAclAssociation(APP_SUBNET, i));
}
return resources;
} | javascript | function buildAppNetworkAcl(numZones = 0) {
if (numZones < 1) {
return {};
}
const resources = {};
Object.assign(
resources,
buildNetworkAcl(APP_SUBNET),
buildNetworkAclEntry(`${APP_SUBNET}NetworkAcl`, '0.0.0.0/0'),
buildNetworkAclEntry(`${APP_SUBNET}NetworkAcl`, '0.0.0.0/0', {
Egress: true,
}),
);
for (let i = 1; i <= numZones; i += 1) {
Object.assign(resources, buildNetworkAclAssociation(APP_SUBNET, i));
}
return resources;
} | [
"function",
"buildAppNetworkAcl",
"(",
"numZones",
"=",
"0",
")",
"{",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"resources",
"=",
"{",
"}",
";",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildNetworkAcl",
"(",
"APP_SUBNET",
")",
",",
"buildNetworkAclEntry",
"(",
"`",
"${",
"APP_SUBNET",
"}",
"`",
",",
"'0.0.0.0/0'",
")",
",",
"buildNetworkAclEntry",
"(",
"`",
"${",
"APP_SUBNET",
"}",
"`",
",",
"'0.0.0.0/0'",
",",
"{",
"Egress",
":",
"true",
",",
"}",
")",
",",
")",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"numZones",
";",
"i",
"+=",
"1",
")",
"{",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildNetworkAclAssociation",
"(",
"APP_SUBNET",
",",
"i",
")",
")",
";",
"}",
"return",
"resources",
";",
"}"
] | Build the Application Network ACL
@param {Number} numZones Number of availability zones | [
"Build",
"the",
"Application",
"Network",
"ACL"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/nacl.js#L128-L149 |
22,897 | smoketurner/serverless-vpc-plugin | src/nacl.js | buildDBNetworkAcl | function buildDBNetworkAcl(appSubnets = []) {
if (!Array.isArray(appSubnets) || appSubnets.length < 1) {
return {};
}
const resources = buildNetworkAcl(DB_SUBNET);
appSubnets.forEach((subnet, index) => {
Object.assign(
resources,
buildNetworkAclEntry(`${DB_SUBNET}NetworkAcl`, subnet, {
RuleNumber: 100 + index,
}),
buildNetworkAclEntry(`${DB_SUBNET}NetworkAcl`, subnet, {
RuleNumber: 100 + index,
Egress: true,
}),
buildNetworkAclAssociation(DB_SUBNET, index + 1),
);
});
return resources;
} | javascript | function buildDBNetworkAcl(appSubnets = []) {
if (!Array.isArray(appSubnets) || appSubnets.length < 1) {
return {};
}
const resources = buildNetworkAcl(DB_SUBNET);
appSubnets.forEach((subnet, index) => {
Object.assign(
resources,
buildNetworkAclEntry(`${DB_SUBNET}NetworkAcl`, subnet, {
RuleNumber: 100 + index,
}),
buildNetworkAclEntry(`${DB_SUBNET}NetworkAcl`, subnet, {
RuleNumber: 100 + index,
Egress: true,
}),
buildNetworkAclAssociation(DB_SUBNET, index + 1),
);
});
return resources;
} | [
"function",
"buildDBNetworkAcl",
"(",
"appSubnets",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"appSubnets",
")",
"||",
"appSubnets",
".",
"length",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"resources",
"=",
"buildNetworkAcl",
"(",
"DB_SUBNET",
")",
";",
"appSubnets",
".",
"forEach",
"(",
"(",
"subnet",
",",
"index",
")",
"=>",
"{",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildNetworkAclEntry",
"(",
"`",
"${",
"DB_SUBNET",
"}",
"`",
",",
"subnet",
",",
"{",
"RuleNumber",
":",
"100",
"+",
"index",
",",
"}",
")",
",",
"buildNetworkAclEntry",
"(",
"`",
"${",
"DB_SUBNET",
"}",
"`",
",",
"subnet",
",",
"{",
"RuleNumber",
":",
"100",
"+",
"index",
",",
"Egress",
":",
"true",
",",
"}",
")",
",",
"buildNetworkAclAssociation",
"(",
"DB_SUBNET",
",",
"index",
"+",
"1",
")",
",",
")",
";",
"}",
")",
";",
"return",
"resources",
";",
"}"
] | Build the Database Network ACL
@param {Array} appSubnets Array of application subnets | [
"Build",
"the",
"Database",
"Network",
"ACL"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/nacl.js#L156-L178 |
22,898 | smoketurner/serverless-vpc-plugin | src/vpce.js | buildVPCEndpoint | function buildVPCEndpoint(service, { routeTableIds = [], subnetIds = [] } = {}) {
const endpoint = {
Type: 'AWS::EC2::VPCEndpoint',
Properties: {
ServiceName: {
'Fn::Join': [
'.',
[
'com.amazonaws',
{
Ref: 'AWS::Region',
},
service,
],
],
},
VpcId: {
Ref: 'VPC',
},
},
};
// @see https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html
if (service === 's3' || service === 'dynamodb') {
endpoint.Properties.VpcEndpointType = 'Gateway';
endpoint.Properties.RouteTableIds = routeTableIds;
endpoint.Properties.PolicyDocument = {
Statement: [
{
Effect: 'Allow',
/*
TODO 11/21: We should restrict the VPC Endpoint to only the Lambda
IAM role, but this doesn't work.
Principal: {
AWS: {
'Fn::GetAtt': [
'IamRoleLambdaExecution',
'Arn',
],
},
}, */
Principal: '*',
Resource: '*',
},
],
};
if (service === 's3') {
endpoint.Properties.PolicyDocument.Statement[0].Action = 's3:*';
} else if (service === 'dynamodb') {
endpoint.Properties.PolicyDocument.Statement[0].Action = 'dynamodb:*';
}
} else {
endpoint.Properties.VpcEndpointType = 'Interface';
endpoint.Properties.SubnetIds = subnetIds;
endpoint.Properties.PrivateDnsEnabled = true;
endpoint.Properties.SecurityGroupIds = [
{
Ref: 'LambdaEndpointSecurityGroup',
},
];
}
const parts = service.split(/[-_.]/g);
parts.push('VPCEndpoint');
const cfName = parts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('');
return {
[cfName]: endpoint,
};
} | javascript | function buildVPCEndpoint(service, { routeTableIds = [], subnetIds = [] } = {}) {
const endpoint = {
Type: 'AWS::EC2::VPCEndpoint',
Properties: {
ServiceName: {
'Fn::Join': [
'.',
[
'com.amazonaws',
{
Ref: 'AWS::Region',
},
service,
],
],
},
VpcId: {
Ref: 'VPC',
},
},
};
// @see https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html
if (service === 's3' || service === 'dynamodb') {
endpoint.Properties.VpcEndpointType = 'Gateway';
endpoint.Properties.RouteTableIds = routeTableIds;
endpoint.Properties.PolicyDocument = {
Statement: [
{
Effect: 'Allow',
/*
TODO 11/21: We should restrict the VPC Endpoint to only the Lambda
IAM role, but this doesn't work.
Principal: {
AWS: {
'Fn::GetAtt': [
'IamRoleLambdaExecution',
'Arn',
],
},
}, */
Principal: '*',
Resource: '*',
},
],
};
if (service === 's3') {
endpoint.Properties.PolicyDocument.Statement[0].Action = 's3:*';
} else if (service === 'dynamodb') {
endpoint.Properties.PolicyDocument.Statement[0].Action = 'dynamodb:*';
}
} else {
endpoint.Properties.VpcEndpointType = 'Interface';
endpoint.Properties.SubnetIds = subnetIds;
endpoint.Properties.PrivateDnsEnabled = true;
endpoint.Properties.SecurityGroupIds = [
{
Ref: 'LambdaEndpointSecurityGroup',
},
];
}
const parts = service.split(/[-_.]/g);
parts.push('VPCEndpoint');
const cfName = parts.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join('');
return {
[cfName]: endpoint,
};
} | [
"function",
"buildVPCEndpoint",
"(",
"service",
",",
"{",
"routeTableIds",
"=",
"[",
"]",
",",
"subnetIds",
"=",
"[",
"]",
"}",
"=",
"{",
"}",
")",
"{",
"const",
"endpoint",
"=",
"{",
"Type",
":",
"'AWS::EC2::VPCEndpoint'",
",",
"Properties",
":",
"{",
"ServiceName",
":",
"{",
"'Fn::Join'",
":",
"[",
"'.'",
",",
"[",
"'com.amazonaws'",
",",
"{",
"Ref",
":",
"'AWS::Region'",
",",
"}",
",",
"service",
",",
"]",
",",
"]",
",",
"}",
",",
"VpcId",
":",
"{",
"Ref",
":",
"'VPC'",
",",
"}",
",",
"}",
",",
"}",
";",
"// @see https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html",
"if",
"(",
"service",
"===",
"'s3'",
"||",
"service",
"===",
"'dynamodb'",
")",
"{",
"endpoint",
".",
"Properties",
".",
"VpcEndpointType",
"=",
"'Gateway'",
";",
"endpoint",
".",
"Properties",
".",
"RouteTableIds",
"=",
"routeTableIds",
";",
"endpoint",
".",
"Properties",
".",
"PolicyDocument",
"=",
"{",
"Statement",
":",
"[",
"{",
"Effect",
":",
"'Allow'",
",",
"/*\n TODO 11/21: We should restrict the VPC Endpoint to only the Lambda\n IAM role, but this doesn't work.\n\n Principal: {\n AWS: {\n 'Fn::GetAtt': [\n 'IamRoleLambdaExecution',\n 'Arn',\n ],\n },\n }, */",
"Principal",
":",
"'*'",
",",
"Resource",
":",
"'*'",
",",
"}",
",",
"]",
",",
"}",
";",
"if",
"(",
"service",
"===",
"'s3'",
")",
"{",
"endpoint",
".",
"Properties",
".",
"PolicyDocument",
".",
"Statement",
"[",
"0",
"]",
".",
"Action",
"=",
"'s3:*'",
";",
"}",
"else",
"if",
"(",
"service",
"===",
"'dynamodb'",
")",
"{",
"endpoint",
".",
"Properties",
".",
"PolicyDocument",
".",
"Statement",
"[",
"0",
"]",
".",
"Action",
"=",
"'dynamodb:*'",
";",
"}",
"}",
"else",
"{",
"endpoint",
".",
"Properties",
".",
"VpcEndpointType",
"=",
"'Interface'",
";",
"endpoint",
".",
"Properties",
".",
"SubnetIds",
"=",
"subnetIds",
";",
"endpoint",
".",
"Properties",
".",
"PrivateDnsEnabled",
"=",
"true",
";",
"endpoint",
".",
"Properties",
".",
"SecurityGroupIds",
"=",
"[",
"{",
"Ref",
":",
"'LambdaEndpointSecurityGroup'",
",",
"}",
",",
"]",
";",
"}",
"const",
"parts",
"=",
"service",
".",
"split",
"(",
"/",
"[-_.]",
"/",
"g",
")",
";",
"parts",
".",
"push",
"(",
"'VPCEndpoint'",
")",
";",
"const",
"cfName",
"=",
"parts",
".",
"map",
"(",
"part",
"=>",
"part",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"part",
".",
"slice",
"(",
"1",
")",
")",
".",
"join",
"(",
"''",
")",
";",
"return",
"{",
"[",
"cfName",
"]",
":",
"endpoint",
",",
"}",
";",
"}"
] | Build a VPCEndpoint
@param {String} service
@param {Object} params
@return {Object} | [
"Build",
"a",
"VPCEndpoint"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/vpce.js#L10-L80 |
22,899 | smoketurner/serverless-vpc-plugin | src/vpce.js | buildEndpointServices | function buildEndpointServices(services = [], numZones = 0) {
if (!Array.isArray(services) || services.length < 1) {
return {};
}
if (numZones < 1) {
return {};
}
const subnetIds = [];
const routeTableIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${APP_SUBNET}Subnet${i}` });
routeTableIds.push({ Ref: `${APP_SUBNET}RouteTable${i}` });
}
const resources = {};
services.forEach(service => {
Object.assign(resources, buildVPCEndpoint(service, { routeTableIds, subnetIds }));
});
return resources;
} | javascript | function buildEndpointServices(services = [], numZones = 0) {
if (!Array.isArray(services) || services.length < 1) {
return {};
}
if (numZones < 1) {
return {};
}
const subnetIds = [];
const routeTableIds = [];
for (let i = 1; i <= numZones; i += 1) {
subnetIds.push({ Ref: `${APP_SUBNET}Subnet${i}` });
routeTableIds.push({ Ref: `${APP_SUBNET}RouteTable${i}` });
}
const resources = {};
services.forEach(service => {
Object.assign(resources, buildVPCEndpoint(service, { routeTableIds, subnetIds }));
});
return resources;
} | [
"function",
"buildEndpointServices",
"(",
"services",
"=",
"[",
"]",
",",
"numZones",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"services",
")",
"||",
"services",
".",
"length",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"if",
"(",
"numZones",
"<",
"1",
")",
"{",
"return",
"{",
"}",
";",
"}",
"const",
"subnetIds",
"=",
"[",
"]",
";",
"const",
"routeTableIds",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"i",
"=",
"1",
";",
"i",
"<=",
"numZones",
";",
"i",
"+=",
"1",
")",
"{",
"subnetIds",
".",
"push",
"(",
"{",
"Ref",
":",
"`",
"${",
"APP_SUBNET",
"}",
"${",
"i",
"}",
"`",
"}",
")",
";",
"routeTableIds",
".",
"push",
"(",
"{",
"Ref",
":",
"`",
"${",
"APP_SUBNET",
"}",
"${",
"i",
"}",
"`",
"}",
")",
";",
"}",
"const",
"resources",
"=",
"{",
"}",
";",
"services",
".",
"forEach",
"(",
"service",
"=>",
"{",
"Object",
".",
"assign",
"(",
"resources",
",",
"buildVPCEndpoint",
"(",
"service",
",",
"{",
"routeTableIds",
",",
"subnetIds",
"}",
")",
")",
";",
"}",
")",
";",
"return",
"resources",
";",
"}"
] | Build VPC endpoints for a given number of services and zones
@param {Array} services Array of VPC endpoint services
@param {Number} numZones Number of availability zones
@return {Object} | [
"Build",
"VPC",
"endpoints",
"for",
"a",
"given",
"number",
"of",
"services",
"and",
"zones"
] | 21a862ac01cc14fc5699fc9d7978bd736622cc1d | https://github.com/smoketurner/serverless-vpc-plugin/blob/21a862ac01cc14fc5699fc9d7978bd736622cc1d/src/vpce.js#L89-L110 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.