_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q52300
train
function (recordingData) { var data = this.data; if (!data.localStorage) { return; } log('Recording stored in localStorage.'); this.el.systems.recordingdb.addRecording(data.recordingName, recordingData); }
javascript
{ "resource": "" }
q52301
train
function (gamepads) { var i; var sceneEl = this.sceneEl; var trackedControlsSystem = sceneEl.systems['tracked-controls']; gamepads = gamepads || [] // convert from read-only GamepadList gamepads = Array.from(gamepads) this.gamepads.forEach(function (gamepad) { if (gamepads[gamepad.ind...
javascript
{ "resource": "" }
q52302
setToken
train
function setToken(list, token, enabled){ enabled ? list.add(token) : list.remove(token); }
javascript
{ "resource": "" }
q52303
debounce
train
function debounce(fn, limit, soon){ var limit = limit < 0 ? 0 : limit, started, context, args, timer, delayed = function(){ // Get the time between now and when the function was first fired var timeSince = Date.now() - started; if(timeSince >= limit){ if(!soon) fn.apply(context, args); ...
javascript
{ "resource": "" }
q52304
fit
train
function fit(){ var height = THIS.headingHeight; if(THIS.open) height += content.scrollHeight; if(useBorders) height += THIS.elBorder; THIS.height = height; }
javascript
{ "resource": "" }
q52305
updateFold
train
function updateFold(fold, offset){ var next = fold; var parentFold = THIS.parentFold; while(next = next.nextFold) next.y += offset; parentFold || edgeCheck(offset); fold.height += offset; THIS.height += offset; parentFold && parentFold.open && THIS.parent.updateFold(parentFold, offset)...
javascript
{ "resource": "" }
q52306
update
train
function update(){ var y = 0; var height = 0; var i = 0; var l = folds.length; var parentFold = THIS.parentFold; var fold, diff; for(; i < l; ++i){ fold = folds[i]; fold.y = y; fold.fit(); y += fold.height; height += fold.height; } diff = heig...
javascript
{ "resource": "" }
q52307
refresh
train
function refresh(allowSnap){ var snap = allowSnap ? snapClass : false; snap && elClasses.add(snap); THIS.update(); THIS.childAccordions && THIS.childAccordions.forEach(function(a){ a.parentFold.open ? a.refresh(allowSnap) : (a.parentFold.needsRefresh = true); }); snap && setTimeo...
javascript
{ "resource": "" }
q52308
getCLIParamsConfig
train
function getCLIParamsConfig(config, commander) { let { file, pathFile, dir, useJsModules, landBase, numWorkers, skipVerify, decaffeinatePath, jscodeshiftPath, eslintPath, } = commander; // As a special case, specifying files to process from the CLI should cause // any equ...
javascript
{ "resource": "" }
q52309
resolveBinary
train
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 ...
javascript
{ "resource": "" }
q52310
getDescriptors
train
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++)...
javascript
{ "resource": "" }
q52311
randomEnglishWord
train
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....
javascript
{ "resource": "" }
q52312
train
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[...
javascript
{ "resource": "" }
q52313
train
function (x, y, funcName) { var idx = this.getIndex(x, y); return this.getBlurPixelAtIndex(idx, funcName); }
javascript
{ "resource": "" }
q52314
train
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 ...
javascript
{ "resource": "" }
q52315
train
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 ...
javascript
{ "resource": "" }
q52316
train
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
{ "resource": "" }
q52317
train
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
{ "resource": "" }
q52318
PNGImage
train
function PNGImage (image) { image.on('error', function (err) { PNGImage.log(err.message); }); this._image = image; }
javascript
{ "resource": "" }
q52319
train
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._ima...
javascript
{ "resource": "" }
q52320
train
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
{ "resource": "" }
q52321
train
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(fun...
javascript
{ "resource": "" }
q52322
train
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); ...
javascript
{ "resource": "" }
q52323
train
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.getCon...
javascript
{ "resource": "" }
q52324
generateFilter
train
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.creat...
javascript
{ "resource": "" }
q52325
train
function (index, appId, userId, deviceId) { 'use strict'; this.index = index; this.appId = appId; this.userId = userId; this.deviceId = deviceId || 'amzn1.ask.device.VOID'; }
javascript
{ "resource": "" }
q52326
train
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
{ "resource": "" }
q52327
train
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; AWSMO...
javascript
{ "resource": "" }
q52328
train
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.vers...
javascript
{ "resource": "" }
q52329
train
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 ...
javascript
{ "resource": "" }
q52330
train
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) { re...
javascript
{ "resource": "" }
q52331
train
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'; }...
javascript
{ "resource": "" }
q52332
train
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
{ "resource": "" }
q52333
train
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'; } ...
javascript
{ "resource": "" }
q52334
train
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
{ "resource": "" }
q52335
train
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 => `"...
javascript
{ "resource": "" }
q52336
train
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-T...
javascript
{ "resource": "" }
q52337
train
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...
javascript
{ "resource": "" }
q52338
train
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.passwor...
javascript
{ "resource": "" }
q52339
train
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]; ...
javascript
{ "resource": "" }
q52340
train
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; ...
javascript
{ "resource": "" }
q52341
train
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 ...
javascript
{ "resource": "" }
q52342
train
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...
javascript
{ "resource": "" }
q52343
checkUpdate
train
function checkUpdate () { var pkg = require("./package.json"); require("update-notifier")({ packageName: pkg.name, packageVersion: pkg.version }).notify(); }
javascript
{ "resource": "" }
q52344
main
train
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); /...
javascript
{ "resource": "" }
q52345
rememberSkip
train
function rememberSkip (title) { return readIgnoreFile().spread(function (ignores, skipFile) { if (!_.contains(ignores, title)) { return fs.writeFile(skipFile, ignores.concat([title]).join("\n")); } }); }
javascript
{ "resource": "" }
q52346
convertIssue
train
function convertIssue (issue) { if (!issue) { return null; } return { "type": "issue", "number": issue.number, "url": issue.url, "title": issue.title, "labels": issue.labels }; }
javascript
{ "resource": "" }
q52347
allIssues
train
function allIssues (client, repo) { return client.getIssues(repo).then(function (issues) { return issues.map(convertIssue); }); }
javascript
{ "resource": "" }
q52348
createIssue
train
function createIssue (client, repo, title, body, labels) { return client.createIssue(repo, title, body, labels).then(convertIssue); }
javascript
{ "resource": "" }
q52349
commentIssue
train
function commentIssue (client, repo, number, comment) { return client.createComment(repo, number, comment).then(convertComment); }
javascript
{ "resource": "" }
q52350
tagIssue
train
function tagIssue (client, repo, number, label) { return client.addLabel(repo, number, label).then(convertIssue); }
javascript
{ "resource": "" }
q52351
connect
train
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 () {...
javascript
{ "resource": "" }
q52352
createToken
train
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(functi...
javascript
{ "resource": "" }
q52353
getFileUrl
train
function getFileUrl (repo, path, sha, line) { return HOST + "/" + repo + "/src/" + sha + "/" + path + "#cl-" + line; }
javascript
{ "resource": "" }
q52354
load
train
function load (commandName) { var command; try { command = require("./cli/" + commandName); } catch (e) { debug("Error loading command", commandName, e); command = null; } return command; }
javascript
{ "resource": "" }
q52355
run
train
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
{ "resource": "" }
q52356
getActiveStepCount
train
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 (jQuer...
javascript
{ "resource": "" }
q52357
train
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].canDow...
javascript
{ "resource": "" }
q52358
train
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....
javascript
{ "resource": "" }
q52359
train
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
{ "resource": "" }
q52360
Game
train
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[...
javascript
{ "resource": "" }
q52361
Scene
train
function Scene(container) { var ctx = container.getContext('2d'), cachedHeight = container.height, cachedWidth = container.width, getWidth = function () { return cachedWidth; }, getHeight = function () { return cachedHeight; }, renderHa...
javascript
{ "resource": "" }
q52362
EventLoop
train
function EventLoop() { var renderCallbacks = [], intervalId, startInternal = function () { intervalId = requestAnimationFrame(startInternal); for (var i = 0, n = renderCallbacks.length; i < n; ++i) { renderCallbacks[i](); } }; this.onR...
javascript
{ "resource": "" }
q52363
whenReady
train
function whenReady() { var pendingObjects = [].slice.call(arguments), wait = pendingObjects.length, resolvedCallback, promise = { run : function (callback) { resolvedCallback = callback; } }, resolved = function () { wait -=...
javascript
{ "resource": "" }
q52364
Handle
train
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 =...
javascript
{ "resource": "" }
q52365
Ball
train
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.v...
javascript
{ "resource": "" }
q52366
WebCamController
train
function WebCamController() { var flow = new oflow.WebCamFlow(), readyCallback, waitReady = true; return { mount: function (handle) { flow.onCalculated(function (direction) { if (waitReady) { readyCallback(); waitReady ...
javascript
{ "resource": "" }
q52367
loadTree
train
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; ...
javascript
{ "resource": "" }
q52368
tryConnect
train
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 ...
javascript
{ "resource": "" }
q52369
loadNterm
train
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
{ "resource": "" }
q52370
findAndReport
train
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({ ...
javascript
{ "resource": "" }
q52371
train
function (callback) { async.parallel( [ // fake db 1 function (callback) { setTimeout(callback, 2000); }, // fake db 2 function (callback) { setTimeout(callback, 1000); } ], callback ); }
javascript
{ "resource": "" }
q52372
train
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...
javascript
{ "resource": "" }
q52373
isStringLiteralCode
train
function isStringLiteralCode(s) { return ( (s.startsWith("'") && s.endsWith("'")) || (s.startsWith('"') && s.endsWith('"')) ) }
javascript
{ "resource": "" }
q52374
templateLiteralToStringConcat
train
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] ...
javascript
{ "resource": "" }
q52375
toFunctionExpression
train
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...
javascript
{ "resource": "" }
q52376
report
train
function report(node, hasThis, hasSuper) { context.report({ node, messageId: "forbidden", fix(fixer) { if (hasSuper) { return undefined } const functionText = toFunctionExpress...
javascript
{ "resource": "" }
q52377
diceCoefficient
train
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...
javascript
{ "resource": "" }
q52378
buildVpc
train
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:...
javascript
{ "resource": "" }
q52379
buildSubnet
train
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: { ...
javascript
{ "resource": "" }
q52380
buildRouteTable
train
function buildRouteTable(name, position, zone) { const cfName = `${name}RouteTable${position}`; return { [cfName]: { Type: 'AWS::EC2::RouteTable', Properties: { VpcId: { Ref: 'VPC', }, Tags: [ { Key: 'Name', Value: { '...
javascript
{ "resource": "" }
q52381
buildRouteTableAssociation
train
function buildRouteTableAssociation(name, position) { const cfName = `${name}RouteTableAssociation${position}`; return { [cfName]: { Type: 'AWS::EC2::SubnetRouteTableAssociation', Properties: { RouteTableId: { Ref: `${name}RouteTable${position}`, }, SubnetId: { ...
javascript
{ "resource": "" }
q52382
buildRoute
train
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 (NatGa...
javascript
{ "resource": "" }
q52383
buildLambdaSecurityGroup
train
function buildLambdaSecurityGroup({ name = 'LambdaExecutionSecurityGroup' } = {}) { return { [name]: { Type: 'AWS::EC2::SecurityGroup', Properties: { GroupDescription: 'Lambda Execution Group', VpcId: { Ref: 'VPC', }, Tags: [ { Key: 'Name...
javascript
{ "resource": "" }
q52384
getPublicIp
train
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; ...
javascript
{ "resource": "" }
q52385
buildBastionIamRole
train
function buildBastionIamRole({ name = 'BastionIamRole' } = {}) { return { [name]: { Type: 'AWS::IAM::Role', Properties: { AssumeRolePolicyDocument: { Statement: [ { Effect: 'Allow', Principal: { Service: 'ec2.amazonaws.com', ...
javascript
{ "resource": "" }
q52386
buildBastionLaunchConfiguration
train
function buildBastionLaunchConfiguration( keyPairName, { name = 'BastionLaunchConfiguration' } = {}, ) { return { [name]: { Type: 'AWS::AutoScaling::LaunchConfiguration', Properties: { AssociatePublicIpAddress: true, BlockDeviceMappings: [ { DeviceName: '/dev/...
javascript
{ "resource": "" }
q52387
buildBastionAutoScalingGroup
train
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::Au...
javascript
{ "resource": "" }
q52388
buildBastionSecurityGroup
train
function buildBastionSecurityGroup(sourceIp = '0.0.0.0/0', { name = 'BastionSecurityGroup' } = {}) { return { [name]: { Type: 'AWS::EC2::SecurityGroup', Properties: { GroupDescription: 'Bastion Host', VpcId: { Ref: 'VPC', }, SecurityGroupIngress: [ {...
javascript
{ "resource": "" }
q52389
buildBastion
train
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( ...
javascript
{ "resource": "" }
q52390
buildRDSSubnetGroup
train
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', Pr...
javascript
{ "resource": "" }
q52391
buildElastiCacheSubnetGroup
train
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::...
javascript
{ "resource": "" }
q52392
buildRedshiftSubnetGroup
train
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::ClusterSu...
javascript
{ "resource": "" }
q52393
buildDAXSubnetGroup
train
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', Prop...
javascript
{ "resource": "" }
q52394
buildSubnetGroups
train
function buildSubnetGroups(numZones = 0) { if (numZones < 2) { return {}; } return Object.assign( {}, buildRDSSubnetGroup(numZones), buildRedshiftSubnetGroup(numZones), buildElastiCacheSubnetGroup(numZones), buildDAXSubnetGroup(numZones), ); }
javascript
{ "resource": "" }
q52395
buildNatSecurityGroup
train
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 f...
javascript
{ "resource": "" }
q52396
buildNatInstance
train
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: { ...
javascript
{ "resource": "" }
q52397
buildAvailabilityZones
train
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 (nu...
javascript
{ "resource": "" }
q52398
buildNatGateway
train
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}Subne...
javascript
{ "resource": "" }
q52399
buildLogBucket
train
function buildLogBucket() { return { LogBucket: { Type: 'AWS::S3::Bucket', DeletionPolicy: 'Retain', Properties: { AccessControl: 'LogDeliveryWrite', BucketEncryption: { ServerSideEncryptionConfiguration: [ { ServerSideEncryptionByDefault: { ...
javascript
{ "resource": "" }