_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.index]) { return; }
// to pass check in updateControllerListOriginal
gamepad.pose = true;
gamepads[gamepad.index] = gamepad;
});
this.updateControllerListOriginal(gamepads);
}
|
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);
if(timer) clearTimeout(timer);
timer = context = args = null;
}
else timer = setTimeout(delayed, limit - timeSince);
};
// Debounced copy of the original function
return function(){
context = this,
args = arguments;
if(!limit)
return fn.apply(context, args);
started = Date.now();
if(!timer){
if(soon) fn.apply(context, args);
timer = setTimeout(delayed, limit);
}
};
}
|
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 = height - _height;
parentFold
? (parentFold.open && THIS.parent.updateFold(parentFold, diff))
: edgeCheck(diff);
THIS.height = height;
}
|
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 && setTimeout(function(e){elClasses.remove(snap)}, 20);
}
|
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 equivalent config file settings to be ignored.
if ((file && file.length > 0) || dir || pathFile) {
config.filesToProcess = null;
config.searchDirectory = null;
config.pathFile = null;
}
if (file && file.length > 0) {
config.filesToProcess = file;
}
if (dir) {
config.searchDirectory = dir;
}
if (pathFile) {
config.pathFile = pathFile;
}
if (useJsModules) {
config.useJSModules = true;
}
if (landBase) {
config.landBase = landBase;
}
if (numWorkers) {
config.numWorkers = numWorkers;
}
if (skipVerify) {
config.skipVerify = true;
}
if (decaffeinatePath) {
config.decaffeinatePath = decaffeinatePath;
}
if (jscodeshiftPath) {
config.jscodeshiftPath = jscodeshiftPath;
}
if (eslintPath) {
config.eslintPath = eslintPath;
}
return config;
}
|
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 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
|
{
"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++) {
const img = images[i];
let bonusFeature = 1;
if (minHeight !== maxHeight) {
bonusFeature = (img.height - minHeight) / (maxHeight - minHeight);
}
result[i].push(bonusFeature);
}
return result;
}
|
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.length-1)];
//word += (i===0) ? randConsonant.toUpperCase() : randConsonant;
word += (i===0) ? randConsonant : randConsonant;
word += i*2<length-1 ? randVowel : '';
}
return word;
}
|
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[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
|
{
"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 : 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
|
{
"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 = g < 0 ? 0 : (g > 255 ? 255 : g);
b = b < 0 ? 0 : (b > 255 ? 255 : b);
return {red: r, green: g, blue: b};
}
|
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._image.bitblt(image, x, y, width, height, 0, 0);
this._image = image;
}
|
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(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
|
{
"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);
}.bind(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.getContents());
}.bind(this)).once('error', function (err) {
this._image.removeListener('close', fn);
fn(err);
}.bind(this));
}
|
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.createImage(image.getWidth(), image.getHeight());
fn(image, newImage, options);
return newImage;
} else {
fn(image, image, options);
return image;
}
};
}
|
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;
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
|
{
"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.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
|
{
"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 || this.locale,
"reason": reason
//TODO: support error
}
};
}
|
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) {
request.context.AudioPlayer.playerActivity = activity;
}
return request;
}
|
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';
}
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
|
{
"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';
}
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
|
{
"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 => `"${text}"`).join(', ') + "]",
actual: actual,
operator: "==", showDiff: true
});
}
|
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-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
|
{
"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 += ' 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
|
{
"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.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
|
{
"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];
if (node.nodeType === 1) {
subNodes.push(node);
}
}
if (subNodes.length) {
content = subNodes;
}
}
return content || propNode.textContent || propNode.text || '';
}
|
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;
}
}
}.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
|
{
"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
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
|
{
"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],
query : parts[6],
fragment : parts[7],
};
result.root =
result.scheme + '://' +
result.host +
(result.port ? ':' + result.port : '');
return result;
}
|
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);
// 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
|
{
"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 () {
// …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
|
{
"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(function (token) {
// Authorize client…
client.setToken(token);
// …and send it back to connect()
return client;
});
});
}
|
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 (jQuery(li).hasClass('is-selected'))
current_index = index;
});
return current_index;
}
|
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].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
|
{
"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.length)
return spliced;
else
return false;
}
else
return console.error(new Error('Bad data passed to clean.forFields()'));
}
|
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[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
|
{
"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;
},
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
|
{
"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.onRender = function (callback) {
if (typeof callback === 'function') {
renderCallbacks.push(callback);
}
};
this.start = function () {
startInternal();
};
this.stop = function () {
if (intervalId) {
cancelAnimationFrame(intervalId);
intervalId = null;
}
};
}
|
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 -= 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
|
{
"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 = 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
|
{
"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.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
|
{
"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 = false;
}
handle.move(-direction.v * 10);
});
flow.startCapture();
},
dismount: function () {
flow.stopCapture();
},
onReady: function (callback) {
readyCallback = callback;
},
step: function () {
}
};
}
|
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;
restoreParent(root.right);
}
}
restoreParent(self.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
// 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
|
{
"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({
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
|
{
"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, 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
|
{
"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]
const text = sourceCode.getText(e)
ss.push(text)
}
})
if (!ss.length || !isStringLiteralCode(ss[0])) {
ss.unshift(`""`)
}
return ss.join("+")
}
|
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 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
|
{
"resource": ""
}
|
q52376
|
report
|
train
|
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
|
{
"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
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
|
{
"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: 'Name',
Value: {
Ref: 'AWS::StackName',
},
},
],
},
},
};
}
|
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: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
name.toLowerCase(),
zone,
],
],
},
},
],
VpcId: {
Ref: 'VPC',
},
},
},
};
}
|
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: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
name.toLowerCase(),
zone,
],
],
},
},
],
},
},
};
}
|
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: {
Ref: `${name}Subnet${position}`,
},
},
},
};
}
|
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 (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
|
{
"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',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
'lambda-exec',
],
],
},
},
],
},
},
};
}
|
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;
});
res.on('end', () => {
resolve(body);
});
})
.on('error', err => {
reject(err);
});
});
}
|
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',
},
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
|
{
"resource": ""
}
|
q52386
|
buildBastionLaunchConfiguration
|
train
|
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
|
{
"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::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
|
{
"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: [
{
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
|
{
"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(
{},
buildBastionEIP(),
buildBastionIamRole(),
buildBastionInstanceProfile(),
buildBastionSecurityGroup(publicIp),
buildBastionLaunchConfiguration(keyPairName),
buildBastionAutoScalingGroup(numZones),
);
}
|
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',
Properties: {
DBSubnetGroupName: {
Ref: 'AWS::StackName',
},
DBSubnetGroupDescription: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
}
|
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::SubnetGroup',
Properties: {
CacheSubnetGroupName: {
Ref: 'AWS::StackName',
},
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
}
|
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::ClusterSubnetGroup',
Properties: {
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
}
|
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',
Properties: {
SubnetGroupName: {
Ref: 'AWS::StackName',
},
Description: {
Ref: 'AWS::StackName',
},
SubnetIds: subnetIds,
},
},
};
}
|
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 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
|
{
"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: {
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
|
{
"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 (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
|
{
"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}Subnet${position}`,
},
Tags: [
{
Key: 'Name',
Value: {
'Fn::Join': [
'-',
[
{
Ref: 'AWS::StackName',
},
zone,
],
],
},
},
],
},
},
};
}
|
javascript
|
{
"resource": ""
}
|
q52399
|
buildLogBucket
|
train
|
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
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.